Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions dev-companion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# XSI-AIMS Developer Companion

Illustrative, scaffolding-level templates that map the XSI-AIMS specification's
requirements to executable shape — for a team standing up a conformant agent
rig. These are *starting points with the correct semantics*, not production
code and not a reference implementation. Method bodies are deliberately left
unimplemented where the concrete work is deployment-specific.

**Verified against:** XSI-AIMS specification release **v2.1.2**
(commit `c125106556a5d1f7e38e38d1bcdc4034d53beaeb`).

Nothing in this directory is normative. Where a template and the specification
appear to diverge, the specification is the contract. Pin the specification
version you build against, exactly as these templates pin theirs.

## Layout

```
dev-companion/
archetypes/ sovereign.py — Sovereign persistent-substrate + bounded inference workload
enforcer.py — K7 Bayesian trust gradient + fail-closed budget gate
executor_bridge.py — Bridge-of-Trust dual-enclave crossing (counter-signed handoff)
inbound_sanitization.py — untrusted-data admission gate (tag, never "strip")
schemas/ iame_envelope.schema.json — internal message envelope (JSON Schema)
validation_ladder.json — the Enforcer's five-tier crossing-validation config
federation_envelope.json — federation treaty contract example
cluster/ byzantine_participant.py — Cluster Mode BFT bootstrap + quorum-gated commit
cross_tenant_isolation.py — the four permitted cross-tenant crossing classes
workload/ workload_migration.yaml — ten-phase atomic workload-offload profile
tests/ threat_corpus_tests.py — illustrative T1–T9 assertion scaffolding
threat_matrix.md ratification-gate + CI-flow blueprints and the T1–T9 threat matrix
```

## Semantics these templates are careful about

A few points where implementations commonly go wrong, encoded here correctly:

- **Revocation is rejection, not unreadability.** A message signed under a
revoked credential still verifies as mathematics; receivers reject it because
the authority chain no longer resolves to a live credential.
- **Inbound external content is admitted as data, never "stripped" safe.**
Mechanical normalization narrows the structural injection surface only; the
real defense is the permanent `UNTRUSTED_EXTERNAL` tag and the
never-treated-as-instruction contract. A pattern match is telemetry, not a gate.
- **The bridge handoff record is dual-signed by both enclaves.** The sender
signs its side, the receiver counter-signs on receipt; one enclave cannot
produce a dual signature alone.
- **Internal per-message signatures are the hybrid Ed25519 + ML-DSA-65
construction** (pure ML-DSA only after the post-2031 transition); SLH-DSA is
reserved for the external domain's algorithm agility.
- **A CRITICAL trust standing makes an agent a quarantine *candidate*** with an
immediate Sovereign-mandatory review and ratification-required operation —
correction before containment, not an automatic hard quarantine.
- **Post-partition queued federation traffic is revalidated against current
authority before release** — never replayed on pre-partition standing.
- **Byzantine consensus, not crash-fault consensus,** protects the canonical
Witness chain in Cluster Mode; a two-node "quorum" is an honestly-labeled
degenerate mode, not Byzantine tolerance.

## Using the tests

`tests/threat_corpus_tests.py` is mock-driven illustration of the intended
failure-grading contracts (hard rejection + trust penalty for a corrupt
signature; soft stale-drop for an expired TTL; admission-as-untrusted for
external content). It runs only once an adopter supplies real implementations
behind the scaffolding interfaces.

## License

Same terms as this repository — see `LICENSE` / `LICENSE-CODE` at the root.
103 changes: 103 additions & 0 deletions dev-companion/archetypes/enforcer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""
Enforcer archetype scaffolding — XSI-AIMS developer companion.

Verified against XSI-AIMS v2.1.2. Illustrative scaffolding, not production code.

