diff --git a/pmoves/Makefile b/pmoves/Makefile index 71fbbccc82..d25a75091a 100644 --- a/pmoves/Makefile +++ b/pmoves/Makefile @@ -4288,7 +4288,7 @@ up-cipher-full: cipher-build-pin-check ## Start Cipher Memory with full embeddin .PHONY: cipher-memory-smoke cipher-memory-smoke: ## Smoke test cipher /api/memory POST + search — FAILS if the vector path is dead (requires up-cipher-full) - @# This target previously had two defects, both fixed here. + @# This target previously had three defects, all fixed here. @# @# 1. Its POST body omitted agentId, which memory-routes.ts requires @# ("agentId is required for per-agent scope" -> 400). Under `curl -sf` @@ -4309,34 +4309,17 @@ cipher-memory-smoke: ## Smoke test cipher /api/memory POST + search — FAILS if @# (memory-routes.ts sets score from the vector hit; the lexical @# fallback has no score field at all) @# A missing agentId is a 400, so the payload must carry one. - @echo "Testing cipher /api/memory POST..." - @resp=$$(curl -sf -X POST http://localhost:$${CIPHER_PORT:-8105}/api/memory \ - -H 'Content-Type: application/json' \ - -d '{"content":"PMOVES cipher smoke test","category":"test","tags":["smoke"],"agentId":"cipher-memory-smoke"}' 2>&1) \ - && echo " POST OK: $$resp" \ - || (echo " POST FAILED: $$resp" && exit 1); \ - case "$$resp" in \ - *'"embedding_id":null'*) \ - echo " ✗ POST stored NOTHING in Qdrant — embedding_id is null."; \ - echo " sidecar.embed() returned null, so storeVector() never ran and"; \ - echo " ensureCollection() never fired. Check that TENSORZERO_URL or"; \ - echo " OLLAMA_URL is reachable FROM the cipher container:"; \ - echo " docker exec pmoves-cipher-api-1 node -e 'fetch(process.env.TENSORZERO_URL+\"/health\").then(r=>console.log(r.status))'"; \ - exit 1;; \ - esac - @echo "Testing cipher /api/memory/search..." - @resp=$$(curl -sf "http://localhost:$${CIPHER_PORT:-8105}/api/memory/search?q=cipher&limit=1" 2>&1) \ - && echo " SEARCH OK: $$resp" \ - || (echo " SEARCH FAILED: $$resp" && exit 1); \ - case "$$resp" in \ - *'"score"'*) ;; \ - *) \ - echo " ✗ SEARCH returned lexical-fallback results, not vector hits (no score field)."; \ - echo " Either the query embedding failed or Qdrant returned no points."; \ - echo " Provision the collection with: make -C pmoves qdrant-provision-cipher"; \ - exit 1;; \ - esac - @echo "✔ Cipher memory pipeline smoke passed (vector path live)" + @# + @# 3. Under token enforcement it could not pass at all: it sent no + @# Authorization header (401), and agentId "cipher-memory-smoke" is an + @# identity no bearer resolves to (403 from assertAgentId). Both read as + @# `POST FAILED:` with an empty message, the same symptom as defect 1. + @# + @# The recipe is now tools/cipher_roundtrip_probe.py: it takes the bearer + @# from the env the session sees (cipher_preflight.layered_environ), writes + @# as the agentId auth.ts accepts for it, reads the record back by id, finds + @# it by search, deletes it, and --require-vector keeps checks 1 and 2. + @$(PYTHON) tools/cipher_roundtrip_probe.py --require-vector .PHONY: cipher-health cipher-health: ## Check Cipher Memory health diff --git a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md index 46e64d71f9..c72bab204b 100644 --- a/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md +++ b/pmoves/docs/AGENTS/AGNOTE4482PHI.t1.md @@ -3581,6 +3581,7 @@ VILLAGE RULE: delivery delegated to a delivery-agent body; control and memory ar - `2026-11-05T14:29:15Z` RELEASE `Mavis (mvs_ce8c1e6e34434db1ba42d3b822ecbd15)` branch: `fix/house-ci-defect-closure` · scope: House CI defect closure lane, PR 2 of 2 -- RELEASE, disposition COMPLETE and VERIFIED. Closes the lane opened by the CLAIM on branch fix/house-ci-defect-closure. (F4) integrations-ghcr.yml resolved a fork-backed entry's build context with "git clone --depth=1 --branch $cfg_ref", a MOVING ref, so the published image was not reproducible from the repository state: two runs a week apart produced two different artifacts under the same tag, and no commit in PMOVES.AI named what was built. PMOVES.AI already records the answer for every fork it tracks as a submodule -- the gitlink -- and build-images.yml already builds from those pins (submodules: recursive, builds github.workspace/); this lane did not. FIX: pmoves/tools/resolve_recorded_pin.py turns the fork URL into the recorded commit, and BOTH lanes that clone a fork now check it out detached; the release-tracked entries keep their own resolver, which still runs last and still wins. The resolver's exit codes are a contract and the workflow step honours them: 0 resolved, 3 not tracked (nothing is recorded, so the branch ref is the only source), 4 ambiguous, 5 declared-but-unrecorded, 6 unreadable -- and 4, 5 and 6 FAIL the step, because a build that resolves a different commit than the recorded one IS the defect. A CORRECTION TO THE ORIGINAL DISCLOSURE: the review said "8 of 21 repo-backed image-matrix entries build from a branch tip". The NUMBER re-measured exactly -- 8 of 21 have a recorded gitlink that differs from the tip of the branch their ref: names -- but the SENTENCE did not. build-images.yml, the workflow that publishes those 21, checks out with submodules: recursive and builds github.workspace/, which IS the recorded commit: git ls-tree HEAD PMOVES-Open-Notebook and the submodule worktree's HEAD are the same commit (f1edc07380946c9a464991123ec94581e83e3703). The branch clone lives in integrations-ghcr.yml, a DIFFERENT publisher with a narrower population. The number survived; the sentence did not. (F5) PMOVES-HiRAG was repaired IN THE FORK through the fork's own PR rule (gh pr merge --merge --admin, NEVER squash, because squashing severs the shared upstream history and every future sync re-conflicts): fork PR #5, base PMOVES.AI-Edition-Hardened, merged 2026-11-05 as a 2-parent merge commit 03d6134b5ebbd7820a971a6fd0ae690e95954ac2 (parents 8e5283a and 189b7e2), ahead_by=2 and behind_by=0 against the old pin 8e5283a -- a clean fast-forward, so nothing was dropped. THE REPAIR: the "from hirag import HiRAG" ImportError is fixed by SPLITTING the import (cohere_* from ._llm, the other 13 moved names from ._llm_backup -- no duplication, and no upstream file edited); the readme case collision is fixed by keeping the fork's revision as README.md and deleting the lowercase readme.md, so the submodule is CLEAN at the merge commit and the permanent dirty state is gone; config.yaml's unterminated quote is closed and the image build now PARSES it, so an unparseable config fails the build instead of a consumer; and the fork's Dockerfile now runs "from hirag import HiRAG, QueryParam" and "yaml.safe_load(open('config.yaml'))" during the image build. The gitlink is promoted from 8e5283a to 03d6134b. REPORTED, NOT FIXED: eval/eval_mhqa.py reads a DIFFERENT config schema than config.yaml provides (config['glm']['url'] against base_url, and it expects an nvidia section that does not exist) -- KeyError: 'url' at line 34. Fixing it is a deeper contract decision about which side is authoritative, so it was left alone and RECORDED in the fork's Dockerfile and in the fork PR body, where the next reader of that repository will find it. (F6) merging this lane's two LEARNINGS files rebuilt the "What shipped" table with a FOUR-column header over THREE-column rows; every COUNT in the table was still correct, so all of the measurement gates PASSED and the lane did not notice -- a REVIEWER reading the rendered table did, and the same defect had ALREADY been fixed once in this lane for exactly the same reason, which is what says the missing thing was a GATE and not more care. FIX: the taxonomy gate now recomputes the table's SHAPE the way it recomputes its counts -- the header declares the column count and every row must carry exactly that many cells, and the separator row's shape is checked too -- and a mutation harness puts the four-column header back, makes a row carry one cell too many, and replaces the separator with a content row; each is proven to kill a NAMED test. (F7) the resolver was exercised only against SYNTHETIC fixtures, so nothing had asked what the integration matrix actually contains -- and the matrix is what decides which artifacts get published. FIX: the gate now drives the REAL resolver over the REAL .github/workflows/integrations-ghcr.matrix.json and asserts every entry lands in exactly one of the two HONEST outcomes (one recorded pin, or honestly not tracked, cross-checked against .gitmodules), with BOTH branches exercised on the real population, because a branch that never runs asserts nothing. A fork tracked twice with disagreeing pins makes the resolver report AMBIGUOUS and fail the PUBLISH lane, and the first sign of that would be a red publish run on main with the artifact due. The gate also asserts that the .gitmodules map and the tree describe the SAME set of submodules -- every declared path has a gitlink and every gitlink has a declaration -- so the missing set is empty and the stricter exit-5 contract changes nothing for the real tree. (F8) pmoves/pyproject.toml declares requires-python ">=3.11" and the house's CI gates run CPython 3.11.17, while a developer workstation runs 3.12 or 3.13. PEP 701 (3.12) allows a BACKSLASH inside an f-string's expression part and 3.11 makes it a SyntaxError, so a gate file in this lane could not even be IMPORTED by the interpreter CI runs. FIX: the pattern is hoisted out of the f-string. The house ALREADY GATES this class -- pmoves/tools/windows_encoding_ratchet.py parses every file with the CI's own interpreter and failed on exactly this -- but it reported it as an "INSTRUMENT ERROR ... cannot parse as Python", which reads like a ratchet defect rather than a code defect, so the DIAGNOSTIC is the part that wanted improving. (F9) the review round on PR #3456 raised SIX findings, all fixed and all gated. P2: the workflow's paths: filter omitted the PIN's own inputs, so advancing a pin would not re-publish and the published image would stay on the previous commit with nothing red -- FIX: .gitmodules, the resolver and the fork-backed submodule paths are now in BOTH push.paths and pull_request.paths, and the required set is DERIVED from the real matrix and the real tree by the gate. P2: a declared-but-unrecorded submodule fell back to a recorded SIBLING and exited 0, contradicting the documented exit-5 contract -- FIX: a non-empty missing set now fails closed with exit 5. Suggestion: the scp-like url git@host:org/repo could not be reduced to /, so the fork read as NOT TRACKED, which authorises the moving branch -- FIX: the scp-like form is reduced, matched by shape. Suggestion: except LookupError around the resolution turned any stray KeyError into exit 3 -- FIX: a dedicated NotTrackedError, so a real LookupError crashes loudly. Nitpick: an unused import shutil -- removed. Nitpick: a dead exit_code parameter whose docstring described a mechanism that did not exist -- removed, and the docstring now points at the real one. GATES: pmoves/tests/tools/test_resolve_recorded_pin.py (18 behavioural tests + 9 mutation kills), pmoves/tests/tools/test_house_ci_defect_closure_learnings_taxonomy.py (11 behavioural tests + 3 mutation kills), pmoves/tests/tools/test_house_ci_defect_closure_register_provenance.py (13 behavioural tests + 4 mutation kills), and the first PR's gates (test_app_pr_approve_guard.py 6 + 6 mutation kills, test_deploy_gateway_agent_env.py 2, test_deploy_gateway_agent_change_gate.py 8, test_deploy_gateway_agent_mutation_kill.py shared) -- 58 behavioural test functions and 30 mutation kills across the lane's six gates, RECOMPUTED by the gate rather than asserted. Every mutation kill is proven against a NAMED test, and the kill signal is pytest's own short summary naming that test. LEARNINGS: pmoves/docs/AGENTS/house_ci_defect_closure_LEARNINGS.md -- 30 lessons in the house's 4-bucket / 5-class taxonomy (reasoning-gap 10, semantic-naming drift 3, contract-correctness 12, defense-in-depth 3, pattern-conformance 2), with the bucket summary, the per-suite counts AND the table's shape all recomputed by the gate. MERGE: PR #3456 @ 3e1c29368b77649fd0ef5a70672494b712b54b62. (F10) the lane's OWN RELEASE row was reviewed on 2026-11-05 by kilo-code-bot, and the finding was CORRECT: the row confessed that the trail payload was UNSIGNED while citing a trail log that the repository's IGNORE RULES EXCLUDE, so the row's only provenance artifact was a receipt that did not exist for anyone reading the repository the row is filed in -- and the row asserted that no signing key was available without recording WHICH check was run, while pmoves/tools/sign_trail.py's _resolve_chit_passphrase consults FIVE sources, not the four environment variables the row's wording implied. THE REGISTER HAD ALREADY ADJUDICATED THIS CLASS: the 2026-08-09 5090-CLAUDE row recorded that the passphrase IS present in that node's shared env, that the register's unsigned-local disclaimers are "a process gap, not a material gap", and that sessions should attempt sign-trail before writing the disclaimer. FIX: the trail was re-emitted and its payload is COMMITTED at a TRACKED path, so the receipt travels with the repository this row is filed in; the key availability is recorded as a MEASUREMENT over all five resolver sources rather than asserted as a fact about the world; the precedent is cited so the next session does not inherit the process gap a third time; and the row's signature state is now checked against the artifact's ACTUAL state by a gate, so a row that claims a signature over an unsigned payload -- or that cites an artifact outside the tree -- cannot be filed. ACK (claim -> work -> sign -> release): the completion trail was emitted by "make -C pmoves sign-trail AGENT=minimax PHASE=release" -- agent_id minimax, display_name MiniMax, glyph U+2B21, colour #7C3AED, accent #A78BFA, voice dimensional, phase release. The identity RESOLVED from pmoves/config/agent_signatures.yaml, so this is the REGISTERED identity and not the fallback presentation AGENTS.md warns about. trail_artifact: pmoves/docs/logs/graphiti_signed_house_ci_defect_closure_release_2026-11-06.json; trail_agent_id: minimax; trail_timestamp: 2026-11-06T05:49:32.185538+00:00; trail_signature_state: UNSIGNED; chit_key_probe: ALL FIVE sources of sign_trail.py's _resolve_chit_passphrase were checked on this host -- CHIT_SIGNING_KEY, CHIT_PASSPHRASE, CHIT_SIGNING_KEY_FILE, CHIT_PASSPHRASE_FILE, and the pmoves/env.tier-* scan -- and NONE yields a passphrase; the probe is a recorded CHECK, not an assertion about the world. The artifact is COMMITTED rather than left as a local log, so a later session can verify the receipt without trusting the row. The payload carries no sig block, so trail_signature_state is UNSIGNED and this is a PRESENTATION trail, not a cryptographic one -- re-signing with the house's key adds the HMAC. The node that holds the key, pmoves-5090, is ONLINE on the tailnet at 100.73.74.3 but refuses non-interactive SSH from this host (publickey, keyboard-interactive), so the receipt cannot be produced from here. ADVISORY WARNINGS the tool itself emitted, disclosed rather than hidden: there is no active signing card for agent_id=minimax, so the payload carries no signing_card_id; and the registered voice dimensional is outside the voice enum of pmoves/contracts/schemas/agent-graphiti/signature.v1.schema.json (voice is not a required field, so the payload is still schema-valid). Both are pre-existing house-config gaps and were NOT fixed in this lane. - `2026-11-06T16:10:01Z` NOTE `pmoves-hermes-elder` · scope: WAVE-ZERO lane 0a retroactively recorded (merge-wave authority: operator grant, board #403, word received 2026-11-06 board #409): three squash merges proven commit-level — PR #3394 actions/checkout 4→7 = 91489608abf4 @ 2026-11-06T13:18:43Z · PR #3393 actions/github-script 7.1.0→9.0.0 = 42239266098f @ 2026-11-06T14:02:30Z · PR #3395 actions/upload-artifact 4→7 = 7c64caaad47f @ 2026-11-06T14:42:21Z; main tip 7c64caaad47f, parents=1 ×3 (linear held), verified:true ×3, CLI-only squash, zero ruleset refusals. Rows filed retroactively — lane executed 13:18–14:42Z before this register write (disclosure per provenance doctrine). Also closes this identity's CLAIM of 2026-10-14T15:38:48Z (fix/amd-overlay-resets-runtime, TTL expired 2026-10-15): expired unreleased, no work delivered. - `2026-11-06T16:10:01Z` CLAIM `pmoves-hermes-elder` branch: `docs/register-wave-zero-1106` · **TTL 48h (expires `2026-11-08T16:10:01Z`)** · scope: WAVE-ZERO 0b execution lane per operator grant (board #403/#409): 0b-dep bot group-bumps PR #3391, #3413, #3435, #3436 then 0b-human per fresh census (per-PR treadmill: update → CI green → approve → squash merge; house subject `(#N)` appended at merge). Exclusions: PR #3420 (approval machinery — human-eyes) regardless of bucketing; DIRTY-bucket PRs out of automation scope. This PR carries the rows and takes its own treadmill before any 0b merge verb; if another register-carrying PR merges mid-treadmill, tail-union rebase per corpus stacked-merge cascade (zero rows lost), never blind update-branch. +- `2026-11-06T18:01:06Z` CLAIM `Z890-CLAUDE` branch: `fix/cipher-fleet-wiring-revival` · **TTL 48h (expires `2026-11-08T18:01:06Z`)** · scope: Revive #3078 cipher topic: authenticated cipher write-read round-trip probe + authenticated cipher-memory-smoke + mcp.json cipher-local note - `2026-11-06T18:10:32Z` CLAIM `Z890-CLAUDE` branch: `fix/launcher-env-allowlist-revival` · **TTL 72h (expires `2026-11-09T18:10:32Z`)** · scope: Launchers stop exporting all of env.shared into agent sessions: derive the allowlist (active MCP refs + named implicit reads - blocklist) in pmoves/tools/launcher_env_allowlist.py; claude-pmoves.sh/.ps1 export only it (launcher road). Revives ef8ef5e46 from #3078. - `2026-11-06T18:24:55Z` RELEASE `Z890-CLAUDE` branch: `fix/env-shared-pinned-leak-guards` · scope: #3459 merged 50a223b3d; z890: env-shared-pinned-check found SSL_CERT_FILE (dead miniconda path) + 3 CA keys absent; env-shared-repair reset all 4; check clean; installed claude-pmoves dry run has no ca-bundle WARN - `2026-11-06T17:41:05Z` CLAIM `5090-CLAUDE` branch: `docs/5090-runbook-surfaces-2026-11-06` · **TTL 48h (expires `2026-11-08T17:41:05Z`)** · scope: Refresh four operator surfaces that the 2026-11-06 5090 funnel rerun and sitrep measured stale. Docs only, no code. (1) pmoves/docs/operations/COMPLETE_BRING_UP_RUNBOOK.md Phase 2-3: every command is bare `make` from the repo root (the AGENTS.md -C trap); Phase 2 names a bootstrap make target that does not exist (env-setup is the real one); Phase 3 step 4 gives no way to verify the ledger, which is why `supabase-bootstrap` never ran on 5090 and public.pmoves_bootstrap_history is absent; the Kong health curl answers 401 without an apikey; auth-check defaults to the CLI port and reports a false FAIL under SUPABASE_RUNTIME=compose; env.tier-ui is not written by the funnel sync (supa-env-fix-tier-ui is), which is the standing pmoves-ui database Unauthorized on 5090. (2) .claude/commands/db/migrate.md is written entirely against the Supabase CLI (`supabase db push`, schema_migrations) and never names the PMOVES ledger or `make -C pmoves supabase-bootstrap`, so a status check there reads clean while the ledger is missing. (3) .claude/skills/node-5090-sitrep/SKILL.md probe paths: Ultimate-TTS-Studio answers on :7862 not :7860, TensorZero on /health not /, Hi-RAG :8086 on / only (measured 2026-11-06: 7860 refused, 7862 200, 3030/ 404, 3030/health 200, 8086/ 200, 8086/health 404) so the sitrep stops reporting false DOWN. (4) .claude/commands/deploy/secrets-funnel.md says plain secrets-funnel is the only correct way; add the Pattern B branch: a node holding a CI-pulled CHIT bundle (make -C pmoves chit-provenance-check) must use secrets-funnel-from-prod or secrets-funnel-sync-from-bundle because chit-export refuses by design (SECRETS_DISTRIBUTION_PATTERNS.md Pattern B). Validation: validate_command_anchors must show 0 new findings and fewer ghosts than baseline. Delivery corrections measured in-lane: the 7862 listener is the Docker ultimate-tts-studio container and native Pinokio UTS is DOWN on 5090 (sitrep now fingerprints 7860-7869 and reports container ports separately); the UI recreate target is up-ui; auth-check must be pointed at the GoTrue loopback health URL because the checker sends no apikey. Not taken, separate lanes: mk/codex.mk CODEX_PY runnability probe; scripts/create_venv.sh foreign-platform venv guard; auth-check compose-port code change; the Supabase boot-user provisioning on 5090 (operator). Worktree ../PMOVES-5090-runbook-surfaces. Bodies: 5090-CLAUDE coordinating; delivery delegated to delivery-agent; review to code-review. diff --git a/pmoves/tests/make/test_cipher_collection_provisioned.py b/pmoves/tests/make/test_cipher_collection_provisioned.py index 339c49dafc..52a1e4e051 100644 --- a/pmoves/tests/make/test_cipher_collection_provisioned.py +++ b/pmoves/tests/make/test_cipher_collection_provisioned.py @@ -32,6 +32,9 @@ provisioner, so a fresh node gets the collection without a manual step. 4. `cipher-memory-smoke` asserts on `embedding_id` and `score` rather than on curl's exit status alone — otherwise it passes with the vector path dead. + When the recipe delegates to `tools/cipher_roundtrip_probe.py`, it must pass + `--require-vector` and the probe must carry those checks. Comment lines in + the recipe do not count. 5. Non-vacuity: `embedding.ts` still gates `storeVector` behind `embed()`, and still writes the named vectors this provisioner creates. If the sidecar is ever changed to provision eagerly, assertions 1-3 stop guarding anything and @@ -116,10 +119,30 @@ def test_cipher_bringup_roads_provision_the_collection(): ) +ROUNDTRIP_PROBE = PMOVES / "tools" / "cipher_roundtrip_probe.py" + + +def _executable(recipe: str) -> str: + """Drop `@#` comment lines: prose about a check is not the check.""" + return "\n".join( + line for line in recipe.splitlines() if not line.lstrip("\t @-+").startswith("#") + ) + + def test_smoke_fails_when_the_vector_path_is_dead(): - recipe = _recipe("cipher-memory-smoke") + recipe = _executable(_recipe("cipher-memory-smoke")) # Both endpoints answer 2xx off the lexical fallback with Qdrant absent, so # exit-status-only assertions pass on a dead pipeline. + if ROUNDTRIP_PROBE.name in recipe: + # The recipe delegates to the authenticated round-trip probe. The two + # vector checks then live in the probe and are only armed by the flag; + # its behaviour is covered by tests/tools/test_cipher_roundtrip_probe.py + # (test_require_vector_fails_on_the_lexical_fallback_only). + assert "--require-vector" in recipe, ( + "cipher-memory-smoke must run cipher_roundtrip_probe.py with " + "--require-vector, or a lexical-fallback round trip passes" + ) + recipe = ROUNDTRIP_PROBE.read_text(encoding="utf-8") assert "embedding_id" in recipe, ( "cipher-memory-smoke must assert POST returned a non-null embedding_id" ) diff --git a/pmoves/tests/tools/test_cipher_roundtrip_probe.py b/pmoves/tests/tools/test_cipher_roundtrip_probe.py new file mode 100644 index 0000000000..4c9d3484c6 --- /dev/null +++ b/pmoves/tests/tools/test_cipher_roundtrip_probe.py @@ -0,0 +1,289 @@ +"""Offline tests for the authenticated cipher write->read round-trip probe. + +The network seam (`_urlopen`) is replaced by an in-process fake cipher that +enforces the same rules as memory-routes.ts + auth.ts: no bearer -> 401 when the +server holds a token, wrong agentId for the bearer -> 403. Nothing here touches +a live cipher or the node's real env.shared. +""" + +from __future__ import annotations + +import importlib.util +import io +import json +import re +import sys +import urllib.error +import urllib.parse +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[3] +MODULE = REPO_ROOT / "pmoves" / "tools" / "cipher_roundtrip_probe.py" +MAKEFILE = REPO_ROOT / "pmoves" / "Makefile" + +spec = importlib.util.spec_from_file_location("cipher_roundtrip_probe", MODULE) +assert spec and spec.loader +rp = importlib.util.module_from_spec(spec) +sys.modules["cipher_roundtrip_probe"] = rp +spec.loader.exec_module(rp) + +# Fake credentials only. Neither is, nor resembles, a real token. +BOOT_TOKEN = "test-bootstrap-token-not-real" +MINTED_TOKEN = "cipher_00000000-0000-4000-8000-00000000test" + + +@pytest.fixture(autouse=True) +def _isolated(tmp_path_factory, monkeypatch): + """No real env.shared, no inherited identity/token, and no real network.""" + absent = tmp_path_factory.mktemp("no-env") / "env.shared.absent" + monkeypatch.setenv("PMOVES_ENV_SHARED", str(absent)) + for name in ("CIPHER_API_TOKEN", "PMOVES_RESOLVED_IDENTITY", "PMOVES_NODE_IDENTITY", "CIPHER_PORT"): + monkeypatch.delenv(name, raising=False) + + def _guard(*_a, **_k): + raise AssertionError("test reached the real network seam") + + monkeypatch.setattr(rp, "_urlopen", _guard) + + +class _Resp: + def __init__(self, status: int, body=None): + self.status = status + self._raw = b"" if body is None else json.dumps(body).encode("utf-8") + + def read(self): + return self._raw + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +class FakeCipher: + """Just enough of memory-routes.ts to exercise the probe.""" + + def __init__(self, token_agent: dict | None = None, embed: bool = True, + score: bool = True, corrupt_read: bool = False, search_hides: bool = False): + # bearer -> agent it resolves to; None means the server enforces nothing + self.token_agent = token_agent + self.embed, self.score = embed, score + self.corrupt_read, self.search_hides = corrupt_read, search_hides + self.store: dict = {} + self.calls: list = [] + self.auth_headers: list = [] + + def _err(self, url, code, message): + body = io.BytesIO(json.dumps({"error": message}).encode("utf-8")) + return urllib.error.HTTPError(url, code, message, {}, body) + + def __call__(self, req, timeout): + url = req.full_url + parsed = urllib.parse.urlsplit(url) + query = dict(urllib.parse.parse_qsl(parsed.query)) + method = req.get_method() + self.calls.append((method, parsed.path)) + auth = req.get_header("Authorization") + self.auth_headers.append(auth) + + auth_agent = None + if self.token_agent is not None: + bearer = auth[len("Bearer "):] if auth and auth.startswith("Bearer ") else None + if bearer not in self.token_agent: + raise self._err(url, 401, "Unauthorized") + auth_agent = self.token_agent[bearer] + + def check(agent): + if auth_agent and agent != auth_agent: + raise self._err(url, 403, f"Forbidden: token belongs to agent '{auth_agent}', " + f"but request specified '{agent}'") + + if method == "POST" and parsed.path == "/api/memory": + body = json.loads(req.data.decode("utf-8")) + check(body["agentId"]) + mid = f"m{len(self.store) + 1}" + self.store[mid] = body + return _Resp(201, {"agentId": body["agentId"], "id": mid, + "embedding_id": mid if self.embed else None}) + if method == "GET" and parsed.path == "/api/memory/search": + check(query.get("agentId")) + results = [] + for mid, rec in self.store.items(): + if self.search_hides or rec["agentId"] != query.get("agentId"): + continue + hit = {"id": mid, "content": rec["content"], "agentId": rec["agentId"]} + if self.score: + hit["score"] = 0.99 + results.append(hit) + return _Resp(200, {"results": results}) + if method == "GET" and parsed.path.startswith("/api/memory/"): + mid = parsed.path.rsplit("/", 1)[1] + if mid not in self.store: + raise self._err(url, 404, "Memory not found") + content = "tampered" if self.corrupt_read else self.store[mid]["content"] + return _Resp(200, {"id": mid, "content": content}) + if method == "DELETE" and parsed.path.startswith("/api/memory/"): + check(query.get("agentId")) + self.store.pop(parsed.path.rsplit("/", 1)[1], None) + return _Resp(204) + raise self._err(url, 404, "no route") + + +def _run(monkeypatch, fake, argv, capsys): + monkeypatch.setattr(rp, "_urlopen", fake) + rc = rp.main(argv) + out = capsys.readouterr() + return rc, out + + +def test_bootstrap_bearer_round_trip_is_authenticated_and_writes_as_bootstrap(monkeypatch, capsys): + monkeypatch.setenv("CIPHER_API_TOKEN", BOOT_TOKEN) + fake = FakeCipher(token_agent={BOOT_TOKEN: "bootstrap"}) + rc, out = _run(monkeypatch, fake, ["--json"], capsys) + row = json.loads(out.out) + assert rc == 0, out + assert row["verdict"] == "ok" + assert row["agent"] == "bootstrap" + assert all(h == f"Bearer {BOOT_TOKEN}" for h in fake.auth_headers) + assert [c[0] for c in fake.calls] == ["POST", "GET", "GET", "DELETE"] + assert row["cleaned_up"] is True and fake.store == {} + + +def test_the_credential_never_reaches_output(monkeypatch, capsys): + monkeypatch.setenv("CIPHER_API_TOKEN", BOOT_TOKEN) + for argv in (["--json"], []): + _, out = _run(monkeypatch, FakeCipher(token_agent={BOOT_TOKEN: "bootstrap"}), argv, capsys) + assert BOOT_TOKEN not in out.out + out.err + # and not on the failure path either + _, out = _run(monkeypatch, FakeCipher(token_agent={"other": "bootstrap"}), ["--json"], capsys) + assert BOOT_TOKEN not in out.out + out.err + + +def test_minted_bearer_writes_as_the_session_identity(monkeypatch, capsys): + monkeypatch.setenv("CIPHER_API_TOKEN", MINTED_TOKEN) + monkeypatch.setenv("PMOVES_RESOLVED_IDENTITY", "z890-claude") + fake = FakeCipher(token_agent={MINTED_TOKEN: "z890-claude"}) + rc, out = _run(monkeypatch, fake, ["--json"], capsys) + assert rc == 0, out + assert json.loads(out.out)["agent"] == "z890-claude" + + +def test_minted_bearer_without_identity_is_unmeasured_not_a_guess(monkeypatch, capsys): + monkeypatch.setenv("CIPHER_API_TOKEN", MINTED_TOKEN) + fake = FakeCipher(token_agent={MINTED_TOKEN: "z890-claude"}) + rc, out = _run(monkeypatch, fake, ["--json"], capsys) + assert rc == 3 + assert json.loads(out.out)["verdict"] == "no_identity" + assert fake.calls == [] + + +def test_wrong_identity_is_a_403_finding_with_the_servers_reason(monkeypatch, capsys): + monkeypatch.setenv("CIPHER_API_TOKEN", BOOT_TOKEN) + fake = FakeCipher(token_agent={BOOT_TOKEN: "bootstrap"}) + rc, out = _run(monkeypatch, fake, ["--json", "--agent", "cipher-memory-smoke"], capsys) + row = json.loads(out.out) + assert rc == 1 + assert row["verdict"] == "unauthorized" and row["failed_step"] == "write" + assert "token belongs to agent 'bootstrap'" in row["error"] + + +def test_missing_bearer_against_an_enforcing_server_is_unauthorized(monkeypatch, capsys): + fake = FakeCipher(token_agent={BOOT_TOKEN: "bootstrap"}) + rc, out = _run(monkeypatch, fake, ["--json"], capsys) + assert rc == 1 + assert json.loads(out.out)["verdict"] == "unauthorized" + + +def test_nothing_listening_is_unmeasured(monkeypatch, capsys): + def refused(req, timeout): + raise urllib.error.URLError("connection refused") + + rc, out = _run(monkeypatch, refused, ["--json"], capsys) + assert rc == 3 + assert json.loads(out.out)["verdict"] == "unreachable" + + +def test_read_back_must_carry_the_written_content(monkeypatch, capsys): + rc, out = _run(monkeypatch, FakeCipher(corrupt_read=True), ["--json"], capsys) + row = json.loads(out.out) + assert rc == 1 and row["verdict"] == "readback_mismatch" + assert row["cleaned_up"] is True + + +def test_a_write_search_cannot_find_is_a_finding(monkeypatch, capsys): + rc, out = _run(monkeypatch, FakeCipher(search_hides=True), ["--json"], capsys) + assert rc == 1 + assert json.loads(out.out)["verdict"] == "search_miss" + + +def test_require_vector_fails_on_the_lexical_fallback_only(monkeypatch, capsys): + rc, out = _run(monkeypatch, FakeCipher(embed=False, score=False), ["--json"], capsys) + assert rc == 0, "without --require-vector a lexical round trip still counts" + rc, out = _run(monkeypatch, FakeCipher(embed=False, score=False), + ["--json", "--require-vector"], capsys) + assert rc == 1 + assert json.loads(out.out)["verdict"] == "vector_path_dead" + rc, _ = _run(monkeypatch, FakeCipher(), ["--json", "--require-vector"], capsys) + assert rc == 0 + + +def test_bearer_resolves_from_the_env_file_like_the_session(monkeypatch, tmp_path, capsys): + env_file = tmp_path / "env.shared" + env_file.write_text(f"CIPHER_API_TOKEN={BOOT_TOKEN}\n", encoding="utf-8") + fake = FakeCipher(token_agent={BOOT_TOKEN: "bootstrap"}) + rc, out = _run(monkeypatch, fake, ["--json", "--env-file", str(env_file)], capsys) + assert rc == 0, out + assert fake.auth_headers[0] == f"Bearer {BOOT_TOKEN}" + + +def test_process_per_agent_bearer_wins_over_the_env_file_bootstrap(monkeypatch, tmp_path, capsys): + """Inside a launched session the launcher re-binds the per-agent token AFTER + env.shared (claude-pmoves.sh "CIPHER TOKEN BIND"). The overlay must not undo + that and quietly test writes as 'bootstrap'.""" + env_file = tmp_path / "env.shared" + env_file.write_text(f"CIPHER_API_TOKEN={BOOT_TOKEN}\n", encoding="utf-8") + monkeypatch.setenv("CIPHER_API_TOKEN", MINTED_TOKEN) + monkeypatch.setenv("PMOVES_RESOLVED_IDENTITY", "z890-claude") + fake = FakeCipher(token_agent={MINTED_TOKEN: "z890-claude", BOOT_TOKEN: "bootstrap"}) + rc, out = _run(monkeypatch, fake, ["--json", "--env-file", str(env_file)], capsys) + row = json.loads(out.out) + assert rc == 0, out + assert all(h == f"Bearer {MINTED_TOKEN}" for h in fake.auth_headers) + assert row["agent"] == "z890-claude" + assert row["agent_source"] == "minted bearer + session identity" + assert all(rec["agentId"] == "z890-claude" for rec in fake.store.values()) + assert MINTED_TOKEN not in out.out + out.err and BOOT_TOKEN not in out.out + out.err + + +def test_env_file_bearer_still_fills_a_gap_in_the_process(monkeypatch, tmp_path): + layered = {"CIPHER_API_TOKEN": BOOT_TOKEN, "OTHER": "x"} + assert rp._process_session_wins(layered, {}, "CIPHER_API_TOKEN") == layered + # an empty process value is a gap, not a binding + assert rp._process_session_wins(layered, {"CIPHER_API_TOKEN": " "}, "CIPHER_API_TOKEN") == layered + won = rp._process_session_wins( + layered, {"CIPHER_API_TOKEN": MINTED_TOKEN, "PMOVES_RESOLVED_IDENTITY": "z890-claude"}, + "CIPHER_API_TOKEN") + assert won["CIPHER_API_TOKEN"] == MINTED_TOKEN + assert won["PMOVES_RESOLVED_IDENTITY"] == "z890-claude" and won["OTHER"] == "x" + + +def test_keep_skips_cleanup(monkeypatch, capsys): + fake = FakeCipher() + rc, _ = _run(monkeypatch, fake, ["--keep"], capsys) + assert rc == 0 + assert "DELETE" not in [c[0] for c in fake.calls] and len(fake.store) == 1 + + +def test_cipher_memory_smoke_runs_the_authenticated_probe(): + """The make target used to curl with no bearer and a fixed agentId no token + resolves to, so under token enforcement it could never pass.""" + text = MAKEFILE.read_text(encoding="utf-8") + m = re.search(r"^cipher-memory-smoke:.*?(?=^\S)", text, re.S | re.M) + assert m, "cipher-memory-smoke target not found" + recipe = m.group(0) + assert "tools/cipher_roundtrip_probe.py" in recipe + assert "--require-vector" in recipe + assert '"agentId":"cipher-memory-smoke"' not in recipe diff --git a/pmoves/tools/cipher_roundtrip_probe.py b/pmoves/tools/cipher_roundtrip_probe.py new file mode 100644 index 0000000000..f77dcfcfd7 --- /dev/null +++ b/pmoves/tools/cipher_roundtrip_probe.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +"""Can this session WRITE a memory and READ IT BACK, authenticated, as itself? + +WHY THIS EXISTS +--------------- +`cipher_preflight.py` answers "is the endpoint reachable and does it accept my +bearer?" -- it reads the status line of `/mcp/sse` and stops. `cipher_identity.py` +answers "which agent_id will my writes be filed under?" without touching the +network. Neither one stores anything, so neither can tell you that memory +actually works: a 200 on the SSE handshake says nothing about whether a write +persists, whether it can be read back, or whether the vector path is live. + +`make -C pmoves cipher-memory-smoke` was the only write->read check, and under +token enforcement it could not pass. It sent no `Authorization` header, and it +wrote as agentId `cipher-memory-smoke` -- an identity no token resolves to, so +even with a bearer every call was 403 (`assertAgentId`, memory-routes.ts:13-27). +Behind `curl -sf` both surfaced as `POST FAILED:` with an empty message. + +This probe does the round trip the way a real client does: + + POST /api/memory write a unique marker as the token's agent + GET /api/memory/{id} read it back by id; content must match + GET /api/memory/search find it again by query, scoped to the agent + DELETE /api/memory/{id} clean up (skip with --keep) + +THE CREDENTIAL AND THE IDENTITY COME FROM THE SAME PLACES THE SESSION USES +-------------------------------------------------------------------------- +The bearer is read from the environment `cipher_preflight.layered_environ()` +builds -- process env with pmoves/env.shared over it, exactly as the launcher +sources it -- so this probe authenticates the way the session will, and from a +named VARIABLE, never argv. The agentId is the one auth.ts will accept for that +bearer (`cipher_identity.classify_token`): a non-`cipher_` token is always +`bootstrap`; a minted `cipher_` token is the session's resolved identity. Pass +`--agent` to override. + +NEVER LOG THE CREDENTIAL. The token goes onto the request and nowhere else. + +Exit codes (same vocabulary as cipher_preflight.py): + 0 round trip complete -- written, read back, found by search + 1 findings -- cipher ANSWERED but the round trip did not hold (401/403, + read-back mismatch, search miss, or --require-vector and the vector path + is dead) + 3 could not measure -- unreachable, no identity to write as, or a crash. + NOT a pass +""" +from __future__ import annotations + +import argparse +import json +import os +import socket +import sys +import urllib.error +import urllib.parse +import urllib.request +import uuid +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Tuple + +_tools_dir = Path(__file__).resolve().parent +if str(_tools_dir) not in sys.path: + sys.path.insert(0, str(_tools_dir)) + +import cipher_identity as ci # noqa: E402 +import cipher_preflight as cp # noqa: E402 + +DEFAULT_TOKEN_ENV = cp.DEFAULT_TOKEN_ENV +TIMEOUT = 30.0 +# Written content is prefixed so a probe record is recognisable if --keep (or a +# failed DELETE) leaves one behind. +MARKER = "cipher-roundtrip-probe" +# Advisory mode (no bearer): the server takes the agentId on trust, so any +# stable name works. It is NOT used when a token is present. +ADVISORY_AGENT = MARKER + + +def default_base_url(environ: Mapping[str, str]) -> str: + return f"http://localhost:{environ.get('CIPHER_PORT') or '8105'}" + + +def _urlopen(req: urllib.request.Request, timeout: float): + """The single network seam. Tests patch this. + + Delegates to cipher_preflight's opener, which refuses redirects: the request + carries a bearer and urllib would forward it to any Location. + """ + return cp._urlopen(req, timeout) + + +def resolve_agent( + explicit: Optional[str], token: Optional[str], environ: Mapping[str, str] +) -> Tuple[str, str]: + """``(agent_id, why)`` -- the agentId auth.ts will accept for this bearer. + + Returns an empty agent_id when there is nothing honest to write as. + """ + if explicit: + return explicit, "--agent" + mode = ci.classify_token(token) + if mode == ci.MODE_BOOTSTRAP: + return ci.BOOTSTRAP_AGENT, "single-token bearer resolves to 'bootstrap' (auth.ts)" + if mode == ci.MODE_PER_AGENT: + agent = ( + environ.get("PMOVES_RESOLVED_IDENTITY") + or environ.get("PMOVES_NODE_IDENTITY") + or "" + ).strip() + if agent: + return agent, "minted bearer + session identity" + return "", ( + "minted bearer but no session identity (PMOVES_RESOLVED_IDENTITY / " + "PMOVES_NODE_IDENTITY unset) -- pass --agent " + ) + return ADVISORY_AGENT, "no bearer: advisory mode, agentId self-declared" + + +def _call( + method: str, + url: str, + token: Optional[str], + body: Optional[Dict[str, Any]] = None, + timeout: float = TIMEOUT, +) -> Tuple[Optional[int], Any, Optional[str]]: + """``(status, parsed_json_or_None, error)``. Never raises for HTTP/network failure. + + ``status is None`` means nothing answered. The error text carries the + server's own ``error`` field (e.g. the 403 identity mismatch) and never a + header value. + """ + headers = {"Accept": "application/json"} + if token: + headers["Authorization"] = f"Bearer {token}" + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with _urlopen(req, timeout) as resp: + raw = resp.read() + payload = json.loads(raw.decode("utf-8")) if raw else None + return resp.status, payload, None + except urllib.error.HTTPError as exc: + detail = "" + try: + parsed = json.loads(exc.read().decode("utf-8")) + if isinstance(parsed, dict) and isinstance(parsed.get("error"), str): + detail = ": " + parsed["error"][:200] + except Exception: # noqa: BLE001 - a non-JSON error body is still an HTTP status + pass + return exc.code, None, f"HTTP {exc.code}{detail}" + except (urllib.error.URLError, socket.timeout, TimeoutError, OSError) as exc: + return None, None, str(getattr(exc, "reason", exc)) + except ValueError: + # Deliberately NOT interpolated: http.client names a rejected header + # value -- the credential -- in this message. + return None, None, "request rejected before send -- detail withheld" + + +def _fail(row: Dict[str, Any], step: str, status: Optional[int], error: Optional[str]) -> Dict[str, Any]: + row["failed_step"] = step + row["error"] = error + if status is None: + row["verdict"] = "unreachable" + elif status in (401, 403): + row["verdict"] = "unauthorized" + else: + row["verdict"] = "http_error" + return row + + +def roundtrip( + base_url: str, + agent: str, + token: Optional[str], + require_vector: bool = False, + keep: bool = False, +) -> Dict[str, Any]: + """Run the round trip. Returns a result row; never contains the token.""" + base = base_url.rstrip("/") + content = f"{MARKER} {uuid.uuid4().hex}" + row: Dict[str, Any] = { + "base_url": base, + "agent": agent, + "auth": "presented" if token else "none", + "verdict": "ok", + "failed_step": None, + "error": None, + "id": None, + "embedded": None, + "vector_hit": None, + "cleaned_up": None, + } + + status, created, err = _call( + "POST", f"{base}/api/memory", token, + {"content": content, "category": "test", "tags": ["smoke", "roundtrip"], "agentId": agent}, + ) + if status is None or status >= 300: + return _fail(row, "write", status, err) + if not isinstance(created, dict) or not created.get("id"): + row.update(verdict="http_error", failed_step="write", error="write answered without an id") + return row + mem_id = str(created["id"]) + row["id"] = mem_id + row["embedded"] = created.get("embedding_id") is not None + + try: + status, got, err = _call("GET", f"{base}/api/memory/{urllib.parse.quote(mem_id, safe='')}", token) + if status is None or status >= 300: + return _fail(row, "read", status, err) + if not isinstance(got, dict) or got.get("content") != content: + row.update(verdict="readback_mismatch", failed_step="read", + error="record read back by id does not carry the written content") + return row + + query = urllib.parse.urlencode({"q": content, "limit": 5, "agentId": agent}) + status, found, err = _call("GET", f"{base}/api/memory/search?{query}", token) + if status is None or status >= 300: + return _fail(row, "search", status, err) + results = (found or {}).get("results") if isinstance(found, dict) else None + hit = next((r for r in results or [] if isinstance(r, dict) and r.get("id") == mem_id), None) + if hit is None: + row.update(verdict="search_miss", failed_step="search", + error=f"search for the written content as '{agent}' did not return it") + return row + # memory-routes.ts sets `score` only on Qdrant hits; lexicalFallback() + # results carry none. embedding_id is null unless the embed succeeded. + row["vector_hit"] = "score" in hit + if require_vector and not (row["embedded"] and row["vector_hit"]): + row.update(verdict="vector_path_dead", failed_step="search", error=( + "round trip held only through the lexical fallback " + f"(embedded={row['embedded']}, vector_hit={row['vector_hit']}); " + "embedded=False means sidecar.embed() failed -- check TENSORZERO_URL / " + "OLLAMA_URL is reachable FROM the cipher container; vector_hit=False " + "with embedded=True means the collection is missing -- provision with " + "make -C pmoves qdrant-provision-cipher" + )) + return row + finally: + if not keep: + q = urllib.parse.urlencode({"agentId": agent}) + status, _, _ = _call( + "DELETE", f"{base}/api/memory/{urllib.parse.quote(mem_id, safe='')}?{q}", token + ) + row["cleaned_up"] = status is not None and status < 300 + + +def exit_code(row: Dict[str, Any]) -> int: + if row["verdict"] == "ok": + return 0 + if row["verdict"] in ("unreachable", "no_identity", "unmeasured"): + return 3 + return 1 + + +# The session binding: the bearer plus the identity it was minted for. +SESSION_IDENTITY_VARS = ("PMOVES_RESOLVED_IDENTITY", "PMOVES_NODE_IDENTITY") + + +def _process_session_wins( + layered: Mapping[str, str], process: Mapping[str, str], token_env: str +) -> Dict[str, str]: + """Put the process's own session binding back over the env-file overlay. + + ``cp.layered_environ`` lays env.shared OVER the process env, and env.shared + carries the node bootstrap bearer. Inside a launched session that clobbers + the per-agent token the launcher deliberately re-binds AFTER loading + env.shared (deploy/provision/claude-pmoves.sh, "CIPHER TOKEN BIND"), so the + probe would test writes as 'bootstrap' instead of the session identity. + Same precedence as the launcher: a bearer already present in the process + wins; env.shared only fills a gap. The identity variables travel with the + bearer so resolve_agent() names the agent that token is bound to. + """ + env = dict(layered) + for key in ((token_env,) if token_env else ()) + SESSION_IDENTITY_VARS: + value = (process.get(key) or "").strip() + if value: + env[key] = value + return env + + +def main(argv: Optional[list] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--base-url", default=None, + help="cipher HTTP base (default http://localhost:$CIPHER_PORT, 8105)") + parser.add_argument("--agent", default=None, + help="agentId to write as (default: what auth.ts accepts for the bearer)") + parser.add_argument("--token-env", default=DEFAULT_TOKEN_ENV, + help="variable holding the bearer; '' probes anonymously. Never the token itself") + parser.add_argument("--env-file", type=Path, default=None) + parser.add_argument("--no-env-file", action="store_false", dest="use_env_file") + parser.add_argument("--require-vector", action="store_true", + help="fail when the round trip only held through the lexical fallback") + parser.add_argument("--keep", action="store_true", help="do not DELETE the probe record") + parser.add_argument("--json", action="store_true", dest="as_json") + args = parser.parse_args(argv) + + try: + if args.use_env_file: + environ, note = cp.layered_environ(args.env_file) + if note: + print(f"[cipher-roundtrip] {note}", file=sys.stderr) + environ = _process_session_wins(environ, os.environ, args.token_env) + else: + environ = dict(os.environ) + token = (environ.get(args.token_env) or "").strip() if args.token_env else "" + if token and not cp._header_safe([token]): + row = {"verdict": "unmeasured", "error": "credential contains CR/LF -- value withheld"} + else: + agent, why = resolve_agent(args.agent, token or None, environ) + if not agent: + row = {"verdict": "no_identity", "error": why} + else: + row = roundtrip(args.base_url or default_base_url(environ), agent, + token or None, args.require_vector, args.keep) + row["agent_source"] = why + except Exception as exc: # noqa: BLE001 - a crash is COULD-NOT-MEASURE, never a pass + row = {"verdict": "unmeasured", "error": f"probe crashed ({type(exc).__name__})"} + + if args.as_json: + print(json.dumps(row, indent=2, sort_keys=True)) + elif row["verdict"] == "ok": + print(f"cipher round trip OK as '{row['agent']}' at {row['base_url']} " + f"(embedded={row['embedded']}, vector_hit={row['vector_hit']}, " + f"cleaned_up={row['cleaned_up']})") + else: + step = f" at {row['failed_step']}" if row.get("failed_step") else "" + print(f"cipher round trip FAILED{step}: {row['verdict']} -- {row.get('error')}", + file=sys.stderr) + return exit_code(row) + + +if __name__ == "__main__": + sys.exit(main())