Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 752c9b44d2 | |||
| 822e050010 | |||
| 41a5c43561 | |||
| 9dc976afaf | |||
| f05d2e593e | |||
| 03e4c0d64d | |||
| e0554209f0 | |||
| f84e737b2a | |||
| d406aa6cd2 | |||
| 10221b0624 | |||
| a0c5ca8761 | |||
| 95e5402efc | |||
| 0361b199c4 | |||
| 30bc424343 | |||
| bfd9556a9e | |||
| ea163dd5dd | |||
| 8e0f155464 | |||
| 3ba68e6461 | |||
| deaf5ab924 | |||
| 9783b79731 | |||
| bff0fb44e8 | |||
| 2be1716520 | |||
| 460d368d8e | |||
| 4801d0aac1 | |||
| 00112f6fc2 | |||
| 95d46c7da3 | |||
| 63cdd7a7c5 | |||
| f4951b9bde | |||
| 33e8309322 | |||
| 3df1a53b5a | |||
| ab445439cc | |||
| c08e5ab670 | |||
| d5056d77b6 | |||
| 5382058b28 | |||
| 71cefdd154 | |||
| 71239b6fbb | |||
| 97642c491f | |||
| e64325b64e | |||
| 62929fc766 | |||
| 2ca73aa3ee | |||
| 8617f936a4 | |||
| 9e82b5f6b8 | |||
| 8c09077def | |||
| 714d4456d9 | |||
| c8d273281a | |||
| bc0f798020 | |||
| 1a2917272d | |||
| 68fb35cd72 | |||
| 7f79955912 | |||
| 96dfda1241 |
@@ -1,4 +1,4 @@
|
||||
// Package assets exposes embedded LLM-facing content.
|
||||
// Package assets exposes embedded LLM-facing content and shared input contracts.
|
||||
package assets
|
||||
|
||||
import (
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
//go:embed notarius.yml dnd generic
|
||||
//go:embed notarius.yml dnd generic shared-domain
|
||||
var embedded embed.FS
|
||||
|
||||
// FS returns the embedded read-only asset filesystem.
|
||||
|
||||
11
assets/shared-domain/SOURCE.md
Normal file
11
assets/shared-domain/SOURCE.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Shared domain contract sources
|
||||
|
||||
Source distribution: `2026.11.1`, commit `f7e3cedeca11ed903311cdf29ca4d81fb1f216b7` of [Maximum Direct shared schemas](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7).
|
||||
|
||||
| Contract | Version | Document marker | Canonical schema ID |
|
||||
| --- | --- | --- | --- |
|
||||
| Glossary | `0.2.0` | `maximumdirect.glossary.v1` | https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json |
|
||||
| RPG party | `0.2.0` | `maximumdirect.rpg.party.v1` | https://schemas.maximumdirect.net/rpg/party/v0.2.0/schema.json |
|
||||
|
||||
The schemas are unchanged. Adjacent semantics are copied with links to unbundled
|
||||
upstream documentation and examples redirected to the pinned source revision.
|
||||
51
assets/shared-domain/glossary/v0.2.0/schema.json
Normal file
51
assets/shared-domain/glossary/v0.2.0/schema.json
Normal 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"]}]
|
||||
}
|
||||
}
|
||||
}
|
||||
83
assets/shared-domain/glossary/v0.2.0/semantics.md
Normal file
83
assets/shared-domain/glossary/v0.2.0/semantics.md
Normal 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](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/validation.md) and [compatibility rules](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/compatibility.md)
|
||||
apply. Start with [campaign vocabulary](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/glossary/v0.2.0/examples/glossary.yml),
|
||||
[weather](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/glossary/v0.2.0/examples/weather.yml), or [sports](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/glossary/v0.2.0/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](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/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.
|
||||
51
assets/shared-domain/rpg/party/v0.2.0/schema.json
Normal file
51
assets/shared-domain/rpg/party/v0.2.0/schema.json
Normal file
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://schemas.maximumdirect.net/rpg/party/v0.2.0/schema.json",
|
||||
"title": "MAXIMUMDIRECT RPG Party v1",
|
||||
"type": "object",
|
||||
"required": ["schema_version", "characters"],
|
||||
"properties": {
|
||||
"schema_version": {"const": "maximumdirect.rpg.party.v1"},
|
||||
"characters": {
|
||||
"type": "object",
|
||||
"propertyNames": {"minLength": 1},
|
||||
"additionalProperties": {"$ref": "#/$defs/rosterEntry"}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"text": {"type": "string", "minLength": 1},
|
||||
"rosterEntry": {
|
||||
"type": "object",
|
||||
"required": ["character"],
|
||||
"properties": {
|
||||
"player": {
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {"name": {"$ref": "#/$defs/text"}}
|
||||
},
|
||||
"character": {
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {
|
||||
"name": {"$ref": "#/$defs/text"},
|
||||
"aliases": {
|
||||
"type": ["array", "null"],
|
||||
"items": {"$ref": "#/$defs/text"}
|
||||
},
|
||||
"classes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {
|
||||
"name": {"$ref": "#/$defs/text"},
|
||||
"level": {"type": "integer", "minimum": 1, "maximum": 9223372036854775807}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
54
assets/shared-domain/rpg/party/v0.2.0/semantics.md
Normal file
54
assets/shared-domain/rpg/party/v0.2.0/semantics.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Party 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.rpg.party.v1`. [Schema](schema.json).
|
||||
The [validation profile](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/validation.md) and [compatibility rules](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/compatibility.md)
|
||||
apply. See the [example](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/rpg/party/v0.2.0/examples/party.yml).
|
||||
|
||||
| Field | Required | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `schema_version` | Yes | Exactly `maximumdirect.rpg.party.v1`. |
|
||||
| `characters` | Yes | Mapping from stable character IDs to roster entries; an empty mapping is valid. |
|
||||
| `characters.<id>.character` | Yes | Character information. |
|
||||
| `character.name` | Yes | Nonempty canonical display name. |
|
||||
| `character.aliases` | No | Alternative names for the same character; omission, null, an empty list, or a list of nonempty strings. |
|
||||
| `character.classes` | No | List of class objects, possibly empty. Each has a nonempty `name` and optional integer `level` from 1 through 9223372036854775807 after native binding. |
|
||||
| `characters.<id>.player` | No | Player relationship. When present, an object with a required nonempty `name`. Multiple characters may have the same player. |
|
||||
|
||||
IDs are nonempty strings scoped to this party, independent of display names and
|
||||
application artifact names. They remain stable when a display name changes.
|
||||
Player names are display labels, not globally unique player identifiers.
|
||||
Equal character names and aliases do not establish identity; consumers decide
|
||||
how to handle ambiguity in a particular task. Supported strings are preserved in the resolved handoff.
|
||||
|
||||
Every object permits additional fields. Classes are optional domain information
|
||||
for campaigns that use them. Other character attributes may be extensions.
|
||||
Known fields have the documented type even when other fields are present.
|
||||
Optional objects and `classes` accept omission, not null. List order carries no
|
||||
additional contract meaning; mapping order never establishes character order.
|
||||
|
||||
A consumer can derive a party glossary from this roster. It uses character IDs
|
||||
as entry IDs, canonical names and aliases, and its selected domain category.
|
||||
Operators need not maintain a duplicate party vocabulary document.
|
||||
|
||||
## Differences from Narratio's existing party input
|
||||
|
||||
This contract uses a shared marker and `aliases` rather than `alias`. Player and
|
||||
class information is optional. IDs follow domain identity rather than artifact
|
||||
key syntax. Name uniqueness, class requirements, and mapping iteration order are
|
||||
consumer decisions. Narratio's existing `narratio.party.v1` format remains a
|
||||
separate released interface until adoption is implemented.
|
||||
20
assets/shared_domain_test.go
Normal file
20
assets/shared_domain_test.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSharedDomainContractsAreEmbedded(t *testing.T) {
|
||||
for _, path := range []string{
|
||||
"shared-domain/SOURCE.md",
|
||||
"shared-domain/glossary/v0.2.0/schema.json",
|
||||
"shared-domain/glossary/v0.2.0/semantics.md",
|
||||
"shared-domain/rpg/party/v0.2.0/schema.json",
|
||||
"shared-domain/rpg/party/v0.2.0/semantics.md",
|
||||
} {
|
||||
if _, err := fs.ReadFile(FS(), path); err != nil {
|
||||
t.Errorf("read embedded %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
54
docs/cli.md
54
docs/cli.md
@@ -23,6 +23,8 @@ notarius completion bash
|
||||
notarius pipeline list
|
||||
notarius pipeline show PIPELINE_ID
|
||||
notarius pipeline validate PIPELINE_ID
|
||||
notarius pipeline preflight PIPELINE_ID --input-file PATH
|
||||
notarius preflight PIPELINE_ID --input-file PATH
|
||||
notarius pipeline run PIPELINE_ID --input-file PATH
|
||||
notarius run PIPELINE_ID --input-file PATH
|
||||
notarius config scopes
|
||||
@@ -106,7 +108,8 @@ This is distinct from native configuration validation: request preparation and
|
||||
dynamic selections are checked when used.
|
||||
|
||||
Show and validate accept configuration selection and native report controls.
|
||||
They inspect the complete configured pipeline; lane selection belongs to run:
|
||||
They inspect the complete configured pipeline; lane selection belongs to run
|
||||
and preflight:
|
||||
|
||||
~~~sh
|
||||
notarius pipeline list --config examples/dnd-complete/config.yml --format json
|
||||
@@ -114,6 +117,44 @@ notarius pipeline show dnd-session --config examples/dnd-complete/config.yml
|
||||
notarius pipeline validate dnd-session --config examples/dnd-complete/config.yml
|
||||
~~~
|
||||
|
||||
### Preflight
|
||||
|
||||
`preflight PIPELINE_ID` is the native alias for `pipeline preflight PIPELINE_ID`.
|
||||
Both accept the same required input, selection, reference, destination, debug,
|
||||
and native override flags as [run](#run). Preflight constructs selected modules,
|
||||
checks the supplied input and external references, checks output and applicable
|
||||
cache access, and invokes available native reachability, authentication, and
|
||||
structured-generation checks for selected model targets. Checks sharing a profile
|
||||
or backend share the corresponding probe. It does not execute the pipeline or
|
||||
publish domain artifacts. Unlike offline validation it can contact providers and
|
||||
incur inference costs; see [Operations](operations.md#preflight-lifecycle).
|
||||
|
||||
The assessment contains `pipeline`, `ready`, `checks`, and an optional
|
||||
`debug_directory`. Each check has a stable class `id`, a structured `scope`, a
|
||||
`result` (`passed`, `failed`, or `warning`), a `message`, and sometimes a `code`.
|
||||
Scopes may identify a path, reference, profile, backend, pipeline, or associated bindings.
|
||||
Cache access problems warn without making readiness false. A failed or incomplete
|
||||
required check makes readiness false. Default text shows the summary, failures,
|
||||
and warnings; verbose visibility adds successful details. JSON and YAML serialize
|
||||
the same assessment. For example, a portion of a successful JSON assessment is:
|
||||
|
||||
~~~json
|
||||
{
|
||||
"checks": [
|
||||
{"id":"input","message":"Source input is valid.","result":"passed","scope":{"path":"/data/source.json"}}
|
||||
],
|
||||
"pipeline": "campaign",
|
||||
"ready": true
|
||||
}
|
||||
~~~
|
||||
|
||||
The checks shown are illustrative, not an exhaustive list. When an assessment is
|
||||
available it is delivered even for unsuccessful readiness; early argument or
|
||||
loading errors can have no assessment. Always use process status as well: capture
|
||||
or report delivery can fail independently of a ready assessment. Quiet mode can
|
||||
suppress stdout and failed delivery can leave partial output. Readiness applies
|
||||
to the supplied input, not a later transcript; run validates its own input.
|
||||
|
||||
### Run
|
||||
|
||||
~~~text
|
||||
@@ -217,7 +258,8 @@ Bind declared slots using `--reference SELECTOR=PATH`:
|
||||
Pipeline/lane selectors may match several targets and fail if they match none.
|
||||
A binding-specific selector requires its selected target to declare the slot.
|
||||
There is no stage-wide merger shorthand. CLI paths override configured external
|
||||
paths; narrower selectors beat broader ones, with last occurrence winning at
|
||||
paths while retaining each target's configured collection selection; CLI-only
|
||||
bindings use slot defaults. Narrower selectors beat broader ones, with last occurrence winning at
|
||||
equal scope. Binding and unbinding the same concrete target at equal scope fails;
|
||||
narrower actions can make intentional exceptions to broader actions.
|
||||
|
||||
@@ -232,8 +274,9 @@ For a complete D&D workflow, pipeline-level references are first-class inputs:
|
||||
~~~sh
|
||||
notarius run dnd-session --config examples/dnd-complete/config.yml \
|
||||
--input-file examples/dnd-complete/transcript.json \
|
||||
--reference party=/data/references/party.txt \
|
||||
--reference glossary=/data/references/glossary.txt \
|
||||
--reference party=/data/references/party.yml \
|
||||
--reference glossary=/data/references/glossary.yml \
|
||||
--reference spell_catalog=/data/references/glossary.yml \
|
||||
--output-dir /data/results --format json
|
||||
~~~
|
||||
|
||||
@@ -349,7 +392,8 @@ quiet command. Run capture selection remains independent of that final mode.
|
||||
|
||||
`--format json --verbose` keeps successful stdout report-only JSON while useful
|
||||
diagnostics go to stderr. No application-wide structured error envelope is
|
||||
introduced; failed stdout is not a success document.
|
||||
introduced. A failed preflight may nevertheless deliver its readiness assessment;
|
||||
run completion reports remain success-only.
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
|
||||
@@ -376,7 +376,7 @@ Logical formats belong to [chunk-map](integrations/chunk-map.md) and
|
||||
## References And Ordered Handoffs
|
||||
|
||||
Reference maps bind named slots that the selected target declares. An external
|
||||
reference is an object with `path`. Pipeline-level maps accept only external
|
||||
reference is an object with `path` and optional `collections`. Pipeline-level maps accept only external
|
||||
paths; step-local and binding-local maps may also select a normalized artifact
|
||||
from an earlier step:
|
||||
|
||||
@@ -409,6 +409,12 @@ slot. A generated binding supplies one normalized artifact in memory, including
|
||||
supported qualified fallback; it does not name a file. A configured generated
|
||||
dependency remains required even when that consumer slot is otherwise optional.
|
||||
|
||||
`collections` is an external-file selection, not an artifact selector. Omitted
|
||||
or null uses the consuming slot's defaults; `[]` selects none. Names compare
|
||||
exactly, empty names are invalid, and repeated names have no additional effect.
|
||||
Explicit names must exist. See [shared domain inputs](integrations/shared-domain-inputs.md)
|
||||
for the D&D collection roles and defaults.
|
||||
|
||||
Pipeline references are configuration defaults. A matching step-local or
|
||||
binding-local external path overrides a pipeline default. CLI reference
|
||||
bindings are then operational overrides of configured external paths; their
|
||||
@@ -419,6 +425,9 @@ after configuration and CLI reference actions are applied. A YAML reference
|
||||
path resolves from the file that supplies its surviving declaration, including
|
||||
an imported fragment or selected overlay. CLI reference paths resolve relative
|
||||
to the process working directory.
|
||||
Replacing an external reference object in a more local configuration scope
|
||||
replaces its selection too. A CLI path override retains the surviving configured
|
||||
selection for each target; a CLI-only binding uses slot defaults.
|
||||
|
||||
### D&D Reference Slots
|
||||
|
||||
@@ -427,11 +436,11 @@ selected target declares them:
|
||||
|
||||
| Slot | Source and use |
|
||||
| --- | --- |
|
||||
| **party** | Optional text campaign context. This is the canonical party-roster spelling. |
|
||||
| **party** | Optional shared party document; canonical party-roster spelling. |
|
||||
| **roster** | Accepted compatibility alias for **party**. |
|
||||
| **players** | Optional text player context. |
|
||||
| **glossary** | Optional text campaign glossary. |
|
||||
| **spell_catalog** | Optional JSON spell-catalog overlay for spell extraction and normalization. See [spell-catalog overlays](integrations/dnd-spell-catalog-overlays.md). |
|
||||
| **glossary** | Optional shared glossary document for general campaign vocabulary. |
|
||||
| **spell_catalog** | Optional shared glossary document for spell recognition and normalization. |
|
||||
| **location_registry** | Required normalized location registry for location-occurrence extraction and normalization. |
|
||||
| **item_registry** | Required normalized item registry for item-occurrence extraction and normalization. |
|
||||
| **npc_registry** | Normalized NPC registry. Optional for spells and combat turns; required for NPC occurrences and enemy-event extraction and normalization. |
|
||||
|
||||
@@ -20,7 +20,7 @@ CLI reference paths use the process working directory. Absolute caller paths
|
||||
are useful for services. Keep credentials in the intended environment, not
|
||||
files, arguments, sessions, or logs.
|
||||
|
||||
Preflight without credentials or inference:
|
||||
Validate without credentials or inference:
|
||||
|
||||
~~~sh
|
||||
notarius config validate --config /absolute/path/to/notarius.yml
|
||||
@@ -41,10 +41,9 @@ notarius run dnd-session \
|
||||
--config /absolute/path/to/notarius.yml \
|
||||
--input-file /absolute/path/to/transcripts/final.trimmed.json \
|
||||
--output-dir /absolute/path/to/notarius-output \
|
||||
--reference party=/absolute/path/to/references/party.txt \
|
||||
--reference players=/absolute/path/to/references/players.txt \
|
||||
--reference glossary=/absolute/path/to/references/glossary.txt \
|
||||
--reference spell_catalog=/absolute/path/to/references/spells.json \
|
||||
--reference party=/absolute/path/to/references/party.yml \
|
||||
--reference glossary=/absolute/path/to/references/glossary.yml \
|
||||
--reference spell_catalog=/absolute/path/to/references/glossary.yml \
|
||||
--format json
|
||||
~~~
|
||||
|
||||
@@ -53,6 +52,17 @@ reach every selected target declaring the slot; narrower overrides follow the
|
||||
[selector contract](../cli.md#reference-selectors). Generated registry, scene,
|
||||
combat, and NPC-occurrence handoffs stay in pipeline configuration, not CLI file
|
||||
bindings.
|
||||
The [shared input contract](../integrations/shared-domain-inputs.md) explains
|
||||
the party and glossary envelopes, selection defaults, and migration. Roster
|
||||
player relationships do not require a separate player file; supplemental
|
||||
`players` text remains optional.
|
||||
|
||||
For an optional online readiness check, use `notarius preflight dnd-session`
|
||||
with the same configuration, transcript, output root, and reference arguments as
|
||||
the run above. Check process status and any available assessment as described in
|
||||
the [subprocess workflow](subprocess.md#prepare-and-run); the
|
||||
[CLI reference](../cli.md#preflight) owns report semantics. A synthetic input
|
||||
checks that input only, not a subsequent final transcript.
|
||||
|
||||
The ordinary input-based session is suitable without an override. Use
|
||||
`--llm-session-id` only to intentionally change its native selection.
|
||||
|
||||
@@ -27,17 +27,36 @@ notarius pipeline validate pipeline-id \
|
||||
Omit the overlay for the composed base. Pipeline validation needs no transcript,
|
||||
reference bytes, credentials, provider call, or state directory.
|
||||
|
||||
Then run with first-class source and output inputs:
|
||||
Optionally perform online readiness checks with the same selection and references
|
||||
that will be used for execution:
|
||||
|
||||
~~~sh
|
||||
notarius preflight pipeline-id \
|
||||
--config /absolute/path/to/notarius.yml --overlay production \
|
||||
--input-file /absolute/path/to/source.json \
|
||||
--reference party=/absolute/path/to/party.yml \
|
||||
--output-dir /absolute/path/to/output-root --format json
|
||||
~~~
|
||||
|
||||
Check process status even when a report is present. On nonzero status, decode an
|
||||
available complete assessment for details when useful; early errors may produce
|
||||
none and failed delivery may leave partial bytes. `ready: true` alone does not
|
||||
override a failing status. A synthetic transcript is ordinary supplied input:
|
||||
its successful assessment does not establish readiness of a future transcript.
|
||||
Preflight can contact providers and incur costs; see
|
||||
[preflight operation](../operations.md#preflight-lifecycle).
|
||||
|
||||
Then run with the same selection and reference:
|
||||
|
||||
~~~sh
|
||||
notarius run pipeline-id \
|
||||
--config /absolute/path/to/notarius.yml --overlay production \
|
||||
--input-file /absolute/path/to/source.json \
|
||||
--reference party=/absolute/path/to/party.yml \
|
||||
--output-dir /absolute/path/to/output-root --format json
|
||||
~~~
|
||||
|
||||
Pass external references as separate arguments, for example
|
||||
`--reference party=/absolute/path/to/party.txt`. Unqualified selectors reach
|
||||
Pass external references as separate arguments. Unqualified selectors reach
|
||||
compatible selected targets; narrower selectors are exceptional overrides.
|
||||
Generated same-run handoffs stay configured, not CLI files. The
|
||||
[reference selector contract](../cli.md#reference-selectors) owns matching and
|
||||
|
||||
@@ -43,7 +43,7 @@ implementing changes. It owns implementation discipline and local commit rules.
|
||||
| Building a subprocess caller or changing its result protocol | [Subprocess Consumer Guide](consumers/subprocess.md), [Complete D&D Consumer Guide](consumers/dnd-pipeline.md), [Native Completion Report](cli.md#completion-report), and [CLI Internals](internal/cli.md) | These separate generic caller workflow, the complete D&D workflow, the native completion report, and CLI implementation behavior. |
|
||||
| Configuration loading, resolution, or user-visible configuration behavior | [Configuration Internals](internal/configuration.md) and [Configuration](config.md) | The internal guide owns loading and resolution mechanics; the reference owns the configuration contract. |
|
||||
| Pipeline resolution or execution | [Pipeline Internals](internal/pipeline.md) | It documents typed preparation, complete assessment, native continuation, workers, and handoff eligibility. |
|
||||
| Production modules or validators | [Module Internals](internal/modules.md), [D&D Module Internals](internal/dnd.md), and [D&D integration contracts](integrations/) | The generic guide owns extension mechanics, the D&D guide owns shared family conventions, and the contracts own durable output shapes. |
|
||||
| Production modules or validators | [Module Internals](internal/modules.md), [D&D Module Internals](internal/dnd.md), [shared domain inputs](integrations/shared-domain-inputs.md), and [D&D integration contracts](integrations/) | The generic guide owns extension mechanics, the D&D guide owns shared family conventions, and the contracts own input and durable output shapes. |
|
||||
| Native execution, prompts, schemas, profiles, or admission | [LLM Integration](internal/llm.md) | It locates shared engine construction, native request/continuation calls, and evidence hooks. |
|
||||
| Kit API, source handoff, or standard-suite integration | [ConfigKit](integrations/pkg-configkit.md), [PromptKit](integrations/pkg-promptkit.md), and [CommandKit](integrations/pkg-commandkit.md) | These define the selected upstream integration boundaries and link pinned native contracts. |
|
||||
| Output, accepted-result reuse, or debug artifacts | [Run State Internals](internal/state.md), [Operations](operations.md), and [Configuration](config.md) | These separate implementation details, operator behavior, and configuration contracts. |
|
||||
|
||||
@@ -67,7 +67,7 @@ into `source_refs`.
|
||||
|
||||
## Related contracts
|
||||
|
||||
The [spell-catalog overlay contract](dnd-spell-catalog-overlays.md) defines
|
||||
The [shared domain input contract](shared-domain-inputs.md) defines
|
||||
the configured catalog additions. The [JSON output contract](json-output.md)
|
||||
defines where this logical artifact is published; [D&D module internals](../internal/dnd.md)
|
||||
describes extraction and validation mechanics.
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
# D&D Spell-Catalog Overlays
|
||||
|
||||
This document defines the optional JSON overlay consumed by the D&D spell
|
||||
extractor. An overlay contributes campaign spell names and aliases for
|
||||
recognition. It does not define spell rules, effects, levels, classes, or
|
||||
transcript evidence. Bind the optional `spell_catalog` reference as described
|
||||
in [Configuration](../config.md#references-and-ordered-handoffs).
|
||||
|
||||
## Contract Identity
|
||||
|
||||
| Property | Value |
|
||||
| --- | --- |
|
||||
| Consumer | D&D spell extraction and normalization |
|
||||
| Reference slot | `spell_catalog` |
|
||||
| Media type | `application/json` |
|
||||
| Required schema version | `notarius.dnd.spell-catalog-overlay.v1` |
|
||||
| Base catalog | Embedded D&D 5e 2014 SRD catalog |
|
||||
|
||||
At most one overlay document may be bound. The maintained example is
|
||||
[spell-catalog.json](../../examples/dnd-complete/spell-catalog.json).
|
||||
|
||||
## Wire Shape
|
||||
|
||||
This is a minimal valid overlay:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "notarius.dnd.spell-catalog-overlay.v1",
|
||||
"catalogs": [
|
||||
{
|
||||
"id": "campaign.example",
|
||||
"ruleset": "dnd-5e-2014",
|
||||
"source": {"title": "Example campaign spells"},
|
||||
"spells": [{"name": "Aegis of Emberfall"}]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Meaning and constraints |
|
||||
| --- | --- | --- |
|
||||
| `schema_version` | Yes | Exactly `notarius.dnd.spell-catalog-overlay.v1`. |
|
||||
| `catalogs` | Yes | Non-empty array of catalog objects with unique IDs. |
|
||||
| `catalogs[].id` | Yes | Non-empty trimmed string. |
|
||||
| `catalogs[].ruleset` | Yes | Exactly `dnd-5e-2014`. |
|
||||
| `catalogs[].source.title` | Yes | Non-empty trimmed string. |
|
||||
| `catalogs[].source.version` | No | String when present. |
|
||||
| `catalogs[].source.url` | No | String when present. |
|
||||
| `catalogs[].source.license` | No | String when present. |
|
||||
| `catalogs[].spells` | Yes | Non-empty array of spell objects. |
|
||||
| `catalogs[].spells[].name` | Yes | Non-empty trimmed string. |
|
||||
| `catalogs[].spells[].aliases` | No | Array of non-empty trimmed strings when present. |
|
||||
|
||||
Unknown fields are rejected at every object level. The document must contain
|
||||
one JSON value; `null` is not accepted for optional strings or aliases.
|
||||
|
||||
## Composition And Compatibility
|
||||
|
||||
Notarius starts with the embedded base catalog, then applies overlay catalogs
|
||||
in ascending catalog-ID order. A new canonical spell name adds a recognition
|
||||
entry. If an overlay names an existing canonical spell, it augments that spell
|
||||
with aliases while retaining the established display spelling.
|
||||
|
||||
Repeated aliases for the same spell are accepted. A canonical-name, canonical-
|
||||
to-alias, or alias-to-alias collision between different spells is rejected,
|
||||
including a collision with the embedded catalog. Matching uses the catalog’s
|
||||
case, whitespace, and apostrophe normalization, so authors should avoid names
|
||||
or aliases that normalize to another spell.
|
||||
|
||||
Spell extraction receives the effective catalog as deterministic canonical-name
|
||||
and alias pairs. An alias in the transcript selects its associated canonical
|
||||
name; the extractor is instructed to return that canonical spelling. The
|
||||
projection contains no catalog source metadata or provenance, and aliases
|
||||
remain recognition context rather than transcript evidence.
|
||||
|
||||
The overlay is a recognition aid only. The durable spell-artifact schema and
|
||||
source-evidence rules are defined by the
|
||||
[D&D spell artifact contract](dnd-spell-artifacts.md).
|
||||
@@ -59,6 +59,9 @@ perform native request preparation; explicit smoke tests can perform network or
|
||||
model work and retain native supported/applicable/result distinctions.
|
||||
Pipeline validation is separately application-owned offline preflight, not a
|
||||
mode added to native configuration validation.
|
||||
The explicit pipeline preflight command submits its readiness value through the
|
||||
same [native reporting API](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/docs/consumers/guide.md#invocation-reporting),
|
||||
including when readiness fails; process and delivery outcomes remain distinct.
|
||||
|
||||
Application run inputs reuse `NewResourceFlags` and `NewExecutionFlags`, selecting
|
||||
profile/session and execution controls while leaving prompt/source inputs
|
||||
@@ -79,7 +82,8 @@ domain artifacts, not a saved report, are the durable deliverables.
|
||||
The nonempty ckprompt declarations also install optional invocation usage
|
||||
reporting. Notarius propagates the invocation context and joins its work before
|
||||
returning; it supplies no manual flag, accounting totals, or final usage callback.
|
||||
Requested debug capture has its own independent native group. See
|
||||
Run debug capture has its own independent native group; preflight smoke usage
|
||||
remains in native smoke reports instead. See
|
||||
[native usage reporting][usage] and [CLI internals](../internal/cli.md#native-reporting-and-outcomes).
|
||||
|
||||
Native reporting handles result/diagnostic destinations, visibility, progress,
|
||||
|
||||
@@ -42,6 +42,11 @@ control effective values.
|
||||
|
||||
## Execution, Interpretation, And Continuation
|
||||
|
||||
Pipeline preflight uses native [resource inspection](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/resource_inspection.go)
|
||||
and [smoke diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/smoke_diagnostics.go)
|
||||
for selected targets. Notarius owns readiness interpretation and retains native
|
||||
reports separately from ordinary execution observation.
|
||||
|
||||
Modules build `RunRequest` with selected prompt/profile/session, owned inline
|
||||
artifacts and variables; they interpret `RunResult` into typed domain values.
|
||||
Notarius materializes source/references and contextual identity projections
|
||||
|
||||
68
docs/integrations/shared-domain-inputs.md
Normal file
68
docs/integrations/shared-domain-inputs.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Shared Domain Reference Inputs
|
||||
|
||||
Notarius accepts shared party and glossary documents as optional D&D reference
|
||||
inputs. The complete example provides a [party](../../examples/dnd-complete/party.yml)
|
||||
and one [multi-collection glossary](../../examples/dnd-complete/glossary.yml).
|
||||
The reference binding interface and defaults belong to
|
||||
[Configuration](../config.md#references-and-ordered-handoffs).
|
||||
|
||||
## Supported Contracts
|
||||
|
||||
Notarius bundles the following contracts from shared schemas distribution
|
||||
`2026.11.1`, commit `f7e3cedeca11ed903311cdf29ca4d81fb1f216b7`, for offline
|
||||
validation. The document marker is not a schema-version selector.
|
||||
|
||||
| Role | Version and marker | Upstream semantics |
|
||||
| --- | --- | --- |
|
||||
| `party` and accepted `roster` aliases | RPG party `0.2.0`, `maximumdirect.rpg.party.v1` | [Party semantics](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/rpg/party/v0.2.0/semantics.md) |
|
||||
| `glossary` and `spell_catalog` | Glossary `0.2.0`, `maximumdirect.glossary.v1` | [Glossary semantics](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/glossary/v0.2.0/semantics.md) |
|
||||
|
||||
Inputs are YAML or JSON, with media types `application/yaml`,
|
||||
`application/x-yaml`, or `application/json`. JSON must use JSON syntax.
|
||||
Both serializations pass through ConfigKit's native mapping load and are
|
||||
validated as complete documents, including unselected collections. See the
|
||||
pinned [ConfigKit native contract](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/docs/config.md)
|
||||
for loading, dynamic numeric binding, limits, and reserved controls such as
|
||||
`extends` and source-root `config`. Notarius adds exact per-collection entry-ID
|
||||
uniqueness and task-specific suitability checks; ordinary extensions remain
|
||||
data, not instructions.
|
||||
|
||||
## Task Views
|
||||
|
||||
Each binding selects collections independently. General glossary context defaults
|
||||
to the available `campaign` and `setting` collections; a bound
|
||||
`spell_catalog` defaults to `spells`, which must exist. Explicit selections
|
||||
must exist, may be empty, and compare names exactly. Empty valid selections or
|
||||
collections contribute no added vocabulary. No binding is required merely
|
||||
because another is present. The same file can serve both roles.
|
||||
|
||||
Party context includes names, aliases, optional player relationships and
|
||||
classes/levels, without exposing roster IDs to the model. Distinct roster
|
||||
entries remain distinct even when names match. `party` takes presentation
|
||||
precedence over `roster`; both supplied documents are validated.
|
||||
`players` remains optional supplemental text. No duplicate player list is
|
||||
needed for relationships already in the roster.
|
||||
|
||||
General glossary context projects names, aliases, categories, descriptions,
|
||||
and plural forms. Spell recognition projects names and aliases only and starts
|
||||
with the embedded D&D 5e 2014 SRD vocabulary. Existing canonical display
|
||||
names take precedence; selected entries may augment their aliases. Conflicting
|
||||
recognition keys for different spells are task errors. Collection names and
|
||||
entry IDs determine deterministic traversal; IDs, provenance, and irrelevant
|
||||
extensions are not promoted to model instructions or transcript evidence.
|
||||
|
||||
## Migration
|
||||
|
||||
Replace plain-text `party` or `roster` files with the shared party envelope
|
||||
and move character/player relationships into roster entries. Replace text
|
||||
`glossary` files and the private `notarius.dnd.spell-catalog-overlay.v1`
|
||||
envelope with shared glossary entries under named collections. Map old spell
|
||||
names and aliases directly to entries; old ruleset metadata is not required,
|
||||
and source information may be optional collection provenance. Aliases may be
|
||||
omitted, null, or empty. Add `collections` on an external binding only when
|
||||
the slot defaults are not appropriate. Existing slot names and CLI selectors
|
||||
remain unchanged. There is no legacy reader or automatic conversion.
|
||||
|
||||
Run and explicit preflight validate supplied documents during preparation,
|
||||
before domain inference; offline pipeline validation does not read reference
|
||||
files. See [CLI preflight](../cli.md#preflight) for its readiness scope.
|
||||
@@ -21,7 +21,7 @@ continue to use their caller-supplied contexts.
|
||||
The constructor wires:
|
||||
|
||||
- native help/version and installed shell completion;
|
||||
- application pipeline declarations and a native run alias;
|
||||
- application pipeline declarations and native run and preflight aliases;
|
||||
- ckconfig whole-application and focused PromptKit scopes, sharing one loader;
|
||||
- ckprompt resource/requirements inspection, concrete request validation,
|
||||
prepared preview, namespace selection, and explicit smoke testing.
|
||||
@@ -63,10 +63,11 @@ with production entries.
|
||||
- validating: domain resolution plus known-resource preflight, supplying the
|
||||
same captured engine only when model roles require it.
|
||||
|
||||
[Preflight](../../internal/preflight/preflight.go) accepts collaborators/data;
|
||||
it does not load configuration, register/construct modules, read execution
|
||||
inputs, render CLI reports, or allocate state. Partial profiles pass native
|
||||
inspection, with concrete request readiness deferred until preparation.
|
||||
[Offline dependency validation](../../internal/preflight/preflight.go) accepts
|
||||
collaborators and data without reading execution inputs or allocating state.
|
||||
Partial profiles pass inspection. The same package also discovers selected
|
||||
initial targets and orchestrates explicit native smoke checks; the CLI owns
|
||||
their input, destination, capture, and presentation boundaries.
|
||||
|
||||
## Run Inputs And Native Overrides
|
||||
|
||||
@@ -93,6 +94,15 @@ Framework/model code transports it rather than deriving another session.
|
||||
|
||||
## Run Orchestration
|
||||
|
||||
[pipeline_invocation.go](../../internal/cli/pipeline_invocation.go) shares
|
||||
loading, selection, reference materialization, construction, input reading,
|
||||
and session selection between run and
|
||||
[preflight](../../internal/cli/pipeline_preflight.go). The latter parses through
|
||||
the prepared pipeline, probes destinations, discovers targets, and hands native
|
||||
observations to its readiness report without invoking the runner or cache store.
|
||||
It finalizes requested capture before report delivery; assessment and capture or
|
||||
delivery outcomes remain independently meaningful.
|
||||
|
||||
The native command declaration in [pipeline_run.go](../../internal/cli/pipeline_run.go)
|
||||
creates a private owner for each invocation. That owner performs the ordered
|
||||
handoff and keeps capture and publication state local to that run:
|
||||
@@ -160,7 +170,8 @@ behavior. There is no universal Notarius envelope or parallel serializer.
|
||||
[schema tests](../../internal/cli/native_schema_load_test.go) cover native
|
||||
composition, captured contexts, and operator contracts.
|
||||
- [Pipeline command tests](../../internal/cli/pipeline_commands_test.go) cover
|
||||
listing/showing/preflight without execution inputs or state.
|
||||
offline listing, showing, and validation; [preflight tests](../../internal/cli/pipeline_preflight_test.go)
|
||||
cover readiness reporting and the explicit online route.
|
||||
- [Override tests](../../internal/cli/execution_overrides_test.go) and
|
||||
[run tests](../../internal/cli/pipeline_run_test.go) cover supplied values,
|
||||
routing, references, sessions, and run ordering.
|
||||
|
||||
@@ -42,6 +42,14 @@ separate from execution integration.
|
||||
|
||||
## Prompt Construction
|
||||
|
||||
The [shared context preparer](../../internal/modules/dnd/shared/context.go)
|
||||
loads and validates selected party and glossary references at construction,
|
||||
then retains narrow immutable prompt projections. Each operation combines them
|
||||
with its own transcript; generated registry and scene handoffs remain dynamic.
|
||||
The spell catalog builds recognition views from the same shared glossary
|
||||
integration. The [shared input contract](../integrations/shared-domain-inputs.md)
|
||||
owns supported formats and selection semantics.
|
||||
|
||||
Content lives beneath [assets/dnd](../../assets/dnd/), with ordinary native
|
||||
declarations imported by [assets/notarius.yml](../../assets/notarius.yml).
|
||||
The root assets package stays a content-only leaf. Declaration-relative content
|
||||
@@ -275,7 +283,7 @@ not accepted-result cache identity.
|
||||
|
||||
| Lane | Intentional behavior |
|
||||
| --- | --- |
|
||||
| Spells | May use a spell-catalog overlay and optional NPC grounding; the catalog validator supplies domain-specific semantic checks. |
|
||||
| Spells | May use a shared glossary for recognition and optional NPC grounding; the catalog validator supplies domain-specific semantic checks. |
|
||||
| NPC registry | Establishes transcript-grounded NPC identities, including factual third-party mentions, without assigning occurrence categories. It does not consume an NPC registry, and its normalizer is the LLM-assisted reconciliation exception described above. |
|
||||
| Combat turns | Requires a scene-description artifact. It calls the LLM only for an exact `combat` classification; non-combat paths directly assess an empty result, while missing or mismatched classifications also retain a bounded warning. Optional NPC grounding never becomes evidence. |
|
||||
| Item occurrences | Requires the normalized item registry for exact deterministic grounding at extraction and normalization. Campaign context may disambiguate, but the registry never becomes occurrence evidence. |
|
||||
|
||||
@@ -29,6 +29,13 @@ operation invokes a model.
|
||||
|
||||
## Requests And Fixed Operation Inputs
|
||||
|
||||
Explicit pipeline preflight inventories selected initial profiles and access
|
||||
scopes, then invokes native smoke diagnostics using request-scoped overrides.
|
||||
It interprets supported/applicable reports and affirmative facts rather than
|
||||
treating a nil error as readiness. Smoke reports and usage remain separate from
|
||||
ordinary execution observer totals. The [native smoke contract](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/smoke_diagnostics.go)
|
||||
owns diagnostic mechanics.
|
||||
|
||||
Core owns the shared engine. A model module prepares transcript, references, contextual identity projections, and any
|
||||
normalization candidate mapping once. It constructs a `promptkit.RunRequest`
|
||||
with its selected prompt, profile/session, native artifact inputs, and variables.
|
||||
|
||||
@@ -19,6 +19,9 @@ and statically selected prompt IDs. Specs can be inspected without constructing
|
||||
modules. The resolver applies model-profile selections only to model roles.
|
||||
Static initial/correction dependencies use the same constants as request builders;
|
||||
they are preflight declarations, not asset manifests or execution fingerprints.
|
||||
The separate initial-prompt selection identifies independently targeted initial
|
||||
requests; correction dependencies remain in the complete offline list. Validator
|
||||
prompt declarations identify assessment requests.
|
||||
|
||||
[BuildRequest](../../internal/framework/pipeline/construction.go) supplies
|
||||
dependencies, option values, and prepared references; one-shot validators may
|
||||
|
||||
@@ -12,6 +12,8 @@ cmd/notarius -> internal/cli: native commands, one selected config result/engine
|
||||
-> resolve + offline preflight + materialize + typed preparation
|
||||
-> pipeline: parse -> chunk -> ordered lane work -> logical files
|
||||
-> internal/cli: publication -> requested capture finish -> report
|
||||
-> explicit preflight: shared local preparation -> destination checks
|
||||
-> native target diagnostics -> capture finish -> readiness report
|
||||
```
|
||||
|
||||
The executable supplies build identity. The composition root owns native command
|
||||
@@ -27,7 +29,7 @@ streams or roots. Standard inspection/preflight paths do not become runs.
|
||||
| Application configuration | [internal/core/config](../../internal/core/config/) | Composed ConfigKit/native settings definition, source-aware normalization, detached runtime conversion, application validation, effective domain resolution. |
|
||||
| Generic source and typed contracts | [internal/core/source](../../internal/core/source/), [internal/framework/contracts](../../internal/framework/contracts/) | Documents/units/chunks, typed production/assessment, source references, codecs, native execution selections, and small cache/evidence collaborators. |
|
||||
| Pipeline framework | [internal/framework/pipeline](../../internal/framework/pipeline/) | Registries, typed resolution, core-invoked preparation and execution, complete candidate assessment, ready-job workers, ordered handoffs, reuse eligibility, evidence/output assembly. |
|
||||
| Offline dependency preflight | [internal/preflight](../../internal/preflight/) | Known native prompt/profile checks on already resolved composition and supplied engine; no synthetic request or execution input reads. |
|
||||
| Pipeline preflight | [internal/preflight](../../internal/preflight/) | Offline known-resource checks plus selected-target discovery and explicit native smoke observation interpretation. |
|
||||
| Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Prepared reconciliation operations, bounded candidate/window inputs, request-local proposal safety, typed fresh application, and evaluation-scoped details. |
|
||||
| Embedded content | [assets](../../assets/) | Content-only native prompt/profile/schema/message files imported with filesystem contexts; no behavioral registry. |
|
||||
| Accepted-result cache | [internal/framework/artifactcache](../../internal/framework/artifactcache/) | Raw accepted artifact/plan bytes under native content keys, confined atomic publication, and deployment-owned creation permissions. |
|
||||
|
||||
@@ -55,6 +55,9 @@ registries and the shared native engine. Builders receive independently owned
|
||||
build requests. Exact Go type, codec, evidence-projector, registration, and
|
||||
constructor checks happen before source parsing. There is no correction transport,
|
||||
asset registry, or persistent execution identity to collect.
|
||||
`PreparedPipeline.ParseSource` shares the constructed adapter's parsing and
|
||||
generic document validation with explicit preflight. The runner uses that same
|
||||
operation and creates its source index once; preflight does not chunk or execute.
|
||||
Pure [profile and binding copies](../../internal/framework/pipeline/profile_copy.go)
|
||||
detach supported mutable options, references, and controls without interpreting
|
||||
names or defaults; decoding and resolution perform their own normalization.
|
||||
|
||||
@@ -122,9 +122,15 @@ in [CLI Reference](../cli.md#output-streams-and-exit-statuses) and the
|
||||
|
||||
## Capture Lifecycle
|
||||
|
||||
Explicit preflight uses the same allocation and terminalization lifecycle, with
|
||||
temporary output/cache access probes instead of a run directory or cache store.
|
||||
It records performed native smoke reports separately from execution observations;
|
||||
capture failure stops remaining diagnostics and is independent of assessment
|
||||
and report delivery. See [preflight operation](../operations.md#preflight-lifecycle).
|
||||
|
||||
[Debug selection](../../internal/cli/run_debug.go) preserves native boolean and
|
||||
supplied directory semantics independently of verbosity. The run path alone
|
||||
calls [debug.Start](../../internal/framework/debug/recorder.go).
|
||||
supplied directory semantics independently of verbosity. Run and explicit preflight
|
||||
call [debug.Start](../../internal/framework/debug/recorder.go).
|
||||
[Bundle allocation](../../internal/core/debugbundle/bundle.go) validates identity,
|
||||
creates a new absolute per-run directory, and atomically updates a relative
|
||||
latest link at start. Failure can return an available directory for explanation/
|
||||
@@ -141,6 +147,10 @@ fallback directory. Available files are retained.
|
||||
|
||||
## Native And Application Evidence
|
||||
|
||||
Both invocation owners share early context capture. It records provider-parameter
|
||||
override presence rather than raw maps; effective parameters remain in native
|
||||
evidence with selected-target sensitivity marks applied.
|
||||
|
||||
[Run capture](../../internal/cli/run_capture.go) snapshots the original secret-aware
|
||||
application/PromptKit configuration. The runner selects the explicit evidence
|
||||
writer when provided, otherwise enabled debug, and writes original and parsed
|
||||
|
||||
@@ -170,6 +170,22 @@ per group rather than an exhaustive occurrence ledger.
|
||||
[Configuration](config.md#producer-controls) owns selected modes, turn allowances,
|
||||
defaults, and precedence.
|
||||
|
||||
## Preflight Lifecycle
|
||||
|
||||
Explicit online preflight reads the selected input and references, prepares the
|
||||
pipeline, and contacts selected providers for applicable native access and
|
||||
structured-generation checks. These checks can incur inference charges. It does
|
||||
not publish extraction artifacts or use accepted cache entries as readiness proof.
|
||||
|
||||
Preflight creates the output root if necessary and writes, closes, and removes a
|
||||
temporary access file. For selected cacheable work, auto and refresh similarly
|
||||
probe the cache root without reading or changing accepted entries; bypass and
|
||||
deterministic work do not access it. Cache probe problems warn; output access
|
||||
failure fails readiness. Temporary probe files are removed when possible, but
|
||||
newly created roots can remain. Requested debug uses the real capture lifecycle
|
||||
and is required work. See [CLI Reference](cli.md#preflight) for the command and
|
||||
assessment and [Debug Bundles](#debug-bundles) for capture handling.
|
||||
|
||||
## Output Bundles
|
||||
|
||||
The encoder defines [logical artifact files](integrations/json-output.md);
|
||||
@@ -249,9 +265,9 @@ Directory configuration alone does not enable it. Explicit empty disables it;
|
||||
a nonempty invocation override can re-enable it. [Configuration](config.md#file-shape-and-defaults)
|
||||
owns defaults/origins; [CLI Reference](cli.md#run) owns mode ordering.
|
||||
|
||||
Allocation creates the run directory and updates `latest` to a relative link
|
||||
Allocation creates the capture directory and updates `latest` to a relative link
|
||||
at session start. It reflects the last successful start link update, including a
|
||||
run that later fails. Completion never retargets it. Concurrent starts retain
|
||||
invocation that later fails. Completion never retargets it. Concurrent starts retain
|
||||
separate directories; disabled capture leaves the link untouched. This link is
|
||||
not an output-discovery API.
|
||||
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# Open Source Attribution Notices
|
||||
|
||||
## Maximum Direct shared schemas
|
||||
|
||||
Material: glossary and RPG party schemas and semantics under `assets/shared-domain/`;
|
||||
schemas copied without modification, semantics adapted for navigation.
|
||||
|
||||
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) |
|
||||
[LICENSE](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/LICENSE).
|
||||
|
||||
[Source](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7).
|
||||
|
||||
## Standard Repository Policies
|
||||
|
||||
Material: policy documents under `docs/policy/`, adapted for this repository.
|
||||
|
||||
121
docs/oss/licenses/CC0-1.0.txt
Normal file
121
docs/oss/licenses/CC0-1.0.txt
Normal file
@@ -0,0 +1,121 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
HEREUNDER.
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without fear
|
||||
of later claims of infringement build upon, modify, incorporate in other
|
||||
works, reuse and redistribute as freely as possible in any form whatsoever
|
||||
and for any purposes, including without limitation commercial purposes.
|
||||
These owners may contribute to the Commons to promote the ideal of a free
|
||||
culture and the further production of creative, cultural and scientific
|
||||
works, or to gain reputation or greater distribution for their Work in
|
||||
part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
||||
is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under its
|
||||
terms, with knowledge of his or her Copyright and Related Rights in the
|
||||
Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not
|
||||
limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image or
|
||||
likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation
|
||||
thereof, including any amended or successor version of such
|
||||
directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention
|
||||
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
||||
irrevocably and unconditionally waives, abandons, and surrenders all of
|
||||
Affirmer's Copyright and Related Rights and associated claims and causes
|
||||
of action, whether now known or unknown (including existing as well as
|
||||
future claims and causes of action), in the Work (i) in all territories
|
||||
worldwide, (ii) for the maximum duration provided by applicable law or
|
||||
treaty (including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional
|
||||
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
||||
member of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason
|
||||
be judged legally invalid or ineffective under applicable law, then the
|
||||
Waiver shall be preserved to the maximum extent permitted taking into
|
||||
account Affirmer's express Statement of Purpose. In addition, to the
|
||||
extent the Waiver is so judged Affirmer hereby grants to each affected
|
||||
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
||||
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
||||
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
||||
maximum duration provided by applicable law or treaty (including future
|
||||
time extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"License"). The License shall be deemed effective as of the date CC0 was
|
||||
applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder
|
||||
of the License, and in such case Affirmer hereby affirms that he or she
|
||||
will not (i) exercise any of his or her remaining Copyright and Related
|
||||
Rights in the Work or (ii) assert any associated claims and causes of
|
||||
action with respect to the Work, in either case contrary to Affirmer's
|
||||
express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy, or
|
||||
the present or absence of errors, whether or not discoverable, all to
|
||||
the greatest extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without
|
||||
limitation any person's Copyright and Related Rights in the Work.
|
||||
Further, Affirmer disclaims responsibility for obtaining any necessary
|
||||
consents, permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to
|
||||
this CC0 or use of the Work.
|
||||
@@ -285,11 +285,14 @@ native supplied-value semantics. CommandKit, ckconfig, and ckprompt own standard
|
||||
commands, parsing, presentation, and delivery outcomes. Notarius supplies domain
|
||||
commands and report content, not a universal result envelope.
|
||||
|
||||
Offline preflight shares domain resolution and checks statically known module,
|
||||
Offline pipeline validation shares domain resolution and checks statically known module,
|
||||
reference, initial/correction/validator prompt, and applicable profile dependencies
|
||||
before execution. It requires no transcript, reference bytes, credentials,
|
||||
provider call, or run storage. Dynamic selections remain runtime checks.
|
||||
Shared loaders allocate no run storage; capture belongs to the run path.
|
||||
Shared loaders allocate no run storage. Explicit online pipeline preflight may
|
||||
read selected inputs and references, probe invocation destinations, allocate
|
||||
requested capture, and run native diagnostics. The pipeline application owns
|
||||
readiness interpretation; ordinary run does not implicitly perform those probes.
|
||||
|
||||
## Trust Boundaries And Threat Scope
|
||||
|
||||
@@ -353,7 +356,8 @@ execution claims on cache hits.
|
||||
|
||||
Debug is never a cache input. Capture requires explicit enablement and a nonempty
|
||||
effective destination; directory configuration alone does not enable it. Requested
|
||||
capture is required work: allocate before engine construction/preflight, record
|
||||
capture is required work for run and explicit preflight: allocate before engine
|
||||
construction and pipeline resolution, record
|
||||
incrementally, and finalize once before successful reporting. Capture failures
|
||||
fail the invocation while retaining available evidence and primary causes.
|
||||
Update the relative `latest` link at session start, never completion.
|
||||
|
||||
83
docs/releases/v0.10.0.md
Normal file
83
docs/releases/v0.10.0.md
Normal file
@@ -0,0 +1,83 @@
|
||||
# Notarius v0.10.0
|
||||
|
||||
Notarius adds pipeline-aware readiness checks and adopts shared party and
|
||||
glossary documents for D&D reference inputs. Operators can check a selected
|
||||
invocation before extraction and maintain one roster and vocabulary source
|
||||
across applications that support the shared contracts.
|
||||
|
||||
## Compatibility And Upgrade
|
||||
|
||||
This release changes the D&D reference-input contract. Existing plain-text
|
||||
`party`, `roster`, and `glossary` inputs and the private
|
||||
`notarius.dnd.spell-catalog-overlay.v1` format must be migrated. There is no
|
||||
legacy reader or automatic conversion. References remain optional.
|
||||
|
||||
- Replace `party` and accepted `roster` inputs with shared RPG party documents.
|
||||
Character aliases, optional player relationships, and classes/levels become
|
||||
contextual input without a second player list. `players` remains optional
|
||||
supplemental text.
|
||||
- Replace general glossary text and private spell overlays with shared glossary
|
||||
documents containing named collections. One file can serve both the `glossary`
|
||||
and `spell_catalog` slots. General context defaults to available `campaign`
|
||||
and `setting` collections; a bound spell catalog defaults to `spells`.
|
||||
- Use `collections` on an external reference binding to select other collections.
|
||||
Omission or null uses slot defaults; explicit `[]` selects none. CLI
|
||||
`--reference` overrides change the path while retaining each target's effective
|
||||
configured selection.
|
||||
|
||||
The selected contracts are glossary and RPG party `0.2.0` from shared schemas
|
||||
distribution `2026.11.1`. Their document markers remain
|
||||
`maximumdirect.glossary.v1` and `maximumdirect.rpg.party.v1`; the markers alone
|
||||
do not identify the exact contract version. YAML and JSON use ConfigKit's native
|
||||
loading boundary, followed by offline schema and domain validation. See
|
||||
[shared domain inputs](../integrations/shared-domain-inputs.md) for supported
|
||||
contracts, task adaptations, and migration guidance, and the refreshed
|
||||
[complete D&D example](../../examples/dnd-complete/config.yml) for maintained files.
|
||||
|
||||
Configuration version `6`, existing reference slot names and CLI selectors,
|
||||
durable output artifact schemas, and lane filenames remain unchanged. The Go
|
||||
consumer minimum remains `1.27.0`; dependency versions are unchanged from v0.9.0.
|
||||
|
||||
## Pipeline-Aware Preflight
|
||||
|
||||
Use `notarius preflight PIPELINE_ID --input-file PATH`, also available as
|
||||
`notarius pipeline preflight`, with the same selection, reference, destination,
|
||||
and execution overrides intended for the run.
|
||||
|
||||
Preflight prepares the selected modules, validates the supplied transcript and
|
||||
references, probes output and applicable cache access, and runs applicable native
|
||||
provider reachability, authentication, and structured-generation checks. Shared
|
||||
backend/profile targets reuse the corresponding probes. It does not execute the
|
||||
extraction pipeline or publish domain artifacts.
|
||||
|
||||
This is an explicit online operation that can incur inference charges. Ordinary
|
||||
run does not implicitly perform these probes; `pipeline validate` remains offline
|
||||
and does not read transcript or reference files. Preflight can create destination
|
||||
directories and temporary access files, and requested debug capture is retained.
|
||||
Cache access problems warn rather than failing readiness.
|
||||
|
||||
Subprocess callers can request JSON or YAML assessments. Check process status as
|
||||
well as `ready`: capture or report delivery can fail independently of readiness.
|
||||
A successful assessment applies to the supplied input, not a later transcript.
|
||||
See the [preflight CLI contract](../cli.md#preflight),
|
||||
[operational lifecycle](../operations.md#preflight-lifecycle), and
|
||||
[subprocess guide](../consumers/subprocess.md).
|
||||
|
||||
## Reference Handling And Reliability
|
||||
|
||||
- Shared schemas are bundled for offline validation. Invalid documents, duplicate
|
||||
glossary entry IDs, missing selected collections, and spell-recognition
|
||||
collisions fail during preparation, before model execution or cache reuse.
|
||||
- All ten D&D extractors and the scene chunker prepare fixed reference context
|
||||
during construction rather than reparsing it for each chunk. Model-facing
|
||||
projections omit opaque roster/entry IDs, provenance, and unrelated extensions.
|
||||
References remain contextual material, not transcript evidence.
|
||||
- Spell recognition retains the embedded D&D 5e 2014 SRD vocabulary, augments it
|
||||
with selected names and aliases, and preserves embedded canonical display names.
|
||||
Conflicting recognition keys remain errors.
|
||||
- Run and preflight share invocation and source preparation. Preflight target
|
||||
associations are built in linear time; disabled capture avoids unnecessary
|
||||
evidence setup. Cancellation and capture failures remain visible independently
|
||||
of completed readiness checks, and early capture excludes raw runtime parameters.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/eric/notarius/src/tag/v0.10.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/eric/notarius/src/tag/v0.10.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/eric/notarius/src/tag/v0.10.0/docs/oss/attribution.md)
|
||||
127
docs/roadmap/narratio-feature-request.md
Normal file
127
docs/roadmap/narratio-feature-request.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# Feature request: pipeline-aware preflight for Narratio
|
||||
|
||||
This is the original consumer request, retained as context for the completed
|
||||
preflight work. The current [CLI contract](../cli.md#preflight) and
|
||||
[subprocess guide](../consumers/subprocess.md#prepare-and-run) describe the
|
||||
implemented behavior, including native capability handling and the simplified
|
||||
readiness report.
|
||||
|
||||
## Purpose
|
||||
|
||||
Provide `notarius preflight` to check whether a selected invocation is ready to
|
||||
begin, as far as can reasonably be determined without executing extraction.
|
||||
This document requests external API and behavior only.
|
||||
|
||||
Narratio orchestrates pipelines that can take hours. It needs to catch invalid
|
||||
configuration, unavailable inputs, and provider-access failures before beginning
|
||||
expensive processing. Notarius should own readiness for its configured pipeline,
|
||||
including which provider targets need checking.
|
||||
|
||||
The existing `pipeline validate` and `promptkit test all` commands are useful
|
||||
building blocks from a caller's perspective. Together they offer a reasonable
|
||||
limited check, but require the caller to select smoke-test profiles and interpret
|
||||
their observations. Pipeline validation also cannot receive the execution's CLI
|
||||
reference bindings. See the current [CLI contract](../cli.md) and
|
||||
[subprocess guide](../consumers/subprocess.md).
|
||||
|
||||
## Requested command
|
||||
|
||||
```text
|
||||
notarius preflight PIPELINE_ID --input-file PATH [the same flags as run]
|
||||
```
|
||||
|
||||
A caller should be able to replace `run` with `preflight` in an invocation without
|
||||
translating its arguments. Accept the same configuration selection and overrides,
|
||||
input file, lane selection, reference bindings and unbindings, LLM selections and
|
||||
execution overrides, output/cache/debug controls, and native reporting options.
|
||||
Retain the same defaults, precedence, path interpretation, and distinction between
|
||||
omitted and explicitly supplied values.
|
||||
|
||||
For example, this proposed invocation checks a transcript and the actual external
|
||||
references that will be supplied to extraction:
|
||||
|
||||
```sh
|
||||
notarius preflight dnd-session \
|
||||
--config /data/notarius.yml \
|
||||
--input-file /data/transcript.json \
|
||||
--reference party=/data/party.yml \
|
||||
--reference glossary=/data/campaign-glossary.yml \
|
||||
--output-dir /data/extraction \
|
||||
--format json
|
||||
```
|
||||
|
||||
Preflight-specific effects of accepted execution flags must be documented. For
|
||||
example, `--cache refresh` must not cause preflight to execute extraction or
|
||||
replace accepted extraction results.
|
||||
|
||||
## Readiness checks
|
||||
|
||||
The command should:
|
||||
|
||||
- Validate the selected configuration, pipeline, modules, prompts, and known
|
||||
dependencies for the intended execution, including the selected lanes.
|
||||
- Apply the supplied reference selectors with execution semantics, including
|
||||
binding precedence and explicit unbinding. Read and validate required external
|
||||
references and the supplied transcript against their input contracts.
|
||||
- Check generated dependencies that can be established before execution without
|
||||
requiring same-run intermediate artifacts to exist already.
|
||||
- Determine and check the relevant provider targets for the selected work,
|
||||
including applicable extraction, normalization, correction, and validator
|
||||
targets. Account for configured selections and invocation overrides without
|
||||
requiring callers to supply a duplicate list of profiles to test.
|
||||
- Check provider reachability, authentication, and required inference capabilities
|
||||
through appropriate native diagnostics, including structured output where
|
||||
needed. Notarius owns which observations establish readiness for its pipeline.
|
||||
- Check the selected destinations as far as practical before execution, exposing
|
||||
configuration or access problems that would prevent the intended work.
|
||||
|
||||
Preserve the distinction between an actual failure, an unsupported diagnostic,
|
||||
known inapplicability, and an unknown observation. An unsupported optional
|
||||
authentication probe need not prevent readiness when other applicable checks
|
||||
establish the access required for execution. Disclose targets or requirements
|
||||
whose readiness cannot be established before extraction; do not silently report
|
||||
them as checked.
|
||||
|
||||
## Outcomes and reports
|
||||
|
||||
Return a domain readiness outcome using native CommandKit reporting and outcome
|
||||
semantics. A failed required check, or inability to complete a required readiness
|
||||
check, must produce an unsuccessful outcome with an actionable explanation.
|
||||
Success means the required readiness checks passed, with any warnings and coverage
|
||||
limits disclosed. It does not merely mean diagnostic commands completed.
|
||||
|
||||
Support native text, YAML, and JSON presentation. Provide a documented
|
||||
machine-readable report identifying the selected pipeline, overall readiness,
|
||||
checks performed, failures, warnings, and incomplete coverage. Findings should
|
||||
identify the relevant input, binding, or provider target when applicable. Callers
|
||||
should not need to parse diagnostic prose or apply their own provider-specific
|
||||
rules to obtain the readiness decision.
|
||||
|
||||
Preserve native configuration errors, cancellation, reporting failures, and
|
||||
credential-handling conventions. A canceled or otherwise incomplete required
|
||||
check must not be presented as successful readiness.
|
||||
|
||||
## Effects and limits
|
||||
|
||||
Preflight may read inputs, probe or create required directories, contact
|
||||
providers, incur smoke-test inference costs, and write requested diagnostics.
|
||||
Document those effects. It must not publish extraction artifacts or populate,
|
||||
refresh, or invalidate accepted extraction results. Existing cached acceptance
|
||||
must not substitute for current provider-readiness checks.
|
||||
|
||||
Readiness does not guarantee later model responses, semantic acceptance, continued
|
||||
provider availability, or feasibility of every data-dependent operation. Report
|
||||
these limits without requiring a full extraction as proof of readiness.
|
||||
|
||||
## Narratio usage
|
||||
|
||||
Narratio will supply its real prepared reference files and the same configuration,
|
||||
credentials, selections, and destinations intended for execution. Its early
|
||||
preflight occurs before the final trimmed transcript exists, so it will supply
|
||||
a known-good synthetic transcript through the ordinary `--input-file` interface.
|
||||
No Narratio-specific fixture mode is requested.
|
||||
|
||||
This checks the supplied fixture, configuration, references, and provider access;
|
||||
it does not establish compatibility of a future transcript. Execution must still
|
||||
validate its real inputs. Requiring the same input interface for preflight and
|
||||
run allows other callers to check their actual transcript when already available.
|
||||
182
docs/roadmap/narratio-shared-schemas-feature-request.md
Normal file
182
docs/roadmap/narratio-shared-schemas-feature-request.md
Normal file
@@ -0,0 +1,182 @@
|
||||
# Feature request: adopt shared domain schemas for Narratio inputs
|
||||
|
||||
## Requested outcome
|
||||
|
||||
Adopt the Maximum Direct shared domain contracts so operators can author one set
|
||||
of inputs for Narratio, Notarius, Audita, and relevant Scriptorium prompts.
|
||||
In particular, one authored spell glossary should supply both transcript correction
|
||||
and Notarius spell recognition without a second operator-maintained spell overlay.
|
||||
|
||||
This is a consumer feature request describing desired external behavior and
|
||||
ownership. Notarius should prepare its own roadmap and implementation plan. It
|
||||
does not prescribe packages, parsing libraries, internal projections, or extraction
|
||||
strategy. The existing [Narratio preflight request](narratio-feature-request.md)
|
||||
remains separate; this request extends the inputs checked by that native interface.
|
||||
|
||||
## Shared contracts and distribution
|
||||
|
||||
The independent [schemas repository](https://forge.maximumdirect.net/eric/schemas)
|
||||
is available locally at `../schemas`. Publication of the initial CalVer distribution
|
||||
`2026.11.0` is in progress at the time of this request. Confirm the published tag
|
||||
and its inventory before selecting the adoption baseline; this document does not
|
||||
assert publication has completed.
|
||||
|
||||
The proposed baseline contains these independently versioned contracts:
|
||||
|
||||
| Schema | Version | Document identifier | Authoritative contract |
|
||||
| --- | --- | --- | --- |
|
||||
| General glossary | `0.1.0` | `maximumdirect.glossary.v1` | [Schema](https://schemas.maximumdirect.net/glossary/v0.1.0/schema.json), [semantics](https://schemas.maximumdirect.net/glossary/v0.1.0/semantics.md) |
|
||||
| RPG party | `0.1.0` | `maximumdirect.rpg.party.v1` | [Schema](https://schemas.maximumdirect.net/rpg/party/v0.1.0/schema.json), [semantics](https://schemas.maximumdirect.net/rpg/party/v0.1.0/semantics.md) |
|
||||
| RPG campaign | `0.1.0` | `maximumdirect.rpg.campaign.v1` | [Schema](https://schemas.maximumdirect.net/rpg/campaign/v0.1.0/schema.json), [semantics](https://schemas.maximumdirect.net/rpg/campaign/v0.1.0/semantics.md) |
|
||||
|
||||
Repository releases use CalVer; each schema uses independent SemVer. A document
|
||||
identifier denotes a contract generation, not an exact schema version or repository
|
||||
date. Canonical hosting serves `main`, so URL availability alone does not establish
|
||||
release status. Select exact versions from a published tag's `catalog.json` and
|
||||
record the source distribution. Unrelated schema updates need no Notarius upgrade.
|
||||
|
||||
Contracts include their semantic documentation, not just JSON Schema. Pin the
|
||||
adopted definitions and make ordinary validation work offline. No import of the
|
||||
schema repository's internal Go harness, runtime network resolution, or dependency
|
||||
on a mutable latest inventory is requested. The repository publishes its
|
||||
[validation profile](https://forge.maximumdirect.net/eric/schemas/src/branch/main/docs/validation.md)
|
||||
and [compatibility guidance](https://forge.maximumdirect.net/eric/schemas/src/branch/main/docs/compatibility.md);
|
||||
use the selected release's copies when establishing supported behavior.
|
||||
|
||||
## Operator workflow and caller boundary
|
||||
|
||||
Operators maintain a roster, shared campaign context where useful, and glossary
|
||||
vocabulary. Narratio prepares durable shared inputs, including four glossary
|
||||
collections: `party`, `campaign`, `setting`, and `spells`. It derives party
|
||||
vocabulary from the roster; operators need not maintain both independently.
|
||||
These collection names are Narratio's domain convention, not an enumeration in
|
||||
the general glossary schema.
|
||||
|
||||
Notarius should consume whichever collections its selected tasks need. Do not
|
||||
require all four merely for uniformity. The roster and a derived party glossary
|
||||
remain different views: the roster also carries player relationships and optional
|
||||
character attributes. Shared RPG campaign context is distinct from Narratio's
|
||||
operational `campaign.yml` configuration.
|
||||
|
||||
Prefer accepting authored YAML as well as equivalent JSON. If a Notarius input
|
||||
requires JSON, Narratio can serialize the same shared document to JSON without
|
||||
changing its contract. Narratio can save selected or combined glossary views when
|
||||
needed, but should not reconstruct Notarius-specific spell records or reproduce
|
||||
its recognition policy. Task-specific interpretation belongs to Notarius.
|
||||
|
||||
Prefer the established [reference binding interface](../config.md#references-and-ordered-handoffs)
|
||||
where it fits. Document which selectors accept which documents and how callers
|
||||
select collections when a file contains several. Exact slot names, selection
|
||||
syntax, and pipeline exposure are for Notarius to design; this request introduces
|
||||
no mandatory new CLI spelling. Preflight and execution must accept the same
|
||||
bindings and interpret them consistently.
|
||||
|
||||
## Glossary and spell recognition
|
||||
|
||||
The shared glossary uses a `schema_version` and `collections` envelope. Entries
|
||||
provide stable collection-scoped IDs, canonical names, categories, optional
|
||||
aliases and descriptions, and extensible domain information. The authoritative
|
||||
contract defines omission, null, and empty values. Notarius should honor those
|
||||
shapes rather than require the current spell overlay's different representation.
|
||||
|
||||
The former [spell-catalog overlay](https://forge.maximumdirect.net/eric/notarius/src/commit/bff0fb44e86e024f1cb5f0987b2ba583c225a53b/docs/integrations/dnd-spell-catalog-overlays.md)
|
||||
requires a separate schema marker and catalog structure, rejects unknown fields,
|
||||
and couples input to catalog/ruleset requirements. Replace that operator-facing
|
||||
format with shared glossary consumption. The operator should be able to supply
|
||||
the same spell document to Audita and Notarius, with serialization conversion
|
||||
as the only format change if necessary.
|
||||
|
||||
Notarius continues to own its embedded vocabulary, normalization, canonical-name
|
||||
selection, source precedence, collision handling, and extraction strategy. Document
|
||||
how the shared input interacts with the embedded catalog. Shared names, aliases,
|
||||
and provenance are reference context; they are not transcript evidence, and
|
||||
schema adoption must not turn reference-only information into observed events.
|
||||
|
||||
Collection provenance is optional source metadata. In the current glossary
|
||||
contract, `ruleset` is not a standard provenance field. If recognition needs game
|
||||
system/ruleset selection, Notarius should define whether that comes from its
|
||||
configuration, supported domain extensions, or another explicit domain input.
|
||||
Do not silently infer it from a Narratio catalog selector or require another
|
||||
copy of the spell vocabulary. Clearly distinguish task-specific requirements
|
||||
from general shared-schema validity.
|
||||
|
||||
## Party and campaign use
|
||||
|
||||
Review the maintained D&D pipeline's party, players, and campaign-context inputs
|
||||
against the shared RPG contracts. Where structured roster information is useful,
|
||||
consume the shared party document, including its character IDs, plural `aliases`,
|
||||
player relationships, and optional attributes. Avoid requiring operators to author
|
||||
a second roster or player list containing the same facts.
|
||||
|
||||
The shared campaign document is available for tasks needing its context. Adoption
|
||||
should not require a new campaign reference slot or a separate campaign file
|
||||
without a demonstrated use. Existing text references need no new typed interface
|
||||
solely because a schema now exists. Notarius should identify which contracts it
|
||||
interprets structurally and which inputs remain ordinary text context.
|
||||
|
||||
## Validation, readiness, and extensions
|
||||
|
||||
For structured shared inputs, enforce the adopted structural and semantic
|
||||
contracts, including glossary entry-ID uniqueness within each collection.
|
||||
Accept permitted extensions without treating them as supported features merely
|
||||
because they are present. Preserve them when forwarding a shared document;
|
||||
task-specific views may omit irrelevant fields.
|
||||
|
||||
Task instructions remain in consumer configuration. An extension named
|
||||
`instruction` must not acquire instruction semantics. ConfigKit retains ownership
|
||||
of configuration composition; the shared schemas describe completed domain
|
||||
documents, not another import or merge system.
|
||||
|
||||
The existing [native preflight](../consumers/subprocess.md#prepare-and-run) should
|
||||
check the supplied references with the same input and task requirements as run,
|
||||
catching malformed documents, incompatible contracts, unavailable selected
|
||||
collections, and determinable recognition conflicts before expensive extraction.
|
||||
Execution still checks its real inputs. Narratio's early preflight may use a
|
||||
synthetic transcript with the actual prepared references; that does not establish
|
||||
readiness of a future transcript.
|
||||
|
||||
Use native outcomes and actionable diagnostics identifying the relevant reference,
|
||||
collection, or field where practical. No new error taxonomy or report protocol is
|
||||
requested. A schema-valid input may still be unsuitable for a selected task;
|
||||
explain that task requirement without redefining the shared contract.
|
||||
|
||||
## Decisions for Notarius's roadmap
|
||||
|
||||
- Which tasks use which collections, and how callers bind files and select
|
||||
collections through the public interface.
|
||||
- How shared spell vocabulary interacts with embedded vocabulary, aliases,
|
||||
ambiguity, and source precedence; which provenance or ruleset information is
|
||||
required, if any, and how omission is handled.
|
||||
- Which party/player/context uses benefit from shared structured inputs, and
|
||||
whether the campaign contract has a concrete role in this adoption.
|
||||
- Accepted serializations, pinned schema versions, and documented task requirements
|
||||
beyond shared conformance.
|
||||
- The release containing the cutover and the operator migration guidance.
|
||||
|
||||
Recommend a direct cutover with migration documentation, without legacy-format
|
||||
conversions, compatibility shims, or a requirement to maintain two input formats.
|
||||
No change to Notarius's output artifact contracts is requested solely to adopt
|
||||
these input schemas. Consumer-side schema gaps should be raised explicitly rather
|
||||
than silently creating another competing format.
|
||||
|
||||
## Observable acceptance
|
||||
|
||||
The resulting roadmap should establish that:
|
||||
|
||||
1. One synthetic spell glossary, including canonical names and aliases, can serve
|
||||
Audita and Notarius without separately authored spell-overlay data. This is a
|
||||
target interoperability outcome; neither application is declared compatible
|
||||
merely by publication of the schemas.
|
||||
2. Selected collections are used predictably; unrelated collections need not be
|
||||
supplied, and callers can determine which input each task consumes.
|
||||
3. Party-derived context can be obtained without a duplicate operator-maintained
|
||||
roster/player list wherever that context is required.
|
||||
4. Supported extensions and null/omitted aliases follow the shared contract;
|
||||
additional Notarius task requirements and conflicts have clear diagnostics.
|
||||
5. Preflight rejects determinable invalid reference inputs consistently with run,
|
||||
and valid shared references reach the intended extraction tasks.
|
||||
6. Ordinary input validation works offline, and documentation names exact supported
|
||||
schema versions, bindings, and migration steps.
|
||||
|
||||
Notarius owns its roadmap, validation approach, and implementation plan. Narratio
|
||||
will adopt the resulting released public interfaces in its subsequent work.
|
||||
@@ -1,8 +0,0 @@
|
||||
Ravenfall watchtower: a ruined watchtower near the party's current route.
|
||||
Mira Thorn: the watchtower's keeper.
|
||||
Elder Rowan: a missing local scholar.
|
||||
Kesh: a goblin captain leading raiders.
|
||||
Moonblade: a blade found in the watchtower's hidden cache.
|
||||
Cure Wounds: a healing spell.
|
||||
Shield: a defensive reaction spell.
|
||||
Aegis of Emberfall: a campaign spell recorded in the supplied catalog overlay.
|
||||
34
examples/dnd-complete/glossary.yml
Normal file
34
examples/dnd-complete/glossary.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
campaign:
|
||||
entries:
|
||||
- id: mira
|
||||
name: Mira Thorn
|
||||
category: person
|
||||
description: The watchtower's keeper.
|
||||
- id: rowan
|
||||
name: Elder Rowan
|
||||
category: person
|
||||
description: A missing local scholar.
|
||||
- id: kesh
|
||||
name: Kesh
|
||||
category: person
|
||||
description: A goblin captain leading raiders.
|
||||
- id: moonblade
|
||||
name: Moonblade
|
||||
category: item
|
||||
description: A blade found in the watchtower's hidden cache.
|
||||
setting:
|
||||
entries:
|
||||
- id: ravenfall
|
||||
name: Ravenfall watchtower
|
||||
category: place
|
||||
description: A ruined watchtower near the party's current route.
|
||||
spells:
|
||||
provenance:
|
||||
title: Notarius example campaign spell names
|
||||
entries:
|
||||
- id: aegis
|
||||
name: Aegis of Emberfall
|
||||
category: spell
|
||||
aliases: [Emberfall Aegis]
|
||||
@@ -1,2 +0,0 @@
|
||||
Aria: party cleric and recurring healer.
|
||||
Borin: fighter ally.
|
||||
18
examples/dnd-complete/party.yml
Normal file
18
examples/dnd-complete/party.yml
Normal file
@@ -0,0 +1,18 @@
|
||||
schema_version: maximumdirect.rpg.party.v1
|
||||
characters:
|
||||
aria:
|
||||
character:
|
||||
name: Aria
|
||||
aliases: [Brightmantle]
|
||||
classes:
|
||||
- name: Cleric
|
||||
level: 3
|
||||
player:
|
||||
name: Alice
|
||||
borin:
|
||||
character:
|
||||
name: Borin
|
||||
classes:
|
||||
- name: Fighter
|
||||
player:
|
||||
name: Ben
|
||||
@@ -15,9 +15,9 @@ pipelines:
|
||||
# Stable campaign context is shared by every module that accepts these slots.
|
||||
references:
|
||||
party:
|
||||
path: ../party.txt
|
||||
path: ../party.yml
|
||||
glossary:
|
||||
path: ../glossary.txt
|
||||
path: ../glossary.yml
|
||||
chunk:
|
||||
module: dnd/scenes
|
||||
output:
|
||||
@@ -71,7 +71,7 @@ pipelines:
|
||||
module: dnd/spells
|
||||
references:
|
||||
spell_catalog:
|
||||
path: ../spell-catalog.json
|
||||
path: ../glossary.yml
|
||||
merge:
|
||||
module: appendorder
|
||||
# Stage-local file references are intentionally bound at each stage.
|
||||
@@ -79,7 +79,7 @@ pipelines:
|
||||
module: dnd/spells
|
||||
references:
|
||||
spell_catalog:
|
||||
path: ../spell-catalog.json
|
||||
path: ../glossary.yml
|
||||
combat-turns:
|
||||
extract:
|
||||
module: dnd/combat-turns
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"schema_version": "notarius.dnd.spell-catalog-overlay.v1",
|
||||
"catalogs": [
|
||||
{
|
||||
"id": "notarius.example-campaign",
|
||||
"ruleset": "dnd-5e-2014",
|
||||
"source": {
|
||||
"title": "Notarius example campaign spell names",
|
||||
"version": "1",
|
||||
"url": "",
|
||||
"license": ""
|
||||
},
|
||||
"spells": [
|
||||
{
|
||||
"name": "Aegis of Emberfall",
|
||||
"aliases": ["Emberfall Aegis"]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -42,8 +42,9 @@ func NewApplication(version string, options Options) (*commandkit.App, error) {
|
||||
definitions = ckprompt.WithNamespaces(definitions, promptkit.Namespaces{})
|
||||
declarations := []commandkit.Declaration{
|
||||
commandkit.Completion("notarius"),
|
||||
pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return effectiveCatalog(options) }, pipelineRunCommand(version, newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) }, options)),
|
||||
pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return effectiveCatalog(options) }, pipelineRunCommand(version, newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) }, options), pipelinePreflightCommand(version, newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) }, options)),
|
||||
commandkit.Alias("run", "pipeline run"),
|
||||
commandkit.Alias("preflight", "pipeline preflight"),
|
||||
ckconfig.Command(ckconfig.Suite[struct{}, *nativeLoaders]{
|
||||
NewState: newState,
|
||||
CheckInput: func(_ string, selection ckconfig.Selection, _ struct{}) error {
|
||||
|
||||
86
internal/cli/context_capture_test.go
Normal file
86
internal/cli/context_capture_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestInvocationCaptureOmitsMarkedRuntimeParameters(t *testing.T) {
|
||||
for _, command := range []string{"run", "preflight"} {
|
||||
for _, earlyFailure := range []bool{false, true} {
|
||||
name := command + "/success"
|
||||
if earlyFailure {
|
||||
name = command + "/early-failure"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, configPath, inputPath, _ := runFixture(t, probe, func(configuration string) string {
|
||||
return strings.Replace(configuration, " prompts:", " extra_params: {token: configured-placeholder}\n prompts:", 1)
|
||||
})
|
||||
if earlyFailure {
|
||||
inputPath += "-missing"
|
||||
}
|
||||
calls := 0
|
||||
client := captureClient(func(ctx context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
calls++
|
||||
if request.Target.ExtraParams["token"] != "runtime-private-placeholder" || request.Target.ExtraParams["caption"] != "ordinary-runtime-caption" {
|
||||
t.Fatal("capture mutated execution parameters")
|
||||
}
|
||||
if productionSchemaHasProperty(request, "status") {
|
||||
return &promptkit.GenerateResponse{Content: `{"status":"ok"}`}, nil
|
||||
}
|
||||
return probe.Generate(ctx, request)
|
||||
})
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client, RunIDGenerator: func(time.Time) (string, error) { return "capture", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := t.TempDir()
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{command, "demo", "--config", configPath, "--input-file", inputPath, "--llm-profile", "chosen", "--llm-extra-params", `{"token":"runtime-private-placeholder","caption":"ordinary-runtime-caption"}`, "--cache", "bypass", "--debug", "--debug-dir", root, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if (outcome.Status != 0) != earlyFailure || earlyFailure && calls != 0 {
|
||||
t.Fatalf("outcome=%+v calls=%d stderr=%s", outcome, calls, stderr.String())
|
||||
}
|
||||
if !earlyFailure {
|
||||
var report map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || calls == 0 {
|
||||
t.Fatalf("report error=%v calls=%d", err, calls)
|
||||
}
|
||||
}
|
||||
ordinaryRetained := false
|
||||
err = filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !entry.Type().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bytes.Contains(content, []byte("runtime-private-placeholder")) {
|
||||
t.Errorf("marked runtime parameter retained in %s", path)
|
||||
}
|
||||
ordinaryRetained = ordinaryRetained || bytes.Contains(content, []byte("ordinary-runtime-caption"))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !earlyFailure && !ordinaryRetained {
|
||||
t.Fatal("ordinary effective parameters were lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
53
internal/cli/destination_probe.go
Normal file
53
internal/cli/destination_probe.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
)
|
||||
|
||||
// probeDestination checks practical write access without publishing an artifact.
|
||||
func probeDestination(root string, mode os.FileMode) error {
|
||||
if err := os.MkdirAll(root, mode); err != nil {
|
||||
return fmt.Errorf("create destination %q: %w", root, err)
|
||||
}
|
||||
file, err := os.CreateTemp(root, ".notarius-probe-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create access probe in %q: %w", root, err)
|
||||
}
|
||||
_, writeErr := file.Write([]byte("probe"))
|
||||
closeErr := file.Close()
|
||||
removeErr := os.Remove(file.Name())
|
||||
if err := errors.Join(writeErr, closeErr, removeErr); err != nil {
|
||||
return fmt.Errorf("access probe in %q: %w", root, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pipelineUsesCache(resolved pipeline.ResolvedPipeline) bool {
|
||||
uses := func(class contracts.ExecutionClass, controls contracts.ProducerControls) bool {
|
||||
return class == contracts.ExecutionClassLLMBacked && controls.Cache != contracts.CacheBypass
|
||||
}
|
||||
if uses(resolved.ChunkExecutionClass, resolved.ChunkControls) {
|
||||
return true
|
||||
}
|
||||
for _, step := range resolved.Steps {
|
||||
for _, lane := range step.ArtifactLanes {
|
||||
if uses(lane.ExtractExecutionClass, lane.ExtractControls) || uses(lane.MergeExecutionClass, lane.MergeControls) || uses(lane.NormalizeExecutionClass, lane.NormalizeControls) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func probePipelineDestinations(outputRoot, cacheRoot string, resolved pipeline.ResolvedPipeline) (outputErr, cacheErr error) {
|
||||
outputErr = probeDestination(outputRoot, 0o755)
|
||||
if outputErr == nil && pipelineUsesCache(resolved) {
|
||||
cacheErr = probeDestination(cacheRoot, 0o777)
|
||||
}
|
||||
return outputErr, cacheErr
|
||||
}
|
||||
70
internal/cli/destination_probe_test.go
Normal file
70
internal/cli/destination_probe_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
)
|
||||
|
||||
func TestDestinationProbesPreserveCacheAndCleanUp(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
output, cache := filepath.Join(root, "output"), filepath.Join(root, "cache")
|
||||
if err := os.Mkdir(cache, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := filepath.Join(cache, "accepted.json")
|
||||
if err := os.WriteFile(entry, []byte(`{"accepted":true}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved := pipeline.ResolvedPipeline{ChunkExecutionClass: contracts.ExecutionClassLLMBacked}
|
||||
for _, mode := range []contracts.CacheMode{contracts.CacheAuto, contracts.CacheRefresh} {
|
||||
resolved.ChunkControls.Cache = mode
|
||||
if outputErr, cacheErr := probePipelineDestinations(output, cache, resolved); outputErr != nil || cacheErr != nil {
|
||||
t.Fatalf("%s: output %v, cache %v", mode, outputErr, cacheErr)
|
||||
}
|
||||
content, err := os.ReadFile(entry)
|
||||
if err != nil || string(content) != `{"accepted":true}` {
|
||||
t.Fatalf("cache entry = %q, %v", content, err)
|
||||
}
|
||||
entries, err := os.ReadDir(cache)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatalf("cache directory = %v, %v", entries, err)
|
||||
}
|
||||
entries, err = os.ReadDir(output)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatalf("output directory = %v, %v", entries, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDestinationProbesDistinguishRequiredAndOptionalAccess(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
file := filepath.Join(root, "file")
|
||||
if err := os.WriteFile(file, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad := filepath.Join(file, "child")
|
||||
resolved := pipeline.ResolvedPipeline{ChunkExecutionClass: contracts.ExecutionClassLLMBacked, ChunkControls: contracts.ProducerControls{Cache: contracts.CacheAuto}}
|
||||
if outputErr, cacheErr := probePipelineDestinations(bad, bad, resolved); outputErr == nil || cacheErr != nil {
|
||||
t.Fatalf("output=%v cache=%v", outputErr, cacheErr)
|
||||
}
|
||||
if outputErr, cacheErr := probePipelineDestinations(filepath.Join(root, "output"), bad, resolved); outputErr != nil || cacheErr == nil {
|
||||
t.Fatalf("output=%v cache=%v", outputErr, cacheErr)
|
||||
}
|
||||
resolved.ChunkControls.Cache = contracts.CacheBypass
|
||||
if outputErr, cacheErr := probePipelineDestinations(filepath.Join(root, "output"), bad, resolved); outputErr != nil || cacheErr != nil {
|
||||
t.Fatalf("bypass: output=%v cache=%v", outputErr, cacheErr)
|
||||
}
|
||||
resolved.ChunkControls.Cache = contracts.CacheAuto
|
||||
resolved.ChunkExecutionClass = contracts.ExecutionClassDeterministic
|
||||
if outputErr, cacheErr := probePipelineDestinations(filepath.Join(root, "output"), bad, resolved); outputErr != nil || cacheErr != nil {
|
||||
t.Fatalf("deterministic: output=%v cache=%v", outputErr, cacheErr)
|
||||
}
|
||||
resolved.Steps = []pipeline.ResolvedPipelineStep{{ArtifactLanes: []pipeline.ResolvedArtifactLane{{NormalizeExecutionClass: contracts.ExecutionClassLLMBacked, NormalizeControls: contracts.ProducerControls{Cache: contracts.CacheRefresh}}}}}
|
||||
if outputErr, cacheErr := probePipelineDestinations(filepath.Join(root, "output"), bad, resolved); outputErr != nil || cacheErr == nil {
|
||||
t.Fatalf("selected model lane: output=%v cache=%v", outputErr, cacheErr)
|
||||
}
|
||||
}
|
||||
@@ -93,9 +93,9 @@ func TestMaintainedCompleteInvocationPublishesRegistryBackedEntityOccurrences(t
|
||||
code := RunWithOptions([]string{
|
||||
"run", "dnd-session", "--config", configPath,
|
||||
"--input-file", repositoryPath("examples", "dnd-complete", "transcript.json"),
|
||||
"--reference", "party=" + repositoryPath("examples", "dnd-complete", "party.txt"),
|
||||
"--reference", "glossary=" + repositoryPath("examples", "dnd-complete", "glossary.txt"),
|
||||
"--reference", "spell_catalog=" + repositoryPath("examples", "dnd-complete", "spell-catalog.json"),
|
||||
"--reference", "party=" + repositoryPath("examples", "dnd-complete", "party.yml"),
|
||||
"--reference", "glossary=" + repositoryPath("examples", "dnd-complete", "glossary.yml"),
|
||||
"--reference", "spell_catalog=" + repositoryPath("examples", "dnd-complete", "glossary.yml"),
|
||||
"--cache", "bypass", "--output-dir", outputRoot,
|
||||
"--llm-session-id", "enemy-event-session", "--format", "json",
|
||||
}, &stdout, &stderr, options)
|
||||
|
||||
@@ -106,8 +106,8 @@ func TestProductionNPCConfigurationValidatesOptionsReferencesAndPlacement(t *tes
|
||||
if err := resolve(func(profile *pipeline.PipelineProfile) {
|
||||
profile.References = pipeline.ExternalReferenceMap(map[string]string{
|
||||
"players": "players.txt",
|
||||
"party": "party.txt",
|
||||
"glossary": "glossary.txt",
|
||||
"party": "party.yml",
|
||||
"glossary": "glossary.yml",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("optional NPC references error = %v, want resolution success", err)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/config"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/integrations/domainrefs"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
locationoccurrenceextract "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/extract/locationoccurrences"
|
||||
locationextract "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/extract/locationregistry"
|
||||
@@ -123,6 +124,25 @@ func TestMaintainedExamplesResolveComposition(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintainedSharedReferencesConform(t *testing.T) {
|
||||
for _, item := range []struct {
|
||||
name string
|
||||
validate func(map[string]any) error
|
||||
}{
|
||||
{"party.yml", domainrefs.ValidateParty},
|
||||
{"glossary.yml", domainrefs.ValidateGlossary},
|
||||
} {
|
||||
content := readRepositoryFile(t, "examples", "dnd-complete", item.name)
|
||||
doc, err := domainrefs.Load(item.name, "application/yaml", content)
|
||||
if err == nil {
|
||||
err = item.validate(doc)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", item.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintainedExampleDevelopmentInheritsComposition(t *testing.T) {
|
||||
path := repositoryPath("examples", "dnd-complete", "config.yml")
|
||||
cfg := loadMaintainedExample(t, path)
|
||||
@@ -427,10 +447,10 @@ func TestCompleteDNDSharedCLIReferencesExpandAcrossCompatibleTargets(t *testing.
|
||||
cfg := loadMaintainedExample(t, repositoryPath("examples", "dnd-complete", "config.yml"))
|
||||
catalog := catalogFromRegistries(productionTestComponents(t).registries)
|
||||
sources := map[string]string{
|
||||
"party": "/references/party.txt",
|
||||
"party": "/references/party.yml",
|
||||
"players": "/references/players.txt",
|
||||
"glossary": "/references/glossary.txt",
|
||||
"spell_catalog": "/references/spells.json",
|
||||
"glossary": "/references/glossary.yml",
|
||||
"spell_catalog": "/references/glossary.yml",
|
||||
}
|
||||
requests := make([]cliReferenceRequest, 0, len(sources))
|
||||
for _, slot := range []string{"party", "players", "glossary", "spell_catalog"} {
|
||||
|
||||
134
internal/cli/pipeline_invocation.go
Normal file
134
internal/cli/pipeline_invocation.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/config"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/preflight"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type loadedPipelineInvocation struct {
|
||||
state *nativeLoaders
|
||||
selection ckconfig.Selection
|
||||
result *configkit.Result[config.Document]
|
||||
loaded *config.LoadedConfig
|
||||
config config.Config
|
||||
}
|
||||
|
||||
func loadPipelineInvocation(ctx context.Context, invocation commandkit.Invocation, input pipelineRunInput, state *nativeLoaders) (loadedPipelineInvocation, *commandkit.Outcome) {
|
||||
selection := captureSelection(input.Selection)
|
||||
if input.OutputDirectory.Set {
|
||||
selection.Overrides = append(selection.Overrides, configkit.Override{Path: configkit.Keys("output", "directory"), Value: input.OutputDirectory.Value, Flag: "--output-dir"})
|
||||
}
|
||||
result, err := state.application(ctx, selection)
|
||||
if err != nil {
|
||||
outcome := pipelineConfigurationFailure(err)
|
||||
return loadedPipelineInvocation{}, &outcome
|
||||
}
|
||||
diagnostics, _ := ckconfig.AdaptDiagnostics("Configuration\n", result.Sources(), result.Diagnostics())
|
||||
for _, diagnostic := range diagnostics {
|
||||
if diagnostic.Severity == commandkit.SeverityWarning {
|
||||
_ = invocation.Reporter().AtEnd().Warn("", diagnostic.Write)
|
||||
} else {
|
||||
_ = invocation.Reporter().AtEnd().Info("", diagnostic.Write)
|
||||
}
|
||||
}
|
||||
loaded, err := config.FromResult(result)
|
||||
if err != nil {
|
||||
outcome := pipelineInvalidConfiguration(err)
|
||||
return loadedPipelineInvocation{}, &outcome
|
||||
}
|
||||
return loadedPipelineInvocation{state: state, selection: selection, result: result, loaded: loaded, config: loaded.RuntimeConfig()}, nil
|
||||
}
|
||||
|
||||
type selectedPipelineInvocation struct {
|
||||
registries pipeline.Registries
|
||||
catalog pipeline.ModuleCatalog
|
||||
effective config.EffectiveConfig
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
|
||||
func selectPipelineInvocation(ctx context.Context, loaded loadedPipelineInvocation, input pipelineRunInput, modules func() (pipeline.Registries, error)) (selectedPipelineInvocation, *commandkit.Outcome) {
|
||||
registries, err := modules()
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(err.Error()).WithCause(err)
|
||||
return selectedPipelineInvocation{}, &outcome
|
||||
}
|
||||
catalog := catalogFromRegistries(registries)
|
||||
binds, unbinds, err := resolveCLIReferenceRequests(loaded.config, input.PipelineID, input.Lanes.Value, catalog, input.References.Value, input.Unbinds.Value)
|
||||
if err != nil {
|
||||
outcome := pipelineInvalidConfiguration(err)
|
||||
return selectedPipelineInvocation{}, &outcome
|
||||
}
|
||||
resolve := config.ResolveInput{PipelineID: input.PipelineID, Only: input.Lanes.Value, Catalog: catalog, ReferenceOverrides: binds, ReferenceUnbinds: unbinds}
|
||||
if input.Cache.Set {
|
||||
resolve.CacheOverride = &input.Cache.Value
|
||||
}
|
||||
if input.Overrides.Resources.Profile.Set {
|
||||
resolve.LLMProfileOverride = &input.Overrides.Resources.Profile.Value
|
||||
}
|
||||
effective, err := loaded.config.Resolve(resolve)
|
||||
if err != nil {
|
||||
outcome := pipelineInvalidConfiguration(err)
|
||||
return selectedPipelineInvocation{}, &outcome
|
||||
}
|
||||
var engine *promptkit.Engine
|
||||
if preflight.RequiresEngine(effective.ResolvedPipeline) {
|
||||
engine, err = loaded.state.engine(ctx, loaded.selection)
|
||||
if err != nil {
|
||||
outcome := pipelineConfigurationFailure(err)
|
||||
return selectedPipelineInvocation{}, &outcome
|
||||
}
|
||||
}
|
||||
if err := preflight.Validate(ctx, effective.ResolvedPipeline, catalog, engine); err != nil {
|
||||
outcome := pipelineResourceFailure(err)
|
||||
return selectedPipelineInvocation{}, &outcome
|
||||
}
|
||||
return selectedPipelineInvocation{registries: registries, catalog: catalog, effective: effective, engine: engine}, nil
|
||||
}
|
||||
|
||||
type preparedPipelineInvocation struct {
|
||||
resolved pipeline.ResolvedPipeline
|
||||
prepared *pipeline.PreparedPipeline
|
||||
raw []byte
|
||||
sessionID string
|
||||
diagnostics []contracts.ProducerDiagnostic
|
||||
failureTarget string
|
||||
}
|
||||
|
||||
func preparePipelineInvocation(loaded loadedPipelineInvocation, selected selectedPipelineInvocation, input pipelineRunInput) (preparedPipelineInvocation, *commandkit.Outcome) {
|
||||
workingDirectory, err := os.Getwd()
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(err.Error()).WithCause(err)
|
||||
return preparedPipelineInvocation{failureTarget: "preparation"}, &outcome
|
||||
}
|
||||
materialized, diagnostics, err := pipeline.MaterializeReferences(selected.effective.ResolvedPipeline, selected.catalog, pipeline.ReferenceMaterializationOptions{ConfigPath: loaded.loaded.MainSourcePath(), WorkingDir: workingDirectory})
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(err.Error()).WithCause(err)
|
||||
return preparedPipelineInvocation{failureTarget: "references"}, &outcome
|
||||
}
|
||||
prepared, err := pipeline.Prepare(materialized, selected.registries, pipeline.ModuleDependencies{Engine: selected.engine})
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(err.Error()).WithCause(err)
|
||||
return preparedPipelineInvocation{resolved: materialized, diagnostics: diagnostics, failureTarget: "modules"}, &outcome
|
||||
}
|
||||
raw, err := os.ReadFile(input.InputFile.Value)
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(fmt.Sprintf("Read input %q: %v", input.InputFile.Value, err)).WithCause(err)
|
||||
return preparedPipelineInvocation{resolved: materialized, diagnostics: diagnostics, failureTarget: "input"}, &outcome
|
||||
}
|
||||
sessionID, err := runSessionID(input.Overrides.Resources.SessionID, materialized.Input.Module, raw)
|
||||
if err != nil {
|
||||
outcome := commandkit.Failure(err.Error()).WithCause(err)
|
||||
return preparedPipelineInvocation{resolved: materialized, diagnostics: diagnostics, failureTarget: "input"}, &outcome
|
||||
}
|
||||
return preparedPipelineInvocation{resolved: materialized, prepared: prepared, raw: raw, sessionID: sessionID, diagnostics: diagnostics}, nil
|
||||
}
|
||||
222
internal/cli/pipeline_preflight.go
Normal file
222
internal/cli/pipeline_preflight.go
Normal file
@@ -0,0 +1,222 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"text/template"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
frameworkdebug "gitea.maximumdirect.net/eric/notarius/internal/framework/debug"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/preflight"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
type preflightScope struct {
|
||||
Pipeline string `json:"pipeline,omitempty" yaml:"pipeline,omitempty"`
|
||||
Path string `json:"path,omitempty" yaml:"path,omitempty"`
|
||||
Reference string `json:"reference,omitempty" yaml:"reference,omitempty"`
|
||||
Profile string `json:"profile,omitempty" yaml:"profile,omitempty"`
|
||||
Backend string `json:"backend,omitempty" yaml:"backend,omitempty"`
|
||||
Bindings []preflight.BindingScope `json:"bindings,omitempty" yaml:"bindings,omitempty"`
|
||||
}
|
||||
|
||||
type preflightCheck struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Scope preflightScope `json:"scope" yaml:"scope"`
|
||||
Result string `json:"result" yaml:"result"`
|
||||
Message string `json:"message" yaml:"message"`
|
||||
Code string `json:"code,omitempty" yaml:"code,omitempty"`
|
||||
}
|
||||
|
||||
type preflightReport struct {
|
||||
Pipeline string `json:"pipeline" yaml:"pipeline"`
|
||||
Ready bool `json:"ready" yaml:"ready"`
|
||||
Checks []preflightCheck `json:"checks" yaml:"checks"`
|
||||
DebugDirectory string `json:"debug_directory,omitempty" yaml:"debug_directory,omitempty"`
|
||||
}
|
||||
|
||||
var preflightTemplate = template.Must(commandkit.ParseTextTemplate("pipeline-preflight", `Pipeline {{printf "%q" .Pipeline}} is {{if .Ready}}ready{{else}}not ready{{end}}.
|
||||
{{range .Checks}}{{if ne .Result "passed"}}{{.Result}}: {{.Message}}
|
||||
{{end}}{{end}}`, nil))
|
||||
|
||||
func pipelinePreflightCommand(version string, newState func() *nativeLoaders, modules func() (pipeline.Registries, error), options Options) commandkit.Command {
|
||||
options = defaultOptions(options)
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[pipelineRunInput]{Name: "preflight", Summary: "Check readiness for a configured pipeline invocation.", Flags: runFlags(), Arguments: pipelineRunArguments(), CheckInput: checkPipelineRunInput,
|
||||
Run: func(invocation commandkit.Invocation, input pipelineRunInput) commandkit.Outcome {
|
||||
return executePreflight(invocation, input, newState(), modules, version, options)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func executePreflight(invocation commandkit.Invocation, input pipelineRunInput, state *nativeLoaders, modules func() (pipeline.Registries, error), version string, options Options) commandkit.Outcome {
|
||||
ctx := invocation.Context
|
||||
loaded, failure := loadPipelineInvocation(ctx, invocation, input, state)
|
||||
if failure != nil {
|
||||
return *failure
|
||||
}
|
||||
report := preflightReport{Pipeline: input.PipelineID, Checks: []preflightCheck{}}
|
||||
var capture *frameworkdebug.Recorder
|
||||
add := func(id string, scope preflightScope, result, message string) {
|
||||
report.Checks = append(report.Checks, preflightCheck{ID: id, Scope: scope, Result: result, Message: message})
|
||||
}
|
||||
finish := func(outcome commandkit.Outcome) commandkit.Outcome {
|
||||
report.DebugDirectory = capture.Path()
|
||||
if err := capture.Finalize(report, outcome.Cause); err != nil {
|
||||
if outcome.Status == 0 {
|
||||
outcome = commandkit.Failure("Could not complete debug capture.").WithCause(err)
|
||||
} else {
|
||||
outcome = outcome.WithCause(err)
|
||||
}
|
||||
}
|
||||
if outcome.Status != 0 && capture.Path() != "" {
|
||||
outcome = outcome.WithExplanation(outcome.Explanation.Message+runLocations("", capture.Path()), outcome.Explanation.Details...)
|
||||
}
|
||||
for _, check := range report.Checks {
|
||||
if check.Result == "passed" {
|
||||
_ = invocation.Reporter().Info(check.Message)
|
||||
}
|
||||
}
|
||||
if err := invocation.Reporter().Report(commandkit.Report{Value: report, TextTemplate: preflightTemplate}); err != nil {
|
||||
if outcome.Status == 0 {
|
||||
return commandkit.Failure("Could not present pipeline readiness." + runLocations("", capture.Path()))
|
||||
}
|
||||
}
|
||||
return outcome
|
||||
}
|
||||
directory, err := input.Debug.directory(loaded.config.Debug.Directory)
|
||||
if err != nil {
|
||||
add("debug", preflightScope{Path: input.Debug.Directory.Value}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
if directory != "" {
|
||||
startedAt := options.Now().UTC()
|
||||
runID, err := options.RunIDGenerator(startedAt)
|
||||
if err == nil {
|
||||
err = validateRunID(runID)
|
||||
}
|
||||
if err == nil {
|
||||
capture, err = startRunDebug(input.Debug, loaded.config.Debug.Directory, runID, startedAt)
|
||||
}
|
||||
if err != nil {
|
||||
add("debug", preflightScope{Path: directory}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
add("debug", preflightScope{Path: capture.Path()}, "passed", "Debug capture is accessible.")
|
||||
if err := captureInvocationContext(capture, input, version, runID, startedAt); err != nil {
|
||||
add("debug", preflightScope{Path: capture.Path()}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
if err := captureRunConfiguration(capture, loaded.result); err != nil {
|
||||
add("debug", preflightScope{Path: capture.Path()}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
}
|
||||
selected, failure := selectPipelineInvocation(ctx, loaded, input, modules)
|
||||
if failure != nil {
|
||||
add("selection", preflightScope{Pipeline: input.PipelineID}, "failed", failure.Explanation.Message)
|
||||
return finish(*failure)
|
||||
}
|
||||
add("selection", preflightScope{Pipeline: input.PipelineID}, "passed", "Pipeline selection and resources are valid.")
|
||||
local, failure := preparePipelineInvocation(loaded, selected, input)
|
||||
for _, diagnostic := range local.diagnostics {
|
||||
for _, sample := range diagnostic.Samples {
|
||||
message := sample.Message
|
||||
if diagnostic.Disposition == contracts.DiagnosticDispositionWarning {
|
||||
report.Checks = append(report.Checks, preflightCheck{ID: "reference", Scope: preflightScope{Reference: sample.Scope}, Result: "warning", Code: diagnostic.ReasonCode, Message: message})
|
||||
} else {
|
||||
_ = invocation.Reporter().Info(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
if failure != nil {
|
||||
scope := preflightScope{Pipeline: input.PipelineID}
|
||||
if local.failureTarget == "input" {
|
||||
scope.Path = input.InputFile.Value
|
||||
} else if local.failureTarget == "references" {
|
||||
var pathErr *os.PathError
|
||||
if errors.As(failure.Cause, &pathErr) {
|
||||
scope.Path = pathErr.Path
|
||||
}
|
||||
}
|
||||
add(local.failureTarget, scope, "failed", failure.Explanation.Message)
|
||||
return finish(*failure)
|
||||
}
|
||||
add("preparation", preflightScope{Pipeline: input.PipelineID}, "passed", "References and modules are prepared.")
|
||||
if _, err := local.prepared.ParseSource(ctx, contracts.ParseRequest{Path: input.InputFile.Value, Raw: local.raw}); err != nil {
|
||||
add("input", preflightScope{Path: input.InputFile.Value}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
add("input", preflightScope{Path: input.InputFile.Value}, "passed", "Source input is valid.")
|
||||
outputErr, cacheErr := probePipelineDestinations(loaded.config.Output.Directory, loaded.config.CacheDirectory, local.resolved)
|
||||
if outputErr != nil {
|
||||
add("output", preflightScope{Path: loaded.config.Output.Directory}, "failed", outputErr.Error())
|
||||
return finish(commandkit.Failure(outputErr.Error()).WithCause(outputErr))
|
||||
}
|
||||
add("output", preflightScope{Path: loaded.config.Output.Directory}, "passed", "Output destination is accessible.")
|
||||
if pipelineUsesCache(local.resolved) {
|
||||
if cacheErr != nil {
|
||||
add("cache", preflightScope{Path: loaded.config.CacheDirectory}, "warning", cacheErr.Error())
|
||||
} else {
|
||||
add("cache", preflightScope{Path: loaded.config.CacheDirectory}, "passed", "Cache destination is accessible.")
|
||||
}
|
||||
}
|
||||
targets, err := preflight.DiscoverTargets(ctx, selected.effective.ResolvedPipeline, selected.catalog, selected.engine)
|
||||
if err != nil {
|
||||
scope := preflightScope{Pipeline: input.PipelineID}
|
||||
var targetErr *preflight.TargetError
|
||||
if errors.As(err, &targetErr) {
|
||||
scope.Bindings = []preflight.BindingScope{targetErr.Scope}
|
||||
}
|
||||
add("targets", scope, "failed", err.Error())
|
||||
return finish(pipelineResourceFailure(err))
|
||||
}
|
||||
if err := capture.WriteJSON("targets.json", targets); err != nil {
|
||||
add("debug", preflightScope{Path: capture.Path()}, "failed", err.Error())
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
var observe func(preflight.SmokeObservation) error
|
||||
if capture.Enabled() {
|
||||
evidence := newRunEvidenceRecorder(capture, loaded.result)
|
||||
evidenceIndex := 0
|
||||
observe = func(observation preflight.SmokeObservation) error {
|
||||
if observation.Report != nil {
|
||||
err := evidence.WriteJSON(fmt.Sprintf("smoke/%03d.json", evidenceIndex), observation.Report)
|
||||
evidenceIndex++
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
observations, err := preflight.RunSmokeChecksObserved(ctx, selected.engine, targets, input.Overrides.Execution.Execution, input.Overrides.Execution.TransientRetries, observe)
|
||||
failedCheck := false
|
||||
for _, observation := range observations {
|
||||
if !observation.Applicable {
|
||||
continue
|
||||
}
|
||||
scope := preflightScope{Profile: observation.ProfileID, Backend: observation.BackendID, Bindings: observation.Bindings}
|
||||
if observation.Err != nil {
|
||||
failedCheck = true
|
||||
add(string(observation.Kind), scope, "failed", observation.Err.Error())
|
||||
} else {
|
||||
add(string(observation.Kind), scope, "passed", fmt.Sprintf("%s check passed for profile %q.", observation.Kind, observation.ProfileID))
|
||||
}
|
||||
}
|
||||
// Recording failure is independent of a completed diagnostic assessment.
|
||||
if ctxErr := ctx.Err(); ctxErr != nil && !errors.Is(err, ctxErr) {
|
||||
err = errors.Join(err, ctxErr)
|
||||
}
|
||||
report.Ready = !failedCheck && len(observations) == 2*len(targets.Access)+len(targets.Profiles) && ctx.Err() == nil
|
||||
if err != nil {
|
||||
if !failedCheck && !report.Ready {
|
||||
if capture.Err() != nil {
|
||||
add("debug", preflightScope{Path: capture.Path()}, "failed", err.Error())
|
||||
} else {
|
||||
add("diagnostics", preflightScope{Pipeline: input.PipelineID}, "failed", err.Error())
|
||||
}
|
||||
}
|
||||
return finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
return finish(commandkit.Success())
|
||||
}
|
||||
225
internal/cli/pipeline_preflight_test.go
Normal file
225
internal/cli/pipeline_preflight_test.go
Normal file
@@ -0,0 +1,225 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
type readinessClient struct {
|
||||
calls int
|
||||
content string
|
||||
}
|
||||
|
||||
func (client *readinessClient) Generate(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
client.calls++
|
||||
return &promptkit.GenerateResponse{Content: client.content}, nil
|
||||
}
|
||||
|
||||
func TestPreflightRoutesAndReports(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
args []string
|
||||
format string
|
||||
}{
|
||||
{[]string{"preflight", "demo"}, "json"},
|
||||
{[]string{"pipeline", "preflight", "demo"}, "yaml"},
|
||||
} {
|
||||
args := append(test.args, "--config", config, "--input-file", input, "--cache", "bypass", "--format", test.format)
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("%v: %+v %s", args, outcome, stderr.String())
|
||||
}
|
||||
var report preflightReport
|
||||
if test.format == "json" {
|
||||
err = json.Unmarshal(out.Bytes(), &report)
|
||||
} else {
|
||||
err = yaml.Unmarshal(out.Bytes(), &report)
|
||||
}
|
||||
if err != nil || !report.Ready || report.Pipeline != "demo" || len(report.Checks) == 0 {
|
||||
t.Fatalf("report=%+v error=%v output=%s", report, err, out.String())
|
||||
}
|
||||
for _, check := range report.Checks {
|
||||
if check.ID == "reachability" || check.ID == "authentication" || check.Result == "warning" {
|
||||
t.Fatalf("unavailable HTTP diagnostics created a check or warning: %+v", check)
|
||||
}
|
||||
}
|
||||
}
|
||||
if client.calls != 2 || probe.parsed != 2 {
|
||||
t.Fatalf("calls=%d parses=%d", client.calls, probe.parsed)
|
||||
}
|
||||
client.content = `{"status":"bad"}`
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var failed preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &failed); err != nil || outcome.Status == 0 || failed.Ready || len(failed.Checks) == 0 {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v", outcome, failed, err)
|
||||
}
|
||||
if outcome.Cause == nil {
|
||||
t.Fatal("failed readiness lost its cause")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightLocalFailureStopsBeforeProvider(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input + "-missing", "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status == 0 || report.Ready || client.calls != 0 {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v calls=%d", outcome, report, err, client.calls)
|
||||
}
|
||||
if last := report.Checks[len(report.Checks)-1]; last.ID != "input" || last.Scope.Path != input+"-missing" {
|
||||
t.Fatalf("input failure scope = %+v", last)
|
||||
}
|
||||
if !errors.Is(outcome.Cause, context.Canceled) && outcome.Cause == nil {
|
||||
t.Fatal("missing input cause")
|
||||
}
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
missingReference := filepath.Join(t.TempDir(), "missing.txt")
|
||||
outcome = app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--reference", "context=" + missingReference, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
report = preflightReport{}
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status == 0 || len(report.Checks) == 0 || report.Checks[len(report.Checks)-1].Scope.Path != missingReference || client.calls != 0 {
|
||||
t.Fatalf("reference failure: outcome=%+v report=%+v err=%v calls=%d", outcome, report, err, client.calls)
|
||||
}
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
outcome = app.Execute(context.Background(), []string{"preflight", "demo", "--config", config}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status == 0 || out.Len() != 0 || client.calls != 0 {
|
||||
t.Fatalf("missing required flag: %+v %q", outcome, out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightHelpIsLazy(t *testing.T) {
|
||||
app, err := NewApplication("test", Options{LookupEnv: func(string) (string, bool) { t.Fatal("help loaded configuration"); return "", false }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{{"preflight", "--help"}, {"pipeline", "preflight", "--help"}} {
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status != 0 || !strings.Contains(out.String(), "--input-file") {
|
||||
t.Fatalf("%v: %+v %s", args, outcome, stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightNativeTextVisibility(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
flag string
|
||||
summary, detail bool
|
||||
}{{"", true, false}, {"--verbose", true, true}, {"--quiet", false, false}} {
|
||||
args := []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass"}
|
||||
if test.flag != "" {
|
||||
args = append(args, test.flag)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status != 0 || strings.Contains(out.String(), "is ready") != test.summary || strings.Contains(stderr.String(), "Source input is valid") != test.detail {
|
||||
t.Fatalf("%s: outcome=%+v stdout=%q stderr=%q", test.flag, outcome, out.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightReportDeliveryFailureDoesNotRepeatChecks(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cause := errors.New("output unavailable")
|
||||
var stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--format", "json"}, commandkit.Streams{Out: failingResultWriter{cause: cause}, Err: &stderr})
|
||||
if outcome.Status == 0 || client.calls != 1 || probe.parsed != 1 {
|
||||
t.Fatalf("outcome=%+v calls=%d parses=%d", outcome, client.calls, probe.parsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightCacheFailureWarnsWithoutPreventingReadiness(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "not-a-directory")
|
||||
if err := os.WriteFile(file, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, err := json.Marshal(filepath.Join(file, "cache"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--set", "/cache_directory=" + string(encoded), "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status != 0 || !report.Ready {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v stderr=%s", outcome, report, err, stderr.String())
|
||||
}
|
||||
found := false
|
||||
for _, check := range report.Checks {
|
||||
if check.ID == "cache" && check.Result == "warning" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("missing cache warning: %+v", report)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightRetainsReferenceWarningWhenInputReadFails(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: &readinessClient{content: `{"status":"ok"}`}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
empty := filepath.Join(t.TempDir(), "empty.txt")
|
||||
if err := os.WriteFile(empty, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input + "-missing", "--reference", "context=" + empty, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status == 0 {
|
||||
t.Fatalf("outcome=%+v report=%+v err=%v", outcome, report, err)
|
||||
}
|
||||
for _, check := range report.Checks {
|
||||
if check.ID == "reference" && check.Result == "warning" && check.Code == "empty_reference" && check.Scope.Reference != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("reference warning lost: %+v", report.Checks)
|
||||
}
|
||||
@@ -2,25 +2,20 @@ package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/config"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/artifactcache"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
frameworkdebug "gitea.maximumdirect.net/eric/notarius/internal/framework/debug"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/preflight"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func pipelineRunCommand(version string, newState func() *nativeLoaders, modules func() (pipeline.Registries, error), options Options) commandkit.Command {
|
||||
options = defaultOptions(options)
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[pipelineRunInput]{Name: "run", Summary: "Execute a configured pipeline and publish its artifacts.",
|
||||
Flags: runFlags(), Arguments: []commandkit.Argument[pipelineRunInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "pipeline-id", Usage: "Configured pipeline identifier."}, true, parseRequiredRunValue, func(input *pipelineRunInput, value commandkit.Supplied[string]) { input.PipelineID = value.Value })},
|
||||
Flags: runFlags(), Arguments: pipelineRunArguments(),
|
||||
CheckInput: checkPipelineRunInput,
|
||||
Run: func(invocation commandkit.Invocation, input pipelineRunInput) commandkit.Outcome {
|
||||
return (&runInvocation{invocation: invocation, input: input, version: version, newState: newState, modules: modules, options: options}).execute()
|
||||
@@ -46,28 +41,11 @@ func (run *runInvocation) execute() commandkit.Outcome {
|
||||
invocation, input, version := run.invocation, run.input, run.version
|
||||
newState, modules, options := run.newState, run.modules, run.options
|
||||
ctx := invocation.Context
|
||||
state := newState()
|
||||
selection := captureSelection(input.Selection)
|
||||
if input.OutputDirectory.Set {
|
||||
selection.Overrides = append(selection.Overrides, configkit.Override{Path: configkit.Keys("output", "directory"), Value: input.OutputDirectory.Value, Flag: "--output-dir"})
|
||||
loaded, failure := loadPipelineInvocation(ctx, invocation, input, newState())
|
||||
if failure != nil {
|
||||
return *failure
|
||||
}
|
||||
result, err := state.application(ctx, selection)
|
||||
if err != nil {
|
||||
return pipelineConfigurationFailure(err)
|
||||
}
|
||||
diagnostics, _ := ckconfig.AdaptDiagnostics("Configuration\n", result.Sources(), result.Diagnostics())
|
||||
for _, diagnostic := range diagnostics {
|
||||
if diagnostic.Severity == commandkit.SeverityWarning {
|
||||
_ = invocation.Reporter().AtEnd().Warn("", diagnostic.Write)
|
||||
} else {
|
||||
_ = invocation.Reporter().AtEnd().Info("", diagnostic.Write)
|
||||
}
|
||||
}
|
||||
loaded, err := config.FromResult(result)
|
||||
if err != nil {
|
||||
return pipelineInvalidConfiguration(err)
|
||||
}
|
||||
cfg := loaded.RuntimeConfig()
|
||||
result, cfg := loaded.result, loaded.config
|
||||
startedAt := options.Now().UTC()
|
||||
runID, err := options.RunIDGenerator(startedAt)
|
||||
if err != nil {
|
||||
@@ -86,61 +64,19 @@ func (run *runInvocation) execute() commandkit.Outcome {
|
||||
run.group = &promptkit.ExecutionGroup{}
|
||||
ctx = promptkit.WithExecutionObserver(ctx, run.group.Observe)
|
||||
}
|
||||
if err := run.capture.WriteJSON("context.json", map[string]any{"application_version": version, "pipeline": input.PipelineID, "input_path": input.InputFile.Value, "run_id": runID, "started_at": startedAt, "lanes": input.Lanes, "resources": input.Overrides.Resources, "execution_overrides": input.Overrides.Execution}); err != nil {
|
||||
if err := captureInvocationContext(run.capture, input, version, runID, startedAt); err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
if err := captureRunConfiguration(run.capture, result); err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
registries, err := modules()
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
selected, failure := selectPipelineInvocation(ctx, loaded, input, modules)
|
||||
if failure != nil {
|
||||
return run.finish(*failure)
|
||||
}
|
||||
catalog := catalogFromRegistries(registries)
|
||||
binds, unbinds, err := resolveCLIReferenceRequests(cfg, input.PipelineID, input.Lanes.Value, catalog, input.References.Value, input.Unbinds.Value)
|
||||
if err != nil {
|
||||
return run.finish(pipelineInvalidConfiguration(err))
|
||||
}
|
||||
resolve := config.ResolveInput{PipelineID: input.PipelineID, Only: input.Lanes.Value, Catalog: catalog, ReferenceOverrides: binds, ReferenceUnbinds: unbinds}
|
||||
if input.Cache.Set {
|
||||
resolve.CacheOverride = &input.Cache.Value
|
||||
}
|
||||
if input.Overrides.Resources.Profile.Set {
|
||||
resolve.LLMProfileOverride = &input.Overrides.Resources.Profile.Value
|
||||
}
|
||||
effective, err := cfg.Resolve(resolve)
|
||||
if err != nil {
|
||||
return run.finish(pipelineInvalidConfiguration(err))
|
||||
}
|
||||
var engine *promptkit.Engine
|
||||
if preflight.RequiresEngine(effective.ResolvedPipeline) {
|
||||
engine, err = state.engine(ctx, selection)
|
||||
if err != nil {
|
||||
return run.finish(pipelineConfigurationFailure(err))
|
||||
}
|
||||
}
|
||||
if err := preflight.Validate(ctx, effective.ResolvedPipeline, catalog, engine); err != nil {
|
||||
return run.finish(pipelineResourceFailure(err))
|
||||
}
|
||||
workingDirectory, err := os.Getwd()
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
materialized, referenceDiagnostics, err := pipeline.MaterializeReferences(effective.ResolvedPipeline, catalog, pipeline.ReferenceMaterializationOptions{ConfigPath: loaded.MainSourcePath(), WorkingDir: workingDirectory})
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
prepared, err := pipeline.Prepare(materialized, registries, pipeline.ModuleDependencies{Engine: engine})
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
}
|
||||
raw, err := os.ReadFile(input.InputFile.Value)
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(fmt.Sprintf("Read input %q: %v", input.InputFile.Value, err)).WithCause(err))
|
||||
}
|
||||
sessionID, err := runSessionID(input.Overrides.Resources.SessionID, materialized.Input.Module, raw)
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
local, failure := preparePipelineInvocation(loaded, selected, input)
|
||||
if failure != nil {
|
||||
return run.finish(*failure)
|
||||
}
|
||||
cache, err := artifactcache.NewFilesystemStore(cfg.CacheDirectory)
|
||||
if err != nil {
|
||||
@@ -150,8 +86,8 @@ func (run *runInvocation) execute() commandkit.Outcome {
|
||||
if run.capture.Enabled() {
|
||||
recorder = newRunEvidenceRecorder(run.capture, result)
|
||||
}
|
||||
_ = invocation.Reporter().Progress(fmt.Sprintf("Running pipeline %q.", effective.ResolvedPipeline.ID))
|
||||
run.output, err = pipeline.New().Run(ctx, pipeline.RunInput{Prepared: prepared, Path: input.InputFile.Value, RawInput: raw, SessionID: sessionID, RunID: runID, StartedAt: startedAt, Diagnostics: referenceDiagnostics, Cache: cache, Debug: recorder, Workers: cfg.Concurrency.Workers, Execution: contracts.ExecutionOptions{Execution: input.Overrides.Execution.Execution, TransientRetries: input.Overrides.Execution.TransientRetries}})
|
||||
_ = invocation.Reporter().Progress(fmt.Sprintf("Running pipeline %q.", selected.effective.ResolvedPipeline.ID))
|
||||
run.output, err = pipeline.New().Run(ctx, pipeline.RunInput{Prepared: local.prepared, Path: input.InputFile.Value, RawInput: local.raw, SessionID: local.sessionID, RunID: runID, StartedAt: startedAt, Diagnostics: local.diagnostics, Cache: cache, Debug: recorder, Workers: cfg.Concurrency.Workers, Execution: contracts.ExecutionOptions{Execution: input.Overrides.Execution.Execution, TransientRetries: input.Overrides.Execution.TransientRetries}})
|
||||
reportRunDiagnostics(invocation.Reporter(), run.output.Diagnostics)
|
||||
if err != nil {
|
||||
return run.finish(commandkit.Failure(err.Error()).WithCause(err))
|
||||
@@ -164,7 +100,7 @@ func (run *runInvocation) execute() commandkit.Outcome {
|
||||
if outcome.Status != 0 {
|
||||
return outcome
|
||||
}
|
||||
return reportRunResult(invocation, runResult{Pipeline: effective.ResolvedPipeline.ID, ArtifactCount: run.output.ArtifactCount(), OutputDirectory: outputDirectory, DebugDirectory: run.capture.Path(), FallbackCount: run.output.FallbackCount})
|
||||
return reportRunResult(invocation, runResult{Pipeline: selected.effective.ResolvedPipeline.ID, ArtifactCount: run.output.ArtifactCount(), OutputDirectory: outputDirectory, DebugDirectory: run.capture.Path(), FallbackCount: run.output.FallbackCount})
|
||||
}
|
||||
|
||||
func (run *runInvocation) finish(outcome commandkit.Outcome) commandkit.Outcome {
|
||||
|
||||
@@ -163,7 +163,7 @@ func runRegistries(t *testing.T, probe *runProbe) pipeline.Registries {
|
||||
check(jsonoutput.Register(registries.Outputs))
|
||||
check(pipeline.RegisterArtifactCodec(registries.ArtifactCodecs, inspectionCodec{}))
|
||||
slots := runReferenceSlots()
|
||||
check(pipeline.RegisterExtractorBuilder(registries.Extractors, pipeline.ModuleSpec{Key: "fixture/extract", Stage: pipeline.StageExtract, ArtifactKind: "test/inspection", ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"inspect-initial", "inspect-correction"}, ReferenceSlots: slots}, func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }, func(request pipeline.BuildRequest) (contracts.Extractor[inspectionArtifact], error) {
|
||||
check(pipeline.RegisterExtractorBuilder(registries.Extractors, pipeline.ModuleSpec{Key: "fixture/extract", Stage: pipeline.StageExtract, ArtifactKind: "test/inspection", ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"inspect-initial", "inspect-correction"}, InitialPrompts: []string{"inspect-initial"}, ReferenceSlots: slots}, func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }, func(request pipeline.BuildRequest) (contracts.Extractor[inspectionArtifact], error) {
|
||||
probe.engines = append(probe.engines, request.Dependencies.Engine)
|
||||
return &runProducer{key: "fixture/extract", engine: request.Dependencies.Engine, probe: probe}, nil
|
||||
}))
|
||||
|
||||
119
internal/cli/preflight_assembled_test.go
Normal file
119
internal/cli/preflight_assembled_test.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
func TestPreflightAndRunWithMaintainedPipeline(t *testing.T) {
|
||||
t.Setenv("OPENROUTER_API_KEY", "fixture-key")
|
||||
var gets, smoke, runCalls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
gets.Add(1)
|
||||
fmt.Fprint(w, `{"data":{"label":"fixture","is_free_tier":false,"usage":0}}`)
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("request: %v", err)
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
if temperature, ok := body["temperature"].(float64); !ok || temperature != 0 {
|
||||
t.Errorf("explicit zero temperature missing: %v", body["temperature"])
|
||||
}
|
||||
encoded, _ := json.Marshal(body["response_format"])
|
||||
schema := string(encoded)
|
||||
content := ""
|
||||
switch {
|
||||
case strings.Contains(schema, `"status"`):
|
||||
smoke.Add(1)
|
||||
content = `{"status":"ok"}`
|
||||
case strings.Contains(schema, `"classification"`):
|
||||
runCalls.Add(1)
|
||||
content = `{"classification":"non_combat","explanation":"No combat."}`
|
||||
case strings.Contains(schema, `"start_unit_id"`):
|
||||
runCalls.Add(1)
|
||||
content = `{"scenes":[{"start_unit_id":1,"end_unit_id":2}]}`
|
||||
case strings.Contains(schema, `"kind"`):
|
||||
runCalls.Add(1)
|
||||
content = `{"kind":"narrative","title":"Camp","summary":"The party rests."}`
|
||||
default:
|
||||
t.Errorf("unexpected request schema: %s", schema)
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}, "finish_reason": "stop"}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
root := t.TempDir()
|
||||
input := filepath.Join(root, "transcript.json")
|
||||
party, glossary := filepath.Join(root, "party.yml"), filepath.Join(root, "glossary.json")
|
||||
for name, data := range map[string][]byte{input: readRepositoryFile(t, "examples", "dnd-minimal", "transcript.json"), party: []byte(validPartyYAML), glossary: []byte(validSharedGlossary)} {
|
||||
if err := os.WriteFile(name, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
output := filepath.Join(root, "output")
|
||||
app, err := NewApplication("test", Options{RunIDGenerator: func(_ time.Time) (string, error) { return "run", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
common := []string{"dnd-session", "--config", repositoryPath("examples", "dnd-complete", "config.yml"), "--input-file", input, "--set", `/pipelines/dnd-session/steps=[{"id":"describe-session","artifacts":{"scene-descriptions":{"extract":{"module":"dnd/scene-descriptions","validators":[{"module":"extract/dnd/scene-descriptions/combat_semantics"}]},"merge":{"module":"appendorder"},"normalize":{"module":"dnd/scene-descriptions"}}}}]`, "--set", `/pipelines/dnd-session/output/options/evidence_context/lanes=["scene-descriptions"]`, "--reference", "party=" + party, "--reference", "glossary=" + glossary, "--output-dir", output, "--cache", "bypass", "--llm-endpoint", server.URL + "/v1", "--llm-temperature=0", "--llm-transient-retries=0", "--format", "json"}
|
||||
var out, stderr bytes.Buffer
|
||||
args := append([]string{"preflight"}, common...)
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status != 0 || !report.Ready {
|
||||
t.Fatalf("preflight outcome=%+v report=%+v err=%v stdout=%s stderr=%s", outcome, report, err, out.String(), stderr.String())
|
||||
}
|
||||
if gets.Load() != 2 || smoke.Load() != 1 || runCalls.Load() != 0 {
|
||||
t.Fatalf("preflight calls: gets=%d smoke=%d run=%d", gets.Load(), smoke.Load(), runCalls.Load())
|
||||
}
|
||||
if entries, err := os.ReadDir(output); err != nil || len(entries) != 0 {
|
||||
t.Fatalf("preflight output=%v err=%v", entries, err)
|
||||
}
|
||||
var validator bool
|
||||
for _, check := range report.Checks {
|
||||
for _, binding := range check.Scope.Bindings {
|
||||
if strings.Contains(binding.Validator, "combat_semantics") {
|
||||
validator = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !validator {
|
||||
t.Fatalf("semantic validator missing from report: %+v", report.Checks)
|
||||
}
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
outcome = app.Execute(context.Background(), append([]string{"run"}, common...), commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status != 0 {
|
||||
t.Fatalf("run outcome=%+v stdout=%s stderr=%s", outcome, out.String(), stderr.String())
|
||||
}
|
||||
if runCalls.Load() < 3 {
|
||||
t.Fatalf("run calls=%d", runCalls.Load())
|
||||
}
|
||||
if err := os.WriteFile(input, []byte(`{"segments":`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := runCalls.Load()
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
outcome = app.Execute(context.Background(), append([]string{"run"}, common...), commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if outcome.Status == 0 || runCalls.Load() != before {
|
||||
t.Fatalf("invalid input outcome=%+v calls=%d stdout=%s stderr=%s", outcome, runCalls.Load(), out.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
150
internal/cli/preflight_capture_test.go
Normal file
150
internal/cli/preflight_capture_test.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestPreflightCapturesEarlyFailureAndUpdatesLatest(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
root := t.TempDir()
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client, Now: func() time.Time { return time.Unix(42, 0) }, RunIDGenerator: func(time.Time) (string, error) { return "inspection", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input + "-missing", "--debug", "--debug-dir", root, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status == 0 || report.Ready || report.DebugDirectory != filepath.Join(root, "inspection") || client.calls != 0 {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v", outcome, report, err)
|
||||
}
|
||||
target, err := os.Readlink(filepath.Join(root, "latest"))
|
||||
if err != nil || target != "inspection" {
|
||||
t.Fatalf("latest=%q err=%v", target, err)
|
||||
}
|
||||
terminal, err := os.ReadFile(filepath.Join(report.DebugDirectory, "outcome.json"))
|
||||
if err != nil || !strings.Contains(string(terminal), "missing") {
|
||||
t.Fatalf("capture=%s err=%v", terminal, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightRetainsCancellationAndCaptureFailure(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
root := t.TempDir()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
client := captureClient(func(ctx context.Context, _ promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
calls++
|
||||
if err := os.Mkdir(filepath.Join(root, "inspection", "smoke", "002.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
return nil, ctx.Err()
|
||||
})
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client, RunIDGenerator: func(time.Time) (string, error) { return "inspection", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(ctx, []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--debug", "--debug-dir", root, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if !errors.Is(outcome.Cause, context.Canceled) || !strings.Contains(outcome.Cause.Error(), "record debug") || calls != 1 {
|
||||
t.Fatalf("outcome=%+v cause=%v calls=%d stderr=%s", outcome, outcome.Cause, calls, stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightPositiveAssessmentSurvivesCaptureFailure(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
root := t.TempDir()
|
||||
calls := 0
|
||||
client := captureClient(func(_ context.Context, _ promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
calls++
|
||||
if latest, err := os.Readlink(filepath.Join(root, "latest")); err != nil || latest != "inspection" {
|
||||
t.Fatalf("latest before provider call = %q, %v", latest, err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(root, "inspection", "smoke", "002.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &promptkit.GenerateResponse{Content: `{"status":"ok"}`}, nil
|
||||
})
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client, RunIDGenerator: func(time.Time) (string, error) { return "inspection", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--debug", "--debug-dir", root, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || !report.Ready || outcome.Status == 0 || outcome.Cause == nil || calls != 1 {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v calls=%d", outcome, report, err, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightDebugAllocationFailureAndDisable(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe)
|
||||
client := &readinessClient{content: `{"status":"ok"}`}
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "file")
|
||||
if err := os.WriteFile(file, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
args []string
|
||||
wantReady bool
|
||||
}{
|
||||
{[]string{"--debug", "--debug-dir", filepath.Join(file, "bad")}, false},
|
||||
{[]string{"--debug", "--debug-dir=", "--cache", "bypass"}, true},
|
||||
{[]string{"--debug=false", "--debug-dir", filepath.Join(file, "bad"), "--cache", "bypass"}, true},
|
||||
} {
|
||||
args := append([]string{"preflight", "demo", "--config", config, "--input-file", input, "--format", "json"}, test.args...)
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || report.Ready != test.wantReady || (outcome.Status == 0) != test.wantReady || report.DebugDirectory != "" {
|
||||
t.Fatalf("%v: outcome=%+v report=%+v err=%v stderr=%s", test.args, outcome, report, err, stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightCaptureFailureBeforeLastProfileIsNotReady(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
_, config, input, _ := runFixture(t, probe, func(configuration string) string {
|
||||
return strings.Replace(configuration, "id: inspect-validator\n default_profile: partial", "id: inspect-validator\n default_profile: chosen", 1)
|
||||
})
|
||||
root := t.TempDir()
|
||||
calls := 0
|
||||
client := captureClient(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
calls++
|
||||
if err := os.Mkdir(filepath.Join(root, "inspection", "smoke", "004.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &promptkit.GenerateResponse{Content: `{"status":"ok"}`}, nil
|
||||
})
|
||||
app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client, RunIDGenerator: func(time.Time) (string, error) { return "inspection", nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--debug", "--debug-dir", root, "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil || report.Ready || outcome.Status == 0 || calls != 1 {
|
||||
t.Fatalf("outcome=%+v report=%+v error=%v calls=%d", outcome, report, err, calls)
|
||||
}
|
||||
}
|
||||
@@ -359,7 +359,7 @@ func TestProductionSpellNormalizerRejectsInvalidCatalogReferencesBeforeExecution
|
||||
t.Fatalf("MaterializeReferences() error = %v, want malformed JSON to reach preparation", err)
|
||||
}
|
||||
_, err = pipeline.Prepare(materialized, components.registries, pipeline.ModuleDependencies{Engine: productionNativeEngine(t, &productionFakeLLMClient{})})
|
||||
for _, fragment := range []string{`pipeline "dnd-session"`, `lane "spells"`, "normalize", `module "dnd/spells"`, "decode spell catalog overlay"} {
|
||||
for _, fragment := range []string{`pipeline "dnd-session"`, `lane "spells"`, "normalize", `module "dnd/spells"`, "invalid JSON syntax"} {
|
||||
if err == nil || !strings.Contains(err.Error(), fragment) {
|
||||
t.Fatalf("Prepare() error = %v, want context fragment %q", err, fragment)
|
||||
}
|
||||
@@ -388,7 +388,7 @@ func TestProductionSpellNormalizerRejectsInvalidCatalogReferencesBeforeExecution
|
||||
t.Fatal(err)
|
||||
}
|
||||
content := productionSpellCatalogContractConfig(t)
|
||||
catalogSource := repositoryPath("examples", "dnd-complete", "spell-catalog.json")
|
||||
catalogSource := loadMaintainedExample(t, writeProductionContractConfig(t, content)).Pipelines["dnd-session"].Artifacts["spells"].Extract.References["spell_catalog"].Path
|
||||
content = strings.Replace(content, catalogSource, "__extract_catalog__", 1)
|
||||
content = replaceRequiredOnce(t, content, catalogSource, catalogPath)
|
||||
content = replaceRequiredOnce(t, content, "__extract_catalog__", catalogSource)
|
||||
@@ -622,6 +622,12 @@ func maintainedExampleFiles(t *testing.T) []maintainedExample {
|
||||
|
||||
func productionSpellCatalogContractConfig(t *testing.T) string {
|
||||
t.Helper()
|
||||
partyPath := writeSharedReference(t, "party.yml", validPartyYAML)
|
||||
glossaryPath := writeSharedReference(t, "glossary.json", validSharedGlossary)
|
||||
catalogPath := filepath.Join(t.TempDir(), "spell-glossary.json")
|
||||
if err := os.WriteFile(catalogPath, []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"aegis","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]}}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return fmt.Sprintf(`version: 6
|
||||
pipelines:
|
||||
dnd-session:
|
||||
@@ -644,7 +650,7 @@ pipelines:
|
||||
references:
|
||||
spell_catalog:
|
||||
path: %q
|
||||
`, repositoryPath("examples", "dnd-complete", "party.txt"), repositoryPath("examples", "dnd-complete", "glossary.txt"), repositoryPath("examples", "dnd-complete", "spell-catalog.json"), repositoryPath("examples", "dnd-complete", "spell-catalog.json"))
|
||||
`, partyPath, glossaryPath, catalogPath, catalogPath)
|
||||
}
|
||||
|
||||
func writeProductionSpellCatalogContractConfig(t *testing.T) string {
|
||||
|
||||
@@ -114,7 +114,7 @@ type recoveryFixture struct {
|
||||
func newRecoveryFixture(t *testing.T) *recoveryFixture {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for _, name := range []string{"prompts.yml", "transcript.json", "party.txt", "glossary.txt", "spell-catalog.json", "pipelines/dnd-session.yml", "pipelines/dnd-session.describe-session.yml"} {
|
||||
for _, name := range []string{"prompts.yml", "transcript.json", "party.yml", "glossary.yml", "pipelines/dnd-session.yml", "pipelines/dnd-session.describe-session.yml"} {
|
||||
content, err := os.ReadFile(repositoryPath("examples", "dnd-complete", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -86,6 +86,51 @@ func TestReferenceSelectorSpecificityAndFinalOccurrenceChooseConcreteBindings(t
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIReferenceOverridesRetainEachTargetSelection(t *testing.T) {
|
||||
cfg := referenceContractConfig()
|
||||
profile := cfg.Pipelines["demo"]
|
||||
profile.References = map[string]pipeline.ReferenceSource{"shared": {Path: "base.yml", Collections: []string{"campaign"}}}
|
||||
alpha := profile.Artifacts["alpha"]
|
||||
alpha.Extract.References["shared"] = pipeline.ReferenceSource{Path: "local.yml", Collections: []string{}}
|
||||
profile.Artifacts["alpha"] = alpha
|
||||
cfg.Pipelines["demo"] = profile
|
||||
catalog := referenceContractCatalog(t, true, true)
|
||||
requests := []cliReferenceRequest{
|
||||
{Selector: mustParseReferenceSelector(t, "shared", "--reference"), Source: "broad.yml"},
|
||||
{Selector: mustParseReferenceSelector(t, "alpha.extract.shared", "--reference"), Source: "narrow.yml"},
|
||||
}
|
||||
overrides, unbinds, err := resolveCLIReferenceRequests(cfg, "demo", nil, catalog, requests, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
effective, err := cfg.Resolve(config.ResolveInput{PipelineID: "demo", Catalog: catalog, ReferenceOverrides: overrides, ReferenceUnbinds: unbinds})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := 0
|
||||
for _, id := range []string{"alpha", "beta"} {
|
||||
lane := referenceContractLane(t, effective.ResolvedPipeline, id)
|
||||
for _, target := range []pipeline.ResolvedReferenceTarget{lane.ExtractReferences, lane.MergeReferences, lane.NormalizeReferences} {
|
||||
for _, binding := range target.Bindings {
|
||||
if binding.SlotName != "shared" {
|
||||
continue
|
||||
}
|
||||
count++
|
||||
if id == "alpha" && target.Stage == pipeline.StageExtract {
|
||||
if binding.Source != "narrow.yml" || binding.Collections == nil || len(binding.Collections) != 0 {
|
||||
t.Fatalf("narrow binding = %#v", binding)
|
||||
}
|
||||
} else if binding.Source != "broad.yml" || !slices.Equal(binding.Collections, []string{"campaign"}) {
|
||||
t.Fatalf("broad binding = %#v", binding)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if count != 6 {
|
||||
t.Fatalf("resolved %d shared bindings, want 6", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequiredReferencesCanBeSuppliedOnlyByCLI(t *testing.T) {
|
||||
cfg := referenceContractConfig()
|
||||
profile := cfg.Pipelines["demo"]
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/config"
|
||||
frameworkdebug "gitea.maximumdirect.net/eric/notarius/internal/framework/debug"
|
||||
@@ -15,6 +16,30 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// Target-aware native evidence retains effective parameters with their secret
|
||||
// marks. Early context records presence only, before a target is available.
|
||||
func captureInvocationContext(recorder *frameworkdebug.Recorder, input pipelineRunInput, version, runID string, startedAt time.Time) error {
|
||||
if !recorder.Enabled() {
|
||||
return nil
|
||||
}
|
||||
execution := input.Overrides.Execution
|
||||
extraParamsSupplied := false
|
||||
if execution.Execution != nil {
|
||||
extraParamsSupplied = execution.Execution.ExtraParams != nil
|
||||
execution.Execution = captureExecutionOverride(execution.Execution)
|
||||
}
|
||||
return recorder.WriteJSON("context.json", map[string]any{"application_version": version, "pipeline": input.PipelineID, "input_path": input.InputFile.Value, "run_id": runID, "started_at": startedAt, "lanes": input.Lanes, "references": input.References, "unbinds": input.Unbinds, "resources": input.Overrides.Resources, "execution_overrides": execution, "extra_params_supplied": extraParamsSupplied})
|
||||
}
|
||||
|
||||
func captureExecutionOverride(execution *promptkit.ExecutionTargetOverride) *promptkit.ExecutionTargetOverride {
|
||||
if execution == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *execution
|
||||
copy.ExtraParams = nil
|
||||
return ©
|
||||
}
|
||||
|
||||
// captureRunConfiguration inspects the original, frozen application load. It
|
||||
// neither reloads resources nor serializes typed settings containing credentials.
|
||||
// Shared loaders remain independent of run storage.
|
||||
@@ -107,6 +132,9 @@ func newRunEvidenceRecorder(recorder *frameworkdebug.Recorder, result *configkit
|
||||
|
||||
func (writer *runEvidenceRecorder) WriteJSON(name string, payload any) error {
|
||||
switch value := payload.(type) {
|
||||
case promptkit.RunRequest:
|
||||
value.Execution = captureExecutionOverride(value.Execution)
|
||||
payload = value
|
||||
case *promptkit.PreparedRun:
|
||||
copy := *value
|
||||
copy.EffectiveModelParams = writer.target(copy.EffectiveModelParams, copy.SelectedProfileID, copy.SelectedBackendID)
|
||||
@@ -115,6 +143,10 @@ func (writer *runEvidenceRecorder) WriteJSON(name string, payload any) error {
|
||||
copy := *value
|
||||
copy.EffectiveModelParams = writer.target(copy.EffectiveModelParams, copy.SelectedProfileID, copy.SelectedBackendID)
|
||||
payload = copy
|
||||
case *promptkit.SmokeTestReport:
|
||||
copy := *value
|
||||
copy.Target.EffectiveSettings = writer.target(copy.Target.EffectiveSettings, copy.Target.ProfileID, copy.Target.BackendID)
|
||||
payload = copy
|
||||
}
|
||||
return writer.Recorder.WriteJSON(name, payload)
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ func (input runDebugInput) directory(configuredDirectory string) (string, error)
|
||||
return filepath.Abs(directory)
|
||||
}
|
||||
|
||||
// Only the run handler calls this, after configuration/run identity and before
|
||||
// engine construction or pipeline preflight. Shared loaders never allocate.
|
||||
// Call after configuration and identity selection, before pipeline resolution.
|
||||
// Shared loaders never allocate.
|
||||
func startRunDebug(input runDebugInput, configuredDirectory, runID string, startedAt time.Time) (*frameworkdebug.Recorder, error) {
|
||||
directory, err := input.directory(configuredDirectory)
|
||||
if err != nil || directory == "" {
|
||||
|
||||
@@ -60,6 +60,10 @@ func runFlags() []commandkit.Flag[pipelineRunInput] {
|
||||
return append(flags, executionOverrideFlags(func(input *pipelineRunInput) *executionOverrides { return &input.Overrides })...)
|
||||
}
|
||||
|
||||
func pipelineRunArguments() []commandkit.Argument[pipelineRunInput] {
|
||||
return []commandkit.Argument[pipelineRunInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "pipeline-id", Usage: "Configured pipeline identifier."}, true, parseRequiredRunValue, func(input *pipelineRunInput, value commandkit.Supplied[string]) { input.PipelineID = value.Value })}
|
||||
}
|
||||
|
||||
func parseRequiredRunValue(value string) (string, error) {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return "", fmt.Errorf("value must not be empty")
|
||||
|
||||
239
internal/cli/shared_reference_workflow_test.go
Normal file
239
internal/cli/shared_reference_workflow_test.go
Normal file
@@ -0,0 +1,239 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type sharedReferenceClient struct {
|
||||
mu sync.Mutex
|
||||
requests []promptkit.GenerateRequest
|
||||
spellResponse string
|
||||
}
|
||||
|
||||
func (client *sharedReferenceClient) Generate(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
client.requests = append(client.requests, request)
|
||||
switch {
|
||||
case productionSchemaHasProperty(request, "status"):
|
||||
return &promptkit.GenerateResponse{Content: `{"status":"ok"}`}, nil
|
||||
case productionSchemaHasProperty(request, "spell_casts"):
|
||||
if client.spellResponse != "" {
|
||||
return &promptkit.GenerateResponse{Content: client.spellResponse}, nil
|
||||
}
|
||||
return &promptkit.GenerateResponse{Content: `{"spell_casts":[]}`}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected provider request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedSpellSelectionDrivesValidationAndNormalization(t *testing.T) {
|
||||
party := writeSharedReference(t, "party.yml", validPartyYAML)
|
||||
glossary := writeSharedReference(t, "glossary.json", validSharedGlossary)
|
||||
configPath := sharedReferenceConfig(t, party, glossary, glossary)
|
||||
client := &sharedReferenceClient{spellResponse: productionSpellResponse("Emberfall Aegis")}
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunWithOptions([]string{"run", "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "bypass", "--format", "json"}, &stdout, &stderr, productionRunOptions(t, client))
|
||||
if code != 0 {
|
||||
t.Fatalf("status=%d stdout=%s stderr=%s", code, stdout.String(), stderr.String())
|
||||
}
|
||||
var report runResult
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := readProductionJSON[dnd.SpellList](t, filepath.Join(report.OutputDirectory, "lanes", "spells.json"))
|
||||
if len(result.SpellCasts) != 1 || result.SpellCasts[0].Spell != "Aegis of Emberfall" {
|
||||
t.Fatalf("normalized shared spell = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidSharedReferencesFailBeforeCachedReuse(t *testing.T) {
|
||||
party := writeSharedReference(t, "party.yml", validPartyYAML)
|
||||
glossary := writeSharedReference(t, "glossary.json", validSharedGlossary)
|
||||
configPath := sharedReferenceConfig(t, party, glossary, glossary)
|
||||
configBytes, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cacheDir := filepath.Join(t.TempDir(), "cache")
|
||||
configBytes = []byte(strings.Replace(string(configBytes), "version: 6\n", fmt.Sprintf("version: 6\ncache_directory: %q\n", cacheDir), 1))
|
||||
if err := os.WriteFile(configPath, configBytes, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &sharedReferenceClient{}
|
||||
options := productionRunOptions(t, client)
|
||||
runNumber := 0
|
||||
options.RunIDGenerator = func(_ time.Time) (string, error) {
|
||||
runNumber++
|
||||
return fmt.Sprintf("run-1700000000000000000-%032x", runNumber), nil
|
||||
}
|
||||
args := []string{"run", "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "auto", "--format", "json"}
|
||||
for i := 0; i < 2; i++ {
|
||||
var stdout, stderr strings.Builder
|
||||
if code := RunWithOptions(args, &stdout, &stderr, options); code != 0 {
|
||||
t.Fatalf("warm run %d status=%d stdout=%s stderr=%s", i, code, stdout.String(), stderr.String())
|
||||
}
|
||||
if i == 1 && len(client.snapshot()) != 1 {
|
||||
t.Fatalf("expected accepted-result reuse, provider calls=%d", len(client.snapshot()))
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(party, []byte("{}"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunWithOptions(args, &stdout, &stderr, options)
|
||||
if code == 0 || len(client.snapshot()) != 1 || !strings.Contains(stderr.String(), "party") {
|
||||
t.Fatalf("invalid cached invocation status=%d calls=%d stderr=%s", code, len(client.snapshot()), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (client *sharedReferenceClient) snapshot() []promptkit.GenerateRequest {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
return append([]promptkit.GenerateRequest(nil), client.requests...)
|
||||
}
|
||||
|
||||
func sharedReferenceConfig(t *testing.T, partyPath, glossaryPath, spellPath string) string {
|
||||
t.Helper()
|
||||
return writeProductionContractConfig(t, fmt.Sprintf(`version: 6
|
||||
pipelines:
|
||||
dnd-session:
|
||||
input: {module: seriatim}
|
||||
references:
|
||||
party: {path: %q}
|
||||
glossary: {path: %q, collections: [setting]}
|
||||
artifacts:
|
||||
spells:
|
||||
extract:
|
||||
module: dnd/spells
|
||||
references:
|
||||
spell_catalog: {path: %q, collections: [custom]}
|
||||
normalize:
|
||||
module: dnd/spells
|
||||
references:
|
||||
spell_catalog: {path: %q, collections: [custom]}
|
||||
`+productionProviderConfiguration, partyPath, glossaryPath, spellPath, spellPath))
|
||||
}
|
||||
|
||||
func writeSharedReference(t *testing.T, name, value string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), name)
|
||||
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
const validPartyYAML = `schema_version: maximumdirect.rpg.party.v1
|
||||
characters:
|
||||
aria:
|
||||
character: {name: Aria, aliases: [Star]}
|
||||
player: {name: Alice}
|
||||
`
|
||||
|
||||
const validSharedGlossary = `{"schema_version":"maximumdirect.glossary.v1","collections":{"setting":{"entries":[{"id":"v","name":"Verdant Tower","category":"place","aliases":["Green Spire"]}]},"custom":{"entries":[{"id":"a","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]}]},"ignored":{"entries":[{"id":"x","name":"Not In Prompt","category":"term"}]}}}`
|
||||
|
||||
func TestSharedReferencesReachRunAndPreflight(t *testing.T) {
|
||||
party := writeSharedReference(t, "party.yml", validPartyYAML)
|
||||
glossary := writeSharedReference(t, "glossary.json", validSharedGlossary)
|
||||
configPath := sharedReferenceConfig(t, party, glossary, glossary)
|
||||
client := &sharedReferenceClient{}
|
||||
outputDir := filepath.Join(t.TempDir(), "output")
|
||||
common := []string{"dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--reference", "party=" + party, "--reference", "glossary=" + glossary, "--reference", "spell_catalog=" + glossary, "--output-dir", outputDir, "--cache", "bypass", "--format", "json"}
|
||||
for _, command := range []string{"preflight", "run"} {
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunWithOptions(append([]string{command}, common...), &stdout, &stderr, productionRunOptions(t, client))
|
||||
if code != 0 {
|
||||
t.Fatalf("%s status=%d stdout=%s stderr=%s", command, code, stdout.String(), stderr.String())
|
||||
}
|
||||
if command == "preflight" {
|
||||
var report preflightReport
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil || !report.Ready || len(client.snapshot()) != 1 {
|
||||
t.Fatalf("preflight = %#v, %v, calls=%d", report, err, len(client.snapshot()))
|
||||
}
|
||||
} else {
|
||||
var report runResult
|
||||
if err := json.Unmarshal([]byte(stdout.String()), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := readProductionJSON[dnd.SpellList](t, filepath.Join(report.OutputDirectory, "lanes", "spells.json"))
|
||||
if len(output.SpellCasts) != 0 {
|
||||
t.Fatalf("references synthesized events: %#v", output)
|
||||
}
|
||||
}
|
||||
}
|
||||
requests := client.snapshot()
|
||||
if len(requests) != 2 || !productionSchemaHasProperty(requests[0], "status") {
|
||||
t.Fatalf("expected one preflight probe and one run request, got %d", len(requests))
|
||||
}
|
||||
var found bool
|
||||
for _, request := range requests {
|
||||
if !productionSchemaHasProperty(request, "spell_casts") {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
var prompt strings.Builder
|
||||
for _, message := range request.Prompt.Messages {
|
||||
prompt.WriteString(message.Content)
|
||||
}
|
||||
for _, want := range []string{"Star", "Alice", "Verdant Tower", "Green Spire", "Aegis of Emberfall", "Emberfall Aegis"} {
|
||||
if !strings.Contains(prompt.String(), want) {
|
||||
t.Errorf("prompt missing %q", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(prompt.String(), "Not In Prompt") {
|
||||
t.Fatal("unselected collection reached model")
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("no domain extraction request observed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedReferencesFailBeforeProviderInRunAndPreflight(t *testing.T) {
|
||||
for _, test := range []struct{ name, party, glossary, spell, want string }{
|
||||
{"bad party", "{}", validSharedGlossary, validSharedGlossary, "party"},
|
||||
{"malformed party", "characters: [", validSharedGlossary, validSharedGlossary, "party"},
|
||||
{"bad glossary", validPartyYAML, "{}", validSharedGlossary, "glossary"},
|
||||
{"duplicate IDs", validPartyYAML, `{"schema_version":"maximumdirect.glossary.v1","collections":{"setting":{"entries":[{"id":"x","name":"A","category":"x"},{"id":"x","name":"B","category":"x"}]}}}`, validSharedGlossary, "duplicate"},
|
||||
{"missing selection", validPartyYAML, `{"schema_version":"maximumdirect.glossary.v1","collections":{}}`, validSharedGlossary, "setting"},
|
||||
{"spell collision", validPartyYAML, validSharedGlossary, `{"schema_version":"maximumdirect.glossary.v1","collections":{"custom":{"entries":[{"id":"a","name":"Alpha","category":"spell","aliases":["Shared"]},{"id":"b","name":"Beta","category":"spell","aliases":["Shared"]}]}}}`, "maps to spells"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
party := writeSharedReference(t, "party.yml", test.party)
|
||||
glossary := writeSharedReference(t, "glossary.json", test.glossary)
|
||||
spell := writeSharedReference(t, "spell.json", test.spell)
|
||||
configPath := sharedReferenceConfig(t, party, glossary, spell)
|
||||
client := &sharedReferenceClient{}
|
||||
for _, command := range []string{"run", "preflight"} {
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunWithOptions([]string{command, "dnd-session", "--config", configPath, "--input-file", repositoryPath("examples", "dnd-minimal", "transcript.json"), "--output-dir", filepath.Join(t.TempDir(), "output"), "--cache", "bypass", "--format", "json"}, &stdout, &stderr, productionRunOptions(t, client))
|
||||
if code == 0 || len(client.snapshot()) != 0 || !strings.Contains(strings.ToLower(stdout.String()+stderr.String()), test.want) {
|
||||
t.Fatalf("%s code=%d calls=%d stdout=%s stderr=%s", command, code, len(client.snapshot()), stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfflineValidationDoesNotReadSharedReferences(t *testing.T) {
|
||||
missing := filepath.Join(t.TempDir(), "missing.json")
|
||||
configPath := sharedReferenceConfig(t, missing, missing, missing)
|
||||
client := &sharedReferenceClient{}
|
||||
var stdout, stderr strings.Builder
|
||||
code := RunWithOptions([]string{"pipeline", "validate", "dnd-session", "--config", configPath}, &stdout, &stderr, productionRunOptions(t, client))
|
||||
if code != 0 || len(client.snapshot()) != 0 {
|
||||
t.Fatalf("offline validation status=%d stdout=%s stderr=%s", code, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ func TestProductionSpellCatalogValidationCoordinatesCorrections(t *testing.T) {
|
||||
wantRejected: true,
|
||||
},
|
||||
{
|
||||
name: "overlay spell becomes valid after correction",
|
||||
name: "shared glossary spell becomes valid after correction",
|
||||
responses: []string{
|
||||
productionSpellResponse("Unknown Spell"),
|
||||
productionSpellResponse("Aegis of Emberfall"),
|
||||
@@ -95,7 +95,7 @@ func TestProductionSpellCatalogValidationCoordinatesCorrections(t *testing.T) {
|
||||
}
|
||||
value := decodeAssembledOutput[dnd.SpellList](t, output.OutputFiles, "lanes/spells.json")
|
||||
if len(value.SpellCasts) != 1 || value.SpellCasts[0].Spell != tt.wantSpell {
|
||||
t.Fatalf("normalized spell list = %#v, want accepted overlay spell", value)
|
||||
t.Fatalf("normalized spell list = %#v, want accepted shared glossary spell", value)
|
||||
}
|
||||
if len(output.Diagnostics.Groups) != 2 || output.Diagnostics.Groups[0].ReasonCode != tt.wantAdvisoryCode {
|
||||
t.Fatalf("diagnostics = %#v, want terminal extract and normalize diagnostics", output.Diagnostics)
|
||||
|
||||
@@ -23,12 +23,12 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved := effective.ResolvedPipeline
|
||||
overlayPath := filepath.Join(t.TempDir(), "catalog.json")
|
||||
sharedGlossaryPath := filepath.Join(t.TempDir(), "catalog.json")
|
||||
for _, target := range []*pipeline.ResolvedReferenceTarget{&resolved.Steps[0].ArtifactLanes[0].ExtractReferences, &resolved.Steps[0].ArtifactLanes[0].NormalizeReferences} {
|
||||
matched := false
|
||||
for index := range target.Bindings {
|
||||
if target.Bindings[index].SlotName == spellcatalog.SpellCatalogReferenceSlot {
|
||||
target.Bindings[index].Source = overlayPath
|
||||
target.Bindings[index].Source = sharedGlossaryPath
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T)
|
||||
}
|
||||
materialize := func(contents string) pipeline.ResolvedPipeline {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(overlayPath, []byte(contents), 0600); err != nil {
|
||||
if err := os.WriteFile(sharedGlossaryPath, []byte(contents), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value, _, err := pipeline.MaterializeReferences(resolved, catalog, pipeline.ReferenceMaterializationOptions{ConfigPath: configPath, WorkingDir: filepath.Dir(configPath)})
|
||||
@@ -47,7 +47,7 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T)
|
||||
}
|
||||
return value
|
||||
}
|
||||
first, second := materialize(reorderedOverlayA), materialize(reorderedOverlayB)
|
||||
first, second := materialize(reorderedSharedGlossaryA), materialize(reorderedSharedGlossaryB)
|
||||
laneA, laneB := first.Steps[0].ArtifactLanes[0], second.Steps[0].ArtifactLanes[0]
|
||||
for _, pair := range [][2]pipeline.ResolvedReferenceTarget{
|
||||
{laneA.ExtractReferences, laneB.ExtractReferences},
|
||||
@@ -68,7 +68,7 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if catalogA.Digest() != catalogB.Digest() || !reflect.DeepEqual(catalogA.OverlayIDs(), []string{"campaign.a", "campaign.b"}) || !reflect.DeepEqual(catalogB.OverlayIDs(), catalogA.OverlayIDs()) || !reflect.DeepEqual(catalogA.PromptSpells(), catalogB.PromptSpells()) {
|
||||
if catalogA.Digest() != catalogB.Digest() || !reflect.DeepEqual(catalogA.CollectionNames(), []string{"spells"}) || !reflect.DeepEqual(catalogB.CollectionNames(), catalogA.CollectionNames()) || !reflect.DeepEqual(catalogA.PromptSpells(), catalogB.PromptSpells()) {
|
||||
t.Fatal("catalog ordering changed semantic recognition")
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,8 @@ func TestMaterializedSpellCatalogOrderingPreservesSemanticContents(t *testing.T)
|
||||
|
||||
func TestConfiguredSpellCatalogBindingChangesResolvedPipelineIdentity(t *testing.T) {
|
||||
base := productionSpellCatalogContractConfig(t)
|
||||
changed := strings.Replace(base, repositoryPath("examples", "dnd-complete", "spell-catalog.json"), filepath.Join(t.TempDir(), "alternate-spell-catalog.json"), 1)
|
||||
source := loadMaintainedExample(t, writeProductionContractConfig(t, base)).Pipelines["dnd-session"].Artifacts["spells"].Extract.References["spell_catalog"].Path
|
||||
changed := strings.Replace(base, source, filepath.Join(t.TempDir(), "alternate-glossary.json"), 1)
|
||||
if changed == base {
|
||||
t.Fatal("production configuration did not contain the maintained catalog binding")
|
||||
}
|
||||
@@ -103,7 +104,7 @@ func TestConfiguredSpellCatalogBindingChangesResolvedPipelineIdentity(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductionOverlayRunAlignsGroundingAndValidation(t *testing.T) {
|
||||
func TestProductionSharedGlossaryRunAlignsGroundingAndValidation(t *testing.T) {
|
||||
outputRoot := filepath.Join(t.TempDir(), "output")
|
||||
client := &productionFakeLLMClient{spellResponse: productionSpellResponse("Aegis of Emberfall")}
|
||||
configPath := writeProductionContractConfig(t, productionSpellCatalogContractConfig(t)+productionProviderConfiguration)
|
||||
@@ -129,7 +130,7 @@ func TestProductionOverlayRunAlignsGroundingAndValidation(t *testing.T) {
|
||||
}
|
||||
for _, fragment := range []string{`"canonical_name":"Aegis of Emberfall"`, `"aliases":["Emberfall Aegis"]`} {
|
||||
if !strings.Contains(prompt.String(), fragment) {
|
||||
t.Fatalf("catalog prompt omitted overlay recognition %q", fragment)
|
||||
t.Fatalf("catalog prompt omitted shared glossary recognition %q", fragment)
|
||||
}
|
||||
}
|
||||
artifact := readProductionJSON[dnd.SpellList](t, filepath.Join(report.OutputDirectory, "lanes", "spells.json"))
|
||||
@@ -138,12 +139,12 @@ func TestProductionOverlayRunAlignsGroundingAndValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
const reorderedOverlayA = `{
|
||||
"schema_version": "notarius.dnd.spell-catalog-overlay.v1",
|
||||
"catalogs": [
|
||||
{"id":"campaign.a","ruleset":"dnd-5e-2014","source":{"title":"Campaign A"},"spells":[{"name":"Aegis of Emberfall","aliases":["Emberfall Aegis"]}]},
|
||||
{"id":"campaign.b","ruleset":"dnd-5e-2014","source":{"title":"Campaign B"},"spells":[{"name":"Cinder Veil","aliases":["Veil of Cinder","Cinder Shroud"]}]}
|
||||
]
|
||||
const reorderedSharedGlossaryA = `{
|
||||
"schema_version": "maximumdirect.glossary.v1",
|
||||
"collections": {"spells": {"entries": [
|
||||
{"id":"a","name":"Aegis of Emberfall","category":"spell","aliases":["Emberfall Aegis"]},
|
||||
{"id":"b","name":"Cinder Veil","category":"spell","aliases":["Veil of Cinder","Cinder Shroud"]}
|
||||
]}}
|
||||
}`
|
||||
|
||||
const reorderedOverlayB = `{"catalogs":[{"spells":[{"aliases":["Cinder Shroud","Veil of Cinder"],"name":"Cinder Veil"}],"source":{"title":"Campaign B"},"ruleset":"dnd-5e-2014","id":"campaign.b"},{"spells":[{"aliases":["Emberfall Aegis"],"name":"Aegis of Emberfall"}],"source":{"title":"Campaign A"},"ruleset":"dnd-5e-2014","id":"campaign.a"}],"schema_version":"notarius.dnd.spell-catalog-overlay.v1"}`
|
||||
const reorderedSharedGlossaryB = `{"collections":{"spells":{"entries":[{"aliases":["Cinder Shroud","Veil of Cinder"],"name":"Cinder Veil","id":"b","category":"spell"},{"aliases":["Emberfall Aegis"],"name":"Aegis of Emberfall","id":"a","category":"spell"}]}},"schema_version":"maximumdirect.glossary.v1"}`
|
||||
|
||||
@@ -71,6 +71,7 @@ type ValidatorDocument struct {
|
||||
type ReferenceDocument struct {
|
||||
Path *string `yaml:"path,omitempty"`
|
||||
Artifact *ArtifactReferenceDocument `yaml:"artifact,omitempty"`
|
||||
Collections []string `yaml:"collections,omitempty"`
|
||||
}
|
||||
|
||||
type ArtifactReferenceDocument struct {
|
||||
|
||||
@@ -243,7 +243,11 @@ func documentReferencesToRuntime(documents map[string]ReferenceDocument) map[str
|
||||
continue
|
||||
}
|
||||
if document.Path != nil {
|
||||
references[name] = pipeline.ExternalReference(*document.Path)
|
||||
reference := pipeline.ExternalReference(*document.Path)
|
||||
if document.Collections != nil {
|
||||
reference.Collections = append([]string{}, document.Collections...)
|
||||
}
|
||||
references[name] = reference
|
||||
}
|
||||
}
|
||||
return references
|
||||
|
||||
@@ -403,6 +403,14 @@ func validateDocumentReferences(references map[string]ReferenceDocument, path co
|
||||
sourcePath := path.Key(name)
|
||||
hasPath := source.Path != nil
|
||||
hasArtifact := source.Artifact != nil
|
||||
for index, collection := range source.Collections {
|
||||
if collection == "" {
|
||||
validation.Error(sourcePath.Key("collections").Index(index), "must not be empty")
|
||||
}
|
||||
}
|
||||
if hasArtifact && source.Collections != nil {
|
||||
validation.Error(sourcePath.Key("collections"), "is only supported with an external path")
|
||||
}
|
||||
if hasPath == hasArtifact {
|
||||
validation.Error(sourcePath, "must select exactly one reference source")
|
||||
continue
|
||||
|
||||
57
internal/core/config/reference_collections_test.go
Normal file
57
internal/core/config/reference_collections_test.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestReferenceCollectionsBindingAndInspection(t *testing.T) {
|
||||
loaded, err := loadConfigSource(configkit.Bytes("settings.yml", []byte(`version: 6
|
||||
pipelines:
|
||||
main:
|
||||
input: {module: input}
|
||||
references:
|
||||
omitted: {path: a.yml}
|
||||
"null": {path: b.yml, collections: null}
|
||||
empty: {path: c.yml, collections: []}
|
||||
named: {path: d.yml, collections: [spells, " Mixed "]}
|
||||
`)), LoadOptions{})
|
||||
if err != nil {
|
||||
if native, ok := err.(*configkit.LoadError); ok {
|
||||
t.Fatalf("%v: %#v", err, native.Diagnostics())
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
refs := loaded.Config.Pipelines["main"].References
|
||||
if refs["omitted"].Collections != nil || refs["null"].Collections != nil || refs["empty"].Collections == nil || len(refs["empty"].Collections) != 0 || refs["named"].Collections[1] != " Mixed " {
|
||||
t.Fatalf("unexpected collection selections: %#v", refs)
|
||||
}
|
||||
copy := loaded.RuntimeConfig()
|
||||
copy.Pipelines["main"].References["named"].Collections[0] = "changed"
|
||||
if refs["named"].Collections[0] != "spells" {
|
||||
t.Fatal("detached runtime selection mutated source")
|
||||
}
|
||||
var effective bytes.Buffer
|
||||
if err := loaded.WriteEffective(&effective); err != nil || !strings.Contains(effective.String(), "collections: []") {
|
||||
t.Fatalf("effective config = %s, %v", effective.String(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceCollectionsRejectInvalidInput(t *testing.T) {
|
||||
for _, value := range []string{
|
||||
"{path: a.yml, collections: [\"\"]}",
|
||||
"{path: a.yml, collections: nope}",
|
||||
"{path: a.yml, collections: [3]}",
|
||||
"{artifact: {step: earlier, lane: output}, collections: []}",
|
||||
} {
|
||||
t.Run(value, func(t *testing.T) {
|
||||
content := "version: 6\npipelines:\n main:\n input: {module: input}\n artifacts:\n output:\n extract:\n module: extract\n references:\n ref: " + value + "\n"
|
||||
if _, err := loadConfigSource(configkit.Bytes("settings.yml", []byte(content)), LoadOptions{}); err == nil {
|
||||
t.Fatal("accepted invalid reference selection")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ type ReferenceProducer struct {
|
||||
|
||||
type ReferenceItem struct {
|
||||
SlotName string `json:"slot_name"`
|
||||
Collections []string `json:"collections,omitempty"`
|
||||
MediaType string `json:"media_type,omitempty"`
|
||||
Content []byte `json:"-"`
|
||||
Digest string `json:"digest,omitempty"`
|
||||
@@ -122,6 +123,9 @@ type ReferenceItem struct {
|
||||
|
||||
func CloneReferenceItem(item ReferenceItem) ReferenceItem {
|
||||
item.Content = append([]byte(nil), item.Content...)
|
||||
if item.Collections != nil {
|
||||
item.Collections = append([]string{}, item.Collections...)
|
||||
}
|
||||
item.ArtifactSchema = CloneArtifactSchema(item.ArtifactSchema)
|
||||
return item
|
||||
}
|
||||
@@ -129,6 +133,7 @@ func CloneReferenceItem(item ReferenceItem) ReferenceItem {
|
||||
func (item ReferenceItem) MarshalJSON() ([]byte, error) {
|
||||
type referenceItemJSON struct {
|
||||
SlotName string `json:"slot_name"`
|
||||
Collections *[]string `json:"collections,omitempty"`
|
||||
MediaType string `json:"media_type,omitempty"`
|
||||
Digest string `json:"digest,omitempty"`
|
||||
Origin ReferenceOrigin `json:"origin"`
|
||||
@@ -147,6 +152,9 @@ func (item ReferenceItem) MarshalJSON() ([]byte, error) {
|
||||
BindingSource: item.BindingSource,
|
||||
ArtifactKind: item.ArtifactKind,
|
||||
}
|
||||
if item.Collections != nil {
|
||||
encoded.Collections = &item.Collections
|
||||
}
|
||||
if item.ArtifactSchema.ID != "" || item.ArtifactSchema.Name != "" || item.ArtifactSchema.Version != "" || len(item.ArtifactSchema.JSONSchema) > 0 {
|
||||
schema := CloneArtifactSchema(item.ArtifactSchema)
|
||||
encoded.ArtifactSchema = &schema
|
||||
|
||||
@@ -123,6 +123,34 @@ func TestReferenceItemJSONOmitsContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceItemCollectionSelectionCopyAndJSON(t *testing.T) {
|
||||
for _, selection := range [][]string{nil, {}, {"campaign"}} {
|
||||
item := ReferenceItem{SlotName: "glossary", Collections: selection}
|
||||
clone := CloneReferenceItem(item)
|
||||
if (clone.Collections == nil) != (selection == nil) || len(clone.Collections) != len(selection) {
|
||||
t.Fatalf("cloned selection = %#v, want %#v", clone.Collections, selection)
|
||||
}
|
||||
encoded, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(encoded, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, present := fields["collections"]
|
||||
if present != (selection != nil) {
|
||||
t.Fatalf("encoded selection = %s", encoded)
|
||||
}
|
||||
if len(selection) > 0 {
|
||||
clone.Collections[0] = "changed"
|
||||
if selection[0] != "campaign" {
|
||||
t.Fatal("copy mutated original selection")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMInputMaterialCopiesContentAndOmitsContentFromJSON(t *testing.T) {
|
||||
content := []byte("raw source bytes")
|
||||
material := NewLLMInputMaterial("transcript", "application/json", content, "sha256:source", "file:///tmp/source.json")
|
||||
|
||||
@@ -27,6 +27,8 @@ type ModuleSpec struct {
|
||||
// Prompts lists statically selected initial/correction IDs shared with the
|
||||
// module's request builders. Dynamic selections are checked at execution.
|
||||
Prompts []string
|
||||
// InitialPrompts identifies requests that independently select a target.
|
||||
InitialPrompts []string
|
||||
ArtifactKind contracts.ArtifactKind
|
||||
Provides []string
|
||||
Requires []string
|
||||
@@ -40,6 +42,7 @@ func normalizeModuleSpec(spec ModuleSpec) ModuleSpec {
|
||||
Stage: spec.Stage,
|
||||
ExecutionClass: executionClass,
|
||||
Prompts: normalizeStringSet(spec.Prompts),
|
||||
InitialPrompts: normalizeStringSet(spec.InitialPrompts),
|
||||
ArtifactKind: normalizeArtifactKind(spec.ArtifactKind),
|
||||
Provides: normalizeCapabilities(spec.Provides),
|
||||
Requires: normalizeCapabilities(spec.Requires),
|
||||
@@ -78,6 +81,7 @@ func cloneModuleSpec(spec ModuleSpec) ModuleSpec {
|
||||
Stage: spec.Stage,
|
||||
ExecutionClass: spec.ExecutionClass,
|
||||
Prompts: append([]string(nil), spec.Prompts...),
|
||||
InitialPrompts: append([]string(nil), spec.InitialPrompts...),
|
||||
ArtifactKind: spec.ArtifactKind,
|
||||
Provides: append([]string(nil), spec.Provides...),
|
||||
Requires: append([]string(nil), spec.Requires...),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -10,6 +11,30 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// ParseSource parses and validates input using the prepared input adapter.
|
||||
func (prepared *PreparedPipeline) ParseSource(ctx context.Context, request contracts.ParseRequest) (*source.SourceDocument, error) {
|
||||
metadata, err := cloneMetadata(request.Metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clone input adapter metadata: %w", err)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Metadata = metadata
|
||||
request.LLMProfile = prepared.resolved.Input.LLMProfile
|
||||
doc, err := prepared.input.Parse(ctx, request)
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return nil, ctxErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse input with adapter %q: %w", prepared.input.Key(), err)
|
||||
}
|
||||
if err := source.ValidateDocument(doc); err != nil {
|
||||
return nil, fmt.Errorf("validate source document: %w", err)
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// PreparedPipeline owns the constructed, run-local implementation set for one
|
||||
// resolved pipeline. Its implementation values are private so execution cannot
|
||||
// replace or reconfigure them after preparation.
|
||||
|
||||
@@ -25,10 +25,24 @@ type ReferenceBinding struct {
|
||||
LaneID string `json:"lane_id,omitempty"`
|
||||
SlotName string `json:"slot_name"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Collections []string `json:"collections,omitempty"`
|
||||
Artifact *ArtifactReference `json:"artifact,omitempty"`
|
||||
BindingSource string `json:"binding_source,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON preserves the distinction between default and empty selections.
|
||||
func (binding ReferenceBinding) MarshalJSON() ([]byte, error) {
|
||||
type bindingFields ReferenceBinding
|
||||
var collections *[]string
|
||||
if binding.Collections != nil {
|
||||
collections = &binding.Collections
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
bindingFields
|
||||
Collections *[]string `json:"collections,omitempty"`
|
||||
}{bindingFields: bindingFields(binding), Collections: collections})
|
||||
}
|
||||
|
||||
type ReferenceUnbind struct {
|
||||
Stage ModuleStage `json:"stage,omitempty"`
|
||||
LaneID string `json:"lane_id,omitempty"`
|
||||
|
||||
@@ -75,6 +75,9 @@ func cloneReferenceSources(references map[string]ReferenceSource) map[string]Ref
|
||||
}
|
||||
|
||||
func cloneReferenceSource(source ReferenceSource) ReferenceSource {
|
||||
if source.Collections != nil {
|
||||
source.Collections = append([]string{}, source.Collections...)
|
||||
}
|
||||
if source.Artifact != nil {
|
||||
artifact := *source.Artifact
|
||||
source.Artifact = &artifact
|
||||
|
||||
@@ -39,6 +39,7 @@ type ArtifactReference struct {
|
||||
type ReferenceSource struct {
|
||||
Path string `json:"path,omitempty"`
|
||||
Artifact *ArtifactReference `json:"artifact,omitempty"`
|
||||
Collections []string `json:"collections,omitempty"`
|
||||
}
|
||||
|
||||
func ExternalReference(path string) ReferenceSource {
|
||||
@@ -64,10 +65,19 @@ func (source ReferenceSource) MarshalJSON() ([]byte, error) {
|
||||
return nil, fmt.Errorf("reference source must not contain both an external path and an artifact selector")
|
||||
}
|
||||
if source.Artifact != nil {
|
||||
if source.Collections != nil {
|
||||
return nil, fmt.Errorf("collection selection requires an external path")
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
Artifact *ArtifactReference `json:"artifact"`
|
||||
}{Artifact: source.Artifact})
|
||||
}
|
||||
if source.Collections != nil {
|
||||
return json.Marshal(struct {
|
||||
Path string `json:"path"`
|
||||
Collections []string `json:"collections"`
|
||||
}{Path: source.Path, Collections: source.Collections})
|
||||
}
|
||||
return json.Marshal(source.Path)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,17 @@ import (
|
||||
)
|
||||
|
||||
func referenceTarget(stage ModuleStage, laneID string, module string, bindings []ReferenceBinding) ResolvedReferenceTarget {
|
||||
bindings = append([]ReferenceBinding(nil), bindings...)
|
||||
for i := range bindings {
|
||||
if bindings[i].Collections != nil {
|
||||
bindings[i].Collections = append([]string{}, bindings[i].Collections...)
|
||||
}
|
||||
}
|
||||
return ResolvedReferenceTarget{
|
||||
Stage: stage,
|
||||
LaneID: strings.TrimSpace(laneID),
|
||||
Module: strings.TrimSpace(module),
|
||||
Bindings: append([]ReferenceBinding(nil), bindings...),
|
||||
Bindings: bindings,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +152,11 @@ func resolveReferenceTargetBindings(target referenceResolutionTarget) ([]Referen
|
||||
if strings.TrimSpace(source) == "" {
|
||||
source = contracts.ReferenceBindingSourceCLI
|
||||
}
|
||||
if err := addReferenceBinding(target, slotByName, bindings, override.SlotName, ExternalReference(override.Source), strings.TrimSpace(source)); err != nil {
|
||||
replacement := ExternalReference(override.Source)
|
||||
if previous, exists := bindings[strings.TrimSpace(override.SlotName)]; exists && previous.Artifact == nil && previous.Collections != nil {
|
||||
replacement.Collections = append([]string{}, previous.Collections...)
|
||||
}
|
||||
if err := addReferenceBinding(target, slotByName, bindings, override.SlotName, replacement, strings.TrimSpace(source)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -187,12 +197,20 @@ func normalizeTargetReferenceSource(target referenceResolutionTarget, slotName s
|
||||
if slotName == "" {
|
||||
return "", ReferenceSource{}, fmt.Errorf("%s reference slot name must not be empty", referenceTargetErrorContext(target))
|
||||
}
|
||||
for _, name := range source.Collections {
|
||||
if name == "" {
|
||||
return "", ReferenceSource{}, fmt.Errorf("%s reference slot %q collection name must not be empty", referenceTargetErrorContext(target), slotName)
|
||||
}
|
||||
}
|
||||
if source.Artifact == nil {
|
||||
source.Path = strings.TrimSpace(source.Path)
|
||||
if source.Path == "" {
|
||||
return "", ReferenceSource{}, fmt.Errorf("%s reference slot %q source must not be empty", referenceTargetErrorContext(target), slotName)
|
||||
}
|
||||
} else {
|
||||
if source.Collections != nil {
|
||||
return "", ReferenceSource{}, fmt.Errorf("%s reference slot %q collection selection requires an external path", referenceTargetErrorContext(target), slotName)
|
||||
}
|
||||
if strings.TrimSpace(source.Path) != "" {
|
||||
return "", ReferenceSource{}, fmt.Errorf("%s reference slot %q must contain exactly one source form", referenceTargetErrorContext(target), slotName)
|
||||
}
|
||||
@@ -222,6 +240,9 @@ func addReferenceBinding(target referenceResolutionTarget, slots map[string]cont
|
||||
binding.Artifact = source.Artifact
|
||||
} else {
|
||||
binding.Source = source.Path
|
||||
if source.Collections != nil {
|
||||
binding.Collections = append([]string{}, source.Collections...)
|
||||
}
|
||||
}
|
||||
bindings[slotName] = binding
|
||||
return nil
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func TestReferenceSourceMapsConflictPreservesTrimmedSourceKinds(t *testing.T) {
|
||||
@@ -35,6 +38,71 @@ func TestReferenceSourceMapsConflictPreservesTrimmedSourceKinds(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceCollectionResolutionAndCopy(t *testing.T) {
|
||||
pipelineSource := ReferenceSource{Path: "base.yml", Collections: []string{"base"}}
|
||||
localSource := ReferenceSource{Path: "local.yml", Collections: []string{}}
|
||||
target := referenceResolutionTarget{
|
||||
PipelineID: "demo", Stage: StageExtract, Module: "extractor",
|
||||
Slots: []contracts.ReferenceSlot{{Name: "glossary"}},
|
||||
PipelineReferences: map[string]ReferenceSource{"glossary": pipelineSource},
|
||||
LocalReferences: map[string]ReferenceSource{"glossary": localSource},
|
||||
}
|
||||
bindings, err := resolveReferenceTargetBindings(target)
|
||||
if err != nil || len(bindings) != 1 || bindings[0].Source != "local.yml" || bindings[0].Collections == nil || len(bindings[0].Collections) != 0 {
|
||||
t.Fatalf("local binding = %#v, %v", bindings, err)
|
||||
}
|
||||
target.LocalReferences["glossary"] = ReferenceSource{Path: "other.yml"}
|
||||
bindings, err = resolveReferenceTargetBindings(target)
|
||||
if err != nil || bindings[0].Collections != nil {
|
||||
t.Fatalf("replacement inherited collections: %#v, %v", bindings, err)
|
||||
}
|
||||
target.LocalReferences = nil
|
||||
bindings, err = resolveReferenceTargetBindings(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bindings[0].Collections[0] = "changed"
|
||||
if pipelineSource.Collections[0] != "base" {
|
||||
t.Fatal("binding selection aliases input")
|
||||
}
|
||||
profile := ClonePipelineProfile(PipelineProfile{References: map[string]ReferenceSource{"glossary": pipelineSource, "empty": localSource}})
|
||||
profile.References["glossary"].Collections[0] = "changed"
|
||||
if pipelineSource.Collections[0] != "base" || profile.References["empty"].Collections == nil {
|
||||
t.Fatal("profile clone lost selection isolation or explicit emptiness")
|
||||
}
|
||||
withEmpty, err := json.Marshal(localSource)
|
||||
if err != nil || !strings.Contains(string(withEmpty), `"collections":[]`) {
|
||||
t.Fatalf("encoded reference = %s, %v", withEmpty, err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
selection []string
|
||||
wantEmpty bool
|
||||
}{{nil, false}, {[]string{}, true}} {
|
||||
encoded, err := json.Marshal(ReferenceBinding{SlotName: "glossary", Collections: test.selection})
|
||||
if err != nil || strings.Contains(string(encoded), `"collections":[]`) != test.wantEmpty {
|
||||
t.Fatalf("encoded binding = %s, %v", encoded, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceOverrideKeepsTargetCollectionSelection(t *testing.T) {
|
||||
for _, selection := range [][]string{nil, {}, {"campaign"}} {
|
||||
target := referenceResolutionTarget{
|
||||
PipelineID: "demo", LaneID: "lane", Stage: StageExtract, Module: "extractor",
|
||||
Slots: []contracts.ReferenceSlot{{Name: "glossary"}},
|
||||
LocalReferences: map[string]ReferenceSource{"glossary": {Path: "old.yml", Collections: selection}},
|
||||
Options: ResolveOptions{ReferenceOverrides: []ReferenceBinding{{Stage: StageExtract, LaneID: "lane", SlotName: "glossary", Source: "new.yml"}}},
|
||||
}
|
||||
bindings, err := resolveReferenceTargetBindings(target)
|
||||
if err != nil || len(bindings) != 1 || bindings[0].Source != "new.yml" || (bindings[0].Collections == nil) != (selection == nil) || len(bindings[0].Collections) != len(selection) {
|
||||
t.Fatalf("override with %#v = %#v, %v", selection, bindings, err)
|
||||
}
|
||||
if len(selection) > 0 && bindings[0].Collections[0] != selection[0] {
|
||||
t.Fatalf("selection changed: %#v", bindings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTargetReferenceSourceOwnsAndValidatesSelector(t *testing.T) {
|
||||
target := referenceResolutionTarget{PipelineID: "demo", StepID: "consumer", LaneID: "lane", Stage: StageExtract, Module: "extractor"}
|
||||
input := ReferenceSource{Artifact: &ArtifactReference{Step: " producer ", Lane: " output "}}
|
||||
|
||||
@@ -170,6 +170,9 @@ func materializeReferenceTarget(
|
||||
SizeBytes: int64(len(content)),
|
||||
BindingSource: strings.TrimSpace(binding.BindingSource),
|
||||
}
|
||||
if binding.Collections != nil {
|
||||
item.Collections = append([]string{}, binding.Collections...)
|
||||
}
|
||||
set.Slots[slotName] = contracts.ResolvedReferenceSlot{
|
||||
Slot: cloneReferenceSlot(slot),
|
||||
Items: []contracts.ReferenceItem{item},
|
||||
@@ -369,6 +372,9 @@ func CloneReferenceTarget(in ResolvedReferenceTarget) ResolvedReferenceTarget {
|
||||
out.Bindings = make([]ReferenceBinding, len(in.Bindings))
|
||||
for i, binding := range in.Bindings {
|
||||
out.Bindings[i] = binding
|
||||
if binding.Collections != nil {
|
||||
out.Bindings[i].Collections = append([]string{}, binding.Collections...)
|
||||
}
|
||||
if binding.Artifact != nil {
|
||||
artifact := *binding.Artifact
|
||||
out.Bindings[i].Artifact = &artifact
|
||||
|
||||
@@ -344,6 +344,30 @@ func TestMaterializeReferencesAcceptsDeclaredJSONMediaType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaterializeReferencesCarriesCollectionsWithoutChangingContent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
content := []byte("collections: {campaign: {entries: []}}\n")
|
||||
writeReferenceFile(t, filepath.Join(dir, "terms.yml"), content)
|
||||
slot := contracts.ReferenceSlot{Name: "glossary", AcceptedMediaTypes: []string{"application/yaml"}}
|
||||
resolved := resolvedPipelineWithReference(t, "glossary", "terms.yml", contracts.ReferenceBindingSourceConfig, slot)
|
||||
resolved.Steps[0].ArtifactLanes[0].ExtractReferences.Bindings[0].Collections = []string{"campaign"}
|
||||
materialized, _, err := MaterializeReferences(resolved, referenceCatalog(t, []contracts.ReferenceSlot{slot}), ReferenceMaterializationOptions{ConfigPath: filepath.Join(dir, "config.yml")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := materialized.Steps[0].ArtifactLanes[0].ExtractReferences
|
||||
item := target.ReferenceSet.Slots["glossary"].Items[0]
|
||||
if string(item.Content) != string(content) || item.Digest != referenceDigest(content) || len(item.Collections) != 1 || item.Collections[0] != "campaign" {
|
||||
t.Fatalf("materialized item = %#v", item)
|
||||
}
|
||||
clone := CloneReferenceTarget(target)
|
||||
clone.Bindings[0].Collections[0] = "changed"
|
||||
clone.ReferenceSet.Slots["glossary"].Items[0].Collections[0] = "changed"
|
||||
if target.Bindings[0].Collections[0] != "campaign" || item.Collections[0] != "campaign" {
|
||||
t.Fatal("cloned selections alias original")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaterializeReferencesAcceptsDeclaredYAMLMediaType(t *testing.T) {
|
||||
configDir := t.TempDir()
|
||||
path := filepath.Join(configDir, "roster.yaml")
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
func prepareRunSource(ctx context.Context, input *RunInput) (*source.SourceDocument, error) {
|
||||
debugRecorder := input.Debug
|
||||
adapter := input.Prepared.input
|
||||
var doc *source.SourceDocument
|
||||
sourceStarted := time.Now().UTC()
|
||||
if debugRecorder.Enabled() {
|
||||
if err := writeDebugTimed(debugRecorder, "source/input.json", debugTimedEnvelope{
|
||||
@@ -30,25 +29,12 @@ func prepareRunSource(ctx context.Context, input *RunInput) (*source.SourceDocum
|
||||
return nil, fmt.Errorf("write source debug artifact: %w", err)
|
||||
}
|
||||
}
|
||||
requestMetadata, err := cloneMetadata(input.Metadata)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clone input adapter metadata: %w", err)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc, err = adapter.Parse(ctx, contracts.ParseRequest{
|
||||
doc, err := input.Prepared.ParseSource(ctx, contracts.ParseRequest{
|
||||
SourceID: input.SourceID, Path: input.Path, Raw: input.RawInput,
|
||||
LLMProfile: input.pipeline.Input.LLMProfile, Metadata: requestMetadata,
|
||||
Metadata: input.Metadata,
|
||||
})
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return nil, ctxErr
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse input with adapter %q: %w", adapter.Key(), err)
|
||||
}
|
||||
if err := source.ValidateDocument(doc); err != nil {
|
||||
return nil, fmt.Errorf("validate source document: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
index := source.NewDocumentIndex(doc)
|
||||
input.sourceIndex = &index
|
||||
|
||||
48
internal/framework/pipeline/source_preparation_test.go
Normal file
48
internal/framework/pipeline/source_preparation_test.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
type sourcePreparationAdapter struct {
|
||||
doc *source.SourceDocument
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (*sourcePreparationAdapter) Key() string { return "test/input" }
|
||||
|
||||
func (adapter *sourcePreparationAdapter) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) {
|
||||
adapter.calls++
|
||||
return adapter.doc, adapter.err
|
||||
}
|
||||
|
||||
func TestPreparedPipelineParsesAndValidatesSource(t *testing.T) {
|
||||
adapter := &sourcePreparationAdapter{doc: typedTestDocumentWithUnits(1)}
|
||||
prepared := &PreparedPipeline{input: adapter}
|
||||
doc, err := prepared.ParseSource(context.Background(), contracts.ParseRequest{})
|
||||
if err != nil || doc != adapter.doc || adapter.calls != 1 {
|
||||
t.Fatalf("ParseSource() = %v, %v; calls = %d", doc, err, adapter.calls)
|
||||
}
|
||||
adapter.doc = &source.SourceDocument{}
|
||||
if _, err := prepared.ParseSource(context.Background(), contracts.ParseRequest{}); err == nil || !strings.Contains(err.Error(), "validate source document") {
|
||||
t.Fatalf("invalid document error = %v", err)
|
||||
}
|
||||
cause := errors.New("adapter failure")
|
||||
adapter.err = cause
|
||||
if _, err := prepared.ParseSource(context.Background(), contracts.ParseRequest{}); !errors.Is(err, cause) {
|
||||
t.Fatalf("adapter error = %v, want original cause", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
calls := adapter.calls
|
||||
if _, err := prepared.ParseSource(ctx, contracts.ParseRequest{}); !errors.Is(err, context.Canceled) || adapter.calls != calls {
|
||||
t.Fatalf("canceled parse error = %v; calls = %d", err, adapter.calls)
|
||||
}
|
||||
}
|
||||
27
internal/integrations/domainrefs/load.go
Normal file
27
internal/integrations/domainrefs/load.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Package domainrefs loads shared domain reference documents.
|
||||
package domainrefs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
// Load resolves a materialized shared reference using ConfigKit's native rules.
|
||||
func Load(label, mediaType string, content []byte) (map[string]any, error) {
|
||||
switch mediaType {
|
||||
case "application/json":
|
||||
if !json.Valid(content) {
|
||||
return nil, fmt.Errorf("reference %q: invalid JSON syntax", label)
|
||||
}
|
||||
case "application/yaml", "application/x-yaml":
|
||||
default:
|
||||
return nil, fmt.Errorf("reference %q: unsupported media type %q", label, mediaType)
|
||||
}
|
||||
result, err := configkit.Load[map[string]any](configkit.Bytes(label, content))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reference %q: %w", label, err)
|
||||
}
|
||||
return result.Config, nil
|
||||
}
|
||||
70
internal/integrations/domainrefs/load_test.go
Normal file
70
internal/integrations/domainrefs/load_test.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package domainrefs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestLoadEquivalentStructuredReferences(t *testing.T) {
|
||||
yaml := []byte("name: Example\nnumber: 42\nfraction: 1.5\ninstruction: data\nnested: {enabled: true}\n")
|
||||
json := []byte(`{"name":"Example","number":42,"fraction":1.5,"instruction":"data","nested":{"enabled":true}}`)
|
||||
want, err := Load("example.yml", "application/yaml", yaml)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, input := range []struct {
|
||||
media string
|
||||
data []byte
|
||||
}{
|
||||
{"application/x-yaml", yaml}, {"application/json", json},
|
||||
} {
|
||||
got, err := Load("example", input.media, input.data)
|
||||
if err != nil || !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("Load(%s) = %#v, %v; want %#v", input.media, got, err, want)
|
||||
}
|
||||
}
|
||||
if want["number"] != int64(42) || want["fraction"] != float64(1.5) || want["instruction"] != "data" {
|
||||
t.Fatalf("unexpected native values: %#v", want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPreservesNativeFailure(t *testing.T) {
|
||||
_, err := Load("roster.yml", "application/yaml", []byte("name: one\nname: two\n"))
|
||||
var native *configkit.LoadError
|
||||
if !errors.As(err, &native) || !strings.Contains(err.Error(), "roster.yml") {
|
||||
t.Fatalf("expected contextual native error, got %v", err)
|
||||
}
|
||||
if _, err := Load("roster.json", "application/json", []byte("name: value")); err == nil {
|
||||
t.Fatal("JSON media accepted YAML syntax")
|
||||
}
|
||||
_, err = Load("roster.json", "application/json", []byte(`{"name":"one","name":"two"}`))
|
||||
if !errors.As(err, &native) {
|
||||
t.Fatalf("expected native error for duplicate JSON keys, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNativeStructuralControls(t *testing.T) {
|
||||
got, err := Load("reference.yml", "application/yaml", []byte(`entries:
|
||||
parent: {name: inherited}
|
||||
child: {extends: parent, instruction: ordinary}
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child := got["entries"].(map[string]any)["child"].(map[string]any)
|
||||
if child["name"] != "inherited" || child["instruction"] != "ordinary" {
|
||||
t.Fatalf("unexpected resolved child: %#v", child)
|
||||
}
|
||||
if _, ok := child["extends"]; ok {
|
||||
t.Fatalf("inheritance control was not consumed: %#v", child)
|
||||
}
|
||||
_, err = Load("reference.yml", "application/yaml", []byte("config: {imports: [{path: missing.yml}]}\n"))
|
||||
var native *configkit.LoadError
|
||||
if !errors.As(err, &native) {
|
||||
t.Fatalf("expected native disabled-import error, got %v", err)
|
||||
}
|
||||
}
|
||||
123
internal/integrations/domainrefs/validate.go
Normal file
123
internal/integrations/domainrefs/validate.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package domainrefs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/assets"
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
|
||||
const (
|
||||
glossaryID = "https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json"
|
||||
partyID = "https://schemas.maximumdirect.net/rpg/party/v0.2.0/schema.json"
|
||||
)
|
||||
|
||||
var compiled struct {
|
||||
sync.Once
|
||||
glossary, party *jsonschema.Schema
|
||||
err error
|
||||
}
|
||||
|
||||
type offlineLoader struct{}
|
||||
|
||||
func (offlineLoader) Load(url string) (any, error) {
|
||||
return nil, fmt.Errorf("schema resource %q is not bundled", url)
|
||||
}
|
||||
|
||||
func compileSchemas() {
|
||||
compiler := jsonschema.NewCompiler()
|
||||
compiler.UseLoader(offlineLoader{})
|
||||
for _, resource := range []struct{ id, path string }{
|
||||
{glossaryID, "shared-domain/glossary/v0.2.0/schema.json"},
|
||||
{partyID, "shared-domain/rpg/party/v0.2.0/schema.json"},
|
||||
} {
|
||||
content, err := fs.ReadFile(assets.FS(), resource.path)
|
||||
if err != nil {
|
||||
compiled.err = err
|
||||
return
|
||||
}
|
||||
doc, err := jsonschema.UnmarshalJSON(bytes.NewReader(content))
|
||||
if err == nil {
|
||||
err = compiler.AddResource(resource.id, doc)
|
||||
}
|
||||
if err != nil {
|
||||
compiled.err = fmt.Errorf("register schema %s: %w", resource.id, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
compiled.glossary, compiled.err = compiler.Compile(glossaryID)
|
||||
if compiled.err == nil {
|
||||
compiled.party, compiled.err = compiler.Compile(partyID)
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateGlossary validates the entire document and per-collection entry IDs.
|
||||
func ValidateGlossary(doc map[string]any) error {
|
||||
compiled.Do(compileSchemas)
|
||||
if compiled.err != nil {
|
||||
return fmt.Errorf("prepare shared schemas: %w", compiled.err)
|
||||
}
|
||||
if err := compiled.glossary.Validate(doc); err != nil {
|
||||
return fmt.Errorf("invalid shared glossary: %w", err)
|
||||
}
|
||||
collections := doc["collections"].(map[string]any)
|
||||
names := make([]string, 0, len(collections))
|
||||
for name := range collections {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
entries := collections[name].(map[string]any)["entries"].([]any)
|
||||
ids := make(map[string]bool, len(entries))
|
||||
for _, raw := range entries {
|
||||
id := raw.(map[string]any)["id"].(string)
|
||||
if ids[id] {
|
||||
return fmt.Errorf("glossary collection %q has duplicate entry ID %q", name, id)
|
||||
}
|
||||
ids[id] = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateParty validates the complete resolved party document.
|
||||
func ValidateParty(doc map[string]any) error {
|
||||
compiled.Do(compileSchemas)
|
||||
if compiled.err != nil {
|
||||
return fmt.Errorf("prepare shared schemas: %w", compiled.err)
|
||||
}
|
||||
if err := compiled.party.Validate(doc); err != nil {
|
||||
return fmt.Errorf("invalid shared party: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SelectCollections returns sorted, unique collection names. A nil selection
|
||||
// uses the caller's defaults; an explicit empty selection remains empty. The
|
||||
// caller chooses defaults appropriate to its task and validates the document first.
|
||||
func SelectCollections(doc map[string]any, selection, defaults []string) ([]string, error) {
|
||||
if selection == nil {
|
||||
selection = defaults
|
||||
}
|
||||
collections := doc["collections"].(map[string]any)
|
||||
seen := make(map[string]bool, len(selection))
|
||||
result := make([]string, 0, len(selection))
|
||||
for _, name := range selection {
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("collection name must not be empty")
|
||||
}
|
||||
if _, ok := collections[name]; !ok {
|
||||
return nil, fmt.Errorf("selected collection %q does not exist", name)
|
||||
}
|
||||
if !seen[name] {
|
||||
seen[name] = true
|
||||
result = append(result, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
107
internal/integrations/domainrefs/validate_test.go
Normal file
107
internal/integrations/domainrefs/validate_test.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package domainrefs
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func document(t *testing.T, source string) map[string]any {
|
||||
t.Helper()
|
||||
doc, err := Load("fixture.json", "application/json", []byte(source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return doc
|
||||
}
|
||||
|
||||
func TestGlossaryConformance(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, source string
|
||||
valid bool
|
||||
}{
|
||||
{"empty", `{"schema_version":"maximumdirect.glossary.v1","collections":{}}`, true},
|
||||
{"extensions and aliases", `{"schema_version":"maximumdirect.glossary.v1","extension":{"count":42},"collections":{"a":{"extension":true,"provenance":{"extension":1.5},"entries":[{"id":"x","name":"N","category":"c","extension":{"instruction":"data"}},{"id":"y","name":"N","category":"c","aliases":null},{"id":"z","name":"N","category":"c","aliases":[]}]},"b":{"entries":[{"id":"x","name":"N","category":"c","aliases":["Alias"]}]}}}`, true},
|
||||
{"empty entries", `{"schema_version":"maximumdirect.glossary.v1","collections":{"a":{"entries":[]}}}`, true},
|
||||
{"duplicate IDs", `{"schema_version":"maximumdirect.glossary.v1","collections":{"a":{"entries":[{"id":"x","name":"N","category":"c"},{"id":"x","name":"N","category":"c"}]}}}`, false},
|
||||
{"invalid unselected collection", `{"schema_version":"maximumdirect.glossary.v1","collections":{"a":{"entries":[]},"b":{"entries":[{"id":"x","name":"N","category":"c","aliases":5}]}}}`, false},
|
||||
{"invalid provenance", `{"schema_version":"maximumdirect.glossary.v1","collections":{"a":{"entries":[],"provenance":null}}}`, false},
|
||||
{"wrong marker", `{"schema_version":"wrong","collections":{}}`, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
doc := document(t, test.source)
|
||||
err := ValidateGlossary(doc)
|
||||
if (err == nil) != test.valid {
|
||||
t.Fatalf("ValidateGlossary = %v, valid %v", err, test.valid)
|
||||
}
|
||||
if test.name == "extensions and aliases" && doc["extension"].(map[string]any)["count"] != int64(42) {
|
||||
t.Fatal("validation changed resolved extension")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartyConformance(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, source string
|
||||
valid bool
|
||||
}{
|
||||
{"empty", `{"schema_version":"maximumdirect.rpg.party.v1","characters":{}}`, true},
|
||||
{"optional and extensions", `{"schema_version":"maximumdirect.rpg.party.v1","extension":true,"characters":{"a":{"extension":1,"character":{"name":"Same","extension":{"v":1.5}}},"b":{"character":{"name":"Same","aliases":null,"classes":[]},"player":{"name":"P","extension":true}},"c":{"character":{"name":"C","aliases":[],"classes":[{"name":"Mage","level":9223372036854775807,"extension":1}]}}}}`, true},
|
||||
{"null classes", `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"N","classes":null}}}}`, false},
|
||||
{"invalid player", `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"N"},"player":null}}}`, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := ValidateParty(document(t, test.source))
|
||||
if (err == nil) != test.valid {
|
||||
t.Fatalf("ValidateParty = %v, valid %v", err, test.valid)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectionSelection(t *testing.T) {
|
||||
doc := document(t, `{"schema_version":"maximumdirect.glossary.v1","collections":{"a":{"entries":[]},"B":{"entries":[]}}}`)
|
||||
if err := ValidateGlossary(doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
selection, defaults []string
|
||||
want []string
|
||||
failure string
|
||||
}{
|
||||
{"default", nil, []string{"a"}, []string{"a"}, ""},
|
||||
{"empty", []string{}, []string{"a"}, []string{}, ""},
|
||||
{"deduplicated and sorted", []string{"a", "B", "a"}, nil, []string{"B", "a"}, ""},
|
||||
{"exact", []string{"b"}, nil, nil, "b"},
|
||||
{"empty name", []string{""}, nil, nil, "empty"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := SelectCollections(doc, test.selection, test.defaults)
|
||||
if test.failure != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), test.failure) {
|
||||
t.Fatalf("selection error = %v", err)
|
||||
}
|
||||
} else if err != nil || !reflect.DeepEqual(got, test.want) {
|
||||
t.Fatalf("selection = %#v, %v; want %#v", got, err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentValidation(t *testing.T) {
|
||||
doc := document(t, `{"schema_version":"maximumdirect.rpg.party.v1","characters":{}}`)
|
||||
var wg sync.WaitGroup
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := ValidateParty(doc); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -37,10 +37,21 @@ var _ contracts.Chunker = (*Chunker)(nil)
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type Chunker struct{}
|
||||
type Chunker struct{ context shared.PreparedContext }
|
||||
|
||||
func New(_ Options) (*Chunker, error) {
|
||||
return &Chunker{}, nil
|
||||
func New(_ Options, references ...contracts.ReferenceSet) (*Chunker, error) {
|
||||
if len(references) > 1 {
|
||||
return nil, chunkerErrorf("at most one reference set may be supplied")
|
||||
}
|
||||
var set contracts.ReferenceSet
|
||||
if len(references) == 1 {
|
||||
set = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(set)
|
||||
if err != nil {
|
||||
return nil, chunkerErrorf("prepare references: %w", err)
|
||||
}
|
||||
return &Chunker{context: context}, nil
|
||||
}
|
||||
|
||||
func (c *Chunker) Key() string {
|
||||
@@ -70,7 +81,7 @@ func (c *Chunker) PrepareChunk(ctx context.Context, req contracts.ChunkInput) (c
|
||||
if err := source.ValidateDocument(req.Source); err != nil {
|
||||
return nil, chunkerErrorf("validate source document: %w", err)
|
||||
}
|
||||
materials := shared.PromptInputs(req.SourceInput, req.References)
|
||||
materials := c.context.Inputs(req.SourceInput)
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content))
|
||||
@@ -105,7 +116,7 @@ func ModuleSpec() pipeline.ModuleSpec {
|
||||
Key: Key,
|
||||
Stage: pipeline.StageChunk,
|
||||
ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...),
|
||||
Provides: append([]string(nil), providedCapabilities...),
|
||||
ReferenceSlots: shared.ReferenceSlots(referenceSlotDescriptions),
|
||||
@@ -118,7 +129,7 @@ func Register(registry *pipeline.ChunkerRegistry) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options)
|
||||
return New(options, request.References)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestNewModuleSpecAndRegister(t *testing.T) {
|
||||
Key: Key,
|
||||
Stage: pipeline.StageChunk,
|
||||
ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: []string{"source.transcript"},
|
||||
Provides: []string{"chunks"},
|
||||
ReferenceSlots: wantReferenceSlots(),
|
||||
@@ -89,16 +89,17 @@ func TestRegisterNilRegistryReturnsError(t *testing.T) {
|
||||
|
||||
func wantReferenceSlots() []contracts.ReferenceSlot {
|
||||
accepted := []string{"application/json", "application/x-yaml", "application/yaml", "text/markdown", "text/plain"}
|
||||
structured := []string{"application/json", "application/x-yaml", "application/yaml"}
|
||||
return []contracts.ReferenceSlot{
|
||||
{
|
||||
Name: "glossary",
|
||||
Description: "Optional campaign glossary reference material used only for scene disambiguation.",
|
||||
AcceptedMediaTypes: append([]string(nil), accepted...),
|
||||
AcceptedMediaTypes: append([]string(nil), structured...),
|
||||
},
|
||||
{
|
||||
Name: "party",
|
||||
Description: "Optional party roster reference material used only for scene disambiguation.",
|
||||
AcceptedMediaTypes: append([]string(nil), accepted...),
|
||||
AcceptedMediaTypes: append([]string(nil), structured...),
|
||||
},
|
||||
{
|
||||
Name: "players",
|
||||
@@ -108,7 +109,7 @@ func wantReferenceSlots() []contracts.ReferenceSlot {
|
||||
{
|
||||
Name: "roster",
|
||||
Description: "Deprecated alias for party roster reference material used only for scene disambiguation.",
|
||||
AcceptedMediaTypes: append([]string(nil), accepted...),
|
||||
AcceptedMediaTypes: append([]string(nil), structured...),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -232,26 +233,26 @@ func TestPlanPassesReferencesAsPromptInputs(t *testing.T) {
|
||||
"party": {
|
||||
Slot: contracts.ReferenceSlot{Name: "party"},
|
||||
Items: []contracts.ReferenceItem{
|
||||
{SlotName: "party", Content: []byte("Aria: cleric")},
|
||||
{SlotName: "party", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria","classes":[{"name":"cleric"}]}}}}`)},
|
||||
},
|
||||
},
|
||||
"glossary": {
|
||||
Slot: contracts.ReferenceSlot{Name: "glossary"},
|
||||
Items: []contracts.ReferenceItem{
|
||||
{SlotName: "glossary", Content: []byte("Brightmantle: local temple")},
|
||||
{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"b","name":"Brightmantle","category":"place","description":"local temple"}]}}}`)},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := runChunk(context.Background(), newChunker(t, client), req); err != nil {
|
||||
if _, err := runChunk(context.Background(), newChunker(t, client, req.References), req); err != nil {
|
||||
t.Fatalf("Plan() error = %v, want nil", err)
|
||||
}
|
||||
var messages string
|
||||
for _, message := range client.requests[0].Prompt.Messages {
|
||||
messages += message.Content
|
||||
}
|
||||
for _, reference := range []string{"Alice: Aria", "Aria: cleric", "Brightmantle: local temple"} {
|
||||
for _, reference := range []string{"Alice: Aria", "cleric", "Brightmantle", "local temple"} {
|
||||
if strings.Count(messages, reference) != 1 {
|
||||
t.Fatalf("reference not rendered once: %q", reference)
|
||||
}
|
||||
@@ -259,20 +260,33 @@ func TestPlanPassesReferencesAsPromptInputs(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
func TestPromptInputsMapLegacyRosterReferenceToParty(t *testing.T) {
|
||||
inputs := shared.PromptInputs(sceneSourceInput(), contracts.ReferenceSet{
|
||||
func TestConstructionRejectsInvalidGlossaryReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid glossary accepted during construction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreparedContextMapsRosterReferenceToParty(t *testing.T) {
|
||||
prepared, err := shared.PrepareContext(contracts.ReferenceSet{
|
||||
Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"roster": {
|
||||
Slot: contracts.ReferenceSlot{Name: "roster"},
|
||||
Items: []contracts.ReferenceItem{
|
||||
{SlotName: "roster", Content: []byte("Legacy roster text")},
|
||||
{SlotName: "roster", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria"}}}}`)},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs := prepared.Inputs(sceneSourceInput())
|
||||
|
||||
if got := string(inputs["party"].Content); got != "Legacy roster text" {
|
||||
t.Fatalf("party input = %q, want legacy roster content", got)
|
||||
if got := string(inputs["party"].Content); !strings.Contains(got, "Aria") {
|
||||
t.Fatalf("party input = %q, want roster content", got)
|
||||
}
|
||||
if _, ok := inputs["roster"]; ok {
|
||||
t.Fatalf("roster prompt input was present; want only party input")
|
||||
@@ -426,7 +440,7 @@ type chunkFixture struct {
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
|
||||
func newChunker(t *testing.T, client promptkit.LLMClient) *chunkFixture {
|
||||
func newChunker(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *chunkFixture {
|
||||
t.Helper()
|
||||
type settings struct {
|
||||
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||
@@ -450,7 +464,7 @@ func newChunker(t *testing.T, client promptkit.LLMClient) *chunkFixture {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chunker, err := New(Options{})
|
||||
chunker, err := New(Options{}, references...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package combatturns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func TestConstructionRejectsInvalidSharedReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid glossary accepted during construction")
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ var _ contracts.Extractor[dnd.CombatTurnList] = (*Extractor)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct {
|
||||
context shared.PreparedContext
|
||||
npcResolver *npcregistry.Resolver
|
||||
sceneResolver *sceneregistry.Resolver
|
||||
}
|
||||
@@ -82,6 +83,10 @@ func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) == 1 {
|
||||
referenceSet = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
npcResolver, err := npcregistry.NewResolver(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare NPC registry prompt input: %w", err)
|
||||
@@ -90,7 +95,7 @@ func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare scene eligibility: %w", err)
|
||||
}
|
||||
return &Extractor{npcResolver: npcResolver, sceneResolver: sceneResolver}, nil
|
||||
return &Extractor{context: context, npcResolver: npcResolver, sceneResolver: sceneResolver}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -136,7 +141,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
}
|
||||
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
materials[NPCRegistryReferenceSlot] = npcRegistry.PromptInput()
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
@@ -172,7 +177,7 @@ func ModuleSpec() pipeline.ModuleSpec {
|
||||
Key: Key,
|
||||
Stage: pipeline.StageExtract,
|
||||
ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...),
|
||||
Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.CombatTurnListKind,
|
||||
|
||||
@@ -125,8 +125,8 @@ func TestExtractPassesReferencesAndNPCGroundingWithoutUsingItAsEvidence(t *testi
|
||||
client := &fakeCombatTurnsLLMClient{response: extractionResponse{CombatTurns: []combatTurnResponse{}}}
|
||||
references := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"players": {Slot: contracts.ReferenceSlot{Name: "players"}, Items: []contracts.ReferenceItem{{SlotName: "players", Content: []byte("Alice: Aria")}}},
|
||||
"party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", Content: []byte("Aria: cleric")}}},
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("ogre: a large foe")}}},
|
||||
"party": {Slot: contracts.ReferenceSlot{Name: "party"}, Items: []contracts.ReferenceItem{{SlotName: "party", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria","classes":[{"name":"cleric"}]}}}}`)}}},
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"o","name":"ogre","category":"foe","description":"a large foe"}]}}}`)}}},
|
||||
NPCRegistryReferenceSlot: {Slot: contracts.ReferenceSlot{Name: NPCRegistryReferenceSlot}, Items: []contracts.ReferenceItem{{SlotName: NPCRegistryReferenceSlot, MediaType: "application/json", Content: npcRegistryJSON(t)}}},
|
||||
}}
|
||||
req := extractionRequest(t)
|
||||
@@ -143,7 +143,7 @@ func TestExtractPassesReferencesAndNPCGroundingWithoutUsingItAsEvidence(t *testi
|
||||
for _, message := range messages {
|
||||
all += message.Content
|
||||
}
|
||||
for _, material := range []string{"Alice: Aria", "Aria: cleric", "ogre: a large foe"} {
|
||||
for _, material := range []string{"Alice: Aria", "cleric", "a large foe"} {
|
||||
if strings.Count(all, material) != 1 {
|
||||
t.Fatalf("campaign input not rendered once: %q", material)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package enemyevents
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func TestConstructionRejectsInvalidSharedReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid glossary accepted during construction")
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ var _ contracts.Extractor[dnd.EnemyEventList] = (*Extractor)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct {
|
||||
context shared.PreparedContext
|
||||
grounding *groundingResolver
|
||||
}
|
||||
|
||||
@@ -44,11 +45,15 @@ func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) == 1 {
|
||||
referenceSet = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
grounding, err := newGroundingResolver(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare grounding: %w", err)
|
||||
}
|
||||
return &Extractor{grounding: grounding}, nil
|
||||
return &Extractor{context: context, grounding: grounding}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -87,7 +92,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
|
||||
order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex)
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
for name, material := range grounding.PromptInputs() {
|
||||
materials[name] = material
|
||||
}
|
||||
@@ -138,7 +143,7 @@ func ModuleSpec() pipeline.ModuleSpec {
|
||||
Key: Key,
|
||||
Stage: pipeline.StageExtract,
|
||||
ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...),
|
||||
Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.EnemyEventListKind,
|
||||
|
||||
@@ -25,9 +25,17 @@ func TestExtractMapsEnemyEventsInSourceOrder(t *testing.T) {
|
||||
}}}
|
||||
|
||||
req := enemyExtractionRequest(t)
|
||||
req.References.Slots["party"] = contracts.ResolvedReferenceSlot{Items: []contracts.ReferenceItem{{
|
||||
MediaType: "application/json",
|
||||
Content: []byte(`{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria","aliases":["Star"]},"player":{"name":"Alice"}}}}`),
|
||||
}}}
|
||||
req.References.Slots["glossary"] = contracts.ResolvedReferenceSlot{Items: []contracts.ReferenceItem{{
|
||||
MediaType: "application/json",
|
||||
Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"w","name":"Watchtower","category":"place","aliases":["The Tower"]}]}}}`),
|
||||
}}}
|
||||
index := source.NewDocumentIndex(req.Source)
|
||||
req.SourceIndex = &index
|
||||
result, err := runExtraction(context.Background(), newEnemyExtractor(t, client), req)
|
||||
result, err := runExtraction(context.Background(), newEnemyExtractor(t, client, req.References), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -50,6 +58,15 @@ func TestExtractMapsEnemyEventsInSourceOrder(t *testing.T) {
|
||||
t.Fatalf("LLM calls = %d, want 1", len(client.requests))
|
||||
}
|
||||
request := client.requests[0]
|
||||
var prompt strings.Builder
|
||||
for _, message := range request.Prompt.Messages {
|
||||
prompt.WriteString(message.Content)
|
||||
}
|
||||
for _, name := range []string{"Aria", "Star", "Alice", "Watchtower", "The Tower"} {
|
||||
if !strings.Contains(prompt.String(), name) {
|
||||
t.Fatalf("prepared context omitted %q", name)
|
||||
}
|
||||
}
|
||||
if request.Prompt.SessionID != "session-123" {
|
||||
t.Fatal("session selection lost")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package itemoccurrences
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func TestConstructionRejectsInvalidSharedReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid glossary accepted during construction")
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,7 @@ var _ contracts.Extractor[dnd.ItemOccurrenceList] = (*Extractor)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct {
|
||||
context shared.PreparedContext
|
||||
itemResolver *itemregistry.Resolver
|
||||
}
|
||||
|
||||
@@ -72,11 +73,15 @@ func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) == 1 {
|
||||
referenceSet = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
itemResolver, err := itemregistry.NewResolver(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare item registry prompt input: %w", err)
|
||||
}
|
||||
return &Extractor{itemResolver: itemResolver}, nil
|
||||
return &Extractor{context: context, itemResolver: itemResolver}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -102,7 +107,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
}
|
||||
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
materials[ItemRegistryReferenceSlot] = registry.PromptInput()
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
@@ -132,7 +137,7 @@ func ModuleSpec() pipeline.ModuleSpec {
|
||||
Key: Key,
|
||||
Stage: pipeline.StageExtract,
|
||||
ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...),
|
||||
Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.ItemOccurrenceListKind,
|
||||
|
||||
@@ -37,13 +37,21 @@ var _ contracts.Extractor[dnd.ItemRegistry] = (*Extractor)(nil)
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct{}
|
||||
type Extractor struct{ context shared.PreparedContext }
|
||||
|
||||
func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) > 1 {
|
||||
return nil, extractorErrorf("at most one reference set may be supplied")
|
||||
}
|
||||
return &Extractor{}, nil
|
||||
var set contracts.ReferenceSet
|
||||
if len(references) == 1 {
|
||||
set = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(set)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
return &Extractor{context: context}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -61,7 +69,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex)
|
||||
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content))
|
||||
@@ -86,7 +94,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
func ModuleSpec() pipeline.ModuleSpec {
|
||||
return pipeline.ModuleSpec{
|
||||
Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...), Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.ItemRegistryKind, ReferenceSlots: referenceSlots(),
|
||||
}
|
||||
|
||||
@@ -70,12 +70,12 @@ func TestExtractPassesReferencesWithoutTreatingThemAsEvidence(t *testing.T) {
|
||||
client := &fakeItemsLLMClient{response: extractionResponse{Items: []itemResponse{}}}
|
||||
req := extractionRequest()
|
||||
req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Star Compass: heirloom")}}},
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"s","name":"Star Compass","category":"item","description":"heirloom"}]}}}`)}}},
|
||||
}}
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil {
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil {
|
||||
t.Fatalf("Extract() error = %v", err)
|
||||
}
|
||||
messageContaining(t, client.requests[0], "Star Compass: heirloom")
|
||||
messageContaining(t, client.requests[0], "Star Compass")
|
||||
if strings.Contains(messageContaining(t, client.requests[0], string(req.Chunk.Content)).Content, "heirloom") {
|
||||
t.Fatal("references became source evidence")
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func assessRegistry(ctx context.Context, request extractionTestInput, value dnd.
|
||||
func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) {
|
||||
client := &fakeItemsLLMClient{responses: []string{ungroundedRegistry, groundedRegistry}}
|
||||
request := extractionRequest()
|
||||
request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}}
|
||||
request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"players": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}}
|
||||
request.Execution.Controls.MaxAdditionalTurns = 1
|
||||
request.Execution.Execution.Execution = &promptkit.ExecutionTargetOverride{Model: "registry-override"}
|
||||
var prepared []promptkit.PreparedRun
|
||||
@@ -56,11 +56,11 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) {
|
||||
}
|
||||
// Changes after capture must not cause source/reference preparation again.
|
||||
request.SourceInput.Content[0] = '!'
|
||||
request.References.Slots["glossary"].Items[0].Content[0] = '!'
|
||||
request.References.Slots["players"].Items[0].Content[0] = '!'
|
||||
}
|
||||
return assessment, err
|
||||
}
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request)
|
||||
if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible ||
|
||||
assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.Items) != 1 {
|
||||
t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared))
|
||||
|
||||
@@ -10,11 +10,20 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
)
|
||||
|
||||
func TestConstructionRejectsInvalidPartyReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"party": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid party accepted during construction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleRegistrationAndNativeDependencies(t *testing.T) {
|
||||
if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one") {
|
||||
t.Fatalf("New() error = %v, want reference-set rejection", err)
|
||||
}
|
||||
want := pipeline.ModuleSpec{Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID, CorrectionPromptID}, Requires: []string{"chunks", "source.transcript"}, Provides: []string{"dnd.item_registry"}, ArtifactKind: dnd.ItemRegistryKind, ReferenceSlots: referenceSlots()}
|
||||
want := pipeline.ModuleSpec{Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID}, Requires: []string{"chunks", "source.transcript"}, Provides: []string{"dnd.item_registry"}, ArtifactKind: dnd.ItemRegistryKind, ReferenceSlots: referenceSlots()}
|
||||
if got := ModuleSpec(); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ModuleSpec() = %#v, want %#v", got, want)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package locationoccurrences
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func TestConstructionRejectsInvalidSharedReference(t *testing.T) {
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte("{}")}}},
|
||||
}}
|
||||
if _, err := New(Options{}, refs); err == nil {
|
||||
t.Fatal("invalid glossary accepted during construction")
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ var _ contracts.Extractor[dnd.LocationOccurrenceList] = (*Extractor)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct {
|
||||
context shared.PreparedContext
|
||||
locationResolver *locationregistry.Resolver
|
||||
}
|
||||
|
||||
@@ -67,11 +68,15 @@ func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) == 1 {
|
||||
referenceSet = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
locationResolver, err := locationregistry.NewResolver(referenceSet)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare location registry prompt input: %w", err)
|
||||
}
|
||||
return &Extractor{locationResolver: locationResolver}, nil
|
||||
return &Extractor{context: context, locationResolver: locationResolver}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -106,7 +111,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
order := shared.NewSourceRefOrderForSource(req.Source, index)
|
||||
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
materials[LocationRegistryReferenceSlot] = grounding.PromptInput()
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
@@ -134,7 +139,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
func ModuleSpec() pipeline.ModuleSpec {
|
||||
return pipeline.ModuleSpec{
|
||||
Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...), Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.LocationOccurrenceListKind, ReferenceSlots: referenceSlots(),
|
||||
}
|
||||
|
||||
@@ -37,13 +37,21 @@ var _ contracts.Extractor[dnd.LocationRegistry] = (*Extractor)(nil)
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct{}
|
||||
type Extractor struct{ context shared.PreparedContext }
|
||||
|
||||
func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) > 1 {
|
||||
return nil, extractorErrorf("at most one reference set may be supplied")
|
||||
}
|
||||
return &Extractor{}, nil
|
||||
var set contracts.ReferenceSet
|
||||
if len(references) == 1 {
|
||||
set = references[0]
|
||||
}
|
||||
context, err := shared.PrepareContext(set)
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare references: %w", err)
|
||||
}
|
||||
return &Extractor{context: context}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
@@ -61,7 +69,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
order := shared.NewSourceRefOrderForSource(req.Source, req.SourceIndex)
|
||||
|
||||
sourceID := req.Source.ID
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
materials := e.context.Inputs(sourceInput)
|
||||
inputs := make(map[string]promptkit.ArtifactRef, len(materials))
|
||||
for name, material := range materials {
|
||||
inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.Content))
|
||||
@@ -86,7 +94,7 @@ func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.Extract
|
||||
func ModuleSpec() pipeline.ModuleSpec {
|
||||
return pipeline.ModuleSpec{
|
||||
Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked,
|
||||
Prompts: []string{PromptID, CorrectionPromptID},
|
||||
Prompts: []string{PromptID, CorrectionPromptID}, InitialPrompts: []string{PromptID},
|
||||
Requires: append([]string(nil), requiredCapabilities...), Provides: append([]string(nil), providedCapabilities...),
|
||||
ArtifactKind: dnd.LocationRegistryKind, ReferenceSlots: referenceSlots(),
|
||||
}
|
||||
|
||||
@@ -73,12 +73,12 @@ func TestExtractPassesReferencesWithoutTreatingThemAsEvidence(t *testing.T) {
|
||||
client := &fakeLocationsLLMClient{response: extractionResponse{Locations: []locationResponse{}}}
|
||||
req := extractionRequest()
|
||||
req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Old Mill: abandoned granary")}}},
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", MediaType: "application/json", Content: []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"m","name":"Old Mill","category":"place","description":"abandoned granary"}]}}}`)}}},
|
||||
}}
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil {
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil {
|
||||
t.Fatalf("Extract() error = %v", err)
|
||||
}
|
||||
messageContaining(t, client.requests[0], "Old Mill: abandoned granary")
|
||||
messageContaining(t, client.requests[0], "abandoned granary")
|
||||
if strings.Contains(messageContaining(t, client.requests[0], string(req.Chunk.Content)).Content, "abandoned granary") {
|
||||
t.Fatal("references became source evidence")
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func assessRegistry(ctx context.Context, request extractionTestInput, value dnd.
|
||||
func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) {
|
||||
client := &fakeLocationsLLMClient{responses: []string{ungroundedRegistry, groundedRegistry}}
|
||||
request := extractionRequest()
|
||||
request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"glossary": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}}
|
||||
request.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"players": {Items: []contracts.ReferenceItem{{Content: []byte("fixed-reference")}}}}}
|
||||
request.Execution.Controls.MaxAdditionalTurns = 1
|
||||
request.Execution.Execution.Execution = &promptkit.ExecutionTargetOverride{Model: "registry-override"}
|
||||
var prepared []promptkit.PreparedRun
|
||||
@@ -56,11 +56,11 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) {
|
||||
}
|
||||
// Changes after capture must not cause source/reference preparation again.
|
||||
request.SourceInput.Content[0] = '!'
|
||||
request.References.Slots["glossary"].Items[0].Content[0] = '!'
|
||||
request.References.Slots["players"].Items[0].Content[0] = '!'
|
||||
}
|
||||
return assessment, err
|
||||
}
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request)
|
||||
if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible ||
|
||||
assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.Locations) != 1 {
|
||||
t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user