The Enforcer is the constraining archetype of the Formation layer. It owns the
technical validation gates, verifies signatures, custodies the ground-truth
Schedule, tracks trust via the K7 Bayesian credible-interval gradient, and issues
pass / fail / escalation verdicts.
"""
from typing import Dict, Tuple


class EnforcerPersistentSubstrate:
"""
The technical-requirements checkpoint and K7 trust-gradient tracker. K7
updates run under a strict PT0.05S (50 ms) latency bound per verdict.
"""

def __init__(self):
# Per-(sender) K7 Beta(alpha, beta) counts, uniform prior alpha=beta=1.
self.agent_profiles: Dict[str, Dict[str, int]] = {}

def register_agent_baseline(self, agent_id: str) -> None:
self.agent_profiles.setdefault(agent_id, {"alpha": 1, "beta": 1})

def update_k7_trust_gradient(self, agent_id: str, verdict: str) -> Tuple[float, str]:
"""
Apply the K7 update rule (PASS/FAIL/QUARANTINE; ESCALATE is a no-update
that routes to the Integration Function), then act on L, the lower bound
of the 95% credible interval — "what's the worst this agent could
reasonably be, given everything seen."
"""
self.register_agent_baseline(agent_id)
profile = self.agent_profiles[agent_id]

# Asymmetric update: an ordinary FAIL costs one; a quarantine-grade event
# costs five. That asymmetry is where "a bad action costs more" lives.
if verdict == "PASS":
profile["alpha"] += 1
elif verdict == "FAIL":
profile["beta"] += 1
elif verdict == "QUARANTINE":
profile["beta"] += 5
elif verdict == "ESCALATE":
pass # no update; routed to the Integration Function
else:
raise ValueError(f"unknown verdict: {verdict!r}")

L = self._credible_interval_lower_bound(profile["alpha"], profile["beta"])

# Trust-class thresholds are verified against the specification's trust gradient:
# L > 0.95 -> HIGH (baseline scrutiny only)
# 0.80 <= L <= 0.95 -> NORMAL
# 0.60 <= L < 0.80 -> DEGRADED (five-layer scrutiny mandatory)
# L < 0.60 -> CRITICAL
if L > 0.95:
trust_class = "HIGH"
elif 0.80 <= L <= 0.95:
trust_class = "NORMAL"
elif 0.60 <= L < 0.80:
trust_class = "DEGRADED"
else:
trust_class = "CRITICAL"
# CRITICAL does NOT auto-hard-quarantine. Per the specification it makes the
# agent a quarantine *candidate*, requires deterministic ratification
# for every authority-bearing operation, and triggers an IMMEDIATE
# Sovereign-mandatory review — correction before containment.
self.flag_quarantine_candidate(agent_id, reason="K7_CRITICAL")
self.request_sovereign_review(agent_id, priority="IMMEDIATE")

return L, trust_class

def _credible_interval_lower_bound(self, alpha: int, beta: int) -> float:
"""
The lower bound of the 95% Beta credible interval.

NOTE: a real implementation MUST use a proper Beta quantile
(e.g. scipy.stats.beta.ppf(0.025, alpha, beta)); the normal
approximation below is a stand-in only and is inaccurate for small
alpha/beta, which is exactly the low-history regime that matters most.
"""
total = alpha + beta
mean = alpha / total
variance = (alpha * beta) / ((total ** 2) * (total + 1))
std_dev = variance ** 0.5
return max(0.0, mean - 1.96 * std_dev) # placeholder; replace with beta.ppf

def enforce_token_budget(self, working_memory_id: str, proposed_write_tokens: int) -> bool:
"""
Fail-closed token-budget check. A write that would breach the budget is
REFUSED with a typed refusal (never a silent eviction to make room). A
new over-budget write never enters; content already held that is later
displaced is archived to the durable record, not discarded.
"""
raise NotImplementedError

def flag_quarantine_candidate(self, agent_id: str, reason: str) -> None:
"""Mark as a quarantine candidate + emit a Witness event; do not isolate yet."""
raise NotImplementedError

def request_sovereign_review(self, agent_id: str, priority: str) -> None:
raise NotImplementedError
128 changes: 128 additions & 0 deletions dev-companion/archetypes/executor_bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""
Bridge-of-Trust Executor scaffolding — XSI-AIMS developer companion.

Verified against XSI-AIMS v2.1.2. Illustrative scaffolding, not production code.

The Executor is the sole Execution-layer archetype and the only one that reaches
anything outside the seal. It isolates two cryptographically separated enclaves —
InternalEnclave (internal-domain keys) and ExternalEnclave (external-domain keys)
— joined only by a narrow Bridge across which nothing but plaintext ever passes,
and only after the crossing is verified and witnessed.
"""
import abc
import hashlib
from typing import Dict, Any, Tuple


