# CAIN-42 L5 Governance — Part 40
## Full Repository Evolution Audit: Consequential Execution Paths & the Governance Boundary

**Repository:** `<redacted-path>/cain-studio-platform`  
**Date:** 2026-09-28  
**Scope:** every git-tracked file (6,518), every Python module (2,476)  
**Mode:** read-only forensic audit. No source file was modified. This report is the only artefact produced (with its JSON twin).

---

## 0. What this audit answers

For every *consequential* execution path in the repository — shell/subprocess, tool & MCP/plugin execution, direct cloud/API control, database mutation, filesystem mutation, credential use, and agent-to-agent delegation — the question asked is not *"is there a security function in this file?"* but:

> **Does the code that actually causes the side effect pass through one of the four canonical CAIN governance boundaries, or can it run without them?**

A finding is marked **GOVERNED** only when the file/function *is* a boundary, *calls into* a boundary, or is *only invoked from* a boundary. **UNGOVERNED** means no import path to any boundary. **PARTIALLY_GOVERNED** means some entry points route through a boundary and others do not, or governance is opt-in per call. **NOT_APPLICABLE** is reserved for paths with no consequential side effect (none of the 84 findings below needed it: a boundary's own act is recorded as GOVERNED with severity `NOT_APPLICABLE`).

## 1. The governance boundaries (as named by the directive)

| Key | Boundary | Enforcement surface |
|-----|----------|---------------------|
| **MCPGate** | `cain/mcp_proxy.py` | `MCPTransparentInterceptor` (evaluate → fabric gate → JIT consume → downstream), `StdioMCPProxy`, `create_mcp_proxy_app` (mid-flight revocation) |
| **TRUST_KERNEL** | `platform-gateway/cain_trust_kernel.py` | `CainTrustRuntimeKernel.evaluate_action`, 16-stage context, `ActionCapabilityToken`, 20 invariants, Merkle evidence |
| **FABRIC** | `platform-gateway/fabric_control_plane.py` | `TrustFabricControlPlane`, `record_decision`, approvals, kill switch, tenant enforcement mode |
| **HYPERVISOR** | `cain45/hypervisor.py` (+ `cain45/confine.py`) | `AgentHypervisor.run` / `call_tool` — the only two doors; bwrap + cgroup confinement |
| **SDK_GUARD** *(supporting)* | `cain/guard.py`, `cain/wrap.py`, `cain/adapters/*` | In-process decorator surface used by `@cain.guard`, `cain.wrap`, LangChain/CrewAI/LlamaIndex adapters |

### How reachability was computed

An AST import graph was built across all 2,493 Python files (`ast.parse`; 8 files failed to parse, all evidence scripts). Two-way reachability to the four boundary files (plus `cain/guard.py`) gives:

| Metric | Value |
|--------|-------|
| Modules that transitively import a boundary (callers) | **531** |
| Modules imported *by* a boundary (callees / governed libraries) | **97** |
| Union = modules on a governed path | **603** |
| Canonical production modules (excl. tests/scripts/vendored) | **1,061** |
| Canonical modules with **zero** importing tests | **477** |
| Canonical modules imported by **nothing** (dead-code candidates) | **200** |
| `.py` files with at least one **byte-identical** twin repo-wide | **457** |

> *Caveat.* Reachability is file-level. A module marked UNGOVERNED can still be *reached* only from a governed caller if some other file defines its entry point; conversely, a module on a governed path can expose other entry points that skip the boundary. Each finding is annotated with its actual route so the reader can judge.

## 2. Summary of findings

| Status | Count |
|--------|-------|
| GOVERNED | 23 |
| UNGOVERNED | 57 |
| PARTIALLY_GOVERNED | 4 |
| **Total consequential findings** | **84** |

Plus 12 duplication findings, 10 dead-code groups, 15 undocumented assumptions, 14 security gaps, 9 missing-test groups and 7 performance findings.

## 3. Consequential execution findings

### Subprocess, shell, `Popen`, `os.system`

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| SHELL-01 | `talos-coder/daemon/tools/run_command.py:48` | `RunCommandTool.execute` | **UNGOVERNED** | HIGH | none (no CAIN import anywhere in talos-coder/) | shell=True with caller-widened allowed_prefixes; whole talos-coder daemon executes shell, reads/edits files and walks outside the CAIN boundary. Default allowlist in main.py is read-only-ish but the tool itself permits unrestricted shell when allowed_prefixes=None. |
| SHELL-02 | `talos-coder/daemon/loop.py:285` | `AgentLoop._run_lint_or_test` | **UNGOVERNED** | MEDIUM | none | Quality-gate commands (lint_cmd/test_cmd from DaemonConfig) executed via subprocess.run with no CAIN evaluation. |
| SHELL-03 | `cain/customer_cli.py:372` | `launch_protected_agent` | **PARTIALLY_GOVERNED** | LOW | inherits CAIN_MODE=enforce in child env | Launches the customer agent with CAIN_MODE=enforce and CAIN_API_KEY exported; the launch itself is unguarded, governance only applies if the child calls the SDK/MCPGate. |
| SHELL-04 | `cain/frontier/discovery.py:13` | `_sh` | **UNGOVERNED** | LOW | none | shell=True discovery of host processes/MCP configs; fixed command strings, but on the frontier loop, not through a boundary. |
| SHELL-05 | `cain/frontier/cluster.py:12` | `_sh` | **UNGOVERNED** | MEDIUM | none | shell=True `docker inspect $(docker ps -q ...)` string interpolation; host command execution feeding the Trust-BOM. Not on a governed path. |
| SHELL-13 | `cain-microservices/sparselogic-compiler/src/sparselogic_compiler/synthesis.py:114` | `synthesis (yosys/nextpnr/pack)` | **UNGOVERNED** | LOW | none | EDA toolchain subprocesses; tool names/paths are internal, but no CAIN gate. |
| SHELL-15 | `platform-gateway/cain_formal_verifier.py:111` | `verify via subprocess` | **UNGOVERNED** | LOW | none | Runs external verifier; audit tooling. |
| SHELL-16 | `platform-gateway/cain_claim_auditor_19.py:163` | `pytest per claim` | **UNGOVERNED** | LOW | none | Spawns `pytest <target>` per claim (see PERF-01). |
| SHELL-17 | `platform-gateway/cain_claim_auditor_20.py:176` | `pytest per claim` | **UNGOVERNED** | LOW | none | Same pattern. |
| SHELL-18 | `platform-gateway/cain_claim_auditor_22.py:96` | `pytest per claim` | **UNGOVERNED** | LOW | none | Same pattern. |
| SHELL-19 | `platform-gateway/cain_conformance_23.py:111` | `git/pytest subprocess` | **UNGOVERNED** | LOW | none | Conformance harness. |
| SHELL-20 | `platform-gateway/cain_rfc3161.py:69` | `openssl ts` | **UNGOVERNED** | LOW | none | RFC3161 timestamping via openssl; not a boundary callee (cain_pqc.py IS a callee and is governed). |

### `eval` / `exec` / dynamic import

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| EVAL-01 | `platform-gateway/cain_control_loop.py:2092` | `SafeExpressionEvaluator.evaluate` | **UNGOVERNED** | MEDIUM | none | eval(compile(...), {'__builtins__': {}}, ctx) — restricted builtins but still eval on policy expressions; module is not on a governed path. Duplicate at cain/substrate/cain_control_loop.py. |
| EVAL-02 | `cain/substrate/cain_control_loop.py:2092` | `SafeExpressionEvaluator.evaluate` | **UNGOVERNED** | MEDIUM | none | Stale duplicate of EVAL-01. |

### Database mutation (raw SQL / ORM writes)

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| DB-01 | `cain45/hypervisor.py:155` | `AgentHypervisor._transition / _put / terminate` | **GOVERNED** | NOT_APPLICABLE | HYPERVISOR | All ZoD/state/evidence/grant/revocation writes are inside the hypervisor authority boundary; raw sqlite writes are the boundary's own evidence store. |
| DB-02 | `platform-gateway/fabric_control_plane.py:887` | `record_decision / _conn` | **GOVERNED** | NOT_APPLICABLE | FABRIC | Decision/principal/approval/kill-switch writes are the control plane itself; uses per-thread pooled WAL connection. |
| DB-03 | `platform-gateway/cain_trust_kernel.py:2164` | `audit_event_ledger / dual custody` | **GOVERNED** | NOT_APPLICABLE | TRUST_KERNEL | Kernel state/evidence persistence is the kernel's own. |
| DB-04 | `platform-gateway/agent_runtime.py:1520` | `record_tool_call / runtime tables` | **UNGOVERNED** | MEDIUM | none | Agent runtime records tool calls and budgets in its own runtime_tool_calls table, but does not consult MCPGate/fabric/kernel before or after; it is an accounting layer, not a gate. DB calls inside loops (see PERF-02). |
| DB-05 | `platform-gateway/cain_a2a.py:202` | `_get_conn + session/delegation writes` | **UNGOVERNED** | MEDIUM | none | A2A sessions, delegations, capability tokens and audit log persisted directly; A2A server-side path does not route through MCPGate/hypervisor. |
| DB-06 | `platform-gateway/cain_skills.py:276` | `skill registry writes` | **UNGOVERNED** | MEDIUM | none | Skill/plugin registry and executions table written directly; no authorisation on publish/upgrade/revoke. |
| DB-07 | `platform-gateway/cain_discovery.py` | `discovery DB writes` | **UNGOVERNED** | LOW | none | Inventory persistence. |
| DB-08 | `platform-gateway/cain_compliance.py` | `compliance records` | **UNGOVERNED** | LOW | none | Compliance-as-a-Service records; no boundary call before write. |
| DB-09 | `platform-gateway/cain_security_core.py` | `security core records` | **UNGOVERNED** | LOW | none | Persists security state directly. |
| DB-10 | `cainaccounts/main.py` | `account DB writes` | **UNGOVERNED** | LOW | none | Separate service; identity/billing DB. |
| DB-11 | `billing-service/db.py` | `billing DB writes` | **UNGOVERNED** | LOW | none | Separate billing service. |
| DB-12 | `clawx/control_plane/store.py` | `grant/revocation/ledger store` | **GOVERNED** | NOT_APPLICABLE | callee of cain.guard (clawx/cain_boundary.py) | clawx control-plane store is reached through the cain.guard surface. |
| DB-13 | `platform-gateway/runtime_engine.py:1250` | `delegate_task / runtime DB` | **UNGOVERNED** | MEDIUM | none | Runtime engine persists tasks/steps/costs directly; delegate_task has no assess_call into a boundary. |

### Filesystem mutation (`shutil`, `os.remove/rename`, `open(...,'w')`)

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| FS-01 | `platform-gateway/cain_kms.py:138` | `_save_encrypted_private_key / cert write` | **UNGOVERNED** | HIGH | none | Writes RSA private key (encrypted, 0600) and public cert to /app/data; key-management is its own module and is not gated. See CRED-01. |
| FS-02 | `clawx/control_plane/keys.py:37` | `signer rotation os.unlink` | **GOVERNED** | NOT_APPLICABLE | callee of cain.guard surface | Atomic signer-key rotation; reached through the guard surface. |
| FS-03 | `platform-gateway/cain_disaster_recovery_42.py:275` | `shutil.rmtree(temp_dir)` | **UNGOVERNED** | LOW | none | Temp cleanup; no gate needed but tracked. |
| FS-04 | `platform-gateway/cain_frontier_lab_api.py:68` | `close -> shutil.rmtree` | **UNGOVERNED** | LOW | none | Lab workspace teardown. |
| FS-05 | `cain-microservices/visual-ide/main.py:126` | `shutil.rmtree(work_dir)` | **UNGOVERNED** | LOW | none | Per-job workspace cleanup. |
| FS-06 | `cain-microservices/weight-alchemist/main.py` | `model weight FS writes` | **UNGOVERNED** | MEDIUM | none | Writes/removes model artifacts without a boundary call. |
| FS-07 | `platform-gateway/cain_dual_custody_store.py` | `dual-custody store writes` | **UNGOVERNED** | MEDIUM | none | Dual-custody material on disk; kernel references a separate dual-custody engine. |

### Credential use & key material

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| CRED-01 | `platform-gateway/cain_kms.py:84` | `KeyManager passphrase derivation` | **UNGOVERNED** | HIGH | none | raw_passphrase = passphrase or CAIN_KMS_MASTER_KEY or CAIN_JWT_SECRET or 'cain-default-secure-vault-passphrase-2026'. A hard-coded, publicly-known fallback passphrase protects the RSA signing key at rest whenever both env vars are unset — a silent weak-key condition, not a crash. |
| CRED-02 | `cain/sovereign.py:122` | `LocalRootOfTrust key storage` | **UNGOVERNED** | MEDIUM | none | Ed25519/ML-DSA keys stored 0600 under /tmp/cain-sovereign-keys by default; no HSM/TEE (documented), but default path is world-writable /tmp. |
| CRED-03 | `platform-gateway/bin/cain_node_identity.py:58` | `NodeIdentity private key` | **UNGOVERNED** | MEDIUM | none | Node Ed25519 private key written to <redacted-path>/identity/*.pem (0600); key generation/loading not gated by a boundary. |
| CRED-04 | `platform-gateway/cain_runtime_trust.py:6592` | `AWS KMS` | **UNGOVERNED** | MEDIUM | none | External KMS usage inside trust-runtime. |
| CRED-05 | `platform-gateway/cain_attestation.py` | `attestation signing keys` | **UNGOVERNED** | MEDIUM | none | Signing material handled outside the kernel boundary. |
| CRED-06 | `platform-gateway/cain_kernel_self_defense.py` | `dual-custody root keys` | **GOVERNED** | NOT_APPLICABLE | callee of TRUST_KERNEL | Dual-custody key registration is a kernel surface. |
| CRED-08 | `cain5/identity_sdk.py` | `identity SDK secrets` | **UNGOVERNED** | MEDIUM | none | cain5 identity SDK handles secrets/tokens without a boundary. |
| CRED-09 | `content-provenance/main.py` | `provenance credentials` | **UNGOVERNED** | LOW | none | Standalone service credentials. |
| CRED-10 | `taloscrypt-mesh/engine.py` | `mesh credentials` | **UNGOVERNED** | LOW | none | Standalone product scaffolding. |

### Agent delegation / agent-to-agent calls

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| DEL-01 | `cain/universal_wrapper.py:492` | `A2AAgentWrapper.send_task` | **PARTIALLY_GOVERNED** | HIGH | MCPGate wrapper (send_task) but self-signed passport check | verify_passport() checks the signature against the SAME fabric's own public key; a delegation is accepted if it is self-consistent, not if the parent actually holds the authority. Capability subset/budget/depth are enforced structurally, but the trust root is the presenter's own key. |
| DEL-02 | `cain45/hypervisor.py:369` | `create_zod / child_within_parent` | **GOVERNED** | NOT_APPLICABLE | HYPERVISOR | Child authority ≤ parent authority is enforced at spawn and continuously via _ancestor_problem; delegation is PBFT-ordered and evidenced. |
| DEL-03 | `cain45/hypervisor.py:649` | `run / call_tool (the two doors)` | **GOVERNED** | NOT_APPLICABLE | HYPERVISOR | Both doors re-check state, grant signature/bindings, expiry, revocation, trust floor, security context and trajectory continuity on every use. |
| DEL-04 | `platform-gateway/cain_a2a.py:202` | `A2A server (sessions/delegations)` | **UNGOVERNED** | MEDIUM | none | Server-side A2A session/delegation engine not routed through a boundary; separate from the wrapped client path in DEL-01. |
| DEL-05 | `platform-gateway/a2a_delegation.py` | `A2A delegation` | **UNGOVERNED** | MEDIUM | none | Parallel A2A delegation implementation. |
| DEL-06 | `platform-gateway/cain_delegation_sovereignty_19.py` | `delegation sovereignty` | **UNGOVERNED** | MEDIUM | none | 19-series delegation fabric; not wired to MCPGate. |
| DEL-07 | `platform-gateway/cain_delegation_graph_42.py` | `delegation graph` | **UNGOVERNED** | LOW | none | Graph analysis of delegation; read-only. |
| DEL-08 | `clawx/control_plane/grants.py:97` | `Grant.delegate` | **GOVERNED** | NOT_APPLICABLE | callee of cain.guard surface | Monotonic grant delegation inside the clawx control plane. |
| DEL-09 | `cain/frontier/capability.py:90` | `delegate` | **GOVERNED** | NOT_APPLICABLE | callee of cain.frontier.gate (MCPGate frontier layer) | Capability attenuation with signed tokens. |
| DEL-10 | `platform-gateway/cain_agi_multiagent.py:32` | `delegate_A_to_B` | **UNGOVERNED** | MEDIUM | none | AGI multi-agent handoff helper; no boundary call. |

### Direct tool / MCP / plugin execution

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| MCP-01 | `platform-gateway/mcp_enforcement_api.py:36` | `enforce` | **GOVERNED** | NOT_APPLICABLE | MCPGate (MCPTransparentInterceptor strict) | HTTP enforcement endpoint runs the real interceptor in strict mode. |
| MCP-02 | `platform-gateway/mcp_runtime.py:775` | `MCPSecurityRuntime.pre_tool_call / post_tool_call` | **UNGOVERNED** | MEDIUM | none (parallel validator, not wired into MCPGate) | A second MCP validation/scanner runtime (tool registry, injection scan, risk score). It is NOT imported by cain/mcp_proxy.py; only by agi_boundary/compliance modules — two MCP gatekeeping stacks that can drift. |

### Direct cloud / infrastructure control

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| SHELL-08 | `cain-microservices/swarm-orchestrator/main.py:143` | `_load_k8s_client / apply` | **UNGOVERNED** | HIGH | none | Direct Kubernetes NetworkingV1Api create/delete of NetworkPolicies; no CAIN authorization on the mutation. Sibling of the K8s appliance monetisation channel. |
| SHELL-11 | `platform-gateway/resilience_controller.py:3` | `kubernetes client` | **UNGOVERNED** | HIGH | none | Kubernetes client loaded at module import; controller actions are not routed through fabric/hypervisor. |

### Agent code execution

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| SHELL-14 | `cain-sandbox/main.py:252` | `execute -> asyncio.create_subprocess_exec` | **UNGOVERNED** | MEDIUM | none (isolated container, explicitly disclosed) | Executes agent-generated code in a dedicated internal docker network with NO governance boundary, only an isolation boundary. Docstring is honest about the limits (no no-new-privileges, no VM). |

### Direct API surfaces

| ID | File : line | Symbol | Status | Severity | Boundary | Note |
|----|-------------|--------|--------|----------|----------|------|
| API-01 | `platform-gateway/main.py` | `FastAPI monolith (446 modules, 7138 LOC)` | **PARTIALLY_GOVERNED** | HIGH | fabric_control_plane for /fabric/* and decisions; MCPGate for /mcp/*; many endpoints are direct | The gateway is the largest surface; a subset (fabric decisions, mcp enforcement, sovereign control after the 2026-09-27 fix) is governed, but hundreds of endpoints are direct DB/HTML/ops with no boundary call. The sovereign write fix exists only in this copy (see DUP-02). |

### Other (uncategorised grouping — category shown explicitly)

| ID | Category | File : line | Symbol | Status | Severity | Boundary | Note |
|----|----------|-------------|--------|--------|----------|----------|------|
| SHELL-06 | subprocess/plugin-exec | `cain/cain_kernel_enforcement.py:403` | `KernelEnforcer/proc launch` | **UNGOVERNED** | MEDIUM | none (ungoverned duplicate) | Duplicate of the governed platform-gateway/cain_kernel_enforcement.py (which IS a callee of mcp_proxy/universal_wrapper). The cain/ copy is not imported by any boundary. |
| SHELL-07 | cloud/infra control | `platform-gateway/cain_lab_public.py:81` | `_docker / _running` | **UNGOVERNED** | HIGH | none | Public lab API can `docker stop` / `docker start` / `docker inspect` named sandbox containers directly via subprocess, with no CAIN decision. |
| SHELL-09 | cloud/docker control | `cain-microservices/orchestrator/causal_orchestrator.py:15` | `docker.from_env` | **UNGOVERNED** | HIGH | none | Docker daemon client at import; orchestrates containers without a CAIN decision. |
| SHELL-10 | cloud/docker control | `cain-microservices/resilience-controller/main.py:163` | `docker.from_env` | **UNGOVERNED** | HIGH | none | Restarts/stops containers directly; infrastructure mutation outside the boundary. |
| SHELL-12 | credential/cloud | `platform-gateway/cain_runtime_trust.py:6592` | `KMS provider (boto3)` | **UNGOVERNED** | MEDIUM | none | AWS KMS client constructed in the trust-runtime module; key operations bypass the local KMS boundary (cain_kms.py) and the kernel. |
| SHELL-21 | subprocess/mcp-exec | `cain/mcp_proxy.py:855` | `StdioMCPProxy.run -> subprocess.Popen` | **GOVERNED** | NOT_APPLICABLE | MCPGate (this file IS the boundary) | Spawning the downstream MCP server is the boundary's own act, guarded by evaluate_tool_call + JIT consume + optional seccomp preexec. |
| SHELL-22 | subprocess/mcp-exec | `cain/universal_wrapper.py:149` | `MCPSmartWrapper discovery/dispatch` | **GOVERNED** | NOT_APPLICABLE | MCPGate interceptor used by the wrapper | Both discovery and invoke go through MCPTransparentInterceptor; deny raises CainActionBlockedException in strict mode. |
| SHELL-23 | subprocess/mcp-exec | `cain/cli_tools.py:122` | `VisualStdioMCPProxy.run` | **GOVERNED** | NOT_APPLICABLE | MCPGate interceptor | Visual firewall wraps the same interceptor; non-TTY fails closed. |
| SHELL-24 | subprocess/mcp-exec | `platform-gateway/cain_kernel_enforcement.py:403` | `kernel enforcer preexec` | **GOVERNED** | NOT_APPLICABLE | callee of MCPGate/universal_wrapper | libseccomp preexec builder used by the governed stdio proxy. |
| EVAL-03 | dynamic import | `platform-gateway/cain_epoch10_public.py:101` | `importlib spec_from_file_location/exec_module` | **UNGOVERNED** | LOW | none | Loads modules by file path at runtime; public evidence builder. |
| CRED-07 | credential/state | `cain/quarantine.py` | `SQLite quarantine state` | **GOVERNED** | NOT_APPLICABLE | callee of MCPGate (check_still_authorized) / guard | Containment state read on every MCP call and every guard evaluation. |
| MCP-03 | MCP tool metadata | `cain/tool_metadata_guard.py` | `ToolMetadataGuard` | **GOVERNED** | NOT_APPLICABLE | MCPGate (used in _evaluate_tool_call_legacy and tools/list filtering) | Pins tool schemas, quarantines rug-pulled/poisoned tools. |
| MCP-04 | plugin execution / registry | `platform-gateway/cain_skills.py` | `skill publish/execute/upgrade/revoke` | **UNGOVERNED** | MEDIUM | none | Reusable-capability (skill) registry mutation has no authorization; implies plugin dynamic behaviour not gated. |
| MCP-05 | tool execution (framework) | `cain/adapters/crewai.py` | `guard_agent / guard_crew` | **GOVERNED** | NOT_APPLICABLE | cain.guard decorator surface | Opt-in framework wrapping. |
| MCP-06 | tool execution (framework) | `cain/adapters/langchain.py` | `CainCallbackHandler/wrap` | **GOVERNED** | NOT_APPLICABLE | cain.guard | Opt-in. |
| MCP-07 | tool execution (framework) | `cain/adapters/llamaindex.py` | `guard_tool` | **GOVERNED** | NOT_APPLICABLE | cain.guard | Opt-in. |
| MCP-08 | tool execution (model) | `cain/wrap.py` | `wrap (OpenAI client interception)` | **PARTIALLY_GOVERNED** | MEDIUM | cain.guard on the chat-completions tool_calls path | Intercepts only the OpenAI-style client.chat.completions path; per CAIN45_BYPASS_AUDIT strict mode returns the tool call to the agent rather than blocking execution in the UNREACHABLE probe, and non-strict is advisory by design. |
| API-02 | direct API/execution gating | `cain/frontier/runtime.py` | `get_gate / GateDecision` | **GOVERNED** | NOT_APPLICABLE | MCPGate frontier layer (_frontier_check) | Capability chain + world model + session + budget; default mode is 'shadow' (see ASSUME-06). |
| PERF-01 | performance | `platform-gateway/cain_claim_auditor_22.py:96` | `audit loop` | **UNGOVERNED** | MEDIUM | none | Spawns a full `pytest <target>` subprocess per claim (120s timeout each); O(claims) interpreter+pytest startups for one audit run. |
| PERF-02 | performance | `platform-gateway/agent_runtime.py:1520` | `record_tool_call and loop bodies` | **UNGOVERNED** | LOW | none | Multiple execute/fetchone calls inside loops in runtime accounting (AST: 6 loop-DB sites around lines 2329/2575/2631); unbounded full-table SELECT rec loops in sibling modules. |
| PERF-03 | performance | `platform-gateway/fabric.py:533` | `validate / domain_index` | **UNGOVERNED** | LOW | none | Four-deep nested loops in canonical validation/domain indexing. |
| PERF-04 | performance | `platform-gateway/cain_control_loop.py:861` | `analyze` | **UNGOVERNED** | LOW | none | Three-deep nested loops in the control-loop analyser. |
| PERF-05 | performance | `cain/mcp_proxy.py:307` | `_evaluate_tool_call_legacy per call` | **GOVERNED** | LOW | MCPGate | Hot path does a function-local import of trajectory_enforcement, json.dumps canonicalization, and (on capability tokens) a synchronous identity_engine DB lookup per call; acceptable for <15ms target but worth caching. |
| PERF-06 | performance | `platform-gateway/main.py` | `import-time monolith` | **UNGOVERNED** | LOW | none | 322KB / 7138 LOC single module plus a 12004-line cain_runtime_trust.py and 8342-line cain_control_loop.py imported into one process — large import/startup and memory footprint per worker. |
| PERF-07 | performance | `platform-gateway/cain_trust_kernel.py:1319` | `CainTrustRuntimeKernel per evaluate_action` | **GOVERNED** | LOW | TRUST_KERNEL | Canonical JSON, Ed25519 verify, Merkle root and trajectory hash chaining per action; inherent, but no batching for high-throughput. |

## 4. Duplicated functionality

The single largest structural risk in the repository. `cain/substrate/` is a **shipped-in-the-wheel** duplicate of `platform-gateway/`, and it has already drifted in security-relevant ways.

| Kind | Paths | Severity | Detail |
|------|-------|----------|--------|
| mass duplication | `cain/substrate/* (251 tracked .py modules)` / `platform-gateway/* (446 .py modules)` | HIGH | 240 of 251 cain/substrate modules are byte-for-byte identical to the platform-gateway module of the same basename; only 11 diverge (__init__.py, agentops.py, cain_mr_client.py, cain_sovereign_api.py, cain_trust_kernel_api.py, cluster_api.py, company.py, fabric.py, main.py, pages.py, seed_48h_changelog.py). |
| security-relevant drift | `cain/substrate/main.py` / `platform-gateway/main.py` | HIGH | platform-gateway/main.py:782 adds '/api/v1/control/sovereign' to the anonymous-write block list (commit 92c2c47, 'close anonymous writes on /api/v1/control/sovereign'); cain/substrate/main.py has no such entry. The wheel copy still exposes the pre-fix behaviour. |
| security-relevant drift | `cain/substrate/cain_trust_kernel_api.py:505` / `platform-gateway/cain_trust_kernel_api.py:505` | MEDIUM | platform-gateway copy was fixed to call api.verify(target_type, payload); the substrate copy still calls api.verify(data, signature_b64, public_key_b64) ('crashed on every call'). |
| security-relevant drift | `cain/substrate/cluster_api.py:1410` / `platform-gateway/cluster_api.py:1410` | MEDIUM | cluster_api verify_action_proof signatures differ; the substrate copy uses the older call shape. |
| exact duplicate boundary source | `cain/substrate/cain_trust_kernel.py` / `platform-gateway/cain_trust_kernel.py` | MEDIUM | Byte-identical (2361 lines each), including the comment 'identical field on cain/substrate/cain_trust_kernel.py's copy of this'. Same for fabric_control_plane.py, cain_kernel_enforcement.py, cain_authority_attenuation.py, cain_computer.py, runtime_policies.py and ~234 others. |
| parallel MCP gatekeeping | `cain/mcp_proxy.py` / `platform-gateway/mcp_runtime.py` | MEDIUM | Two independent MCP validation stacks: MCPTransparentInterceptor (live boundary) and MCPSecurityRuntime.pre_tool_call/post_tool_call (registry/injection/risk scanner) which is never imported by mcp_proxy. |
| parallel adversarial engines | `platform-gateway/adversarial_engine.py` / `platform-gateway/cain_adversarial_suite.py` / `platform-gateway/cain_adversarial_simulator_v2.py` | MEDIUM | Three adversarial suites with overlapping categories. |
| universal wrapper copies | `cain/universal_wrapper.py` / `platform-gateway/cain_universal_wrapper.py` | LOW | Byte-identical. |
| kernel enforcement copies | `cain/cain_kernel_enforcement.py` / `platform-gateway/cain_kernel_enforcement.py` | MEDIUM | Duplicate of the governed seccomp enforcer; the cain/ copy is not a callee of any boundary. |
| cain5 copies | `cain5/` / `platform-gateway/cain5/` | MEDIUM | 9 files, 4 byte-identical, 5 divergent (cli.py, decision_cli.py, journey_audit.py, observatory.py, onboarding.py, trust_api.py, intelligence_gateway.py, hardening.py, setup.py). |
| build artifact | `build/lib/cain/**` / `build/lib/cain5/**` / `build/lib/cain-microservices/**` / `build/lib/cainloan/**` | LOW | A full vendored copy of the package tree (357+ duplicate .py files) present on disk; not git-tracked but importable if CWD/sys.path resolves build/. |
| proof-bundle copies | `platform-gateway/frontend/proof/bundle/cain42-convergence-fabric/*` / `private/unpublished/platform-gateway/**` / `clawx-site/evidence/**` | LOW | Verifier/evidence scripts copied into published proof bundles; clawx-site/evidence holds 7 identical copies of cain_37_independent_verifier.py. 457 .py files repo-wide have at least one byte-identical twin. |

**The canonical duplicate pair called out by the directive:** `cain/substrate/cain_trust_kernel.py` is **byte-for-byte identical** to `platform-gateway/cain_trust_kernel.py` (2,361 lines each). The same is true of `fabric_control_plane.py`, `cain_kernel_enforcement.py`, `cain_authority_attenuation.py`, `cain_computer.py` and `runtime_policies.py`. `cain/substrate/` contains 251 tracked `.py` files; **240 are byte-identical** to the `platform-gateway/` module of the same basename and **11 have diverged** (`__init__.py`, `agentops.py`, `cain_mr_client.py`, `cain_sovereign_api.py`, `cain_trust_kernel_api.py`, `cluster_api.py`, `company.py`, `fabric.py`, `main.py`, `pages.py`, `seed_48h_changelog.py`).

`tests/test_substrate_gateway_parity.py` already asserts parity and lists the allowed-drift set; two of the current divergences are **not** benign:

1. `cain/substrate/main.py` lacks the `'/api/v1/control/sovereign'` anonymous-write block added to `platform-gateway/main.py:782` (commit `92c2c47`). The wheel copy still has the vulnerability.
2. `cain/substrate/cain_trust_kernel_api.py:505` retains the `api.verify(data, signature_b64, public_key_b64)` call that the gateway copy replaced (“crashed on every call”).

## 5. Dead-code candidates

| Path | Why it is dead | Severity |
|------|----------------|----------|
| `cain/substrate/ (whole tree)` | Only a handful of runtime imports reference it (cain/kernel.py sys.path, cain/audit.py cain.substrate.trust_graph, cain_cli). The other ~240 modules are unimported duplicates. | MEDIUM |
| `platform-gateway/bin/*.py (14 CLIs)` | No canonical module or test imports them; none referenced by pyproject [project.scripts] except cain_cli_entry. | LOW |
| `cain5/* and platform-gateway/cain5/*` | Standalone CLIs/SDKs imported by nothing canonical. | LOW |
| `SDK/cain10-python-sdk/**/api/**` | Generated client methods imported by nothing. | LOW |
| `CAIN_*_VERIFICATION_BUNDLE/standalone_verifier_*.py` | One-shot verifiers, no importers. | LOW |
| `CAIN42_PUBLIC_VERIFIER/verify_cain42.py` | No importers; evidence-artifact verifier. | LOW |
| `build/lib/**` | Untracked build output (357+ duplicate .py); should not be importable on the path. | MEDIUM |
| `actionproof/{db,engine,rules}.py, billing-service/{db,pricing}.py, cainaccounts/migrate.py, derivation-copilot/{db,billing,verifier}.py, caingrid/cainroute/cainwitness engines, echoworkforce/engine.py, mcp-security-scanner/engine.py` | No importers found; product scaffolding. | LOW |
| `platform-gateway/cain_35/cain_37/cain_41_independent_verifier.py` | Independent verifiers with zero importers. | LOW |
| `platform-gateway/cain_time_travel.py, cain_distributed_adversarial.py, cain_node_main.py, cain_performance_benchmark_tk3.py, trajectory_benchmark.py` | Zero prod importers and zero importing tests. | LOW |

## 6. Undocumented assumptions

Assumptions embedded in enforcement code that materially change its guarantee — none of them are stated in the public claims matrix.

| ID | Where | Assumption | Impact | Severity |
|----|-------|-----------|--------|----------|
| ASSUME-01 | `cain/guard.py:477` | CAIN_ALLOW_OFFLINE_LOCAL defaults to 'true': when the remote gateway is unreachable, guard() does NOT deny — it falls back to the local deterministic baseline. | Central decision plane is silently bypassed by default on network failure, contradicting the module docstring's 'Strict fail-closed'. The local baseline still enforces quarantine/self-authoring/HIGH/CRITICAL/allowlist, so it is a partial, not total, fail-open. | HIGH |
| ASSUME-02 | `cain/frontier/gate.py:40` | resolve_mode() default is CAIN_FRONTIER_MODE='shadow', not 'enforce'. | The frontier gate (capability chain, world model, session, budget) records what WOULD be blocked but does not block unless the env var is set. Invalid values correctly fall back to enforce. | HIGH |
| ASSUME-03 | `cain/mcp_proxy.py:297-298` | Exceptions from the trajectory-aware authorization gate are swallowed at debug level and the call proceeds. | An unreachable/erroring trajectory enforcer is treated as 'no constraint', not as deny — a fail-open inside an enforcement layer (the legacy baseline still runs afterwards). | HIGH |
| ASSUME-04 | `cain/mcp_proxy.py:597` | A capability token minted without a bound model_id (default 'UNSPECIFIED') passes model-continuity with a stated 'UNVERIFIED' reason. | Model substitution is only detectable for tokens that opted into model binding. | MEDIUM |
| ASSUME-05 | `cain/mcp_proxy.py:110 / cain45/hypervisor.py` | MCP identity/plan binding is opt-in (require_identity_binding=False by default); hypervisor _recover_after_restart demotes RUNNING ZoDs. | Default MCPGate does not require runtime attestation unless enabled. | MEDIUM |
| ASSUME-06 | `cain45/hypervisor.py:95` | trust_fn defaults to lambda agent_id: 1.0 (maximum trust) when the caller supplies none. | A hypervisor constructed without a trust function grants the full trust floor; trust is then not evidence-derived for that deployment. | MEDIUM |
| ASSUME-07 | `cain45/hypervisor.py:377,407` | 'allowlisted egress is not enforced in Evolution 1; only deny-all is'; attestation 'hardware_backed is always False: no TPM/TEE exists here'. | Documented in code but not surfaced in the public claims matrix; egress allow-listing and hardware attestation are absent. | MEDIUM |
| ASSUME-08 | `cain/substrate/cain_adversarial_worker.py:256` | Control is 'advisory, not enforced'. | An adversarial-worker control that does not actually block. | MEDIUM |
| ASSUME-09 | `cain/substrate/containment.py:212` | Containment actions are 'reported, not enforced, until thresholds are calibrated on real traffic'. | Moat-7 automated containment may report without acting. | MEDIUM |
| ASSUME-10 | `platform-gateway/cain_cluster_security_properties.py:137` | git_commit is a known placeholder ('cain-dist-moats-v2') in the cluster identity, so the software-attestation property is self-reported VIOLATED. | Cluster image provenance is a placeholder; the code honestly flags it. | MEDIUM |
| ASSUME-11 | `cain/mcp_proxy.py:774` | Postcondition default is UNVERIFIED unless a checker is registered for the tool. | Honest, but means effect verification is opt-in per tool; most deployments will report UNVERIFIED. | LOW |
| ASSUME-12 | `AGENTS.md (repo root & platform-gateway)` | 200 formal invariants and 120 adversarial vectors are claimed 200/200 and 120/120; the file itself states these were NOT re-verified in the 2026-09-27 audit. | Public assurance numbers exceed the current verified evidence. | MEDIUM |
| ASSUME-13 | `cain/substrate/cain_distributed_trust.py:196` | Merged trust 'cannot exceed 2 * the average' ('simple cap for now'). | Ad-hoc cap in federated trust merge. | LOW |
| ASSUME-14 | `platform-gateway/cain_runtime_trust.py:6592` | AWS KMS path imports boto3 at call time and raises if absent; no local-enclave fallback assertion in the trust path. | Trust-root key custody depends on an optional dependency. | LOW |
| ASSUME-15 | `CAIN45_BYPASS_AUDIT.json (repo root)` | RAW: an agent that calls its undecorated tool or opens its own socket always executes. | The SDK surfaces (guard/wrap/adapters/MCPGate) are opt-in libraries; only the CAIN-45 confined ZoD is non-bypassable. Recorded as GAP by the project's own audit. | CRITICAL |

## 7. Security gaps

| ID | Gap | Severity | Evidence |
|----|-----|----------|----------|
| GAP-01 | Raw execution bypass (in-process surfaces are opt-in) | CRITICAL | CAIN45_BYPASS_AUDIT.json: raw-process RAW tool_ran=true, GAP; conclusion: 'An agent that calls its tool directly, or opens its own socket, is not stopped by anything in CAIN-42.' |
| GAP-02 | Shipped wheel copy of main.py lacks the anonymous-write fix on /api/v1/control/sovereign | HIGH | cain/substrate/main.py vs platform-gateway/main.py:782 (commit 92c2c47). |
| GAP-03 | Hard-coded fallback passphrase for the KMS signing key at rest | HIGH | platform-gateway/cain_kms.py:84. |
| GAP-04 | Offline fallback is allowed by default (CAIN_ALLOW_OFFLINE_LOCAL=true) | HIGH | cain/guard.py:477. |
| GAP-05 | Frontier gate defaults to shadow (non-blocking) | HIGH | cain/frontier/gate.py:40 (default 'shadow'). |
| GAP-06 | Trajectory gate exceptions fail open | HIGH | cain/mcp_proxy.py:297-298. |
| GAP-07 | Self-signed A2A delegation passports accepted | HIGH | cain/universal_wrapper.py:455-465,499 (verify with same fabric key). |
| GAP-08 | Shell and infra mutation shipped as ungoverned microservices | HIGH | talos-coder/daemon/tools/run_command.py:48; cain-microservices/swarm-orchestrator, orchestrator, resilience-controller; platform-gateway/resilience_controller.py; platform-gateway/cain_lab_public.py. |
| GAP-09 | Parallel MCP validation stack not wired to the live interceptor | MEDIUM | platform-gateway/mcp_runtime.py not imported by cain/mcp_proxy.py. |
| GAP-10 | eval() on policy expressions in the control loop | MEDIUM | platform-gateway/cain_control_loop.py:2092. |
| GAP-11 | Public assurance counts (200 invariants / 120 vectors) exceed re-verified evidence | MEDIUM | AGENTS.md self-note; CAIN42_L5_BASELINE / truth registry. |
| GAP-12 | Sovereign node keys default to /tmp | MEDIUM | cain/sovereign.py:122. |
| GAP-13 | Duplicated source is a standing drift risk (2 divergences already introduce regressions) | HIGH | 240/251 identical, 11 divergent, 2 security-relevant. |
| GAP-14 | Build artifact tree importable as a second copy of the package | LOW | build/lib/cain/** (357+ duplicate files). |

## 8. Missing tests

Measured by *importing* test modules; suites that drive a module over HTTP/subprocess count as zero importers, so treat this as a lower bound on coverage gaps.

| Path | Detail | Severity |
|------|--------|----------|
| `platform-gateway/main.py` | 7138-line monolith, no importing test (exercised only via HTTP/subprocess by e2e suites); true unit coverage of most routes is therefore indirect. | HIGH |
| `platform-gateway/cain_sentinel.py` | Moat #7 sentinel; 6 production importers, zero importing tests found. | HIGH |
| `platform-gateway/proof.py / proof_api.py` | Proof surfaces; no direct importing tests. | MEDIUM |
| `platform-gateway/events.py` | 12 production importers, no importing test. | MEDIUM |
| `cain45/l5/{authority,boundary,caller_auth,certificate,intent,invariants,autonomy}.py` | L5 governance layer; no importing tests. | MEDIUM |
| `platform-gateway/cain_trust_state_machine.py` | 4 importers, no test. | MEDIUM |
| `platform-gateway/cain_memory_api.py / cain_planner_api.py / cain_control_loop_api.py / agent_security_api.py / identity_api.py / trajectory_api.py / trust_graph_api.py / mcp_enforcement_api.py` | API routers with no direct importing tests. | MEDIUM |
| `cain/substrate/* (all modules)` | Zero importing tests; their platform-gateway twins are tested, but the shipped copies are not directly covered (and have already diverged). | MEDIUM |
| `stats` | Import-graph method: of 1061 canonical production modules, 477 have zero importing tests; 200 canonical modules are imported by nothing at all. | MEDIUM |

## 9. Performance bottlenecks

| ID | Where | Detail | Severity |
|----|-------|--------|----------|
| PERF-01 | `platform-gateway/cain_claim_auditor_[19/20/22].py:163/176/96` | Full pytest subprocess per claim (120s timeout each). | MEDIUM |
| PERF-02 | `platform-gateway/agent_runtime.py:1520,2329,2575,2631` | DB execute/fetchone inside loops; runtime accounting hot path. | LOW |
| PERF-03 | `platform-gateway/fabric.py:533 (validate), :407 (domain_index)` | 4- and 3-deep nested loops over canonical fabric; also in substrate twin. | LOW |
| PERF-04 | `platform-gateway/cain_control_loop.py:861 (analyze)` | 3-deep nested loop analyser. | LOW |
| PERF-05 | `cain/mcp_proxy.py:307 (per call)` | function-local imports + JSON canonicalization + synchronous identity DB lookup on the hot path. | LOW |
| PERF-06 | `platform-gateway/main.py (7138 LOC), cain_runtime_trust.py (12004), cain_control_loop.py (8342)` | Import-time cost / memory per worker of very large modules in one process. | LOW |
| PERF-07 | `cain/mcp_proxy.py:410,443` | json.dumps(sort_keys) for the context digest on every call instead of a pre-serialized canonical form. | LOW |

## 10. Top 15 gaps, prioritized by severity

| # | Severity | Gap | Remediation | Evidence |
|---|----------|-----|-------------|----------|
| 1 | **CRITICAL** | Raw execution bypass: agent code that does not call the SDK/MCPGate is not governed at all. | Make confinement non-optional: run agents only inside CAIN-45 ZoDs (bwrap+cgroup, broker-only egress) rather than relying on opt-in decorators. | CAIN45_BYPASS_AUDIT.json GAP/RAW |
| 2 | **HIGH** | Shipped wheel main.py is missing the /api/v1/control/sovereign anonymous-write fix (security drift in cain/substrate). | Delete cain/substrate and build the wheel from the live tree, or make the parity test fail the build (tests/test_substrate_gateway_parity.py already exists). | cain/substrate/main.py vs platform-gateway/main.py:782 |
| 3 | **HIGH** | Hard-coded fallback passphrase protects the KMS signing key at rest when CAIN_KMS_MASTER_KEY / CAIN_JWT_SECRET are unset. | Generate a random per-host passphrase sealed with the OS root of trust, or refuse to start when no master key is supplied. | platform-gateway/cain_kms.py:84 |
| 4 | **HIGH** | guard() defaults to offline-local fallback when the gateway is unreachable (CAIN_ALLOW_OFFLINE_LOCAL=true). | Default CAIN_ALLOW_OFFLINE_LOCAL=false; make the local baseline an explicit operator opt-in with a signed config. | cain/guard.py:477 |
| 5 | **HIGH** | Frontier gate default mode is 'shadow' — capability chain, world model, session and budget do not block. | Default CAIN_FRONTIER_MODE=enforce in production, or refuse production startup when it is shadow. | cain/frontier/gate.py:40 |
| 6 | **HIGH** | Trajectory authorization gate swallows exceptions (fail-open). | Treat enforcer errors as DENY when a trajectory is expected (mirror the fabric-gate fail-closed pattern). | cain/mcp_proxy.py:297-298 |
| 7 | **HIGH** | A2A delegation passports verified against the presenter's own key. | Verify the passport against the registered root/parent principal key, not the embedded/same-fabric key. | cain/universal_wrapper.py:455-465,499 |
| 8 | **HIGH** | Ungoverned shell / infra-mutation microservices (talos-coder, swarm-orchestrator k8s, orchestrator/resilience docker, lab docker stop/start, k8s controller). | Route every infrastructure mutation through a ZoD/grant; or isolate these services behind MCPGate with default-deny. | talos-coder/daemon/tools/run_command.py:48; cain-microservices/*; platform-gateway/cain_lab_public.py:81; platform-gateway/resilience_controller.py:3 |
| 9 | **HIGH** | Duplicate source (240/251 identical, 11 divergent) is a standing drift risk; two divergences are already regressions. | Single source of truth: generate cain/substrate from platform-gateway at build time, and gate on tests/test_substrate_gateway_parity.py. | cain/substrate vs platform-gateway |
| 10 | **MEDIUM** | Two parallel MCP gatekeeping stacks; mcp_runtime.py is not wired to the live interceptor. | Route mcp_runtime validation through MCPTransparentInterceptor (or remove it) so there is one gate. | platform-gateway/mcp_runtime.py |
| 11 | **MEDIUM** | eval() on policy expressions in cain_control_loop.py (and substrate copy). | Use the AST-based SafeExpressionEvaluator without eval(compile(...)) or replace with a declarative policy DSL. | platform-gateway/cain_control_loop.py:2092 |
| 12 | **MEDIUM** | Public assurance counts (200 invariants / 120 vectors) exceed re-verified evidence. | Re-run and publish per-invariant results, or downgrade the public numbers to what the truth registry evidences. | AGENTS.md; CAIN42_PUBLIC_CLAIMS_MATRIX.json |
| 13 | **MEDIUM** | Moat #7 sentinel and the L5 governance layer (+ main.py) have no importing tests. | Add direct unit/import tests for cain_sentinel, cain45/l5/*, and the main.py route table. | import-graph analysis; 477 modules with zero importing tests |
| 14 | **MEDIUM** | Sovereign node keys default to /tmp/cain-sovereign-keys. | Default to a root-owned 0700 directory with an explicit config; fail if the path is world-writable. | cain/sovereign.py:122 |
| 15 | **MEDIUM** | Build artifact tree (build/lib/**) importable as a second copy of the package. | Remove build/ from the repo/working tree and ensure it is never on sys.path/importable. | build/lib/cain/** |

## 11. Honesty statement

- This audit used static analysis only: import-graph reachability plus pattern search. It did not execute the production system, so a governed *file* is not a claim that *every* call site within it is governed.
- No source file was modified. The only files written are `CAIN42_L5_REPOSITORY_AUDIT.md` and `CAIN42_L5_REPOSITORY_AUDIT.json`.
- Prior project artefacts already document the master bypass: `CAIN45_BYPASS_AUDIT.json` (raw-process `RAW` verdict `GAP`) and the self-noted un-re-verified 200-invariant / 120-vector counts in `AGENTS.md`. This audit reproduces and extends those findings rather than discovering them for the first time.
- Where a governance boundary's own act performs a consequential effect (e.g. `cain/mcp_proxy.py:855` spawning the downstream MCP server, `cain45/hypervisor.py` writing its evidence DB), the finding is **GOVERNED** because that act *is* the boundary; it is not evidence of a gap.

---

*Generated read-only by the CAIN-42 L5 Part 40 repository auditor.*
