From b0619f554c91b127395718c97be2767fb2467048 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 16:36:48 -0500 Subject: [PATCH 1/2] test(conformance): cases 24-25 (expansion by requested_excluded, refused by bound) Runners (both languages) gain an optional selection block and expand steps; verdict rows gain a selections key only for those cases. validate_fixtures.py recomputes selection_digest and the parent chain; CI cross-language expects 25. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 +- conformance/README.md | 15 +- .../24-expansion-requested-excluded.json | 160 +++++++++++ .../25-expansion-refused-by-bound.json | 266 ++++++++++++++++++ conformance/runners/validate_fixtures.py | 20 +- python/interplane/conformance.py | 32 ++- python/tests/test_conformance.py | 11 +- rust/crates/interplane-conformance/src/lib.rs | 57 +++- .../interplane-conformance/tests/fixtures.rs | 26 ++ 9 files changed, 577 insertions(+), 12 deletions(-) create mode 100644 conformance/fixtures/24-expansion-requested-excluded.json create mode 100644 conformance/fixtures/25-expansion-refused-by-bound.json 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/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/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/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()); +} From 8e73ceb431f3a8e3e3150563f2fb478310a5fd62 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 16:36:48 -0500 Subject: [PATCH 2/2] feat(crossaxis): tokenizer-aware selection measurement and bounded capability expansion measure gains rendered_bytes and a unit-disciplined tokens block (TokenCounter, BytesOnly, EstimatedTokens v1); expand/discover add evidence-based bounded expansion with selection_digest/parent_digest. Expansion never grants authority. Receipts normalized across languages (omit-when-empty); Rust mock catalog omits empty required so both mock catalogs share one digest. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 9 +- README.md | 2 +- STATUS.md | 10 +- python/interplane/crossaxis.py | 330 ++++++++++- python/tests/test_crossaxis.py | 233 ++++++++ python/tests/test_schemas.py | 27 + rust/crates/interplane-core/src/types.rs | 59 ++ rust/crates/interplane-crossaxis/src/lib.rs | 589 ++++++++++++++++++- rust/crates/interplane-crossveil/src/mock.rs | 14 +- spec/CROSSAXIS.md | 119 +++- spec/schemas/selection.schema.json | 50 +- 11 files changed, 1401 insertions(+), 41 deletions(-) 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/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_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-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::>>() + }) + .ok_or_else(|| bad("discovery_hit needs names: [string]"))?; + Ok(Evidence::DiscoveryHit { + query: v.get("query").and_then(Value::as_str).map(str::to_string), + names, + }) + } + other => Err(ExpansionError(format!("unknown evidence kind: {other:?}"))), + } + } +} + +/// The evidence or selection is unusable (refusals are recorded in the receipt, not returned). +#[derive(Debug, Clone, PartialEq, Eq, Error)] +#[error("{0}")] +pub struct ExpansionError(pub String); + +/// Digest of the selection with `selection_digest` and `measure` removed. +pub fn selection_digest(sel: &Selection) -> String { + let mut v = serde_json::to_value(sel).unwrap_or(Value::Null); + if let Some(o) = v.as_object_mut() { + o.remove("selection_digest"); + o.remove("measure"); + } + interplane_core::digest(&v) +} + +/// 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 gives `[]`. Pure. +pub fn discover( + catalog: &Catalog, + selection: &Selection, + query: &str, + limit: usize, +) -> Vec { + let q = query.to_ascii_lowercase(); + if q.is_empty() { + return vec![]; + } + let mut hits: Vec = catalog + .capabilities + .iter() + .filter(|c| { + selection + .excluded + .iter() + .any(|e| e.name == c.name && e.reason != "runtime_disabled") + }) + .filter(|c| { + c.name.to_ascii_lowercase().contains(&q) + || c.description.to_ascii_lowercase().contains(&q) + }) + .map(|c| c.name.clone()) + .collect(); + hits.sort(); + hits.truncate(limit); + hits +} + +/// Bounded evidence-based expansion; returns a new selection (the input is untouched). Bounds +/// recorded in `selector.expansion` win over `max_expansions` / `max_added_per_expansion`, which +/// win over the defaults (2 and 8); the effective bounds are recorded. `evidence_json` is the +/// evidence object whose digest goes into the receipt. Refusal reasons and order: spec/CROSSAXIS.md. +pub fn expand( + selection: &Selection, + catalog: &Catalog, + evidence_json: &Value, + max_expansions: Option, + max_added_per_expansion: Option, +) -> Result { + let evidence = Evidence::from_value(evidence_json)?; + let cat_digest = catalog + .catalog_digest + .clone() + .unwrap_or_else(|| catalog.compute_digest()); + if selection.catalog_digest != cat_digest { + return Err(ExpansionError( + "selection was made against a different catalog".into(), + )); + } + let find = |n: &str| catalog.capabilities.iter().find(|c| c.name == n); + let (kind, candidates): (&str, Vec) = match &evidence { + Evidence::RequestedExcluded { + name, + include_domain_siblings, + } => { + let mut c = vec![name.clone()]; + if *include_domain_siblings { + if let Some(cap) = find(name) { + let mut sib: Vec = catalog + .capabilities + .iter() + .filter(|o| { + o.name != *name && o.domains.iter().any(|d| cap.domains.contains(d)) + }) + .map(|o| o.name.clone()) + .collect(); + sib.sort(); + c.extend(sib); + } + } + ("requested_excluded", c) + } + Evidence::DiscoveryHit { names, .. } => ("discovery_hit", names.clone()), + }; + + let mut out = selection.clone(); + let parent = selection_digest(selection); + let rec = out.selector.expansion.clone(); + let max_exp = rec + .as_ref() + .map(|b| b.max_expansions) + .or(max_expansions) + .unwrap_or(DEFAULT_MAX_EXPANSIONS); + let max_add = rec + .as_ref() + .map(|b| b.max_added_per_expansion) + .or(max_added_per_expansion) + .unwrap_or(DEFAULT_MAX_ADDED_PER_EXPANSION); + out.selector.expansion = Some(ExpansionBounds { + max_expansions: max_exp, + max_added_per_expansion: max_add, + }); + + let used = out + .expansions + .iter() + .filter(|e| !e.added.is_empty()) + .count() as u64; + let round = out.expansions.len() as u64 + 1; + let cap_limit = out.selector.max_capabilities; + let mut added: Vec = vec![]; + let mut refused: Vec = vec![]; + let mut seen: Vec<&String> = vec![]; + for name in &candidates { + if seen.contains(&name) { + continue; + } + seen.push(name); + let reason = if find(name).is_none() { + Some("not_in_catalog") + } else if out.selected.iter().any(|e| &e.name == name) { + Some("already_selected") + } else if out + .excluded + .iter() + .any(|e| &e.name == name && e.reason == "runtime_disabled") + { + Some("runtime_disabled") + } else if used >= max_exp { + Some("max_expansions") + } else if added.len() as u64 >= max_add { + Some("max_added_per_expansion") + } else if cap_limit.is_some_and(|m| (out.selected.len() + added.len()) as u64 >= m) { + Some("max_capabilities") + } else { + None + }; + match reason { + None => added.push(name.clone()), + Some(r) => refused.push(RefusedEntry { + name: name.clone(), + reason: r.into(), + }), + } + } + for name in &added { + if let Some(c) = find(name) { + out.selected.push(SelectedEntry { + name: c.name.clone(), + rule_id: format!("expansion:{round}"), + domains: c.domains.clone(), + extensions: Map::new(), + }); + } + } + out.excluded.retain(|e| !added.contains(&e.name)); + out.expansions.push(ExpansionEntry { + round, + reason: kind.into(), + evidence_digest: interplane_core::digest(evidence_json), + added, + refused, + }); + out.measure = None; + out.parent_digest = Some(parent); + out.selection_digest = None; + out.selection_digest = Some(selection_digest(&out)); + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -445,4 +801,225 @@ mod tests { Some(r#"[{"name":"send"}]"#.len() as u64) ); } + + // ---- measurement + fn msgs() -> Value { + json!([{"role":"system","content":"s"},{"role":"user","content":"find the readme"}]) + } + #[test] + fn measure_bytes_are_wire_bytes_and_tokens_are_absent_without_a_counter() { + let cat = catalog(); + let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); + measure(&mut s, &cat, &caps, openai_tools_renderer); + let m = s.measure.clone().unwrap(); + assert_eq!( + m.rendered_bytes.unwrap().full, + canonicalize(&openai_tools_renderer(&cat.capabilities)).len() as u64 + ); + assert_eq!(m.full_rendered_bytes, Some(m.rendered_bytes.unwrap().full)); + assert!(m.tokens.is_none()); + let v = serde_json::to_value(&s).unwrap(); + assert!(v["measure"].get("tokens").is_none() && v["measure"].get("full_tokens").is_none()); + assert!(v.get("always_include").is_none()); + assert_eq!( + v["selector"], + json!({"name": "domain_match", "version": "1"}) + ); + } + #[test] + fn estimated_tokens_exact_and_differential() { + let cat = catalog(); + let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); + let m = msgs(); + measure_tokens( + &mut s, + &cat, + &caps, + openai_tools_renderer, + Some((&EstimatedTokens, &m, BenchTotals::default())), + ); + let t = s.measure.unwrap().tokens.unwrap(); + let est = |v: &Value| (canonicalize(v).len() as u64).div_ceil(4); + assert_eq!( + (t.unit.as_str(), t.source.as_str()), + ("tokens_estimated", ESTIMATOR_SOURCE) + ); + assert_eq!(t.base_context, est(&m)); + let (full_t, sel_t) = ( + est(&openai_tools_renderer(&cat.capabilities)), + est(&openai_tools_renderer(&caps)), + ); + assert_eq!( + (t.tool_schema.full, t.tool_schema.selected), + (full_t, sel_t) + ); + assert_eq!(t.first_turn_prompt.full, t.base_context + full_t); + assert!(TOKEN_UNITS.contains(&"bytes") && t.all_rounds_prompt.is_none()); + // the Python implementation computes the same numbers from the same inputs + assert_eq!(EstimatedTokens.count_prompt(&json!([]), None), 1); + assert_eq!(BytesOnly.count_prompt(&json!([]), Some(&json!({}))), 4); + } + + // ---- expansion + fn email_sel(max: Option) -> (Catalog, Selection) { + let cat = catalog(); + let (s, _) = select(&cat, &["email".to_string()], max, &[]); + (cat, s) + } + fn big() -> Catalog { + let mut c = catalog(); + c.capabilities.push(cap("list", &["filesystem"], json!({}))); + c.capabilities + .push(cap("trash", &["filesystem"], json!({}))); + c + } + fn rx(name: &str) -> Value { + json!({"kind": "requested_excluded", "name": name}) + } + #[test] + fn expand_adds_records_and_chains_digests() { + let (cat, sel) = email_sel(None); + let before = sel.clone(); + let out = expand(&sel, &cat, &rx("write"), None, None).unwrap(); + assert_eq!(sel, before, "input untouched"); + let names: Vec<_> = out.selected.iter().map(|e| e.name.as_str()).collect(); + assert_eq!(names, ["send", "write"]); + assert_eq!(out.selected[1].rule_id, "expansion:1"); + assert!(!out.excluded.iter().any(|e| e.name == "write")); + let e = &out.expansions[0]; + assert_eq!( + (e.round, e.reason.as_str(), e.added.clone()), + (1, "requested_excluded", vec!["write".to_string()]) + ); + assert_eq!(e.evidence_digest, interplane_core::digest(&rx("write"))); + assert_eq!(out.parent_digest, Some(selection_digest(&sel))); + assert_eq!(out.selection_digest, Some(selection_digest(&out))); + assert_eq!( + out.selector.expansion, + Some(ExpansionBounds { + max_expansions: 2, + max_added_per_expansion: 8 + }) + ); + let again = expand(&sel, &cat, &rx("write"), None, None).unwrap(); + assert_eq!( + canonicalize(&serde_json::to_value(&again).unwrap()), + canonicalize(&serde_json::to_value(&out).unwrap()) + ); + let out2 = expand(&out, &cat, &rx("read"), None, None).unwrap(); + assert_eq!(out2.parent_digest, out.selection_digest); + assert_eq!( + out2.expansions.iter().map(|e| e.round).collect::>(), + [1, 2] + ); + } + #[test] + fn expand_drops_measure_and_rejects_a_foreign_catalog_and_bad_evidence() { + let cat = catalog(); + let (mut s, caps) = select(&cat, &["email".to_string()], None, &[]); + measure(&mut s, &cat, &caps, openai_tools_renderer); + assert!(expand(&s, &cat, &rx("read"), None, None) + .unwrap() + .measure + .is_none()); + let mut other = catalog(); + other.capabilities.pop(); + other.catalog_digest = None; + assert!(expand(&s, &other, &rx("read"), None, None).is_err()); + for bad in [ + json!({}), + json!({"kind": "x"}), + json!({"kind": "requested_excluded"}), + json!({"kind": "discovery_hit"}), + ] { + assert!(expand(&s, &cat, &bad, None, None).is_err()); + } + } + #[test] + fn expand_refusal_reasons_and_order() { + let cat = catalog(); + let (_, sel) = email_sel(Some(2)); + let ev = json!({"kind": "discovery_hit", "names": ["nope", "send", "read", "write"]}); + let last = expand(&sel, &cat, &ev, None, None) + .unwrap() + .expansions + .pop() + .unwrap(); + assert_eq!(last.added, ["read"]); + let r: Vec<_> = last + .refused + .iter() + .map(|r| (r.name.as_str(), r.reason.as_str())) + .collect(); + assert_eq!( + r, + [ + ("nope", "not_in_catalog"), + ("send", "already_selected"), + ("write", "max_capabilities") + ] + ); + // max_added_per_expansion + let cat = big(); + let (s2, _) = select(&cat, &["email".to_string()], None, &[]); + let ev = json!({"kind": "discovery_hit", "names": ["read", "list", "trash"]}); + let last = expand(&s2, &cat, &ev, None, Some(2)) + .unwrap() + .expansions + .pop() + .unwrap(); + assert_eq!(last.added, ["read", "list"]); + assert_eq!(last.refused[0].reason, "max_added_per_expansion"); + // max_expansions: refused rounds are recorded, count in numbering, and add nothing + let mut s = s2; + for n in ["read", "list"] { + s = expand(&s, &cat, &rx(n), None, None).unwrap(); + } + let s3 = expand(&s, &cat, &rx("trash"), Some(99), None).unwrap(); + let last = s3.expansions.last().unwrap(); + assert_eq!((last.round, last.added.len()), (3, 0)); + assert_eq!(last.refused[0].reason, "max_expansions"); + assert!( + !s3.selected.iter().any(|e| e.name == "trash"), + "recorded bounds win over arguments" + ); + } + #[test] + fn expand_siblings_runtime_disabled_and_discover() { + let (cat, sel) = email_sel(None); + let ev = + json!({"kind": "requested_excluded", "name": "write", "include_domain_siblings": true}); + let last = expand(&sel, &cat, &ev, None, None) + .unwrap() + .expansions + .pop() + .unwrap(); + assert_eq!(last.added, ["write", "read"]); + let mut dis = sel.clone(); + dis.excluded + .iter_mut() + .find(|e| e.name == "read") + .unwrap() + .reason = "runtime_disabled".into(); + assert!(!discover(&cat, &dis, "d", 8).contains(&"read".to_string())); + let last = expand(&dis, &cat, &rx("read"), None, None) + .unwrap() + .expansions + .pop() + .unwrap(); + assert_eq!(last.refused[0].reason, "runtime_disabled"); + // discover: ASCII case-insensitive over name and description, sorted, capped, excluded only + let cat = big(); + let (s, _) = select(&cat, &["email".to_string()], None, &[]); + assert_eq!( + discover(&cat, &s, "R", 8), + ["bare", "read", "trash", "write"] + ); + assert_eq!( + discover(&cat, &s, "D", 8), + ["bare", "list", "read", "trash", "write"] + ); + assert_eq!(discover(&cat, &s, "d", 2), ["bare", "list"]); + assert!(discover(&cat, &s, "send", 8).is_empty() && discover(&cat, &s, "", 8).is_empty()); + } } diff --git a/rust/crates/interplane-crossveil/src/mock.rs b/rust/crates/interplane-crossveil/src/mock.rs index 037d83e..00088d2 100644 --- a/rust/crates/interplane-crossveil/src/mock.rs +++ b/rust/crates/interplane-crossveil/src/mock.rs @@ -338,10 +338,16 @@ impl RuntimeAuthority for MockRuntime { name: name.into(), }), description: format!("mock capability {}", s.cap), - parameters: json!({"type": "object", "properties": props, "required": req}) - .as_object() - .cloned() - .unwrap_or_default(), + // `required` is omitted when empty: the same parameters object as the + // Python mock, so both languages derive the same catalog digest. + parameters: if req.is_empty() { + json!({"type": "object", "properties": props}) + } else { + json!({"type": "object", "properties": props, "required": req}) + } + .as_object() + .cloned() + .unwrap_or_default(), domains: s.domains.iter().map(|d| d.to_string()).collect(), runtime_effects: None, schema_digest: None, diff --git a/spec/CROSSAXIS.md b/spec/CROSSAXIS.md index 015b159..8c4f435 100644 --- a/spec/CROSSAXIS.md +++ b/spec/CROSSAXIS.md @@ -35,11 +35,124 @@ Domain resolution (what the user asked -> requested domains) is **not** in v0.1 runner takes domains as input. Selecting domains with a classifier or the model itself is a runtime or bench concern; the receipt records whatever was requested. -The `measure` block is filled by rendering the full catalog and the selection with the same -Lenshift renderer and counting bytes (and tokens when a tokenizer is available). That is the -before/after receipt. +The `measure` block is the before/after receipt; see Measure below. Why this is the first killer feature: both real runtimes dump every tool schema into context (Odysseus ~60 function schemas; AIEN CLI a prose list), and small local models get buried. Select is a receipt-producing, deterministic subset. It grants nothing: an excluded capability is simply not rendered, and an included one still crosses Crossveil. + +## Measure (v0.2) + +`selection.measure` is additive; the 0.1 fields (`full_count`, `selected_count`, +`full_rendered_bytes`, `selected_rendered_bytes`) keep their meaning. `full_tokens`, +`selected_tokens` and `tokenizer` are deprecated and are no longer written; readers must still +accept them. + +``` +measure: { + rendered_bytes: {full, selected}, // always present + tokens?: { + unit, // bytes | tokens_model_reported | tokens_endpoint_tokenizer | tokens_estimated + source, // free text: "usage.prompt_tokens max_tokens=1 differential", + // "llama.cpp /tokenize", "estimator v1 ceil(utf8_bytes/4)" + base_context, // prompt size of system + user, no tools + tool_schema: {full, selected}, + first_turn_prompt: {full, selected}, // system + user + tools + all_rounds_prompt?: {full, selected}, // bench total over the whole task + completion?: {full, selected} // bench total + } +} +``` + +**Bytes are wire bytes.** `rendered_bytes` is the UTF-8 length of the canonical JSON (RFC 8785) of +the `tools` array produced by the renderer, which must be the renderer whose output is sent +unchanged (`openai_tools_renderer` for OpenAI-style endpoints: `{"type":"function","function": +{name, description, parameters}}`). A sender that serializes with another JSON writer must say so +in `source`; byte counts then are not comparable. + +**Unit discipline.** Every number inside one `tokens` block is in the block's single `unit`. A +block never mixes units; a bench that has two kinds of counts writes two runs, not one block. +`bytes` is the unit of `BytesOnly` (canonical-JSON bytes of messages plus tools); it exists so a +no-tokenizer run still has the same shape. `tokens_estimated` is always an estimate and is labelled +so by its unit; it must not be compared with measured units. + +**Differential rule.** `first_turn_prompt = count(system+user+tools)`, `base_context = +count(system+user)`, `tool_schema = first_turn_prompt - base_context` (clamped at 0), for +`full` and `selected` alike. Under `tokens_model_reported` the two counts are +`usage.prompt_tokens` of two requests with `max_tokens=1` to the same endpoint with the same +model, system and user messages; the second adds the rendered tools and nothing else. Under +`tokens_endpoint_tokenizer` they are the tokenizer's counts of the same two request bodies. + +**TokenCounter.** Core is stdlib-only and offline. It defines the interface and two offline +counters; live counters (model-reported, endpoint tokenizer) are implemented by the bench runner +against this interface and Core only assembles the receipt. + +- Python: `TokenCounter` protocol with `unit`, `source`, `count_prompt(messages, tools_or_None) -> int`. + Rust: `trait TokenCounter { unit(), source(), count_prompt(&Value, Option<&Value>) -> u64 }`. +- `BytesOnly`: `len(jcs(messages)) + len(jcs(tools))` in UTF-8 bytes (tools term absent for `None`). +- `EstimatedTokens` (estimator v1): for a JSON value `v`, `est(v) = ceil(len(utf8(jcs(v))) / 4)`; + `count_prompt = est(messages) + est(tools)` (second term absent for `None`). + `source = "estimator v1 ceil(utf8_bytes/4)"`. +- `all_rounds_prompt` and `completion` are totals the bench measured in the block's unit; Core + validates shape and non-negativity only. + +## Bounded expansion (v0.2) + +Expansion is an evidence-based, bounded widening of a selection on top of `domain_match` v1. It +is not a semantic router: Core never guesses what the model "meant". It only reacts to evidence. +**Expansion never touches authority.** It changes which descriptors Lenshift renders and nothing +else: every call, expanded-in or not, still crosses Crossveil, where the runtime decides. A +capability added by expansion that the runtime denies is `denied` exactly as before (conformance +case 24). + +`expand(selection, catalog, evidence, max_expansions?, max_added_per_expansion?) -> selection'` +is pure and deterministic: the same catalog, selection and evidence give byte-identical +`selection'`. The input is not modified. If `selection.catalog_digest` is not the catalog's digest +the call fails (nothing is recorded). + +Evidence (a JSON object; `evidence_digest` is its JCS digest): + +1. `{"kind":"requested_excluded","name":N,"include_domain_siblings"?:bool}`. The model called a + capability that exists in the full catalog but was excluded from the current selection + (observable as `unknown_capability` at the selected view). Candidates: `N`, then, only when + `include_domain_siblings` is true, every other capability sharing a domain with `N`, sorted by + name. +2. `{"kind":"discovery_hit","query"?:Q,"names":[..]}`. `names` is the output of `discover`. + Candidates: `names` in the given order, duplicates dropped. + +`discover(catalog, selection, query, limit=8) -> [name]` is pure: ASCII case-insensitive +substring match of `query` against the name or description of EXCLUDED capabilities (excluded +with reason `runtime_disabled` are never offered), sorted by name, at most `limit`; an empty query +gives `[]`. A runtime or bench may expose `discover` to the model as an always-included read-only +tool; Core defines no such tool in any catalog. + +Bounds: `max_expansions` (default 2) and `max_added_per_expansion` (default 8), always within the +selector's `max_capabilities`. The effective bounds are recorded in `selector.expansion` +`{max_expansions, max_added_per_expansion}`; once recorded they win over later arguments, so the +receipt alone determines the result. + +Each candidate is checked in this order and the first failing check is its refusal reason: +`not_in_catalog`, `already_selected`, `runtime_disabled`, `max_expansions` (rounds that added +something already equal `max_expansions`), `max_added_per_expansion`, `max_capabilities` +(selected plus added so far already equal `max_capabilities`). Pinned (`always_include`) entries +may already exceed `max_capabilities`; expansion then adds nothing. + +Every call appends `{round, reason, evidence_digest, added[], refused[{name, reason}]}` to +`selection.expansions[]`, including a call that adds nothing: `round` is the 1-based position in +that list (refused rounds are numbered but do not count toward `max_expansions`). `reason` is the +evidence kind. Added entries are appended to `selected` (rule id `expansion:`, in candidate +order) and removed from `excluded`; the stale `measure` is dropped (the caller measures again). +`selection_digest` is the JCS digest of the selection with `selection_digest` and `measure` +removed; `expand` sets `parent_digest` to that digest of its input and `selection_digest` on its +output. `select` never writes a digest. + +Receipt normalization (both languages): optional fields are omitted when empty (`always_include`, +`selected[].domains`, `selector.max_capabilities` when null). + +Reference API. Python (`interplane.crossaxis`): `measure(full, selected, renderer, counter=None, +messages=None, all_rounds_prompt=None, completion=None)`, `token_block(...)`, +`BytesOnly()`, `EstimatedTokens()`, `discover(catalog, selection, query, limit=8)`, +`expand(selection, catalog, evidence, max_expansions=None, max_added_per_expansion=None)`, +`selection_digest(selection)`. Rust (`interplane_crossaxis`): `measure`, `measure_tokens`, +`openai_tools_renderer`, `discover`, `expand`, `selection_digest`. diff --git a/spec/schemas/selection.schema.json b/spec/schemas/selection.schema.json index 1a72cbb..e10d747 100644 --- a/spec/schemas/selection.schema.json +++ b/spec/schemas/selection.schema.json @@ -12,7 +12,7 @@ "selector": { "type": "object", "required": ["name", "version"], - "properties": {"name": {"type": "string"}, "version": {"type": "string"}, "max_capabilities": {"type": ["integer", "null"], "minimum": 1}}, + "properties": {"name": {"type": "string"}, "version": {"type": "string"}, "max_capabilities": {"type": ["integer", "null"], "minimum": 1}, "expansion": {"$ref": "#/$defs/ExpansionBounds"}}, "additionalProperties": true }, "requested_domains": {"type": "array", "items": {"type": "string"}}, @@ -29,11 +29,57 @@ "selected_rendered_bytes": {"type": "integer", "minimum": 0}, "full_tokens": {"type": ["integer", "null"], "minimum": 0}, "selected_tokens": {"type": ["integer", "null"], "minimum": 0}, - "tokenizer": {"type": ["string", "null"]} + "tokenizer": {"type": ["string", "null"]}, + "rendered_bytes": {"$ref": "#/$defs/FullSelected", "description": "Canonical-JSON bytes of the rendered tools array, exactly as sent."}, + "tokens": {"$ref": "#/$defs/TokenMeasure"} }, "additionalProperties": true }, + "expansions": {"type": "array", "description": "One entry per expansion attempt, in order (CROSSAXIS.md, Bounded expansion).", "items": {"$ref": "#/$defs/Expansion"}}, + "parent_digest": {"$ref": "common.schema.json#/$defs/Digest", "description": "selection_digest of the selection this one was expanded from."}, + "selection_digest": {"$ref": "common.schema.json#/$defs/Digest", "description": "JCS digest of this selection with selection_digest and measure removed. Present on expanded selections."}, "extensions": {"type": "object", "additionalProperties": true} }, + "$defs": { + "FullSelected": { + "type": "object", + "required": ["full", "selected"], + "properties": {"full": {"type": "integer", "minimum": 0}, "selected": {"type": "integer", "minimum": 0}}, + "additionalProperties": false + }, + "TokenMeasure": { + "type": "object", + "description": "Every number in the block is in `unit`; units are never mixed in one block.", + "required": ["unit", "source", "base_context", "tool_schema", "first_turn_prompt"], + "properties": { + "unit": {"enum": ["bytes", "tokens_model_reported", "tokens_endpoint_tokenizer", "tokens_estimated"]}, + "source": {"type": "string", "minLength": 1, "description": "Free text: how the numbers were obtained."}, + "base_context": {"type": "integer", "minimum": 0}, + "tool_schema": {"$ref": "#/$defs/FullSelected"}, + "first_turn_prompt": {"$ref": "#/$defs/FullSelected"}, + "all_rounds_prompt": {"$ref": "#/$defs/FullSelected"}, + "completion": {"$ref": "#/$defs/FullSelected"} + }, + "additionalProperties": false + }, + "ExpansionBounds": { + "type": "object", + "required": ["max_expansions", "max_added_per_expansion"], + "properties": {"max_expansions": {"type": "integer", "minimum": 0}, "max_added_per_expansion": {"type": "integer", "minimum": 0}}, + "additionalProperties": false + }, + "Expansion": { + "type": "object", + "required": ["round", "reason", "evidence_digest", "added", "refused"], + "properties": { + "round": {"type": "integer", "minimum": 1}, + "reason": {"enum": ["requested_excluded", "discovery_hit"]}, + "evidence_digest": {"$ref": "common.schema.json#/$defs/Digest"}, + "added": {"type": "array", "items": {"type": "string"}}, + "refused": {"type": "array", "items": {"type": "object", "required": ["name", "reason"], "properties": {"name": {"type": "string"}, "reason": {"enum": ["not_in_catalog", "already_selected", "runtime_disabled", "max_expansions", "max_added_per_expansion", "max_capabilities"]}}, "additionalProperties": false}} + }, + "additionalProperties": false + } + }, "additionalProperties": true }