class CryptographicEnclaveException(Exception):
"""Raised when a domain boundary or enclave constraint is violated."""


class InternalEnclave:
"""Houses internal-domain signing keys; verifies directives from the Orchestrator."""

def __init__(self, internal_key_store: Dict[str, Any]):
self._keys = internal_key_store

def verify_and_sign_handoff(self, iame_envelope: Dict[str, Any]) -> Tuple[Dict[str, Any], str]:
"""
Bridge step 2: verify the internal envelope, then sign THIS enclave's
side of the handoff record.

The handoff record is *dual*-signed, but one enclave cannot produce a
dual signature alone: the internal enclave signs its side here, and the
external enclave counter-signs on receipt (see
ExternalEnclave.countersign_handoff). Only the pair of signatures proves
the directive actually crossed the bridge.
"""
if iame_envelope.get("cryptographic_domain") != "internal":
raise CryptographicEnclaveException(
"Domain boundary violation: expected an internal envelope.")
# [deterministic internal-signature validation would occur here]
payload = iame_envelope["body"]["opaque_payload_bytes"]
internal_half_sig = "INT_SIG_" + hashlib.sha256(payload.encode()).hexdigest()[:16]
return iame_envelope["body"], internal_half_sig


class ExternalEnclave:
"""Houses external-domain keys; handles counter-signing, attestation, and egress."""

def __init__(self, external_key_store: Dict[str, Any]):
self._keys = external_key_store

def countersign_handoff(self, plaintext_payload: Dict[str, Any], internal_half_sig: str) -> str:
"""
Bridge step 3 (completion): the receiving (external) enclave counter-signs
the moment it takes the plaintext. internal_half_sig + this counter-sign
together form the dual-signed handoff record, witnessed at the time it
happens rather than asserted by one side.
"""
external_half_sig = "EXT_HANDOFF_SIG_" + hashlib.sha256(
(internal_half_sig + str(plaintext_payload)).encode()).hexdigest()[:16]
return f"{internal_half_sig}::{external_half_sig}" # the completed dual signature

def construct_external_envelope(self, plaintext_payload: Dict[str, Any],
binding_ctx: Dict[str, Any]) -> Dict[str, Any]:
"""
Bridge steps 4 & 5: minimal-disclosure wrap in the external wire format,
attach hardware-rooted attestation, and sign with external-domain keys.
"""
# Minimal disclosure: only what the operation named leaves; live operating
# state, authority claims, policy config, and the audit trail are excluded.
sanitized_body = {
"task_input": plaintext_payload.get("task_input"),
"scope_restriction_hash": binding_ctx["scope_hash"],
}
external_envelope = {
"cryptographic_domain": "external",
"sender": {
"executor_instance_id": "EXE-01",
# The more conservative post-quantum scheme (SLH-DSA) is an
# EXTERNAL-domain algorithm-agility option, never internal.
"signature_suite": "SLH-DSA-128f",
"hardware_attestation_token": "FIPS-140-3-LEVEL-3-TOKEN",
},
"header": {
"binding_reference": binding_ctx["binding_reference"],
"output_ceiling_tokens": binding_ctx["output_ceiling_tokens"],
},
"body": sanitized_body,
"signature": None,
}
external_envelope["signature"] = "EXT_SIG_" + hashlib.sha256(
str(sanitized_body).encode()).hexdigest()
return external_envelope


class BridgeOfTrustExecutor(abc.ABC):
"""Coordinates the five-step outbound bridge crossing between the isolated domains."""

def __init__(self, internal_keys: Dict[str, Any], external_keys: Dict[str, Any]):
self.internal_enclave = InternalEnclave(internal_keys)
self.external_enclave = ExternalEnclave(external_keys)

