Document prompt-owned schemas and finalize migration

This commit is contained in:
2026-11-20 15:46:39 +00:00
parent 9bed36282a
commit e9a12d43c2
16 changed files with 174 additions and 106 deletions

View File

@@ -83,20 +83,25 @@ promptInputs, err := promptkit.DirectoryInputs("prompts")
if err != nil { return err } if err != nil { return err }
profileInputs, err := promptkit.DirectoryInputs("profiles") profileInputs, err := promptkit.DirectoryInputs("profiles")
if err != nil { return err } if err != nil { return err }
filesystem := configkit.NewFilesystem("application schemas", os.DirFS("."))
schemaInput := configkit.Input{
Source: promptkit.SchemaRootSource("application schemas", "schemas"),
Filesystem: &configkit.FilesystemContext{FS: &filesystem, Root: ".", BaseDir: "."},
}
engine, err := promptkit.NewEngine(promptkit.Config{ engine, err := promptkit.NewEngine(promptkit.Config{
Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{ Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{
{Inputs: promptInputs}, {Inputs: promptInputs},
{Inputs: profileInputs}, {Inputs: profileInputs},
{Inputs: []configkit.Input{schemaInput}},
}}, }},
SchemaDir: "schemas",
}) })
``` ```
For a single highest-priority document, set `Sources.Main` to a For a single highest-priority document, set `Sources.Main` to a
`*configkit.Input`; omit it for ordinary layered construction. A single file `*configkit.Input`; omit it for ordinary layered construction. A single file
can use `configkit.File` directly. `PromptSource`, `ProfileSource`, `BackendSource`, and raw can use `configkit.File` directly. `PromptSource`, `ProfileSource`, `BackendSource`, and raw
`configkit.Mapping` supply programmatic definitions. Schema and runtime `configkit.Mapping` supply programmatic definitions. Runtime collaborator
collaborator options remain available. Construction validates the final options remain available. Construction validates the final
effective configuration and captures referenced prompt content; construct a effective configuration and captures referenced prompt content; construct a
new engine to observe configuration edits. See the [constructor GoDoc](../../engine.go) new engine to observe configuration edits. See the [constructor GoDoc](../../engine.go)
for the exact public contract and the [framework format reference](../formats.md) for the exact public contract and the [framework format reference](../formats.md)
@@ -705,7 +710,7 @@ corrected automatically:
request.Validation = &promptkit.OutputContract{ request.Validation = &promptkit.OutputContract{
Format: promptkit.FormatJSON, Format: promptkit.FormatJSON,
ValidationMode: promptkit.ValidationJSONSchema, ValidationMode: promptkit.ValidationJSONSchema,
SchemaPath: "events.schema.json", Schema: map[string]any{"type": "object"},
RepairAttempts: 1, RepairAttempts: 1,
} }
``` ```
@@ -1119,10 +1124,20 @@ secret-handling policies.
## Extension Interfaces ## Extension Interfaces
JSON Schema validation and native structured output use a self-contained root JSON Schema validation and native structured output use a self-contained root
document. Internal references are supported; references to other files or document. See [schema selection and resource context](../formats.md#schemas).
network resources fail during preparation. `WithSchemaFile` selects one root Prepared executions retain their captured schema even if the source later changes.
file, while `WithSchemaFS` and `SchemaDir` select a root source. Prepared
executions retain their captured schema even if the source later changes. ### Migrating Schema Sources
`Config.SchemaDir`, `WithSchemaFS`, and `WithSchemaFile` have been removed.
Supply a context-backed `SchemaRootSource` at the desired ConfigKit layer, as
shown above, or declare `schema_root` in application or collection mappings.
For a former single-file source, configure `schema_file` relative to its
contributing source, or supply its directory as a root and use its basename in
`schema_path`. To substitute an unrelated file per request, read and decode it
in the caller and supply its value as `OutputContract.Schema`. There is no
implicit working-directory root. Public structs gained fields; change any
positional struct literals to keyed literals when migrating.
Inject an [`LLMClient` or `ArtifactReader`](../../types.go) when the built-in Inject an [`LLMClient` or `ArtifactReader`](../../types.go) when the built-in
behavior does not fit the application. Their GoDoc defines concurrent use, behavior does not fit the application. Their GoDoc defines concurrent use,

View File

@@ -201,11 +201,19 @@ messages; the integration contract defines its wire representation.
| --- | --- | --- | | --- | --- | --- |
| `format` | yes | `text`, `markdown`, or `json` | | `format` | yes | `text`, `markdown`, or `json` |
| `validation_mode` | yes | `none`, `basic`, `json`, or `json_schema` | | `validation_mode` | yes | `none`, `basic`, `json`, or `json_schema` |
| `schema_path` | for `json_schema` | Path in the selected schema source | | `schema` | one selection for `json_schema` | Inline JSON Schema value |
| `schema_file` | one selection for `json_schema` | File relative to the contributing field's source context |
| `schema_path` | one selection for `json_schema` | Path within the applicable explicit schema root |
| `repair_attempts` | no | Integer 0–3; default 0. Positive values need `basic`, `json`, or `json_schema` | | `repair_attempts` | no | Integer 0–3; default 0. Positive values need `basic`, `json`, or `json_schema` |
`none` skips content validation; `basic` requires nonempty content; `json` `none` skips content validation; `basic` requires nonempty content; `json`
accepts any valid JSON value; `json_schema` checks the selected schema. accepts any valid JSON value; `json_schema` checks the selected schema.
In `json_schema` mode exactly one nonnull `schema`, `schema_file`, or
`schema_path` must be selected. Null clears a selection; `false`, `true`, and
`{}` are values. Blank references are invalid. Other modes ignore these fields
for schema selection and loading. ConfigKit composes inline mappings normally;
switching forms can require explicitly clearing an inherited alternative.
Replacing an identified prompt record replaces its complete earlier record.
`format` determines output artifact metadata. JSON Schema mode also supplies `format` determines output artifact metadata. JSON Schema mode also supplies
structured-output metadata to compatible clients. Plain `json` does not structured-output metadata to compatible clients. Plain `json` does not
request a provider-native JSON-object constraint. A positive repair budget request a provider-native JSON-object constraint. A positive repair budget
@@ -433,14 +441,31 @@ generic inheritance and layer mechanics, consult
## Schemas ## Schemas
Schemas are JSON documents selected by a prompt or request `schema_path`. Schemas can be inline, source-relative files, or files under an explicit root.
Directory and `fs.FS` schema paths resolve within the configured root. Each An optional `schema_root` may be set at the application root and in each
schema must be self-contained: in-document references, IDs, and anchors are collection. A collection's nonnull root takes precedence over the application
root for its prompts; an absent or null collection root falls back to the
application root. A nonnull blank root is invalid. There is no implicit
working-directory root. Roots and `schema_file` references resolve using the
effective field's contributing ConfigKit filesystem and base directory;
missing usable context is a configuration error. An explicit `.` is valid
with usable context. A `schema_path` requires an applicable root. Root choice
is made before reading: a missing file never triggers another-root search.
Schema selection and context are captured during construction without reading
schema files. Files are read and compiled during preparation; a missing,
malformed, or unresolvable file is an operational validation error. Inline
configuration values follow native ConfigKit composition and null handling.
For request-level replacement, inline `Schema` needs no root and `SchemaPath`
uses the selected prompt's applicable root. A replacement does not inherit the
configured schema selection or `schema_file` context.
Runtime inline values are encoded as JSON before preparation; file-backed JSON
uses the existing number-preserving decoder. No additional numerical equivalence
between input representations is implied.
Each schema must be self-contained: in-document references, IDs, and anchors are
supported, but references requiring another file or network resource fail. supported, but references requiring another file or network resource fail.
References must also work without the source filename as a base; use fragment References must also work without the source filename as a base; use fragment
references or explicit schema IDs rather than relying on that filename. references or explicit schema IDs rather than relying on that filename.
`WithSchemaFile` exposes one schema under its base name. An unreadable,
invalid, or unresolvable schema causes an operational validation error.
Valid JSON that fails the schema instead yields a failed validation result. Valid JSON that fails the schema instead yields a failed validation result.
Schema documents are detached without applying the provider extra-parameter Schema documents are detached without applying the provider extra-parameter
copy limits; this does not change the schema decoder, compiler, or copy limits; this does not change the schema decoder, compiler, or

View File

@@ -28,7 +28,7 @@ contributor workflow and validation.
| `internal/profile` | Provides a narrow captured-profile lookup contract and not-found identity. | [Profile lookup](../../internal/profile/repository.go), [framework formats](../formats.md) | | `internal/profile` | Provides a narrow captured-profile lookup contract and not-found identity. | [Profile lookup](../../internal/profile/repository.go), [framework formats](../formats.md) |
| `internal/prompt` | Renders prompt messages from Go templates with artifact, variable, session, and cache-control data, and conservatively enumerates dependencies from captured template syntax. | [Go-template renderer](../../internal/prompt/go_renderer.go), [requirement discovery](../../internal/prompt/requirements.go) | | `internal/prompt` | Renders prompt messages from Go templates with artifact, variable, session, and cache-control data, and conservatively enumerates dependencies from captured template syntax. | [Go-template renderer](../../internal/prompt/go_renderer.go), [requirement discovery](../../internal/prompt/requirements.go) |
| `internal/artifact` | Resolves ordinary inline and unrestricted caller-selected file references into copied artifacts with metadata and hashes. | [Internal sources and validation](sources.md) | | `internal/artifact` | Resolves ordinary inline and unrestricted caller-selected file references into copied artifacts with metadata and hashes. | [Internal sources and validation](sources.md) |
| `internal/validate` | Validates basic, JSON, and JSON Schema output using operating-system filesystem or `fs.FS` schema sources and creates operation-local validation plans with canonical contained schema resources. | [Framework formats](../formats.md#schemas), [internal sources and validation](sources.md) | | `internal/validate` | Creates operation-local validation plans from inline schema documents or bound filesystem resources and validates basic, JSON, and JSON Schema output. | [Framework formats](../formats.md#schemas), [internal sources and validation](sources.md) |
| `internal/llm` | Defines the internal generation boundary and implements outbound OpenAI-compatible chat requests from resolved execution targets, including bounded response decoding, authentication, deadline handling, per-invocation HTTP evidence and built-in diagnostic probes, and ownership of the OpenAI-compatible reserved request-field policy. | [Internal model client](llm.md) | | `internal/llm` | Defines the internal generation boundary and implements outbound OpenAI-compatible chat requests from resolved execution targets, including bounded response decoding, authentication, deadline handling, per-invocation HTTP evidence and built-in diagnostic probes, and ownership of the OpenAI-compatible reserved request-field policy. | [Internal model client](llm.md) |
| `internal/observation` | Owns invocation-local run IDs, presence-aware usage and phase accounting, synchronous metadata event delivery and composition, and explicit terminal-based group aggregation; smoke diagnostics keep their private evidence outside ordinary observer events. | [Internal execution observation](observation.md) | | `internal/observation` | Owns invocation-local run IDs, presence-aware usage and phase accounting, synchronous metadata event delivery and composition, and explicit terminal-based group aggregation; smoke diagnostics keep their private evidence outside ordinary observer events. | [Internal execution observation](observation.md) |
| `internal/usecase` | Selects captured prompts and profiles, enumerates requirements from captured prompt syntax, applies request overrides and completion checks, coordinates ordinary and single-claim prepared execution across rendering, artifact loading, operation-local validation plans, generation, capacity, and bounded repair, advances a single conversation branch, and runs explicit smoke diagnostics with private cases, shared generation/capacity, and optional built-in HTTP probes. | [Internal runner](runner.md), [requirement inspection](../../internal/usecase/requirements_inspection.go), [prepared-execution implementation](../../internal/usecase/prepared_execution.go) | | `internal/usecase` | Selects captured prompts and profiles, enumerates requirements from captured prompt syntax, applies request overrides and completion checks, coordinates ordinary and single-claim prepared execution across rendering, artifact loading, operation-local validation plans, generation, capacity, and bounded repair, advances a single conversation branch, and runs explicit smoke diagnostics with private cases, shared generation/capacity, and optional built-in HTTP probes. | [Internal runner](runner.md), [requirement inspection](../../internal/usecase/requirements_inspection.go), [prepared-execution implementation](../../internal/usecase/prepared_execution.go) |

View File

@@ -126,12 +126,12 @@ performs only the work needed to validate routing and admission:
1. validate the required prompt selection and normalize any direct session ID; 1. validate the required prompt selection and normalize any direct session ID;
2. select the captured prompt definition and hash; 2. select the captured prompt definition and hash;
3. select the request profile or the prompt's default profile; 3. resolve and validate the effective output contract and select its applicable
4. retain the profile's selected backend identity, when present; bound file without loading its schema;
5. apply explicit request overrides to its captured backend-completed target; 4. select the request profile or the prompt's default profile;
6. validate endpoint, model, numeric overrides, and credential requirements; 5. retain the profile's selected backend identity, when present;
7. resolve and validate the effective output contract without loading its 6. apply explicit request overrides to its captured backend-completed target;
schema; and 7. validate endpoint, model, numeric overrides, and credential requirements; and
8. retain the definition, source identities, effective settings, output 8. retain the definition, source identities, effective settings, output
contract, and preparation start time in invocation-local state. contract, and preparation start time in invocation-local state.

View File

@@ -86,7 +86,10 @@ returning and retains no source capability for public inspection.
Prompt materialization shares a lazy metadata snapshot across root and collection Prompt materialization shares a lazy metadata snapshot across root and collection
resources during construction, avoiding a full metadata copy per collection. resources during construction, avoiding a full metadata copy per collection.
Input metadata, message content and templates, and output contracts are captured Input metadata, message content and templates, and output contracts are captured
separately before the definition, inspection, and hash are assembled. separately before the definition, inspection, and hash are assembled. Schema
root and source-relative file bindings capture the effective field context
without opening schema files; capabilities are excluded from the hash. Inline
schema values and file-reference strings participate in the definition hash.
Normalization and defaults are recorded at individual resolved field paths, Normalization and defaults are recorded at individual resolved field paths,
including message roles and cache controls. List indexes identify fields for including message roles and cache controls. List indexes identify fields for
@@ -212,18 +215,20 @@ buffer-to-string copy. The
## Schemas And Output Validation ## Schemas And Output Validation
`internal/validate` provides validators backed by an operating-system `internal/validate` prepares a source-neutral input containing an output contract
filesystem or an `fs.FS`. Invalid generated content is returned as a validation and an optional bound `fs.FS` file. Invalid generated content is returned as a validation
result; inability to load, register, or compile a schema is an operational result; inability to load, register, or compile a schema is an operational
error. Basic validation checks body emptiness on the byte slice directly error. Basic validation checks body emptiness on the byte slice directly
instead of first making a response-sized string copy. instead of first making a response-sized string copy.
Every preparation operation creates one operation-local validation plan. None, Every preparation operation creates one operation-local validation plan. None,
basic, and JSON modes retain the effective output contract without source basic, and JSON modes retain the effective output contract without source
access. JSON Schema mode loads the root document once, compiles its declared access. JSON Schema mode uses the captured inline document or loads the bound
root document once, compiles its declared
schema locations, and retains the compiled root validator. External resources schema locations, and retains the compiled root validator. External resources
are rejected without file or network loading; in-document references remain are rejected without file or network loading; in-document references remain
supported. Root resources use canonical escaped file or private-scheme URLs. The supported. Bound files use canonical escaped private-scheme URLs; inline values
use a stable private retrieval URL. The
provider-facing structured-output metadata uses the root document captured by provider-facing structured-output metadata uses the root document captured by
the same plan. Its detached schema document is not revalidated against the the same plan. Its detached schema document is not revalidated against the
runtime provider-value copier's traversal limits. Smoke inference uses a runtime provider-value copier's traversal limits. Smoke inference uses a

View File

@@ -372,6 +372,8 @@ covered end to end without application-managed mounts or live infrastructure.
## Stage 8 — Migrate Documentation And Validate The Assembled Sprint ## Stage 8 — Migrate Documentation And Validate The Assembled Sprint
Status: complete.
1. Update GoDoc and [formats.md](../formats.md) for selection/null/composition, 1. Update GoDoc and [formats.md](../formats.md) for selection/null/composition,
source context, root scope, inactive modes, preparation failures, and removed source context, root scope, inactive modes, preparation failures, and removed
implicit root. Update the [consumer guide](../consumers/pkg-promptkit.md) with implicit root. Update the [consumer guide](../consumers/pkg-promptkit.md) with

View File

@@ -253,13 +253,13 @@ func NewEngine(cfg Config, opts ...Option) (*Engine, error) {
// unrendered messages are returned in definition order. DefaultProfileID is // unrendered messages are returned in definition order. DefaultProfileID is
// declared metadata only and is not // declared metadata only and is not
// resolved. OutputContract is the normalized declared contract, with a JSON // resolved. OutputContract is the normalized declared contract, with a JSON
// Schema path when declared but without loading or compiling that schema. // Schema selection when declared but without loading or compiling schema files.
// PromptHash is the same opaque equality value as PreparedRun.PromptHash for // PromptHash is the same opaque equality value as PreparedRun.PromptHash for
// the selected captured definition; its spelling, length, // the selected captured definition; its spelling, length,
// encoding, algorithm, and security properties are not contracts. // encoding, algorithm, and security properties are not contracts.
// //
// This method does not return parsed templates, source paths, schemas, // This method does not return parsed templates, filesystem capabilities,
// rendered messages, or execution settings. It does not resolve a profile or // schema file contents, rendered messages, or execution settings. It does not resolve a profile or
// credential, read artifacts or schemas, render, validate, admit capacity, // credential, read artifacts or schemas, render, validate, admit capacity,
// contact a provider, or generate model output. The returned PromptInspection // contact a provider, or generate model output. The returned PromptInspection
// and its input slice are caller-owned. Inspection does not reload configuration // and its input slice are caller-owned. Inspection does not reload configuration

View File

@@ -91,9 +91,11 @@ func run() (summary, error) {
return summary{}, err return summary{}, err
} }
backendID, proposalModel, assessmentModel := "offline-backend", "proposal-model", "assessment-model" backendID, proposalModel, assessmentModel := "offline-backend", "proposal-model", "assessment-model"
filesystem := configkit.NewFilesystem("example schemas", assets)
backend := promptkit.LocalBackend("https://example.invalid/v1", 1) backend := promptkit.LocalBackend("https://example.invalid/v1", 1)
backend.ID = backendID backend.ID = backendID
inputs = append(inputs, inputs = append(inputs,
configkit.Input{Source: promptkit.SchemaRootSource("example schemas", "schemas"), Filesystem: &configkit.FilesystemContext{FS: &filesystem, Root: ".", BaseDir: "."}},
configkit.Input{Source: promptkit.BackendSource("example backend", []promptkit.BackendConfig{ configkit.Input{Source: promptkit.BackendSource("example backend", []promptkit.BackendConfig{
backend, backend,
})}, })},
@@ -105,7 +107,7 @@ func run() (summary, error) {
engine, err := promptkit.NewEngine(promptkit.Config{ engine, err := promptkit.NewEngine(promptkit.Config{
Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}}, Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: inputs}}},
HTTPClient: &http.Client{Transport: transport}, HTTPClient: &http.Client{Transport: transport},
}, promptkit.WithBundledOpenRouter(false), promptkit.WithSchemaFS(assets, "schemas")) // Keep the example's configuration self-contained. }, promptkit.WithBundledOpenRouter(false)) // Keep the example's configuration self-contained.
if err != nil { if err != nil {
return summary{}, err return summary{}, err
} }

View File

@@ -14,4 +14,11 @@ prompts:
output: output:
format: json format: json
validation_mode: json_schema validation_mode: json_schema
schema_path: assessment.schema.json schema:
$schema: https://json-schema.org/draft/2020-12/schema
type: object
required: [recommendation, confidence]
properties:
recommendation: {type: string}
confidence: {type: number}
additionalProperties: false

View File

@@ -1,10 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["recommendation", "confidence"],
"properties": {
"recommendation": {"type": "string"},
"confidence": {"type": "number"}
},
"additionalProperties": false
}

View File

@@ -2,93 +2,73 @@ package jsonvalue
import "reflect" import "reflect"
func cloneTrustedMap(src map[string]any) map[string]any { type cloneReference struct {
if src == nil { typeOf reflect.Type
return nil pointer uintptr
} length int
out := make(map[string]any, len(src))
for k, v := range src {
out[k] = CloneTrusted(v)
}
return out
} }
// CloneTrusted detaches a previously accepted value without revalidating it. // CloneTrusted detaches a previously accepted value without revalidating it.
// Cyclic values can also occur in inactive, uninterpreted request fields.
func CloneTrusted(value any) any { func CloneTrusted(value any) any {
if value == nil { if value == nil {
return nil return nil
} }
switch v := value.(type) { return cloneTrustedReflect(reflect.ValueOf(value), make(map[cloneReference]reflect.Value)).Interface()
case map[string]any:
return cloneTrustedMap(v)
case []any:
out := make([]any, len(v))
for i, item := range v {
out[i] = CloneTrusted(item)
}
return out
case []string:
if v == nil {
return []string(nil)
}
return append([]string{}, v...)
case []byte:
if v == nil {
return []byte(nil)
}
return append([]byte{}, v...)
default:
return cloneTrustedReflect(reflect.ValueOf(value)).Interface()
}
} }
func cloneTrustedReflect(value reflect.Value) reflect.Value { func cloneTrustedReflect(value reflect.Value, active map[cloneReference]reflect.Value) reflect.Value {
if !value.IsValid() { if !value.IsValid() {
return value return value
} }
switch value.Kind() { switch value.Kind() {
case reflect.Interface: case reflect.Interface:
if value.IsNil() { if value.IsNil() {
return reflect.Zero(value.Type()) return reflect.Zero(value.Type())
} }
copied := cloneTrustedReflect(value.Elem())
if copied.IsValid() && copied.Type().AssignableTo(value.Type()) {
return copied
}
out := reflect.New(value.Type()).Elem() out := reflect.New(value.Type()).Elem()
out.Set(copied) out.Set(cloneTrustedReflect(value.Elem(), active))
return out return out
case reflect.Pointer, reflect.Map, reflect.Slice:
if value.IsNil() {
return reflect.Zero(value.Type())
}
key := cloneReference{typeOf: value.Type(), pointer: uintptr(value.UnsafePointer())}
if value.Kind() == reflect.Slice {
key.length = value.Len()
}
if existing, found := active[key]; found {
return existing
}
var out reflect.Value
switch value.Kind() {
case reflect.Pointer: case reflect.Pointer:
if value.IsNil() { out = reflect.New(value.Type().Elem())
return reflect.Zero(value.Type())
}
out := reflect.New(value.Type().Elem())
out.Elem().Set(cloneTrustedReflect(value.Elem()))
return out
case reflect.Map: case reflect.Map:
if value.IsNil() { out = reflect.MakeMapWithSize(value.Type(), value.Len())
return reflect.Zero(value.Type()) case reflect.Slice:
out = reflect.MakeSlice(value.Type(), value.Len(), value.Cap())
} }
out := reflect.MakeMapWithSize(value.Type(), value.Len()) active[key] = out
defer delete(active, key)
switch value.Kind() {
case reflect.Pointer:
out.Elem().Set(cloneTrustedReflect(value.Elem(), active))
case reflect.Map:
iter := value.MapRange() iter := value.MapRange()
for iter.Next() { for iter.Next() {
out.SetMapIndex(cloneTrustedReflect(iter.Key()), cloneTrustedReflect(iter.Value())) out.SetMapIndex(cloneTrustedReflect(iter.Key(), active), cloneTrustedReflect(iter.Value(), active))
} }
return out
case reflect.Slice: case reflect.Slice:
if value.IsNil() {
return reflect.Zero(value.Type())
}
out := reflect.MakeSlice(value.Type(), value.Len(), value.Cap())
for i := 0; i < value.Len(); i++ { for i := 0; i < value.Len(); i++ {
out.Index(i).Set(cloneTrustedReflect(value.Index(i))) out.Index(i).Set(cloneTrustedReflect(value.Index(i), active))
}
} }
return out return out
case reflect.Array: case reflect.Array:
out := reflect.New(value.Type()).Elem() out := reflect.New(value.Type()).Elem()
for i := 0; i < value.Len(); i++ { for i := 0; i < value.Len(); i++ {
out.Index(i).Set(cloneTrustedReflect(value.Index(i))) out.Index(i).Set(cloneTrustedReflect(value.Index(i), active))
} }
return out return out
default: default:

View File

@@ -25,3 +25,13 @@ func TestCloneTrustedPreservesTypesAndDetaches(t *testing.T) {
t.Fatal("nil/empty shape changed") t.Fatal("nil/empty shape changed")
} }
} }
func TestCloneTrustedDetachesCycles(t *testing.T) {
original := map[string]any{}
original["self"] = original
copy := CloneTrusted(original).(map[string]any)
copy["self"].(map[string]any)["changed"] = true
if copy["changed"] != true || original["changed"] != nil {
t.Fatal("cyclic copy did not preserve its cycle independently")
}
}

View File

@@ -10,11 +10,17 @@ import (
func TestPreparationRejectsInvalidOutputContractWithPublicError(t *testing.T) { func TestPreparationRejectsInvalidOutputContractWithPublicError(t *testing.T) {
engine := newSimpleEngine(t, "message") engine := newSimpleEngine(t, "message")
cycle := map[string]any{}
cycle["self"] = cycle
for _, tc := range []struct { for _, tc := range []struct {
name string name string
contract promptkit.OutputContract contract promptkit.OutputContract
}{ }{
{
name: "cyclic inline schema",
contract: promptkit.OutputContract{Format: promptkit.FormatJSON, ValidationMode: promptkit.ValidationJSONSchema, Schema: cycle},
},
{ {
name: "inline schema cannot be encoded", name: "inline schema cannot be encoded",
contract: promptkit.OutputContract{ contract: promptkit.OutputContract{
@@ -67,3 +73,18 @@ func TestPreparationRejectsInvalidOutputContractWithPublicError(t *testing.T) {
}) })
} }
} }
func TestInactiveSchemaDoesNotInterpretCyclicValue(t *testing.T) {
cycle := map[string]any{}
cycle["self"] = cycle
engine := newSimpleEngine(t, "message")
prepared, err := engine.Prepare(context.Background(), promptkit.RunRequest{PromptID: "prompt", Validation: &promptkit.OutputContract{Format: promptkit.FormatText, ValidationMode: promptkit.ValidationNone, Schema: cycle}})
if err != nil {
t.Fatal(err)
}
copy := prepared.OutputContract.Schema.(map[string]any)
copy["self"].(map[string]any)["changed"] = true
if copy["changed"] != true || cycle["changed"] != nil {
t.Fatal("inactive schema copy shares caller storage")
}
}

View File

@@ -37,7 +37,9 @@ type PromptMessageConfig struct {
// PromptCacheControlConfig supplies optional cache-control source fields. // PromptCacheControlConfig supplies optional cache-control source fields.
type PromptCacheControlConfig struct{ Type, TTL *string } type PromptCacheControlConfig struct{ Type, TTL *string }
// PromptOutputConfig supplies optional output contract source fields. // PromptOutputConfig supplies optional output contract source fields. Schema
// supplies a nonnull inline value, and SchemaFile and SchemaPath are reference
// selections. Raw ConfigKit mappings can express explicit null to clear one.
type PromptOutputConfig struct { type PromptOutputConfig struct {
Format, ValidationMode, SchemaPath, SchemaFile *string Format, ValidationMode, SchemaPath, SchemaFile *string
Schema any Schema any
@@ -45,6 +47,8 @@ type PromptOutputConfig struct {
} }
// SchemaRootSource supplies a schema root as a native configuration mapping. // SchemaRootSource supplies a schema root as a native configuration mapping.
// The caller chooses the input layer and supplies its filesystem context. The
// helper neither validates the value nor opens resources.
func SchemaRootSource(label, root string) configkit.Source { func SchemaRootSource(label, root string) configkit.Source {
return configkit.Mapping(label, map[string]any{"schema_root": root}) return configkit.Mapping(label, map[string]any{"schema_root": root})
} }
@@ -54,7 +58,7 @@ func SchemaRootSource(label, root string) configkit.Source {
// sibling inheritance and layered sources can complete them before NewEngine // sibling inheritance and layered sources can complete them before NewEngine
// validates the final configuration. Mapping snapshots supported values when // validates the final configuration. Mapping snapshots supported values when
// constructed; the helper neither resolves inheritance nor reads files. // constructed; the helper neither resolves inheritance nor reads files.
// Relative content files use the ConfigKit Input filesystem context of the // Relative content and schema files use the ConfigKit Input filesystem context of the
// contributing field. Raw mappings remain available for explicit null and // contributing field. Raw mappings remain available for explicit null and
// generic ConfigKit operations. // generic ConfigKit operations.
func PromptSource(label string, prompts []PromptConfig) configkit.Source { func PromptSource(label string, prompts []PromptConfig) configkit.Source {

View File

@@ -75,8 +75,8 @@ type PromptCacheControlInspection struct {
TTL *string `json:"ttl,omitempty" yaml:"ttl,omitempty"` TTL *string `json:"ttl,omitempty" yaml:"ttl,omitempty"`
} }
// PromptOutputInspection describes a prompt's output contract. SchemaPath is // PromptOutputInspection describes a prompt's configured output contract.
// a reference and is not loaded by inspection. // SchemaFile and SchemaPath are references and are not loaded by inspection.
type PromptOutputInspection struct { type PromptOutputInspection struct {
Format OutputFormat `json:"format" yaml:"format"` Format OutputFormat `json:"format" yaml:"format"`
ValidationMode ValidationMode `json:"validation_mode" yaml:"validation_mode"` ValidationMode ValidationMode `json:"validation_mode" yaml:"validation_mode"`

View File

@@ -39,7 +39,7 @@ const (
ValidationBasic ValidationMode = "basic" ValidationBasic ValidationMode = "basic"
// ValidationJSON requires syntactically valid JSON. // ValidationJSON requires syntactically valid JSON.
ValidationJSON ValidationMode = "json" ValidationJSON ValidationMode = "json"
// ValidationJSONSchema requires JSON that satisfies OutputContract.SchemaPath. // ValidationJSONSchema requires JSON satisfying the selected schema.
ValidationJSONSchema ValidationMode = "json_schema" ValidationJSONSchema ValidationMode = "json_schema"
) )
@@ -494,7 +494,11 @@ type ExecutionTargetPresence struct {
// //
// A non-nil RunRequest.Validation replaces the complete prompt contract. It // A non-nil RunRequest.Validation replaces the complete prompt contract. It
// does not merge fields. The public Engine performs bounded correction after a // does not merge fields. The public Engine performs bounded correction after a
// failed eligible validation when RepairAttempts is positive. // failed eligible validation when RepairAttempts is positive. A JSON Schema
// request replacement requires exactly one of Schema and SchemaPath; other
// modes ignore them. A replacement uses the prompt's configured root for
// SchemaPath. For a configured source-relative file, prepared output contracts
// expose neither selection; StructuredOutput contains the selected document.
type OutputContract struct { type OutputContract struct {
// Format selects generated artifact metadata. An empty value in a non-nil // Format selects generated artifact metadata. An empty value in a non-nil
// request replacement defaults to FormatText. // request replacement defaults to FormatText.
@@ -502,7 +506,9 @@ type OutputContract struct {
// ValidationMode selects the content check. Use one of the declared // ValidationMode selects the content check. Use one of the declared
// ValidationMode constants. // ValidationMode constants.
ValidationMode ValidationMode `json:"validation_mode"` ValidationMode ValidationMode `json:"validation_mode"`
// Schema supplies an inline JSON Schema. Nil means no inline selection. // Schema supplies an inline JSON Schema. Nil or a value encoding as JSON
// null means no selection; false and an empty object are selections. In
// JSON Schema mode the value must be JSON-encodable.
Schema any `json:"schema,omitempty"` Schema any `json:"schema,omitempty"`
// SchemaPath identifies a schema under the applicable configured root. // SchemaPath identifies a schema under the applicable configured root.
SchemaPath string `json:"schema_path"` SchemaPath string `json:"schema_path"`
@@ -522,7 +528,8 @@ type ValidationResult struct {
Mode ValidationMode `json:"mode"` Mode ValidationMode `json:"mode"`
// Errors contains validation diagnostics when Status is ValidationFailed. // Errors contains validation diagnostics when Status is ValidationFailed.
Errors []string `json:"errors,omitempty"` Errors []string `json:"errors,omitempty"`
// SchemaPath is the effective schema path for JSON Schema validation. // SchemaPath is the explicit-root path for JSON Schema validation. It is
// empty for inline and source-relative schema selections.
SchemaPath string `json:"schema_path,omitempty"` SchemaPath string `json:"schema_path,omitempty"`
// RepairAttempts is the number of corrective generation calls actually // RepairAttempts is the number of corrective generation calls actually
// started for this result. // started for this result.