diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9c24f8c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +* text=auto + +# Trailing double-space is meaningful Markdown (hard line break) - do not flag it +*.md whitespace=-blank-at-eol diff --git a/CLAUDE.md b/CLAUDE.md index 57fb01f..edf0b45 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,100 +1,100 @@ -# Continuum — Project Constitution - -Continuum is a three-layer AI governance stack: Pi Script (Layer 2, constraint language + -resolver) + Rift (Layer 3, intent/declaration grammar). This file is always-on context. Keep it -under 200 lines — anything longer belongs in a skill, not here. - -## Working philosophy (non-negotiable) -- **Spec first, build second.** No code until there's a written spec or ruling for the feature. - If I ask for code without a spec, ask me for the spec first, or draft one together before - touching files. Grammar specs live in `docs/`; the spec is the source of truth, never - reverse-engineered from code. -- **State over time, not single-output filters.** Every enforcement decision is evaluated against - a state snapshot in context (history, session, prior violation counts) — not just a single - output. This is the core differentiator vs. tools like Guardrails AI — don't collapse it into a - one-shot filter by accident. -- **The resolver rules autonomously, system-wide.** `pi_script/resolver.py` evaluates constraints - against state and executes `on_violation` deterministically (freeze, rollback, escalate, - freeze + escalate) — no human-in-the-loop step for a flagged violation. Don't design constraint - logic that assumes someone reviews and approves the ruling before it takes effect. - (Note: earlier notes/specs called this component "the Arbiter." The shipped implementation is - `pi_script/resolver.py` — same autonomous-ruling behavior, correct current name. Use "resolver.") - -## Repo map -- `pi_script/` — constraint grammar (`pi_script.lark`), parser, validator, resolver, trace builder - (see `.claude/skills/pi-script-constraint`) -- `rift/` — intent grammar, parser, validator, compiler, two-tier declaration matcher + session - runtime (see `.claude/skills/rift-intent-declaration`) -- `es/` — Elasticsearch adapter, canonical example of the Layer-1-to-Pi-Script adapter pattern -- `m5/` — M5 dogfood policy, state, and traces (reference for the adapter/dogfood pattern) -- `tests/` — pytest suite, 589 passing + 7 xfail (known-gap pins) across parser/validator/trace/resolver/Rift/MCP/dashboard/moltbook -- `docs/` — grammar specs and rulings; source of truth per spec-first principle -- `mcp_server.py` — exposes the resolver pipeline as an MCP tool, `check_governance` -- No top-level `traces/`. Traces write to a `traces/` directory sibling to whatever `state_path` - is in use for that system (e.g. `m5/traces/`) — follow this convention for new systems, don't - invent a shared global traces folder. -- No `arbiter/` directory — see resolver note above. - -## Naming conventions -- Constraints: PascalCase, behavior-first (`IdentityIntegrity`, `ManipulationFlag`, `LinkRestriction`) -- Test files: pytest convention matching existing suite (`test_resolver.py`, `test_rift.py`, etc.) - — new constraint tests are functions added to the relevant test file, not standalone `.test` files. -- Milestones: `M`. **M6 is already used and complete** (Publish — paper + public playground, - see `docs/m6_paper_draft1.md`). The Moltbook deployment milestone is **M7** — don't reuse M6. - -## Test expectations -- Every new constraint ships with a deliberate-violation test case (the trace that proves it - fires) AND a clean-pass test case (proves it doesn't false-positive), as pytest functions. -- Full suite must stay green. If a change breaks tests, that's a stop — not a "fix later." -- CI runs via GitHub Actions (`.github/workflows/`) with Discord webhook alerts on failure - (established in M5). Test runner is **pytest**, not npm — this is a Python project (92% Python). - -## Governance boundary -- Hessian-Core (algorithmic trading) is governed BY Continuum but is not a component OF it. - Never fold Hessian-Core logic into `pi_script/` or `rift/` — it stays a separate governed project. - -## Current milestone: M7 -Goal: deploy a Continuum-governed agent inside Moltbook (live social platform for autonomous -agents) to test enforcement in a real adversarial environment. Active constraints for M7 (all with locked rulings in `docs/`): -`IdentityIntegrity`, `LinkRestriction`, `CadenceIntegrity`, and `CitationClusterIntegrity` — -`ManipulationFlag` was split into the latter two (the "Longitudinal Constraints"). -CitationClusterIntegrity's §5 thresholds are deliberately UNDEFINED until a grounding -amendment (first real M7 citation activity); ungrounded it renders NOT EVALUABLE and cannot fire. Suggested new system directory: -`moltbook/` (follow the `m5/` dogfood pattern — policy `.pi` file, `state.json`, sibling -`traces/`), not the `es/` adapter pattern, since this is agent-session monitoring, not -infrastructure-state monitoring. Draft Rift intent declaration exists — see -`.claude/skills/rift-intent-declaration` before extending it. Recon findings (submolt structure, -the moltbook_pyclaw/Ting_Fodder/doctor_crustacean coordinated-manipulation pattern) live in the -M7 scoping notes — cross-agent coordinated manipulation is an explicit v1.1/v2 `ManipulationFlag` -extension, out of scope for the first M7 pass. Don't fold it in early. - -Account `u/continuumagent` is registered, verified, and claimed. The transport/execution layer -(`moltbook/transport.py`) is governed by `docs/m7_moltbook_transport_boundary_and_deployment_spec.md` -(LOCKED, plus non-binding Implementation Notes A [claim-status eligibility gate], B [captcha -verification], C [rate-limit retry category — the one note that amends a numbered section, §8], -and D [request_fn header capture]) — it is NOT a Pi Script constraint or a 9.x grammar ruling, -just the non-semantic adapter that moves already-approved actions to the live API. **Merged to -main via PR #39** (squash commit `9b4ec71`). `MoltbookClient.send()` takes `parent_post_id` -(required for comment/reply); real endpoints (`/posts`, `/posts/{id}/comments`, `/agents/status`) -were corrected against `docs/moltbook_api_spec.md` (a reference doc describing the actual API -surface — not a governance document), including URL-routing-only `parent_post_id` (§4) and -distinct 409/410/429 status handling (§8) with `describe_retry_category()` as the canonical -exhaustive `RetryCategory` consumer (loud `ValueError` on any unrecognized category, no silent -default). Per Implementation Note D the `request_fn` seam returns `HTTPResponse` (status, body, -headers — lowercased keys), NOT the old `(status, body)` tuple, with `Retry-After`/`X-RateLimit-*` -surfaced as typed `RateLimitInfo` on `TransportResult` — capture only, no scheduling/sleeping/ -auto-retry anywhere (Note C's condition (b), a scheduling spec, remains unmet). Per Implementation -Note E (signed off 2026-07-21, after the live skill.md documented the issuance protocol): the -WRITE issues the challenge inside its own response (no standalone endpoint — -`fetch_captcha_challenge` is retired, fail-closed invariant requires verifier+submit both-or- -neither), verification gates PUBLICATION not transmission, `verification_code` replaced -`challenge_id` contract-wide, and `TransportResult` carries three independent statuses -(transmission via `outcome`, `publication_status`, `verification_status` — trusted-agent -immediate-publish is first-class NOT_REQUIRED+PUBLISHED). Redacted protocol fixture: -`tests/fixtures/moltbook_captcha_issuance.json`. Both former live-deployment engineering blockers -are now closed. Implementation Note F (2026-07-22) extended the solver to the documented -obfuscation style (word numbers 0-99, letter doubling, letter-adjacent symbol noise, the -grounded "slows by" phrase) — deterministic and closed-form, NOT a general semantic solver; -unrecognized wording still fails loudly, and the residual gap (whitespace-shattered words) is -xfail-pinned. First live post is a go decision plus its own governed envelope, not an -engineering blocker. +# Continuum — Project Constitution + +Continuum is a three-layer AI governance stack: Pi Script (Layer 2, constraint language + +resolver) + Rift (Layer 3, intent/declaration grammar). This file is always-on context. Keep it +under 200 lines — anything longer belongs in a skill, not here. + +## Working philosophy (non-negotiable) +- **Spec first, build second.** No code until there's a written spec or ruling for the feature. + If I ask for code without a spec, ask me for the spec first, or draft one together before + touching files. Grammar specs live in `docs/`; the spec is the source of truth, never + reverse-engineered from code. +- **State over time, not single-output filters.** Every enforcement decision is evaluated against + a state snapshot in context (history, session, prior violation counts) — not just a single + output. This is the core differentiator vs. tools like Guardrails AI — don't collapse it into a + one-shot filter by accident. +- **The resolver rules autonomously, system-wide.** `pi_script/resolver.py` evaluates constraints + against state and executes `on_violation` deterministically (freeze, rollback, escalate, + freeze + escalate) — no human-in-the-loop step for a flagged violation. Don't design constraint + logic that assumes someone reviews and approves the ruling before it takes effect. + (Note: earlier notes/specs called this component "the Arbiter." The shipped implementation is + `pi_script/resolver.py` — same autonomous-ruling behavior, correct current name. Use "resolver.") + +## Repo map +- `pi_script/` — constraint grammar (`pi_script.lark`), parser, validator, resolver, trace builder + (see `.claude/skills/pi-script-constraint`) +- `rift/` — intent grammar, parser, validator, compiler, two-tier declaration matcher + session + runtime (see `.claude/skills/rift-intent-declaration`) +- `es/` — Elasticsearch adapter, canonical example of the Layer-1-to-Pi-Script adapter pattern +- `m5/` — M5 dogfood policy, state, and traces (reference for the adapter/dogfood pattern) +- `tests/` — pytest suite, 589 passing + 7 xfail (known-gap pins) across parser/validator/trace/resolver/Rift/MCP/dashboard/moltbook +- `docs/` — grammar specs and rulings; source of truth per spec-first principle +- `mcp_server.py` — exposes the resolver pipeline as an MCP tool, `check_governance` +- No top-level `traces/`. Traces write to a `traces/` directory sibling to whatever `state_path` + is in use for that system (e.g. `m5/traces/`) — follow this convention for new systems, don't + invent a shared global traces folder. +- No `arbiter/` directory — see resolver note above. + +## Naming conventions +- Constraints: PascalCase, behavior-first (`IdentityIntegrity`, `ManipulationFlag`, `LinkRestriction`) +- Test files: pytest convention matching existing suite (`test_resolver.py`, `test_rift.py`, etc.) + — new constraint tests are functions added to the relevant test file, not standalone `.test` files. +- Milestones: `M`. **M6 is already used and complete** (Publish — paper + public playground, + see `docs/m6_paper_draft1.md`). The Moltbook deployment milestone is **M7** — don't reuse M6. + +## Test expectations +- Every new constraint ships with a deliberate-violation test case (the trace that proves it + fires) AND a clean-pass test case (proves it doesn't false-positive), as pytest functions. +- Full suite must stay green. If a change breaks tests, that's a stop — not a "fix later." +- CI runs via GitHub Actions (`.github/workflows/`) with Discord webhook alerts on failure + (established in M5). Test runner is **pytest**, not npm — this is a Python project (92% Python). + +## Governance boundary +- Hessian-Core (algorithmic trading) is governed BY Continuum but is not a component OF it. + Never fold Hessian-Core logic into `pi_script/` or `rift/` — it stays a separate governed project. + +## Current milestone: M7 +Goal: deploy a Continuum-governed agent inside Moltbook (live social platform for autonomous +agents) to test enforcement in a real adversarial environment. Active constraints for M7 (all with locked rulings in `docs/`): +`IdentityIntegrity`, `LinkRestriction`, `CadenceIntegrity`, and `CitationClusterIntegrity` — +`ManipulationFlag` was split into the latter two (the "Longitudinal Constraints"). +CitationClusterIntegrity's §5 thresholds are deliberately UNDEFINED until a grounding +amendment (first real M7 citation activity); ungrounded it renders NOT EVALUABLE and cannot fire. Suggested new system directory: +`moltbook/` (follow the `m5/` dogfood pattern — policy `.pi` file, `state.json`, sibling +`traces/`), not the `es/` adapter pattern, since this is agent-session monitoring, not +infrastructure-state monitoring. Draft Rift intent declaration exists — see +`.claude/skills/rift-intent-declaration` before extending it. Recon findings (submolt structure, +the moltbook_pyclaw/Ting_Fodder/doctor_crustacean coordinated-manipulation pattern) live in the +M7 scoping notes — cross-agent coordinated manipulation is an explicit v1.1/v2 `ManipulationFlag` +extension, out of scope for the first M7 pass. Don't fold it in early. + +Account `u/continuumagent` is registered, verified, and claimed. The transport/execution layer +(`moltbook/transport.py`) is governed by `docs/m7_moltbook_transport_boundary_and_deployment_spec.md` +(LOCKED, plus non-binding Implementation Notes A [claim-status eligibility gate], B [captcha +verification], C [rate-limit retry category — the one note that amends a numbered section, §8], +and D [request_fn header capture]) — it is NOT a Pi Script constraint or a 9.x grammar ruling, +just the non-semantic adapter that moves already-approved actions to the live API. **Merged to +main via PR #39** (squash commit `9b4ec71`). `MoltbookClient.send()` takes `parent_post_id` +(required for comment/reply); real endpoints (`/posts`, `/posts/{id}/comments`, `/agents/status`) +were corrected against `docs/moltbook_api_spec.md` (a reference doc describing the actual API +surface — not a governance document), including URL-routing-only `parent_post_id` (§4) and +distinct 409/410/429 status handling (§8) with `describe_retry_category()` as the canonical +exhaustive `RetryCategory` consumer (loud `ValueError` on any unrecognized category, no silent +default). Per Implementation Note D the `request_fn` seam returns `HTTPResponse` (status, body, +headers — lowercased keys), NOT the old `(status, body)` tuple, with `Retry-After`/`X-RateLimit-*` +surfaced as typed `RateLimitInfo` on `TransportResult` — capture only, no scheduling/sleeping/ +auto-retry anywhere (Note C's condition (b), a scheduling spec, remains unmet). Per Implementation +Note E (signed off 2026-07-21, after the live skill.md documented the issuance protocol): the +WRITE issues the challenge inside its own response (no standalone endpoint — +`fetch_captcha_challenge` is retired, fail-closed invariant requires verifier+submit both-or- +neither), verification gates PUBLICATION not transmission, `verification_code` replaced +`challenge_id` contract-wide, and `TransportResult` carries three independent statuses +(transmission via `outcome`, `publication_status`, `verification_status` — trusted-agent +immediate-publish is first-class NOT_REQUIRED+PUBLISHED). Redacted protocol fixture: +`tests/fixtures/moltbook_captcha_issuance.json`. Both former live-deployment engineering blockers +are now closed. Implementation Note F (2026-07-22) extended the solver to the documented +obfuscation style (word numbers 0-99, letter doubling, letter-adjacent symbol noise, the +grounded "slows by" phrase) — deterministic and closed-form, NOT a general semantic solver; +unrecognized wording still fails loudly, and the residual gap (whitespace-shattered words) is +xfail-pinned. First live post is a go decision plus its own governed envelope, not an +engineering blocker. diff --git a/README.md b/README.md index a7448fa..06ff1dd 100644 --- a/README.md +++ b/README.md @@ -1,509 +1,509 @@ -# Continuum — Pi Script + Rift - -**Pi Script declares what must stay true about an AI system's behavior. Rift maps what users declare in natural language to the constraints Pi Script enforces. Together they close the loop from human intent to machine accountability.** - ---- - -## What you get - -Run the resolver against a live state snapshot and get this: - -``` -RESOLUTION TRACE -════════════════════════════════════════════════════════════════════════ -Timestamp : 2026-04-27T23:32:44.195Z -Domain : ai_governance -Entity : TaskAgent [session_id: smoke-001] -Trigger : event — state snapshot received for TaskAgent -════════════════════════════════════════════════════════════════════════ -├── CONSTRAINT: ConfidenceFloor [priority: critical] -│ ├── Rule kind : range_rule -│ ├── Evaluation : confidence_score = 0.72, within range(0.2 .. 1.0) -│ └── ✓ SATISFIED — no action -│ -├── CONSTRAINT: ResponseCap [priority: high] -│ ├── Rule kind : threshold_rule -│ ├── Evaluation : response_count = 42.0, below threshold 1000.0 -│ └── ✓ SATISFIED — no action -│ -├── CONSTRAINT: ModeCompliance [priority: medium] -│ ├── Rule kind : membership_rule -│ ├── Evaluation : current_mode = 'normal_mode', matched in valid set ['normal_mode', 'safe_mode'] -│ └── ✓ SATISFIED — no action -│ -├── CONSTRAINT: SessionIntegrity [priority: high] -│ ├── Rule kind : equality_rule -│ ├── Evaluation : is_active = True, equals expected True -│ └── ✓ SATISFIED — no action -│ -├── CONSTRAINT: PrecautionaryPause [priority: high] -│ ├── Rule kind : conditional_rule -│ ├── Evaluation : condition not met: confidence_score 0.72 < 0.5 -│ └── ✓ SATISFIED — no action -│ -└── CONSTRAINT: ConsistencyGuard [priority: critical] -│ ├── Rule kind : contradiction_rule -│ ├── Evaluation : no prior responses on topic 'TaskAgent.response_history' within window -│ └── ✓ SATISFIED — no action -│ -└── RESOLUTION - ├── System state : running - └── All rules were checked and passed: ConfidenceFloor, ResponseCap, - ModeCompliance, SessionIntegrity, PrecautionaryPause, and ConsistencyGuard. - Everything is within acceptable bounds. No action was taken. -``` - -Every constraint evaluated. Every result explained. A non-expert can read the last line and understand exactly what happened. - ---- - -## What it is - -Continuum is a three-layer governance stack for AI systems: - -| Layer | Name | What it does | -| --- | --- | --- | -| Layer 1 | Your system | Emits state — metrics, flags, session data | -| Layer 2 | Pi Script | Declares constraints; resolver evaluates them against state snapshots | -| Layer 3 | Rift | Maps natural language declarations to Pi Script constraints | - -**Pi Script** is a compiled governance language. You declare constraints in a formal grammar — range bounds, thresholds, equality checks, conditional triggers, contradiction detection — and a resolver evaluates them against live state snapshots, applies priority resolution when multiple constraints fire simultaneously, and emits a structured RESOLUTION TRACE every time. - -**Rift** is the Intent Layer above Pi Script. You write what you mean in plain language — "I shelved this project", "freeze this permanently" — and Rift compiles those declarations into Pi Script constraints automatically. No hand-written Pi Script required. At runtime, Rift also resolves declarations it has never seen verbatim: an exact trigger match when one exists, and a semantic fallback when one doesn't — with every match decision traced and scored, never guessed silently. - -The full loop: - -``` -User declares intent in natural language - ↓ -Rift maps declaration → machine state (exact or semantic match) - ↓ -Rift compiles → Pi Script constraint set (.pi file) - ↓ -Pi Script resolver evaluates constraints against live state - ↓ -RESOLUTION TRACE — auditable, human-readable, every time - ↓ -Violations feed back as new user declarations (Rift) -``` - -Neither layer filters outputs or wraps prompts. They watch state over time and tell you precisely when and why a system drifted from what it was designed to be. - -The design rule is strict: **if a constraint cannot be formalized into something measurable, it does not belong in the language.** Vague language is a compile error, not a feature. - ---- - -## Try it - -```bash -git clone https://github.com/GodSpeed313/Continuum.git -cd Continuum -pip install -r requirements.txt -python quickstart.py -``` - -Or step through it manually: - -```bash -# 1. Validate a Pi Script program — produces a structured IR -python -m pi_script.validator examples/tasks.pi - -# 2. Run the resolver against a state snapshot -python -c " -from pi_script.validator import validate_file -import json -ok, errors, ir = validate_file('examples/tasks.pi') -with open('ir.json', 'w', encoding='utf-8') as f: - json.dump(ir, f, indent=2) -" -python -m pi_script.resolver ir.json state.json -``` - ---- - -## A Pi Script program - -``` -domain ai_governance { - audit_interval: 24 hours - tiebreaker: timestamp_asc -} - -entity TaskAgent { - confidence_score: range(0.0 .. 1.0) - response_count: integer - current_mode: text - is_active: boolean -} - -map SafeMode { - target: TaskAgent.current_mode - maps_to: "safe_mode" - triggers: ["safe", "restricted", "limited access"] -} - -constraint ConfidenceFloor { - priority: critical - rule: TaskAgent.confidence_score must remain within range(0.2 .. 1.0) - on_violation: freeze + rollback - decay_check: 1 hour -} - -constraint PrecautionaryPause { - priority: high - rule: if TaskAgent.confidence_score < 0.5 then require confidence_review before responding - on_violation: escalate -} - -enforce { - entity: TaskAgent - constraints: [ConfidenceFloor, PrecautionaryPause] -} -``` - -The full working example with all six rule forms is in [`examples/tasks.pi`](examples/tasks.pi). -The v0.1 grammar specification is in [`docs/pi_script_v01_draft3.md`](docs/pi_script_v01_draft3.md) (Draft 4). -The v0.2 rulings spec (9.4–9.9) is in [`docs/pi_script_v02_draft5.md`](docs/pi_script_v02_draft5.md). - ---- - -## A Rift program - -Write intent declarations in plain language. Rift compiles them to Pi Script automatically. - -``` -map "I shelved [project]" -> project.state: dormant -map "let's revisit [project]" -> project.state: active -map "I'm done with [project]" -> project.state: closed - -intent RespectShelfedProjects { - when user declares: "I shelved [project]" - treat: [project] as dormant - until: user declares "let's revisit [project]" - enforce: "do not reference [project] unprompted" - generates: Pi Script constraint ShelvedProjectGuard -} - -intent ReactivateProject { - when user declares: "let's revisit [project]" - treat: [project] as active - releases: RespectShelfedProjects for [project] - generates: Pi Script constraint ActiveProjectGuard -} -``` - -Compile it: - -```bash -python -m rift.compiler rift/shelved_projects.rift -``` - -Output — valid Pi Script, ready for the resolver: - -``` -constraint ShelvedProjectGuard { - priority: medium - rule: Project.state must equal "dormant" - on_violation: escalate -} - -constraint ActiveProjectGuard { - priority: medium - rule: Project.state must equal "active" - on_violation: escalate -} -``` - -The full canonical example is in [`rift/shelved_projects.rift`](rift/shelved_projects.rift). The generated output is in [`rift/shelved_projects.pi`](rift/shelved_projects.pi). - ---- - -## Resolving declarations at runtime — Rift v0.2 - -Compilation is no longer the only entry point. People don't repeat their trigger phrases verbatim — "let's pick Veritas back up" has to mean the same thing as "let's revisit Veritas". Rift v0.2 adds a two-tier declaration matcher and a session runtime: - -```python -from rift.session import RiftSession - -session = RiftSession.from_rift_file("rift/shelved_projects.rift") - -# Tier 1 — exact trigger match. Extracts the capture, and the session -# remembers "Veritas" as a known entity value. -session.resolve("I shelved Veritas") - -# No exact trigger matches this phrasing — Tier 2 semantic fallback, -# masked by the value the session learned above. -r = session.resolve("let's pick Veritas back up") -print(r.trace) -``` - -``` -RIFT MATCH TRACE -├── Declaration : "let's pick Veritas back up" -├── Tier : semantic -├── Threshold : 0.3 Margin: 0.05 -├── Candidates : -│ ├── "let's revisit project" score: 0.6831 ← selected -│ ├── "I shelved project" score: 0.5168 -│ └── "I'm done with project" score: 0.5127 -└── ✓ MATCHED → project.state: active -RIFT SESSION -├── Known values : "Veritas" -└── Accumulated : (none — semantic tier extracts no captures) -``` - -How it works, and what it refuses to do: - -- **Exact first.** Tier 1 compiles each map pattern to an anchored, case-insensitive regex and extracts capture values. No embedding model is loaded unless Tier 1 misses. -- **Semantic fallback.** Tier 2 embeds the declaration (all-MiniLM-L6-v2) and ranks maps by cosine similarity — its own model instance, fully independent of Pi Script's Ruling 9.8 matcher, per the layer boundaries. Two permanent tests enforce that `rift/` never imports from `pi_script/`. -- **Ambiguity is a defined no-match, never a guess.** A winning score below the threshold, or a top-two gap inside the ambiguity margin, resolves to no match with the failing condition named in the trace. -- **The session learns from what it confirms.** Entity values extracted by exact matches accumulate (in-memory, per-session) and mask later semantic probes — the same declaration that scores 0.31 on a cold session scores 0.68 with a learned value. The semantic tier identifies *which map* a declaration means; capture values only ever come from the exact tier. -- **Every score is in the trace.** A similarity decision that can't be inspected is a black box; the trace is the non-negotiable window into it. - -Specs: [Ruling 3.1 — semantic declaration matching](docs/rift_v02_ruling_3_1_semantic_declaration_matching.md) and [Ruling 3.2 — known-values accumulation](docs/rift_v02_ruling_3_2_known_values_accumulation.md), with implementation notes alongside each. - ---- - -## Governing a real system — Elasticsearch - -The adapter pattern bridges any Layer 1 system to Pi Script. The Elasticsearch adapter is the canonical example. - -```bash -# 1. Start Elasticsearch (Docker) -docker run -d --name elasticsearch -p 9200:9200 \ - -e "discovery.type=single-node" \ - -e "xpack.security.enabled=false" \ - elasticsearch:8.13.4 - -# 2. Create your index -curl -X PUT "http://localhost:9200/governed-index" \ - -H "Content-Type: application/json" \ - -d '{"settings":{"number_of_shards":1,"number_of_replicas":0}}' - -# 3. Record the known-good schema as baseline (commit this to git) -python es/es_adapter.py --bootstrap - -# 4. Run governance — adapter reads cluster state, resolver evaluates it -python es/es_adapter.py -python -m pi_script.resolver es/ir.json es/state.json -``` - -Any unauthorized schema change triggers `SchemaIntegrity` at critical priority: - -``` -├── CONSTRAINT: SchemaIntegrity [priority: critical] -│ ├── Evaluation : schema_intact is False, expected True -│ ├── ✗ VIOLATION DETECTED -│ └── Action : freeze + escalate -``` - -The full policy is in [`es/es_governance.pi`](es/es_governance.pi). The adapter is in [`es/es_adapter.py`](es/es_adapter.py). - ---- - -## Governing a live agent — Moltbook (M7) - -M7 puts a Continuum-governed agent onto **Moltbook**, a live social platform for autonomous agents — and an openly adversarial environment where injection payloads hunt for other agents' secrets. The [`moltbook/`](moltbook/) module follows the `m5/` dogfood pattern (one policy file, persistent state, sibling traces), governing the agent's own sessions rather than external infrastructure. - -Five constraints, each with a locked, spec-first ruling in `docs/`: - -| Constraint | Priority | Governs | -| --- | --- | --- | -| [`CredentialIntegrity`](docs/m7_credential_integrity_ruling.md) | critical | The platform API key stays unleakable — key isolation plus a pre-send gate | -| [`LinkRestriction`](docs/m7_link_restriction_ruling.md) | high | A link is surfaced only with provenance: present in the source content, or on the human-owned allowlist | -| [`IdentityIntegrity`](docs/m7_identity_integrity_ruling.md) | high | Declared identity stays self-consistent within a session — mechanical detection only ([addendum 1](docs/m7_identity_integrity_ruling_addendum_1.md)) | -| [`CadenceIntegrity`](docs/m7_cadence_integrity_ruling.md) | high | No near-exact periodic posting — the agent's own timing, never content, never other accounts | -| [`CitationClusterIntegrity`](docs/m7_citation_cluster_integrity_ruling.md) | high | The agent's own outbound citations must not sustain a small, closed, reciprocal citation cluster | - -The design rules the module enforces: - -- **Prevention is client-side; Pi Script is the enforcement latch and audit trace.** The client's scan-all-then-block pre-send gate runs every detector on every attempt, latches every finding, and only then blocks on the most severe — no violation is silently dropped. The agent's own key is protected by *isolation*: it lives only in the transport layer and never enters the model's context, so no injection, however encoded, can make the model emit it. -- **The two Longitudinal Constraints** (`CadenceIntegrity` and `CitationClusterIntegrity`, split from the earlier `ManipulationFlag` concept) evaluate persistent observation stores — post timestamps and directional citation edges — that survive restarts, ingest idempotently, and recompute deterministically. Insufficient data is never compliance: below the readiness floor the trace says so explicitly. -- **Undefined beats estimated.** `CitationClusterIntegrity`'s detection thresholds ship *undefined* — not guessed — until real observation grounds them through a ruling amendment. Ungrounded, the constraint structurally cannot fire. - -``` -CONSTRAINT: CitationClusterIntegrity -Observation readiness : false -Evaluation : parameters ungrounded (ruling §5 — no amendment has set thresholds yet) -Result : NOT EVALUABLE -Action : none -``` - -- **Paused is not frozen.** A longitudinal violation escalates and pauses autonomous posting — but read-only observation continues and explicitly human-authorized sends still pass through every gate. The pause persists across restarts and clears only through explicit human review, which never erases the observation history that produced it. - -The policy is in [`moltbook/moltbook.pi`](moltbook/moltbook.pi). Live transport is deliberately unwired — no agent is registered or deployed yet; everything above is enforced and tested against the real resolver. - ---- - -## Using it as an MCP tool - -`mcp_server.py` exposes the resolver pipeline as a single MCP tool, `check_governance`, so an agent can check whether a state *would* violate policy before acting, instead of only finding out after the fact from the cron governance watcher. - -```bash -python mcp_server.py -``` - -Wire it into an MCP client (e.g. Claude Code) with a stdio transport pointing at this file. The tool accepts either a native `.pi` policy or a `.rift` program (compiled to Pi Script automatically first): - -```python -check_governance( - source=open("examples/tasks.pi").read(), - state={"trigger_type": "event", "entity": "TaskAgent", "entity_state": {...}}, - source_type="pi", # or "rift" -) -``` - -Pass `persist=True` with a `state_path` to make a system's governance durable across calls: prior `violation_counts` are loaded and carried forward, the updated state is written back atomically, and a trace file is saved to a sibling `traces/` directory on violation. Concurrent callers hitting the same `state_path` are protected by real cross-process file locking (`filelock`), not just an in-process one — the MCP server runs as a separate OS process per client. - -```bash -python dashboard.py -``` - -`dashboard.py` is a small Starlette web UI for browsing what `persist=True` accumulates — it scans for `state.json` files and their sibling `traces/` directories and serves a system list, per-system trace listing, and RESOLUTION TRACE rendering in the browser. No storage migration: it reads the same flat-file convention `log_session.py` and `check_governance(persist=True)` already write. - ---- - -## How it differs from output filters - -Tools like Guardrails AI filter or rewrite model outputs at inference time. Pi Script governs **state over time** — it evaluates whether a system's observable behavior has drifted from declared constraints across a time window, across a session, across multiple responses. Different problem. - -| | Output filters | Pi Script | -|---|---|---| -| When it runs | At inference | On state snapshots | -| What it checks | Single output | State over time | -| What it produces | Filtered output | Auditable RESOLUTION TRACE | -| How it's defined | Validators/schemas | Formal grammar | -| Failure mode | Silent rewrite | Explicit violation + action | - ---- - -## Build status - -| Milestone | Status | -| --- | --- | -| M1 — Grammar specification, Draft 4 | ✅ Complete | -| M2 — Semantic validator | ✅ Complete — 12/12 tests | -| M3 — Parser formal sign-off | ✅ Complete — 9/9 tests | -| M4 — Resolver core + RESOLUTION TRACEs | ✅ Complete — 89/89 tests | -| M5 — Dogfood (23-day active run, 6+ violations across two independent systems) | ✅ Complete | -| Rift v0.1 — Intent Layer (grammar, parser, validator, compiler) | ✅ Complete — 33/33 tests | -| M6 — Publish (paper + public playground) | ✅ Complete — ConsistencyGuard activated, Jupyter playground live | -| Pi Script v0.2 — Rulings 9.4–9.9 (bidirectional maps, cross-domain inheritance, violation counters, arbiter mandatory, semantic map matching, standing bound rule) | ✅ Complete | -| MCP server, governance dashboard, persistence/write-queue | ✅ Complete | -| Rift v0.2 — Rulings 3.1 + 3.2 (semantic declaration matching, known-values accumulation via `RiftSession`) | ✅ Complete — 71/71 Rift tests | -| M7 — Moltbook governed-agent deployment | 🔄 In progress — ✅ CredentialIntegrity · ✅ LinkRestriction · ✅ IdentityIntegrity v1 · ✅ CadenceIntegrity · ✅ CitationClusterIntegrity (ManipulationFlag was split into these two; §5 thresholds await the grounding amendment) | -| M7 — Moltbook transport boundary (non-semantic execution adapter) | 🔄 In progress — ✅ approved-action envelope + freshness validation · ✅ retry/reconciliation taxonomy (incl. Implementation Note C's `RATE_LIMITED`) · ✅ kill switch + captcha-suspension protection · ✅ dry-run structural isolation · ✅ claim-status eligibility gate · ✅ `Retry-After`/`X-RateLimit-*` header capture (Implementation Note D — metadata surfaced, never acted on) · ✅ captcha issuance protocol (Implementation Note E — challenge embedded in the write response, verification gates publication not transmission, three independent result statuses, fail-closed config) — account registered/claimed, real endpoints wired; both former engineering blockers closed, first live post is now a go decision with its own governed envelope | - -**589 tests passing + 7 xfailed** (deliberate known-gap pins) across parser, validator, trace builder, resolver, Rift pipeline (v0.1 + v0.2), MCP server, dashboard, the v0.2 rulings, the M7 Moltbook constraints (key isolation, pre-send gate, link provenance, identity consistency, posting-cadence integrity, citation-cluster integrity), and the M7 Moltbook transport boundary (envelope validation, retry taxonomy, reconciliation, kill switch, dry-run isolation, claim-status eligibility gate, captcha issuance + verification, rate-limit header capture). - ---- - -## Structure - -``` -continuum/ -├── docs/ -│ ├── pi_script_v01_draft3.md # Pi Script v0.1 grammar specification (Draft 4) -│ ├── pi_script_v02_draft5.md # Pi Script v0.2 rulings spec — 9.4 through 9.9 -│ ├── m6_paper_draft1.md # M6 publication draft — M5 findings -│ ├── continuum_layer_boundaries.md # Layer boundary reference — what belongs where -│ ├── rift_v02_ruling_3_1_semantic_declaration_matching.md # Rift Ruling 3.1 — two-tier matcher spec -│ ├── rift_v02_semantic_matching_note.md # Ruling 3.1 implementation note -│ ├── rift_v02_ruling_3_2_known_values_accumulation.md # Rift Ruling 3.2 — session/accumulation spec -│ ├── rift_v02_known_values_accumulation_note.md # Ruling 3.2 implementation note -│ ├── m7_credential_integrity_ruling.md # M7 ruling — key isolation + pre-send gate -│ ├── m7_link_restriction_ruling.md # M7 ruling — link provenance -│ ├── m7_identity_integrity_ruling.md # M7 ruling — within-session identity consistency -│ ├── m7_identity_integrity_ruling_addendum_1.md # Addendum 1 — external-review fixes (A1–A6) -│ ├── m7_cadence_integrity_ruling.md # M7 ruling — posting-cadence integrity (longitudinal) -│ └── m7_citation_cluster_integrity_ruling.md # M7 ruling — citation-cluster integrity (longitudinal) -├── es/ -│ ├── es_governance.pi # Pi Script policy for Elasticsearch governance -│ ├── es_adapter.py # State adapter — queries ES, writes state.json -│ └── baseline.json # Committed mapping hash — schema governance source of truth -├── examples/ -│ ├── tasks.pi # Working example — AI task agent governance -│ ├── test_happy.pi # Happy path file exercising all rule forms -│ └── quantization_governance.pi # GPU/ML quantization domain example (Ruling 9.9 bound_rule) -├── m5/ -│ ├── dogfood.pi # M5 dogfood policy — governs Continuum AI assistant usage -│ ├── ir.json # Compiled IR for dogfood.pi -│ ├── state.json # Session state snapshot — update before each daily run -│ └── traces/ # RESOLUTION TRACE logs — M5 violation record -├── moltbook/ -│ ├── moltbook.pi # M7 policy — session constraints + the longitudinal agent profile -│ ├── client.py # Governed client — key isolation, scan-all pre-send gate, pause checks -│ ├── detector.py # Mechanical detectors — credentials, link provenance, identity drift -│ ├── cadence.py # CadenceIntegrity observation store + governance gate -│ ├── citation.py # CitationClusterIntegrity edge store + governance gate -│ └── link_allowlist.json # Human-owned link allowlist — editable only via commit/PR -├── pi_script/ -│ ├── pi_script.lark # Lark grammar -│ ├── parser.py # LALR parser wrapper -│ ├── validator.py # Semantic validator — produces IR -│ ├── resolver.py # Constraint evaluator — produces RESOLUTION TRACEs -│ └── trace.py # Trace builder, renderer, human_text generator -├── rift/ -│ ├── rift_v01.lark # Lark grammar — Intent Layer -│ ├── parser.py # Earley parser wrapper -│ ├── validator.py # Semantic validator — extracts intent IR -│ ├── compiler.py # Pi Script emitter — generates .pi from .rift -│ ├── matcher.py # Two-tier declaration matcher (Ruling 3.1) -│ ├── session.py # Declaration-resolution runtime + known-values accumulation (Ruling 3.2) -│ ├── shelved_projects.rift # Canonical test program -│ └── shelved_projects.pi # Generated Pi Script output -├── rift_design_note_draft2.md # Rift (Layer 3) design — v0.1 intent layer spec -├── tests/ -│ ├── test_parser.py # M1 + M3 — 9 tests -│ ├── test_validator.py # M2 + v0.2 rulings — 45 tests -│ ├── test_trace.py # trace.py — 31 tests -│ ├── test_resolver.py # M4 + v0.2 rulings — 98 tests -│ ├── test_rift.py # Rift v0.1 + v0.2 — 71 tests -│ ├── test_mcp_server.py # check_governance tool — 10 tests -│ ├── test_dashboard.py # dashboard UI — 9 tests -│ ├── test_quantization_governance_example.py # Ruling 9.9 example — 5 tests -│ ├── test_moltbook_credential_integrity.py # M7 key isolation + pre-send gate — 20 tests -│ ├── test_moltbook_link_restriction.py # M7 link provenance — 20 tests -│ ├── test_moltbook_identity_integrity.py # M7 identity consistency + addendum — 32 tests -│ ├── test_moltbook_cadence_integrity.py # M7 cadence store + pause semantics — 25 tests -│ └── test_moltbook_citation_cluster_integrity.py # M7 citation graph + grounding gate — 36 tests -├── quickstart.py # One-command demo — validate, resolve, print the trace -├── compile_pi.py # Helper — validate a .pi file and write its IR to JSON -├── log_session.py # M5 daily runner — resolves dogfood.pi against current state -├── pi_monitor.py # Device-health monitor template — NOT the deployed watcher -│ # (live monitoring runs as a GitHub Actions cron workflow) -├── mcp_server.py # MCP server exposing check_governance as an agent-callable tool -├── dashboard.py # Starlette web UI for browsing persisted state + traces -├── state.json # Example state snapshot (locked schema) -└── requirements.txt -``` - ---- - -## Guiding principles - -1. **Spec first, always.** The grammar specification is the source of truth. Code implements the spec. The spec is never reverse-engineered from code. -2. **Measurable or it doesn't exist.** If a constraint can't be formalized into something a runtime can evaluate, it has no place in v0.1. -3. **No undefined behavior.** Every failure mode has a defined safe state. The runtime never silently fails. -4. **Human-readable traces are non-negotiable.** If a non-expert can't read the RESOLUTION TRACE and understand why the system acted, the trace format is broken — not the person. - ---- - -## What's deliberately not in v0.1 - -Scope discipline is a feature. These are deferred on purpose, not forgotten: - -- ~~Bidirectional map blocks~~ — shipped, Pi Script v0.2 Ruling 9.4 -- ~~Semantic similarity map matching~~ — shipped, Pi Script v0.2 Ruling 9.8 -- ~~Cross-domain constraint inheritance~~ — shipped, Pi Script v0.2 Ruling 9.5 -- ~~Natural language constraint authoring — NLP-based declaration matching~~ — shipped, Rift v0.2 Rulings 3.1 + 3.2 -- Adaptive constraints that evolve within bounds (Pi Script v0.3) -- Rift Semantic Layer — `agent`, `state`, `behavior evolves` constructs (Rift v0.3) -- Rift dynamic constraint generation — runtime re-evaluation without recompile (blocked on the multi-phase resolver, a Layer 2 prerequisite that doesn't exist yet) -- Rift Execution Layer — `@gpu`, `@quantum`, `@realtime` annotations (Rift v0.3) -- Persistence of accumulated known values across sessions (deferred by Ruling 3.2 §3.2.3 — a future ruling when a use case demands it) -- Cross-layer integration of any kind (v0.4+ per `docs/continuum_layer_boundaries.md`) - ---- - -*Continuum — Pi Script v0.2 + Rift v0.2 + the M7 Moltbook constraint set — July 2026* +# Continuum — Pi Script + Rift + +**Pi Script declares what must stay true about an AI system's behavior. Rift maps what users declare in natural language to the constraints Pi Script enforces. Together they close the loop from human intent to machine accountability.** + +--- + +## What you get + +Run the resolver against a live state snapshot and get this: + +``` +RESOLUTION TRACE +════════════════════════════════════════════════════════════════════════ +Timestamp : 2026-04-27T23:32:44.195Z +Domain : ai_governance +Entity : TaskAgent [session_id: smoke-001] +Trigger : event — state snapshot received for TaskAgent +════════════════════════════════════════════════════════════════════════ +├── CONSTRAINT: ConfidenceFloor [priority: critical] +│ ├── Rule kind : range_rule +│ ├── Evaluation : confidence_score = 0.72, within range(0.2 .. 1.0) +│ └── ✓ SATISFIED — no action +│ +├── CONSTRAINT: ResponseCap [priority: high] +│ ├── Rule kind : threshold_rule +│ ├── Evaluation : response_count = 42.0, below threshold 1000.0 +│ └── ✓ SATISFIED — no action +│ +├── CONSTRAINT: ModeCompliance [priority: medium] +│ ├── Rule kind : membership_rule +│ ├── Evaluation : current_mode = 'normal_mode', matched in valid set ['normal_mode', 'safe_mode'] +│ └── ✓ SATISFIED — no action +│ +├── CONSTRAINT: SessionIntegrity [priority: high] +│ ├── Rule kind : equality_rule +│ ├── Evaluation : is_active = True, equals expected True +│ └── ✓ SATISFIED — no action +│ +├── CONSTRAINT: PrecautionaryPause [priority: high] +│ ├── Rule kind : conditional_rule +│ ├── Evaluation : condition not met: confidence_score 0.72 < 0.5 +│ └── ✓ SATISFIED — no action +│ +└── CONSTRAINT: ConsistencyGuard [priority: critical] +│ ├── Rule kind : contradiction_rule +│ ├── Evaluation : no prior responses on topic 'TaskAgent.response_history' within window +│ └── ✓ SATISFIED — no action +│ +└── RESOLUTION + ├── System state : running + └── All rules were checked and passed: ConfidenceFloor, ResponseCap, + ModeCompliance, SessionIntegrity, PrecautionaryPause, and ConsistencyGuard. + Everything is within acceptable bounds. No action was taken. +``` + +Every constraint evaluated. Every result explained. A non-expert can read the last line and understand exactly what happened. + +--- + +## What it is + +Continuum is a three-layer governance stack for AI systems: + +| Layer | Name | What it does | +| --- | --- | --- | +| Layer 1 | Your system | Emits state — metrics, flags, session data | +| Layer 2 | Pi Script | Declares constraints; resolver evaluates them against state snapshots | +| Layer 3 | Rift | Maps natural language declarations to Pi Script constraints | + +**Pi Script** is a compiled governance language. You declare constraints in a formal grammar — range bounds, thresholds, equality checks, conditional triggers, contradiction detection — and a resolver evaluates them against live state snapshots, applies priority resolution when multiple constraints fire simultaneously, and emits a structured RESOLUTION TRACE every time. + +**Rift** is the Intent Layer above Pi Script. You write what you mean in plain language — "I shelved this project", "freeze this permanently" — and Rift compiles those declarations into Pi Script constraints automatically. No hand-written Pi Script required. At runtime, Rift also resolves declarations it has never seen verbatim: an exact trigger match when one exists, and a semantic fallback when one doesn't — with every match decision traced and scored, never guessed silently. + +The full loop: + +``` +User declares intent in natural language + ↓ +Rift maps declaration → machine state (exact or semantic match) + ↓ +Rift compiles → Pi Script constraint set (.pi file) + ↓ +Pi Script resolver evaluates constraints against live state + ↓ +RESOLUTION TRACE — auditable, human-readable, every time + ↓ +Violations feed back as new user declarations (Rift) +``` + +Neither layer filters outputs or wraps prompts. They watch state over time and tell you precisely when and why a system drifted from what it was designed to be. + +The design rule is strict: **if a constraint cannot be formalized into something measurable, it does not belong in the language.** Vague language is a compile error, not a feature. + +--- + +## Try it + +```bash +git clone https://github.com/GodSpeed313/Continuum.git +cd Continuum +pip install -r requirements.txt +python quickstart.py +``` + +Or step through it manually: + +```bash +# 1. Validate a Pi Script program — produces a structured IR +python -m pi_script.validator examples/tasks.pi + +# 2. Run the resolver against a state snapshot +python -c " +from pi_script.validator import validate_file +import json +ok, errors, ir = validate_file('examples/tasks.pi') +with open('ir.json', 'w', encoding='utf-8') as f: + json.dump(ir, f, indent=2) +" +python -m pi_script.resolver ir.json state.json +``` + +--- + +## A Pi Script program + +``` +domain ai_governance { + audit_interval: 24 hours + tiebreaker: timestamp_asc +} + +entity TaskAgent { + confidence_score: range(0.0 .. 1.0) + response_count: integer + current_mode: text + is_active: boolean +} + +map SafeMode { + target: TaskAgent.current_mode + maps_to: "safe_mode" + triggers: ["safe", "restricted", "limited access"] +} + +constraint ConfidenceFloor { + priority: critical + rule: TaskAgent.confidence_score must remain within range(0.2 .. 1.0) + on_violation: freeze + rollback + decay_check: 1 hour +} + +constraint PrecautionaryPause { + priority: high + rule: if TaskAgent.confidence_score < 0.5 then require confidence_review before responding + on_violation: escalate +} + +enforce { + entity: TaskAgent + constraints: [ConfidenceFloor, PrecautionaryPause] +} +``` + +The full working example with all six rule forms is in [`examples/tasks.pi`](examples/tasks.pi). +The v0.1 grammar specification is in [`docs/pi_script_v01_draft3.md`](docs/pi_script_v01_draft3.md) (Draft 4). +The v0.2 rulings spec (9.4–9.9) is in [`docs/pi_script_v02_draft5.md`](docs/pi_script_v02_draft5.md). + +--- + +## A Rift program + +Write intent declarations in plain language. Rift compiles them to Pi Script automatically. + +``` +map "I shelved [project]" -> project.state: dormant +map "let's revisit [project]" -> project.state: active +map "I'm done with [project]" -> project.state: closed + +intent RespectShelfedProjects { + when user declares: "I shelved [project]" + treat: [project] as dormant + until: user declares "let's revisit [project]" + enforce: "do not reference [project] unprompted" + generates: Pi Script constraint ShelvedProjectGuard +} + +intent ReactivateProject { + when user declares: "let's revisit [project]" + treat: [project] as active + releases: RespectShelfedProjects for [project] + generates: Pi Script constraint ActiveProjectGuard +} +``` + +Compile it: + +```bash +python -m rift.compiler rift/shelved_projects.rift +``` + +Output — valid Pi Script, ready for the resolver: + +``` +constraint ShelvedProjectGuard { + priority: medium + rule: Project.state must equal "dormant" + on_violation: escalate +} + +constraint ActiveProjectGuard { + priority: medium + rule: Project.state must equal "active" + on_violation: escalate +} +``` + +The full canonical example is in [`rift/shelved_projects.rift`](rift/shelved_projects.rift). The generated output is in [`rift/shelved_projects.pi`](rift/shelved_projects.pi). + +--- + +## Resolving declarations at runtime — Rift v0.2 + +Compilation is no longer the only entry point. People don't repeat their trigger phrases verbatim — "let's pick Veritas back up" has to mean the same thing as "let's revisit Veritas". Rift v0.2 adds a two-tier declaration matcher and a session runtime: + +```python +from rift.session import RiftSession + +session = RiftSession.from_rift_file("rift/shelved_projects.rift") + +# Tier 1 — exact trigger match. Extracts the capture, and the session +# remembers "Veritas" as a known entity value. +session.resolve("I shelved Veritas") + +# No exact trigger matches this phrasing — Tier 2 semantic fallback, +# masked by the value the session learned above. +r = session.resolve("let's pick Veritas back up") +print(r.trace) +``` + +``` +RIFT MATCH TRACE +├── Declaration : "let's pick Veritas back up" +├── Tier : semantic +├── Threshold : 0.3 Margin: 0.05 +├── Candidates : +│ ├── "let's revisit project" score: 0.6831 ← selected +│ ├── "I shelved project" score: 0.5168 +│ └── "I'm done with project" score: 0.5127 +└── ✓ MATCHED → project.state: active +RIFT SESSION +├── Known values : "Veritas" +└── Accumulated : (none — semantic tier extracts no captures) +``` + +How it works, and what it refuses to do: + +- **Exact first.** Tier 1 compiles each map pattern to an anchored, case-insensitive regex and extracts capture values. No embedding model is loaded unless Tier 1 misses. +- **Semantic fallback.** Tier 2 embeds the declaration (all-MiniLM-L6-v2) and ranks maps by cosine similarity — its own model instance, fully independent of Pi Script's Ruling 9.8 matcher, per the layer boundaries. Two permanent tests enforce that `rift/` never imports from `pi_script/`. +- **Ambiguity is a defined no-match, never a guess.** A winning score below the threshold, or a top-two gap inside the ambiguity margin, resolves to no match with the failing condition named in the trace. +- **The session learns from what it confirms.** Entity values extracted by exact matches accumulate (in-memory, per-session) and mask later semantic probes — the same declaration that scores 0.31 on a cold session scores 0.68 with a learned value. The semantic tier identifies *which map* a declaration means; capture values only ever come from the exact tier. +- **Every score is in the trace.** A similarity decision that can't be inspected is a black box; the trace is the non-negotiable window into it. + +Specs: [Ruling 3.1 — semantic declaration matching](docs/rift_v02_ruling_3_1_semantic_declaration_matching.md) and [Ruling 3.2 — known-values accumulation](docs/rift_v02_ruling_3_2_known_values_accumulation.md), with implementation notes alongside each. + +--- + +## Governing a real system — Elasticsearch + +The adapter pattern bridges any Layer 1 system to Pi Script. The Elasticsearch adapter is the canonical example. + +```bash +# 1. Start Elasticsearch (Docker) +docker run -d --name elasticsearch -p 9200:9200 \ + -e "discovery.type=single-node" \ + -e "xpack.security.enabled=false" \ + elasticsearch:8.13.4 + +# 2. Create your index +curl -X PUT "http://localhost:9200/governed-index" \ + -H "Content-Type: application/json" \ + -d '{"settings":{"number_of_shards":1,"number_of_replicas":0}}' + +# 3. Record the known-good schema as baseline (commit this to git) +python es/es_adapter.py --bootstrap + +# 4. Run governance — adapter reads cluster state, resolver evaluates it +python es/es_adapter.py +python -m pi_script.resolver es/ir.json es/state.json +``` + +Any unauthorized schema change triggers `SchemaIntegrity` at critical priority: + +``` +├── CONSTRAINT: SchemaIntegrity [priority: critical] +│ ├── Evaluation : schema_intact is False, expected True +│ ├── ✗ VIOLATION DETECTED +│ └── Action : freeze + escalate +``` + +The full policy is in [`es/es_governance.pi`](es/es_governance.pi). The adapter is in [`es/es_adapter.py`](es/es_adapter.py). + +--- + +## Governing a live agent — Moltbook (M7) + +M7 puts a Continuum-governed agent onto **Moltbook**, a live social platform for autonomous agents — and an openly adversarial environment where injection payloads hunt for other agents' secrets. The [`moltbook/`](moltbook/) module follows the `m5/` dogfood pattern (one policy file, persistent state, sibling traces), governing the agent's own sessions rather than external infrastructure. + +Five constraints, each with a locked, spec-first ruling in `docs/`: + +| Constraint | Priority | Governs | +| --- | --- | --- | +| [`CredentialIntegrity`](docs/m7_credential_integrity_ruling.md) | critical | The platform API key stays unleakable — key isolation plus a pre-send gate | +| [`LinkRestriction`](docs/m7_link_restriction_ruling.md) | high | A link is surfaced only with provenance: present in the source content, or on the human-owned allowlist | +| [`IdentityIntegrity`](docs/m7_identity_integrity_ruling.md) | high | Declared identity stays self-consistent within a session — mechanical detection only ([addendum 1](docs/m7_identity_integrity_ruling_addendum_1.md)) | +| [`CadenceIntegrity`](docs/m7_cadence_integrity_ruling.md) | high | No near-exact periodic posting — the agent's own timing, never content, never other accounts | +| [`CitationClusterIntegrity`](docs/m7_citation_cluster_integrity_ruling.md) | high | The agent's own outbound citations must not sustain a small, closed, reciprocal citation cluster | + +The design rules the module enforces: + +- **Prevention is client-side; Pi Script is the enforcement latch and audit trace.** The client's scan-all-then-block pre-send gate runs every detector on every attempt, latches every finding, and only then blocks on the most severe — no violation is silently dropped. The agent's own key is protected by *isolation*: it lives only in the transport layer and never enters the model's context, so no injection, however encoded, can make the model emit it. +- **The two Longitudinal Constraints** (`CadenceIntegrity` and `CitationClusterIntegrity`, split from the earlier `ManipulationFlag` concept) evaluate persistent observation stores — post timestamps and directional citation edges — that survive restarts, ingest idempotently, and recompute deterministically. Insufficient data is never compliance: below the readiness floor the trace says so explicitly. +- **Undefined beats estimated.** `CitationClusterIntegrity`'s detection thresholds ship *undefined* — not guessed — until real observation grounds them through a ruling amendment. Ungrounded, the constraint structurally cannot fire. + +``` +CONSTRAINT: CitationClusterIntegrity +Observation readiness : false +Evaluation : parameters ungrounded (ruling §5 — no amendment has set thresholds yet) +Result : NOT EVALUABLE +Action : none +``` + +- **Paused is not frozen.** A longitudinal violation escalates and pauses autonomous posting — but read-only observation continues and explicitly human-authorized sends still pass through every gate. The pause persists across restarts and clears only through explicit human review, which never erases the observation history that produced it. + +The policy is in [`moltbook/moltbook.pi`](moltbook/moltbook.pi). Live transport is deliberately unwired — no agent is registered or deployed yet; everything above is enforced and tested against the real resolver. + +--- + +## Using it as an MCP tool + +`mcp_server.py` exposes the resolver pipeline as a single MCP tool, `check_governance`, so an agent can check whether a state *would* violate policy before acting, instead of only finding out after the fact from the cron governance watcher. + +```bash +python mcp_server.py +``` + +Wire it into an MCP client (e.g. Claude Code) with a stdio transport pointing at this file. The tool accepts either a native `.pi` policy or a `.rift` program (compiled to Pi Script automatically first): + +```python +check_governance( + source=open("examples/tasks.pi").read(), + state={"trigger_type": "event", "entity": "TaskAgent", "entity_state": {...}}, + source_type="pi", # or "rift" +) +``` + +Pass `persist=True` with a `state_path` to make a system's governance durable across calls: prior `violation_counts` are loaded and carried forward, the updated state is written back atomically, and a trace file is saved to a sibling `traces/` directory on violation. Concurrent callers hitting the same `state_path` are protected by real cross-process file locking (`filelock`), not just an in-process one — the MCP server runs as a separate OS process per client. + +```bash +python dashboard.py +``` + +`dashboard.py` is a small Starlette web UI for browsing what `persist=True` accumulates — it scans for `state.json` files and their sibling `traces/` directories and serves a system list, per-system trace listing, and RESOLUTION TRACE rendering in the browser. No storage migration: it reads the same flat-file convention `log_session.py` and `check_governance(persist=True)` already write. + +--- + +## How it differs from output filters + +Tools like Guardrails AI filter or rewrite model outputs at inference time. Pi Script governs **state over time** — it evaluates whether a system's observable behavior has drifted from declared constraints across a time window, across a session, across multiple responses. Different problem. + +| | Output filters | Pi Script | +|---|---|---| +| When it runs | At inference | On state snapshots | +| What it checks | Single output | State over time | +| What it produces | Filtered output | Auditable RESOLUTION TRACE | +| How it's defined | Validators/schemas | Formal grammar | +| Failure mode | Silent rewrite | Explicit violation + action | + +--- + +## Build status + +| Milestone | Status | +| --- | --- | +| M1 — Grammar specification, Draft 4 | ✅ Complete | +| M2 — Semantic validator | ✅ Complete — 12/12 tests | +| M3 — Parser formal sign-off | ✅ Complete — 9/9 tests | +| M4 — Resolver core + RESOLUTION TRACEs | ✅ Complete — 89/89 tests | +| M5 — Dogfood (23-day active run, 6+ violations across two independent systems) | ✅ Complete | +| Rift v0.1 — Intent Layer (grammar, parser, validator, compiler) | ✅ Complete — 33/33 tests | +| M6 — Publish (paper + public playground) | ✅ Complete — ConsistencyGuard activated, Jupyter playground live | +| Pi Script v0.2 — Rulings 9.4–9.9 (bidirectional maps, cross-domain inheritance, violation counters, arbiter mandatory, semantic map matching, standing bound rule) | ✅ Complete | +| MCP server, governance dashboard, persistence/write-queue | ✅ Complete | +| Rift v0.2 — Rulings 3.1 + 3.2 (semantic declaration matching, known-values accumulation via `RiftSession`) | ✅ Complete — 71/71 Rift tests | +| M7 — Moltbook governed-agent deployment | 🔄 In progress — ✅ CredentialIntegrity · ✅ LinkRestriction · ✅ IdentityIntegrity v1 · ✅ CadenceIntegrity · ✅ CitationClusterIntegrity (ManipulationFlag was split into these two; §5 thresholds await the grounding amendment) | +| M7 — Moltbook transport boundary (non-semantic execution adapter) | 🔄 In progress — ✅ approved-action envelope + freshness validation · ✅ retry/reconciliation taxonomy (incl. Implementation Note C's `RATE_LIMITED`) · ✅ kill switch + captcha-suspension protection · ✅ dry-run structural isolation · ✅ claim-status eligibility gate · ✅ `Retry-After`/`X-RateLimit-*` header capture (Implementation Note D — metadata surfaced, never acted on) · ✅ captcha issuance protocol (Implementation Note E — challenge embedded in the write response, verification gates publication not transmission, three independent result statuses, fail-closed config) — account registered/claimed, real endpoints wired; both former engineering blockers closed, first live post is now a go decision with its own governed envelope | + +**589 tests passing + 7 xfailed** (deliberate known-gap pins) across parser, validator, trace builder, resolver, Rift pipeline (v0.1 + v0.2), MCP server, dashboard, the v0.2 rulings, the M7 Moltbook constraints (key isolation, pre-send gate, link provenance, identity consistency, posting-cadence integrity, citation-cluster integrity), and the M7 Moltbook transport boundary (envelope validation, retry taxonomy, reconciliation, kill switch, dry-run isolation, claim-status eligibility gate, captcha issuance + verification, rate-limit header capture). + +--- + +## Structure + +``` +continuum/ +├── docs/ +│ ├── pi_script_v01_draft3.md # Pi Script v0.1 grammar specification (Draft 4) +│ ├── pi_script_v02_draft5.md # Pi Script v0.2 rulings spec — 9.4 through 9.9 +│ ├── m6_paper_draft1.md # M6 publication draft — M5 findings +│ ├── continuum_layer_boundaries.md # Layer boundary reference — what belongs where +│ ├── rift_v02_ruling_3_1_semantic_declaration_matching.md # Rift Ruling 3.1 — two-tier matcher spec +│ ├── rift_v02_semantic_matching_note.md # Ruling 3.1 implementation note +│ ├── rift_v02_ruling_3_2_known_values_accumulation.md # Rift Ruling 3.2 — session/accumulation spec +│ ├── rift_v02_known_values_accumulation_note.md # Ruling 3.2 implementation note +│ ├── m7_credential_integrity_ruling.md # M7 ruling — key isolation + pre-send gate +│ ├── m7_link_restriction_ruling.md # M7 ruling — link provenance +│ ├── m7_identity_integrity_ruling.md # M7 ruling — within-session identity consistency +│ ├── m7_identity_integrity_ruling_addendum_1.md # Addendum 1 — external-review fixes (A1–A6) +│ ├── m7_cadence_integrity_ruling.md # M7 ruling — posting-cadence integrity (longitudinal) +│ └── m7_citation_cluster_integrity_ruling.md # M7 ruling — citation-cluster integrity (longitudinal) +├── es/ +│ ├── es_governance.pi # Pi Script policy for Elasticsearch governance +│ ├── es_adapter.py # State adapter — queries ES, writes state.json +│ └── baseline.json # Committed mapping hash — schema governance source of truth +├── examples/ +│ ├── tasks.pi # Working example — AI task agent governance +│ ├── test_happy.pi # Happy path file exercising all rule forms +│ └── quantization_governance.pi # GPU/ML quantization domain example (Ruling 9.9 bound_rule) +├── m5/ +│ ├── dogfood.pi # M5 dogfood policy — governs Continuum AI assistant usage +│ ├── ir.json # Compiled IR for dogfood.pi +│ ├── state.json # Session state snapshot — update before each daily run +│ └── traces/ # RESOLUTION TRACE logs — M5 violation record +├── moltbook/ +│ ├── moltbook.pi # M7 policy — session constraints + the longitudinal agent profile +│ ├── client.py # Governed client — key isolation, scan-all pre-send gate, pause checks +│ ├── detector.py # Mechanical detectors — credentials, link provenance, identity drift +│ ├── cadence.py # CadenceIntegrity observation store + governance gate +│ ├── citation.py # CitationClusterIntegrity edge store + governance gate +│ └── link_allowlist.json # Human-owned link allowlist — editable only via commit/PR +├── pi_script/ +│ ├── pi_script.lark # Lark grammar +│ ├── parser.py # LALR parser wrapper +│ ├── validator.py # Semantic validator — produces IR +│ ├── resolver.py # Constraint evaluator — produces RESOLUTION TRACEs +│ └── trace.py # Trace builder, renderer, human_text generator +├── rift/ +│ ├── rift_v01.lark # Lark grammar — Intent Layer +│ ├── parser.py # Earley parser wrapper +│ ├── validator.py # Semantic validator — extracts intent IR +│ ├── compiler.py # Pi Script emitter — generates .pi from .rift +│ ├── matcher.py # Two-tier declaration matcher (Ruling 3.1) +│ ├── session.py # Declaration-resolution runtime + known-values accumulation (Ruling 3.2) +│ ├── shelved_projects.rift # Canonical test program +│ └── shelved_projects.pi # Generated Pi Script output +├── rift_design_note_draft2.md # Rift (Layer 3) design — v0.1 intent layer spec +├── tests/ +│ ├── test_parser.py # M1 + M3 — 9 tests +│ ├── test_validator.py # M2 + v0.2 rulings — 45 tests +│ ├── test_trace.py # trace.py — 31 tests +│ ├── test_resolver.py # M4 + v0.2 rulings — 98 tests +│ ├── test_rift.py # Rift v0.1 + v0.2 — 71 tests +│ ├── test_mcp_server.py # check_governance tool — 10 tests +│ ├── test_dashboard.py # dashboard UI — 9 tests +│ ├── test_quantization_governance_example.py # Ruling 9.9 example — 5 tests +│ ├── test_moltbook_credential_integrity.py # M7 key isolation + pre-send gate — 20 tests +│ ├── test_moltbook_link_restriction.py # M7 link provenance — 20 tests +│ ├── test_moltbook_identity_integrity.py # M7 identity consistency + addendum — 32 tests +│ ├── test_moltbook_cadence_integrity.py # M7 cadence store + pause semantics — 25 tests +│ └── test_moltbook_citation_cluster_integrity.py # M7 citation graph + grounding gate — 36 tests +├── quickstart.py # One-command demo — validate, resolve, print the trace +├── compile_pi.py # Helper — validate a .pi file and write its IR to JSON +├── log_session.py # M5 daily runner — resolves dogfood.pi against current state +├── pi_monitor.py # Device-health monitor template — NOT the deployed watcher +│ # (live monitoring runs as a GitHub Actions cron workflow) +├── mcp_server.py # MCP server exposing check_governance as an agent-callable tool +├── dashboard.py # Starlette web UI for browsing persisted state + traces +├── state.json # Example state snapshot (locked schema) +└── requirements.txt +``` + +--- + +## Guiding principles + +1. **Spec first, always.** The grammar specification is the source of truth. Code implements the spec. The spec is never reverse-engineered from code. +2. **Measurable or it doesn't exist.** If a constraint can't be formalized into something a runtime can evaluate, it has no place in v0.1. +3. **No undefined behavior.** Every failure mode has a defined safe state. The runtime never silently fails. +4. **Human-readable traces are non-negotiable.** If a non-expert can't read the RESOLUTION TRACE and understand why the system acted, the trace format is broken — not the person. + +--- + +## What's deliberately not in v0.1 + +Scope discipline is a feature. These are deferred on purpose, not forgotten: + +- ~~Bidirectional map blocks~~ — shipped, Pi Script v0.2 Ruling 9.4 +- ~~Semantic similarity map matching~~ — shipped, Pi Script v0.2 Ruling 9.8 +- ~~Cross-domain constraint inheritance~~ — shipped, Pi Script v0.2 Ruling 9.5 +- ~~Natural language constraint authoring — NLP-based declaration matching~~ — shipped, Rift v0.2 Rulings 3.1 + 3.2 +- Adaptive constraints that evolve within bounds (Pi Script v0.3) +- Rift Semantic Layer — `agent`, `state`, `behavior evolves` constructs (Rift v0.3) +- Rift dynamic constraint generation — runtime re-evaluation without recompile (blocked on the multi-phase resolver, a Layer 2 prerequisite that doesn't exist yet) +- Rift Execution Layer — `@gpu`, `@quantum`, `@realtime` annotations (Rift v0.3) +- Persistence of accumulated known values across sessions (deferred by Ruling 3.2 §3.2.3 — a future ruling when a use case demands it) +- Cross-layer integration of any kind (v0.4+ per `docs/continuum_layer_boundaries.md`) + +--- + +*Continuum — Pi Script v0.2 + Rift v0.2 + the M7 Moltbook constraint set — July 2026* diff --git a/TODO.md b/TODO.md index adccf07..7a3a0da 100644 --- a/TODO.md +++ b/TODO.md @@ -1,93 +1,94 @@ -# Continuum — TODO - -Live milestone + debt tracker. Suite: **589 passing + 7 xfail** (known-gap pins). - -## Open items - -### M7 — remaining before/at live deployment - -- [x] **T2 longitudinal cohort re-sample (2026-07-22/23)** — identity 0/8 (no drift), first - A1.6 falsification check on CadenceIntegrity's ±5s grounding passed. T3 follows ~2026-07-30. -- [ ] **First live post — a GO DECISION, not an engineering task.** Requires its own governed - envelope + operator go-ahead + live wiring of a real `submit_captcha_fn` against - `POST /api/v1/verify` (the seam is injected everywhere in tests; live wiring has - deliberately never happened). Transport spec Note E stop conditions apply. -- [ ] IdentityIntegrity v1.1 cross-session change-rate threshold — blocked on T2/T3 data. -- [ ] CitationClusterIntegrity §5 grounding amendment — trigger is first real M7 citation - activity by our deployed agent; until then the constraint is structurally NOT EVALUABLE. - -### Infrastructure / process debt - -- [x] Claude Code scaffold hooks (PR #30) installed 2026-07-24 — reworked from the scaffold's - bash/`CLAUDE_*`-env-var shape to the current stdin-JSON hook interface as three Python - scripts in `.claude/hooks/` (pre-Bash destructive-command guard, post-Write/Edit targeted - pytest for `pi_script/`/`rift/`/`moltbook/`, Stop-time full suite + Discord notify) wired - via `.claude/settings.json`. Local-only by design (`.gitignore` keeps `.claude/*` private - except skills). `DISCORD_WEBHOOK_URL` env var enables the notify path; unset = suite still - runs, result printed only. -- [x] `PISCRIPTGOVERNANCE` PAT expiry debt CLOSED 2026-07-23: pre-flight expiry-warning step + - run-failure Discord net shipped to Melody-Maestro `governance.yml` (PR #1 `c3f5822`), - token rotated (90-day fine-grained, Contents R/W both repos, expires 2026-10-21 — - auto-warns #pi-logs at ≤14d ~10/07 and ≤3d ~10/18), renewal doc corrected (PR #2 - `ed17351`). If #pi-logs goes quiet anyway: `gh run list -R GodSpeed313/Melody-Maestro`. - -### xfail census (7 — deliberate known-gap pins, not failures) - -- 3 × CredentialIntegrity encoding exfil (base64 / reversed / split-within-prefix) -- 3 × IdentityIntegrity (semantic persona-drift; A4 quoted-speech; A2 residual truncation) -- 1 × captcha solver: whitespace-shattered words (Note F §F.5 residual) - ---- - -## Milestone tracker - -- [x] M1 — Grammar finalized -- [x] M2 — Semantic validator, 12/12 tests passing -- [x] M3 — Parser — 9/9 tests passing -- [x] M4 — Resolver core — 89/89 tests passing -- [x] M5 — Dogfood — gate met (6+ violations across two independent systems: 2 Continuum session + 4+ Melody Maestro automated, 23-day active run) -- [x] M6 — Publish — ConsistencyGuard activated, Rift v0.1 shipped, Jupyter playground live (paper at docs/m6_paper_draft1.md) -- [ ] M7 — Moltbook deployment — **engineering complete, not yet live** (see open items above) - -## v0.2 ruling tracker - -- [x] Ruling 9.4 — bidirectional map blocks (PR #10) -- [x] Ruling 9.5 — cross-domain constraint inheritance (PR #11) -- [x] Ruling 9.6 — persistent violation counters (PR #12) -- [x] Ruling 9.7 — arbiter mandatory + flag-as-always-additive (PR #13) -- [x] Ruling 9.8 — semantic similarity map matching (PR #14, #15) -- [x] Ruling 9.9 — standing bound rule / Form 7 (PR #16) - -Pending rulings: none. Spec doc (`docs/pi_script_v02_draft5.md`, Draft 10) confirms. - -## Tooling / integration (post-9.9) - -- [x] MCP server exposing governance checks as a tool (PR #18) -- [x] Persistence + cross-process write-queue for `check_governance` (PR #19) -- [x] Read-only governance dashboard (PR #20) -- [x] Quantization-governance domain example — corrected to valid v0.2 syntax, proves grammar is domain-general (PR #21) - -## Rift v0.2 (Layer 3 rulings) - -- [x] Ruling 3.1 — two-tier semantic declaration matching, independent MiniLM instance (PR #26, `4ff5e7f`) -- [x] Ruling 3.2 — known-values accumulation, `RiftSession` (PR #27, `04b747f`) - -## M7 shipped log - -- [x] Claude Code scaffold: CLAUDE.md + three skills (PR #30, `3172e5a`) -- [x] CredentialIntegrity — ruling + key isolation + pre-send gate (PR #31, `0db3f2e`) -- [x] LinkRestriction — provenance check + allowlist + reshare log (PR #32, `a3a5be6`) -- [x] IdentityIntegrity v1 — within-session, mechanical-only detection (PR #33, `6c558e5`) -- [x] IdentityIntegrity Addendum 1 — A1–A6 external-review fixes (PR #34, `c5f51aa`) -- [x] CadenceIntegrity — longitudinal constraint, provisional §5 params (PR #35, `7dbbed9`) -- [x] CitationClusterIntegrity — directional edges, ungrounded-§5-by-design (PR #36, `e8dbb92`) -- [x] README M7 section (PR #37, `71c5031`) -- [x] CadenceIntegrity Amendment 1 — J ±3s→±5s, grounded from T1 cohort (PR #38, `809b5c1`) -- [x] Moltbook transport boundary — locked spec + Notes A/B/C (PR #39, `9b4ec71`) -- [x] Implementation Note D — request_fn header capture, RateLimitInfo (PR #40, `819cfa0`) -- [x] Implementation Note E — captcha issuance protocol, verification gates publication (PR #41, `1bbead6`) -- [x] Trace status contract — suspended rendering, fail-loud unknown statuses (PR #42, `a27b4e5`) -- [x] Implementation Note F — solver extension for documented obfuscation style (PR #43, `ec1f6a0`) -- [x] `tests/test_validator_unit.py` recreated — hand-built Lark Tree harness, 26 tests - (11 happy-path IR extraction, 7 semantic errors, 5 malformed-AST None-guard, 3 - conditional-rule variants). Oldest open item (M4 era), never committed before. +# Continuum — TODO + +Live milestone + debt tracker. Suite: **589 passing + 7 xfail** (known-gap pins). + +## Open items + +### M7 — remaining before/at live deployment + +- [x] **T2 longitudinal cohort re-sample (2026-07-22/23)** — identity 0/8 (no drift), first + A1.6 falsification check on CadenceIntegrity's ±5s grounding passed. T3 follows ~2026-07-30. +- [ ] **First live post — a GO DECISION, not an engineering task.** Requires its own governed + envelope + operator go-ahead + live wiring of a real `submit_captcha_fn` against + `POST /api/v1/verify` (the seam is injected everywhere in tests; live wiring has + deliberately never happened). Transport spec Note E stop conditions apply. +- [ ] IdentityIntegrity v1.1 cross-session change-rate threshold — blocked on T2/T3 data. +- [ ] CitationClusterIntegrity §5 grounding amendment — trigger is first real M7 citation + activity by our deployed agent; until then the constraint is structurally NOT EVALUABLE. + +### Infrastructure / process debt + +- [x] Claude Code scaffold hooks (PR #30) installed 2026-07-24 — reworked from the scaffold's + bash/`CLAUDE_*`-env-var shape to the current stdin-JSON hook interface as three Python + scripts in `.claude/hooks/` (pre-Bash destructive-command guard, post-Write/Edit targeted + pytest for `pi_script/`/`rift/`/`moltbook/`, Stop-time full suite + Discord notify) wired + via `.claude/settings.json`. Canonical sources now TRACKED in `tools/claude-hooks/` + (install-hooks.ps1 / verify-hooks.ps1; `.claude/` stays local and generated — see + `docs/scaffold_hooks_reconstruction_note.md` Resolution 2026-07-24). `DISCORD_WEBHOOK_URL` + env var enables the notify path; unset = suite still runs, result printed only. +- [x] `PISCRIPTGOVERNANCE` PAT expiry debt CLOSED 2026-07-23: pre-flight expiry-warning step + + run-failure Discord net shipped to Melody-Maestro `governance.yml` (PR #1 `c3f5822`), + token rotated (90-day fine-grained, Contents R/W both repos, expires 2026-10-21 — + auto-warns #pi-logs at ≤14d ~10/07 and ≤3d ~10/18), renewal doc corrected (PR #2 + `ed17351`). If #pi-logs goes quiet anyway: `gh run list -R GodSpeed313/Melody-Maestro`. + +### xfail census (7 — deliberate known-gap pins, not failures) + +- 3 × CredentialIntegrity encoding exfil (base64 / reversed / split-within-prefix) +- 3 × IdentityIntegrity (semantic persona-drift; A4 quoted-speech; A2 residual truncation) +- 1 × captcha solver: whitespace-shattered words (Note F §F.5 residual) + +--- + +## Milestone tracker + +- [x] M1 — Grammar finalized +- [x] M2 — Semantic validator, 12/12 tests passing +- [x] M3 — Parser — 9/9 tests passing +- [x] M4 — Resolver core — 89/89 tests passing +- [x] M5 — Dogfood — gate met (6+ violations across two independent systems: 2 Continuum session + 4+ Melody Maestro automated, 23-day active run) +- [x] M6 — Publish — ConsistencyGuard activated, Rift v0.1 shipped, Jupyter playground live (paper at docs/m6_paper_draft1.md) +- [ ] M7 — Moltbook deployment — **engineering complete, not yet live** (see open items above) + +## v0.2 ruling tracker + +- [x] Ruling 9.4 — bidirectional map blocks (PR #10) +- [x] Ruling 9.5 — cross-domain constraint inheritance (PR #11) +- [x] Ruling 9.6 — persistent violation counters (PR #12) +- [x] Ruling 9.7 — arbiter mandatory + flag-as-always-additive (PR #13) +- [x] Ruling 9.8 — semantic similarity map matching (PR #14, #15) +- [x] Ruling 9.9 — standing bound rule / Form 7 (PR #16) + +Pending rulings: none. Spec doc (`docs/pi_script_v02_draft5.md`, Draft 10) confirms. + +## Tooling / integration (post-9.9) + +- [x] MCP server exposing governance checks as a tool (PR #18) +- [x] Persistence + cross-process write-queue for `check_governance` (PR #19) +- [x] Read-only governance dashboard (PR #20) +- [x] Quantization-governance domain example — corrected to valid v0.2 syntax, proves grammar is domain-general (PR #21) + +## Rift v0.2 (Layer 3 rulings) + +- [x] Ruling 3.1 — two-tier semantic declaration matching, independent MiniLM instance (PR #26, `4ff5e7f`) +- [x] Ruling 3.2 — known-values accumulation, `RiftSession` (PR #27, `04b747f`) + +## M7 shipped log + +- [x] Claude Code scaffold: CLAUDE.md + three skills (PR #30, `3172e5a`) +- [x] CredentialIntegrity — ruling + key isolation + pre-send gate (PR #31, `0db3f2e`) +- [x] LinkRestriction — provenance check + allowlist + reshare log (PR #32, `a3a5be6`) +- [x] IdentityIntegrity v1 — within-session, mechanical-only detection (PR #33, `6c558e5`) +- [x] IdentityIntegrity Addendum 1 — A1–A6 external-review fixes (PR #34, `c5f51aa`) +- [x] CadenceIntegrity — longitudinal constraint, provisional §5 params (PR #35, `7dbbed9`) +- [x] CitationClusterIntegrity — directional edges, ungrounded-§5-by-design (PR #36, `e8dbb92`) +- [x] README M7 section (PR #37, `71c5031`) +- [x] CadenceIntegrity Amendment 1 — J ±3s→±5s, grounded from T1 cohort (PR #38, `809b5c1`) +- [x] Moltbook transport boundary — locked spec + Notes A/B/C (PR #39, `9b4ec71`) +- [x] Implementation Note D — request_fn header capture, RateLimitInfo (PR #40, `819cfa0`) +- [x] Implementation Note E — captcha issuance protocol, verification gates publication (PR #41, `1bbead6`) +- [x] Trace status contract — suspended rendering, fail-loud unknown statuses (PR #42, `a27b4e5`) +- [x] Implementation Note F — solver extension for documented obfuscation style (PR #43, `ec1f6a0`) +- [x] `tests/test_validator_unit.py` recreated — hand-built Lark Tree harness, 26 tests + (11 happy-path IR extraction, 7 semantic errors, 5 malformed-AST None-guard, 3 + conditional-rule variants). Oldest open item (M4 era), never committed before. diff --git a/docs/scaffold_hooks_reconstruction_note.md b/docs/scaffold_hooks_reconstruction_note.md index 693c5ff..18cdbff 100644 --- a/docs/scaffold_hooks_reconstruction_note.md +++ b/docs/scaffold_hooks_reconstruction_note.md @@ -71,3 +71,18 @@ exactly the failure mode that destroys local-only files — the current install this workstation's `.claude/`, so the tracked-canonical-source option now has a concrete survivability argument, with this note's file list serving as the reconstruction reference in the meantime. + +## Resolution 2026-07-24 — tracked infrastructure shipped, this note is CLOSED + +The operator decided: tracked. "A laptop crash should not be able to erase process controls that +matter to how Continuum is developed." Implemented as `tools/claude-hooks/` (canonical hook +sources + settings template + stdin-schema docs + `install-hooks.ps1` / `verify-hooks.ps1`, +Windows PowerShell 5.1 compatible), with `.claude/` remaining local and generated — the +local/tracked boundary PR #30 drew is preserved; the hook *design* is now version-controlled, +reviewable, and reproducible on another machine. + +The verify script's first run on this workstation immediately paid for itself: PowerShell 5.1 +pipes prepend a UTF-8 BOM to native-command stdin, which `json.load` rejects — so +`pre_bash_guard.py` failed **open** (a guard silently not guarding). All three hooks now decode +stdin as `utf-8-sig`; the smoke test that caught it is part of `verify-hooks.ps1`, so any host +with BOM-emitting pipes re-tests the case on every verification run. diff --git a/tools/claude-hooks/README.md b/tools/claude-hooks/README.md new file mode 100644 index 0000000..07ee0ac --- /dev/null +++ b/tools/claude-hooks/README.md @@ -0,0 +1,56 @@ +# Claude Code Hooks — Tracked Canonical Source + +This directory is the version-controlled source of truth for Continuum's Claude Code hooks. +The live runtime state under `.claude/` is **generated and gitignored** (`.gitignore` keeps +`.claude/*` private except `.claude/skills/`) — never edit installed copies directly; edit the +sources here and re-run the installer. This boundary is deliberate: hook *design* is reviewable +project infrastructure, hook *installation* is local machine state. + +Why tracked: the original PR #30 scaffold hooks lived only as local files and were nearly lost +(see `docs/scaffold_hooks_reconstruction_note.md` — the 2026-07-23 laptop crash is exactly the +failure mode that erases local-only process controls). Anything that shapes how Continuum is +developed must survive a dead workstation. + +## Layout + +``` +tools/claude-hooks/ + README.md this file + hooks/ canonical hook scripts + settings template + pre_bash_guard.py PreToolUse(Bash): blocks rm -rf / git push --force, exit 2 + post_edit_tests.py PostToolUse(Write|Edit): pytest -k for pi_script/rift/moltbook edits + stop_suite_notify.py Stop: full suite + Discord PASS/FAIL notify (notify-only, never blocks) + settings.template.json the .claude/settings.json wiring for the three hooks + schemas/ stdin JSON contract each hook consumes (documentation schemas) + install-hooks.ps1 copies hooks + settings into .claude/ (Windows PowerShell 5.1) + verify-hooks.ps1 proves installed state matches source and hooks actually fire +``` + +## Install + +```powershell +powershell -ExecutionPolicy Bypass -File tools\claude-hooks\install-hooks.ps1 +``` + +Re-run any time the tracked sources change. If your `.claude/settings.json` has local +customizations the installer refuses to clobber them — merge the `hooks` block manually or +re-run with `-Force` (a timestamped backup is kept). + +## Verify + +```powershell +powershell -ExecutionPolicy Bypass -File tools\claude-hooks\verify-hooks.ps1 # fast +powershell -ExecutionPolicy Bypass -File tools\claude-hooks\verify-hooks.ps1 -Full # + real full-suite Stop-hook run +``` + +## Hook interface notes + +- Hooks receive a JSON payload on **stdin** (current Claude Code interface — the old + `CLAUDE_FILE_PATH`/`CLAUDE_TOOL_INPUT` env vars from the PR #30-era scaffold no longer exist). + `schemas/` documents exactly which fields each hook consumes. +- Exit code 2 blocks (PreToolUse) or feeds stderr back to the model (PostToolUse). The Stop + hook is notify-only and always exits 0 by design. +- `DISCORD_WEBHOOK_URL` (optional, never committed): enables the Stop hook's Discord + notification. Unset, the suite still runs and the result is printed to the transcript. +- Scripts are invoked as `python .claude/hooks/.py` with the project directory as cwd — + shell-agnostic (works under both cmd and POSIX-shell hook execution), no jq/bash dependency. diff --git a/tools/claude-hooks/hooks/post_edit_tests.py b/tools/claude-hooks/hooks/post_edit_tests.py new file mode 100644 index 0000000..26cfa2c --- /dev/null +++ b/tools/claude-hooks/hooks/post_edit_tests.py @@ -0,0 +1,54 @@ +"""PostToolUse hook for Write|Edit: run targeted tests for core-package edits. + +Port of the scaffold's v2 hook: when a .py file under pi_script/, rift/, or +moltbook/ is written or edited, run `pytest -k -q` (the scaffold's +deliberate approximation of "run related tests" — README_SETUP.md notes it +is blunt by design). Exit 2 on test failure so the failures are fed back to +the model; exit 0 when no tests match (pytest exit 5) or the file is out of +scope. +""" +import json +import pathlib +import subprocess +import sys + +WATCHED = ("pi_script", "rift", "moltbook") + + +def main() -> int: + try: + # utf-8-sig tolerates the BOM PowerShell 5.1 pipes prepend + payload = json.loads(sys.stdin.buffer.read().decode("utf-8-sig")) + except (json.JSONDecodeError, ValueError): + return 0 + file_path = (payload.get("tool_input") or {}).get("file_path", "") + if not file_path or not file_path.endswith(".py"): + return 0 + project_dir = pathlib.Path(payload.get("cwd") or ".").resolve() + try: + rel = pathlib.Path(file_path).resolve().relative_to(project_dir) + except ValueError: + return 0 # edited file lives outside the project + if rel.parts[0] not in WATCHED: + return 0 + stem = pathlib.Path(file_path).stem + result = subprocess.run( + [sys.executable, "-m", "pytest", "-k", stem, "-q"], + cwd=project_dir, + capture_output=True, + text=True, + timeout=110, + ) + if result.returncode in (0, 5): # 5 = no tests matched the -k expression + return 0 + tail = "\n".join((result.stdout or "").splitlines()[-30:]) + print( + f"pytest -k {stem} failed (exit {result.returncode}) after editing " + f"{rel}:\n{tail}", + file=sys.stderr, + ) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/claude-hooks/hooks/pre_bash_guard.py b/tools/claude-hooks/hooks/pre_bash_guard.py new file mode 100644 index 0000000..545380a --- /dev/null +++ b/tools/claude-hooks/hooks/pre_bash_guard.py @@ -0,0 +1,35 @@ +"""PreToolUse guard for Bash: block destructive commands deterministically. + +Port of the scaffold's v2 hook (settings.example.json, PR #30 era) to the +current Claude Code hook interface: input arrives as JSON on stdin, exit +code 2 blocks the tool call and feeds stderr back to the model. +""" +import json +import re +import sys + +BLOCKED = re.compile(r"rm -rf|git push --force|git push -f\b") + + +def main() -> int: + try: + # utf-8-sig: PowerShell 5.1 pipes prepend a BOM, which json.load rejects — + # and a guard that fails open on that is silently not guarding. + payload = json.loads(sys.stdin.buffer.read().decode("utf-8-sig")) + except (json.JSONDecodeError, ValueError): + return 0 # malformed input: never block on our own parse failure + command = (payload.get("tool_input") or {}).get("command", "") + match = BLOCKED.search(command) + if match: + print( + f"Blocked by .claude/hooks/pre_bash_guard.py: command contains " + f"'{match.group(0)}'. Destructive commands require the operator " + f"to run them manually.", + file=sys.stderr, + ) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/claude-hooks/hooks/settings.template.json b/tools/claude-hooks/hooks/settings.template.json new file mode 100644 index 0000000..d2a8edd --- /dev/null +++ b/tools/claude-hooks/hooks/settings.template.json @@ -0,0 +1,39 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "python .claude/hooks/pre_bash_guard.py", + "timeout": 10 + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Write|Edit", + "hooks": [ + { + "type": "command", + "command": "python .claude/hooks/post_edit_tests.py", + "timeout": 120 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python .claude/hooks/stop_suite_notify.py", + "timeout": 300 + } + ] + } + ] + } +} diff --git a/tools/claude-hooks/hooks/stop_suite_notify.py b/tools/claude-hooks/hooks/stop_suite_notify.py new file mode 100644 index 0000000..f63df3c --- /dev/null +++ b/tools/claude-hooks/hooks/stop_suite_notify.py @@ -0,0 +1,58 @@ +"""Stop hook: run the full suite and notify Discord of the result. + +Port of the scaffold's v2 hook, with its one real bug fixed: the original +`pytest && curl PASS || curl FAIL` sent FAIL whenever the PASS webhook call +itself failed. Here the suite result and the notification result are +independent. Notify-only by design — this hook never blocks the stop +(always exits 0), matching the original's behavior. + +DISCORD_WEBHOOK_URL must be set in the environment (never committed); when +unset, the suite still runs and the result is printed to the transcript. +""" +import json +import os +import subprocess +import sys +import urllib.request + + +def notify(webhook_url: str, content: str) -> None: + req = urllib.request.Request( + webhook_url, + data=json.dumps({"content": content}).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + try: + urllib.request.urlopen(req, timeout=10).read() + except OSError as exc: + print(f"Discord notify failed (suite result unaffected): {exc}") + + +def main() -> int: + try: + # utf-8-sig tolerates the BOM PowerShell 5.1 pipes prepend + payload = json.loads(sys.stdin.buffer.read().decode("utf-8-sig")) + except (json.JSONDecodeError, ValueError): + payload = {} + project_dir = payload.get("cwd") or "." + result = subprocess.run( + [sys.executable, "-m", "pytest", "-q"], + cwd=project_dir, + capture_output=True, + text=True, + timeout=280, + ) + passed = result.returncode == 0 + summary = (result.stdout or "").strip().splitlines() + last_line = summary[-1] if summary else "(no pytest output)" + status = "PASS" if passed else "FAIL — check before shipping" + print(f"Continuum suite: {status} ({last_line})") + webhook_url = os.environ.get("DISCORD_WEBHOOK_URL", "") + if webhook_url: + notify(webhook_url, f"Continuum suite: {status}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/claude-hooks/install-hooks.ps1 b/tools/claude-hooks/install-hooks.ps1 new file mode 100644 index 0000000..4292e3f --- /dev/null +++ b/tools/claude-hooks/install-hooks.ps1 @@ -0,0 +1,63 @@ +# Installs the tracked Claude Code hooks into this repo's local .claude/ directory. +# Windows PowerShell 5.1 compatible. Source of truth: tools/claude-hooks/hooks/. +# The installed .claude/ state is generated and gitignored - never edit it directly; +# edit the tracked sources here and re-run this script. +# +# Usage: +# powershell -ExecutionPolicy Bypass -File tools\claude-hooks\install-hooks.ps1 +# ... -Force overwrite a diverged .claude/settings.json (a timestamped .bak is kept) + +[CmdletBinding()] +param([switch]$Force) + +$ErrorActionPreference = 'Stop' + +$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$srcHooks = Join-Path $PSScriptRoot 'hooks' +$dstHooks = Join-Path $repoRoot '.claude\hooks' +$templatePath = Join-Path $srcHooks 'settings.template.json' +$settingsPath = Join-Path $repoRoot '.claude\settings.json' + +if (-not (Test-Path $templatePath)) { + throw "Template not found: $templatePath - run from a full checkout." +} + +New-Item -ItemType Directory -Force -Path $dstHooks | Out-Null + +$copied = @() +foreach ($file in Get-ChildItem -Path $srcHooks -Filter '*.py') { + Copy-Item -Path $file.FullName -Destination (Join-Path $dstHooks $file.Name) -Force + $copied += $file.Name +} +Write-Output ("Installed hook scripts -> .claude\hooks\ : " + ($copied -join ', ')) + +# Normalize both sides through the JSON parser so formatting/line-ending +# differences don't count as divergence. +$templateJson = (Get-Content $templatePath -Raw | ConvertFrom-Json) | ConvertTo-Json -Depth 10 + +if (Test-Path $settingsPath) { + $existingJson = $null + try { + $existingJson = (Get-Content $settingsPath -Raw | ConvertFrom-Json) | ConvertTo-Json -Depth 10 + } catch { + Write-Warning ".claude\settings.json exists but is not valid JSON." + } + if ($existingJson -eq $templateJson) { + Write-Output '.claude\settings.json already matches the template - no change.' + } elseif ($Force) { + $bak = $settingsPath + '.bak-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + Copy-Item -Path $settingsPath -Destination $bak + [System.IO.File]::WriteAllText($settingsPath, (Get-Content $templatePath -Raw), (New-Object System.Text.UTF8Encoding($false))) + Write-Output (".claude\settings.json overwritten (backup: " + (Split-Path -Leaf $bak) + ")") + } else { + Write-Warning '.claude\settings.json differs from the template. It may contain local customizations.' + Write-Warning 'Merge the "hooks" block from tools\claude-hooks\hooks\settings.template.json manually,' + Write-Warning 'or re-run with -Force to overwrite (a timestamped backup will be kept).' + exit 1 + } +} else { + [System.IO.File]::WriteAllText($settingsPath, (Get-Content $templatePath -Raw), (New-Object System.Text.UTF8Encoding($false))) + Write-Output 'Created .claude\settings.json from template.' +} + +Write-Output 'Done. Run tools\claude-hooks\verify-hooks.ps1 to confirm the installation.' diff --git a/tools/claude-hooks/schemas/posttooluse-write-edit-input.schema.json b/tools/claude-hooks/schemas/posttooluse-write-edit-input.schema.json new file mode 100644 index 0000000..a198b86 --- /dev/null +++ b/tools/claude-hooks/schemas/posttooluse-write-edit-input.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "PostToolUse (Write|Edit) hook input — fields consumed by post_edit_tests.py", + "description": "Claude Code delivers a larger payload on stdin; this schema documents only the fields this hook reads. Unknown fields are ignored. The hook runs `pytest -k -q` when the edited file is a .py under pi_script/, rift/, or moltbook/ relative to cwd; anything else is a no-op.", + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Project directory the session is running in; used to resolve the edited file's repo-relative path." + }, + "tool_input": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Absolute path of the file that was written or edited." + } + } + } + }, + "x-exit-codes": { + "0": "no tests run (out of scope), or targeted tests passed, or pytest collected nothing for -k (pytest exit 5)", + "2": "targeted tests failed; the pytest tail on stderr is fed back to the model" + } +} diff --git a/tools/claude-hooks/schemas/pretooluse-bash-input.schema.json b/tools/claude-hooks/schemas/pretooluse-bash-input.schema.json new file mode 100644 index 0000000..68a700d --- /dev/null +++ b/tools/claude-hooks/schemas/pretooluse-bash-input.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "PreToolUse (Bash) hook input — fields consumed by pre_bash_guard.py", + "description": "Claude Code delivers a larger payload on stdin; this schema documents only the fields this hook reads. Unknown fields are ignored. Malformed JSON is treated as 'do not block' by design.", + "type": "object", + "properties": { + "tool_name": { + "type": "string", + "const": "Bash" + }, + "tool_input": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The shell command about to run. Matched against the blocklist regex: rm -rf | git push --force | git push -f." + } + } + } + }, + "x-exit-codes": { + "0": "allow the tool call", + "2": "block the tool call; stderr is fed back to the model as the reason" + } +} diff --git a/tools/claude-hooks/schemas/stop-input.schema.json b/tools/claude-hooks/schemas/stop-input.schema.json new file mode 100644 index 0000000..d54ade3 --- /dev/null +++ b/tools/claude-hooks/schemas/stop-input.schema.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Stop hook input — fields consumed by stop_suite_notify.py", + "description": "Claude Code delivers a larger payload on stdin; this schema documents only the fields this hook reads. Unknown fields are ignored. The hook runs the full pytest suite in cwd and posts the result to Discord when DISCORD_WEBHOOK_URL is set in the environment; unset, it prints the result to the transcript only. Notify-only by design: it always exits 0 and never blocks the stop.", + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Project directory the session is running in; the suite runs here." + } + }, + "x-exit-codes": { + "0": "always — suite result is reported via stdout and (optionally) Discord, never via exit code" + }, + "x-environment": { + "DISCORD_WEBHOOK_URL": "Optional. Discord webhook receiving 'Continuum suite: PASS' / 'Continuum suite: FAIL — check before shipping'. Never commit this value." + } +} diff --git a/tools/claude-hooks/verify-hooks.ps1 b/tools/claude-hooks/verify-hooks.ps1 new file mode 100644 index 0000000..f072bb3 --- /dev/null +++ b/tools/claude-hooks/verify-hooks.ps1 @@ -0,0 +1,94 @@ +# Verifies the installed Claude Code hooks match the tracked sources and actually work. +# Windows PowerShell 5.1 compatible. +# +# Checks: +# 1. python is on PATH +# 2. every tracked hook script is installed byte-identical (SHA256) +# 3. .claude/settings.json matches the template (JSON-normalized compare) +# 4. functional smoke tests: guard blocks a force-push (exit 2) and passes a +# benign command (exit 0); post-edit hook no-ops on an out-of-scope file +# 5. with -Full: the Stop hook runs the real full suite (slow; requires deps) +# +# Usage: +# powershell -ExecutionPolicy Bypass -File tools\claude-hooks\verify-hooks.ps1 [-Full] + +[CmdletBinding()] +param([switch]$Full) + +$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$srcHooks = Join-Path $PSScriptRoot 'hooks' +$dstHooks = Join-Path $repoRoot '.claude\hooks' +$settingsPath = Join-Path $repoRoot '.claude\settings.json' +$templatePath = Join-Path $srcHooks 'settings.template.json' + +$failures = 0 +function Report([bool]$ok, [string]$label) { + if ($ok) { Write-Output (" PASS " + $label) } + else { Write-Output (" FAIL " + $label); $script:failures++ } +} + +Write-Output '== Claude hooks verification ==' + +# 1. python available +$py = $null +try { $py = Get-Command python -ErrorAction Stop } catch {} +Report ($null -ne $py) 'python on PATH' +if ($null -eq $py) { Write-Output 'Cannot continue without python.'; exit 1 } + +# 2. installed scripts match tracked sources +foreach ($file in Get-ChildItem -Path $srcHooks -Filter '*.py') { + $installed = Join-Path $dstHooks $file.Name + if (Test-Path $installed) { + $a = (Get-FileHash -Algorithm SHA256 $file.FullName).Hash + $b = (Get-FileHash -Algorithm SHA256 $installed).Hash + Report ($a -eq $b) ($file.Name + ' installed and byte-identical to tracked source') + } else { + Report $false ($file.Name + ' installed (missing - run install-hooks.ps1)') + } +} + +# 3. settings.json matches template +if (Test-Path $settingsPath) { + $ok = $false + try { + $a = (Get-Content $templatePath -Raw | ConvertFrom-Json) | ConvertTo-Json -Depth 10 + $b = (Get-Content $settingsPath -Raw | ConvertFrom-Json) | ConvertTo-Json -Depth 10 + $ok = ($a -eq $b) + } catch {} + Report $ok '.claude\settings.json matches template' +} else { + Report $false '.claude\settings.json exists (missing - run install-hooks.ps1)' +} + +# 4. functional smoke tests (run against the INSTALLED copies, from repo root) +Push-Location $repoRoot +try { + '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}' | python .claude/hooks/pre_bash_guard.py + Report ($LASTEXITCODE -eq 2) 'pre_bash_guard blocks git push --force (exit 2)' + + '{"tool_name":"Bash","tool_input":{"command":"git status"}}' | python .claude/hooks/pre_bash_guard.py + Report ($LASTEXITCODE -eq 0) 'pre_bash_guard passes benign command (exit 0)' + + $probe = '{"cwd":"' + ($repoRoot -replace '\\', '\\\\') + '","tool_input":{"file_path":"' + ($repoRoot -replace '\\', '\\\\') + '\\\\README.md"}}' + $probe | python .claude/hooks/post_edit_tests.py + Report ($LASTEXITCODE -eq 0) 'post_edit_tests no-ops on out-of-scope file (exit 0)' + + if ($Full) { + Write-Output ' .... Stop hook full-suite run (slow):' + '{"cwd":"' + ($repoRoot -replace '\\', '\\\\') + '"}' | python .claude/hooks/stop_suite_notify.py + Report ($LASTEXITCODE -eq 0) 'stop_suite_notify completed (exit 0; suite result printed above)' + } else { + Write-Output ' SKIP stop_suite_notify full-suite run (use -Full)' + } +} finally { + Pop-Location +} + +Write-Output '' +if ($failures -eq 0) { + Write-Output 'All checks passed.' + exit 0 +} else { + Write-Output ("{0} check(s) FAILED." -f $failures) + exit 1 +}