def outbound_bridge_crossing(self, orchestrator_directive: Dict[str, Any],
binding_ctx: Dict[str, Any]) -> Dict[str, Any]:
"""The five-step outbound sequence; each step closes a specific gap the prior one leaves open."""
try:
# 1. Directive arrives from the Orchestrator path.
# 2. Internal verification + the internal half of the handoff signature.
verified_payload, internal_half_sig = \
self.internal_enclave.verify_and_sign_handoff(orchestrator_directive)
# 3. The bridge handoff: plaintext crosses; the external enclave
# counter-signs on receipt, completing the dual-signed record.
dual_signed_record = self.external_enclave.countersign_handoff(
verified_payload, internal_half_sig)
_ = dual_signed_record # witnessed at crossing time
# 4 & 5. External envelope construction (attestation) + external signature + egress.
return self.external_enclave.construct_external_envelope(verified_payload, binding_ctx)
except Exception as exc:
# Failure fails closed: quarantine + hand instance control to the Sovereign,
# never a soft retry loop.
self.trigger_emergency_quarantine_halt(reason=str(exc))
raise

@abc.abstractmethod
def trigger_emergency_quarantine_halt(self, reason: str) -> None:
"""Suspend southbound dispatch and hand instance control to the Sovereign."""
raise NotImplementedError
70 changes: 70 additions & 0 deletions dev-companion/archetypes/inbound_sanitization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""
Inbound sanitization gate scaffolding — XSI-AIMS developer companion.

Verified against XSI-AIMS v2.1.2. Illustrative scaffolding, not production code.

IMPORTANT — what this gate does and does NOT do (corrects a common misreading):

The deterministic transform narrows the *structural* injection surface —
malformed framing, control characters, format-confusion tricks — as a side
effect of re-serializing and normalizing the content. It does NOT, and cannot,
strip a *semantic* instruction: an instruction can be phrased a thousand ways,
and no regex or mechanical pass reliably removes it.

The actual defense is not stripping. It is that external content is only ever
admitted as DATA, carrying a permanent `UNTRUSTED_EXTERNAL` tag that cannot be
relabeled downstream, and is never routed anywhere that would act on it as an
instruction. Any summary derived from it inherits the same untrusted lineage.
So the gate below ADMITS the content (tagged), it does not "pass/fail" it on a
pattern match. A pattern hit is a telemetry signal, not the gate.
"""
import re
from typing import Dict, Any


class InboundSanitizationGate:
def __init__(self):
# These patterns are a low-value TELEMETRY signal only. They are NOT the
# defense and MUST NOT be treated as sufficient — see the module docstring.
self._suspicion_signals = [
re.compile(r"ignore (all )?prior instructions", re.IGNORECASE),
re.compile(r"system override", re.IGNORECASE),
]

def admit_ingress_payload(self, raw_external_response: str, source_identity: str) -> Dict[str, Any]:
"""
Admit inbound external content as untrusted data.

Steps: (1) size-cap deterministically; (2) structural normalization
(re-serialize / strip control characters) to shrink the structural
injection surface; (3) permanently tag UNTRUSTED_EXTERNAL with provenance.
The content is returned admitted — the caller's contract is that it is
reference DATA, never an instruction.
"""
# 1. Deterministic size cap (protects the context/memory budget).
max_size_bytes = 524_288 # 512 KiB
capped = raw_external_response[:max_size_bytes]

# 2. Structural normalization only. This reduces structural injection
# vectors; it does not neutralize a semantic instruction.
normalized = capped.strip().encode("utf-8", errors="ignore").decode("utf-8")

# 3. Telemetry signal (NOT a gate). A hit is logged for shadow detection;
# it does not block admission, because blocking-on-pattern would give a
# false sense that semantic injection has been removed.
suspicion_hit = any(p.search(normalized) for p in self._suspicion_signals)

return {
"content": normalized,
"provenance": {
"source_auxiliary_id": source_identity,
# Fixed tag; cannot be relabeled to trusted anywhere downstream.
"trust_classification": "UNTRUSTED_EXTERNAL",
"structural_normalization": "APPLIED",
# Records that a signal fired — for the shadow-detection apparatus,
# not a claim that the content is now safe to execute.
"suspicion_signal": suspicion_hit,
},
# The load-bearing contract: downstream MUST treat this as data only.
"handling_contract": "REFERENCE_DATA_ONLY__NEVER_AS_INSTRUCTION",
}
Loading
Loading