Lower compound literals for Codex schemas

This commit is contained in:
Meta Vens 2026-08-28 16:31:04 +02:00
commit ec153a9e87
2 changed files with 172 additions and 3 deletions

View file

@ -293,6 +293,14 @@ fn responses_schema_is_strict(schema: &serde_json::Value) -> bool {
if map.contains_key("$ref") && map.len() != 1 {
return false;
}
if map.get("const").is_some_and(|value| {
matches!(
value,
serde_json::Value::Array(_) | serde_json::Value::Object(_)
)
}) {
return false;
}
if (map.contains_key("const") || map.contains_key("enum")) && !map.contains_key("type")
{
return false;
@ -468,6 +476,86 @@ fn infer_responses_literal_type(map: &mut serde_json::Map<String, serde_json::Va
}
}
fn compound_const_array_item_schema(values: &[serde_json::Value]) -> serde_json::Value {
if values.is_empty() {
// maxItems: 0 makes this item type unreachable, but the Responses
// schema dialect still expects arrays to declare an item shape.
return serde_json::json!({"type":"string"});
}
if values.iter().all(serde_json::Value::is_string) {
let values = values
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect::<BTreeSet<_>>()
.into_iter()
.collect::<Vec<_>>();
return if values.len() == 1 {
serde_json::json!({"type":"string", "const":values[0]})
} else {
serde_json::json!({"type":"string", "enum":values})
};
}
let mut alternatives = Vec::new();
let mut seen = BTreeSet::new();
for value in values {
let mut alternative = serde_json::json!({"const":value});
lower_schema_for_responses_format(&mut alternative);
let digest = serde_json::to_string(&alternative).expect("JSON schema serializes");
if seen.insert(digest) {
alternatives.push(alternative);
}
}
if alternatives.len() == 1 {
alternatives.pop().expect("one alternative")
} else {
serde_json::json!({"anyOf":alternatives})
}
}
fn lower_compound_const(map: &mut serde_json::Map<String, serde_json::Value>) {
let Some(value) = map.get("const").cloned() else {
return;
};
match value {
serde_json::Value::Array(values) => {
map.remove("const");
map.insert("type".to_string(), serde_json::json!("array"));
map.insert("minItems".to_string(), serde_json::json!(values.len()));
map.insert("maxItems".to_string(), serde_json::json!(values.len()));
map.insert(
"items".to_string(),
compound_const_array_item_schema(&values),
);
}
serde_json::Value::Object(values) => {
map.remove("const");
map.insert("type".to_string(), serde_json::json!("object"));
map.insert(
"required".to_string(),
serde_json::Value::Array(
values
.keys()
.cloned()
.map(serde_json::Value::String)
.collect(),
),
);
map.insert(
"properties".to_string(),
values
.into_iter()
.map(|(name, value)| (name, serde_json::json!({"const":value})))
.collect::<serde_json::Map<_, _>>()
.into(),
);
map.insert("additionalProperties".to_string(), serde_json::json!(false));
}
_ => {}
}
}
fn nullable_responses_property(property: serde_json::Value) -> serde_json::Value {
if property
.get("anyOf")
@ -519,6 +607,7 @@ fn lower_schema_for_responses_format(schema: &mut serde_json::Value) {
let serde_json::Value::Object(map) = schema else {
return;
};
lower_compound_const(map);
infer_responses_literal_type(map);
if map.get("format").and_then(serde_json::Value::as_str) == Some("uuid") {
map.remove("format");
@ -698,6 +787,74 @@ mod tests {
Ok(())
}
#[test]
fn strict_schema_projection_lowers_compound_literals_only_on_the_provider_clone() -> Result<()>
{
fn contains_compound_const(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::Object(map) => {
map.get("const").is_some_and(|value| {
matches!(
value,
serde_json::Value::Array(_) | serde_json::Value::Object(_)
)
}) || map.values().any(contains_compound_const)
}
serde_json::Value::Array(values) => values.iter().any(contains_compound_const),
_ => false,
}
}
let native = serde_json::json!({
"type":"object",
"required":["empty", "ids", "manifest"],
"properties":{
"empty":{"type":"array", "const":[]},
"ids":{"type":"array", "const":["council:a", "council:b"]},
"manifest":{
"type":"object",
"const":{
"governing_ids":["council:a", "council:b"],
"schema":"fixture.v1"
}
}
},
"additionalProperties":false
});
let mut projected = native.clone();
project_strict_responses_schema(&mut projected)?;
assert!(contains_compound_const(&native));
assert!(!contains_compound_const(&projected));
assert_eq!(projected["properties"]["empty"]["minItems"], 0);
assert_eq!(projected["properties"]["empty"]["maxItems"], 0);
assert_eq!(projected["properties"]["empty"]["items"]["type"], "string");
assert_eq!(projected["properties"]["ids"]["minItems"], 2);
assert_eq!(projected["properties"]["ids"]["maxItems"], 2);
assert_eq!(
projected["properties"]["ids"]["items"]["enum"],
serde_json::json!(["council:a", "council:b"])
);
assert_eq!(
projected["properties"]["manifest"]["additionalProperties"],
false
);
assert!(responses_schema_is_strict(&projected));
let reordered = serde_json::json!({
"empty":[],
"ids":["council:a", "council:a"],
"manifest":{
"governing_ids":["council:b", "council:a"],
"schema":"fixture.v1"
}
});
assert!(jsonschema::validator_for(&projected)?.is_valid(&reordered));
assert!(!jsonschema::validator_for(&native)?.is_valid(&reordered));
Ok(())
}
#[test]
fn strict_schema_projection_rejects_ref_siblings_before_provider_submission() {
let mut schema = serde_json::json!({

View file

@ -936,6 +936,16 @@ object is never accepted as a substitute for route, relationship, assignment,
or facet authority. Canonical campaign and resolution documents retain their
map-shaped storage contracts.
The Codex/OpenAI connector owns one further provider-only projection for exact
compound literals. Scalar `const` values survive. Array and object `const`
values lower recursively to the supported strict Responses subset: fixed array
lengths with bounded item literals, or closed objects with every exact key
required. Array ordering and multiplicity are necessarily wider at this
transport layer. The native request schema remains unchanged, and its consumer
validator still owns exact equality before any proposal can reach admission.
No compiler, elaborator title, or generic agent loop carries a provider-specific
repair for this dialect boundary.
`F:\Projects\Kalsa` is the first bundled fantasy Vault canary. Its typed
manifest makes the `Public` tree player-safe world knowledge and the `Spoilers`
tree GM-only canon; workshop material is non-canonical. Selection, Git/Obsidian
@ -1036,9 +1046,11 @@ owns each dispatch's exact operation contract: it derives the instruction,
projects the generated structured-output schema down to the assigned variant
and deterministic values, and validates the submitted proposal against the
frozen snapshot. The provider-backed worker only routes that assignment through
the generic `ModelAgent`; the harness owns the bounded two-step transcript/tool
loop and receipt chain, not world semantics. Local rejection returns as the
next tool observation. Patina, Ledger, Hearth,
the generic `ModelAgent`; the connector may structurally widen unsupported
compound literals on its private schema clone, while this unchanged assignment
validator retains exact semantic authority. The harness owns the bounded
two-step transcript/tool loop and receipt chain, not world semantics. Local
rejection returns as the next tool observation. Patina, Ledger, Hearth,
Veil, and Ember use the fast model class; Charter and Tangle use balanced;
Numen uses capable. The worker returns the complete action/tool receipt chain
with its proposal. A failed wave returns the consumed schedule, every completed