Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/interplane-mv/patches/d270bbc8ada94cc6
# interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
## GitHub aien-dev/interplane-mv#4 (code only)
closed derived `d270bbc8ada94cc6` #4
Imported from GitHub aien-dev/interplane-mv#4 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base `64db4e42fef74b399a925cb168ca35f586edb803` · Head `8e73ceb431f3a8e3e3150563f2fb478310a5fd62`
greptile-apps[bot] commented on `python/interplane/crossaxis.py` line 512 on 2026-10-04 21:45 UTC
Unrelated discovery names accepted
If a caller supplies discovery names rather than passing through the output of `discover`, `expand` does not check whether they match the query. A `file` query omitted `web_fetch`, but supplying that name added and rendered its descriptor. This is a non-blocking visibility concern: the model can see an unrelated tool, though expansion does not grant permission to run it.
Artifacts
Evidence from the check
- The executed script selects an email-domain view and compares discovery with expansion using an unrelated catalog capability.
Command output from the check
- The first command exited 0 and shows that a `file` query omits `web_fetch` from discovery results.
Command output from the check
- The second command exited 0 and shows `web_fetch` added and its descriptor rendered despite its absence from discovery results.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: python/interplane/crossaxis.py
Line: 508-512
Comment:
**Unrelated discovery names accepted**
If a caller supplies discovery names rather than passing through the output of `discover`, `expand` does not check whether they match the query. A `file` query omitted `web_fetch`, but supplying that name added and rendered its descriptor. This is a non-blocking visibility concern: the model can see an unrelated tool, though expansion does not grant permission to run it.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `python/interplane/crossaxis.py` line 492 on 2026-10-04 21:45 UTC
Stale catalog digest accepted
If capabilities change while the catalog retains its stored digest, `expand` compares the selection against that stored value rather than the current catalog. An old selection accepted and rendered a changed parameter schema under the original digest. This is a non-blocking consistency concern: callers can receive descriptors that the selection digest does not identify.
Artifacts
Evidence from the check
- The authored Python script selects, mutates, round-trips, expands, and renders a catalog in three modes, providing the executed source.
Command output from the check
- The script expanded the original catalog and rendered `write_file` with its original string parameter, establishing the baseline.
Command output from the check
- The script changed and round-tripped the catalog without clearing its digest; expansion succeeded and rendered the new integer parameter under the old digest.
Command output from the check
- The script cleared the digest after the same mutation and expansion rejected the catalog, isolating reliance on the stored value.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: python/interplane/crossaxis.py
Line: 492
Comment:
**Stale catalog digest accepted**
If capabilities change while the catalog retains its stored digest, `expand` compares the selection against that stored value rather than the current catalog. An old selection accepted and rendered a changed parameter schema under the original digest. This is a non-blocking consistency concern: callers can receive descriptors that the selection digest does not identify.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `python/interplane/crossaxis.py` line 567 on 2026-10-04 21:45 UTC
Refused receipts keep growing
Every refused expansion adds a receipt round without using the `max_expansions` allowance. After 600 refusals, the Python receipt had 601 rounds and reached 125,291 bytes; later attempts took longer as the history grew. This is a non-blocking storage and processing cost for repeated retries, also observed in Rust.
Artifacts
Evidence from the check
- This authored script selects a catalog, permits one addition, and measures repeated refused expansions; it reproduces receipt growth.
Evidence from the check
- This authored Rust example exercises the equivalent selection and expansion sequence; it reproduces receipt growth.
Command output from the check
- The Python reproduction ran with zero refused attempts and recorded the one-round baseline; the receipt was 1,197 bytes.
Command output from the check
- The same Python reproduction ran with 600 refused attempts and recorded 601 rounds and rising execution time; the receipt reached 125,291 bytes.
Command output from the check
- The Rust example ran with zero refused attempts and recorded the one-round baseline; the receipt was 823 bytes.
Command output from the check
- The same Rust example ran with 600 refused attempts and recorded 601 rounds and rising execution time; the receipt reached 121,917 bytes.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: python/interplane/crossaxis.py
Line: 558-567
Comment:
**Refused receipts keep growing**
Every refused expansion adds a receipt round without using the `max_expansions` allowance. After 600 refusals, the Python receipt had 601 rounds and reached 125,291 bytes; later attempts took longer as the history grew. This is a non-blocking storage and processing cost for repeated retries, also observed in Rust.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] reviewed (COMMENTED) on 2026-10-04 21:45 UTC
greptile-apps[bot] wrote on 2026-10-04 21:45 UTC
Confidence Score: 4/5
[Medium risk] Adds capability expansion and measurement features to the selection system.
The observed expansion issues are non-blocking, so this review does not consider the PR unsafe to merge.
Findings
- Unrelated discovery names accepted ▶
- Stale catalog digest accepted ▶
- Refused receipts keep growing ▶ Fix with agent prompt
```
### Issue 1
python/interplane/crossaxis.py:508-512
If a caller supplies discovery names rather than passing through the output of `discover`, `expand` does not check whether they match the query. A `file` query omitted `web_fetch`, but supplying that name added and rendered its descriptor. This is a non-blocking visibility concern: the model can see an unrelated tool, though expansion does not grant permission to run it.
### Issue 2
python/interplane/crossaxis.py:492
If capabilities change while the catalog retains its stored digest, `expand` compares the selection against that stored value rather than the current catalog. An old selection accepted and rendered a changed parameter schema under the original digest. This is a non-blocking consistency concern: callers can receive descriptors that the selection digest does not identify.
### Issue 3
python/interplane/crossaxis.py:558-567
Every refused expansion adds a receipt round without using the `max_expansions` allowance. After 600 refusals, the Python receipt had 601 rounds and reached 125,291 bytes; later attempts took longer as the history grew. This is a non-blocking storage and processing cost for repeated retries, also observed in Rust.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
Summary
The PR adds unit-labelled measurement, bounded capability expansion, digest-linked receipts, and two cross-language conformance cases. A caller can select capabilities, discover excluded tools, and expand the visible selection while retaining a receipt. Expansion can also render an unrelated caller-supplied discovery result, accept changed catalog descriptors under a stale stored digest, and accumulate increasingly costly receipts from repeated refusals. These are non-blocking concerns; none grants runtime authority. Reviews (1) · Last reviewed commit: "feat(crossaxis): tokenizer-aware selecti..."
### Apply it
```
git checkout -b patch-d270bbc8ada94cc6 64db4e42fef74b399a925cb168ca35f586edb803
curl -fsSL https://interplane.io/drakestapleton/interplane-mv/patches/d270bbc8ada94cc6.patch | git am
```
Raw patch (mbox) · Diff
### Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
```
github-import 1
aien-dev/interplane-mv
4
8e73ceb431f3a8e3e3150563f2fb478310a5fd62
```
```
{"kind":"github-import","owner":"aien-dev","repo":"interplane-mv","number":4,"url":"https://github.com/aien-dev/interplane-mv/pull/4","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:03Z","metadata":"unavailable","state_derived":true}
```
### Changes
```
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b874b42..a817cf5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -62,7 +62,7 @@ jobs:
import json,sys
r=json.load(open('rust-verdicts.json')); p=json.load(open('py-verdicts.json'))
bad=[c for c in sorted(set(r)|set(p)) if json.dumps(r.get(c),sort_keys=True)!=json.dumps(p.get(c),sort_keys=True)]
- print('cases:',len(r),'mismatches:',bad); sys.exit(1 if bad or len(r)!=23 else 0)
+ print('cases:',len(r),'mismatches:',bad); sys.exit(1 if bad or len(r)!=25 else 0)
PY
adapter-aien:
runs-on: ubuntu-latest
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81ecd39..39868ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,13 @@
# Changelog
-## Unreleased (0.1.0)
+## Unreleased (0.2, CrossAxis lane)
+
+- `selection.measure`: `rendered_bytes` and an optional unit-disciplined `tokens` block (`bytes`, `tokens_model_reported`, `tokens_endpoint_tokenizer`, `tokens_estimated`); `TokenCounter` with `BytesOnly` and `EstimatedTokens` (estimator v1) in both languages.
+- Bounded capability expansion: `expand` and `discover` (pure Core functions), `selection.expansions[]`, `parent_digest`, `selection_digest`, `selector.expansion` bounds. Expansion never grants authority.
+- Receipt normalization (additive, no existing conformance expectation changed): both languages now omit empty `always_include`, empty `selected[].domains`, a null `selector.max_capabilities` and null legacy token fields; the Rust mock catalog omits an empty `required`, so both mock catalogs have one digest.
+- Conformance: cases 24 (expansion by requested_excluded, call still denied) and 25 (expansion refused by bounds); 25/25 byte-identical.
+
+## 0.1.0 (unreleased)
- Phase 0 audit (`CURRENT_STATE.md`).
- Core schemas, specs for Core, Lenshift, Crossveil, CrossAxis, Probe, Vectorveil, RelayLine, versioning.
diff --git a/README.md b/README.md
index 7e72d2d..50f9a0d 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@ and execution. INTERPLANE only standardizes what crosses between them and makes
| **Crossveil** | the authority-boundary contract: two runtime callbacks, a lifecycle with fail-closed invariants, trust classes | see `STATUS.md` |
| **CrossAxis** | explicit, versioned capability mapping; a deterministic domain selector with a before/after receipt | minimal in 0.1 |
| **Interplane Probe** | measured capability qualification of an OpenAI-compatible endpoint | see `STATUS.md` |
-| **Conformance** | 23 canonical cases plus 31 dialect fixtures; Rust and Python runners must agree byte for byte | see `STATUS.md` |
+| **Conformance** | 25 canonical cases plus 31 dialect fixtures; Rust and Python runners must agree byte for byte | see `STATUS.md` |
| Vectorveil | the envelope and canonical JSON; no transport framework | envelope only |
| RelayLine | the event vocabulary for multi-round exchanges | contract only |
diff --git a/STATUS.md b/STATUS.md
index a131ebf..bf3986c 100644
--- a/STATUS.md
+++ b/STATUS.md
@@ -7,15 +7,17 @@ byte-identical) · `qualified` (measured against a real model/backend).
| Component | Rust | Python | Fixtures | Notes |
|---|---|---|---|---|
| Core schemas | specified | specified | validated | 10 schemas under spec/schemas, JSON Schema 2020-12 |
-| Core types + validation + JCS | conformant | conformant | 23 cases + digest/jcs-01 | verdict files byte-identical |
+| Core types + validation + JCS | conformant | conformant | 25 cases + digest/jcs-01 | verdict files byte-identical |
| Lenshift openai | conformant | conformant | 8 dialect fixtures | |
| Lenshift qwen35 | conformant, qualified | conformant, qualified | 10 dialect fixtures + real captures | real Qwen3.5-9B captures under qualification/captures |
| Lenshift aien_legacy | tested | tested | 13 dialect fixtures, JCS-identical | aien-cli textual `` JSON (client.rs:381-419); unterminated calls rejected |
| Lenshift ajax | reserved | reserved | none | no official artifact (2026-10-04) |
| CrossAxis mapping + coercion | conformant | conformant | cases 04, 20, 21 | stale-digest refusal |
-| CrossAxis Select (domain_match v1) | tested | tested, qualified | - | receipt: 71 -> 9 tools, 89% fewer first-turn prompt tokens |
-| Crossveil pipeline + mock runtime | conformant | conformant | 23 cases | fails closed on adapter faults |
-| Conformance runner | implemented | implemented | 23/23 both | `--dump` writes canonical results per case |
+| CrossAxis Select (domain_match v1) | tested | tested, qualified | - | receipt: 71 -> 9 tools, 89% fewer first-turn prompt tokens (0.1 measure: rendered bytes + model-reported tokens) |
+| CrossAxis measure units (bytes, tokens_model_reported, tokens_endpoint_tokenizer, tokens_estimated) | tested | tested | schema-validated (selection.schema.json) | not yet qualified: Core ships BytesOnly + EstimatedTokens (estimator v1); live counters belong to the bench runner |
+| CrossAxis expansion v1 (expand + discover, bounded) | conformant | conformant | cases 24, 25 | selections and digests byte-identical across languages; not yet qualified against a live model; never grants authority |
+| Crossveil pipeline + mock runtime | conformant | conformant | 25 cases | fails closed on adapter faults |
+| Conformance runner | implemented | implemented | 25/25 both | `--dump` writes canonical results per case |
| Interplane Probe | qualified | qualified | - | both run live against Qwen3.5-9B/Ollama 0.34.0 with identical verdicts (reports under qualification/reports) |
| AIEN adapter | tested (10 pipeline tests) | - | - | ADR 0003; real aien-mcp SpeculativeLane + aegis gate; aien-cli SafetyEngine not linkable (private); AGPL |
| Odysseus adapter | - | tested (55 tests vs odysseus@2992bf6) | - | executes read_file/ls/glob/grep via Odysseus handlers; AGPL |
diff --git a/conformance/README.md b/conformance/README.md
index 294e388..f0f8922 100644
--- a/conformance/README.md
+++ b/conformance/README.md
@@ -7,7 +7,7 @@ was taken and is listed below.
## Layout
-- `fixtures/NN-slug.json`: the 23 required cases (01-18 core; 19 valid write, 20 missing required argument, 21 stale capability mapping, 22 untrusted tool result, 23 untrusted memory result). `fixtures/digest/jcs-01.json`: the JCS digest check.
+- `fixtures/NN-slug.json`: the 25 required cases (01-18 core; 19 valid write, 20 missing required argument, 21 stale capability mapping, 22 untrusted tool result, 23 untrusted memory result; 24 expansion by requested_excluded, 25 expansion refused by bound). `fixtures/digest/jcs-01.json`: the JCS digest check.
- `../dialects/fixtures/{openai,qwen35}/*.json`: Lenshift parse fixtures.
- `runners/validate_fixtures.py`: checks every envelope and intent against `spec/schemas/`, fixture shape,
runtime-count consistency, the JCS fixture, plus negative controls. Exit status is non-zero on failure.
@@ -32,6 +32,18 @@ was taken and is listed below.
4. `result_digest` is `null` in fixtures: implementations compute it (digest of the canonical result payload
with `provenance.duration_ms` null) and the cross-language comparison covers it.
+## Selection and expansion fixtures (cases 24, 25)
+
+A fixture may carry `selection: {requested_domains, max_capabilities, always_include}`: the runner
+builds the mock catalog and runs `select` before the first step. A step `{"turn": n, "expand":
+{"evidence": {...}, "max_expansions"?, "max_added_per_expansion"?}}` runs `expand` on the current
+selection and does not touch the pipeline. `expected.selections` is the exact selection receipt
+after each expand step, in order (digests included). A verdict row gains a `selections` key only
+for such cases, so rows 01-23 are unchanged. The reference pipeline has no selected-view mapping:
+the `unknown_capability` that motivates a `requested_excluded` expansion is supplied by the harness
+(the step's evidence), not produced by the pipeline. Case 24 then sends the call through the
+pipeline and expects `denied`: visibility is not authority.
+
## Fixture-level `mapping_table`
Absent means `mock-table`. Case 21 sets `"mapping_table": "mock-table-stale"` (same rules, wrong catalog digest), so CrossAxis must refuse with `stale_capability` before any runtime contact.
@@ -72,3 +84,4 @@ array to the fixture's `expected.observed` after setting every `result_digest` t
22. Error messages are now pinned by CORE.md ("Canonical result payload shape"); cases 20 and 21 assert them with `result_checks`. `missing tool name` (item 13) is confirmed by that table.
23. Case 20: the runtime is asked and answers `invalid`, so stage `REJECTED`, decision `invalid`, decide true (CORE.md case table row 20). Case 21: nothing reaches the runtime, so decision null, decide false.
24. Case 22/23 `provenance.trusted` is asserted false (CORE.md: false for the two untrusted levels); case 19 true.
+25. Cases 24-25 (CROSSAXIS.md, Bounded expansion): the selection receipt after each expansion is compared exactly; `validate_fixtures.py` also recomputes `selection_digest` and the `parent_digest` chain independently and validates each receipt against `selection.schema.json`.
diff --git a/conformance/fixtures/24-expansion-requested-excluded.json b/conformance/fixtures/24-expansion-requested-excluded.json
new file mode 100644
index 0000000..23fd9cf
--- /dev/null
+++ b/conformance/fixtures/24-expansion-requested-excluded.json
@@ -0,0 +1,160 @@
+{
+ "case": "24-expansion-requested-excluded",
+ "description": "CrossAxis expansion v1. The selection exposes only email capabilities; the model called write_file, which exists in the catalog but was excluded (an unknown_capability at the selected view, supplied by the harness: the reference pipeline has no selected-view mapping). Evidence requested_excluded adds exactly that capability, the receipt records the round, the evidence digest and parent_digest. Expansion changes only what is rendered: the call still crosses Crossveil and the mock policy denies it.",
+ "limits": {
+ "max_argument_bytes": 65536
+ },
+ "trace_id": "trace-24",
+ "selection": {
+ "requested_domains": [
+ "email"
+ ],
+ "max_capabilities": null,
+ "always_include": []
+ },
+ "steps": [
+ {
+ "turn": 0,
+ "expand": {
+ "evidence": {
+ "kind": "requested_excluded",
+ "name": "write_file"
+ }
+ }
+ },
+ {
+ "turn": 1,
+ "dialect": "openai",
+ "model": "mock-model",
+ "input": {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [
+ {
+ "id": "call_24a",
+ "type": "function",
+ "function": {
+ "name": "write_file",
+ "arguments": "{\"path\": \"/tmp/out.txt\", \"content\": \"hello\"}"
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "expected": {
+ "observed": [
+ {
+ "request_id": "call_24a",
+ "stage": "DENIED",
+ "decision": "denied",
+ "status": "denied",
+ "error_code": "policy_denied",
+ "decide_invoked": true,
+ "execute_invoked": false,
+ "result_digest": null
+ }
+ ],
+ "turns": [
+ {
+ "turn": 1,
+ "outcome": "tool_request",
+ "intents": 1,
+ "rejected": 0,
+ "text": ""
+ }
+ ],
+ "runtime": {
+ "decide_calls": 1,
+ "execute_calls": 0
+ },
+ "result_checks": [
+ {
+ "request_id": "call_24a",
+ "path": "decision.reason",
+ "equals": "mock policy: writes are denied"
+ }
+ ],
+ "selections": [
+ {
+ "catalog_digest": "sha256:58b8ce6dd694fd20945e69dc56fd93cf1e4a1b561afa763cd96a7c2608ac68fc",
+ "excluded": [
+ {
+ "name": "append_note",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "delete_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "fail_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "list_dir",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "read_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "recall_memory",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "slow_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "web_fetch",
+ "reason": "domain_mismatch"
+ }
+ ],
+ "expansions": [
+ {
+ "added": [
+ "write_file"
+ ],
+ "evidence_digest": "sha256:cd01d654288526d06d827984daebedf1a0a6bb3898f387ffda64cb1c2e425117",
+ "reason": "requested_excluded",
+ "refused": [],
+ "round": 1
+ }
+ ],
+ "kind": "selection",
+ "parent_digest": "sha256:be25d914921cb453ae85ebe80aae2e07df1c0b13f33c80b34c5e177efe812061",
+ "requested_domains": [
+ "email"
+ ],
+ "runtime": "mock",
+ "selected": [
+ {
+ "domains": [
+ "email"
+ ],
+ "name": "send_email",
+ "rule_id": "domain:email"
+ },
+ {
+ "domains": [
+ "filesystem"
+ ],
+ "name": "write_file",
+ "rule_id": "expansion:1"
+ }
+ ],
+ "selection_digest": "sha256:57624fe0189cc34b61029c26ac291a27d032e0b6d8f65904f0dc77f9ab3c33e5",
+ "selector": {
+ "expansion": {
+ "max_added_per_expansion": 8,
+ "max_expansions": 2
+ },
+ "name": "domain_match",
+ "version": "1"
+ }
+ }
+ ]
+ }
+}
diff --git a/conformance/fixtures/25-expansion-refused-by-bound.json b/conformance/fixtures/25-expansion-refused-by-bound.json
new file mode 100644
index 0000000..2406930
--- /dev/null
+++ b/conformance/fixtures/25-expansion-refused-by-bound.json
@@ -0,0 +1,266 @@
+{
+ "case": "25-expansion-refused-by-bound",
+ "description": "CrossAxis expansion v1 bounds. max_capabilities=2 with one email capability selected leaves room for one; max_expansions=1. Round 1 (requested_excluded write_file with domain siblings) adds write_file and refuses its four domain siblings with max_capabilities. Round 2 (discovery_hit) is refused in full: web_fetch with max_expansions, nope with not_in_catalog (checked first), send_email with already_selected. Refused rounds are still recorded and count in round numbering, not toward max_expansions.",
+ "limits": {
+ "max_argument_bytes": 65536
+ },
+ "trace_id": "trace-25",
+ "selection": {
+ "requested_domains": [
+ "email"
+ ],
+ "max_capabilities": 2,
+ "always_include": []
+ },
+ "steps": [
+ {
+ "turn": 0,
+ "expand": {
+ "evidence": {
+ "kind": "requested_excluded",
+ "name": "write_file",
+ "include_domain_siblings": true
+ },
+ "max_expansions": 1
+ }
+ },
+ {
+ "turn": 1,
+ "expand": {
+ "evidence": {
+ "kind": "discovery_hit",
+ "query": "fetch",
+ "names": [
+ "web_fetch",
+ "nope",
+ "send_email"
+ ]
+ }
+ }
+ }
+ ],
+ "expected": {
+ "observed": [],
+ "turns": [],
+ "runtime": {
+ "decide_calls": 0,
+ "execute_calls": 0
+ },
+ "selections": [
+ {
+ "catalog_digest": "sha256:58b8ce6dd694fd20945e69dc56fd93cf1e4a1b561afa763cd96a7c2608ac68fc",
+ "excluded": [
+ {
+ "name": "append_note",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "delete_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "fail_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "list_dir",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "read_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "recall_memory",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "slow_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "web_fetch",
+ "reason": "domain_mismatch"
+ }
+ ],
+ "expansions": [
+ {
+ "added": [
+ "write_file"
+ ],
+ "evidence_digest": "sha256:cb902800bea47dc15333a9d7fb5d4c8e77185ddd14e28301d0a4bebf005adb76",
+ "reason": "requested_excluded",
+ "refused": [
+ {
+ "name": "append_note",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "delete_file",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "list_dir",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "read_file",
+ "reason": "max_capabilities"
+ }
+ ],
+ "round": 1
+ }
+ ],
+ "kind": "selection",
+ "parent_digest": "sha256:0ddd0a049dbeb187d16e82cd8c9d67caddefc5edca9c6a610bd23ded2e2329de",
+ "requested_domains": [
+ "email"
+ ],
+ "runtime": "mock",
+ "selected": [
+ {
+ "domains": [
+ "email"
+ ],
+ "name": "send_email",
+ "rule_id": "domain:email"
+ },
+ {
+ "domains": [
+ "filesystem"
+ ],
+ "name": "write_file",
+ "rule_id": "expansion:1"
+ }
+ ],
+ "selection_digest": "sha256:776f329424ed07229b7cc4e040045a89a79fdfaefd75df94d9fc42af5050391f",
+ "selector": {
+ "expansion": {
+ "max_added_per_expansion": 8,
+ "max_expansions": 1
+ },
+ "max_capabilities": 2,
+ "name": "domain_match",
+ "version": "1"
+ }
+ },
+ {
+ "catalog_digest": "sha256:58b8ce6dd694fd20945e69dc56fd93cf1e4a1b561afa763cd96a7c2608ac68fc",
+ "excluded": [
+ {
+ "name": "append_note",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "delete_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "fail_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "list_dir",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "read_file",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "recall_memory",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "slow_tool",
+ "reason": "domain_mismatch"
+ },
+ {
+ "name": "web_fetch",
+ "reason": "domain_mismatch"
+ }
+ ],
+ "expansions": [
+ {
+ "added": [
+ "write_file"
+ ],
+ "evidence_digest": "sha256:cb902800bea47dc15333a9d7fb5d4c8e77185ddd14e28301d0a4bebf005adb76",
+ "reason": "requested_excluded",
+ "refused": [
+ {
+ "name": "append_note",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "delete_file",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "list_dir",
+ "reason": "max_capabilities"
+ },
+ {
+ "name": "read_file",
+ "reason": "max_capabilities"
+ }
+ ],
+ "round": 1
+ },
+ {
+ "added": [],
+ "evidence_digest": "sha256:430a70415cbed34d539256799f7647366f08f93b7e2e298daf630885b32df093",
+ "reason": "discovery_hit",
+ "refused": [
+ {
+ "name": "web_fetch",
+ "reason": "max_expansions"
+ },
+ {
+ "name": "nope",
+ "reason": "not_in_catalog"
+ },
+ {
+ "name": "send_email",
+ "reason": "already_selected"
+ }
+ ],
+ "round": 2
+ }
+ ],
+ "kind": "selection",
+ "parent_digest": "sha256:776f329424ed07229b7cc4e040045a89a79fdfaefd75df94d9fc42af5050391f",
+ "requested_domains": [
+ "email"
+ ],
+ "runtime": "mock",
+ "selected": [
+ {
+ "domains": [
+ "email"
+ ],
+ "name": "send_email",
+ "rule_id": "domain:email"
+ },
+ {
+ "domains": [
+ "filesystem"
+ ],
+ "name": "write_file",
+ "rule_id": "expansion:1"
+ }
+ ],
+ "selection_digest": "sha256:02c309510e03f5dd560005b7926f148128672328286c5d719812f3d2f8c02c8d",
+ "selector": {
+ "expansion": {
+ "max_added_per_expansion": 8,
+ "max_expansions": 1
+ },
+ "max_capabilities": 2,
+ "name": "domain_match",
+ "version": "1"
+ }
+ }
+ ]
+ }
+}
diff --git a/conformance/runners/validate_fixtures.py b/conformance/runners/validate_fixtures.py
index 3b2b28e..405f6ba 100644
--- a/conformance/runners/validate_fixtures.py
+++ b/conformance/runners/validate_fixtures.py
@@ -4,7 +4,7 @@
Exit status is non-zero on any failure. Checks:
* every explicit envelope step validates against envelope.schema.json
* every intent in dialects/fixtures validates against intent.schema.json
- * fixture shape, 18 required cases, filename == case slug
+ * fixture shape, 25 required cases, filename == case slug
* expected.runtime counts agree with the observed records
* the JCS digest fixture recomputes
* negative control: a mutated envelope MUST fail validation
@@ -32,6 +32,7 @@ def validator(name):
Draft202012Validator.check_schema(schemas[name])
return Draft202012Validator(schemas[name], registry=registry, format_checker=FormatChecker())
V_ENV, V_INTENT = validator("envelope.schema.json"), validator("intent.schema.json")
+V_SEL = validator("selection.schema.json")
def check(v, inst, where):
errs = sorted(v.iter_errors(inst), key=lambda e: list(e.absolute_path))
@@ -66,7 +67,8 @@ REQUIRED = {
"05-policy-denial","06-explicit-approval","07-successful-execution","08-execution-error","09-timeout",
"10-multiple-sequential-calls","11-model-continuation","12-unsupported-dialect","13-unsupported-version",
"14-unknown-fields","15-oversized-arguments","16-duplicate-request-ids","17-replay","18-model-retry-after-denial",
- "19-valid-write-request","20-missing-required-argument","21-stale-capability-mapping","22-untrusted-tool-result","23-untrusted-memory-result"}
+ "19-valid-write-request","20-missing-required-argument","21-stale-capability-mapping","22-untrusted-tool-result","23-untrusted-memory-result",
+ "24-expansion-requested-excluded","25-expansion-refused-by-bound"}
OBS_KEYS = ["request_id","stage","decision","status","error_code","decide_invoked","execute_invoked","result_digest"]
n_env = n_cases = 0
neg_done = False
@@ -94,10 +96,24 @@ for p in sorted(glob.glob(os.path.join(FIX, "*.json"))):
if V_ENV.is_valid(bad): fail("negative control: envelope without trace_id unexpectedly valid")
neg_done = True
elif "dialect" in s and "input" in s: pass
+ elif "expand" in s:
+ if "selection" not in f: fail("%s: expand step without a selection block" % name)
+ ev = s["expand"].get("evidence", {})
+ if ev.get("kind") not in ("requested_excluded", "discovery_hit"): fail("%s: bad evidence kind" % name)
else: fail("%s: step %s has neither envelope nor dialect+input" % (name, s.get("turn")))
for c in exp.get("result_checks", []):
if set(c) != {"request_id", "path", "equals"} or c["request_id"] not in {o["request_id"] for o in obs}:
fail("%s: malformed result_check %s" % (name, c))
+ if ("selection" in f) != (name[:2] in ("24", "25")): fail("%s: selection block only in cases 24-25" % name)
+ if "selection" in f:
+ n_exp = sum(1 for s in f["steps"] if "expand" in s)
+ sels = exp.get("selections", [])
+ if len(sels) != n_exp: fail("%s: expected.selections must have one entry per expand step" % name)
+ for i, sel in enumerate(sels):
+ check(V_SEL, sel, "%s selections[%d]" % (name, i))
+ if sel.get("selection_digest") != "sha256:" + hashlib.sha256(jcs({k: v for k, v in sel.items() if k not in ("selection_digest", "measure")}).encode()).hexdigest():
+ fail("%s: selections[%d] selection_digest does not recompute" % (name, i))
+ if i and sel.get("parent_digest") != sels[i - 1].get("selection_digest"): fail("%s: parent_digest chain broken at %d" % (name, i))
if ("mapping_table" in f) != name.startswith("21"): fail("%s: mapping_table present only in case 21" % name)
if name.startswith("21") and f.get("mapping_table") != "mock-table-stale": fail("21: mapping_table must be mock-table-stale")
if name[:2] in ("19", "22", "23", "20", "21"):
diff --git a/python/interplane/conformance.py b/python/interplane/conformance.py
index 8c48264..c5e70e3 100644
--- a/python/interplane/conformance.py
+++ b/python/interplane/conformance.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any, Optional
from .core import Limits, jcs
+from .crossaxis import expand, select
from .crossveil import canonical_result_payload, default_pipeline
@@ -30,7 +31,29 @@ def run_case(case: dict) -> dict:
observed: list = []
results: list = []
turns: list = []
+ selections: list = []
+ sel_spec = case.get("selection")
+ catalog = pipe.runtime.catalog()
+ sel = None
+ if sel_spec is not None:
+ sel, _ = select(
+ catalog,
+ sel_spec.get("requested_domains", []),
+ sel_spec.get("max_capabilities"),
+ sel_spec.get("always_include"),
+ )
for step in case["steps"]:
+ if "expand" in step:
+ ex = step["expand"]
+ sel = expand(
+ sel,
+ catalog,
+ ex["evidence"],
+ ex.get("max_expansions"),
+ ex.get("max_added_per_expansion"),
+ )
+ selections.append(sel.to_dict())
+ continue
if "envelope" in step:
result, record = pipe.admit_envelope(step["envelope"], turn=step.get("turn"))
results.append(result)
@@ -65,6 +88,8 @@ def run_case(case: dict) -> dict:
problems.append(f"observed[{i}].{key}: {got.get(key)!r} != {value!r}")
if "turns" in expected and turns != expected["turns"]:
problems.append(f"turns {turns!r} != {expected['turns']!r}")
+ if "selections" in expected and selections != expected["selections"]:
+ problems.append("selections differ from expected")
if "runtime" in expected and runtime != expected["runtime"]:
problems.append(f"runtime {runtime!r} != {expected['runtime']!r}")
for check in expected.get("result_checks", []):
@@ -81,6 +106,7 @@ def run_case(case: dict) -> dict:
"observed": observed,
"turns": turns,
"runtime": runtime,
+ "selections": selections,
"problems": problems,
"results": [canonical_result_payload(r) for r in results],
}
@@ -111,8 +137,12 @@ def main(argv: Optional[list] = None) -> int:
failed += not v["pass"]
print(f"{len(verdicts) - failed}/{len(verdicts)} passed")
out = {
- k: {f: v[f] for f in ("pass", "observed", "turns", "runtime")} for k, v in verdicts.items()
+ k: {f: v[f] for f in ("pass", "observed", "turns", "runtime", "selections") if f in v}
+ for k, v in verdicts.items()
}
+ for v in out.values():
+ if not v.get("selections"):
+ v.pop("selections", None)
Path(args.out).write_text(jcs(out) + "\n", encoding="utf-8")
return 1 if failed else 0
diff --git a/python/interplane/crossaxis.py b/python/interplane/crossaxis.py
index bdc907e..a3e6b18 100644
--- a/python/interplane/crossaxis.py
+++ b/python/interplane/crossaxis.py
@@ -7,10 +7,11 @@ should this model see?". It never answers "may the model run it?".
import copy
import re
from dataclasses import dataclass, field
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Optional, Protocol
from .core import (
DIGEST_RE,
+ digest,
Catalog,
CapabilityRequest,
ErrorCode,
@@ -205,6 +206,21 @@ def coerce_arguments(args: dict, parameters_schema: Optional[dict]) -> tuple:
return out, coerced
+def _selector(max_capabilities: Optional[int]) -> dict:
+ out: dict = {"name": "domain_match", "version": "1"}
+ if max_capabilities is not None:
+ out["max_capabilities"] = max_capabilities
+ return out
+
+
+def _selected_entry(cap, rule: str) -> dict:
+ """Receipt entry; ``domains`` is omitted when empty (same rule as the Rust implementation)."""
+ entry = {"name": cap.name, "rule_id": rule}
+ if cap.domains:
+ entry["domains"] = list(cap.domains)
+ return entry
+
+
def select(
catalog: Catalog,
requested_domains: list,
@@ -247,13 +263,10 @@ def select(
selection = Selection(
runtime=catalog.runtime,
catalog_digest=catalog.catalog_digest or catalog.computed_digest(),
- selector={"name": "domain_match", "version": "1", "max_capabilities": max_capabilities},
+ selector=_selector(max_capabilities),
requested_domains=list(requested_domains),
- always_include=list(always_include or []),
- selected=[
- {"name": c.name, "rule_id": rule, "domains": list(c.domains or [])}
- for c, rule in chosen
- ],
+ always_include=list(always_include) if always_include else None,
+ selected=[_selected_entry(c, rule) for c, rule in chosen],
excluded=excluded,
)
if renderer is not None:
@@ -272,31 +285,308 @@ def openai_tools_renderer(caps: list) -> list:
]
-def measure(full: list, selected: list, renderer: Callable) -> dict:
- """Before/after rendered size on the same renderer. Tokens are null without a tokenizer."""
- def size(caps: list) -> int:
- rendered = renderer(caps)
- text = rendered if isinstance(rendered, str) else jcs(rendered)
- return len(text.encode("utf-8"))
- return {
+# ---------------------------------------------------------------------------------------------
+# Measurement: rendered bytes and token accounting (spec/CROSSAXIS.md, "Measure")
+# ---------------------------------------------------------------------------------------------
+
+TOKEN_UNITS = ("bytes", "tokens_model_reported", "tokens_endpoint_tokenizer", "tokens_estimated")
+ESTIMATOR_SOURCE = "estimator v1 ceil(utf8_bytes/4)"
+
+
+def _wire_bytes(value: Any) -> int:
+ """Bytes of ``value`` serialized as sent on the wire: canonical JSON (RFC 8785), UTF-8."""
+ text = value if isinstance(value, str) else jcs(value)
+ return len(text.encode("utf-8"))
+
+
+class TokenCounter(Protocol):
+ """Counts one prompt. ``unit`` is one of ``TOKEN_UNITS``; ``source`` is free text for the receipt.
+
+ ``count_prompt(messages, tools)`` returns the size of ``messages`` plus the rendered ``tools``
+ list (``None`` means no tools in the request). A live counter (model-reported
+ ``usage.prompt_tokens`` with max_tokens=1, an endpoint ``/tokenize``) lives in the bench runner
+ and implements this protocol; Core stays offline.
+ """
+
+ unit: str
+ source: str
+
+ def count_prompt(self, messages: list, tools: Optional[list]) -> int: ...
+
+
+class BytesOnly:
+ """Unit ``bytes``: canonical-JSON bytes of ``messages`` plus, when present, of ``tools``."""
+
+ unit = "bytes"
+ source = "canonical json bytes of messages and tools"
+
+ def count_prompt(self, messages: list, tools: Optional[list]) -> int:
+ return _wire_bytes(messages) + (_wire_bytes(tools) if tools is not None else 0)
+
+
+class EstimatedTokens:
+ """Unit ``tokens_estimated``. Estimator v1: ``ceil(utf8_len(jcs(value)) / 4)`` per value.
+
+ A prompt is the estimate for ``messages`` plus, when present, the estimate for ``tools``.
+ Always labelled as an estimate; never mix it with measured counts.
+ """
+
+ unit = "tokens_estimated"
+ source = ESTIMATOR_SOURCE
+
+ @staticmethod
+ def _est(value: Any) -> int:
+ return -(-_wire_bytes(value) // 4)
+
+ def count_prompt(self, messages: list, tools: Optional[list]) -> int:
+ return self._est(messages) + (self._est(tools) if tools is not None else 0)
+
+
+def _pair(value: Any, label: str) -> dict:
+ if not (
+ isinstance(value, dict)
+ and set(value) == {"full", "selected"}
+ and all(isinstance(v, int) and not isinstance(v, bool) and v >= 0 for v in value.values())
+ ):
+ raise ValueError(f"{label} must be {{full, selected}} non-negative integers")
+ return {"full": value["full"], "selected": value["selected"]}
+
+
+def token_block(
+ unit: str,
+ source: str,
+ base_context: int,
+ tool_schema: dict,
+ first_turn_prompt: dict,
+ all_rounds_prompt: Optional[dict] = None,
+ completion: Optional[dict] = None,
+) -> dict:
+ """Assemble ``measure.tokens`` with unit discipline: one unit for every number in the block."""
+ if unit not in TOKEN_UNITS:
+ raise ValueError(f"unit must be one of {TOKEN_UNITS}")
+ if not isinstance(source, str) or not source:
+ raise ValueError("source is required")
+ if not isinstance(base_context, int) or isinstance(base_context, bool) or base_context < 0:
+ raise ValueError("base_context must be a non-negative integer")
+ block = {
+ "unit": unit,
+ "source": source,
+ "base_context": base_context,
+ "tool_schema": _pair(tool_schema, "tool_schema"),
+ "first_turn_prompt": _pair(first_turn_prompt, "first_turn_prompt"),
+ }
+ if all_rounds_prompt is not None:
+ block["all_rounds_prompt"] = _pair(all_rounds_prompt, "all_rounds_prompt")
+ if completion is not None:
+ block["completion"] = _pair(completion, "completion")
+ return block
+
+
+def measure(
+ full: list,
+ selected: list,
+ renderer: Callable,
+ counter: Optional[TokenCounter] = None,
+ messages: Optional[list] = None,
+ all_rounds_prompt: Optional[dict] = None,
+ completion: Optional[dict] = None,
+) -> dict:
+ """Before/after size on the same renderer; the bytes are those of the ``tools`` array as sent.
+
+ Without ``counter`` the block has counts and ``rendered_bytes`` only. With a counter and the
+ base ``messages`` (system + user, as sent), ``tokens`` is filled by prompt differences:
+ ``first_turn_prompt = count(messages, tools)``, ``base_context = count(messages, None)``,
+ ``tool_schema = first_turn_prompt - base_context`` (clamped at 0). ``all_rounds_prompt`` and ``completion``
+ are totals the bench measured in the same unit; they are passed through.
+ """
+ full_r, sel_r = renderer(full), renderer(selected)
+ f_bytes, s_bytes = _wire_bytes(full_r), _wire_bytes(sel_r)
+ out: dict = {
"full_count": len(full),
"selected_count": len(selected),
- "full_rendered_bytes": size(full),
- "selected_rendered_bytes": size(selected),
- "full_tokens": None,
- "selected_tokens": None,
- "tokenizer": None,
+ "full_rendered_bytes": f_bytes,
+ "selected_rendered_bytes": s_bytes,
+ "rendered_bytes": {"full": f_bytes, "selected": s_bytes},
}
+ if counter is not None:
+ if messages is None:
+ raise ValueError("a counter needs the base messages")
+ base = counter.count_prompt(messages, None)
+ first_f = counter.count_prompt(messages, full_r)
+ first_s = counter.count_prompt(messages, sel_r)
+ out["tokens"] = token_block(
+ counter.unit,
+ counter.source,
+ base,
+ {"full": max(first_f - base, 0), "selected": max(first_s - base, 0)},
+ {"full": first_f, "selected": first_s},
+ all_rounds_prompt,
+ completion,
+ )
+ return out
+
+
+# ---------------------------------------------------------------------------------------------
+# Expansion (spec/CROSSAXIS.md, "Bounded expansion"). Changes what is rendered, never authority.
+# ---------------------------------------------------------------------------------------------
+
+DEFAULT_MAX_EXPANSIONS = 2
+DEFAULT_MAX_ADDED_PER_EXPANSION = 8
+DEFAULT_DISCOVER_LIMIT = 8
+
+
+class ExpansionError(Exception):
+ """The evidence or selection is unusable (refusals are recorded in the receipt, not raised)."""
+
+
+def selection_digest(selection: Any) -> str:
+ """Digest of the selection with ``selection_digest`` and ``measure`` removed."""
+ d = selection.to_dict() if hasattr(selection, "to_dict") else copy.deepcopy(selection)
+ d.pop("selection_digest", None)
+ d.pop("measure", None)
+ return digest(d)
+
+
+def _ascii_lower(text: str) -> str:
+ return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in text)
+
+
+def discover(
+ catalog: Catalog, selection: Selection, query: str, limit: int = DEFAULT_DISCOVER_LIMIT
+) -> list:
+ """Names of EXCLUDED capabilities whose name or description contains ``query``.
+
+ ASCII case-insensitive substring; sorted by name; at most ``limit``. ``runtime_disabled``
+ exclusions are never offered. An empty query returns ``[]``. Pure: no state, no I/O.
+ """
+ q = _ascii_lower(query)
+ if not q:
+ return []
+ off = {e["name"] for e in selection.excluded if e.get("reason") != "runtime_disabled"}
+ hits = [
+ c.name
+ for c in catalog.capabilities
+ if c.name in off and (q in _ascii_lower(c.name) or q in _ascii_lower(c.description or ""))
+ ]
+ return sorted(hits)[: max(limit, 0)]
+
+
+def expand(
+ selection: Selection,
+ catalog: Catalog,
+ evidence: dict,
+ max_expansions: Optional[int] = None,
+ max_added_per_expansion: Optional[int] = None,
+) -> Selection:
+ """Bounded evidence-based expansion. Returns a new Selection; the input is not modified.
+
+ ``evidence`` is ``{"kind": "requested_excluded", "name": N, "include_domain_siblings"?: bool}``
+ or ``{"kind": "discovery_hit", "query"?: Q, "names": [..]}``. Bounds recorded in
+ ``selector.expansion`` win over the arguments; the arguments win over the defaults (2 and 8);
+ the effective bounds are recorded. Refusal reasons and their order: spec/CROSSAXIS.md.
+ """
+ if not isinstance(evidence, dict):
+ raise ExpansionError("evidence must be an object")
+ if selection.catalog_digest != (catalog.catalog_digest or catalog.computed_digest()):
+ raise ExpansionError("selection was made against a different catalog")
+ kind = evidence.get("kind")
+ by_name = {c.name: c for c in catalog.capabilities}
+ if kind == "requested_excluded":
+ name = evidence.get("name")
+ if not isinstance(name, str) or not name:
+ raise ExpansionError("requested_excluded needs a name")
+ candidates = [name]
+ if evidence.get("include_domain_siblings") is True and name in by_name:
+ doms = set(by_name[name].domains or [])
+ candidates += sorted(
+ c.name
+ for c in catalog.capabilities
+ if c.name != name and doms.intersection(c.domains or [])
+ )
+ elif kind == "discovery_hit":
+ names = evidence.get("names")
+ if not isinstance(names, list) or not all(isinstance(n, str) for n in names):
+ raise ExpansionError("discovery_hit needs names: [string]")
+ candidates = names
+ else:
+ raise ExpansionError(f"unknown evidence kind: {kind!r}")
+
+ out = Selection.from_dict(selection.to_dict())
+ parent = selection_digest(selection)
+ recorded = out.selector.get("expansion") or {}
+ max_exp = recorded.get("max_expansions", max_expansions)
+ max_add = recorded.get("max_added_per_expansion", max_added_per_expansion)
+ max_exp = DEFAULT_MAX_EXPANSIONS if max_exp is None else max_exp
+ max_add = DEFAULT_MAX_ADDED_PER_EXPANSION if max_add is None else max_add
+ out.selector["expansion"] = {"max_expansions": max_exp, "max_added_per_expansion": max_add}
+
+ log = list(out.extra.get("expansions") or [])
+ used = sum(1 for e in log if e.get("added"))
+ round_no = len(log) + 1
+ selected_names = {e["name"] for e in out.selected}
+ excluded_reason = {e["name"]: e.get("reason") for e in out.excluded}
+ cap = out.selector.get("max_capabilities")
+ added: list = []
+ refused: list = []
+ seen: set = set()
+ for name in candidates:
+ if name in seen:
+ continue
+ seen.add(name)
+ reason = None
+ if name not in by_name:
+ reason = "not_in_catalog"
+ elif name in selected_names:
+ reason = "already_selected"
+ elif excluded_reason.get(name) == "runtime_disabled":
+ reason = "runtime_disabled"
+ elif used >= max_exp:
+ reason = "max_expansions"
+ elif len(added) >= max_add:
+ reason = "max_added_per_expansion"
+ elif cap is not None and len(selected_names) + len(added) >= cap:
+ reason = "max_capabilities"
+ if reason is None:
+ added.append(name)
+ else:
+ refused.append({"name": name, "reason": reason})
+ for name in added:
+ out.selected.append(_selected_entry(by_name[name], f"expansion:{round_no}"))
+ out.excluded = [e for e in out.excluded if e["name"] not in added]
+ log.append(
+ {
+ "round": round_no,
+ "reason": kind,
+ "evidence_digest": digest(evidence),
+ "added": added,
+ "refused": refused,
+ }
+ )
+ out.extra["expansions"] = log
+ out.measure = None
+ out.extra["parent_digest"] = parent
+ out.extra.pop("selection_digest", None)
+ out.extra["selection_digest"] = selection_digest(out)
+ return out
__all__ = [
+ "BytesOnly",
+ "EstimatedTokens",
+ "ExpansionError",
"MappingError",
"MappingTable",
"Rule",
+ "TOKEN_UNITS",
+ "TokenCounter",
"coerce_arguments",
- "select",
+ "discover",
+ "expand",
"measure",
"openai_tools_renderer",
+ "select",
+ "selection_digest",
+ "token_block",
]
diff --git a/python/tests/test_conformance.py b/python/tests/test_conformance.py
index d575f92..3cfb3a2 100644
--- a/python/tests/test_conformance.py
+++ b/python/tests/test_conformance.py
@@ -23,12 +23,15 @@ def test_runner_writes_sorted_verdicts(tmp_path, capsys):
text = out.read_text(encoding="utf-8")
data = json.loads(text)
assert list(data) == sorted(data) and len(data) == len(CASES)
- assert all(
- v["pass"] and set(v) == {"pass", "observed", "runtime", "turns"} for v in data.values()
- )
+ base = {"pass", "observed", "runtime", "turns"}
+ assert all(v["pass"] and set(v) - {"selections"} == base for v in data.values())
+ assert {k for k, v in data.items() if "selections" in v} == {
+ "24-expansion-requested-excluded",
+ "25-expansion-refused-by-bound",
+ }
assert text == jcs(data) + "\n"
assert all(o["result_digest"] for v in data.values() for o in v["observed"])
- assert "18/18" in capsys.readouterr().out or len(CASES) != 18
+ assert "25/25" in capsys.readouterr().out or len(CASES) != 25
@pytest.mark.skipif(not CASES, reason="no conformance fixtures")
diff --git a/python/tests/test_crossaxis.py b/python/tests/test_crossaxis.py
index 7f81714..6dc753c 100644
--- a/python/tests/test_crossaxis.py
+++ b/python/tests/test_crossaxis.py
@@ -1,13 +1,21 @@
import pytest
from interplane.core import ErrorCode, ToolRequest
+from interplane.core import digest, jcs
from interplane.crossaxis import (
+ BytesOnly,
+ EstimatedTokens,
+ ExpansionError,
MappingError,
MappingTable,
coerce_arguments,
+ discover,
+ expand,
measure,
openai_tools_renderer,
select,
+ selection_digest,
+ token_block,
)
from interplane.crossveil import MockRuntime, mock_mapping_table
@@ -185,3 +193,228 @@ def test_mapping_table_catalog_digest_and_messages():
with pytest.raises(MappingError) as e:
table.map(intent(None, "q"))
assert e.value.message == "no mapping for tool: q"
+
+
+# ---- measurement: units and the receipt shape
+
+
+def test_select_receipt_omits_empty_optional_fields():
+ cat = MockRuntime().catalog()
+ sel, _ = select(cat, ["email"])
+ d = sel.to_dict()
+ assert "always_include" not in d and sel.selector == {"name": "domain_match", "version": "1"}
+ assert d["selected"] == [{"name": "send_email", "rule_id": "domain:email", "domains": ["email"]}]
+ sel2, _ = select(cat, [], None, ["fail_tool"])
+ assert sel2.to_dict()["always_include"] == ["fail_tool"]
+
+
+def test_measure_bytes_are_the_wire_bytes_and_no_null_token_fields():
+ cat = MockRuntime().catalog()
+ sel, caps = select(cat, ["email"], renderer=openai_tools_renderer)
+ m = sel.measure
+ assert m["rendered_bytes"] == {
+ "full": len(jcs(openai_tools_renderer(cat.capabilities)).encode()),
+ "selected": len(jcs(openai_tools_renderer(caps)).encode()),
+ }
+ assert m["full_rendered_bytes"] == m["rendered_bytes"]["full"]
+ assert "tokens" not in m and "full_tokens" not in m and "tokenizer" not in m
+
+
+MSGS = [{"role": "system", "content": "s"}, {"role": "user", "content": "find the readme"}]
+
+
+def test_measure_estimated_tokens_exact():
+ cat = MockRuntime().catalog()
+ caps = [cat.get("send_email")]
+ m = measure(cat.capabilities, caps, openai_tools_renderer, EstimatedTokens(), MSGS)
+ t = m["tokens"]
+ est = lambda v: -(-len(jcs(v).encode()) // 4) # noqa: E731
+ base = est(MSGS)
+ assert t["unit"] == "tokens_estimated" and t["source"] == "estimator v1 ceil(utf8_bytes/4)"
+ assert t["base_context"] == base
+ full_t = est(openai_tools_renderer(cat.capabilities))
+ assert t["tool_schema"] == {"full": full_t, "selected": est(openai_tools_renderer(caps))}
+ assert t["first_turn_prompt"]["full"] == base + full_t
+ assert "all_rounds_prompt" not in t and "completion" not in t
+
+
+def test_estimator_and_bytes_parity_constants_match_rust():
+ assert EstimatedTokens().count_prompt([], None) == 1
+ assert BytesOnly().count_prompt([], {}) == 4
+
+
+def test_measure_bytes_counter_and_bench_totals_passthrough():
+ cat = MockRuntime().catalog()
+ m = measure(
+ cat.capabilities,
+ cat.capabilities[:1],
+ openai_tools_renderer,
+ BytesOnly(),
+ MSGS,
+ all_rounds_prompt={"full": 9, "selected": 4},
+ completion={"full": 3, "selected": 2},
+ )
+ t = m["tokens"]
+ assert t["unit"] == "bytes" and t["tool_schema"]["full"] == m["rendered_bytes"]["full"]
+ assert t["all_rounds_prompt"] == {"full": 9, "selected": 4}
+ assert t["completion"] == {"full": 3, "selected": 2}
+
+
+def test_token_block_unit_discipline():
+ ok = dict(
+ source="usage.prompt_tokens max_tokens=1 differential",
+ base_context=10,
+ tool_schema={"full": 5, "selected": 1},
+ first_turn_prompt={"full": 15, "selected": 11},
+ )
+ assert token_block("tokens_model_reported", **ok)["unit"] == "tokens_model_reported"
+ with pytest.raises(ValueError):
+ token_block("tokens", **ok)
+ with pytest.raises(ValueError):
+ token_block("tokens_estimated", **{**ok, "tool_schema": {"full": -1, "selected": 0}})
+ with pytest.raises(ValueError):
+ token_block("tokens_estimated", **{**ok, "source": ""})
+ with pytest.raises(ValueError):
+ measure([], [], lambda c: [], EstimatedTokens()) # a counter needs the base messages
+
+
+# ---- bounded expansion
+
+
+def _email_selection(max_caps=None):
+ cat = MockRuntime().catalog()
+ return cat, select(cat, ["email"], max_caps)[0]
+
+
+def test_expand_requested_excluded_adds_and_chains_digests():
+ cat, sel = _email_selection()
+ before = sel.to_dict()
+ out = expand(sel, cat, {"kind": "requested_excluded", "name": "write_file"})
+ assert sel.to_dict() == before, "input is not modified"
+ assert [e["name"] for e in out.selected] == ["send_email", "write_file"]
+ assert out.selected[1]["rule_id"] == "expansion:1"
+ assert "write_file" not in [e["name"] for e in out.excluded]
+ d = out.to_dict()
+ assert d["expansions"] == [
+ {
+ "round": 1,
+ "reason": "requested_excluded",
+ "evidence_digest": digest({"kind": "requested_excluded", "name": "write_file"}),
+ "added": ["write_file"],
+ "refused": [],
+ }
+ ]
+ assert d["parent_digest"] == selection_digest(sel) and d["selection_digest"] == selection_digest(d)
+ assert d["selector"]["expansion"] == {"max_expansions": 2, "max_added_per_expansion": 8}
+ assert "measure" not in d
+ # deterministic
+ again = expand(sel, cat, {"kind": "requested_excluded", "name": "write_file"})
+ assert jcs(again.to_dict()) == jcs(d)
+ # chaining: second expansion's parent is the first's digest
+ out2 = expand(out, cat, {"kind": "requested_excluded", "name": "read_file"})
+ assert out2.to_dict()["parent_digest"] == d["selection_digest"]
+ assert [x["round"] for x in out2.to_dict()["expansions"]] == [1, 2]
+
+
+def test_expand_drops_stale_measure_and_checks_catalog():
+ cat = MockRuntime().catalog()
+ sel, _ = select(cat, ["email"], renderer=openai_tools_renderer)
+ assert sel.measure is not None
+ out = expand(sel, cat, {"kind": "requested_excluded", "name": "read_file"})
+ assert out.measure is None
+ cat.capabilities.pop()
+ cat.catalog_digest = None
+ with pytest.raises(ExpansionError):
+ expand(sel, cat, {"kind": "requested_excluded", "name": "read_file"})
+
+
+def test_expand_refusal_reasons_and_order():
+ cat, sel = _email_selection(max_caps=2)
+
+ def refused(s, ev, **kw):
+ return expand(s, cat, ev, **kw).to_dict()["expansions"][-1]["refused"]
+
+ ev = {"kind": "discovery_hit", "names": ["nope", "send_email", "read_file", "write_file"]}
+ out = expand(sel, cat, ev)
+ last = out.to_dict()["expansions"][-1]
+ assert last["added"] == ["read_file"] # room for one under max_capabilities=2
+ assert last["refused"] == [
+ {"name": "nope", "reason": "not_in_catalog"},
+ {"name": "send_email", "reason": "already_selected"},
+ {"name": "write_file", "reason": "max_capabilities"},
+ ]
+ # max_added_per_expansion
+ cat2, sel2 = _email_selection()
+ last = expand(
+ sel2, cat2, {"kind": "discovery_hit", "names": ["read_file", "list_dir", "web_fetch"]},
+ max_added_per_expansion=2,
+ ).to_dict()["expansions"][-1]
+ assert last["added"] == ["read_file", "list_dir"]
+ assert last["refused"] == [{"name": "web_fetch", "reason": "max_added_per_expansion"}]
+ # max_expansions: a refused round does not count, but nothing more is added
+ s = sel2
+ for name in ("read_file", "list_dir"):
+ s = expand(s, cat2, {"kind": "requested_excluded", "name": name})
+ assert refused(s, {"kind": "requested_excluded", "name": "web_fetch"}) == [
+ {"name": "web_fetch", "reason": "max_expansions"}
+ ]
+ s2 = expand(s, cat2, {"kind": "requested_excluded", "name": "web_fetch"})
+ assert [e["round"] for e in s2.to_dict()["expansions"]] == [1, 2, 3]
+ assert "web_fetch" not in [e["name"] for e in s2.selected]
+ # recorded bounds win over later arguments
+ assert refused(s, {"kind": "requested_excluded", "name": "web_fetch"}, max_expansions=99) == [
+ {"name": "web_fetch", "reason": "max_expansions"}
+ ]
+
+
+def test_expand_siblings_and_bad_evidence():
+ cat, sel = _email_selection()
+ ev = {"kind": "requested_excluded", "name": "write_file", "include_domain_siblings": True}
+ last = expand(sel, cat, ev).to_dict()["expansions"][-1]
+ assert last["added"] == ["write_file", "append_note", "delete_file", "list_dir", "read_file"]
+ for bad in ({}, {"kind": "x"}, {"kind": "requested_excluded"}, {"kind": "discovery_hit"}):
+ with pytest.raises(ExpansionError):
+ expand(sel, cat, bad)
+
+
+def test_runtime_disabled_is_never_expanded_or_discovered():
+ cat, sel = _email_selection()
+ sel.excluded = [
+ dict(e, reason="runtime_disabled") if e["name"] == "read_file" else e for e in sel.excluded
+ ]
+ assert "read_file" not in discover(cat, sel, "file")
+ last = expand(sel, cat, {"kind": "requested_excluded", "name": "read_file"}).to_dict()
+ assert last["expansions"][-1]["refused"] == [{"name": "read_file", "reason": "runtime_disabled"}]
+
+
+def test_discover_is_ascii_case_insensitive_sorted_capped_and_excluded_only():
+ cat, sel = _email_selection()
+ assert discover(cat, sel, "FILE") == ["delete_file", "read_file", "write_file"]
+ assert discover(cat, sel, "file", limit=2) == ["delete_file", "read_file"]
+ assert discover(cat, sel, "email") == [] # send_email is selected, not excluded
+ assert discover(cat, sel, "") == []
+ assert discover(cat, sel, "fetch") == ["web_fetch"]
+
+
+def test_expanded_capability_is_still_denied_by_the_runtime():
+ from interplane.crossveil import default_pipeline
+
+ pipe = default_pipeline()
+ cat = pipe.runtime.catalog()
+ sel, _ = select(cat, ["email"])
+ out = expand(sel, cat, {"kind": "requested_excluded", "name": "write_file"})
+ assert "write_file" in [e["name"] for e in out.selected]
+ msg = {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "c1",
+ "type": "function",
+ "function": {"name": "write_file", "arguments": '{"path": "/a", "content": "x"}'},
+ }
+ ],
+ }
+ turn = pipe.run_turn("openai", "m", msg, "t", 0)
+ assert [r.status for r in turn.results] == ["denied"]
+ assert pipe.runtime.execute_calls == 0
diff --git a/python/tests/test_schemas.py b/python/tests/test_schemas.py
index e1604b3..79f2139 100644
--- a/python/tests/test_schemas.py
+++ b/python/tests/test_schemas.py
@@ -29,6 +29,8 @@ def run_cases():
pipe = default_pipeline()
results = []
for step in case["steps"]:
+ if "expand" in step:
+ continue
if "envelope" in step:
results.append(pipe.admit_envelope(step["envelope"])[0])
else:
@@ -106,6 +108,31 @@ def test_decisions_capability_requests_catalog_selection_validate():
validate("selection", select(cat, ["filesystem"], 3, ["fail_tool"])[0].to_dict())
+def test_expansion_receipts_and_measure_validate():
+ from interplane.crossaxis import EstimatedTokens, expand, openai_tools_renderer
+
+ cat = default_pipeline().runtime.catalog()
+ sel, caps = select(cat, ["email"], 3, ["fail_tool"], renderer=openai_tools_renderer)
+ validate("selection", sel.to_dict())
+ from interplane.crossaxis import measure
+
+ msgs = [{"role": "user", "content": "hi"}]
+ sel.measure = measure(cat.capabilities, caps, openai_tools_renderer, EstimatedTokens(), msgs)
+ validate("selection", sel.to_dict())
+ out = expand(sel, cat, {"kind": "requested_excluded", "name": "read_file"})
+ out = expand(out, cat, {"kind": "discovery_hit", "names": ["web_fetch", "nope"]})
+ validate("selection", out.to_dict())
+ for path in sorted(CONF.glob("2[45]-*.json")):
+ for s in load(path)["expected"]["selections"]:
+ validate("selection", s)
+ bad = out.to_dict()
+ bad["expansions"][0]["refused"] = [{"name": "x"}]
+ assert errors("selection", bad)
+ bad = sel.to_dict()
+ bad["measure"]["tokens"]["unit"] = "tokens"
+ assert errors("selection", bad)
+
+
def test_envelopes_from_pipeline_validate():
for path in sorted(CONF.glob("*.json")):
for step in load(path)["steps"]:
diff --git a/rust/crates/interplane-conformance/src/lib.rs b/rust/crates/interplane-conformance/src/lib.rs
index a85aa1b..69a084a 100644
--- a/rust/crates/interplane-conformance/src/lib.rs
+++ b/rust/crates/interplane-conformance/src/lib.rs
@@ -3,6 +3,7 @@
use std::path::Path;
use interplane_core::{canonicalize, digest, Limits, RequestLedger};
+use interplane_crossaxis::{expand, select};
use interplane_crossveil::{
mock_mapping_table, MockRuntime, ObservedRecord, Pipeline, RuntimeAuthority,
};
@@ -19,6 +20,8 @@ pub struct CaseRun {
pub execute_calls: u32,
/// Every produced `result` payload, keyed by request id (last one wins), in order.
pub results: Vec,
+ /// The selection receipt after each `expand` step, in order.
+ pub selections: Vec,
}
/// Run one fixture document.
@@ -30,6 +33,27 @@ pub fn run_case(fx: &Value) -> CaseRun {
let mut observed = vec![];
let mut turns = vec![];
let mut results = vec![];
+ let mut selections = vec![];
+ let catalog = rt.catalog();
+ let mut sel = fx.get("selection").map(|spec| {
+ let strings = |k: &str| -> Vec {
+ spec[k]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+ select(
+ &catalog,
+ &strings("requested_domains"),
+ spec["max_capabilities"].as_u64().map(|m| m as usize),
+ &strings("always_include"),
+ )
+ .0
+ });
{
let mut p = Pipeline::new(
DialectRegistry::with_defaults(),
@@ -46,7 +70,24 @@ pub fn run_case(fx: &Value) -> CaseRun {
}
for step in fx["steps"].as_array().cloned().unwrap_or_default() {
let turn = step["turn"].as_u64().unwrap_or(0);
- if let Some(env) = step.get("envelope") {
+ if let Some(ex) = step.get("expand") {
+ if let Some(cur) = sel.take() {
+ let next = expand(
+ &cur,
+ &catalog,
+ &ex["evidence"],
+ ex["max_expansions"].as_u64(),
+ ex["max_added_per_expansion"].as_u64(),
+ );
+ match next {
+ Ok(n) => {
+ selections.push(serde_json::to_value(&n).unwrap_or(Value::Null));
+ sel = Some(n);
+ }
+ Err(e) => selections.push(json!({"error": e.to_string()})),
+ }
+ }
+ } else if let Some(env) = step.get("envelope") {
let (r, o) = p.admit_value(env);
results.push(serde_json::to_value(&r).unwrap_or(Value::Null));
observed.push(o);
@@ -75,6 +116,7 @@ pub fn run_case(fx: &Value) -> CaseRun {
decide_calls: rt.decide_calls,
execute_calls: rt.execute_calls,
results,
+ selections,
}
}
@@ -135,6 +177,11 @@ pub fn compare(fx: &Value, run: &CaseRun) -> Vec {
run.decide_calls, run.execute_calls
));
}
+ if let Some(want) = exp.get("selections") {
+ if want != &Value::Array(run.selections.clone()) {
+ errs.push("selections differ from expected".to_string());
+ }
+ }
for c in exp["result_checks"].as_array().cloned().unwrap_or_default() {
let rid = c["request_id"].as_str().unwrap_or("");
let path = c["path"].as_str().unwrap_or("");
@@ -155,12 +202,16 @@ pub fn compare(fx: &Value, run: &CaseRun) -> Vec {
/// One row of the verdict file.
pub fn verdict(run: &CaseRun, errs: &[String]) -> Value {
- json!({
+ let mut v = json!({
"pass": errs.is_empty(),
"observed": serde_json::to_value(&run.observed).unwrap_or(Value::Null),
"turns": run.turns,
"runtime": {"decide_calls": run.decide_calls, "execute_calls": run.execute_calls},
- })
+ });
+ if !run.selections.is_empty() {
+ v["selections"] = Value::Array(run.selections.clone());
+ }
+ v
}
/// Load `NN-*.json` fixtures (not subdirectories), sorted by file name.
diff --git a/rust/crates/interplane-conformance/tests/fixtures.rs b/rust/crates/interplane-conformance/tests/fixtures.rs
index 3664a1b..c2be2b6 100644
--- a/rust/crates/interplane-conformance/tests/fixtures.rs
+++ b/rust/crates/interplane-conformance/tests/fixtures.rs
@@ -35,3 +35,29 @@ fn verdicts_are_deterministic() {
"digests are stable across runs"
);
}
+
+#[test]
+fn expanded_in_capability_is_still_denied_and_a_changed_selection_is_detected() {
+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../conformance/fixtures");
+ let all = load_fixtures(&dir).unwrap();
+ assert_eq!(all.len(), 25);
+ let mut fx = all
+ .into_iter()
+ .find(|f| f["case"] == "24-expansion-requested-excluded")
+ .unwrap();
+ let run = run_case(&fx);
+ assert_eq!(run.selections.len(), 1);
+ let names: Vec<&str> = run.selections[0]["selected"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|e| e["name"].as_str().unwrap())
+ .collect();
+ assert_eq!(names, ["send_email", "write_file"]);
+ assert_eq!(run.observed.len(), 1);
+ assert_eq!(run.observed[0].status.as_str(), "denied");
+ assert_eq!((run.decide_calls, run.execute_calls), (1, 0));
+ // negative control: a wrong expected selection must be reported.
+ fx["expected"]["selections"][0]["selection_digest"] = serde_json::json!("sha256:00");
+ assert!(!compare(&fx, &run).is_empty());
+}
diff --git a/rust/crates/interplane-core/src/types.rs b/rust/crates/interplane-core/src/types.rs
index 298bbbe..a186809 100644
--- a/rust/crates/interplane-core/src/types.rs
+++ b/rust/crates/interplane-core/src/types.rs
@@ -594,10 +594,37 @@ pub struct SelectorInfo {
pub version: String,
#[serde(default, skip_serializing_if = "is_none")]
pub max_capabilities: Option,
+ /// Expansion bounds, recorded by the first `expand` (spec/CROSSAXIS.md).
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub expansion: Option,
#[serde(flatten)]
pub extensions: Extensions,
}
+/// Bounds recorded in `selector.expansion`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ExpansionBounds {
+ pub max_expansions: u64,
+ pub max_added_per_expansion: u64,
+}
+
+/// A capability refused by an expansion, and why.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct RefusedEntry {
+ pub name: String,
+ pub reason: String,
+}
+
+/// One entry of `selection.expansions[]`.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ExpansionEntry {
+ pub round: u64,
+ pub reason: String,
+ pub evidence_digest: String,
+ pub added: Vec,
+ pub refused: Vec,
+}
+
/// A selected capability.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SelectedEntry {
@@ -618,6 +645,28 @@ pub struct ExcludedEntry {
pub extensions: Extensions,
}
+/// A `{full, selected}` pair of non-negative integers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FullSelected {
+ pub full: u64,
+ pub selected: u64,
+}
+
+/// `measure.tokens`: every number is in `unit`; units are never mixed in one block.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TokenMeasure {
+ /// `bytes`, `tokens_model_reported`, `tokens_endpoint_tokenizer` or `tokens_estimated`.
+ pub unit: String,
+ pub source: String,
+ pub base_context: u64,
+ pub tool_schema: FullSelected,
+ pub first_turn_prompt: FullSelected,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub all_rounds_prompt: Option,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub completion: Option,
+}
+
/// Before/after size of the rendered tool surface.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Measure {
@@ -635,6 +684,10 @@ pub struct Measure {
pub selected_tokens: Option,
#[serde(default, skip_serializing_if = "is_none")]
pub tokenizer: Option,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub rendered_bytes: Option,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub tokens: Option,
#[serde(flatten)]
pub extensions: Extensions,
}
@@ -653,6 +706,12 @@ pub struct Selection {
pub excluded: Vec,
#[serde(default, skip_serializing_if = "is_none")]
pub measure: Option,
+ #[serde(default, skip_serializing_if = "is_empty_vec")]
+ pub expansions: Vec,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub parent_digest: Option,
+ #[serde(default, skip_serializing_if = "is_none")]
+ pub selection_digest: Option,
#[serde(flatten)]
pub extensions: Extensions,
}
diff --git a/rust/crates/interplane-crossaxis/src/lib.rs b/rust/crates/interplane-crossaxis/src/lib.rs
index 5963105..ceea4ce 100644
--- a/rust/crates/interplane-crossaxis/src/lib.rs
+++ b/rust/crates/interplane-crossaxis/src/lib.rs
@@ -2,8 +2,9 @@
//! It never answers "may the model run it?".
use interplane_core::{
canonicalize, CapabilityDescriptor, CapabilityRequest, CapabilityRequestKind, Catalog,
- ErrorCode, ExcludedEntry, MappingInfo, Measure, SelectedEntry, Selection, SelectionKind,
- SelectorInfo, ToolRef, ToolRequest,
+ ErrorCode, ExcludedEntry, ExpansionBounds, ExpansionEntry, FullSelected, MappingInfo, Measure,
+ RefusedEntry, SelectedEntry, Selection, SelectionKind, SelectorInfo, TokenMeasure, ToolRef,
+ ToolRequest,
};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Number, Value};
@@ -233,6 +234,7 @@ pub fn select(
name: "domain_match".into(),
version: "1".into(),
max_capabilities: max_capabilities.map(|m| m as u64),
+ expansion: None,
extensions: Map::new(),
},
requested_domains: requested_domains.to_vec(),
@@ -248,13 +250,86 @@ pub fn select(
.collect(),
excluded,
measure: None,
+ expansions: vec![],
+ parent_digest: None,
+ selection_digest: None,
extensions: Map::new(),
};
(sel, descriptors)
}
+/// Render descriptors as OpenAI-style `tools` entries (the default measuring renderer; the same
+/// shape as the Python `openai_tools_renderer`).
+pub fn openai_tools_renderer(caps: &[CapabilityDescriptor]) -> Value {
+ Value::Array(
+ caps.iter()
+ .map(|c| {
+ serde_json::json!({"type": "function", "function": {
+ "name": c.name, "description": c.description, "parameters": c.parameters}})
+ })
+ .collect(),
+ )
+}
+
+/// Bytes of `v` as sent on the wire: canonical JSON (RFC 8785), UTF-8.
+fn wire_bytes(v: &Value) -> u64 {
+ canonicalize(v).len() as u64
+}
+
+/// The unit values of `measure.tokens.unit`.
+pub const TOKEN_UNITS: [&str; 4] = [
+ "bytes",
+ "tokens_model_reported",
+ "tokens_endpoint_tokenizer",
+ "tokens_estimated",
+];
+/// `source` recorded by [`EstimatedTokens`].
+pub const ESTIMATOR_SOURCE: &str = "estimator v1 ceil(utf8_bytes/4)";
+
+/// Counts one prompt. A live counter (model-reported `usage.prompt_tokens`, an endpoint
+/// `/tokenize`) lives in the bench runner and implements this trait; Core stays offline.
+/// `messages` is the JSON array of messages as sent, `tools` the rendered `tools` array (`None`
+/// means no tools in the request).
+pub trait TokenCounter {
+ /// One of [`TOKEN_UNITS`].
+ fn unit(&self) -> &str;
+ /// Free text recorded in the receipt.
+ fn source(&self) -> &str;
+ fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64;
+}
+
+/// Unit `bytes`: canonical-JSON bytes of `messages` plus, when present, of `tools`.
+pub struct BytesOnly;
+impl TokenCounter for BytesOnly {
+ fn unit(&self) -> &str {
+ "bytes"
+ }
+ fn source(&self) -> &str {
+ "canonical json bytes of messages and tools"
+ }
+ fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64 {
+ wire_bytes(messages) + tools.map_or(0, wire_bytes)
+ }
+}
+
+/// Unit `tokens_estimated`. Estimator v1: `ceil(utf8_len(jcs(value)) / 4)` per value; a prompt is
+/// the estimate for `messages` plus, when present, the estimate for `tools`.
+pub struct EstimatedTokens;
+impl TokenCounter for EstimatedTokens {
+ fn unit(&self) -> &str {
+ "tokens_estimated"
+ }
+ fn source(&self) -> &str {
+ ESTIMATOR_SOURCE
+ }
+ fn count_prompt(&self, messages: &Value, tools: Option<&Value>) -> u64 {
+ let est = |v: &Value| wire_bytes(v).div_ceil(4);
+ est(messages) + tools.map_or(0, est)
+ }
+}
+
/// Fill `selection.measure`: render the full catalog and the selection with the same renderer and
-/// count the canonical-JSON bytes of each rendering.
+/// count the canonical-JSON bytes of each rendering (the bytes of `tools` as sent).
pub fn measure(
selection: &mut Selection,
catalog: &Catalog,
@@ -263,19 +338,300 @@ pub fn measure(
) where
F: Fn(&[CapabilityDescriptor]) -> Value,
{
- let bytes = |caps: &[CapabilityDescriptor]| canonicalize(&render(caps)).len() as u64;
+ measure_tokens(selection, catalog, selected, render, None);
+}
+
+/// Totals the bench measured in the same unit as the counter, passed through into the receipt.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct BenchTotals {
+ pub all_rounds_prompt: Option,
+ pub completion: Option,
+}
+
+/// [`measure`] plus `measure.tokens` when a counter and the base `messages` (system + user, as
+/// sent) are given: `first_turn_prompt = count(messages, tools)`, `base_context = count(messages,
+/// None)`, `tool_schema = first_turn_prompt - base_context`.
+pub fn measure_tokens(
+ selection: &mut Selection,
+ catalog: &Catalog,
+ selected: &[CapabilityDescriptor],
+ render: F,
+ counted: Option<(&dyn TokenCounter, &Value, BenchTotals)>,
+) where
+ F: Fn(&[CapabilityDescriptor]) -> Value,
+{
+ let (full_r, sel_r) = (render(&catalog.capabilities), render(selected));
+ let (f_bytes, s_bytes) = (wire_bytes(&full_r), wire_bytes(&sel_r));
+ let tokens = counted.map(|(counter, messages, totals)| {
+ let base = counter.count_prompt(messages, None);
+ let first = FullSelected {
+ full: counter.count_prompt(messages, Some(&full_r)),
+ selected: counter.count_prompt(messages, Some(&sel_r)),
+ };
+ TokenMeasure {
+ unit: counter.unit().to_string(),
+ source: counter.source().to_string(),
+ base_context: base,
+ tool_schema: FullSelected {
+ full: first.full.saturating_sub(base),
+ selected: first.selected.saturating_sub(base),
+ },
+ first_turn_prompt: first,
+ all_rounds_prompt: totals.all_rounds_prompt,
+ completion: totals.completion,
+ }
+ });
selection.measure = Some(Measure {
full_count: Some(catalog.capabilities.len() as u64),
selected_count: Some(selected.len() as u64),
- full_rendered_bytes: Some(bytes(&catalog.capabilities)),
- selected_rendered_bytes: Some(bytes(selected)),
+ full_rendered_bytes: Some(f_bytes),
+ selected_rendered_bytes: Some(s_bytes),
full_tokens: None,
selected_tokens: None,
tokenizer: None,
+ rendered_bytes: Some(FullSelected {
+ full: f_bytes,
+ selected: s_bytes,
+ }),
+ tokens,
extensions: Map::new(),
});
}
+pub const DEFAULT_MAX_EXPANSIONS: u64 = 2;
+pub const DEFAULT_MAX_ADDED_PER_EXPANSION: u64 = 8;
+pub const DEFAULT_DISCOVER_LIMIT: usize = 8;
+
+/// Evidence for [`expand`].
+#[derive(Debug, Clone, PartialEq)]
+pub enum Evidence {
+ /// The model called a capability that exists in the catalog but is not in the selection.
+ RequestedExcluded {
+ name: String,
+ include_domain_siblings: bool,
+ },
+ /// Names returned by [`discover`] for `query`.
+ DiscoveryHit {
+ query: Option,
+ names: Vec,
+ },
+}
+
+impl Evidence {
+ /// Parse the evidence JSON object (the form hashed into `evidence_digest`).
+ pub fn from_value(v: &Value) -> Result {
+ let bad = |m: &str| ExpansionError(m.to_string());
+ match v.get("kind").and_then(Value::as_str) {
+ Some("requested_excluded") => Ok(Evidence::RequestedExcluded {
+ name: v
+ .get("name")
+ .and_then(Value::as_str)
+ .filter(|n| !n.is_empty())
+ .ok_or_else(|| bad("requested_excluded needs a name"))?
+ .to_string(),
+ include_domain_siblings: v.get("include_domain_siblings")
+ == Some(&Value::Bool(true)),
+ }),
+ Some("discovery_hit") => {
+ let names = v
+ .get("names")
+ .and_then(Value::as_array)
+ .and_then(|a| {
+ a.iter()
+ .map(|n| n.as_str().map(str::to_string))
+ .collect::