Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

fix/Anything-slot-shaping · L-260902-10eb56 (#1287)

Louis Choquel22e3dcd7f5bf
diff --git a/.test_durations b/.test_durations
index 800717a4b..6011f6fe4 100644
--- a/.test_durations
+++ b/.test_durations
@@ -728,12 +728,12 @@
"tests/integration/pipelex/pipeline/test_optional_method_inputs.py::TestOptionalMethodInputs::test_preexisting_absence_record_keeps_its_provenance": 0.06,
"tests/integration/pipelex/pipeline/test_optional_method_inputs.py::TestOptionalMethodInputs::test_provided_optional_input_leaves_no_record": 0.0748,
"tests/integration/pipelex/pipeline/test_pipe_io_artifacts.py::TestBuildPipeIOArtifacts::test_equals_the_three_builders_in_sequence_and_shares_one_key_set": 0.6938,
- "tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_anything_input_publishes_permissive_schema": 0.4712,
+ "tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_anything_input_publishes_its_schema": 0.4712,
"tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_multiplicity_entry_shapes": 1.4763,
"tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_optional_markers_reported_on_contracts": 3.2615,
"tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_schema_render_failure_converts_to_structured_error": 1.4442,
"tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_signature_pipes_in_lenient_batch": 1.1716,
- "tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_structureless_output_renders_permissively": 1.0264,
+ "tests/integration/pipelex/pipeline/test_pipe_io_contracts.py::TestBuildPipeIOContracts::test_structureless_output_renders_its_schema": 1.0264,
"tests/integration/pipelex/pipeline/test_pipeline_run_id_resubmission.py::TestPipelineRunIdResubmission::test_failure_clears_registry_entry": 0.3555,
"tests/integration/pipelex/pipeline/test_pipeline_run_id_resubmission.py::TestPipelineRunIdResubmission::test_setup_failure_frees_entry_even_when_tracer_teardown_raises": 0.6068,
"tests/integration/pipelex/pipeline/test_pipeline_run_id_resubmission.py::TestPipelineRunIdResubmission::test_setup_failure_self_cleans_and_same_id_resubmits": 0.391,
@@ -5970,7 +5970,7 @@
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_json_single_is_empty_mapping": 0.5727,
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_python_format_is_refused": 0.1758,
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_schema_fixed_count_bounds_the_array": 0.0342,
- "tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_schema_single_is_annotated_permissive": 0.3844,
+ "tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_schema_single_excludes_array_and_null": 0.3844,
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecStructurelessRender::test_schema_variable_list_wraps_in_unbounded_array": 0.3682,
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecToBundleRepresentation::test_presence_defaults_to_plain": 0.0006,
"tests/unit/pipelex/core/pipes/test_stuff_spec.py::TestStuffSpecToBundleRepresentation::test_to_bundle_representation_with_custom_domain_concept": 0.0007,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a0b39445..19e42bbea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,27 @@
# Changelog
+## [Unreleased]
+
+### Changed
+
+- **A bare string at an `Anything` input is an `Anything` value (Breaking)**: it becomes a `native.Anything` stuff holding text, where it used to become a `native.Text` stuff.
+- **A `JSON` input reads a JSON object literally (Breaking)**: a bare string at a `JSON` input is refused instead of becoming `native.Text`, the compact inputs template of a `JSON` input is the bare object rather than the envelope `{"concept": "native.JSON", "content": {"json_obj": …}}`, and a `JSONContent` holding a value JSON cannot encode, such as a date or a set, raises a pydantic `ValidationError` instead of a `TypeError`.
+- **An envelope-shaped item of a bare `Anything[]` or `JSON[]` list is refused (Breaking)**: an item holding `concept` and `content` keys is no longer read as data; wrap the whole list in one envelope to type it.
+- **A value the fallback has no reading for is a `StructureValidationError` (Breaking)**: at a `Dynamic` or container-native input, a bare value the bottom-up reading cannot build, such as a list of plain objects, raises `StructureValidationError` naming the input and its concept instead of an unnamed `StuffFactoryError`, and its next step names the declaration that reads the value (`JSON`, `JSON[]`, `Anything` or `Anything[]`) when one does.
+- **An explicit single value at a fixed-count input is refused (Breaking)**: an envelope holding one value at a `Concept[N]` input raises `MultiplicityCountMismatchError` instead of being stored as a single value.
+- **NaN and the infinities are refused at `Number`, `JSON` and `Anything` inputs (Breaking)**: a TOML inputs file can spell `nan` and `inf`, which JSON cannot hold, so a `Number` or `Anything` input given one raises `WrongScalarKindError`, and an object holding one anywhere inside it raises `StructureValidationError`, where each used to store a number that JSON serialization turns into `null`. A `JSONContent` or a `NumberContent` holding one raises a pydantic `ValidationError`, which is also what an explicit envelope building one reports.
+- **Chaining an `Anything` value through `--with-memory` changes it (Breaking)**: an `Anything` stuff's content is dumped as its content class's fields, so a bare `"hi"` sent to an `Anything` input is dumped as `{"text": "hi"}`, and a method reading that memory at an `Anything` input receives that object rather than the string; a list is dumped as one object holding its `items`. It used to travel as `native.Text`, since a bare string at an `Anything` input became a `native.Text` stuff.
+- **The `Anything` input schema excludes array and null**: the JSON Schema published for an `Anything` input carries `"not": {"type": ["array", "null"]}`, and so does each item of an `Anything[]` input's schema.
+
+### Fixed
+
+- **`Anything` inputs take any JSON value**: a string, a number, a boolean, an object or a date at an `Anything` input becomes its natural content under the `Anything` concept, `Anything[]` takes a list of them, a prebuilt list mixing contents of different kinds included, and a typed envelope keeps its own concept; they used to be refused, a bare string aside. A sequence declaring an `Anything` output over a narrower last step now validates.
+- **`JSON` inputs take objects and lists of objects**: a JSON object at a `JSON` input, and a list of them at a `JSON[]` input, now build, where a list of plain objects used to be refused with an error naming neither the input nor its concept.
+- **A single `Anything` value survives the transport boundary**: a stuff whose concept is `native.Anything` keeps its content's class through `dump_for_transport` and hydration, which a distributed or sandboxed run relies on; hydration used to fail looking for an `AnythingContent` class.
+- **A composite nested in an `Anything` value or in another composite survives transport**: its components, a nested composite and a list of composites included, come back through hydration as typed contents, where they came back as dicts carrying class markers.
+- **The result files of an `Anything` output render its value**: a delivery whose main output is `Anything` renders `main_stuff.json`, `.md` and `.html` from the hydrated content, where it fell back to a raw dump of the transport form.
+- **A prebuilt list is refused where one value belongs**: a `ListContent` given as an item of a plural input, or as the content of an `Anything` envelope at a single input, is refused instead of being stored nested or in a singular slot.
+
## [v0.68.0] - 2026-09-27
### Highlights
diff --git a/docs/building-methods/concepts/native-concepts.md b/docs/building-methods/concepts/native-concepts.md
index 348246474..263d10ed1 100644
--- a/docs/building-methods/concepts/native-concepts.md
+++ b/docs/building-methods/concepts/native-concepts.md
@@ -41,6 +41,36 @@ Here are all the native concepts you can use out of the box:
| `Composite` | A named composition of contents | `CompositeContent` |
| `Anything` | Any type of content | *No specific implementation* |
+## Choosing among `Anything`, `JSON` and `Dynamic`
+
+Three natives hold data whose shape your method does not describe, and each takes a different kind of input. Choose in this order:
+
+1. **Data you already have as JSON objects: name it.** Declare a concept that refines `JSON`, with a plain-language description. It takes the object exactly as you have it, with no data model to write, and its name and description tell an agent or a reader what the object means, which a bare `JSON` does not. When you later want the fields validated, turn it into a concept with a structure.
+2. **`JSON` or `JSON[]`** when the data has no name worth giving it. `JSON` is a JSON object, not any JSON value; a list of objects is `JSON[]`.
+3. **`Anything`** when the pipe is generic over its input: it passes a value along or renders it, whatever it is. It is not the place to put JSON data.
+4. **`Dynamic`** is not recommended for inputs for now: what a `Dynamic` input holds is still being settled.
+
+For example, a pipe summarizing orders from a shop's API names them:
+
+```toml
+[concept.Order]
+description = "A customer order, as the shop's API returns it"
+refines = "JSON"
+
+[pipe.summarize_order]
+type = "PipeLLM"
+description = "Summarize a customer order"
+inputs = { order = "Order" }
+output = "Text"
+prompt = """
+Summarize this order in two sentences:
+
+@order
+"""
+```
+
+The input is the object itself, `{"order": {"id": 42, "items": [{"sku": "A-1", "quantity": 2}]}}`, and a list of orders would be declared `Order[]`.
+
## Native Concept Structures
Each native concept has a corresponding Python structure that defines its data model. Understanding these structures helps you work with the data they contain.
@@ -240,6 +270,10 @@ class JSONContent(StuffContent):
json_obj: dict[str, Any]
```
+A `JSON` input takes a JSON object as it is, `{"a": 1}`, and its inputs template shows the bare object; `JSON[]` takes a list of objects. `JSON` is a JSON object, not any JSON value, so a string or a number there is refused. The explicit form carries the content form: `{"concept": "JSON", "content": {"json_obj": {"a": 1}}}`.
+
+**Use for:** Data you already have as JSON objects, preferably through a concept that refines `JSON` (see [Choosing among `Anything`, `JSON` and `Dynamic`](#choosing-among-anything-json-and-dynamic)).
+
### HtmlContent
Represents HTML content with styling:
@@ -289,8 +323,12 @@ Each named sub-content is a top-level field of the composite — there is no wra
### Anything
-!!! note "Special Concepts"
- `Anything` is referenced in the native concept definitions but does not have specific implementations. It is handled through the generic content system and is primarily used as semantic markers.
+`Anything` has no content class of its own: an `Anything` value is held in the content class matching what it is.
+
+- **As an input**, it takes any JSON value but an array or null. A string, a number, a boolean or an object becomes text, a number, a yes/no or a JSON object, and the input keeps the `Anything` concept. A typed envelope, `{"concept": "Text", "content": "hi"}`, hands it a specific concept, which it keeps, since every concept satisfies `Anything`. `Anything[]` takes a list of such values.
+- **As an output**, it promises nothing narrower: a pipe declared to output `Anything` may produce any concept.
+
+**Use for:** Pipes that are generic over their input, passing a value along or rendering it whatever it is.
## Using Native Concepts
diff --git a/docs/building-methods/concepts/refining-concepts.md b/docs/building-methods/concepts/refining-concepts.md
index aee5bd766..707ec31ae 100644
--- a/docs/building-methods/concepts/refining-concepts.md
+++ b/docs/building-methods/concepts/refining-concepts.md
@@ -166,6 +166,16 @@ description = "A condensed version of a longer text"
refines = "Text"
```
+### Refining JSON
+
+Data you already have as JSON objects is best named by a concept refining `JSON`. It takes the object exactly as you have it, with no structure to write, and its name and description say what the object means. See [Choosing among `Anything`, `JSON` and `Dynamic`](native-concepts.md#choosing-among-anything-json-and-dynamic).
+
+```toml
+[concept.Order]
+description = "A customer order, as the shop's API returns it"
+refines = "JSON"
+```
+
### Building Concept Hierarchies
You can build hierarchies by refining concepts that have their own structures. The refined concept inherits the structure from the base concept:
diff --git a/docs/building-methods/pipes/provide-inputs.md b/docs/building-methods/pipes/provide-inputs.md
index b9ebae8e4..2238b6eb4 100644
--- a/docs/building-methods/pipes/provide-inputs.md
+++ b/docs/building-methods/pipes/provide-inputs.md
@@ -59,7 +59,7 @@ Match the value to the input's declared concept. The declared concept is applied
| Declared concept refines… | Provide | Example |
| --- | --- | --- |
| `Text` | a string | `"What are the fees?"` |
-| `Number` | a number (not a boolean) | `42` or `3.14` |
+| `Number` | a finite number (not a boolean, not NaN or an infinity) | `42` or `3.14` |
| `YesNo` | a boolean | `true` / `false` |
| `Date` | an extended ISO 8601 date/datetime string (or a TOML date literal) | `"2026-09-01"` |
| `Image` / `Document` | a URL or file path | `"photo.jpg"`, `"https://…/a.pdf"` |
@@ -84,8 +84,15 @@ Each value is typed as the **declared** concept — `question` becomes a `legal.
!!! note "Numbers vs. booleans"
A boolean is never read as a number, even though `true`/`false` look numeric to some languages. Provide `true`/`false` only for a `YesNo`-refining input; provide `42` for a `Number`-refining one.
+!!! note "`Anything` and `JSON` inputs"
+ An input declared `Anything` takes any JSON value but an array or null: a string, a number, a boolean or an object becomes the matching content (text, number, yes/no, JSON object), and the input keeps the `Anything` concept. Provide a typed envelope, `{"concept": "Text", "content": "hi"}`, to hand it a specific concept instead, which it keeps. `Anything[]` takes a list of such values. A working memory dumps an `Anything` stuff's content as its content class's fields, `{"text": "hi"}` for a string, so a `--with-memory` envelope piped into another method's `Anything` input hands it that object rather than the original value.
+
+ An input declared `JSON` takes a JSON object as it is, and `JSON[]` takes a list of them; its inputs template shows the bare object. A string or a number at a `JSON` input is refused.
+
+ In a bare list for `Anything[]` or `JSON[]`, an item shaped like an envelope (an object with `concept` and `content` keys) is refused rather than guessed at. To type a list, wrap the whole list in one envelope instead.
+
!!! note "Concepts the signature can't shape"
- A handful of concepts carry no single expected value shape — `Dynamic`, `Anything`, and the container/structural natives (`Html`, `JSON`, `Page`, `TextAndImages`, `SearchResult`, `Composite`). For an input declared as one of these, the signature can't guide interpretation, so the value is read by its own shape (a bare string becomes `native.Text`, and so on). Use the explicit format if you need a specific concept there.
+ A few concepts still carry no single expected value shape — `Dynamic` and the container natives (`Html`, `Page`, `TextAndImages`, `SearchResult`, `Composite`). For an input declared as one of these, the value is read by its own shape (a bare string becomes `native.Text`, and so on), and a value with no reading, such as a list of plain objects, is refused with an error naming the input and the declaration to change. Use the explicit format if you need a specific concept there.
## Lists and multiplicity
diff --git a/docs/contribute/generate-projection-corpus.md b/docs/contribute/generate-projection-corpus.md
index 9a9b9db65..bdf6b00ce 100644
--- a/docs/contribute/generate-projection-corpus.md
+++ b/docs/contribute/generate-projection-corpus.md
@@ -66,15 +66,15 @@ The verdict follows the same declared-never-discovered discipline as the diverge
The manifest holds the error's **class name**, never its message. The class name is contract-stable — the error-identity snapshot makes a rename a reviewable diff — while the message is wording that would churn these committed bytes across pydantic versions, so it goes to the console and to the refusal only. Passing verdicts are printed as a count, never committed: a template the shaper takes back is the state every entry is working towards, not a fact worth pinning.
-Two gaps are declared today, and each entry names the item whose fix retires it. One is a descriptor gap — a nested list inside a structure — which takes both shapes of the two probe pipes that reach it. The other is `native.Anything`, whose slot the input shaper refuses: it accepts a bare string alone at an `Anything` position, so the empty object the contract publishes as that slot's template is a template the runtime cannot take back. Closing either one deletes its own entries; the lapse rule fails the command until somebody does.
+One gap is declared today, and its entries name the item whose fix retires it: a descriptor gap — a nested list inside a structure — which takes both shapes of the two probe pipes that reach it. Closing it deletes its entries; the lapse rule fails the command until somebody does.
-A key is a whole template and never a slot, and the shaper stops at the first slot it refuses — so an entry suspends this check for every other slot in the same pipe. Put a known-open gap in a pipe of its own rather than declaring the pipe that happens to contain it: `scaffold_anything_slot` exists for exactly that reason, so that `scaffold_open_natives` beside it keeps round-tripping and the `unknown-empty-object` claim keeps the one site that demonstrates it.
+A key is a whole template and never a slot, and the shaper stops at the first slot it refuses — so an entry suspends this check for every other slot in the same pipe. Put a known-open gap in a pipe of its own rather than declaring the pipe that happens to contain it, so that the slots beside it keep round-tripping and every divergence claim keeps the sites that demonstrate it.
## The bundles
-`tests/data/input_semantics/` holds the corpus bundles, and the command above names every one of them: a bundle that exists in that directory but is left off the command line does not appear in the capture, and the regeneration silently drops the pipes it contributed. `probe_bundle.mthds` exercises every construct the language accepts and `hinted_bundle.mthds` the intent hints; `output_bundle.mthds` covers the output form specifically, since every bundle before it resolved to `Text`; `scaffold_bundle.mthds` was added for this corpus and covers what the others do not — a text field merely named `url` beside a real file position, an optional nested structure, optional `native.Image` and `native.Document` fields inside a structure, and both a fixed `[N]` and a variable `[]` slot over a structured concept. Its `scaffold_open_natives` pipe holds the natives whose payload shape the descriptor states openly, at slot positions: `native.Dynamic` and `native.Composite`, which declare no pinned structure and whose node is therefore `unknown`, beside `native.JSON`, which does declare one — its pinned blueprint carries a required `json_obj`, so it expands like any other pinned native and its dict is where `unknown-empty-object` is measured. Its `scaffold_dynamic_prompt` pipe puts a `native.Dynamic` slot at an LLM prompt position under both markers, which the corpus could not carry while the prompt analyzers read a dynamic concept's universal compatibility as identity and demanded an `ImageContent` for it.
+`tests/data/input_semantics/` holds the corpus bundles, and the command above names every one of them: a bundle that exists in that directory but is left off the command line does not appear in the capture, and the regeneration silently drops the pipes it contributed. `probe_bundle.mthds` exercises every construct the language accepts and `hinted_bundle.mthds` the intent hints; `output_bundle.mthds` covers the output form specifically, since every bundle before it resolved to `Text`; `scaffold_bundle.mthds` was added for this corpus and covers what the others do not — a text field merely named `url` beside a real file position, an optional nested structure, optional `native.Image` and `native.Document` fields inside a structure, and both a fixed `[N]` and a variable `[]` slot over a structured concept. Its `scaffold_open_natives` pipe holds the natives whose payload shape the descriptor states openly, at slot positions: `native.Dynamic`, `native.Composite` and `native.Anything`, which declare no pinned structure and whose node is therefore `unknown`, beside `native.JSON`, which does declare one — its pinned blueprint carries a required `json_obj`, so its explicit template expands like any other pinned native's, while its compact template is the bare object with `json_obj` unwrapped, and that dict is where `unknown-empty-object` is measured. Its `scaffold_dynamic_prompt` pipe puts a `native.Dynamic` slot at an LLM prompt position under both markers, which the corpus could not carry while the prompt analyzers read a dynamic concept's universal compatibility as identity and demanded an `ImageContent` for it.
-`native.Anything` is the third of that family, and it sits in `scaffold_anything_slot` on its own — the one slot the corpus carries knowing the runtime refuses it. It no longer crashes the engine's renderer — the structureless arm renders it without resolving a class — but its template value is the empty mapping `{}`, which the input shaper takes back in neither shape: at an `Anything` position the shaper accepts a bare string alone, and returns it as a `native.Text` stuff rather than an `Anything` one. That is a runtime gap, not a projection one — the descriptor states `Anything` as `unknown` exactly as it states `Dynamic` and `Composite`, and a projection reading only the descriptor has nothing to render there but the empty object. So the slot is captured and both shapes of its own pipe are declared in `EXPECTED_UNSHAPEABLE` against the item tracking the shaper fix, which is the mechanism this page describes for a known-open gap. Giving it a pipe to itself is what keeps that declaration from reaching the three natives beside it that do round-trip. Closing it deletes those entries and regenerates.
+`native.Anything`'s compact template keeps its envelope, `{"concept": "native.Anything", "content": {}}`, in the engine and in every projection: its bare placeholder, `{}`, would read as "send an object", while the envelope names the concept that says any value goes. The input shaper takes that envelope back, reading its empty object as a JSON object under the `Anything` concept.
## When to rerun it
diff --git a/docs/errors/structure-validation-error.md b/docs/errors/structure-validation-error.md
index 80778cfc3..9c7a52063 100644
--- a/docs/errors/structure-validation-error.md
+++ b/docs/errors/structure-validation-error.md
@@ -3,11 +3,19 @@ title: "Structure validation"
description: "Reference for the `StructureValidationError` Pipelex error class."
---
-<!-- pipelex:generated -->
+<!-- pipelex:authored -->
# Structure validation
-A provided value failed to validate against the declared concept's structure (D4/D5).
+A provided input value could not be built as the concept its input declares.
+
+Most often the value is the right JSON kind but does not fit the concept's structure: an object missing a required field, a malformed `{"url": ...}` for an image or a document, a string that is not an ISO date for a `Date` input. The message names the input and the declared concept, and ends with the expected shape rendered from the method's signature. The fix is the value.
+
+The other case is a value that an input reading bare values by their own shape has no reading for. An input declared `Dynamic`, or as one of the container natives (`Html`, `Page`, `TextAndImages`, `SearchResult`, `Composite`), reads a bare value that way, and some values have none: a number, or a list of plain objects. The message says so, `Input 'records' could not be built as 'native.Dynamic': you provided a list of 2 item(s), and an input of this concept reads a bare value by its own shape, with no reading for this one.`, and its next step names the declaration that would read the value: `JSON` for an object, `JSON[]` for a list of objects, `Anything` or `Anything[]` for anything else, or a concept with a structure that describes it. The fix is usually the method's declaration rather than the value.
+
+When no declaration reads the value, such as an empty list at a `Html[]` input, a list mixing prebuilt contents of different kinds, or a list holding nulls or nested lists, the message carries the reason itself.
+
+The error is in the `input` domain, so an HTTP surface answers 422.
| Field | Value |
|---|---|
diff --git a/docs/under-the-hood/pipe-io-contracts.md b/docs/under-the-hood/pipe-io-contracts.md
index d3e30175f..88f1cff1b 100644
--- a/docs/under-the-hood/pipe-io-contracts.md
+++ b/docs/under-the-hood/pipe-io-contracts.md
@@ -37,9 +37,9 @@ The JSON Schema on an input names its concept: `title` is the `concept_ref`, `de
## The one concept with no structure class: `native.Anything`
-`native.Anything` is the only concept that declares no structure class, so its input schema cannot come from a pydantic render. (That is a different question from the three natives which declare no *pinned structure* — `Dynamic`, `Anything`, `Composite` — and therefore render as `unknown` in the [input-form descriptor](input-form-descriptor.md).) It publishes the **permissive schema**: no constraint keywords, only the identity annotations every rendered input schema carries — `{"title": "native.Anything", "description": "…"}`. Annotation keywords constrain nothing, so this is semantically the empty schema (any JSON value), which is what an untyped vehicle means, while consumers still see the concept's identity instead of a bare `{}` they would have to special-case. Multiplicity wraps exactly as above: `Anything[]` is an array of that schema, a fixed count adds the bounds.
+`native.Anything` is the only concept that declares no structure class, so its input schema cannot come from a pydantic render. (That is a different question from the three natives which declare no *pinned structure* — `Dynamic`, `Anything`, `Composite` — and therefore render as `unknown` in the [input-form descriptor](input-form-descriptor.md).) It publishes the identity annotations every rendered input schema carries and one constraint — `{"title": "native.Anything", "description": "…", "not": {"type": ["array", "null"]}}`. An `Anything` value is any JSON value but an array or null: a list is the multiplicity's to express, as `Anything[]`, and null is never an input. Multiplicity wraps exactly as above: `Anything[]` is an array of that schema, so every item carries the same exclusion, and a fixed count adds the bounds.
-The schema states what the *concept* admits, not what today's input shaper accepts: an `Anything` slot currently takes a string (shaped into a `native.Text` stuff) and refuses the other JSON types. Narrowing the published schema to match would be stating a runtime limitation as a contract, so the schema stays permissive and the shaper is what has to catch up.
+The schema and the input shaper agree on what a value may be: a string, a number, a boolean or an object at an `Anything` slot is shaped into its natural content (text, number, yes/no, JSON object) under the `native.Anything` concept, and an array or null at a single slot is refused, as the schema says. The two differ in two places the schema does not state: it wraps a single bare value sent to an `Anything[]` input into a one-item list, and it refuses an `Anything[]` item keyed exactly `concept` and `content`, which reads as an envelope.
## Which surfaces carry it
diff --git a/pipelex/cli/dev_cli/commands/generate_projection_corpus_cmd.py b/pipelex/cli/dev_cli/commands/generate_projection_corpus_cmd.py
index dfa0b7a9b..316d0b4d4 100644
--- a/pipelex/cli/dev_cli/commands/generate_projection_corpus_cmd.py
+++ b/pipelex/cli/dev_cli/commands/generate_projection_corpus_cmd.py
@@ -42,7 +42,10 @@ from pipelex.base_exceptions import PipelexError
from pipelex.cli.cli_factory import make_pipelex_for_cli
from pipelex.cli.dev_cli.commands.projection_reference import (
ENVELOPE_CONTENT_KEY,
+ JSON_CONTENT_KEY,
+ NATIVE_JSON,
keeps_envelope,
+ native_code,
project_concept_comments,
project_inputs_template,
)
@@ -143,19 +146,14 @@ DIVERGENCE_ITEMS: dict[str, str] = {
# that carries nothing else; where a corpus bundle would otherwise mix it with slots that do shape,
# the bundle isolates it instead of widening the declaration.
#
-# Two gaps are declared. `L-260830-191719` is the nested-list descriptor gap (`matrix` in `Widget`),
-# which takes both shapes of both probe pipes that reach it. `L-260902-10eb56` is `native.Anything`,
-# which is why `scaffold_anything_slot` holds that native alone: its template value is the empty
-# object every `unknown` node renders, and the shaper accepts a bare string alone at an `Anything`
-# position — so the contract publishes a template the runtime cannot take back. Each fix deletes its
-# own entries and regenerates.
+# One gap is declared: `L-260830-191719`, the nested-list descriptor gap (`matrix` in `Widget`),
+# which takes both shapes of both probe pipes that reach it. Its fix deletes its entries and
+# regenerates.
EXPECTED_UNSHAPEABLE: dict[tuple[str, str], str] = {
("input_semantics_probe.probe_markers", COMPACT_SHAPE): "L-260830-191719",
("input_semantics_probe.probe_markers", EXPLICIT_SHAPE): "L-260830-191719",
("input_semantics_probe.probe_single", COMPACT_SHAPE): "L-260830-191719",
("input_semantics_probe.probe_single", EXPLICIT_SHAPE): "L-260830-191719",
- ("input_semantics_scaffold.scaffold_anything_slot", COMPACT_SHAPE): "L-260902-10eb56",
- ("input_semantics_scaffold.scaffold_anything_slot", EXPLICIT_SHAPE): "L-260902-10eb56",
}
@@ -236,16 +234,15 @@ def _write_text(*, path: Path, content: str) -> None:
path.write_text(content, encoding="utf-8")
-def _engine_dict_placeholder(*, path: list[str]) -> dict[str, str]:
+def _engine_dict_placeholder(*, field_name: str) -> dict[str, str]:
"""What the engine renders at a dict-typed field, which is exactly where the descriptor says `unknown`.
`ConceptRepresentationGenerator._generate_dict_value` returns `{f"{name}_key": f"{name}_value"}`,
and `generate_field_value` is its only caller — dispatched on `origin is dict`, the same test that
makes the input-form deriver state the node as `unknown`. A dict inside a list never reaches it
(`_generate_list_value` routes items through `_generate_basic_value`, which returns no dicts), so
- the placeholder is always keyed by the field's own name — the last segment of the walk's path.
+ the placeholder is always keyed by the field's own name.
"""
- field_name = path[-1]
return {f"{field_name}_key": f"{field_name}_value"}
@@ -274,6 +271,8 @@ class DivergenceCollector:
self.examples: dict[str, list[DivergenceExample]] = {}
self.unclassified: list[str] = []
self._fixed_counts: dict[tuple[str, ...], int] = {}
+ self._json_slot_paths: set[tuple[str, ...]] = set()
+ self._json_list_slot_paths: set[tuple[str, ...]] = set()
def register_fixed_counts(self, *, pipe_ref: str, descriptor: PipeInputFormDescriptor) -> None:
"""Record where this pipe's descriptor declares a fixed element count, by the path the walk meets.
@@ -299,6 +298,28 @@ class DivergenceCollector:
else:
self._fixed_counts[pipe_ref, COMPACT_SHAPE, field.name] = field.item_count
+ def register_json_unwraps(self, *, pipe_ref: str, descriptor: PipeInputFormDescriptor) -> None:
+ """Record where this pipe's compact shape unwraps a `native.JSON` slot, by the path the walk meets.
+
+ The compact shape renders a `JSON` slot, or each item of a `JSON[]` slot, as the object its
+ `json_obj` holds, so the walk meets the engine's dict placeholder at the slot's own path (or
+ at an item's index) rather than at a segment named `json_obj`. The placeholder is keyed by
+ the field that holds the dict, which only the descriptor can name there. Only top-level slots
+ unwrap: a `JSON` node nested in a structure keeps its content form in both shapes.
+ """
+ for field in descriptor.fields:
+ if isinstance(field, ListField):
+ if native_code(node=field.item) == NATIVE_JSON:
+ self._json_list_slot_paths.add((pipe_ref, COMPACT_SHAPE, field.name))
+ elif native_code(node=field) == NATIVE_JSON:
+ self._json_slot_paths.add((pipe_ref, COMPACT_SHAPE, field.name))
+
+ def _dict_field_name(self, *, path: list[str]) -> str:
+ """The name of the field holding the dict at `path`: its last segment, unless an unwrapped `JSON` slot sits there."""
+ if tuple(path) in self._json_slot_paths or tuple(path[:-1]) in self._json_list_slot_paths:
+ return JSON_CONTENT_KEY
+ return path[-1]
+
def _record(self, *, divergence_id: str, path: list[str], engine: Any, expected: Any) -> None:
self.counts[divergence_id] = self.counts.get(divergence_id, 0) + 1
sites = self.examples.setdefault(divergence_id, [])
@@ -323,7 +344,8 @@ class DivergenceCollector:
# time: a projection rendering nothing where the engine renders an object is one fact, not N.
# Reached by the required dict inside `native.JSON` — `json_obj`, whose descriptor node is
# `unknown` like every dict field, so the projection renders the empty object while the
- # engine fills it with a sample key. The corpus's optional dict fields never reach here:
+ # engine fills it with a sample key. In the compact shape that dict is the slot's whole value,
+ # `json_obj` unwrapped, which is why the placeholder's key comes from `_dict_field_name`. The corpus's optional dict fields never reach here:
# the engine drops those entirely, which is `optional-field-included`.
#
# Recognised by the engine's own placeholder rather than by the empty object alone, because
@@ -336,7 +358,8 @@ class DivergenceCollector:
# what makes the descriptor node `unknown`. A non-matching value falls through to the dict
# walk below, where each key the projection dropped is `engine-only-field` and the capture
# refuses.
- if isinstance(engine_value, dict) and projected_value == {} and engine_value == _engine_dict_placeholder(path=path):
+ engine_placeholder = _engine_dict_placeholder(field_name=self._dict_field_name(path=path))
+ if isinstance(engine_value, dict) and projected_value == {} and engine_value == engine_placeholder:
self._record(divergence_id="unknown-empty-object", path=path, engine=engine_value, expected=projected_value)
return
if (
@@ -551,6 +574,7 @@ def _capture_pipe(
templates_dir = output_dir / TEMPLATES_DIR_NAME
engine_dir = output_dir / ENGINE_DIR_NAME
collector.register_fixed_counts(pipe_ref=pipe.pipe_ref, descriptor=descriptor)
+ collector.register_json_unwraps(pipe_ref=pipe.pipe_ref, descriptor=descriptor)
for explicit in (False, True):
shape = EXPLICIT_SHAPE if explicit else COMPACT_SHAPE
template, json_text, toml_text = _render_projection(descriptor=descriptor, explicit=explicit)
diff --git a/pipelex/cli/dev_cli/commands/projection_reference.py b/pipelex/cli/dev_cli/commands/projection_reference.py
index da172e376..23740579d 100644
--- a/pipelex/cli/dev_cli/commands/projection_reference.py
+++ b/pipelex/cli/dev_cli/commands/projection_reference.py
@@ -37,6 +37,7 @@ from pipelex.pipeline.input_form import (
InputFormField,
InputFormItem,
ListItem,
+ ObjectItem,
PipeInputFormDescriptor,
)
@@ -61,23 +62,30 @@ TIME_CONTENT_KEY = "time"
NATIVE_PREFIX = "native."
-# The natives the runtime's input shaper cannot build top-down: their light form keeps the whole
-# `{concept, content}` envelope, because a bare value at one of these positions is not re-shapable.
-# The vocabulary is the standard's closed native set (`mthds/docs/spec/native-concepts.md`), which is
-# why a projection may consult it: it reads an identity the descriptor states, never sniffs a shape.
+# The open natives whose light form keeps the whole `{concept, content}` envelope: a bare value at
+# one of these positions either has no reading every runtime shares or, for `Anything`, would
+# misstate what the slot takes — its bare placeholder `{}` reads as "send an object", while the
+# envelope names the concept that says any value goes. The vocabulary is the standard's closed native
+# set (`mthds/docs/spec/native-concepts.md`), which is why a projection may consult it: it reads an
+# identity the descriptor states, never sniffs a shape.
OUT_OF_MATRIX_NATIVES = frozenset(
{
"Anything",
"Composite",
"Dynamic",
"Html",
- "JSON",
"Page",
"SearchResult",
"TextAndImages",
}
)
+# `native.JSON`'s light form is the JSON object itself: the descriptor states the content form, an
+# object holding one `json_obj`, and the compact projection unwraps it, since the shaper reads a bare
+# object at a `JSON` position literally.
+NATIVE_JSON = "JSON"
+JSON_CONTENT_KEY = "json_obj"
+
# `native.Number`'s content is a number union, and the runtime placeholders it as `1` rather than as
# the `0` / `0.0` a plain `type = "number"` structure field takes. The descriptor states `kind =
# "number"` for both, so the native identity is what separates them.
@@ -113,7 +121,7 @@ def keeps_envelope(*, node: InputFormItem) -> bool:
beside its required `date` makes the rendered form an object.
"""
code = native_code(node=node)
- if code is None:
+ if code is None or code == NATIVE_JSON:
return False
return code in OUT_OF_MATRIX_NATIVES or node.kind is FieldKind.OBJECT
@@ -234,13 +242,27 @@ def _slot_content(*, node: InputFormItem, name: str) -> Any:
def _light_value(*, node: InputFormItem, name: str) -> Any:
- """One slot's (or one slot element's) light value: a scalar unwraps, everything else keeps its dict."""
+ """One slot's (or one slot element's) light value: a scalar unwraps, a `JSON` object unwraps its
+ `json_obj`, and everything else keeps its dict.
+ """
content_key = slot_content_key(node=node)
if content_key is not None:
return _leaf_placeholder(node=node, name=content_key)
+ if native_code(node=node) == NATIVE_JSON:
+ return _json_object(node=node)
return project_value(node=node, name=name)
+def _json_object(*, node: InputFormItem) -> Any:
+ """The object a `JSON` node carries under `json_obj`, which its light form is."""
+ if isinstance(node, ObjectItem):
+ for field in node.fields:
+ if field.name == JSON_CONTENT_KEY:
+ return project_value(node=field, name=JSON_CONTENT_KEY)
+ msg = f"A '{NATIVE_PREFIX}{NATIVE_JSON}' node must be an object carrying a '{JSON_CONTENT_KEY}' field, got a '{node.kind}' node"
+ raise ValueError(msg)
+
+
def _compact_slot(*, field: InputFormField) -> Any:
"""One slot in the light shape.
diff --git a/pipelex/core/concepts/concept.py b/pipelex/core/concepts/concept.py
index 12cfbc14e..d81b7090b 100644
--- a/pipelex/core/concepts/concept.py
+++ b/pipelex/core/concepts/concept.py
@@ -118,9 +118,11 @@ class Concept(ConceptAbstract):
) -> bool:
"""Whether the two concepts' *declarations* establish that `concept_1` satisfies `concept_2`.
- This is the string tier of compatibility: dynamic short-circuits, ref equality, declared
- structure-class-name equality, and `refines` chains — the last resolved through
- `concept_resolver` when a refinement crosses a package boundary (`dep->domain.Code`).
+ This is the string tier of compatibility: dynamic short-circuits, the structureless top of
+ the lattice (every concept satisfies `native.Anything`, which declares no structure class,
+ while `Anything` satisfies nothing narrower), ref equality, declared structure-class-name
+ equality, and `refines` chains — the last resolved through `concept_resolver` when a
+ refinement crosses a package boundary (`dep->domain.Code`).
The two verdicts are asymmetric, deliberately. `True` means "established by the
declarations". `False` means "*not established at this tier*" — NOT "incompatible": two
@@ -135,6 +137,10 @@ class Concept(ConceptAbstract):
return True
if NativeConceptCode.is_dynamic_concept(concept_code=concept_2.code):
return True
+ if not concept_2.declares_a_structure_class:
+ # `native.Anything` promises no structure, so any value satisfies it; the reverse is
+ # never established here, since an `Anything` value is not known to be anything narrower.
+ return True
if concept_1.concept_ref == concept_2.concept_ref:
return True
if concept_1.structure_class_name == concept_2.structure_class_name:
@@ -220,13 +226,13 @@ class Concept(ConceptAbstract):
) -> tuple[dict[str, Any], set[str]]:
"""Render a representation for a concept that declares no structure class (`native.Anything`).
- The SCHEMA arm publishes the permissive schema: no constraint keywords, only the concept's
- identity annotations (`title` = concept ref, `description` = authored description) —
- semantically the empty schema, "any JSON value", which is what an untyped vehicle means,
- while keeping the invariant that every rendered input schema carries its concept's
- identity. The JSON arm renders the empty mapping `{}` — the escape hatch's only honest
- example value. Multiplicity wraps exactly as for class-backed concepts. PYTHON is refused:
- there is no class to instantiate.
+ The SCHEMA arm publishes the concept's identity annotations (`title` = concept ref,
+ `description` = authored description) and one constraint: the value is not an array and
+ not null. An untyped vehicle takes any other JSON value, but a list is the multiplicity's
+ to express (`Anything[]`), never a single value's, and null is never an input. The
+ multiplicity wraps exactly as for class-backed concepts, so every item of `Anything[]`
+ carries the same exclusion. The JSON arm renders the empty mapping `{}` — the escape
+ hatch's only honest example value. PYTHON is refused: there is no class to instantiate.
Returns:
Tuple of (representation dict with "concept" and "content" keys, empty imports set)
@@ -236,7 +242,11 @@ class Concept(ConceptAbstract):
"""
match output_format:
case ConceptRepresentationFormat.SCHEMA:
- json_schema: dict[str, Any] = {"title": self.concept_ref, "description": self.description}
+ json_schema: dict[str, Any] = {
+ "title": self.concept_ref,
+ "description": self.description,
+ "not": {"type": ["array", "null"]},
+ }
content = self._wrap_schema_for_multiplicity(json_schema=json_schema, multiplicity=multiplicity)
return {"concept": self.concept_ref, "content": content}, set()
case ConceptRepresentationFormat.JSON:
diff --git a/pipelex/core/memory/exceptions.py b/pipelex/core/memory/exceptions.py
index 41399939a..0d9646fa6 100644
--- a/pipelex/core/memory/exceptions.py
+++ b/pipelex/core/memory/exceptions.py
@@ -136,7 +136,9 @@ class StructureValidationError(InputShapingError):
Covers a structured-concept dict missing a required field, a malformed ``{"url": ...}`` for a
file concept, a non-ISO string for a Date concept — any value that is the right JSON kind but
- does not build into the declared content class.
+ does not build into the declared content class. It also covers a value an input reading bare
+ values by their own shape has no reading for — a list of plain objects at a ``Dynamic`` or
+ ``Html`` input — where the fix is usually the input's declaration rather than the value (R8).
"""
@classmethod
@@ -155,6 +157,37 @@ class StructureValidationError(InputShapingError):
)
return cls(message, variable_name=variable_name, user_action=user_action)
+ @classmethod
+ def make_for_unreadable_bare_value(
+ cls,
+ *,
+ variable_name: str,
+ declared_concept_ref: str,
+ provided_description: str,
+ suggested_declaration: str,
+ expected_shape: str,
+ ) -> "StructureValidationError":
+ """The refusal for a bare value that an input of this concept, which reads a value by its own shape, cannot read.
+
+ The advice names the declaration to change rather than an envelope, because the person who
+ sent the value usually also declared the input, and an envelope helps only a caller who knows
+ a concept both compatible with the input and able to hold the value. `suggested_declaration`
+ is the one that reads this value: `'JSON'` for an object, `'JSON[]'` for a list of objects,
+ `'Anything'` or `'Anything[]'` for anything else.
+ """
+ message = (
+ f"Input '{variable_name}' could not be built as '{declared_concept_ref}': you provided {provided_description}, "
+ f"and an input of this concept reads a bare value by its own shape, with no reading for this one.\nExpected shape:\n{expected_shape}"
+ )
+ user_action = UserAction(
+ kind=UserActionKind.CHANGE_INPUT,
+ detail=(
+ f"Declare input '{variable_name}' in the method as {suggested_declaration}, "
+ "or as a concept with a structure that describes the value."
+ ),
+ )
+ return cls(message, variable_name=variable_name, user_action=user_action)
+
class ExplicitConceptIncompatibleError(InputShapingError):
"""An explicit envelope/object names a concept incompatible with the declared one (D6).
diff --git a/pipelex/core/memory/input_shaper.py b/pipelex/core/memory/input_shaper.py
index 840d416f6..0e4c17036 100644
--- a/pipelex/core/memory/input_shaper.py
+++ b/pipelex/core/memory/input_shaper.py
@@ -3,7 +3,9 @@
The ``InputShaper`` interprets each provided input *top-down against the pipe's declared
signature* instead of bottom-up from the value's shape alone. A bare string becomes the declared
concept (a ``legal.Question``, not ``native.Text``); a bare number satisfies a ``Number``-refining
-input; a bare dict validates against a structured concept; a JSON list shapes element-wise into
+input; a bare dict validates against a structured concept; a bare object is the value of a ``JSON``
+input; any JSON value fills a ``native.Anything`` input, held as the natural content for its JSON
+type; a JSON list shapes element-wise into
``ListContent[declared]``; the ``{"concept", "content"}`` envelope stays as a compat-checked escape
hatch.
@@ -11,11 +13,13 @@ This module is the top-down *dispatch*: the actual content building reuses the e
(``StuffContentFactory`` / ``ConceptLibrary.is_compatible`` / the bottom-up ``StuffFactory``). The
new code decides which arm each value takes; it does not invent new content builders.
-See ``wip/inputs/smart-inputs-design.md`` (D1-D11) for the full rationale.
+See ``wip/inputs/smart-inputs-design.md`` (D1-D11) for the full rationale, and
+``wip/anything-slot/design.md`` (R1-R10) for the ``Anything`` and ``JSON`` arms.
"""
import datetime
import json
+import math
from enum import StrEnum
from pathlib import Path
from typing import Any, cast
@@ -27,6 +31,7 @@ from pipelex.base_exceptions import PipelexUnexpectedError
from pipelex.core.concepts.concept import Concept
from pipelex.core.concepts.concept_provider_abstract import ConceptProviderAbstract
from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat
+from pipelex.core.concepts.exceptions import ConceptLibraryConceptNotFoundError
from pipelex.core.concepts.native.concept_native import NativeConceptCode
from pipelex.core.memory.exceptions import (
ExplicitConceptIncompatibleError,
@@ -41,7 +46,7 @@ from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs
from pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpec
from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity, fixed_item_count, is_multiple_multiplicity
-from pipelex.core.stuffs.exceptions import StuffContentFactoryError
+from pipelex.core.stuffs.exceptions import StuffContentFactoryError, StuffFactoryError
from pipelex.core.stuffs.list_content import ListContent
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.stuffs.stuff import DictStuff, Stuff
@@ -54,10 +59,13 @@ from pipelex.tools.uri.uri_resolver import resolve_local_path_reference
class InputKind(StrEnum):
"""Which interpretation arm a declared input concept takes (D5).
- Resolved once per input from the *declared concept's* nature. ``DYNAMIC`` is the bottom-up
- fallback used for ``Dynamic`` / ``Anything`` and the out-of-matrix natives (Html, JSON, Page,
- TextAndImages, SearchResult, Composite) — the signature genuinely does not know how to shape
- them, so today's shape-driven ``StuffFactory`` path handles the whole value.
+ Resolved once per input from the *declared concept's* nature. ``ANYTHING`` is the structureless
+ ``native.Anything``: it takes any JSON value but an array or a null, held as the natural content
+ for the value's JSON type while the stuff keeps the declared concept (R1). ``JSON`` takes a JSON
+ object as it is (R7). ``DYNAMIC`` is the bottom-up fallback used for ``Dynamic`` and the natives
+ no arm reads top-down (Html, Page, TextAndImages, SearchResult, Composite) — the shape-driven
+ ``StuffFactory`` path handles the whole value there, and a value it has no reading for is
+ refused naming the input (R8).
"""
TEXT = "text"
@@ -68,6 +76,8 @@ class InputKind(StrEnum):
IMAGE = "image"
DOCUMENT = "document"
STRUCTURED = "structured"
+ JSON = "json"
+ ANYTHING = "anything"
DYNAMIC = "dynamic"
@property
@@ -84,6 +94,31 @@ class InputKind(StrEnum):
| InputKind.TIME
| InputKind.IMAGE
| InputKind.DOCUMENT
+ | InputKind.JSON
+ | InputKind.ANYTHING
+ | InputKind.DYNAMIC
+ ):
+ return False
+
+ @property
+ def reads_objects_literally(self) -> bool:
+ """Whether a bare object is itself the value, rather than the fields of a declared structure.
+
+ Such a kind cannot tell an item shaped like a ``{"concept", "content"}`` envelope from raw
+ data, so an item of that shape in a bare list is refused rather than read either way (R10).
+ """
+ match self:
+ case InputKind.JSON | InputKind.ANYTHING:
+ return True
+ case (
+ InputKind.TEXT
+ | InputKind.NUMBER
+ | InputKind.YES_NO
+ | InputKind.DATE
+ | InputKind.TIME
+ | InputKind.IMAGE
+ | InputKind.DOCUMENT
+ | InputKind.STRUCTURED
| InputKind.DYNAMIC
):
return False
@@ -185,12 +220,34 @@ class InputShaper:
case InputKind.DYNAMIC:
# The signature genuinely does not know how to shape this — hand the whole raw value
# to the bottom-up factory (today's behavior, including its own list handling).
- return StuffFactory.make_stuff_from_stuff_content_or_data(
- stuff_content_or_data=value,
- concept_provider=concept_provider,
- name=variable_name,
- search_scope=search_scope,
- )
+ try:
+ return StuffFactory.make_stuff_from_stuff_content_or_data(
+ stuff_content_or_data=value,
+ concept_provider=concept_provider,
+ name=variable_name,
+ search_scope=search_scope,
+ )
+ except StuffFactoryError as exc:
+ # (R8) The factory's refusal names neither the input nor its declared concept, so it
+ # is re-raised naming both, with the factory's own message as the cause.
+ expected_shape = cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec)
+ suggested_declaration = cls._declaration_suggested_for(value=value)
+ if suggested_declaration is None:
+ # Not a value without a reading: an empty list, or prebuilt contents the
+ # factory could not type. Its reason is the one the caller can act on.
+ raise StructureValidationError.make(
+ variable_name=variable_name,
+ declared_concept_ref=declared_concept.concept_ref,
+ reason=str(exc),
+ expected_shape=expected_shape,
+ ) from exc
+ raise StructureValidationError.make_for_unreadable_bare_value(
+ variable_name=variable_name,
+ declared_concept_ref=declared_concept.concept_ref,
+ provided_description=cls._describe_value(value),
+ suggested_declaration=suggested_declaration,
+ expected_shape=expected_shape,
+ ) from exc
case (
InputKind.TEXT
| InputKind.NUMBER
@@ -200,6 +257,8 @@ class InputShaper:
| InputKind.IMAGE
| InputKind.DOCUMENT
| InputKind.STRUCTURED
+ | InputKind.JSON
+ | InputKind.ANYTHING
):
content = cls._shape_with_multiplicity(
value,
@@ -209,6 +268,7 @@ class InputShaper:
variable_name=variable_name,
search_scope=search_scope,
inputs_base_dir=inputs_base_dir,
+ is_raw_data=False,
)
return StuffFactory.make_stuff(concept=declared_concept, content=content, name=variable_name)
@@ -221,6 +281,9 @@ class InputShaper:
"""
if NativeConceptCode.is_dynamic_concept(concept_code=concept.code):
return InputKind.DYNAMIC
+ if not concept.declares_a_structure_class:
+ # `native.Anything`: decided from the concept alone, since it has no class to resolve.
+ return InputKind.ANYTHING
ordered_natives: list[tuple[NativeConceptCode, InputKind]] = [
(NativeConceptCode.YES_NO, InputKind.YES_NO),
@@ -230,6 +293,7 @@ class InputShaper:
(NativeConceptCode.IMAGE, InputKind.IMAGE),
(NativeConceptCode.DOCUMENT, InputKind.DOCUMENT),
(NativeConceptCode.TEXT, InputKind.TEXT),
+ (NativeConceptCode.JSON, InputKind.JSON),
]
for native_code, input_kind in ordered_natives:
wanted_concept = concept_provider.get_native_concept(native_concept=native_code)
@@ -237,8 +301,8 @@ class InputShaper:
return input_kind
# A user (non-native) concept whose structure is StructuredContent dispatches its dict
- # top-down. Everything else — the out-of-matrix natives (Html/JSON/Page/TextAndImages/
- # SearchResult/Composite/Anything) — falls back to bottom-up building.
+ # top-down. Everything else — the natives no arm reads top-down (Html/Page/TextAndImages/
+ # SearchResult/Composite) — falls back to bottom-up building.
if not Concept.is_native_concept(concept=concept):
if issubclass(concept_provider.get_structure_class(concept=concept), StructuredContent):
return InputKind.STRUCTURED
@@ -267,8 +331,14 @@ class InputShaper:
variable_name: str,
search_scope: str | None,
inputs_base_dir: Path | None,
+ is_raw_data: bool,
) -> StuffContent:
- """Peel the declared multiplicity (D2), then build the item content(s)."""
+ """Peel the declared multiplicity (D2), then build the item content(s).
+
+ ``is_raw_data`` is set when the value arrived as the content of an ``Anything`` envelope,
+ which is raw data at every depth, so an envelope-shaped list item is read as an object
+ there instead of being refused (R10's escape).
+ """
is_list, fixed_count = cls._peel_multiplicity(stuff_spec.multiplicity)
# (D11) A declared structured LIST input accepts a table reference — a bare tabular path
@@ -299,6 +369,7 @@ class InputShaper:
fixed_count=fixed_count,
search_scope=search_scope,
inputs_base_dir=inputs_base_dir,
+ is_raw_data=is_raw_data,
)
# Singular (no multiplicity, or a count of one). A list here is ambiguous — hard error (D2).
@@ -373,6 +444,7 @@ class InputShaper:
fixed_count: int | None,
search_scope: str | None,
inputs_base_dir: Path | None,
+ is_raw_data: bool,
) -> ListContent[StuffContent]:
"""Shape a declared-multiple input element-wise into a ListContent (D2)."""
# A single bare value auto-wraps into a one-item list; an empty list stays empty (legal).
@@ -385,6 +457,22 @@ class InputShaper:
provided_count=len(item_values),
expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),
)
+ if input_kind.reads_objects_literally and not is_raw_data:
+ # (R10) The envelope collision rule of D6 applies at the top of a slot only, so an item
+ # shaped like an envelope would otherwise be taken as a raw object here, one spelling
+ # meaning two things depending on where it sits.
+ for item_value in item_values:
+ if cls._is_envelope_dict(item_value):
+ raise cls._wrong_kind(
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ expected_kind=(
+ 'a plain value for each list item, not an item shaped like a {"concept", "content"} envelope '
+ "(to type a list, wrap the whole list in one envelope instead)"
+ ),
+ value=item_value,
+ )
items = [
cls._build_item_content(
item_value,
@@ -421,6 +509,16 @@ class InputShaper:
then delegates to ``StuffContentFactory`` so a refining subclass is honored.
"""
concept = stuff_spec.concept
+ if isinstance(value, ListContent):
+ # A list is the multiplicity's to express (D2), so a list where one value belongs is
+ # refused, as a bare array is: an item of a plural slot, or the content of a single one.
+ raise cls._wrong_kind(
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ expected_kind="a single value, not a list",
+ value=value,
+ )
if isinstance(value, StuffContent):
built = StuffFactory.make_stuff_from_stuff_content_or_data(
stuff_content_or_data=value, concept_provider=concept_provider, name=variable_name, search_scope=search_scope
@@ -447,8 +545,7 @@ class InputShaper:
concept, concept_provider=concept_provider, value={"text": value}, stuff_spec=stuff_spec, variable_name=variable_name
)
case InputKind.NUMBER:
- # bool is a subclass of int — exclude it explicitly so a boolean never becomes a number.
- if isinstance(value, bool) or not isinstance(value, (int, float)):
+ if not cls._is_json_number(value=value):
raise cls._wrong_kind(
concept_provider=concept_provider, stuff_spec=stuff_spec, variable_name=variable_name, expected_kind="a number", value=value
)
@@ -520,12 +617,99 @@ class InputShaper:
stuff_spec=stuff_spec,
variable_name=variable_name,
)
+ case InputKind.JSON:
+ if not isinstance(value, dict):
+ raise cls._wrong_kind(
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ expected_kind="a JSON object",
+ value=value,
+ )
+ # Built with the declared concept, so a concept refining JSON gets its own class.
+ return cls._build_json_object_content(
+ cast("dict[str, Any]", value),
+ concept=concept,
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ )
+ case InputKind.ANYTHING:
+ return cls._build_anything_content(value, concept_provider=concept_provider, stuff_spec=stuff_spec, variable_name=variable_name)
case InputKind.DYNAMIC:
# Unreachable: DYNAMIC short-circuits in `_shape_one` before multiplicity peeling.
# Kept so the match over InputKind stays exhaustive.
msg = f"Input '{variable_name}': DYNAMIC kind must be handled by the bottom-up fallback, not per-item shaping."
raise PipelexUnexpectedError(msg)
+ @classmethod
+ def _build_anything_content(
+ cls, value: Any, *, concept_provider: ConceptProviderAbstract, stuff_spec: StuffSpec, variable_name: str
+ ) -> StuffContent:
+ """Build the natural content for one value at an ``Anything`` slot, keyed on its JSON type (R1).
+
+ Nothing is inferred beyond the JSON type: a string that looks like a URL or a date is text.
+ Each content is built through the matching native concept from the injected provider. An
+ array (an item of a list) and a null (an item) have no content to become, and neither has
+ a Python object that is not a JSON value.
+ """
+ native_code: NativeConceptCode
+ canonical: dict[str, Any] | str | bool | datetime.date | datetime.time
+ # bool before number: bool is a subclass of int, and a boolean is never a number.
+ if isinstance(value, bool):
+ native_code, canonical = NativeConceptCode.YES_NO, value
+ elif cls._is_json_number(value=value):
+ native_code, canonical = NativeConceptCode.NUMBER, {"number": value}
+ elif isinstance(value, datetime.time):
+ native_code, canonical = NativeConceptCode.TIME, value
+ elif isinstance(value, datetime.date):
+ # Covers datetime, a subclass of date: DateContent keeps its time of day.
+ native_code, canonical = NativeConceptCode.DATE, value
+ elif isinstance(value, str):
+ native_code, canonical = NativeConceptCode.TEXT, {"text": value}
+ elif isinstance(value, dict):
+ return cls._build_json_object_content(
+ cast("dict[str, Any]", value),
+ concept=concept_provider.get_native_concept(native_concept=NativeConceptCode.JSON),
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ )
+ else:
+ raise cls._wrong_kind(
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ expected_kind="a string, a number, a boolean or an object (a list only as a whole plural input, never null)",
+ value=value,
+ )
+ return cls._make_content(
+ concept_provider.get_native_concept(native_concept=native_code),
+ concept_provider=concept_provider,
+ value=canonical,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ )
+
+ @classmethod
+ def _build_json_object_content(
+ cls,
+ json_object: dict[str, Any],
+ *,
+ concept: Concept,
+ concept_provider: ConceptProviderAbstract,
+ stuff_spec: StuffSpec,
+ variable_name: str,
+ ) -> StuffContent:
+ """Build a ``JSONContent`` (or the class of a concept refining ``JSON``) holding an object as it is.
+
+ The object is taken literally, ``{"json_obj": ...}`` included: ``json_obj`` is the content
+ form's field, which travels inside an envelope, never a key a bare object is read through.
+ """
+ return cls._make_content(
+ concept, concept_provider=concept_provider, value={"json_obj": json_object}, stuff_spec=stuff_spec, variable_name=variable_name
+ )
+
@classmethod
def _make_content(
cls,
@@ -538,6 +722,11 @@ class InputShaper:
) -> StuffContent:
"""Delegate to ``StuffContentFactory``, wrapping a build failure as a D4 structure error.
+ ``concept`` names the structure class that builds the value: the declared concept, except at
+ an ``Anything`` slot, where it is the native concept matching the value's JSON type. A
+ failure is reported against the declared concept either way, since that is what the caller
+ sees in the signature.
+
The structure class is resolved through the **injected provider**, then handed down as a
resolved type — the shape ``hub-layering.md`` prescribes for exactly this ("rendering takes
the resolved class, not the name"), and the one ``StuffSpec.render_stuff_spec`` already
@@ -563,7 +752,7 @@ class InputShaper:
except (ValidationError, StuffContentFactoryError) as exc:
raise StructureValidationError.make(
variable_name=variable_name,
- declared_concept_ref=concept.concept_ref,
+ declared_concept_ref=stuff_spec.concept.concept_ref,
reason=str(exc),
expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),
) from exc
@@ -585,7 +774,36 @@ class InputShaper:
``StuffContent``/``ListContent`` all name (or infer) their own concept. ``StuffFactory`` builds
them exactly as today — so the explicit, possibly more-specific concept is preserved — and the
one new rule is: that concept must be compatible with the declared one, else a D4 error.
+
+ An envelope naming a structureless concept (``native.Anything``) is the one exception (R5):
+ the factory has no class to build it with, so its content is shaped here as the bare value
+ it is, by the ``Anything`` arm and against the declared multiplicity.
"""
+ structureless_envelope_stuff = cls._try_shape_structureless_envelope(
+ value,
+ concept_provider=concept_provider,
+ declared_concept=declared_concept,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ search_scope=search_scope,
+ )
+ if structureless_envelope_stuff is not None:
+ return structureless_envelope_stuff
+
+ if isinstance(value, ListContent) and not declared_concept.declares_a_structure_class:
+ prebuilt_items = cast("ListContent[StuffContent]", value).items
+ if len({type(item) for item in prebuilt_items}) > 1:
+ # A prebuilt list mixing kinds infers no single concept, so at an `Anything` slot it is
+ # the bare list of its items, exactly as it is inside an `Anything` envelope.
+ return cls._shape_one(
+ list(prebuilt_items),
+ concept_provider=concept_provider,
+ stuff_spec=stuff_spec,
+ variable_name=variable_name,
+ search_scope=search_scope,
+ inputs_base_dir=None,
+ )
+
stuff = StuffFactory.make_stuff_from_stuff_content_or_data(
stuff_content_or_data=cast("StuffContentOrData", value),
concept_provider=concept_provider,
@@ -605,6 +823,74 @@ class InputShaper:
cls._reconcile_explicit_multiplicity(stuff, concept_provider=concept_provider, stuff_spec=stuff_spec, variable_name=variable_name)
return stuff
+ @classmethod
+ def _try_shape_structureless_envelope(
+ cls,
+ value: Any,
+ *,
+ concept_provider: ConceptProviderAbstract,
+ declared_concept: Concept,
+ stuff_spec: StuffSpec,
+ variable_name: str,
+ search_scope: str | None,
+ ) -> Stuff | None:
+ """Shape an envelope naming a structureless concept, or return ``None`` for every other explicit form (R5).
+
+ The envelope's concept is resolved through the injected provider first. A concept that does
+ not resolve returns ``None`` too, so the bottom-up factory reports it exactly as it reports
+ any unknown envelope concept. A structureless envelope is honoured wherever its concept is
+ compatible with the declared one, which is an ``Anything`` or a ``Dynamic`` slot, and there
+ its content is raw data at every depth; anywhere else it is refused before anything is built,
+ since an ``Anything`` value is not known to satisfy anything narrower.
+ """
+ envelope_concept_ref: Any
+ content: Any
+ if isinstance(value, DictStuff):
+ envelope_concept_ref, content = value.concept, value.content
+ elif cls._is_envelope_dict(value):
+ envelope_dict = cast("dict[str, Any]", value)
+ envelope_concept_ref, content = envelope_dict["concept"], envelope_dict["content"]
+ else:
+ return None
+ if not isinstance(envelope_concept_ref, str):
+ return None
+ try:
+ envelope_concept = concept_provider.get_required_entry_concept(concept_ref_or_code=envelope_concept_ref, search_scope=search_scope)
+ except ConceptLibraryConceptNotFoundError:
+ return None
+ if envelope_concept.declares_a_structure_class:
+ return None
+
+ expected_shape = cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec)
+ if not concept_provider.is_compatible(tested_concept=envelope_concept, wanted_concept=declared_concept):
+ raise ExplicitConceptIncompatibleError.make(
+ variable_name=variable_name,
+ declared_concept_ref=declared_concept.concept_ref,
+ provided_concept_ref=envelope_concept.concept_ref,
+ expected_shape=expected_shape,
+ )
+ if content is None:
+ raise NullInputError.make(variable_name=variable_name, declared_concept_ref=declared_concept.concept_ref, expected_shape=expected_shape)
+ if isinstance(content, ListContent):
+ # A prebuilt list is the same value as the bare list of its items, and is shaped as one.
+ content = list(cast("ListContent[StuffContent]", content).items)
+ shaping_spec = stuff_spec
+ if NativeConceptCode.is_dynamic_concept(concept_code=declared_concept.code):
+ # Match `_shape_explicit` at a Dynamic slot: the signature cannot guide list-vs-single
+ # shape there, so the content's own shape decides it.
+ shaping_spec = StuffSpec(concept=declared_concept, multiplicity=True if isinstance(content, list) else None)
+ shaped_content = cls._shape_with_multiplicity(
+ content,
+ concept_provider=concept_provider,
+ stuff_spec=shaping_spec,
+ input_kind=InputKind.ANYTHING,
+ variable_name=variable_name,
+ search_scope=search_scope,
+ inputs_base_dir=None,
+ is_raw_data=True,
+ )
+ return StuffFactory.make_stuff(concept=envelope_concept, content=shaped_content, name=variable_name)
+
@classmethod
def _reconcile_explicit_multiplicity(
cls, stuff: Stuff, *, concept_provider: ConceptProviderAbstract, stuff_spec: StuffSpec, variable_name: str
@@ -620,10 +906,20 @@ class InputShaper:
an explicit singular is taken as given, not auto-wrapped.
"""
content = stuff.content
+ is_list, fixed_count = cls._peel_multiplicity(stuff_spec.multiplicity)
if not isinstance(content, ListContent):
+ if fixed_count is not None:
+ # A single value is one item, never the N a fixed count declares, whether or not a
+ # singular under `[]` is ever auto-wrapped.
+ raise MultiplicityCountMismatchError.make(
+ variable_name=variable_name,
+ declared_concept_ref=stuff_spec.concept.concept_ref,
+ expected_count=fixed_count,
+ provided_count=1,
+ expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),
+ )
return
list_content = cast("ListContent[StuffContent]", content)
- is_list, fixed_count = cls._peel_multiplicity(stuff_spec.multiplicity)
if not is_list:
raise ListWhereSingularError.make(
variable_name=variable_name,
@@ -651,6 +947,11 @@ class InputShaper:
"""
if isinstance(value, (DictStuff, StuffContent)):
return True
+ return cls._is_envelope_dict(value)
+
+ @classmethod
+ def _is_envelope_dict(cls, value: Any) -> bool:
+ """Whether a value is a plain object whose keys are exactly ``concept`` and ``content``."""
return isinstance(value, dict) and set(cast("dict[Any, Any]", value).keys()) == {"concept", "content"}
@classmethod
@@ -665,12 +966,62 @@ class InputShaper:
expected_shape=cls._render_expected_shape(concept_provider=concept_provider, stuff_spec=stuff_spec),
)
+ @classmethod
+ def _declaration_suggested_for(cls, *, value: Any) -> str | None:
+ """The declaration that reads a bare value the fallback has no reading for, or ``None`` when no
+ declaration reads it, so the refusal never advises a declaration that would refuse the value too.
+ """
+ if isinstance(value, dict):
+ return "'JSON'" if cls._is_json_encodable(value=value) else None
+ if isinstance(value, list):
+ items = cast("list[Any]", value)
+ if not items or not all(cls._anything_reads_item(item=item) for item in items):
+ return None
+ if all(isinstance(item, dict) for item in items):
+ return "'JSON[]'"
+ return "'Anything[]'"
+ return "'Anything'" if cls._anything_reads_item(item=value) else None
+
+ @classmethod
+ def _anything_reads_item(cls, *, item: Any) -> bool:
+ """Whether the `Anything` arm builds a content for one value, as a single value or a list item.
+
+ Mirrors what `_build_anything_content` and `_shape_list` accept: a boolean, a finite number,
+ a string, a date or a time, and an object JSON can encode that is not shaped like an envelope.
+ """
+ if isinstance(item, (bool, str, datetime.date, datetime.time)):
+ return True
+ if isinstance(item, (int, float)):
+ return cls._is_json_number(value=item)
+ if isinstance(item, dict):
+ return not cls._is_envelope_dict(item) and cls._is_json_encodable(value=item)
+ return False
+
+ @classmethod
+ def _is_json_encodable(cls, *, value: Any) -> bool:
+ """Whether JSON can hold a value as it is, with no NaN or infinity anywhere inside it."""
+ try:
+ json.dumps(value, allow_nan=False)
+ except (TypeError, ValueError):
+ return False
+ return True
+
@classmethod
def _render_expected_shape(cls, *, concept_provider: ConceptProviderAbstract, stuff_spec: StuffSpec) -> str:
"""Render the expected input shape from the signature, reused verbatim in D4 error hints."""
rendered = stuff_spec.render_stuff_spec(concept_provider=concept_provider, output_format=ConceptRepresentationFormat.JSON)
return json.dumps(rendered, ensure_ascii=False)
+ @classmethod
+ def _is_json_number(cls, *, value: Any) -> bool:
+ """Whether a value is a number JSON can hold: never a boolean, and never NaN or an infinity,
+ which a TOML inputs file can spell but JSON serialization turns into `null`.
+ """
+ # bool is a subclass of int, and a boolean is never a number.
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return False
+ return not isinstance(value, float) or math.isfinite(value)
+
@classmethod
def _describe_value(cls, value: Any) -> str:
"""A short human description of a provided value, for error messages."""
@@ -679,6 +1030,8 @@ class InputShaper:
return "null"
if isinstance(value, bool):
return f"a boolean ({str(value).lower()})"
+ if isinstance(value, float) and not math.isfinite(value):
+ return f"a number JSON cannot hold ({value})"
if isinstance(value, str):
return f'a string ("{value[:40]}")'
if isinstance(value, (int, float)):
diff --git a/pipelex/core/memory/working_memory.py b/pipelex/core/memory/working_memory.py
index 73260ec98..05dcb7845 100644
--- a/pipelex/core/memory/working_memory.py
+++ b/pipelex/core/memory/working_memory.py
@@ -609,6 +609,11 @@ class WorkingMemory(WorkingMemoryAbstract[Stuff], ContextProviderAbstract):
# only exist in a per-workflow ClassRegistry.
serialized_items.append(_encode_content_with_class_markers(item))
raw_root[stuff_name]["content"] = serialized_items
+ elif not stuff.concept.declares_a_structure_class and stuff_name in raw_root:
+ # A structureless concept (`native.Anything`) names no content class, so the
+ # hydrator cannot find one through the concept: a single content carries its own
+ # class markers, exactly as a list item does.
+ raw_root[stuff_name]["content"] = _encode_content_with_class_markers(cast("StuffContent", content))
elif isinstance(content, CompositeContent) and stuff_name in raw_root:
# Composite components are extra="allow" fields: a plain model_dump loses
# their classes, so stamp each component with the same pipelex-private
diff --git a/pipelex/core/stuffs/json_content.py b/pipelex/core/stuffs/json_content.py
index ad1233222..fd2a7bb12 100644
--- a/pipelex/core/stuffs/json_content.py
+++ b/pipelex/core/stuffs/json_content.py
@@ -20,12 +20,12 @@ class JSONContent(StuffContent):
@field_validator("json_obj", mode="before")
@classmethod
def check_valid_json(cls, value: dict[str, Any]) -> dict[str, Any]:
+ # A ValueError, never a TypeError: pydantic turns only the former into a ValidationError, so a
+ # dict holding a value that is not JSON is reported like any other invalid content. NaN and the
+ # infinities are refused too, since JSON cannot hold them and serialization would turn them into null.
try:
- json.dumps(value)
- except TypeError as exc:
- msg = f"json_obj is not valid JSON: {exc}"
- raise TypeError(msg) from exc
- except json.JSONDecodeError as exc:
+ json.dumps(value, allow_nan=False)
+ except (TypeError, ValueError) as exc:
msg = f"json_obj is not valid JSON: {exc}"
raise ValueError(msg) from exc
return value
diff --git a/pipelex/core/stuffs/number_content.py b/pipelex/core/stuffs/number_content.py
index 1f5dc9349..35fbdbb48 100644
--- a/pipelex/core/stuffs/number_content.py
+++ b/pipelex/core/stuffs/number_content.py
@@ -1,6 +1,7 @@
import json
+import math
-from pydantic import Field
+from pydantic import Field, field_validator
from typing_extensions import override
from pipelex.core.stuffs.stuff_content import StuffContent
@@ -11,6 +12,15 @@ class NumberContent(StuffContent):
number: int | float = Field(description="The number")
+ @field_validator("number")
+ @classmethod
+ def check_finite(cls, value: float) -> int | float:
+ # NaN and the infinities are not JSON numbers: serialization would turn them into null.
+ if isinstance(value, float) and not math.isfinite(value):
+ msg = f"number must be finite, got {value}"
+ raise ValueError(msg)
+ return value
+
@property
@override
def short_desc(self) -> str:
diff --git a/pipelex/pipe_machinery/rendering/input_renderer.py b/pipelex/pipe_machinery/rendering/input_renderer.py
index 74eec9f12..58e1f04db 100644
--- a/pipelex/pipe_machinery/rendering/input_renderer.py
+++ b/pipelex/pipe_machinery/rendering/input_renderer.py
@@ -141,15 +141,28 @@ def _delighten_entry(entry: dict[str, Any], *, kind: InputKind) -> Any:
"""Turn one envelope entry (``{"concept", "content"}``) into the light value the shaper accepts.
Mirrors the shaper's arms (see ``input_shaper.py``): a scalar unwraps to its single content
- field, a structured value keeps its content dict, and a Dynamic / out-of-matrix value keeps the
+ field — a ``JSON`` input's ``json_obj`` included, so its light value is the bare object — a
+ structured value keeps its content dict, and a Dynamic / out-of-matrix value keeps the
whole envelope — the signature genuinely can't shape it, so bottom-up building still needs it.
+ An ``Anything`` value keeps its envelope too, though the shaper reads a bare value there: the
+ bare placeholder ``{}`` would read as "send an object", while the envelope names the concept
+ that says any value goes.
"""
match kind:
- case InputKind.DYNAMIC:
+ case InputKind.DYNAMIC | InputKind.ANYTHING:
return entry
case InputKind.STRUCTURED:
return entry["content"]
- case InputKind.TEXT | InputKind.NUMBER | InputKind.YES_NO | InputKind.DATE | InputKind.TIME | InputKind.IMAGE | InputKind.DOCUMENT:
+ case (
+ InputKind.TEXT
+ | InputKind.NUMBER
+ | InputKind.YES_NO
+ | InputKind.DATE
+ | InputKind.TIME
+ | InputKind.IMAGE
+ | InputKind.DOCUMENT
+ | InputKind.JSON
+ ):
return _unwrap_scalar_content(entry["content"], envelope=entry)
@@ -157,10 +170,10 @@ def _unwrap_scalar_content(content: Any, *, envelope: dict[str, Any]) -> Any:
"""Unwrap a scalar input's content to its bare field value (element-wise for a list).
Each scalar content is a single-field dict (``{"text": ...}`` / ``{"number": ...}`` / ``{"url":
- ...}`` / ``{"date": ...}`` / ``{"yes_no": ...}``) — the bare value the shaper re-wraps. A content
- that is not a single-field dict (a refining scalar with extra required fields, which the shaper
- can't build from a bare value anyway) can't be delightened losslessly, so the whole envelope is
- kept for that input, so the template still runs.
+ ...}`` / ``{"date": ...}`` / ``{"yes_no": ...}`` / ``{"json_obj": ...}``) — the bare value the
+ shaper re-wraps. A content that is not a single-field dict (a refining scalar with extra required
+ fields, which the shaper can't build from a bare value anyway) can't be delightened losslessly,
+ so the whole envelope is kept for that input, so the template still runs.
"""
items: list[Any] = cast("list[Any]", content) if isinstance(content, list) else [content]
unwrapped: list[Any] = []
diff --git a/pipelex/pipe_run/delivery_executor.py b/pipelex/pipe_run/delivery_executor.py
index d3186502c..92ccb53b2 100644
--- a/pipelex/pipe_run/delivery_executor.py
+++ b/pipelex/pipe_run/delivery_executor.py
@@ -287,14 +287,15 @@ class DeliveryExecutor:
if concept is None:
log.warning(f"Local hydration failed for delivery main stuff, falling back to raw render: concept '{concept_ref}' not known locally")
return None
- registry = get_class_registry()
- item_class = registry.get_class(name=concept.structure_class_name)
- if item_class is None or not issubclass(item_class, StuffContent):
- log.warning(
- f"Local hydration failed for delivery main stuff, falling back to raw render: "
- f"class '{concept.structure_class_name}' not registered locally"
- )
- return None
+ # A structureless concept (`native.Anything`) names no class to look up: its content carries its own.
+ if concept.declares_a_structure_class:
+ item_class = get_class_registry().get_class(name=concept.structure_class_name)
+ if item_class is None or not issubclass(item_class, StuffContent):
+ log.warning(
+ f"Local hydration failed for delivery main stuff, falling back to raw render: "
+ f"class '{concept.structure_class_name}' not registered locally"
+ )
+ return None
content = hydrate_content(concept=concept, raw_content=stuff_raw["content"])
return Stuff(
stuff_code=stuff_raw["stuff_code"],
diff --git a/pipelex/pipeline/pipe_io_contracts.py b/pipelex/pipeline/pipe_io_contracts.py
index 880c4f463..0c0546c98 100644
--- a/pipelex/pipeline/pipe_io_contracts.py
+++ b/pipelex/pipeline/pipe_io_contracts.py
@@ -90,8 +90,8 @@ def _render_output_schema(*, pipe: PipeAbstract, concept_provider: ConceptProvid
try:
if not pipe.output.is_multiple():
# The single arm needs no structureless special case: `render_stuff_spec` handles
- # `native.Anything` itself, publishing the permissive schema with the concept's
- # identity annotations. Short-circuiting to a bare `{}` here would be strictly
+ # `native.Anything` itself, publishing its schema with the concept's identity
+ # annotations. Short-circuiting to a bare `{}` here would be strictly
# worse — it would drop the `title`/`description` every rendered schema is
# supposed to carry.
rendered = pipe.output.render_stuff_spec(concept_provider=concept_provider, output_format=ConceptRepresentationFormat.SCHEMA)
diff --git a/pipelex/runtime_bridge/primitives/hydration.py b/pipelex/runtime_bridge/primitives/hydration.py
index b2ad3af48..f197a9306 100644
--- a/pipelex/runtime_bridge/primitives/hydration.py
+++ b/pipelex/runtime_bridge/primitives/hydration.py
@@ -47,7 +47,8 @@ def _validate_as_known_class(*, item_class: type[StuffContent], raw_item: StuffC
def _hydrate_list_item(raw_item: dict[str, Any] | str | StuffContent) -> StuffContent:
- """Hydrate a single list item for Anything[] results.
+ """Hydrate one content that carries its own class markers: an item of an Anything[] list,
+ or the single content of a stuff whose concept names no content class (`native.Anything`).
Resolves the item class from the pipelex-private ``__pipelex_class__`` /
``__pipelex_module__`` markers written by ``dump_for_transport``. Falls back
@@ -71,6 +72,10 @@ def _hydrate_list_item(raw_item: dict[str, Any] | str | StuffContent) -> StuffCo
if class_name is not None:
item_class = get_class_registry().get_required_subclass(name=class_name, base_class=StuffContent)
clean_item = {key: val for key, val in raw_item.items() if key not in {"__pipelex_class__", "__pipelex_module__"}}
+ if issubclass(item_class, CompositeContent):
+ # A composite's components are extra="allow" fields with no annotations to drive
+ # validation, so each is rebuilt from its own markers first, at any depth.
+ clean_item = {component_name: _hydrate_composite_component(raw_value) for component_name, raw_value in clean_item.items()}
return cast("StuffContent", item_class.model_validate(clean_item))
# No __class__ metadata — fall back to TextContent for marker-less simple text dicts.
@@ -130,6 +135,10 @@ def hydrate_content(raw_content: list[Any] | dict[str, Any] | str, *, concept: C
items = [_hydrate_list_item(raw_item) for raw_item in raw_items]
return ListContent(items=items)
+ if not concept.declares_a_structure_class:
+ # `native.Anything` names no content class: the single content carries its own markers.
+ return _hydrate_list_item(raw_content)
+
if isinstance(raw_content, dict):
structure_class = get_class_registry().get_class(name=concept.structure_class_name)
if structure_class is not None and issubclass(structure_class, CompositeContent):
diff --git a/subject_grants.toml b/subject_grants.toml
index 8794935c5..e2b6c7bcf 100644
--- a/subject_grants.toml
+++ b/subject_grants.toml
@@ -2652,10 +2652,18 @@ rationale = "Verb-object: renders the absence record; single operand."
param = "absence_record"
rationale = "Verb-object: renders the absence record; single operand."
+["pipelex/core/memory/input_shaper.py::InputShaper._build_anything_content"]
+param = "value"
+rationale = "Verb-object: builds the content for the raw value; the rest is context."
+
["pipelex/core/memory/input_shaper.py::InputShaper._build_item_content"]
param = "value"
rationale = "Verb-object: shapes the raw value into content; the rest is context."
+["pipelex/core/memory/input_shaper.py::InputShaper._build_json_object_content"]
+param = "json_object"
+rationale = "Verb-object: builds the content holding the JSON object; the concept and the rest are context."
+
["pipelex/core/memory/input_shaper.py::InputShaper._check_input_names"]
param = "pipeline_inputs"
rationale = "Validator: the pipeline inputs are the operand checked against the specs."
@@ -2664,6 +2672,10 @@ rationale = "Validator: the pipeline inputs are the operand checked against the
param = "value"
rationale = "Noun-named derivation: describes the value; single operand."
+["pipelex/core/memory/input_shaper.py::InputShaper._is_envelope_dict"]
+param = "value"
+rationale = "Predicate on the value; single operand."
+
["pipelex/core/memory/input_shaper.py::InputShaper._is_explicit"]
param = "value"
rationale = "Predicate on the value; single operand."
@@ -2704,6 +2716,10 @@ rationale = "Verb-object: shapes the raw value; the rest is context."
param = "value"
rationale = "Verb-object: shapes the raw value; the rest is context."
+["pipelex/core/memory/input_shaper.py::InputShaper._try_shape_structureless_envelope"]
+param = "value"
+rationale = "Verb-object: shapes the raw value when it is a structureless envelope; the rest is context."
+
["pipelex/core/memory/input_shaper.py::InputShaper.resolve_input_kind"]
param = "concept"
rationale = "Noun-named derivation: the input kind of the concept; single operand."
diff --git a/tests/data/input_semantics/scaffold_bundle.mthds b/tests/data/input_semantics/scaffold_bundle.mthds
index c44406d74..988f29fef 100644
--- a/tests/data/input_semantics/scaffold_bundle.mthds
+++ b/tests/data/input_semantics/scaffold_bundle.mthds
@@ -53,36 +53,20 @@ Any number of bookmarks:
"""
# The natives whose payload shape the descriptor states openly, at slot positions — the one place
-# the corpus never reached. `native.Dynamic` and `native.Composite` declare no pinned structure, so
-# their node is `unknown` and every projection renders the empty object both renderers agree on.
-# `native.JSON` is not: its pinned blueprint carries a required `json_obj`, so it expands like any
-# other pinned native, and the dict inside it is the corpus's first REQUIRED unknown node — the
-# engine invents a sample key there, the projection leaves the object empty for whoever fills it in.
-# `native.Anything` belongs to the same family and is deliberately NOT here: it is the one open
-# native the input shaper refuses, so it sits in its own pipe below rather than putting this whole
-# template behind a declared refusal. That matters because the round-trip gate keys on the pipe and
-# the shape, never on the slot: an entry here would suspend the shaper check for `json_in`,
-# `dynamic_in` and `composite_in` too, and `json_in`'s dict is the only site where the corpus
-# measures `unknown-empty-object` — the class whose whole claim is that the empty object round-trips.
+# the corpus never reached. `native.Dynamic`, `native.Composite` and `native.Anything` declare no
+# pinned structure, so their node is `unknown`, every projection renders the empty object both
+# renderers agree on, and the input shaper takes that object back at each of them. `native.JSON` is
+# not: its pinned blueprint carries a required `json_obj`, so its explicit template expands like any
+# other pinned native's, while its compact template is the bare object with `json_obj` unwrapped.
+# That dict is the corpus's first REQUIRED unknown node — the engine invents a sample key there, the
+# projection leaves the object empty for whoever fills it in — and the only site where the corpus
+# measures `unknown-empty-object`, the class whose whole claim is that the empty object round-trips.
[pipe.scaffold_open_natives]
type = "PipeCompose"
-description = "SCAFFOLD_pipe_scaffold_open_natives: a pinned-dict native beside the two structureless ones, each at a slot position"
-inputs = { json_in = "JSON", dynamic_in = "Dynamic", composite_in = "Composite" }
+description = "SCAFFOLD_pipe_scaffold_open_natives: a pinned-dict native beside the three structureless ones, each at a slot position"
+inputs = { json_in = "JSON", dynamic_in = "Dynamic", composite_in = "Composite", anything_in = "Anything" }
output = "Text"
-template = "SCAFFOLD_template_open_natives: $json_in $dynamic_in $composite_in"
-
-# `native.Anything`, alone, because the runtime refuses the template the descriptor makes it publish.
-# The node is `unknown` exactly as its two siblings above are, so the projection renders the same
-# empty object — and those two hand that value straight back, while `native.Anything` alone has no
-# dict-content arm: the shaper answers "not compatible with a dict content" and accepts a bare string
-# there and nothing else, returning it as a `native.Text` stuff. Both shapes of THIS pipe are
-# therefore declared in the capture's unshapeable record, and nothing else is dragged in with them.
-[pipe.scaffold_anything_slot]
-type = "PipeCompose"
-description = "SCAFFOLD_pipe_scaffold_anything_slot: the one open-shaped native whose published template the runtime refuses, alone at a slot position"
-inputs = { anything_in = "Anything" }
-output = "Text"
-template = "SCAFFOLD_template_anything_slot: $anything_in"
+template = "SCAFFOLD_template_open_natives: $json_in $dynamic_in $composite_in $anything_in"
# A `native.Dynamic` slot read by a PipeLLM prompt, under both markers. Until the prompt analyzers
# stopped reading universal compatibility as identity, this bundle did not validate at all: a dynamic
diff --git a/tests/integration/pipelex/cli/test_trace_input_semantics_cmd.py b/tests/integration/pipelex/cli/test_trace_input_semantics_cmd.py
index 1b667a3f9..2520ed108 100644
--- a/tests/integration/pipelex/cli/test_trace_input_semantics_cmd.py
+++ b/tests/integration/pipelex/cli/test_trace_input_semantics_cmd.py
@@ -92,11 +92,11 @@ class TestTraceInputSemantics:
hop4_multi = _read_json(output_dir / manifest["hop4_schema_renders"]["trace_tool_test.do_one.items"])
assert hop4_multi["content"]["type"] == "array"
# `native.Anything` declares no structure class: hop 3 records the skip rather than resolving
- # one, and hop 4 still renders — through the structureless arm, as the permissive schema.
+ # one, and hop 4 still renders — through the structureless arm, excluding only array and null.
assert any("native.Anything" in entry for entry in manifest["hop3_skipped"])
hop4_loose = _read_json(output_dir / manifest["hop4_schema_renders"]["trace_tool_test.do_one.loose"])
assert hop4_loose["concept"] == "native.Anything"
- assert set(hop4_loose["content"]) == {"title", "description"}
+ assert set(hop4_loose["content"]) == {"title", "description", "not"}
# Hop 5: the final wire contracts, keyed by namespaced pipe_ref, with presence flags.
hop5 = _read_json(output_dir / HOP5_FILE_NAME)
diff --git a/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py b/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py
index 78e7463e2..8a408b95f 100644
--- a/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py
+++ b/tests/integration/pipelex/pipeline/test_pipe_io_contracts.py
@@ -182,8 +182,8 @@ class TestBuildPipeIOContracts:
gate = io_contracts["optional_contracts_test.gate"]
assert gate.output.optional is True
- async def test_structureless_output_renders_permissively(self, load_empty_library: Callable[[], str]) -> None:
- """A pipe RESOLVING TO `native.Anything` carries a permissive schema rather than failing the build.
+ async def test_structureless_output_renders_its_schema(self, load_empty_library: Callable[[], str]) -> None:
+ """A pipe RESOLVING TO `native.Anything` carries its schema rather than failing the build.
`Anything` is the untyped vehicle: `structure_class` is `None` for it, so the
`AnythingContent` name derived mechanically from its code has no class behind it
@@ -192,14 +192,14 @@ class TestBuildPipeIOContracts:
raised `PipeIOContractError` naming a class that never existed, taking every OTHER
pipe in the bundle down with it.
- **The schema is permissive, not empty**, and the difference is the point. It carries
- no constraint keyword — "any JSON value" is what an untyped vehicle means — but it
- does carry the concept's identity annotations, because every rendered schema does
- and an exception for this one would be a second rule. A bare `{}` would read the
- same to a validator and tell a reader nothing about what they are looking at.
+ **The schema is nearly unconstrained, not empty**, and the difference is the point. It
+ excludes only array and null — a list is the multiplicity's to express, and null is
+ never a value — but it does carry the concept's identity annotations, because every
+ rendered schema does and an exception for this one would be a second rule. A bare
+ `{}` would tell a reader nothing about what they are looking at.
Scoped to the OUTPUT side: the input side is covered by
- `test_anything_input_publishes_permissive_schema` below, which reaches the plural
+ `test_anything_input_publishes_its_schema` below, which reaches the plural
arms too. This one exists because an `Anything`-resolving `PipeCondition` — a router
that resolves to whatever branch it took — is ordinary in a real method, and the
output contract gained its schema after that test was written.
@@ -276,10 +276,10 @@ class TestBuildPipeIOContracts:
one_schema = make_from_one.inputs["docs"].json_schema
assert one_schema.get("type") != "array"
- async def test_anything_input_publishes_permissive_schema(self, load_empty_library: Callable[[], str]) -> None:
+ async def test_anything_input_publishes_its_schema(self, load_empty_library: Callable[[], str]) -> None:
"""A `native.Anything` input renders instead of crashing: the contract publishes the
- permissive schema — no constraint keywords, only the concept's identity annotations —
- with multiplicity wrapping exactly as for class-backed concepts.
+ concept's identity annotations and excludes only array and null, with multiplicity
+ wrapping exactly as for class-backed concepts, so every item carries the exclusion.
"""
outer_library_id = load_empty_library()
try:
@@ -295,12 +295,14 @@ class TestBuildPipeIOContracts:
assert single.multiplicity == IOMultiplicity.SINGLE
assert single.json_schema["title"] == "native.Anything"
assert single.json_schema["description"]
- assert set(single.json_schema) == {"title", "description"}
+ assert set(single.json_schema) == {"title", "description", "not"}
+ assert single.json_schema["not"] == {"type": ["array", "null"]}
batch = carry.inputs["batch_in"]
assert batch.multiplicity == IOMultiplicity.VARIABLE
assert batch.json_schema["type"] == "array"
assert batch.json_schema["items"]["title"] == "native.Anything"
+ assert batch.json_schema["items"]["not"] == {"type": ["array", "null"]}
assert "minItems" not in batch.json_schema
pair = carry.inputs["pair_in"]
diff --git a/tests/integration/pipelex/pipeline/test_protocol_validate.py b/tests/integration/pipelex/pipeline/test_protocol_validate.py
index ca9515441..c376b418f 100644
--- a/tests/integration/pipelex/pipeline/test_protocol_validate.py
+++ b/tests/integration/pipelex/pipeline/test_protocol_validate.py
@@ -59,6 +59,27 @@ output = "Text"
template = "$anything_in"
"""
+_ANYTHING_OUTPUT_SEQUENCE_MTHDS = """
+domain = "protocol_validate_anything_output"
+description = "Bundle whose sequence declares a native.Anything output over a Text-producing last step"
+
+[pipe.seq]
+type = "PipeSequence"
+description = "Echo a text through a sequence that promises nothing narrower than Anything"
+inputs = { doc = "Text" }
+output = "Anything"
+steps = [
+ { pipe = "echo", result = "echoed" },
+]
+
+[pipe.echo]
+type = "PipeCompose"
+description = "Echo the text"
+inputs = { doc = "Text" }
+output = "Text"
+template = "$doc"
+"""
+
_MAIN_PIPE_MTHDS = """
domain = "protocol_validate_graph"
description = "Bundle declaring a main_pipe, for the graph arm"
@@ -158,14 +179,30 @@ class TestProtocolValidate:
assert isinstance(report, PipelexValidationReport)
assert report.is_runnable is True
anything_schema = report.pipe_io_contracts["protocol_validate_anything.carry"].inputs["anything_in"].json_schema
- # The permissive schema carries the identity annotations and nothing else: no constraint
- # keyword may appear, and `description` must be the concept's own, not an empty string.
- assert set(anything_schema) == {"title", "description"}
+ # The schema carries the identity annotations and excludes only array and null, and
+ # `description` must be the concept's own, not an empty string.
+ assert set(anything_schema) == {"title", "description", "not"}
assert anything_schema["title"] == "native.Anything"
assert anything_schema["description"]
finally:
clear_current_library()
+ async def test_anything_output_sequence_validates(self, load_empty_library: Callable[[], str]) -> None:
+ """Every concept satisfies `native.Anything`, so a sequence declaring `output = "Anything"`
+ validates over a last step producing `Text` — the output check asks the same compatibility
+ question the input shaper does.
+ """
+ load_empty_library()
+ try:
+ runner = PipelexMTHDSProtocol()
+ report = await runner.validate(mthds_contents=[_ANYTHING_OUTPUT_SEQUENCE_MTHDS])
+
+ assert isinstance(report, PipelexValidationReport)
+ assert report.is_runnable is True
+ assert report.pipe_io_contracts["protocol_validate_anything_output.seq"].output.concept_ref == "native.Anything"
+ finally:
+ clear_current_library()
+
async def test_hint_lint_warns_without_invalidating(self, load_empty_library: Callable[[], str]) -> None:
"""A warnable hint (unknown key) rides the advisory `warnings` channel; the bundle stays
valid and runnable, and the applicable `intent` beside it warns nothing (spec: hints are
diff --git a/tests/unit/pipelex/cli/dev_cli/test_projection_divergence_gate.py b/tests/unit/pipelex/cli/dev_cli/test_projection_divergence_gate.py
index ae7c51e9e..5df8a4299 100644
--- a/tests/unit/pipelex/cli/dev_cli/test_projection_divergence_gate.py
+++ b/tests/unit/pipelex/cli/dev_cli/test_projection_divergence_gate.py
@@ -15,11 +15,12 @@ import pytest
from pipelex.cli.dev_cli.commands.generate_projection_corpus_cmd import (
COMPACT_SHAPE,
+ EXPLICIT_SHAPE,
MOCK_URL_PREFIX,
DivergenceCollector,
)
from pipelex.core.pipes.variable_multiplicity import PresenceMarker
-from pipelex.pipeline.input_form import ListField, PipeInputFormDescriptor, TextItem
+from pipelex.pipeline.input_form import ListField, ObjectField, ObjectItem, PipeInputFormDescriptor, TextItem, UnknownField
def _list_slot_descriptor(*, name: str, item_count: int | None) -> PipeInputFormDescriptor:
@@ -38,6 +39,31 @@ def _list_slot_descriptor(*, name: str, item_count: int | None) -> PipeInputForm
)
+def _json_slots_descriptor() -> PipeInputFormDescriptor:
+ """A descriptor with a `JSON` slot and a `JSON[]` slot, each node an object holding a required `json_obj`."""
+ return PipeInputFormDescriptor(
+ fields=[
+ ObjectField(
+ name="json_in",
+ required=True,
+ presence=PresenceMarker.PLAIN,
+ gating=False,
+ concept_ref="native.JSON",
+ fields=[UnknownField(name="json_obj", required=True)],
+ ),
+ ListField(
+ name="records",
+ required=True,
+ presence=PresenceMarker.PLAIN,
+ gating=False,
+ concept_ref="native.JSON",
+ item=ObjectItem(required=True, concept_ref="native.JSON", fields=[UnknownField(name="json_obj", required=True)]),
+ item_count=None,
+ ),
+ ]
+ )
+
+
class TestTheDivergenceGateSeesEveryDifference:
def test_a_key_only_the_engine_renders_refuses_the_record(self) -> None:
"""A field the projection stopped rendering: the dict walk iterates the projected keys."""
@@ -150,8 +176,41 @@ class TestTheDivergenceGateSeesEveryDifference:
collector.compare(
engine_value={"json_obj_key": "json_obj_value"},
projected_value={},
- path=["scaffold.scaffold_open_natives", COMPACT_SHAPE, "json_in", "json_obj"],
+ path=["scaffold.scaffold_open_natives", EXPLICIT_SHAPE, "json_in", "content", "json_obj"],
)
assert collector.counts == {"unknown-empty-object": 1}
assert not collector.unclassified
+
+ def test_an_unwrapped_json_slot_keeps_its_class(self) -> None:
+ """The compact shape unwraps `json_obj`, so the placeholder sits at the slot, and at each item of a list."""
+ collector = DivergenceCollector()
+ collector.register_json_unwraps(pipe_ref="scaffold.scaffold_open_natives", descriptor=_json_slots_descriptor())
+
+ collector.compare(
+ engine_value={"json_obj_key": "json_obj_value"},
+ projected_value={},
+ path=["scaffold.scaffold_open_natives", COMPACT_SHAPE, "json_in"],
+ )
+ collector.compare(
+ engine_value={"json_obj_key": "json_obj_value"},
+ projected_value={},
+ path=["scaffold.scaffold_open_natives", COMPACT_SHAPE, "records", "0"],
+ )
+
+ assert collector.counts == {"unknown-empty-object": 2}
+ assert not collector.unclassified
+
+ def test_an_unregistered_json_slot_is_not_absorbed(self) -> None:
+ """Without the descriptor's word, a slot-level placeholder keyed `json_obj` is a difference the capture refuses."""
+ collector = DivergenceCollector()
+
+ collector.compare(
+ engine_value={"json_obj_key": "json_obj_value"},
+ projected_value={},
+ path=["scaffold.scaffold_open_natives", COMPACT_SHAPE, "json_in"],
+ )
+
+ assert "unknown-empty-object" not in collector.counts
+ with pytest.raises(ValueError, match="Undeclared divergence class"):
+ collector.declared()
diff --git a/tests/unit/pipelex/cli/dev_cli/test_projection_reference.py b/tests/unit/pipelex/cli/dev_cli/test_projection_reference.py
index 64710b08f..28f72773b 100644
--- a/tests/unit/pipelex/cli/dev_cli/test_projection_reference.py
+++ b/tests/unit/pipelex/cli/dev_cli/test_projection_reference.py
@@ -217,6 +217,27 @@ class TestOutOfMatrixNatives:
projected = project_inputs_template(descriptor=_descriptor(date_slot), explicit=False)["date_in"]
assert projected == {"concept": "native.Date", "content": {"date": "2026-01-01", "time": "12:00:00"}}
+ def test_a_json_slot_unwraps_to_its_object_in_the_compact_shape(self):
+ """`native.JSON` is not out of matrix: the shaper reads a bare object there literally, so the
+ compact shape is the object its `json_obj` holds, and the explicit shape keeps the content form.
+ """
+ json_node: dict[str, Any] = {
+ "kind": "object",
+ "concept_ref": "native.JSON",
+ "required": True,
+ "fields": [{"kind": "unknown", "name": "json_obj", "required": True}],
+ }
+ single = {**json_node, "name": "payload"}
+ plural = {"kind": "list", "name": "records", "concept_ref": "native.JSON", "required": True, "item": json_node}
+ descriptor = _descriptor(single, plural)
+
+ compact = project_inputs_template(descriptor=descriptor, explicit=False)
+ explicit = project_inputs_template(descriptor=descriptor, explicit=True)
+
+ assert compact == {"payload": {}, "records": [{}]}
+ assert explicit["payload"] == {"concept": "native.JSON", "content": {"json_obj": {}}}
+ assert explicit["records"] == {"concept": "native.JSON", "content": [{"json_obj": {}}]}
+
def test_a_nested_field_naming_a_native_holds_that_native_s_content_object(self):
"""A nested `native.Text` is a `TextContent`, so the payload carries `{"text": ...}` there —
where an authored `type = "text"` field beside it carries the bare value. The descriptor
diff --git a/tests/unit/pipelex/core/memory/input_shaper/data.py b/tests/unit/pipelex/core/memory/input_shaper/data.py
index 8c8ddace6..dffb24be2 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/data.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/data.py
@@ -1,6 +1,6 @@
"""Shared fixtures data for the InputShaper unit tests.
-Defines a small library of concepts covering each D5 arm — Text/Number/YesNo/Date/Image/Document
+Defines a small library of concepts covering each D5 arm — Text/Number/YesNo/Date/Image/Document/JSON
refinements plus structured concepts — and a helper to build an ``InputStuffSpecs`` fixture from a
list of ``(variable_name, concept_ref, multiplicity)`` entries resolved against the current library.
"""
@@ -13,6 +13,7 @@ from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
from pipelex.core.stuffs.date_content import DateContent
from pipelex.core.stuffs.document_content import DocumentContent
from pipelex.core.stuffs.image_content import ImageContent
+from pipelex.core.stuffs.json_content import JSONContent
from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.structured_content import StructuredContent
from pipelex.core.stuffs.text_content import TextContent
@@ -50,6 +51,10 @@ class Exhibit(DocumentContent):
"""Refines native Document."""
+class Payload(JSONContent):
+ """Refines native JSON — the subclass generated for `refines = "JSON"`."""
+
+
# Structured test concepts carry a `Shaper`-prefixed name so their registration in the by-name
# global class registry can never be shadowed by an identically-named StructuredContent from another
# test suite (e.g. an integration test's `Person`/`Invoice`). The concept code matches the class name
@@ -64,6 +69,13 @@ class ShaperPerson(StructuredContent):
name: str = Field(description="The person's name")
+class ShaperRecord(StructuredContent):
+ """A structure every field of which is optional, so any object built of its keys validates."""
+
+ a: int | None = Field(default=None, description="An optional number")
+ b: int | None = Field(default=None, description="Another optional number")
+
+
class ShaperWeird(StructuredContent):
"""A pathological structure whose fields are literally `concept` and `content` (collision-rule test)."""
@@ -73,7 +85,7 @@ class ShaperWeird(StructuredContent):
# Non-StructuredContent refinements — registered explicitly (the refinement machinery would register
# a subclass like these for a `refines = "<native>"` concept).
-REFINING_CLASSES = [Question, Priority, Verdict, Deadline, OpeningTime, Photo, Exhibit]
+REFINING_CLASSES = [Question, Priority, Verdict, Deadline, OpeningTime, Photo, Exhibit, Payload]
# (concept_code, structure_class_name, refines) for every test concept.
CONCEPT_DEFS: list[tuple[str, str, str | None]] = [
@@ -84,8 +96,10 @@ CONCEPT_DEFS: list[tuple[str, str, str | None]] = [
("OpeningTime", "OpeningTime", "native.Time"),
("Photo", "Photo", "native.Image"),
("Exhibit", "Exhibit", "native.Document"),
+ ("Payload", "Payload", "native.JSON"),
("ShaperInvoice", "ShaperInvoice", None),
("ShaperPerson", "ShaperPerson", None),
+ ("ShaperRecord", "ShaperRecord", None),
("ShaperWeird", "ShaperWeird", None),
]
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_anything_envelopes.py b/tests/unit/pipelex/core/memory/input_shaper/test_anything_envelopes.py
new file mode 100644
index 000000000..39ff5463e
--- /dev/null
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_anything_envelopes.py
@@ -0,0 +1,187 @@
+from typing import Any
+
+import pytest
+
+from pipelex.core.memory.exceptions import (
+ ListWhereSingularError,
+ WrongScalarKindError,
+)
+from pipelex.core.memory.input_shaper import InputShaper
+from pipelex.core.stuffs.image_content import ImageContent
+from pipelex.core.stuffs.json_content import JSONContent
+from pipelex.core.stuffs.list_content import ListContent
+from pipelex.core.stuffs.number_content import NumberContent
+from pipelex.core.stuffs.stuff_content import StuffContent
+from pipelex.core.stuffs.text_content import TextContent
+from pipelex.core.stuffs.yes_no_content import YesNoContent
+from pipelex.interpreter_hub import get_concept_library
+from tests.unit.pipelex.core.memory.input_shaper.data import Question, ShaperPerson, build_input_specs
+
+
+class TestInputShaperAnythingEnvelopes:
+ @pytest.mark.parametrize("anything_spelling", ["Anything", "native.Anything"])
+ @pytest.mark.parametrize(
+ ("content", "expected_content"),
+ [
+ ({}, JSONContent(json_obj={})),
+ ("hi", TextContent(text="hi")),
+ (4.2, NumberContent(number=4.2)),
+ (False, YesNoContent(yes_no=False)),
+ ],
+ )
+ def test_anything_envelope_is_the_bare_value(self, anything_spelling: str, content: Any, expected_content: StuffContent) -> None:
+ """An `Anything` envelope's content is shaped exactly as the same bare value would be (R1)."""
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+ provided = {"concept": anything_spelling, "content": content}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == expected_content
+
+ def test_anything_envelope_around_a_list_at_a_plural_slot(self) -> None:
+ input_specs = build_input_specs([("payload", "native.Anything", True)])
+ provided: dict[str, Any] = {"concept": "native.Anything", "content": [1, "a"]}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == ListContent(items=[NumberContent(number=1), TextContent(text="a")])
+
+ def test_anything_envelope_around_a_list_at_a_single_slot_raises(self) -> None:
+ """The envelope does not lift D2: a single `Anything` slot never holds a list."""
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+ provided: dict[str, Any] = {"concept": "native.Anything", "content": [1, "a"]}
+
+ with pytest.raises(ListWhereSingularError, match="declares a single"):
+ InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ @pytest.mark.parametrize(
+ ("provided", "expected_concept_ref", "expected_content"),
+ [
+ ({"concept": "Text", "content": "hi"}, "native.Text", TextContent(text="hi")),
+ ({"concept": "native.JSON", "content": {"json_obj": {"a": 1}}}, "native.JSON", JSONContent(json_obj={"a": 1})),
+ ({"concept": "shaper_test.ShaperPerson", "content": {"name": "Ada"}}, "shaper_test.ShaperPerson", ShaperPerson(name="Ada")),
+ ({"concept": "Image", "content": {"url": "photo.jpg"}}, "native.Image", ImageContent(url="photo.jpg")),
+ ],
+ )
+ def test_typed_envelope_at_an_anything_slot_keeps_its_concept(
+ self, provided: dict[str, Any], expected_concept_ref: str, expected_content: StuffContent
+ ) -> None:
+ """R2 and D6: every concept satisfies `Anything`, and the explicit, more specific concept wins."""
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == expected_concept_ref
+ assert stuff.content == expected_content
+
+ def test_prebuilt_content_at_an_anything_slot_keeps_its_inferred_concept(self) -> None:
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+
+ working_memory = InputShaper.shape(
+ {"payload": Question(text="Why?")}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library()
+ )
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "shaper_test.Question"
+ assert stuff.content == Question(text="Why?")
+
+ def test_list_of_prebuilt_contents_of_different_kinds_at_anything_list(self) -> None:
+ """Each prebuilt item is compat-checked against `Anything`, so a heterogeneous list is fine."""
+ input_specs = build_input_specs([("payload", "native.Anything", True)])
+ provided: list[StuffContent] = [TextContent(text="a"), NumberContent(number=1)]
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == ListContent(items=[TextContent(text="a"), NumberContent(number=1)])
+
+ def test_a_prebuilt_list_of_different_kinds_at_anything_list_is_the_list_of_its_items(self) -> None:
+ """A mixed `ListContent` infers no single concept, so it is read as the bare list of its items."""
+ input_specs = build_input_specs([("payload", "native.Anything", True)])
+ prebuilt: ListContent[StuffContent] = ListContent(items=[TextContent(text="a"), NumberContent(number=1)])
+
+ working_memory = InputShaper.shape({"payload": prebuilt}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == prebuilt
+
+ def test_a_prebuilt_list_of_different_kinds_at_a_single_anything_slot_raises(self) -> None:
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+ prebuilt: ListContent[StuffContent] = ListContent(items=[TextContent(text="a"), NumberContent(number=1)])
+
+ with pytest.raises(ListWhereSingularError, match="declares a single"):
+ InputShaper.shape({"payload": prebuilt}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ def test_nested_envelope_escape_holds_an_envelope_shaped_object(self) -> None:
+ """An object keyed exactly `concept` and `content` travels as raw data inside an `Anything` envelope."""
+ input_specs = build_input_specs([("payload", "native.Anything", None)])
+ provided = {"concept": "native.Anything", "content": {"concept": "x", "content": "y"}}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == JSONContent(json_obj={"concept": "x", "content": "y"})
+
+ def test_anything_envelope_content_is_raw_at_every_depth(self) -> None:
+ """R10's escape: inside an `Anything` envelope, an envelope-shaped list item is raw data."""
+ input_specs = build_input_specs([("payload", "native.Anything", True)])
+ envelope_shaped_item = {"concept": "Image", "content": {"url": "photo.jpg"}}
+ provided: dict[str, Any] = {"concept": "native.Anything", "content": [envelope_shaped_item, "caption"]}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == ListContent(items=[JSONContent(json_obj=envelope_shaped_item), TextContent(text="caption")])
+
+ def test_anything_envelope_at_a_dynamic_slot_keeps_its_concept(self) -> None:
+ """`Anything` satisfies `Dynamic`, so the envelope is honoured there too, and read as R1 reads it."""
+ input_specs = build_input_specs([("payload", "native.Dynamic", None)])
+ provided = {"concept": "native.Anything", "content": {"a": 1}}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == JSONContent(json_obj={"a": 1})
+
+ def test_anything_envelope_around_a_prebuilt_list_is_the_list_of_its_items(self) -> None:
+ """A prebuilt `ListContent` is the same value as the bare list of its items (R5 reads it by R1 and R3)."""
+ prebuilt: ListContent[TextContent] = ListContent(items=[TextContent(text="a"), TextContent(text="b")])
+ provided: dict[str, Any] = {"concept": "native.Anything", "content": prebuilt}
+
+ for multiplicity in (True, 2):
+ input_specs = build_input_specs([("payload", "native.Anything", multiplicity)])
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+ assert working_memory.root["payload"].content == prebuilt
+
+ single_specs = build_input_specs([("payload", "native.Anything", None)])
+ with pytest.raises(ListWhereSingularError):
+ InputShaper.shape({"payload": provided}, input_specs=single_specs, concept_provider=get_concept_library())
+
+ def test_a_prebuilt_list_as_a_list_item_is_refused(self) -> None:
+ """An item of a plural slot that is itself a list is refused, whether it is a bare array or a `ListContent`."""
+ input_specs = build_input_specs([("items", "native.Text", True)])
+ provided: list[ListContent[TextContent]] = [ListContent(items=[TextContent(text="a"), TextContent(text="b")])]
+
+ with pytest.raises(WrongScalarKindError, match="a single value, not a list"):
+ InputShaper.shape({"items": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ def test_anything_envelope_at_a_dynamic_slot_takes_its_multiplicity_from_its_content(self) -> None:
+ """At a `Dynamic` slot the signature cannot say list or single, so the content does, as for every other envelope."""
+ input_specs = build_input_specs([("payload", "native.Dynamic", None)])
+ provided = {"concept": "native.Anything", "content": [1, 2]}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == ListContent(items=[NumberContent(number=1), NumberContent(number=2)])
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_anything_schema_agreement.py b/tests/unit/pipelex/core/memory/input_shaper/test_anything_schema_agreement.py
new file mode 100644
index 000000000..c9413a385
--- /dev/null
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_anything_schema_agreement.py
@@ -0,0 +1,61 @@
+from typing import Any
+
+import jsonschema
+import pytest
+
+from pipelex.core.concepts.concept_representation_generator import ConceptRepresentationFormat
+from pipelex.core.memory.exceptions import InputShapingError
+from pipelex.core.memory.input_shaper import InputShaper
+from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
+from pipelex.interpreter_hub import get_concept_library
+from tests.unit.pipelex.core.memory.input_shaper.data import build_input_specs
+
+# (multiplicity, provided value) — every JSON type at each declaration, including the ones refused. Two shapes
+# are left out because the two sides differ on them by design: a single bare value at `Anything[]`, which the
+# shaper wraps into a one-item list, and an `Anything[]` item keyed exactly `concept` and `content`, which R10
+# refuses and the schema does not state (`wip/anything-slot/plan.md` defers it).
+AGREEMENT_CASES: list[tuple[VariableMultiplicity | None, Any]] = [
+ (None, {}),
+ (None, {"a": 1}),
+ (None, "hi"),
+ (None, ""),
+ (None, 3),
+ (None, 4.2),
+ (None, 0),
+ (None, True),
+ (None, False),
+ (None, None),
+ (None, []),
+ (None, ["a"]),
+ (None, [{"a": 1}]),
+ (True, []),
+ (True, ["hi", 3, True, {"a": 1}]),
+ (True, [[1]]),
+ (True, [None]),
+ (True, [["a"], "b"]),
+ (2, ["hi", {"a": 1}]),
+ (2, ["hi"]),
+ (2, ["hi", None]),
+]
+
+
+class TestAnythingSchemaAgreement:
+ @pytest.mark.parametrize(("multiplicity", "provided_value"), AGREEMENT_CASES)
+ def test_the_schema_admits_exactly_what_the_shaper_takes(self, multiplicity: VariableMultiplicity | None, provided_value: Any) -> None:
+ """R4: the published `Anything` schema and the input shaper accept and refuse the same JSON types."""
+ input_specs = build_input_specs([("payload", "native.Anything", multiplicity)])
+ stuff_spec = input_specs.root["payload"]
+ rendered = stuff_spec.render_stuff_spec(concept_provider=get_concept_library(), output_format=ConceptRepresentationFormat.SCHEMA)
+ json_schema = rendered["content"]
+
+ # The `types-jsonschema` overloads of `is_valid` carry an `Unknown` arm.
+ schema_admits = jsonschema.Draft202012Validator(json_schema).is_valid(provided_value) # pyright: ignore[reportUnknownMemberType]
+ try:
+ InputShaper.shape({"payload": provided_value}, input_specs=input_specs, concept_provider=get_concept_library())
+ shaper_takes = True
+ except InputShapingError:
+ shaper_takes = False
+
+ assert schema_admits == shaper_takes, (
+ f"schema admits={schema_admits}, shaper takes={shaper_takes} for {provided_value!r} at multiplicity {multiplicity!r}: {json_schema}"
+ )
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py b/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
index 26b59516d..3b88635dc 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_errors.py
@@ -47,6 +47,56 @@ ERROR_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, type[InputSh
("structure-missing-field", "shaper_test.ShaperInvoice", None, {"invoice_number": "INV-1"}, StructureValidationError, "could not be built"),
# D4 a non-ISO date string is the right kind but an invalid value.
("non-iso-date", "shaper_test.Deadline", None, "March 7, 2026", StructureValidationError, "ISO 8601"),
+ # R3 Anything keeps D2 and D9: a list at a single slot, a count mismatch, a null anywhere.
+ ("anything-list-where-singular", "native.Anything", None, [1, 2], ListWhereSingularError, "single"),
+ ("anything-count-mismatch", "native.Anything", 2, [1], MultiplicityCountMismatchError, "exactly 2"),
+ ("anything-null-item", "native.Anything", True, [1, None], WrongScalarKindError, "provided null"),
+ ("anything-nested-list-item", "native.Anything", True, [[1, 2]], WrongScalarKindError, "a list of 2 item"),
+ ("anything-null-envelope-content", "native.Anything", None, {"concept": "native.Anything", "content": None}, NullInputError, "null"),
+ # NaN and the infinities, which a TOML inputs file can spell, are numbers JSON cannot hold.
+ ("nan-for-number", "shaper_test.Priority", None, float("nan"), WrongScalarKindError, "a number JSON cannot hold"),
+ ("inf-for-number", "native.Number", None, float("inf"), WrongScalarKindError, "a number JSON cannot hold"),
+ ("nan-for-anything", "native.Anything", None, float("nan"), WrongScalarKindError, "a number JSON cannot hold"),
+ ("inf-item-for-anything-list", "native.Anything", True, [1, float("-inf")], WrongScalarKindError, "a number JSON cannot hold"),
+ ("json-object-holding-nan", "native.JSON", None, {"a": float("nan")}, StructureValidationError, "not valid JSON"),
+ ("anything-object-holding-an-infinity", "native.Anything", None, {"a": {"b": float("inf")}}, StructureValidationError, "not valid JSON"),
+ ("json-list-item-holding-an-infinity", "native.JSON", True, [{"a": float("-inf")}], StructureValidationError, "not valid JSON"),
+ # R1 a Python caller's value that is not JSON at all.
+ ("anything-not-a-json-value", "native.Anything", None, {1, 2}, WrongScalarKindError, "a value of type set"),
+ # An object holding a value that is not JSON is a typed refusal, not a raw TypeError from the validator.
+ ("anything-object-holding-a-non-json-value", "native.Anything", None, {"a": object()}, StructureValidationError, "not valid JSON"),
+ # R10 an item of a bare list shaped like an envelope is refused, and the message says how to type a list.
+ (
+ "anything-envelope-shaped-item",
+ "native.Anything",
+ True,
+ [{"concept": "Image", "content": {"url": "photo.jpg"}}, "caption"],
+ WrongScalarKindError,
+ "wrap the whole list in one",
+ ),
+ # R5 an Anything envelope is not known to satisfy anything narrower.
+ (
+ "anything-envelope-at-text-slot",
+ "native.Text",
+ None,
+ {"concept": "native.Anything", "content": "hi"},
+ ExplicitConceptIncompatibleError,
+ "not compatible",
+ ),
+ # R7 a JSON slot takes a JSON object and nothing else. A string used to become native.Text.
+ ("json-string", "native.JSON", None, "hi", WrongScalarKindError, "expects a JSON object"),
+ ("json-number", "native.JSON", None, 3, WrongScalarKindError, "expects a JSON object"),
+ ("json-boolean", "native.JSON", None, True, WrongScalarKindError, "expects a JSON object"),
+ ("json-list-where-singular", "native.JSON", None, [{"a": 1}], ListWhereSingularError, "single"),
+ ("json-array-item", "native.JSON", True, [{"a": 1}, [1, 2]], WrongScalarKindError, "expects a JSON object"),
+ (
+ "json-envelope-shaped-item",
+ "native.JSON",
+ True,
+ [{"concept": "JSON", "content": {"json_obj": {}}}],
+ WrongScalarKindError,
+ "wrap the whole list in one",
+ ),
# D6 an explicit envelope naming an incompatible concept.
(
"explicit-incompatible",
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py b/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py
index 89ba5b56f..3a3656b42 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_explicit_forms.py
@@ -2,6 +2,7 @@ import datetime
from typing import Any
import pytest
+from pydantic import ValidationError
from pipelex import log, pretty_print
from pipelex.core.memory.exceptions import (
@@ -126,6 +127,22 @@ class TestInputShaperExplicitForms:
with pytest.raises(MultiplicityCountMismatchError, match="exactly 2 items"):
InputShaper.shape({"questions": provided}, input_specs=input_specs, search_scope="shaper_test", concept_provider=get_concept_library())
+ @pytest.mark.parametrize("declared_concept", ["native.Number", "native.Anything"])
+ def test_explicit_number_envelope_holding_nan_raises(self, declared_concept: str) -> None:
+ """An explicit envelope builds its content bottom-up, and `NumberContent` refuses a number JSON cannot hold."""
+ input_specs = build_input_specs([("payload", declared_concept, None)])
+ provided: dict[str, Any] = {"concept": "Number", "content": {"number": float("nan")}}
+
+ with pytest.raises(ValidationError, match="number must be finite"):
+ InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ def test_explicit_single_into_fixed_count_raises(self) -> None:
+ """A single value is one item, never the N a fixed count declares."""
+ input_specs = build_input_specs([("answers", "native.Text", 2)])
+ provided = {"concept": "native.Text", "content": "hello"}
+ with pytest.raises(MultiplicityCountMismatchError, match="but you provided 1"):
+ InputShaper.shape({"answers": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
def test_explicit_list_into_list_slot_ok(self) -> None:
"""D2/D6: an explicit ListContent whose length matches a declared list slot shapes cleanly."""
input_specs = build_input_specs([("questions", "shaper_test.Question", True)])
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py b/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py
new file mode 100644
index 000000000..57cfa105a
--- /dev/null
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_fallback_refusal.py
@@ -0,0 +1,115 @@
+from typing import Any
+
+import pytest
+
+from pipelex.base_exceptions import ErrorDomain
+from pipelex.cogt.inference.error_classification import UserActionKind
+from pipelex.core.memory.exceptions import (
+ StructureValidationError,
+)
+from pipelex.core.memory.input_shaper import InputShaper
+from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
+from pipelex.core.stuffs.exceptions import StuffFactoryError
+from pipelex.core.stuffs.number_content import NumberContent
+from pipelex.core.stuffs.text_content import TextContent
+from pipelex.interpreter_hub import get_concept_library
+from tests.unit.pipelex.core.memory.input_shaper.data import build_input_specs
+
+
+class TestInputShaperFallbackRefusal:
+ @pytest.mark.parametrize(
+ ("concept_ref", "multiplicity"),
+ [
+ ("native.Dynamic", None),
+ ("native.Dynamic", True),
+ ("native.Composite", True),
+ ("native.Html", True),
+ ("native.TextAndImages", True),
+ ("native.SearchResult", True),
+ ("native.Page", True),
+ ],
+ )
+ def test_a_list_of_objects_is_refused_naming_the_input(self, concept_ref: str, multiplicity: VariableMultiplicity | None) -> None:
+ input_specs = build_input_specs([("records", concept_ref, multiplicity)])
+ records_input: dict[str, Any] = {"records": [{"a": 1}, {"b": 2}]}
+
+ with pytest.raises(StructureValidationError) as exc_info:
+ InputShaper.shape(records_input, input_specs=input_specs, concept_provider=get_concept_library())
+
+ error = exc_info.value
+ message = str(error)
+ assert "Input 'records'" in message
+ assert f"'{concept_ref}'" in message
+ assert "a list of 2 item(s)" in message
+ assert "Expected shape:" in message
+ # The factory's own text, with its `typing.Union[...]` spelling of what it accepts, stays on
+ # the chain as the cause and out of what a caller reads.
+ assert "typing.Union" not in message
+ assert isinstance(error.__cause__, StuffFactoryError)
+ assert error.error_domain == ErrorDomain.INPUT
+ # The fix is on the author's side: the declaration, and no envelope.
+ assert error.user_action is not None
+ assert error.user_action.kind == UserActionKind.CHANGE_INPUT
+ assert "'JSON[]'" in error.user_action.detail
+ assert "envelope" not in error.user_action.detail
+
+ def test_a_bare_number_at_a_dynamic_slot_is_refused_naming_the_input(self) -> None:
+ input_specs = build_input_specs([("payload", "native.Dynamic", None)])
+ payload_input: dict[str, Any] = {"payload": 3}
+
+ with pytest.raises(StructureValidationError, match=r"Input 'payload' could not be built as 'native\.Dynamic'") as exc_info:
+ InputShaper.shape(payload_input, input_specs=input_specs, concept_provider=get_concept_library())
+
+ assert "a number (3)" in str(exc_info.value)
+ assert isinstance(exc_info.value.__cause__, StuffFactoryError)
+
+ @pytest.mark.parametrize(
+ ("concept_ref", "multiplicity", "provided_value", "suggested_declaration"),
+ [
+ ("native.Dynamic", None, 3, "'Anything'"),
+ ("native.Dynamic", None, True, "'Anything'"),
+ ("native.Dynamic", True, [1, "a"], "'Anything[]'"),
+ ("native.Dynamic", True, [{"a": 1}, {"b": 2}], "'JSON[]'"),
+ ],
+ )
+ def test_the_advice_names_the_declaration_that_reads_the_value(
+ self, concept_ref: str, multiplicity: VariableMultiplicity | None, provided_value: Any, suggested_declaration: str
+ ) -> None:
+ input_specs = build_input_specs([("payload", concept_ref, multiplicity)])
+ payload_input: dict[str, Any] = {"payload": provided_value}
+
+ with pytest.raises(StructureValidationError, match="with no reading for this one") as exc_info:
+ InputShaper.shape(payload_input, input_specs=input_specs, concept_provider=get_concept_library())
+
+ user_action = exc_info.value.user_action
+ assert user_action is not None
+ assert f"as {suggested_declaration}," in user_action.detail
+
+ @pytest.mark.parametrize(
+ ("concept_ref", "multiplicity", "provided_value", "factory_reason"),
+ [
+ ("native.Html", True, [], "empty list"),
+ ("native.Dynamic", True, [TextContent(text="a"), NumberContent(number=1)], "not of the same type"),
+ # `Anything[]` refuses a nested list and a null item too, so no declaration is advised.
+ ("native.Dynamic", True, [[1, 2], [3]], "could not be built"),
+ ("native.Dynamic", True, [1, None], "could not be built"),
+ # NaN, an object holding one, and envelope-shaped items are refused by every declaration too.
+ ("native.Dynamic", None, float("nan"), "Unexpected type"),
+ ("native.Dynamic", True, [1, float("inf")], "Cannot create Stuff from list"),
+ ("native.Dynamic", None, {"a": float("nan")}, "should represent a StuffContentOrData"),
+ ("native.Dynamic", True, [{"concept": "Text", "content": "a"}], "Cannot create Stuff from list"),
+ ],
+ )
+ def test_a_refusal_that_is_not_about_a_reading_keeps_the_factory_s_reason(
+ self, concept_ref: str, multiplicity: VariableMultiplicity | None, provided_value: Any, factory_reason: str
+ ) -> None:
+ input_specs = build_input_specs([("payload", concept_ref, multiplicity)])
+ payload_input: dict[str, Any] = {"payload": provided_value}
+
+ with pytest.raises(StructureValidationError, match=r"Input 'payload' could not be built as") as exc_info:
+ InputShaper.shape(payload_input, input_specs=input_specs, concept_provider=get_concept_library())
+
+ message = str(exc_info.value)
+ assert factory_reason in message
+ assert "no reading" not in message
+ assert isinstance(exc_info.value.__cause__, StuffFactoryError)
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_json_envelopes.py b/tests/unit/pipelex/core/memory/input_shaper/test_json_envelopes.py
new file mode 100644
index 000000000..4521b0122
--- /dev/null
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_json_envelopes.py
@@ -0,0 +1,31 @@
+from typing import Any
+
+from pipelex.core.memory.input_shaper import InputShaper
+from pipelex.core.stuffs.json_content import JSONContent
+from pipelex.core.stuffs.list_content import ListContent
+from pipelex.interpreter_hub import get_concept_library
+from tests.unit.pipelex.core.memory.input_shaper.data import build_input_specs
+
+
+class TestInputShaperJSONEnvelopes:
+ def test_json_envelope_carries_the_content_form(self) -> None:
+ input_specs = build_input_specs([("payload", "native.JSON", None)])
+ provided = {"concept": "native.JSON", "content": {"json_obj": {"a": 1}}}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.JSON"
+ assert stuff.content == JSONContent(json_obj={"a": 1})
+
+ def test_json_envelope_around_a_list_of_content_forms_is_r10s_escape(self) -> None:
+ """At `JSON[]`, an object keyed `concept` and `content` travels as the `json_obj` of one content form."""
+ input_specs = build_input_specs([("payload", "native.JSON", True)])
+ envelope_shaped_object = {"concept": "Image", "content": {"url": "photo.jpg"}}
+ provided: dict[str, Any] = {"concept": "native.JSON", "content": [{"json_obj": envelope_shaped_object}, {"json_obj": {"b": 2}}]}
+
+ working_memory = InputShaper.shape({"payload": provided}, input_specs=input_specs, concept_provider=get_concept_library())
+
+ stuff = working_memory.root["payload"]
+ assert stuff.concept.concept_ref == "native.JSON"
+ assert stuff.content == ListContent(items=[JSONContent(json_obj=envelope_shaped_object), JSONContent(json_obj={"b": 2})])
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_list_of_objects_report.py b/tests/unit/pipelex/core/memory/input_shaper/test_list_of_objects_report.py
new file mode 100644
index 000000000..6e59c2730
--- /dev/null
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_list_of_objects_report.py
@@ -0,0 +1,70 @@
+from typing import Any
+
+import pytest
+
+from pipelex.core.memory.exceptions import InputShapingError, ListWhereSingularError, StructureValidationError, WrongScalarKindError
+from pipelex.core.memory.input_shaper import InputShaper
+from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
+from pipelex.core.stuffs.json_content import JSONContent
+from pipelex.core.stuffs.list_content import ListContent
+from pipelex.core.stuffs.stuff_content import StuffContent
+from pipelex.interpreter_hub import get_concept_library
+from tests.unit.pipelex.core.memory.input_shaper.data import ShaperRecord, build_input_specs
+
+# The report that widened this arm: a list of plain JSON objects sent to an input slot hit the
+# bottom-up fallback's `Cannot create Stuff from list of <class 'dict'>` without naming the slot.
+# Every declaration below now either takes the list or refuses it with a typed input error, so a
+# `StuffFactoryError` can never again reach a caller from a bare value.
+LIST_OF_OBJECTS: list[dict[str, Any]] = [{"a": 1}, {"b": 2}]
+
+# (concept_ref, multiplicity, expected: the content it shapes into, or the error class it raises)
+REPORT_CASES: list[tuple[str, VariableMultiplicity | None, StuffContent | type[InputShapingError]]] = [
+ ("native.Anything", True, ListContent(items=[JSONContent(json_obj={"a": 1}), JSONContent(json_obj={"b": 2})])),
+ ("native.JSON", True, ListContent(items=[JSONContent(json_obj={"a": 1}), JSONContent(json_obj={"b": 2})])),
+ ("shaper_test.ShaperRecord", True, ListContent(items=[ShaperRecord(a=1), ShaperRecord(b=2)])),
+ ("native.Anything", None, ListWhereSingularError),
+ ("native.JSON", None, ListWhereSingularError),
+ ("shaper_test.ShaperRecord", None, ListWhereSingularError),
+ ("native.Text", None, ListWhereSingularError),
+ ("native.Text", True, WrongScalarKindError),
+ ("native.Number", True, WrongScalarKindError),
+ ("native.YesNo", True, WrongScalarKindError),
+ ("native.Date", True, WrongScalarKindError),
+ ("native.Time", True, WrongScalarKindError),
+ ("native.Image", True, StructureValidationError),
+ ("native.Document", True, StructureValidationError),
+ ("native.Dynamic", None, StructureValidationError),
+ ("native.Dynamic", True, StructureValidationError),
+ ("native.Composite", None, StructureValidationError),
+ ("native.Composite", True, StructureValidationError),
+ ("native.Html", None, StructureValidationError),
+ ("native.Html", True, StructureValidationError),
+ ("native.TextAndImages", None, StructureValidationError),
+ ("native.TextAndImages", True, StructureValidationError),
+ ("native.SearchResult", None, StructureValidationError),
+ ("native.SearchResult", True, StructureValidationError),
+ ("native.Page", None, StructureValidationError),
+ ("native.Page", True, StructureValidationError),
+]
+
+
+class TestListOfObjectsReport:
+ @pytest.mark.parametrize(("concept_ref", "multiplicity", "expected"), REPORT_CASES)
+ def test_a_list_of_plain_objects_is_taken_or_refused_by_name(
+ self,
+ concept_ref: str,
+ multiplicity: VariableMultiplicity | None,
+ expected: StuffContent | type[InputShapingError],
+ ) -> None:
+ input_specs = build_input_specs([("records", concept_ref, multiplicity)])
+ records_input: dict[str, Any] = {"records": LIST_OF_OBJECTS}
+
+ if isinstance(expected, StuffContent):
+ working_memory = InputShaper.shape(records_input, input_specs=input_specs, concept_provider=get_concept_library())
+ stuff = working_memory.root["records"]
+ assert stuff.concept.concept_ref == concept_ref
+ assert stuff.content == expected
+ return
+
+ with pytest.raises(expected, match="Input 'records'"):
+ InputShaper.shape(records_input, input_specs=input_specs, concept_provider=get_concept_library())
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py b/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
index 553e98719..c2666e438 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_multiplicity.py
@@ -6,9 +6,12 @@ import pytest
from pipelex import log, pretty_print
from pipelex.core.memory.input_shaper import InputShaper
from pipelex.core.pipes.variable_multiplicity import VariableMultiplicity
+from pipelex.core.stuffs.json_content import JSONContent
from pipelex.core.stuffs.list_content import ListContent
+from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.core.stuffs.text_content import TextContent
+from pipelex.core.stuffs.yes_no_content import YesNoContent
from pipelex.interpreter_hub import get_concept_library
from tests.unit.pipelex.core.memory.input_shaper.data import Deadline, Question, ShaperPerson, build_input_specs
@@ -88,6 +91,38 @@ MULTIPLICITY_CASES: list[tuple[str, str, VariableMultiplicity | None, Any, str,
"shaper_test.Deadline",
ListContent(items=[Deadline(date=datetime.date(2026, 1, 1)), Deadline(date=datetime.date(2026, 2, 2))]),
),
+ # R3 Anything[]: shaped element-wise, and the items may differ in JSON type.
+ (
+ "anything-list-mixed",
+ "native.Anything",
+ True,
+ ["a", 1, True, {"k": 1}],
+ "native.Anything",
+ ListContent(items=[TextContent(text="a"), NumberContent(number=1), YesNoContent(yes_no=True), JSONContent(json_obj={"k": 1})]),
+ ),
+ ("anything-list-empty", "native.Anything", True, [], "native.Anything", ListContent(items=[])),
+ ("anything-list-auto-wrap-single", "native.Anything", True, "solo", "native.Anything", ListContent(items=[TextContent(text="solo")])),
+ # A single object is wrapped too, rather than read as a list.
+ ("anything-list-auto-wrap-object", "native.Anything", True, {"a": 1}, "native.Anything", ListContent(items=[JSONContent(json_obj={"a": 1})])),
+ (
+ "anything-fixed-count-two",
+ "native.Anything",
+ 2,
+ [1, "b"],
+ "native.Anything",
+ ListContent(items=[NumberContent(number=1), TextContent(text="b")]),
+ ),
+ # R7 JSON[]: each object in turn, a single object wrapped, an empty list legal.
+ (
+ "json-list-of-objects",
+ "native.JSON",
+ True,
+ [{"a": 1}, {"b": 2}],
+ "native.JSON",
+ ListContent(items=[JSONContent(json_obj={"a": 1}), JSONContent(json_obj={"b": 2})]),
+ ),
+ ("json-list-auto-wrap-object", "native.JSON", True, {"a": 1}, "native.JSON", ListContent(items=[JSONContent(json_obj={"a": 1})])),
+ ("json-list-empty", "native.JSON", True, [], "native.JSON", ListContent(items=[])),
]
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_provider_injection.py b/tests/unit/pipelex/core/memory/input_shaper/test_provider_injection.py
index 9212c4d97..5cf218750 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_provider_injection.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_provider_injection.py
@@ -65,6 +65,22 @@ class TestConceptProviderInjection:
assert stub.is_compatible.called
assert stub.get_native_concept.called
+ def test_resolve_input_kind_answers_anything_without_resolving_a_class(self, mocker: MockerFixture) -> None:
+ """`native.Anything` has no class to resolve, so its arm is chosen from the concept alone.
+
+ The stub fails on any class resolution and any compatibility question, so an implementation
+ that walked the ordered natives, or asked for `AnythingContent`, would raise here.
+ """
+ library = get_concept_library()
+ anything_concept = library.get_native_concept(native_concept=NativeConceptCode.ANYTHING)
+
+ stub = mocker.Mock(spec=ConceptProviderAbstract)
+ stub.get_structure_class.side_effect = AssertionError("no structure class may be resolved for native.Anything")
+ stub.is_compatible.side_effect = AssertionError("no compatibility question is needed for native.Anything")
+
+ assert InputShaper.resolve_input_kind(anything_concept, concept_provider=stub) is InputKind.ANYTHING
+ assert not stub.get_structure_class.called
+
def test_building_a_value_resolves_the_structure_class_through_the_injected_provider(self, mocker: MockerFixture) -> None:
"""Content building takes the class from the provider, not from the ambient class registry.
diff --git a/tests/unit/pipelex/core/memory/input_shaper/test_scalar_arms.py b/tests/unit/pipelex/core/memory/input_shaper/test_scalar_arms.py
index 9b8771f3b..9fd34f637 100644
--- a/tests/unit/pipelex/core/memory/input_shaper/test_scalar_arms.py
+++ b/tests/unit/pipelex/core/memory/input_shaper/test_scalar_arms.py
@@ -7,14 +7,17 @@ from pipelex import log, pretty_print
from pipelex.core.memory.input_shaper import InputShaper
from pipelex.core.stuffs.date_content import DateContent
from pipelex.core.stuffs.image_content import ImageContent
+from pipelex.core.stuffs.json_content import JSONContent
from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.core.stuffs.text_content import TextContent
+from pipelex.core.stuffs.time_content import TimeContent
from pipelex.core.stuffs.yes_no_content import YesNoContent
from pipelex.interpreter_hub import get_concept_library
from tests.unit.pipelex.core.memory.input_shaper.data import (
Deadline,
Exhibit,
+ Payload,
Photo,
Priority,
Question,
@@ -50,10 +53,54 @@ SCALAR_ARM_CASES: list[tuple[str, str, Any, str, StuffContent]] = [
"shaper_test.ShaperInvoice",
ShaperInvoice(invoice_number="INV-001", amount=1250.0),
),
- # D5 Dynamic/Anything/out-of-matrix natives: bottom-up passthrough (today's behavior).
+ # D5 Dynamic and the out-of-matrix natives: bottom-up passthrough.
("dynamic-str-bottom-up", "native.Dynamic", "hi", "native.Text", TextContent(text="hi")),
- ("anything-str-bottom-up", "native.Anything", "hi", "native.Text", TextContent(text="hi")),
("html-out-of-matrix-bottom-up", "native.Html", "hi", "native.Text", TextContent(text="hi")),
+ # R1 Anything: the slot keeps its declared concept, and the content is the natural one for the
+ # value's JSON type. Nothing is guessed from a string's text: a URL or an ISO date stays text.
+ ("anything-string", "native.Anything", "hi", "native.Anything", TextContent(text="hi")),
+ ("anything-url-string-stays-text", "native.Anything", "photo.jpg", "native.Anything", TextContent(text="photo.jpg")),
+ ("anything-iso-string-stays-text", "native.Anything", "2026-07-07", "native.Anything", TextContent(text="2026-07-07")),
+ ("anything-int", "native.Anything", 3, "native.Anything", NumberContent(number=3)),
+ ("anything-float", "native.Anything", 3.5, "native.Anything", NumberContent(number=3.5)),
+ ("anything-zero-is-a-number", "native.Anything", 0, "native.Anything", NumberContent(number=0)),
+ # A boolean is never a number, although bool subclasses int.
+ ("anything-true", "native.Anything", True, "native.Anything", YesNoContent(yes_no=True)),
+ ("anything-false", "native.Anything", False, "native.Anything", YesNoContent(yes_no=False)),
+ # The published fill-in template's value, `{}`, shapes.
+ ("anything-empty-object", "native.Anything", {}, "native.Anything", JSONContent(json_obj={})),
+ (
+ "anything-nested-object",
+ "native.Anything",
+ {"a": {"b": [1, "two", None]}},
+ "native.Anything",
+ JSONContent(json_obj={"a": {"b": [1, "two", None]}}),
+ ),
+ # An object is read literally: `json_obj` is JSONContent's field name, not something a caller spells.
+ (
+ "anything-json-obj-key-taken-literally",
+ "native.Anything",
+ {"json_obj": {"a": 1}},
+ "native.Anything",
+ JSONContent(json_obj={"json_obj": {"a": 1}}),
+ ),
+ # R7 JSON: a bare object is the JSON object itself, read literally.
+ ("json-object", "native.JSON", {"a": 1}, "native.JSON", JSONContent(json_obj={"a": 1})),
+ ("json-empty-object", "native.JSON", {}, "native.JSON", JSONContent(json_obj={})),
+ ("json-nested-object", "native.JSON", {"a": {"b": [1, {"c": None}]}}, "native.JSON", JSONContent(json_obj={"a": {"b": [1, {"c": None}]}})),
+ ("json-obj-key-taken-literally", "native.JSON", {"json_obj": {"a": 1}}, "native.JSON", JSONContent(json_obj={"json_obj": {"a": 1}})),
+ # A concept refining JSON is built through its own class.
+ ("json-refining", "shaper_test.Payload", {"order_id": 7}, "shaper_test.Payload", Payload(json_obj={"order_id": 7})),
+ # TOML temporal literals (inputs files only).
+ ("anything-toml-date", "native.Anything", datetime.date(2026, 7, 7), "native.Anything", DateContent(date=datetime.date(2026, 7, 7))),
+ (
+ "anything-toml-datetime",
+ "native.Anything",
+ datetime.datetime(2026, 7, 7, 15, 40),
+ "native.Anything",
+ DateContent(date=datetime.date(2026, 7, 7), time=datetime.time(15, 40)),
+ ),
+ ("anything-toml-time", "native.Anything", datetime.time(15, 40), "native.Anything", TimeContent(time=datetime.time(15, 40))),
]
diff --git a/tests/unit/pipelex/core/pipes/test_stuff_spec.py b/tests/unit/pipelex/core/pipes/test_stuff_spec.py
index 65186bedf..5024b23fc 100644
--- a/tests/unit/pipelex/core/pipes/test_stuff_spec.py
+++ b/tests/unit/pipelex/core/pipes/test_stuff_spec.py
@@ -148,19 +148,19 @@ class _RefusingConceptProvider(ConceptProviderAbstract):
class TestStuffSpecStructurelessRender:
"""`native.Anything` renders without resolving a structure class.
- SCHEMA publishes the permissive schema — no constraint keywords, only the concept's identity
- annotations (`title` = concept ref, `description` = authored description); JSON renders the
- empty mapping. Multiplicity wraps exactly as for class-backed concepts.
+ SCHEMA publishes the concept's identity annotations (`title` = concept ref, `description` =
+ authored description) and excludes only array and null; JSON renders the empty mapping.
+ Multiplicity wraps exactly as for class-backed concepts, so every item carries the exclusion.
"""
- def test_schema_single_is_annotated_permissive(self):
+ def test_schema_single_excludes_array_and_null(self):
concept = ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.ANYTHING)
stuff_spec = StuffSpec(concept=concept)
result = stuff_spec.render_stuff_spec(concept_provider=_RefusingConceptProvider(), output_format=ConceptRepresentationFormat.SCHEMA)
assert result["concept"] == "native.Anything"
- assert result["content"] == {"title": "native.Anything", "description": concept.description}
+ assert result["content"] == {"title": "native.Anything", "description": concept.description, "not": {"type": ["array", "null"]}}
def test_schema_variable_list_wraps_in_unbounded_array(self):
concept = ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.ANYTHING)
@@ -170,7 +170,7 @@ class TestStuffSpecStructurelessRender:
assert result["content"] == {
"type": "array",
- "items": {"title": "native.Anything", "description": concept.description},
+ "items": {"title": "native.Anything", "description": concept.description, "not": {"type": ["array", "null"]}},
}
def test_schema_fixed_count_bounds_the_array(self):
@@ -181,7 +181,7 @@ class TestStuffSpecStructurelessRender:
assert result["content"] == {
"type": "array",
- "items": {"title": "native.Anything", "description": concept.description},
+ "items": {"title": "native.Anything", "description": concept.description, "not": {"type": ["array", "null"]}},
"minItems": 3,
"maxItems": 3,
}
diff --git a/tests/unit/pipelex/core/stuffs/number_content/test_number_content_validation.py b/tests/unit/pipelex/core/stuffs/number_content/test_number_content_validation.py
new file mode 100644
index 000000000..f388e235a
--- /dev/null
+++ b/tests/unit/pipelex/core/stuffs/number_content/test_number_content_validation.py
@@ -0,0 +1,16 @@
+import pytest
+from pydantic import ValidationError
+
+from pipelex.core.stuffs.number_content import NumberContent
+
+
+class TestNumberContentValidation:
+ @pytest.mark.parametrize("number", [0, -3, 4.2, 1e308])
+ def test_a_finite_number_is_kept(self, number: float) -> None:
+ assert NumberContent(number=number).number == number
+
+ @pytest.mark.parametrize("non_finite", [float("nan"), float("inf"), float("-inf")])
+ def test_a_non_finite_number_is_refused(self, non_finite: float) -> None:
+ """NaN and the infinities are not JSON numbers: serialization would turn them into null."""
+ with pytest.raises(ValidationError, match="number must be finite"):
+ NumberContent(number=non_finite)
diff --git a/tests/unit/pipelex/core/stuffs/test_json_content_validation.py b/tests/unit/pipelex/core/stuffs/test_json_content_validation.py
index b77f7cf88..395efc9d6 100644
--- a/tests/unit/pipelex/core/stuffs/test_json_content_validation.py
+++ b/tests/unit/pipelex/core/stuffs/test_json_content_validation.py
@@ -1,4 +1,5 @@
import pytest
+from pydantic import ValidationError
from pipelex.core.stuffs.json_content import JSONContent
@@ -26,30 +27,38 @@ class TestJSONContentValidation:
assert content.json_obj == json_obj
def test_invalid_json_with_non_serializable_object(self):
- """Test that non-JSON-serializable objects raise TypeError."""
+ """Test that non-JSON-serializable objects raise a ValidationError, never a raw TypeError."""
class NonSerializable:
pass
json_obj = {"object": NonSerializable()}
- with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ with pytest.raises(ValidationError, match="json_obj is not valid JSON"):
+ JSONContent(json_obj=json_obj)
+
+ @pytest.mark.parametrize("non_finite", [float("nan"), float("inf"), float("-inf")])
+ def test_invalid_json_with_a_nested_non_finite_number(self, non_finite: float):
+ """NaN and the infinities are not JSON, at any depth: serialization would turn them into null."""
+ json_obj = {"outer": {"inner": [1, non_finite]}}
+
+ with pytest.raises(ValidationError, match="json_obj is not valid JSON"):
JSONContent(json_obj=json_obj)
def test_invalid_json_with_non_serializable_function(self):
- """Test that functions in JSON object raise TypeError."""
+ """Test that functions in JSON object raise a ValidationError, never a raw TypeError."""
def some_function():
pass
json_obj = {"func": some_function}
- with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ with pytest.raises(ValidationError, match="json_obj is not valid JSON"):
JSONContent(json_obj=json_obj)
def test_invalid_json_with_set(self):
- """Test that sets in JSON object raise TypeError."""
+ """Test that sets in JSON object raise a ValidationError, never a raw TypeError."""
json_obj = {"data": {1, 2, 3}}
- with pytest.raises(TypeError, match="json_obj is not valid JSON"):
+ with pytest.raises(ValidationError, match="json_obj is not valid JSON"):
JSONContent(json_obj=json_obj)
diff --git a/tests/unit/pipelex/libraries/test_concept_library_compatibility.py b/tests/unit/pipelex/libraries/test_concept_library_compatibility.py
index 9584ee061..ec7f8da25 100644
--- a/tests/unit/pipelex/libraries/test_concept_library_compatibility.py
+++ b/tests/unit/pipelex/libraries/test_concept_library_compatibility.py
@@ -100,21 +100,28 @@ class TestConceptLibraryCompatibility:
assert library.is_compatible(tested_concept=one, wanted_concept=other) is False
- def test_the_structureless_native_concept_is_answered_not_raised(self):
- """`native.Anything` declares no content class, so there is no structural check to attempt.
-
- This is the one case where "no class" is a property of the concept rather than a missing
- registration, and it must stay a plain `False` — the loud raise is for names that *should*
- have resolved.
+ @pytest.mark.parametrize("strict", [False, True])
+ def test_every_concept_satisfies_the_structureless_native_concept(self, strict: bool):
+ """`native.Anything` is the top of the lattice: every concept satisfies it, and it satisfies nothing narrower.
+
+ The declaration tier decides both directions, so no class is ever resolved: the user concept
+ below names a structure class that is never registered, and asking about it still answers
+ instead of raising `ConceptStructureClassNotFoundError`. The reverse direction stays a plain
+ `False` rather than a raise, because `Anything`'s missing class is a property of the concept,
+ not a missing registration.
"""
library = ConceptLibrary.make_empty_with_native_concepts()
anything = library.get_native_concept(native_concept=NativeConceptCode.ANYTHING)
text = library.get_native_concept(native_concept=NativeConceptCode.TEXT)
+ dynamic = library.get_native_concept(native_concept=NativeConceptCode.DYNAMIC)
+ user_concept = _make_concept(code="Ghost", domain_code="nowhere", structure_class_name="GhostContentThatIsNeverRegistered")
assert anything.declares_a_structure_class is False
assert text.declares_a_structure_class is True
- assert library.is_compatible(tested_concept=anything, wanted_concept=text) is False
- assert library.is_compatible(tested_concept=text, wanted_concept=anything) is False
+ for tested in (text, dynamic, user_concept, anything):
+ assert library.is_compatible(tested_concept=tested, wanted_concept=anything, strict=strict) is True, tested.concept_ref
+ assert library.is_compatible(tested_concept=anything, wanted_concept=text, strict=strict) is False
+ assert library.is_compatible(tested_concept=anything, wanted_concept=user_concept, strict=strict) is False
def test_get_structure_class_raises_on_an_unregistered_name(self):
library = ConceptLibrary.make_empty()
diff --git a/tests/unit/pipelex/pipe_machinery/rendering/test_input_renderer_light.py b/tests/unit/pipelex/pipe_machinery/rendering/test_input_renderer_light.py
index 8f826a3a3..e37ee27c3 100644
--- a/tests/unit/pipelex/pipe_machinery/rendering/test_input_renderer_light.py
+++ b/tests/unit/pipelex/pipe_machinery/rendering/test_input_renderer_light.py
@@ -83,6 +83,20 @@ class TestInputRendererLight:
entry = {"concept": "native.Anything", "content": {"whatever": "value"}}
assert _delighten_entry(entry, kind=InputKind.DYNAMIC) == entry
+ def test_json_unwraps_to_the_bare_object(self) -> None:
+ """A JSON input's ``{"json_obj": ...}`` content becomes the bare object the caller has."""
+ entry: dict[str, Any] = {"concept": "native.JSON", "content": {"json_obj": {}}}
+ assert _delighten_entry(entry, kind=InputKind.JSON) == {}
+
+ def test_json_multiple_unwraps_to_a_list_of_bare_objects(self) -> None:
+ entry: dict[str, Any] = {"concept": "native.JSON", "content": [{"json_obj": {"a": 1}}, {"json_obj": {}}]}
+ assert _delighten_entry(entry, kind=InputKind.JSON) == [{"a": 1}, {}]
+
+ def test_anything_keeps_the_whole_envelope(self) -> None:
+ """An `Anything` input keeps its envelope: the bare placeholder `{}` would read as "send an object"."""
+ entry: dict[str, Any] = {"concept": "native.Anything", "content": {}}
+ assert _delighten_entry(entry, kind=InputKind.ANYTHING) == entry
+
def test_scalar_with_extra_required_fields_falls_back_to_envelope(self) -> None:
"""A scalar whose content is not a single field can't be delightened losslessly — keep the envelope."""
entry = {"concept": "demo.Weird", "content": {"text": "t", "extra": "x"}}
diff --git a/tests/unit/pipelex/pipe_run/test_delivery_executor.py b/tests/unit/pipelex/pipe_run/test_delivery_executor.py
index d21d78845..529fbe812 100644
--- a/tests/unit/pipelex/pipe_run/test_delivery_executor.py
+++ b/tests/unit/pipelex/pipe_run/test_delivery_executor.py
@@ -12,6 +12,8 @@ from pipelex.cogt.llm.llm_report import LLMTokensUsage
from pipelex.cogt.usage.cost_category import CostCategory
from pipelex.cogt.usage.token_category import TokenCategory
from pipelex.core.concepts.concept import Concept
+from pipelex.core.concepts.concept_factory import ConceptFactory
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
from pipelex.core.memory.absence import AbsenceKind, AbsenceRecord
from pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundError
from pipelex.core.memory.working_memory import WorkingMemory
@@ -21,6 +23,8 @@ from pipelex.core.pipes.pipe_io_artifacts import (
PIPE_IO_CONTRACTS_FILE_NAME,
render_pipe_io_artifact_files,
)
+from pipelex.core.stuffs.list_content import ListContent
+from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.stuff import Stuff
from pipelex.core.stuffs.text_content import TextContent
from pipelex.graph.graphspec import GraphSpec, PipelineRef
@@ -487,6 +491,27 @@ class TestDeliveryExecutor:
assert isinstance(result.content, TextContent)
assert result.content.text == "Hello!"
+ @pytest.mark.parametrize("anything_is_a_list", [False, True])
+ async def test_try_local_hydrate_stuff_reads_an_anything_content_by_its_own_markers(self, anything_is_a_list: bool) -> None:
+ """`native.Anything` names no class to look up, so the delivery hydrates it from the content's own
+ markers rather than falling back to a raw render that would show them.
+ """
+ working_memory = WorkingMemory()
+ content = ListContent(items=[TextContent(text="a"), NumberContent(number=1)]) if anything_is_a_list else TextContent(text="Hello!")
+ working_memory.root["main_stuff"] = Stuff(
+ stuff_code="test",
+ stuff_name="main_stuff",
+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.ANYTHING),
+ content=content,
+ )
+ stuff_raw = json.loads(json.dumps(working_memory.dump_for_transport()))["root"]["main_stuff"]
+
+ result = DeliveryExecutor.try_local_hydrate_stuff(stuff_raw)
+
+ assert result is not None
+ assert result.concept.concept_ref == "native.Anything"
+ assert result.content == content
+
async def test_try_local_hydrate_stuff_returns_none_for_unknown_concept(self, mocker: MockerFixture) -> None:
"""A dynamic concept is unknown to a crate-free delivery worker: the ref resolves to nothing, the raw render takes over."""
from pipelex import log as pipelex_log # ruff: ignore[import-outside-top-level]
diff --git a/tests/unit/pipelex/runtime_bridge/primitives/test_hydration.py b/tests/unit/pipelex/runtime_bridge/primitives/test_hydration.py
index 5a1cc7c9f..ea63fc806 100644
--- a/tests/unit/pipelex/runtime_bridge/primitives/test_hydration.py
+++ b/tests/unit/pipelex/runtime_bridge/primitives/test_hydration.py
@@ -6,15 +6,21 @@ from typing import Any, cast
import pytest
from pipelex.core.concepts.concept import Concept
+from pipelex.core.concepts.concept_factory import ConceptFactory
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
from pipelex.core.domains.domain import SpecialDomain
from pipelex.core.memory.absence import AbsenceKind, AbsenceRecord
from pipelex.core.memory.working_memory import WorkingMemory
from pipelex.core.pipes.pipe_output import PipeOutput
+from pipelex.core.stuffs.composite_content import CompositeContent
from pipelex.core.stuffs.date_content import DateContent
+from pipelex.core.stuffs.json_content import JSONContent
from pipelex.core.stuffs.list_content import ListContent
from pipelex.core.stuffs.number_content import NumberContent
from pipelex.core.stuffs.stuff import Stuff
+from pipelex.core.stuffs.stuff_content import StuffContent
from pipelex.core.stuffs.text_content import TextContent
+from pipelex.core.stuffs.time_content import TimeContent
from pipelex.core.stuffs.yes_no_content import YesNoContent
from pipelex.interpreter_hub import (
clear_current_library,
@@ -90,6 +96,10 @@ class TestHydrateWorkingMemory:
registry.register_class(YesNoContent)
if not registry.has_class(name="DateContent"):
registry.register_class(DateContent)
+ if not registry.has_class(name="TimeContent"):
+ registry.register_class(TimeContent)
+ if not registry.has_class(name="JSONContent"):
+ registry.register_class(JSONContent)
def test_hydrate_with_native_text(self) -> None:
"""A raw dict containing TextContent stuff hydrates to typed TextContent."""
@@ -281,6 +291,81 @@ class TestHydrateWorkingMemory:
assert list_content.items[1].text == "red"
assert list_content.items[2].text == "green"
+ @pytest.mark.parametrize(
+ "content",
+ [
+ TextContent(text="hi"),
+ NumberContent(number=3),
+ YesNoContent(yes_no=True),
+ JSONContent(json_obj={"a": 1}),
+ DateContent(date=datetime.date(2026, 9, 27)),
+ TimeContent(time=datetime.time(12, 30)),
+ ],
+ )
+ def test_a_single_anything_content_round_trips_by_its_own_class(self, content: StuffContent) -> None:
+ """`native.Anything` names no content class, so a single content carries its own class markers
+ across the transport boundary and comes back as the same class, under the same concept.
+ """
+ working_memory = WorkingMemory()
+ working_memory.root["payload"] = Stuff(
+ stuff_code="test",
+ stuff_name="payload",
+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.ANYTHING),
+ content=content,
+ )
+
+ raw = working_memory.dump_for_transport()
+ assert raw["root"]["payload"]["content"]["__pipelex_class__"] == type(content).__name__
+
+ hydrated = hydrate_working_memory(raw)
+
+ stuff = hydrated.root["payload"]
+ assert stuff.concept.concept_ref == "native.Anything"
+ assert stuff.content == content
+
+ @pytest.mark.parametrize("anything_is_a_list", [False, True])
+ def test_a_composite_under_anything_round_trips_with_typed_components(self, anything_is_a_list: bool) -> None:
+ """A composite carried by its own markers rebuilds its components at every depth, a nested
+ composite and a list of composites included, instead of leaving marker-bearing dicts.
+ """
+ inner = CompositeContent.model_validate({"note": TextContent(text="inner")})
+ composite = CompositeContent.model_validate(
+ {
+ "title": TextContent(text="hi"),
+ "nested": inner,
+ "many": ListContent(items=[inner, CompositeContent.model_validate({"count": NumberContent(number=2)})]),
+ }
+ )
+ content: StuffContent = ListContent(items=[composite]) if anything_is_a_list else composite
+ working_memory = WorkingMemory()
+ working_memory.root["payload"] = Stuff(
+ stuff_code="test",
+ stuff_name="payload",
+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.ANYTHING),
+ content=content,
+ )
+
+ raw = json.loads(json.dumps(working_memory.dump_for_transport()))
+ hydrated = hydrate_working_memory(raw)
+
+ hydrated_content = hydrated.root["payload"].content
+ if anything_is_a_list:
+ assert isinstance(hydrated_content, ListContent)
+ hydrated_composite = cast("ListContent[StuffContent]", hydrated_content).items[0]
+ else:
+ hydrated_composite = hydrated_content
+ assert isinstance(hydrated_composite, CompositeContent)
+ components = hydrated_composite.components
+ assert components["title"] == TextContent(text="hi")
+ assert isinstance(components["nested"], CompositeContent)
+ assert components["nested"].components == {"note": TextContent(text="inner")}
+ many = components["many"]
+ assert isinstance(many, ListContent)
+ many_items = cast("ListContent[StuffContent]", many).items
+ assert all(isinstance(item, CompositeContent) for item in many_items)
+ assert cast("CompositeContent", many_items[1]).components == {"count": NumberContent(number=2)}
+ assert "__pipelex_class__" not in json.dumps(hydrated.smart_dump(), default=str)
+
def test_dump_for_transport_list_items_carry_pipelex_markers_only(self) -> None:
"""dump_for_transport must emit pipelex-private type markers, never kajson's __class__/__module__.
diff --git a/wip/anything-slot/design.md b/wip/anything-slot/design.md
new file mode 100644
index 000000000..9a87f4a3b
--- /dev/null
+++ b/wip/anything-slot/design.md
@@ -0,0 +1,244 @@
+---
+status: landed
+item: L-260902-10eb56
+---
+
+# What an `Anything` or `JSON` input slot takes, and how the rest of the shaper's fallback refuses
+
+`native.Anything` is the concept the MTHDS standard defines as the untyped vehicle: structureless by design, "accepts any type". Its published input contract already says so — a permissive JSON Schema and the fill-in template `{"concept": "native.Anything", "content": {}}` — but the input shaper does not honour it. This document verifies the bug, rules on what an `Anything` slot takes and what stuff it produces, and rules jointly on the two sibling items the ledger asked to have decided together.
+
+The same fallback path also breaks `native.JSON` slots, and it refuses everything else it cannot read without naming the slot, which a later report ran into: "one input was a list of plain JSON objects … most likely an Anything or dynamic slot". So the design also gives `JSON` a handler of its own whose compact template is the bare object (R7), and makes the fallback's remaining refusals typed input errors that name the input and its declared concept (R8). It rules on an envelope-shaped item inside an `Anything[]` or `JSON[]` list (R10), and on how the docs teach the choice among the untyped concepts (R11). And because a value that goes in has to come back out, it rules on the wire form of an `Anything` value on the output side too (R9), which is built under its own items rather than here. The build is in `plan.md` beside it.
+
+## Verification
+
+The bug is confirmed on `dev` at `be796a0d8`, and it is wider than filed. Measured through `pipelex.kernel.memory_ops.shape_inputs`, the entry point an entry-pipe run uses, with a `PipeCompose` declaring `inputs = { anything_in = "Anything" }` and a second declaring `inputs = { items = "Anything[]" }`:
+
+```
+== carry (anything_in)
+ bare {} REFUSED StuffFactoryError: ... does not have a 'concept' key.
+ bare string OK -> concept=native.Text content=TextContent
+ bare number REFUSED StuffFactoryError: Unexpected type for stuff_content_or_data: <class 'int'>
+ bare float REFUSED StuffFactoryError: Unexpected type for stuff_content_or_data: <class 'float'>
+ bare bool REFUSED StuffFactoryError: Unexpected type for stuff_content_or_data: <class 'bool'>
+ bare list REFUSED StuffFactoryError: Cannot create Stuff from list of <class 'int'>
+ bare dict REFUSED StuffFactoryError: ... does not have a 'concept' key.
+ envelope {} REFUSED StuffFactoryError: ... 'Anything' is not compatible with a dict content
+ envelope str REFUSED StuffFactoryError: ... 'Anything' is not compatible with native concept 'native.Text', ...
+ envelope num REFUSED StuffFactoryError: Unexpected type for content value: <class 'int'>
+ envelope list REFUSED StuffFactoryError: Cannot create Stuff from list of <class 'int'> in content
+ envelope native.Text REFUSED ExplicitConceptIncompatibleError: ... declares concept 'native.Anything', but you provided a value typed as 'native.Text'
+ envelope native.JSON REFUSED ExplicitConceptIncompatibleError: ... typed as 'native.JSON' ...
+ envelope Question REFUSED ExplicitConceptIncompatibleError: ... typed as 'anything_probe.Question' ...
+== carry_list (items)
+ bare [{}] REFUSED StuffFactoryError: Cannot create Stuff from list of <class 'dict'>
+ bare [str] OK -> concept=native.Text content=ListContent
+ bare [1,2] REFUSED StuffFactoryError: Cannot create Stuff from list of <class 'int'>
+ bare [] REFUSED StuffFactoryError: Cannot create Stuff 'items' from empty list
+ envelope [{}] REFUSED ValidationError: 1 validation error for TextContent (raw pydantic, untyped)
+```
+
+Three things the item did not record:
+
+- **A typed envelope is refused too.** `{"concept": "Text", "content": "hi"}`, a `native.JSON` envelope and a user concept are all refused with `ExplicitConceptIncompatibleError`. The cause is `ConceptLibrary.is_compatible(tested=X, wanted=native.Anything)`, which answers `False` for every `X` but `Anything` itself: the declaration tier (`Concept.are_compatible_by_declaration`, `pipelex/core/concepts/concept.py`) has no rule for it, and the class tier bails out because `Anything` declares no class. So the one spelling that names its type explicitly — D6's escape hatch — cannot reach an `Anything` slot at all.
+- **The same compatibility gap refuses a valid bundle at validation time.** A `PipeSequence` declaring `output = "Anything"` over a last step producing `Text` fails to validate: `PipeSequence concept mismatch: the output concept 'native.Text' of the last step 'echo' of sequence pipe 'seq' is not compatible with the output concept 'native.Anything' of the sequence.` (`pipelex/pipe_controllers/sequence/pipe_sequence.py`, the `is_compatible` check in its output validation).
+- **`Anything[]` ignores its multiplicity.** The `DYNAMIC` arm returns before `_shape_with_multiplicity`, so a legal empty list is refused, a fixed count is never checked and a single value is never wrapped — Gap B of `wip/inputs/input-shaper-multiplicity-gaps.md`, still open for both `Dynamic` and `Anything`. The `[{}]` envelope escapes as a raw pydantic `ValidationError`, because Case 2.6 of the bottom-up factory falls back to `TextContent` for an item class it cannot resolve.
+
+The root cause is the one the item names: `resolve_input_kind` sends `Anything` down the `DYNAMIC` arm, which hands the raw value to the bottom-up `StuffFactory`, and that factory infers a concept from the value's shape without consulting the declared one. It has no arm for a number, a boolean, a bare object or a list of non-strings, and its envelope arm looks up `AnythingContent` in the class registry and finds nothing.
+
+**The list-of-objects report, reproduced.** The report pointed at the `DYNAMIC` call in `_shape_one` (`input_shaper.py`, line 188 on `dev` at `d93a24767`) and the bottom-up factory's `Cannot create Stuff from list of <class 'dict'>` (`stuff_factory.py`, line 454), without naming the slot. That is because the refusal names neither the input nor its declared concept. Sending `[{"a": 1}, {"b": 2}]` to every slot kind that reaches the fallback gives the same error at eleven of them: `Anything`, `Anything[]`, `Dynamic`, `Dynamic[]`, `JSON`, `JSON[]`, `Composite[]`, `Html[]`, `TextAndImages[]`, `SearchResult[]` and `Page[]`. A user concept with a structure, `Record[]`, takes the same list. `StuffFactoryError` declares no error domain, so the refusal is not even classified as the caller's input fault.
+
+**A `JSON` slot is broken in both directions.** Measured on the same `dev`:
+
+```
+JSON hi OK concept=native.Text content=TextContent(text='hi')
+JSON ['a', 'b'] OK concept=native.Text content=ListContent(items=[TextContent(text='a'), TextContent(text='b')])
+JSON {'a': 1} REFUSED StuffFactoryError: Trying to create a Stuff 'x' from a dict ... does not have a 'concept' key.
+JSON {'json_obj': {'a': 1}} REFUSED StuffFactoryError: (same)
+JSON 3 REFUSED StuffFactoryError: Unexpected type for stuff_content_or_data: <class 'int'>
+JSON[] hi OK concept=native.Text content=TextContent(text='hi') (not even wrapped into a list)
+```
+
+It refuses every object — the one thing a `JSON` slot is for — and quietly accepts a string as a `native.Text` stuff sitting in a slot the method declared `JSON`. Only the envelope, `{"concept": "native.JSON", "content": {"json_obj": {…}}}`, works today.
+
+**What the runtime already does with an `Anything` stuff.** No arm has to be invented downstream. `PipeBatch` stamps the slot's *declared* concept onto the stuffs it builds — each item stuff takes the input spec's concept and each aggregate takes the batch's output concept (`pipelex/pipe_controllers/batch/pipe_batch.py`, the two `StuffFactory.make_stuff` calls) — so a batch over `Anything[]` already produces stuffs whose concept is `native.Anything` and whose contents are concrete. `PipeParallel` guards `declares_a_structure_class` on a branch stuff's concept for the same reason. Measured by handing the runner a pre-built working memory: a `native.Anything` stuff holding a `JSONContent`, a `TextContent` or a `NumberContent` renders through `$anything_in` as `{"a": 1}`, `hi` and `4.2`, a mixed `ListContent` renders item by item, and every run result serializes.
+
+## Rulings
+
+### R1 — The slot keeps its declared concept; the content is the value's natural content
+
+**A bare value at an `Anything` slot becomes a stuff whose concept is `native.Anything` and whose content is the native content its JSON type names.** Nothing is inferred beyond the JSON type, and nothing is guessed from the value's text.
+
+| Value | Content |
+| --- | --- |
+| string | `TextContent` |
+| number (a boolean is never a number) | `NumberContent` |
+| boolean | `YesNoContent` |
+| object | `JSONContent`, the object as `json_obj` — so the published template `{}` shapes into `JSONContent(json_obj={})` |
+| TOML date or datetime literal (inputs files only) | `DateContent` |
+| TOML time literal (inputs files only) | `TimeContent` |
+| an already-built `StuffContent` object (Python callers) | the explicit arm, as today: its concept is inferred from its class and kept, per R2 and D6 |
+| array | refused at a single slot (R3), shaped element-wise at a plural one |
+| null | refused (R3) |
+| anything else a Python caller hands in | refused as not a JSON value |
+
+A string that looks like a URL is still text. The file-ish reading of D3 belongs to slots that declare `Image` or `Document`, and an `Anything` slot declares nothing of the kind.
+
+Why the declared concept rather than the natural one. Every top-down arm of the shaper already stamps the declared concept (`StuffFactory.make_stuff(concept=declared_concept, …)` at the end of `_shape_one`), and `PipeBatch` does the same for `Anything` today. A stuff has exactly one concept, so inferring `native.Text` or `native.Number` breaks on the first heterogeneous `Anything[]` list, while `native.Anything` over a mixed `ListContent` is exactly what a batch already produces. And the concept a stuff carries at an `Anything` slot should say what the method declared there, not what the shaper guessed: the content class already says what the value concretely is. That last point holds in memory only. On the wire the content class is invisible, which R9 answers.
+
+The invariant this relaxes is "the content is an instance of the concept's structure class". It becomes "…when the concept declares one", which is what `Concept.declares_a_structure_class` exists to say.
+
+### R2 — Every concept satisfies `native.Anything`
+
+**`Concept.are_compatible_by_declaration` answers `True` whenever the wanted concept is `native.Anything`**, right after its two dynamic short-circuits, keyed on `not concept_2.declares_a_structure_class`. The reverse stays `False`: an `Anything` value is not known to be a `Text`, and `strict=True` changes nothing, since the rule sits in the declaration tier.
+
+Consequences, all intended:
+
+- A typed envelope at an `Anything` slot is accepted and **keeps its explicit concept** — D6's "explicit wins when compatible", with `Anything` at the top of the lattice. `{"concept": "Image", "content": {"url": …}}` produces a `native.Image` stuff.
+- A `PipeSequence` whose output is `Anything` validates over any last step.
+- The rule matches the language reference ("Accepts any type") and what `pipelex` already does by special case in controller validation (`pipe_abstract.py`, the `DYNAMIC`/`ANYTHING` carve-outs) and in `PipeCondition`. The implementers' runtime guide in `mthds` narrows it to native concepts; that inconsistency is filed as L-260927-afaf62 for the standard's owner.
+
+The sites that ask `is_compatible` with a wanted concept of `Anything` are the shaper's two compatibility checks and `PipeSequence`'s output check; every other site asks about `Text`, `Html`, `Image`, `Document`, `YesNo`, `Date` or `Time`, which this rule does not touch.
+
+### R3 — Multiplicity is peeled for `Anything` like every typed kind; D2 and D9 hold
+
+`Anything` leaves the `DYNAMIC` short-circuit and takes the path the typed kinds take, `_shape_with_multiplicity`, with a new per-item arm. So:
+
+- `Anything[]` shapes element-wise, and **items may differ in JSON type**. `[]` is a legal empty list, and a single value is wrapped into a one-item list (D2).
+- `Anything[N]` checks the count.
+- An array at a single `Anything` slot is `ListWhereSingularError` (D2), and an item of a plural slot that is itself an array is refused as a wrong kind. A list of lists has no stuff to become.
+- A top-level null is `NullInputError` (D9), whether bare or as an envelope's content, and a null item is refused as a wrong kind.
+
+This closes Gap B of `input-shaper-multiplicity-gaps.md` for `Anything`. `Dynamic` keeps its bottom-up arm; nothing here rules on it.
+
+### R4 — The published schema says what R3 refuses: no array and no null at an element position *(decided with Louis, 2026-09-27)*
+
+**The permissive schema gains one constraint: `{"title": "native.Anything", "description": "…", "not": {"type": ["array", "null"]}}`.** `Anything[]` wraps it exactly as today, so its items exclude arrays and null too, and the standard's rule that a plural schema's items are "exactly what the same concept would carry at single" holds unchanged.
+
+The item asked to close the gap in the shaper rather than narrow the contract to a limitation, and R4 is the one place this design narrows. It is not a limitation of the `Anything` arm, though: D2 (a single slot never holds a list) and D9 (absence is an omitted key, never a null) refuse those two shapes at *every* slot, and every other slot's schema already excludes them — an object schema admits neither an array nor a null. The permissive schema is the one exception on the wire. The standard says a machine consumer validates a payload with `json_schema` and an ordinary validator (`mthds/docs/spec/pipe-io-contracts.md`, Non-Goals), and `mthds-form` does exactly that with ajv, so leaving the schema permissive keeps a gap a client meets as a refused run after its own validation passed.
+
+### R5 — The envelope spellings
+
+- **`{"concept": "native.Anything", "content": v}` at an `Anything` slot is the bare value `v`**, shaped by R1 and R3. This is the spelling both corpus shapes publish, so it is the one the round-trip gate measures.
+- **A typed envelope at an `Anything` slot** builds bottom-up as today and keeps its concept (R2).
+- **An envelope naming `native.Anything` at any other slot** is refused with `ExplicitConceptIncompatibleError` before anything is built: an `Anything` is not known to satisfy anything narrower. Today that case fails inside the factory with an untyped "not compatible with a dict content".
+
+The shaper recognizes the first case by resolving the envelope's concept through the provider it already holds, with the pipe's search scope, and by asking whether that concept declares a structure class. It does not ask the factory, which has no multiplicity awareness.
+
+D6's collision rule is unchanged and matters more here than anywhere: an object whose keys are exactly `concept` and `content` is always read as an envelope. So a raw `Anything` value of that one shape has to be sent inside an `Anything` envelope, `{"concept": "native.Anything", "content": {"concept": …, "content": …}}`, which R5 then shapes as the bare object it holds. The content of an `Anything` envelope is raw data at every depth, the items of a list included, which is what R10 relies on.
+
+### R6 — There is never an `AnythingContent` class; the joint ruling with the sibling items
+
+The item asked for L-260902-9546ef and L-260902-db6d1e to be ruled on together with this one, because introducing an `AnythingContent` class would change what they are. **This design introduces none, and rules that none will be introduced.** A class would have to give the untyped vehicle a shape — a `value` field, at least — and the pinned native definition says `Anything` is structureless and that a consumer must "never invent a shape" (`mthds/docs/spec/native-concepts.md`). It would also flip `declares_a_structure_class` for `Anything`, and with it every structureless arm L-260831-8f7c8c landed: the published schema, the fill-in template and the input-form descriptor's `unknown` node.
+
+So the two siblings keep the fix directions they already state, now settled rather than provisional:
+
+- **L-260902-9546ef** (and L-260926-f7bb28, the same site reached with `Anything[]`, now linked to it): `pipe_llm.py` resolves the output class straight from the registry. The fix routes the lookup through the guard and decides what a `PipeLLM` produces for an `Anything` output; whatever it decides, the refusal it raises is a domained `PipelexError`, never an unregistered class.
+- **L-260902-db6d1e**: `pipelex build runner` refuses an `Anything` input cleanly, since PYTHON has no class to instantiate, and `refines = "Anything"` gets the standalone field-less `StructuredContent` the cross-package arm already builds, which is what codegen already emits.
+
+Neither is widened into this change. They share a principle with it and no code.
+
+### R7 — A `JSON` slot takes a JSON object, top-down
+
+**`native.JSON`, and every concept refining it, gets its own shaper handler instead of the fallback.** `resolve_input_kind` recognizes it by strict compatibility with `native.JSON`, as it does the other matrix natives, so a refining concept is built through its own class.
+
+- **A bare object is the JSON object itself**, stored as `json_obj`: `{"a": 1}` becomes `JSONContent(json_obj={"a": 1})`. This is the reading a caller means, and the one the report needed.
+- **Every bare object is read literally, `{"json_obj": {…}}` included.** That object becomes `JSONContent(json_obj={"json_obj": {…}})`, just as a bare `{"text": "hi"}` at a `Text` slot is not read as a text content. The `json_obj` mapping is the content form, and the content form travels inside the envelope, for `JSON` as for every native. There is no collision rule: one looked necessary only because the compact template taught callers the wrapped form, and the next point changes the template instead.
+- **The compact template shows the bare object.** The engine's light template unwraps `json_obj` the way it unwraps `text` for `Text` and `number` for `Number`, and the reference projection and both mirrors do the same, so `JSON` leaves `OUT_OF_MATRIX_NATIVES`. A developer reading the template for a `JSON` slot sees the object they have, not a Python field name inside an envelope. The corpus's `json_in` compact bytes change in all three repos in the regeneration that already retires the two `EXPECTED_UNSHAPEABLE` entries.
+- **Anything else is refused as a wrong kind**, naming "a JSON object": a string, a number, a boolean. `JSONContent` holds an object only, which the pinned native definition fixes (`json_obj`, a `dict`), so a JSON array is not a `JSON` value either. Whether the standard should widen that was question 4 (L-260927-a8ec06), decided: it stays an object, and this design says "a JSON object" in every doc and error it touches.
+- **Multiplicity is peeled like every typed kind.** `JSON[]` shapes each object in turn, a single object is wrapped, `[]` is legal, and an array at a single `JSON` slot is `ListWhereSingularError`, whose detail already names `JSON[]` as the declaration to change.
+- **The envelope is unchanged**: its content is still `JSONContent`'s field mapping, `{"json_obj": {…}}`, built bottom-up and compatibility-checked as today. The published `json_schema` describes that content form, as it does for every native (`Text`'s is `{"text": …}`), so it does not change either, and neither does codegen's `JSON` type.
+
+The `Anything` handler's object row (R1) and this handler build the same content, so they share the code that turns an object into a `JSONContent`.
+
+### R8 — The fallback's remaining refusals are typed input errors that name the slot
+
+After R1 and R7, the bottom-up fallback still serves `Dynamic`, `Composite`, `Html`, `Page`, `TextAndImages`, `SearchResult`, and any user concept whose content class is not a structured one, such as a refinement of `Html`. It keeps reading a bare value by its own shape; what changes is how it refuses one. **A `StuffFactoryError` raised on that path is re-raised as a `StructureValidationError`** — an `InputShapingError`, `input`-domained and caller-facing — carrying the input name, the declared concept, the expected shape rendered from the signature, and a reason the shaper writes itself: what the value is, and that a slot of this concept reads a bare value by its own shape and has no reading for this one. The factory's own message, with its `typing.Union[…]` spelling of the accepted types, stays on the chain as the cause and out of the text a caller reads.
+
+**The refusal's user action names the fix on the method author's side**: declare the input as `JSON` or `JSON[]` when the value is plain JSON data, or as a concept with a structure. The person who sent a list of plain JSON objects to a `Dynamic[]` slot is usually also the person who declared it, and the declaration is what should change. This mirrors `ListWhereSingularError`, whose detail already says "or declare it as a list ('X[]') in the method". The refusal does not suggest an envelope. An envelope helps only a caller who knows a concept both compatible with the slot and able to hold the value, and at a `Dynamic` slot the obvious one, `Dynamic` itself, silently drops an object's content (L-260927-bea35e).
+
+`StructureValidationError` already has the right message form ("Input 'x' could not be built as 'native.Dynamic': …") and a page of its own, so no new error class and no change to the error identity snapshot are needed. Its `make` hard-codes the user action's detail, so it gains a way to pass this one; its docstring widens to cover this case. The explicit arm's untyped escapes are not part of R8: they are L-260831-1e1a71, which already owns them.
+
+### R9 — On the output side, an `Anything` stuff's content is its plain JSON value *(built under L-260927-da1b09 and L-260927-223013)*
+
+R1 keeps the declared concept and relies on the content class to say what the value is. That holds in memory, but a stuff's wire form carries only `concept` and `content`, and the content is dumped as its class's fields. Measured by dumping a `PipeOutput` holding `native.Anything` stuffs:
+
+```
+string {"concept": "native.Anything", "content": {"text": "hi"}}
+object {"concept": "native.Anything", "content": {"json_obj": {"text": "hi"}}}
+number {"concept": "native.Anything", "content": {"number": 4.2}}
+list {"concept": "native.Anything", "content": {"items": [{"text": "a"}, {"number": 1}, {"json_obj": {"k": 1}}]}}
+```
+
+A consumer can decode that only by guessing Pipelex's content field names, which is exactly the shape-sniffing the projections refuse to do. And once R1 and R5 land, a value changes type between two methods: a bare `"hi"` comes back as `{"text": "hi"}`, and the standard's `--with-memory` chaining feeds that into the next method's `Anything` slot, where R5 reads it as the object `{"text": "hi"}`.
+
+**The public wire form of an `Anything` stuff's content is its plain JSON value**: a `TextContent` is its string, a `NumberContent` its number, a `YesNoContent` its boolean, a `JSONContent` its object, a `DateContent` or `TimeContent` its ISO string, a `ListContent` the array of its items' values. Any other content class, such as a Python caller's `ImageContent` inside an `Anything[]` list, keeps its content form. A date comes back as a string, the one lossy case, since JSON has no date type. This is what the standard already implies, since a stuff's content is "the value, shaped as the concept's structure dictates" and `Anything` has no structure, and L-260927-223013 asks `mthds` to say it outright. The internal serialization (kajson, Temporal payloads) keeps content classes, because the runtime must restore them exactly; only the public projections change.
+
+This is not built here. It changes the run result, the CLI's outputs and what the app and SDKs display, which is its own review, and it has its own test: a round trip through `--with-memory` that must return every R1 value unchanged. L-260927-da1b09 carries it, blocked by this item because its round trip needs R1 and R5.
+
+### R10 — An envelope-shaped item of a bare `Anything[]` or `JSON[]` list is refused
+
+D6's collision rule reads an object whose keys are exactly `concept` and `content` as an envelope, but only at the top of a slot (`InputShaper._is_explicit`). An item of a list reaches `_build_item_content`, which recognizes an already-built `StuffContent` object and nothing else. So under R1 and R7 as first written, `[{"concept": "Image", "content": {…}}, "caption"]` at `Anything[]` would have shaped its first item into a `JSONContent` holding the envelope, silently accepting one spelling with two meanings depending on where it sits.
+
+**Such an item is refused as a wrong kind**, and the message says that one envelope around the whole list is how to type a list. Every other list kind already refuses it: at `Text[]` it is not a string, and at a structured concept's list it fails the structure. Two escapes stay open, both reusing an existing rule. A list of values of one concept travels in one typed envelope around the whole list. A list whose items genuinely are raw objects keyed `concept` and `content` travels inside an `Anything` envelope, whose content is raw data at every depth (R5), or, for `JSON[]`, inside a `JSON` envelope, whose items are content forms.
+
+### R11 — The docs teach one choice among the untyped concepts, and lead with naming the JSON
+
+After this change, three natives mean "no declared structure", each with its own rules: `Anything`, `JSON` and `Dynamic`. The docs so far describe each in its own section, so an author, human or agent, gets no rule for choosing. They get one, in this order:
+
+1. **Data you already have as JSON objects: name it.** A concept that refines `JSON`, such as `concept.Order` with `refines = "JSON"` and a plain-language description, takes the object exactly as the developer has it, with no data model to rebuild (R7 builds it through its own class), while its name and description give an agent or a reader the meaning a bare `JSON` withholds. `tests/e2e/pipelex/pipes/pipe_operators/pipe_llm/pipe_llm_json_concept.mthds` already does it on the output side with `VectorIndex`. Fields come later, when validation is wanted, by turning it into a concept with a structure.
+2. **`JSON` or `JSON[]`** when the data has no name worth giving it. It is a JSON object; a list of them is `JSON[]`.
+3. **`Anything`** when the pipe is generic over its input — it passes a value along or renders it whatever it is. It is not the place to put JSON.
+4. **`Dynamic`** is not recommended for inputs until L-260927-bea35e rules on what its slot holds.
+
+This is the one place where the two aims of the language meet: the developer keeps their JSON as it is, and the method still says what that JSON is.
+
+## Rejected alternatives
+
+- **Infer the natural concept** (`native.Text` for a string, `native.JSON` for an object). It is what the bottom-up path does for a string today, and it has no answer for a heterogeneous `Anything[]`, since one stuff has one concept. It also discards the declaration for a guess, which is exactly what the item objected to.
+- **A real `AnythingContent` class.** Rejected under R6.
+- **Keep the `Anything` schema permissive and document the two refusals instead** (R4's alternative). It narrows nothing, but a client that validates with `json_schema`, as the standard tells it to, would still meet an array or a null refused only when the run starts.
+- **Accept an array at a single `Anything` slot as a `ListContent`.** A single slot holding a list is what D2 exists to prevent, and every controller reads multiplicity through `Stuff.is_list`, so the stuff would be plural wherever it went while its slot says single.
+- **Keep the `DYNAMIC` arm and teach the bottom-up factory about `Anything`.** The factory has no declared concept and no multiplicity to consult. That is the reason the top-down shaper exists.
+- **Treat `JSON` as a structured concept**, so a bare object is the content and must carry `json_obj`. It matches the contract to the letter, but it refuses a plain object, which is what every caller of a `JSON` slot sends and what the report sent.
+- **Keep the envelope in `JSON`'s compact template, and read a bare `{"json_obj": {…}}` as the content.** This was R7's first draft: it spared the corpus and both mirrors a projection change, and the collision rule kept a caller who copied the content out of the envelope from being wrapped twice. But it left every template a developer or an agent reads teaching a Python field name inside an envelope, while the shaper preferred the plain object, and it made one object shape mean two things at one slot. Fixing the template removes the reason for the rule.
+- **A new error class for the fallback's refusal.** It would add a wire `error_type` for a case `StructureValidationError` already describes, and consumers branch on `error_type`.
+- **Suggest an envelope in the fallback's refusal.** R8's first draft did. The advice is generic, the caller rarely knows which concept to name, and at a `Dynamic` slot the obvious one loses data.
+- **Read an envelope-shaped list item as a per-item envelope**, keeping its content. It would match what a Python caller's `StuffContent` item already does, but the item's concept would be dropped, since a list stuff carries one concept, and only `Anything[]` and `JSON[]` would read it while every other list kind refuses it. Per-item envelopes, if wanted, are a feature for every kind.
+- **Carry the content class on the wire beside an `Anything` value** (a type tag), instead of R9's plain value. A tag is a shape the runtime invents for a concept the standard says has none, and a consumer would still need Pipelex's class vocabulary to read it.
+
+## What deliberately does not change
+
+- **The input-form descriptor** still states `Anything` as `unknown` and `JSON` as an object with a `json_obj` field: the descriptor describes the content form, and the compact projection is what unwraps it.
+- **`Anything`'s compact template keeps its envelope**, in the engine's light template and in all three projections, so `InputKind.ANYTHING` joins the `DYNAMIC` arm of `_delighten_entry` in `pipelex/pipe_machinery/rendering/input_renderer.py` and `Anything` stays in `OUT_OF_MATRIX_NATIVES`. Its bare placeholder, `{}`, would read as "send an object", while the envelope names the concept that says any value goes. `JSON` is the one that changes (R7): its light template unwraps `json_obj`, and it leaves `OUT_OF_MATRIX_NATIVES` in `pipelex/cli/dev_cli/commands/projection_reference.py`, `mthds-js/src/protocol/inputs_template.ts` and `mthds-python/mthds/protocol/inputs_template.py` together, so the engine and the projections agree and no divergence class opens.
+- **The comment on `OUT_OF_MATRIX_NATIVES` goes stale in those three places.** It justifies keeping the envelope by saying an input shaper "cannot build" these natives top-down, which after R1 is no longer true of `Anything`. It should say instead that these are the open natives whose compact form keeps the envelope, because a bare value there either has no reading every runtime shares or, for `Anything`, would misstate what the slot takes.
+- **Codegen** still emits `z.unknown()` and `Any` for an `Anything` slot. With R4, that type is wider than the contract by the array and the null; it is a declared imprecision of a structureless concept, which is how codegen already treats all three of them. Its `JSON` type stays `{ json_obj: … }`, the content form, like `{ text: … }` for `Text`.
+- **Prompt attachment** stays a static decision on the declared concept, so an image handed to an `Anything` slot through a typed envelope renders as text in a `PipeLLM` prompt and is not attached. This is the same give-up `Dynamic` has, recorded on L-260901-45becb.
+- **`native.Dynamic`** keeps its bottom-up arm. Its own data-loss bug, found here, is filed separately (below).
+
+## Behaviour changes a caller can see
+
+- A bare string at an `Anything` slot now produces a `native.Anything` stuff holding a `TextContent`, not a `native.Text` stuff. The content, and therefore every rendering of it, is identical, but the working memory, the run output and the graph now report the concept the method declared. `tests/unit/pipelex/core/memory/input_shaper/test_scalar_arms.py` pins the old behaviour (`anything-str-bottom-up`) and changes with it. This goes in the changelog under *Changed*.
+- Every other JSON value, the published template and every typed envelope start being accepted.
+- At a `JSON` slot, a bare object and a list of objects start being accepted, and a bare string, which used to become a `native.Text` stuff in that slot, is now refused as a wrong kind. That refusal is the fix, not a regression, and it goes in the changelog under *Changed* because a caller could have been relying on it.
+- The compact inputs template for a `JSON` slot is now the bare object, in the engine (`pipelex codegen inputs`, the API's template) and in both projections.
+- An item of a bare `Anything[]` or `JSON[]` list that is shaped like an envelope is refused (R10).
+- At the remaining fallback slots, the refusal that used to be an unclassified `StuffFactoryError` is now a `StructureValidationError`: `input`-domained, naming the input and its concept, with a user action naming the declaration to change. A consumer branching on `error_type` sees a new value on this path.
+- Under R4, `PipeInputContract.json_schema` for an `Anything` slot gains the `not` clause, which the shared projection corpus captures, so the committed capture changes in `mthds-js` and `mthds-python` in the same regeneration that retires the two `EXPECTED_UNSHAPEABLE` entries.
+
+## Adjacent findings, filed
+
+- L-260927-bea35e (`pipelex`, bug): a `native.Dynamic` envelope silently drops its object content, because `DynamicContent` declares no fields and inherits `extra="ignore"`. Measured: `{"a": 1, "b": "x"}` shapes into `DynamicContent()`. It now also carries the list half of the report: a bare object or a list of objects at a `Dynamic` slot has no reading at all, which after R8 is a typed refusal rather than an accepted value.
+- L-260927-afaf62 (`mthds`, spec): the runtime guide's pseudo-code admits only native concepts into `Anything`.
+- L-260927-da1b09 (`pipelex`, bug) and L-260927-223013 (`mthds`, spec): R9, the plain-value wire form of an `Anything` stuff's content.
+- L-260927-a8ec06 (`mthds`, decision): question 4, decided and closed — `JSON` stays an object.
+- L-260927-702c56 (`pipelex`, feature): a `.json` or `.jsonl` file reference read into a `JSON[]` slot, the way D11 reads a CSV into a structured list.
+
+## Questions, all decided with Louis on 2026-09-27
+
+1. **R4** — narrow the published schema by D2 and D9, or leave it permissive and document the two refusals. *Decided:* narrow it.
+2. **R7's collision rule.** *Decided:* there is none. Every bare object is read literally, and `JSON`'s compact template becomes the bare object, so no caller learns the wrapped form.
+3. **The corpus pipe.** `scaffold_anything_slot` exists only to isolate a declared gap. *Decided:* fold `anything_in` back into `scaffold_open_natives`, the original intent of L-260902-543ad0, which removes one pipe's files from both mirrors and one entry from `conformance`'s corpus census. Keeping the separate pipe was equally correct and changed fewer files, but a pipe whose only justification is a closed gap would need a new one.
+4. **Should `JSON` hold any JSON value, not only an object?** A question for the standard, filed as L-260927-a8ec06. *Decided:* keep it an object. Widening would make a single `JSON` slot the one position that holds an array, against D2, and every array-shaped payload but a list of lists already has a home.
+5. **`Anything`'s compact template.** *Decided:* it keeps its envelope, because the bare placeholder `{}` would read as "send an object" (see "What deliberately does not change").
+6. **R10's escape.** *Decided:* the content of an `Anything` envelope is raw data at every depth, list items included, so a list of genuine `{concept, content}` objects travels inside one; the alternative, refusing the spelling everywhere and sending such data through a structured concept, was simpler but left a developer's JSON with no way in as it is.
+7. **`Dynamic` in R11.** *Decided:* the docs say `Dynamic` is not recommended for inputs until L-260927-bea35e rules on what its slot holds, rather than leaving it out of the rule while it loses data.
diff --git a/wip/anything-slot/plan.md b/wip/anything-slot/plan.md
new file mode 100644
index 000000000..81890478c
--- /dev/null
+++ b/wip/anything-slot/plan.md
@@ -0,0 +1,252 @@
+---
+status: landed
+item: L-260902-10eb56
+---
+
+# Plan: `Anything` and `JSON` slots take what they declare, and the fallback refuses by name
+
+Builds the rulings in `design.md` beside this file, except R9, which its own items carry. One `pipelex` pull request carries Phases 1 to 5, because the corpus generator's lapse rule fails the moment the shaper accepts the `Anything` template, so the fix and the retirement of its `EXPECTED_UNSHAPEABLE` entries cannot land apart. Phase 6 is the cross-repo half: the shared corpus re-committed in both mirrors together with their projections' `JSON` unwrap (R7), and `conformance`'s corpus census, all from the merged `dev`.
+
+Branch `fix/Anything-slot-shaping`, worktree `_pipelex--anything-slot-shaping`. Work test-first: each phase writes its failing tests before the code.
+
+## Phase 1 — every concept satisfies `native.Anything` (R2)
+
+1. In `Concept.are_compatible_by_declaration` (`pipelex/core/concepts/concept.py`), after the two dynamic short-circuits, return `True` when `not concept_2.declares_a_structure_class`. Update the docstring's list of what the declaration tier decides.
+2. Tests:
+ - `tests/unit/pipelex/libraries/test_concept_library_compatibility.py::test_the_structureless_native_concept_is_answered_not_raised` pins `is_compatible(text, anything) is False`; rewrite it to pin the new rule both ways — `Text`, a user concept and `Dynamic` satisfy `Anything`, with and without `strict`, while `Anything` still does not satisfy `Text` — and keep its point that nothing is resolved from the registry.
+ - A bundle-level test that a `PipeSequence` declaring `output = "Anything"` over a `Text`-producing last step validates. It fails today with `PipeSequence concept mismatch`. `tests/integration/pipelex/pipeline/test_protocol_validate.py` already holds the `Anything` input verdict test and is the natural home.
+3. Sweep the `is_compatible` callers once more for a site whose wanted concept can be `Anything` and which relied on `False`. The design found only the shaper's two checks and `PipeSequence`'s output check.
+
+## Phase 2 — the `ANYTHING` arm in the input shaper (R1, R3, R5)
+
+All in `pipelex/core/memory/input_shaper.py` unless named otherwise.
+
+1. Add `InputKind.ANYTHING`, `is_structured` `False`. Rewrite the `InputKind` docstring and the module docstring, which name `Anything` as a bottom-up fallback.
+2. `resolve_input_kind`: return `ANYTHING` for a concept that does not declare a structure class, right after the `Dynamic` check and before the ordered natives.
+3. `_shape_one`: `ANYTHING` joins the typed group, so it goes through `_shape_with_multiplicity` and the stuff is stamped with the declared concept.
+4. `_build_item_content`: an `ANYTHING` arm implementing the R1 table, checked in this order — boolean before number, since `bool` is an `int`; `datetime.time`; `datetime.date` (which covers `datetime`); string; object; then a refusal through `_wrong_kind` for a nested list, a null item, an item whose keys are exactly `concept` and `content` (R10, with an `expected_kind` saying that one envelope around the whole list is how to type it) or any non-JSON object, with an `expected_kind` that says what an `Anything` item may be. The R10 check applies to an item of a bare list only: it takes a flag that step 6 clears when the list arrived inside an `Anything` envelope, whose content is raw at every depth. Each accepted value goes through `_make_content` with the matching native concept from the provider, so the injected-provider rule holds and a build failure is a `StructureValidationError`. The object row goes through a helper that Phase 3's `JSON` arm reuses: it takes the object literally, `{"json_obj": {…}}` included.
+5. `_make_content` catches `ValidationError` and `StuffContentFactoryError` only, but `JSONContent`'s validator raises a bare `TypeError` for a Python dict holding a value that is not JSON (`JSONContent(json_obj={"a": object()})` → `TypeError: json_obj is not valid JSON`). Make that a typed refusal, preferably by fixing the validator to raise `ValueError` so pydantic reports it as a `ValidationError`; that covers the `Anything` object row, the `JSON` arm and the `JSON` envelope at once.
+6. `_shape_explicit` (R5): when the value is a `{"concept", "content"}` envelope, resolve its concept through `concept_provider.get_required_entry_concept(…, search_scope=…)` first. If that concept declares no structure class: at an `Anything` slot, shape `content` as a bare value with step 4's R10 flag cleared, since an `Anything` envelope's content is raw at every depth (a `None` content raises `NullInputError`); at any other slot, raise `ExplicitConceptIncompatibleError` before building. Every other explicit form keeps today's path, and the D6 compatibility check now passes for typed envelopes by Phase 1. When the envelope's concept does not resolve, catch the provider's not-found error and fall through to today's path, so the factory reports it exactly as it does now. Cover the nested-envelope escape of the design's R5 with a test: an `Anything` envelope whose content is itself an object keyed `concept` and `content` shapes into a `JSONContent` holding that object.
+7. `pipelex/pipe_machinery/rendering/input_renderer.py`: `InputKind.ANYTHING` joins the `DYNAMIC` arm of `_delighten_entry`, so the engine's light template keeps the envelope (see "What deliberately does not change" in the design).
+8. Tests, in `tests/unit/pipelex/core/memory/input_shaper/`:
+ - `test_scalar_arms.py`: `anything-str-bottom-up` pins the old `native.Text` result; replace it with one row per R1 value — string, integer, float, boolean, `{}`, a nested object, `{"json_obj": {…}}` taken literally, a TOML date, datetime and time — each asserting concept `native.Anything` and the exact content.
+ - `test_multiplicity.py`: `Anything[]` with a mixed list, `[]`, a single value auto-wrapped, and `Anything[2]` with a wrong count; a list at a single `Anything` slot raising `ListWhereSingularError`; `[{"concept": "Image", "content": {…}}, "caption"]` raising `WrongScalarKindError` whose message says to wrap the whole list (R10).
+ - `test_explicit_forms.py`: the `native.Anything` envelope in both spellings of the concept (`Anything`, `native.Anything`) over `{}`, a string, a number and a list at a plural slot; typed envelopes (`Text`, `JSON`, a user concept, `Image`) at an `Anything` slot keeping their concept; an `Anything` envelope at a `Text` slot raising `ExplicitConceptIncompatibleError`; an `Anything` envelope around a list whose item is keyed `concept` and `content`, at `Anything[]`, shaping that item into a `JSONContent` holding it (R10's escape).
+ - `test_errors.py`: null envelope content, a null item, a nested list item, a non-JSON Python object, and the non-serializable dict of step 5 — each a typed `InputShapingError`, never a raw exception.
+ - `test_provider_injection.py`: `resolve_input_kind` answers `ANYTHING` without resolving any class, on the stub provider that fails on class resolution.
+ - `tests/unit/pipelex/pipe_machinery/rendering/test_input_renderer_light.py`: the light template for an `Anything` slot keeps the envelope.
+ - Mutation-test the new arm once: break the boolean-before-number order, the D9 check and the R10 check, and watch the matching rows go red.
+
+## Phase 3 — the `JSON` arm and the fallback's typed refusal (R7, R8)
+
+1. Add `InputKind.JSON`, `is_structured` `False`, and `(NativeConceptCode.JSON, InputKind.JSON)` to the ordered natives of `resolve_input_kind`, so `native.JSON` and every concept refining it leave the fallback.
+2. `_shape_one`: `JSON` joins the typed group.
+3. `_build_item_content`, the `JSON` arm: every object goes through Phase 2's object helper, taken literally — `{"json_obj": {…}}` included, since R7 has no collision rule — and built with the *declared* concept so a refining class is honoured; an item of a bare list keyed exactly `concept` and `content` is refused as in the `Anything` arm (R10); anything else is `_wrong_kind` with "a JSON object".
+4. `input_renderer._delighten_entry`: `InputKind.JSON` joins the scalar arm, whose `_unwrap_scalar_content` already turns a single-field content into its value, so the light template for a `JSON` slot is the bare object and for `JSON[]` a list of bare objects. Update both functions' docstrings, which list the scalar fields and say an out-of-matrix value keeps its envelope.
+5. R8, in `_shape_one`'s `DYNAMIC` arm: catch `StuffFactoryError` from the bottom-up factory and raise a `StructureValidationError` from it, with the input name, the declared concept ref, the expected shape, and a reason the shaper writes from `_describe_value(value)`: this concept's slot reads a bare value by its own shape and has no reading for this one. The user action's detail names the fix on the author's side — declare the input as `JSON` or `JSON[]` for plain JSON data, or as a concept with a structure — and suggests no envelope. `StructureValidationError.make` hard-codes its detail, so give it an optional one or add a sibling classmethod on the same class; either keeps the error identity. The factory's message stays on the chain only, so no `typing.Union[…]` reaches a caller. Widen `StructureValidationError`'s docstring (`pipelex/core/memory/exceptions.py`) to cover a value the fallback has no reading for. If the generated error page is built from that docstring, regenerate it with `pipelex-dev generate-error-pages` and review the diff; `generate-error-identity` should report no change, since no class is added or renamed.
+6. Tests:
+ - `test_scalar_arms.py`: `JSON` rows — `{"a": 1}`, `{}`, a nested object, and `{"json_obj": {"a": 1}}` taken literally into `JSONContent(json_obj={"json_obj": {"a": 1}})` — and a concept refining `JSON` built through its own class; a string, a number and a boolean raising `WrongScalarKindError`. The string row pins the behaviour change: it used to become `native.Text`.
+ - `test_multiplicity.py`: `JSON[]` with the report's value `[{"a": 1}, {"b": 2}]`, a single object wrapped, `[]`, a list at a single `JSON` slot raising `ListWhereSingularError`, an array item refused, an envelope-shaped item refused (R10).
+ - `test_explicit_forms.py`: the `JSON` envelope with `{"json_obj": …}` content unchanged; a `JSON` envelope around a list of content forms at `JSON[]`, one of them holding an object keyed `concept` and `content` (R10's escape). If the bottom-up factory cannot build a list inside a `JSON` envelope, record it here and decide at Checkpoint 1 whether R10's `JSON[]` escape needs the fix or a different spelling.
+ - `test_errors.py`: R8 at `Dynamic`, `Dynamic[]`, `Composite[]`, `Html[]`, `TextAndImages[]`, `SearchResult[]` and `Page[]` — a `StructureValidationError` whose message names the input and its concept, whose `error_domain` is `input`, whose `__cause__` is the factory's `StuffFactoryError`, whose text holds no `typing.Union`, and whose user action names `JSON[]` and no envelope.
+ - **The report's regression test**: one parametrized test sending `[{"a": 1}, {"b": 2}]` to every slot kind the design measured — accepted at `Anything[]`, `JSON[]` and a structured user concept's list, `ListWhereSingularError` at `Anything` and `JSON`, `StructureValidationError` everywhere else — so a `StuffFactoryError` can never again reach a caller from this path.
+ - `test_input_renderer_light.py`: the light template for a `JSON` slot is the bare object, for `JSON[]` a list of bare objects, and each shapes back through the shaper into the same content as the explicit template.
+
+**Checkpoint 1** — `make agent-check` clean, the shaper suite and the compatibility suite green, and both probe matrices of `design.md` — the `Anything` matrix and the list-of-objects one — re-run, with every row either accepted as the rulings say or refused with a typed error. Record here what was measured and anything decided on the way, then `/rev`.
+
+*Reached, 2026-09-27.* `make agent-check` is clean and the unit suite is green but for the four projection-corpus tests, which fail on the `JSON` unwrap until Phase 5 changes the reference projection. Both matrices were re-run through `shape_inputs` against a probe bundle, and every row lands as ruled:
+
+```
+== carry (anything_in)
+ bare {} / string / 3 / 4.2 / true / {"a": 1} / a TOML date OK native.Anything, JSONContent / TextContent / NumberContent / YesNoContent / JSONContent / DateContent
+ bare list, envelope list REFUSED ListWhereSingularError
+ envelope {} / str / num OK native.Anything, the same contents as bare
+ envelope Text / native.JSON / Question OK each keeps its own concept
+== carry_list (items)
+ bare [{}] / ["a"] / [1, 2] / [] / envelope [{}] OK native.Anything, ListContent of the natural contents
+== [{"a": 1}, {"b": 2}] per slot
+ Anything, JSON REFUSED ListWhereSingularError
+ Anything[], JSON[], Record[] OK
+ Dynamic, Dynamic[], Composite[], Html[], TextAndImages[], SearchResult[], Page[]
+ REFUSED StructureValidationError "Input 'x' could not be built as 'native.<X>': you provided a list of 2 item(s), …"
+== JSON slot
+ "hi", 3 REFUSED WrongScalarKindError "expects a JSON object"
+ {"a": 1}, {"json_obj": {"a": 1}} OK JSONContent holding the object literally
+```
+
+Decided on the way:
+
+- **R5's "any other slot" is read through compatibility.** The shaper asks `is_compatible(Anything, declared)` rather than whether the slot is `Anything`, so an `Anything` envelope is also honoured at a `Dynamic` slot, which it satisfies by the dynamic short-circuit, and keeps its concept there (D6, explicit wins when compatible). Everywhere else it is `ExplicitConceptIncompatibleError`, as ruled. A `DictStuff` naming a structureless concept takes the same path as the plain envelope.
+- **R10's check sits in `_shape_list`**, not in the item arm: only a list's items can be envelope-shaped bare values, since a top-level one is an envelope by D6. The flag that clears it inside an `Anything` envelope is `is_raw_data`, threaded through `_shape_with_multiplicity`.
+- **R10's `JSON[]` escape needs no fix**: a `JSON` envelope around a list of content forms builds through the bottom-up factory's Case 2.6 unchanged, pinned by `test_json_envelope_around_a_list_of_content_forms_is_r10s_escape`.
+- **`_make_content` reports the declared concept** in a `StructureValidationError`, since the `Anything` arm builds through a native concept's class. The `JSONContent` validator raises `ValueError` now, and the three `test_json_content_validation.py` tests that pinned the raw `TypeError` pin a `ValidationError`.
+- **R8's refusal is `StructureValidationError.make_for_unreadable_bare_value`**, a sibling of `make`, so the error identity is unchanged.
+- **Mutation-tested**: putting the number check before the boolean one, dropping the null-content check, dropping the R10 check and ignoring its escape flag each turn the matching rows red.
+
+## Phase 4 — the published schema excludes array and null (R4)
+
+1. `Concept.render_structureless_representation`, SCHEMA arm: add `"not": {"type": ["array", "null"]}` to the element schema. The multiplicity wrapper is unchanged, so `Anything[]` items carry it.
+2. Tests: `tests/integration/pipelex/pipeline/test_pipe_io_contracts.py` pins the `Anything`, `Anything[]` and `Anything[2]` schemas; `tests/unit/pipelex/core/pipes/test_stuff_spec.py` pins the structureless render. Add a check that validates the design's accepted and refused values against the rendered schema with `jsonschema`, so the contract and the shaper are shown to agree rather than asserted to.
+
+## Phase 5 — the corpus and the docs
+
+1. `pipelex/cli/dev_cli/commands/generate_projection_corpus_cmd.py`: delete the two `L-260902-10eb56` entries from `EXPECTED_UNSHAPEABLE`, and rewrite the comment above it so it describes the one gap still declared, `L-260830-191719`.
+2. `tests/data/input_semantics/scaffold_bundle.mthds`: fold `anything_in = "Anything"` back into `scaffold_open_natives` (inputs and template), delete `scaffold_anything_slot`, and rewrite the comments above both so they describe the four open natives as they now are (design, question 3).
+3. `pipelex/cli/dev_cli/commands/projection_reference.py`: remove `JSON` from `OUT_OF_MATRIX_NATIVES` and give a `JSON` slot a compact unwrap of `json_obj`, keyed on the native's identity the way the set already is, since its descriptor node is an `object` and `keeps_envelope` answers `True` for every native object node. Reword the set's comment, which says an input shaper cannot build these natives top-down, to the reason in the design's "What deliberately does not change".
+4. Regenerate into a scratch directory with the four-bundle command from `docs/contribute/generate-projection-corpus.md`, in the order it gives, and read the result: no `input_semantics_scaffold` template declared unshapeable, the divergence classes and their site counts unchanged, `json_in`'s compact template the bare object in both formats with the engine and the reference agreeing, and the `anything_in` contract carrying the Phase 4 schema. Record the summary line (pipes, divergences, templates shaping cleanly) here, because the Phase 6 items check their own regeneration against it.
+5. Update the tests that read the scaffold: `tests/integration/pipelex/pipeline/test_input_form.py` where the scaffold's pipes changed, and `tests/unit/pipelex/cli/dev_cli/test_generate_projection_corpus.py`, which compares the manifest's unshapeable list with `EXPECTED_UNSHAPEABLE` and follows by itself.
+6. Docs, each describing the current behaviour with no history:
+ - `docs/under-the-hood/pipe-io-contracts.md`, the `native.Anything` section: drop the paragraph saying the shaper has to catch up, and state what the schema admits.
+ - `docs/building-methods/pipes/provide-inputs.md`: the admonition that groups `Anything` and `JSON` with the natives read by their own shape. Give each its own sentences — `Anything` takes any JSON value into its natural content and keeps its concept, a typed envelope keeps its own; `JSON` takes a JSON object as it is, or, as `JSON[]`, a list of them, and its template shows the bare object — and say that an item shaped like an envelope is refused in a bare list, and that for the natives still read by their own shape, a value with no reading is refused naming the input and the declaration to change.
+ - `docs/building-methods/concepts/native-concepts.md`: the choice among the untyped concepts, in R11's order, as its own section ahead of the per-concept structures — naming the JSON by refining `JSON` first, with a worked `refines = "JSON"` concept taking a plain object as input. The `Anything` section says it is "primarily used as semantic markers"; say what an `Anything` input takes and what an `Anything` output means. The `JSONContent` section says what a `JSON` input takes, and that `JSON` is a JSON object, not any JSON value.
+ - `docs/building-methods/concepts/refining-concepts.md`: a pointer to that section, since refining `JSON` is the pattern it recommends for data a developer already has.
+ - `docs/errors/structure-validation-error.md`: the case of a value the fallback has no reading for, with changing the input's declaration as the fix.
+ - `docs/contribute/generate-projection-corpus.md`: the paragraph on `native.Anything` sitting alone in `scaffold_anything_slot`.
+ - `CHANGELOG.md`, under the unreleased section. *Fixed*: the values and typed envelopes an `Anything` slot now accepts, its multiplicity, the `PipeSequence` output; objects and lists of objects at a `JSON` slot; the fallback's refusal now a typed input error naming the input. *Changed*: a bare string at an `Anything` slot now produces a `native.Anything` stuff; a bare string at a `JSON` slot is now refused instead of becoming `native.Text`; the compact inputs template for a `JSON` slot is the bare object; an envelope-shaped item of a bare `Anything[]` or `JSON[]` list is refused; the fallback's refusal carries a new `error_type` and names the declaration to change; and the schema, if Phase 4 ran.
+7. `make agent-check`, including `make drift-check`; follow `docs/contribute/drift-contracts.md` for any contract it opens. Then `make agent-test`, and `make test-ts-gates` only if Phase 4 changed anything the TypeScript gates read.
+
+**Checkpoint 2** — the full suite green, the corpus summary recorded, the docs and changelog written. `/rev`, then the pull request: title `fix/Anything-slot-shaping · L-260902-10eb56`, body ending `Closes L-260902-10eb56`. Tell the reviewers that the fold deletes one pipe's files from both mirrors on purpose, and that `conformance`'s census (`tests/mthds/fixtures/protocol_corpus_census.json`, which L-260902-e62273 added) is edited to match in Phase 6.
+
+## Phase 6 — the mirrors' projections, the shared corpus and the census
+
+When the pull request opens, file three items the way L-260902-543ad0 filed its two, each `--blocked-by L-260902-10eb56`:
+
+- **`mthds-js`** and **`mthds-python`**, each carrying the Checkpoint 2 summary and the exact regeneration command. Each changes its projection before re-committing the corpus — `src/protocol/inputs_template.ts` and `mthds/protocol/inputs_template.py` respectively: `JSON` leaves `OUT_OF_MATRIX_NATIVES`, a `JSON` slot's compact value is its `json_obj` unwrapped (the phase 5 reference projection is the model), and the set's comment takes the reword. Without the projection change, each repo's own harness fails its byte parity with the new capture.
+- **`conformance`**: remove `input_semantics_scaffold.scaffold_anything_slot` from `tests/mthds/fixtures/protocol_corpus_census.json`, since the census is checked as an equality and the fold removes that pipe.
+
+After the merge, each mirror is regenerated from a merged `pipelex` `dev` with the `projection-corpus-update` skill, on a branch cut from the mirror's `dev`, and the three pull requests merge together, or `conformance`'s fixture-drift and census checks go red for everyone.
+
+**Checkpoint 3** — both mirrors carry the new capture and projection, the census matches it, L-260902-10eb56 is landed with `/ledger-land`, and this document and `design.md` flip to `landed`.
+
+## Handoff — design session, 2026-09-27
+
+**Done.** The bug is verified and both documents are written; no code has changed. `design.md` carries the two measured matrices (the `Anything` slot on `dev` at `be796a0d8`, and the list-of-objects report plus the `JSON` slot on `dev` at `d93a24767`) and rulings R1 to R8. The scope widened once, on Louis's go-ahead, from the `Anything` slot alone to R7 (a `JSON` handler) and R8 (the fallback's typed refusal), after a report of a list of plain JSON objects hitting `input_shaper.py:188` → `stuff_factory.py:454` at an unnamed slot. The probe scripts that produced the matrices are not kept; the matrices in `design.md` are the record, and Checkpoint 1 re-runs them against the fix.
+
+**Open at the time, and answered since (see the ratification below).** Open questions 1 and 3 at the end of `design.md`: R4 (narrow the `Anything` schema by D2 and D9) and folding `anything_in` back into `scaffold_open_natives`. Each carries a recommendation; the documents flip from `draft` to `active` when Louis ratifies them, in the same change that records his answers here. Question 4, whether `JSON` should hold any JSON value, belongs to the standard (L-260927-a8ec06) and blocks nothing here.
+
+## Handoff — review of the rulings, 2026-09-27
+
+A second session reviewed the design from two sides, what keeps the language clear to non-technical readers and agents, and what a developer holding plain JSON needs, and Louis agreed with every change it proposed. No code has changed. The changes are:
+
+- **R7 has no collision rule** (open question 2, now decided). `JSON`'s compact template becomes the bare object in the engine, the reference projection and both mirrors, so no caller learns the `json_obj` wrapper, and every bare object is read literally. This grows Phase 3 (the light template), Phase 5 (the reference projection) and Phase 6, whose mirror items now change projection code rather than only re-committing the corpus.
+- **R8's refusal names the declaration to change** (`JSON`, `JSON[]`, or a concept with a structure) and no longer suggests an envelope, because at a `Dynamic` slot the obvious one drops the object's content (L-260927-bea35e).
+- **R10, new**: an envelope-shaped item of a bare `Anything[]` or `JSON[]` list is refused, which D6's top-level-only collision rule would otherwise have let through as JSON.
+- **R11, new**: the docs teach one choice among `Anything`, `JSON` and `Dynamic`, leading with naming the JSON through a concept refining `JSON`.
+- **R9, new and built elsewhere**: on the output side, an `Anything` stuff's content goes on the public wire as its plain JSON value. Measured, it goes out as its content class's fields today (`{"text": "hi"}`), so once R1 lands a value chained through `--with-memory` changes type. L-260927-da1b09 (`pipelex`) and L-260927-223013 (`mthds`) carry it.
+- **A correction to the first review.** The published `json_schema` and codegen's `JSON` type describe the content form for every native (`Text`'s is `{"text": …}`), so neither is a `JSON`-specific defect and neither changes.
+- **A stale claim in Checkpoint 2, fixed.** `conformance` pins a corpus census as an equality since L-260902-e62273 closed, so the fold of `scaffold_anything_slot` needs a census edit; Phase 6 now files a `conformance` item beside the two mirrors.
+
+**Ratified, 2026-09-27.** Louis answered every open question of `design.md` and the choices this review had made on its own, each as recommended: R4 narrows the `Anything` schema, so Phase 4 is built unconditionally; `anything_in` folds back into `scaffold_open_natives`; `JSON` stays an object, recorded and closed on L-260927-a8ec06; `Anything`'s compact template keeps its envelope; the content of an `Anything` envelope is raw data at every depth, list items included, which is R10's escape; and R11 advises against `Dynamic` for inputs while L-260927-bea35e is open. Both documents are `active` from this change. One point is left to measurement rather than decision: R10's escape for `JSON[]`, a `JSON` envelope around a list, which Phase 3 tests and Checkpoint 1 decides if the factory cannot build it.
+
+**Next, done since.** `dev` was merged into the branch after the ratification, bringing it to the v0.67.1 release and the `mthds` 0.17.0 pin, and the build session below claimed the item and started Phase 1.
+
+## Handoff — build session, 2026-09-27
+
+**Done.** Phases 1 to 3 are built, tested and committed as "Shape Anything and JSON slots top-down, and refuse the fallback by name", and Checkpoint 1's probe is recorded above. The four tests of `tests/unit/pipelex/cli/dev_cli/test_generate_projection_corpus.py` are expected to fail until Phase 5, with `Undeclared divergence class(es) ['engine-only-field']`, because the engine's `JSON` template is unwrapped while the reference projection is not yet.
+
+**Checkpoint 1's `/rev` ran but is not triaged** (the triage is recorded in the next section). Profile 4, round 1, bar `open`, fix mode `ask`, on the branch against `origin/dev` at the commit named above. All four reviewers returned (cubic, Codex's review and adversarial runs, and the bundled `code-review` at `medium`, whose provenance matched the worktree, the commit and the diff's files). The session stopped at its context threshold before verifying anything, so no finding below has been verified, fixed or rejected, and no `ledger review-pass` is recorded. The merged findings, with the reviewers who raised each:
+
+1. **Transport round-trip of a single `Anything` value** (Codex adversarial, high, `input_shaper.py` `_build_anything_content`). An `Anything` stuff holding a `TextContent`, sent through `dump_for_transport()` then `hydrate_working_memory()`, is reported to raise `PipeJobError: Class 'AnythingContent' not found in registry`, because the singular dump does not keep the concrete content class and hydration resolves the class from the declared concept. Verify with that exact round trip first. If real, it is a critical at every bar (a distributed run loses the input), and it touches R6 (no `AnythingContent` class ever) and R9 (L-260927-da1b09), so the fix is hydration reading the concrete class rather than a new class.
+2. **An envelope can escape the declared multiplicity** (three reviewers, three cases, `input_shaper.py` `_try_shape_structureless_envelope` and `_reconcile_explicit_multiplicity`):
+ - `code-review`: an `Anything` envelope whose content is a prebuilt `ListContent` becomes `ListContent(items=[ListContent(...)])` at `Anything[]`, and a bare `ListContent` at a single `Anything` slot, because `_shape_list` treats a non-`list` value as one item. Reproduced by the reviewer's probe.
+ - Codex adversarial: a typed envelope `{"concept": "native.Text", "content": "hello"}` at `Anything[]` stores a scalar `TextContent`, since reconciliation returns early when the content is not a `ListContent`, and `Anything[N]` counts are not checked. Check whether a `Text` envelope at `Text[]` does the same on `dev`; if so the hole predates this branch but is widened by it.
+ - cubic: at a singular `Dynamic` slot, `{"concept": "native.Anything", "content": [1, 2]}` raises `ListWhereSingularError` while `{"concept": "Text", "content": ["a", "b"]}` is accepted, because the structureless path peels multiplicity where `_shape_explicit` deliberately skips it for `Dynamic`. Decide one behaviour for both.
+3. **R8's refusal is too broad and its advice too narrow** (`code-review`, cubic; `input_shaper.py` `DYNAMIC` arm, `exceptions.py` `make_for_unreadable_bare_value`). It rewrites every `StuffFactoryError` from the fallback, so a list of an unregistered `StructuredContent` (`[Zork(), Zork()]` at a `Dynamic` slot) reports "no reading for this one" and hides that no concept `Zork` is registered, as does a mixed list of prebuilt contents or `[]` at `Html[]`. And it always advises `JSON` or `JSON[]`, which refuses a scalar too (`3` at a `Dynamic` slot). Reword only the no-reading cases, keep the factory's reason otherwise, and advise by the value's shape: a scalar towards `Anything` or its native, an object or a list of objects towards `JSON` or `JSON[]`.
+4. **The published `Anything` schema admits array and null** (both Codex runs). This is Phase 4, planned; the adversarial run adds that `Anything[]` items must carry the exclusion too, which Phase 4's step 1 already says.
+5. **The corpus gate, the stale docs and the missing changelog entry** (Codex review twice, cubic). This is Phase 5, planned.
+6. **Test layout** (cubic, P3): `test_explicit_forms.py` now holds three test classes and `test_errors.py` two, and the new classes carry docstrings, against the repo's testing rules. Move `TestInputShaperAnythingEnvelopes`, `TestInputShaperJSONEnvelopes` and `TestInputShaperFallbackRefusal` into their own modules, as `test_list_of_objects_report.py` already is, and drop the class docstrings.
+
+**Next, done since.** The triage below verified findings 1 to 3, fixed what survived and recorded the pass before Phase 4 started.
+
+Read for Phases 4 and 5 while the reviewers ran, so none of it needs re-deriving:
+
+- **Phase 4** also moves `test_anything_input_produces_a_verdict` in `tests/integration/pipelex/pipeline/test_protocol_validate.py`, which pins `set(anything_schema) == {"title", "description"}`, and `tests/integration/pipelex/cli/test_trace_input_semantics_cmd.py`, besides the two files step 2 names.
+- **Phase 5, the reference projection**: in `projection_reference.py`, `keeps_envelope` answers `code in OUT_OF_MATRIX_NATIVES or node.kind is FieldKind.OBJECT`, so the `JSON` code has to answer `False` ahead of the object test, and `_light_value` has to unwrap `json_obj` for a node whose native code is `JSON`.
+- **Phase 5, the divergence collector**: `_engine_dict_placeholder(path)` in `generate_projection_corpus_cmd.py` keys its placeholder by `path[-1]`, which at a compact `JSON` position is the slot name or a list index rather than `json_obj`. Give the collector the exact `JSON` positions from the descriptor, the way `register_fixed_counts` receives the fixed counts, use them in the `unknown-empty-object` arm, and update `tests/unit/pipelex/cli/dev_cli/test_projection_divergence_gate.py` to match. The site counts should not move; the example paths will.
+- **Phase 5, the error page**: `docs/errors/structure-validation-error.md` is generated, so the new case means converting it to an authored page (`<!-- pipelex:authored -->`, modelled on `docs/errors/model-not-found-error.md`) and running `generate-error-pages` and `generate-error-identity`, which should show no identity change.
+
+## Checkpoint 1's review, triaged — 2026-09-27
+
+The same session resumed after a compaction and triaged the findings above, with one verifier subagent reproducing findings 1 to 3 on the branch and, through `git archive origin/dev`, on `dev`. Every fix below was mutation-tested: removing it turns its test red.
+
+- **1, transport: confirmed and fixed.** The defect predates the branch (a hand-built `native.Anything` stuff fails the same way on `dev`), but R1 made every single `Anything` input reach it. `WorkingMemory.dump_for_transport` now stamps the class markers on the single content of a structureless concept, as it does on list items, and `hydrate_content` rebuilds that content from them. R9's premise, that internal serialization keeps content classes, holds again.
+- **2a, a prebuilt list in an `Anything` envelope: confirmed and fixed.** The envelope's `ListContent` is read as the list of its items, and a `ListContent` as an item is refused as a wrong kind, which also closes the same nesting at `Text[]` that predates the branch.
+- **2b, a typed singular envelope at a plural slot: predates the branch.** The `[N]` half is fixed, since a single value is never N items: `_reconcile_explicit_multiplicity` raises `MultiplicityCountMismatchError`. Whether a singular under `[]` is wrapped stays with Gap A in `wip/inputs/input-shaper-multiplicity-gaps.md`.
+- **2c, an `Anything` envelope at a `Dynamic` slot: confirmed and fixed.** It takes list or single from its content, as `_shape_explicit` does for every other envelope there.
+- **3, the fallback's refusal: confirmed and fixed.** An empty list, or a list holding prebuilt contents, keeps the factory's own reason through `StructureValidationError.make`; every other value gets `make_for_unreadable_bare_value`, whose advice now names the declaration that reads it: `JSON` for an object, `JSON[]` for a list of objects, `Anything` or `Anything[]` otherwise.
+- **4 and 5** were Phases 4 and 5, built next. **6, the test layout**, is fixed: each new test class has its own module, with no class or module docstring.
+
+## Checkpoint 2 — reached, 2026-09-27
+
+Phases 4 and 5 are built. The corpus regenerated with the four-bundle command reads: 16 pipes and 32 templates, 28 shaping cleanly and 4 declared unshapeable, all under L-260830-191719; divergences `file-leaf-not-expanded` 6, `fixed-count-honoured` 4, `object-native-keeps-envelope` 1, `optional-field-included` 167, `text-named-url` 6, `unknown-empty-object` 2, the same site counts as the committed capture. The compact `unknown-empty-object` example moved from `json_in.content.json_obj` to `json_in`, `json_in`'s compact template is `{}` in both formats, `anything_in` keeps its envelope and round-trips, and its contract carries the Phase 4 schema.
+
+Decided on the way:
+
+- **The divergence collector learns where a compact `JSON` slot unwraps** from the descriptor, through `register_json_unwraps`, as it learns fixed counts, because the engine's dict placeholder is keyed by the field holding the dict (`json_obj`) and the walk's path no longer names it there. An unregistered slot-level placeholder is refused, which a test pins.
+- **The schema and the shaper are shown to agree** by `test_anything_schema_agreement.py`, which validates every JSON type at `Anything`, `Anything[]` and `Anything[2]` against both, rather than asserting the schema's keys.
+- **`docs/errors/structure-validation-error.md` is an authored page now**, and the error identity did not change.
+- **The docs' `Order` example** (a concept refining `JSON`, singly and as `Order[]`) was probed through `validate_bundle` and `shape_inputs` before it was written down.
+
+## Checkpoint 2's review, triaged — 2026-09-27
+
+`/rev` at profile 4, round 2, bar `defects`, on the branch against `origin/dev` at the commit "Fix the Checkpoint 1 review findings, narrow the Anything schema, and land the corpus and docs". All four reviewers returned: cubic, Codex's review and adversarial runs, and the bundled `code-review` at `medium`, whose provenance matched the worktree, the commit and the diff's files. Every fix below was mutation-tested.
+
+- **A composite under `Anything` loses its components across transport** (`code-review`): fixed. `_hydrate_list_item` rebuilds a composite's components from their own markers at any depth, which also closes the nested-composite gap `wip/nested-composite-hydration-not-recursive.md` recorded, so that note is gone.
+- **The delivery cannot hydrate an `Anything` main stuff** (cubic, outside the diff but made visible by it): fixed. `try_local_hydrate_stuff` looked the concept's class up in the registry first, which a structureless concept never has, so the result files fell back to a raw dump that now showed the class markers.
+- **The fallback advises `Anything[]` for lists it refuses** (cubic, Codex review): fixed. A list holding nulls or nested lists gets no suggested declaration and keeps the factory's reason.
+- **A prebuilt `ListContent` mixing kinds is refused at `Anything[]`** (cubic): fixed. It is read as the bare list of its items, as inside an `Anything` envelope.
+- **NaN and the infinities** (Codex review): fixed at `Number` and `Anything` inputs, which refuse them as numbers JSON cannot hold.
+- **The changelog and the error page** (cubic): the chaining change through `--with-memory` is now a Breaking entry and a caveat in `provide-inputs.md`, the `JSONContent` entry names the case that actually changed (a value JSON cannot encode), and the error page no longer calls the container natives structureless.
+- **This plan's stale "Next" blocks and a local path** (cubic): the handoffs' next steps are marked done and the paths are gone.
+- **Chaining an `Anything` value through `--with-memory` changes its type** (Codex adversarial, high): deferred as ruled. It is R9, which `design.md` keeps out of this branch because it changes the run result and what every consumer displays; L-260927-da1b09 carries it with its round-trip test, blocked by this item.
+- **A typed singular envelope at `Anything[]` is stored unwrapped** (Codex adversarial, medium): deferred to Gap A's auto-wrap question, recorded in `wip/inputs/input-shaper-multiplicity-gaps.md`.
+- **A TOML date inside an object at a `JSON` or `Anything` input is refused** (cubic): deferred below. The refusal is typed and names the input; whether a date inside an object should become its ISO string is a reading of its own.
+
+The round was recorded with each Codex run named, and the pull request opened as pipelex#1287, where round 3 ran.
+
+## Checkpoint 2's review, round 3 — 2026-09-27
+
+`/rev` at profile 4, round 3, bar `necessity`, against pipelex#1287 at the commit "Fix the Checkpoint 2 review findings on transport, delivery and the fallback's advice". All four reviewers returned, and `code-review`'s provenance matched. Every fix below was mutation-tested.
+
+- **NaN and the infinities nested in an object** (cubic, both Codex runs; the adversarial run rated it high): fixed as a critical, since JSON serialization turned them into `null`. `JSONContent` validates with `allow_nan=False`, so a `JSON` or `Anything` object holding one anywhere is refused like any other value JSON cannot hold.
+- **The fallback's advice still named declarations that refuse the value** (`code-review`, cubic, Codex adversarial): fixed, because round 2's own fix was incomplete and its NaN refusal added a case. `_declaration_suggested_for` now asks `_anything_reads_item`, which mirrors what the `Anything` arm accepts: an envelope-shaped item, a non-finite number or an object JSON cannot encode gets no suggestion.
+- **The `Anything[]` schema admits an envelope-shaped item that R10 refuses** (cubic, Codex adversarial): deferred below.
+- **The inputs-file loader rewrites every relative `url` key, `JSON` data included** (cubic): deferred to L-260927-55f503. It predates this branch, which only adds a way in.
+- **A single `Anything` output holding a list breaks the narrowed schema** (`code-review`): rejected. An output contract describes the dumped content, and a `ListContent` comes back as an object holding `items`, which the schema admits; the bare array exists only in the private transport encoding.
+- **A `JSON` refinement with sibling fields loses them in the reference projection** (Codex review): rejected. A refining concept cannot declare a structure (`concept_blueprint.py`), so the state cannot occur.
+
+## Checkpoint 2's review, round 4 — 2026-09-27
+
+`/rev` at profile 4, round 4, bar `freeze`, against pipelex#1287 at the commit "Refuse NaN inside JSON objects, advise only declarations that read the value, and land the campaign docs", run by the skill's unattended default for a `freeze` bar. All four reviewers returned, and `code-review`'s provenance matched.
+
+- **An explicit `Number` envelope still carries NaN into a `NumberContent`** (Codex review): fixed as a critical, since serialization turns it into `null`. `NumberContent` refuses a non-finite number itself, so every explicit form and every concept refining `Number` is covered.
+- **Three statements this branch wrote were wrong**, corrected with no behaviour change: the changelog named the old `JSON` compact template as `{"json_obj": …}` where it was the whole envelope (cubic); `native-concepts.md` said `JSON` declares no structure of its own (cubic); and the docs and the agreement test claimed the `Anything` schema and the shaper agree exactly, where the shaper also wraps a single value sent to `Anything[]` (`code-review`).
+- **Repeated from earlier rounds and already traced** (Codex adversarial): the `--with-memory` chaining (R9, L-260927-da1b09), a typed singular envelope at `Anything[]` (Gap A), the inputs-file `url` rewrite (L-260927-55f503) and the `Anything[]` schema's envelope-shaped item (below).
+- **Deferred below**: the advice for an object with non-string keys (Codex review), and the second copy of the `Anything` arm's rules in `_anything_reads_item` (cubic).
+
+## After the merge
+
+L-260902-10eb56 lands with pipelex#1287, and both campaign documents are `landed` from that merge. Checkpoint 3's cross-repo half is carried by three items, each blocked by this one: L-260927-b1ca80 (`mthds-js`) and L-260927-cd33d1 (`mthds-python`) change their projections and re-commit the regenerated corpus with the `projection-corpus-update` skill, checking it against the Checkpoint 2 summary above, and L-260927-7f1e95 (`conformance`) removes `scaffold_anything_slot` from the census. The three pull requests merge together, or `conformance`'s fixture-drift and census checks go red for everyone.
+
+## Ledger
+
+- L-260902-10eb56 is claimed from the worktree; `ledger claim L-260902-10eb56 --renew` at the start of each session.
+- Ruled on here but not built: L-260902-9546ef, L-260926-f7bb28 (now linked to it) and L-260902-db6d1e keep their own fix directions under the design's R6.
+- Filed from this design: L-260927-bea35e (`pipelex`, the `Dynamic` envelope data loss, now also carrying the list half of the report) and L-260927-afaf62 (`mthds`, the runtime guide's compatibility pseudo-code).
+- Filed from the review: L-260927-da1b09 (`pipelex`, R9's runtime half, blocked by this item) and L-260927-223013 (`mthds`, R9's wording in the standard); L-260927-a8ec06 (`mthds`, question 4, decided and closed: `JSON` stays an object); L-260927-702c56 (`pipelex`, a JSON file reference into `JSON[]`, blocked by this item).
+- Filed at the pull request (Phase 6): L-260927-b1ca80 (`mthds-js`), L-260927-cd33d1 (`mthds-python`) and L-260927-7f1e95 (`conformance`), each blocked by this item.
+- Filed from round 3: L-260927-55f503 (`pipelex`, the inputs-file loader's signature-blind `url` rewrite).
+- Not touched: L-260831-1e1a71 owns the explicit arm's untyped escapes, which R8 deliberately leaves alone.
+
+## Deferred
+
+- **What a `Dynamic` slot holds.** Gap B of `wip/inputs/input-shaper-multiplicity-gaps.md` stays open for `native.Dynamic`, and a bare object or a list of objects there is refused, typed but refused. Both belong to L-260927-bea35e, which has to rule on what a `Dynamic` slot holds anyway.
+- **Top-down handlers for `Composite`, `Html`, `Page`, `TextAndImages` and `SearchResult`.** They stay on the fallback, refusing by name under R8 and taking an envelope. None has been reported, and each needs its own reading of a bare value.
+- **Codegen's `unknown` for an `Anything` slot** admits an array and a null that R4 excludes. A structureless concept is a declared imprecision in codegen, so it is left as is unless a consumer asks.
+- **The output side of an `Anything` value (R9)** is L-260927-da1b09 and L-260927-223013, with the round-trip test.
+- **A JSON file reference into `JSON[]`**, the way D11 reads a CSV into a structured list, is L-260927-702c56.
+- **Per-item envelopes in a list**, for every kind, would be a feature of their own; R10 refuses the spelling rather than read it for two kinds only.
+- **A TOML date inside an object** at a `JSON` or `Anything` input is refused as a value JSON cannot hold, though the same date at the top of an `Anything` input is read. Converting it to its ISO string would be a reading of its own, left until a caller asks.
+- **An envelope-shaped item of an `Anything[]` list** passes the published schema, an object that is neither an array nor null, while R10 refuses it. A schema can state it, as an item that is not an object keyed exactly `concept` and `content`, but every consumer of every `Anything[]` schema would carry that clause for one pathological shape, which a clear refusal already names. `test_anything_schema_agreement.py` says it leaves the shape out.
+- **The fallback's advice for an object with non-string keys**, which only a Python caller can send: `json.dumps` coerces `{1: "x"}`, so the refusal advises `JSON`, and `JSONContent` then refuses the integer key. The advice is wrong, but the refusal it rides on is right.
+- **`_anything_reads_item` restates what the `Anything` arm accepts** so the fallback never advises a declaration that refuses the value. Deriving both from one predicate would stop them drifting apart; the fallback-refusal tests pin every case the two share today.
diff --git a/wip/inputs/input-shaper-multiplicity-gaps.md b/wip/inputs/input-shaper-multiplicity-gaps.md
index dff931cc1..95934b041 100644
--- a/wip/inputs/input-shaper-multiplicity-gaps.md
+++ b/wip/inputs/input-shaper-multiplicity-gaps.md
@@ -52,3 +52,7 @@ The Phase-5 reconcile introduced a narrower regression: a singular `native.Dynam
`InputShaper._shape_explicit` now returns immediately after compatibility when the declared concept is exactly `native.Dynamic`, matching the bare-value Dynamic fallback. Pinned by `test_explicit_list_content_into_dynamic_slot_ok`.
This does **not** resolve the broader Gap B above: declared `Dynamic[]`/`Anything[N]` still do not peel multiplicity, and the empty-list/count/auto-wrap semantics remain deferred to the holistic D2 pass.
+
+## Anything-slot review, round 2 (2026-09-27) — the auto-wrap question now reaches `Anything[]`
+
+The anything-slot branch (`wip/anything-slot/`) made every concept compatible with `native.Anything`, so a typed singular envelope such as `{"concept": "native.Text", "content": "hello"}` at an `Anything[]` input is now accepted and, under Gap A's auto-wrap sub-question, stored as a single `TextContent` rather than a one-item `ListContent`. A consumer iterating the input, such as a `PipeBatch`, then refuses it at run time, while the same bare `"hello"` would have been wrapped. Codex's adversarial review rated it medium. It is the same question as above, reached through a new door rather than a new defect, so it stays with the holistic D2 pass. The fixed-count half is settled on that branch: an explicit single value at a `Concept[N]` input now raises `MultiplicityCountMismatchError`.
diff --git a/wip/nested-composite-hydration-not-recursive.md b/wip/nested-composite-hydration-not-recursive.md
deleted file mode 100644
index 52cb735ef..000000000
--- a/wip/nested-composite-hydration-not-recursive.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# Nested CompositeContent hydration is not recursive across the runtime bridge
-
-**Status:** Deferred follow-up (confirmed defect, deliberately not fixed in the v0.37.0 release). Flagged by codex and cubic on PR #1020.
-
-## Problem
-
-The transport encode side recurses, the hydration side doesn't:
-
-- **Encode** (`pipelex/core/memory/working_memory.py`): `_encode_composite_for_transport` sends every composite component through `_encode_content_with_class_markers`, which recurses back into `_encode_composite_for_transport` when the component is itself a `CompositeContent`. Inner components are correctly stamped with `__pipelex_class__` / `__pipelex_module__` markers at every depth.
-- **Hydrate** (`pipelex/runtime_bridge/primitives/hydration.py`): `_hydrate_list_item`'s marker branch strips the markers only at the top level and calls `item_class.model_validate(clean_item)`. When `item_class` is a `CompositeContent` subclass (extra="allow" — no annotations to drive validation), the inner components are left as raw marker-bearing dicts instead of typed `StuffContent`.
-
-Consequence: a `CompositeContent` nested inside another `CompositeContent` (e.g. a `PipeParallel` result feeding another parallel's combine, crossing the Temporal/runtime-bridge boundary via `dump_for_transport()` → `hydrate_working_memory()`) round-trips with corrupted typed access — downstream `rendered_*` calls and type checks see dicts with `__pipelex_*` keys.
-
-One level of composite (the common case, top-level composite stuff) hydrates correctly via `hydrate_content`'s composite branch; only *nested* composites are affected.
-
-## Proposed fix
-
-In `_hydrate_list_item` (hydration.py), in the marker branch: after resolving `item_class` and building `clean_item`, when `issubclass(item_class, CompositeContent)`, map each value of `clean_item` through the existing `_hydrate_composite_component` before `model_validate`. The mutual recursion `_hydrate_composite_component` ↔ `_hydrate_list_item` then handles arbitrary nesting depth.
-
-## Test shape (TDD)
-
-In `tests/unit/pipelex/runtime_bridge/primitives/test_hydration.py`: build a `WorkingMemory` whose main stuff is a `CompositeContent` containing (a) a nested `CompositeContent` component and (b) a list-of-composites component; run `dump_for_transport()` → `json.dumps`/`json.loads` → `hydrate_working_memory()`; assert every nested component is a typed `StuffContent` instance and no `__pipelex_class__` / `__pipelex_module__` key survives anywhere in the tree.