diff --git a/.github/workflows/scopemoat.yml b/.github/workflows/scopemoat.yml index 5f28dd6..d466ed7 100644 --- a/.github/workflows/scopemoat.yml +++ b/.github/workflows/scopemoat.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Check out the base branch (engine, store and baseline come from it) + - name: Check out the base branch (store and baseline come from it; pr_check.py runs a copy of its engine) run: | git fetch --no-tags origin "${{ github.event.pull_request.head.sha }}" git checkout --detach "${{ github.event.pull_request.base.sha }}" diff --git a/EVIDENCE.md b/EVIDENCE.md index c120fd3..91a699a 100644 --- a/EVIDENCE.md +++ b/EVIDENCE.md @@ -12,7 +12,7 @@ Every result ScopeMoat publishes, where its record lives, and the command that r | Relate path query agrees with the Python reference: 0 membership mismatches over 539 fixture-by-case comparisons | main | `blind/v5/reach_crosscheck.py`, `blind/v5/reach_inventory.json` | `python acceptance.py` (check K7) | | Browser explorer: Relate's WebAssembly build (1.4.0) returns the same rows as relate-db for every recorded state, 6/6 (proposal, repair, missing evidence; baseline and candidate each) | main | `explorer/` (index.html, data/scenarios.json, vendor/relate-wasm-1.4.0/) | `python -m explorer.build_export --check` (exit 0: data current), then `node explorer/parity.mjs` (expected `Parity: 6/6 states identical`) | | Transit search guard: on the pinned forwarding-clique fixture, 5 forwarding systems still BLOCK with the same Relate path; 6 and 20 are held for review by the search-size guard in under 0.2 s instead of 23 s / out of memory | main | `perf/README.md`, `perf/forwarding_clique.py`, `perf/bench.py` | `python perf/bench.py 5 6 7 20`; acceptance P1-P3 | -| Engine and gate behaviour | main | `acceptance.py` (122 required checks), `blind/v5/checks_v5.py` (67), `t3/test_t3.py` (36) | `python acceptance.py`; `python blind/v5/checks_v5.py`; `python t3/test_t3.py` | +| Engine and gate behaviour | main | `acceptance.py` (140 required checks), `blind/v5/checks_v5.py` (67), `t3/test_t3.py` (36) | `python acceptance.py`; `python blind/v5/checks_v5.py`; `python t3/test_t3.py` | ## How to read these diff --git a/README.md b/README.md index 12b0448..4764039 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ A shallow clone skips the T4 rescore; a ZIP download (no git) skips the T4 and T ## How it uses Relate - **Mode: single file.** The baseline `graph/brightline.rl` is committed to the repo and opened read-only. Each check copies it into an in-memory Relate database and tests the change in a transaction that is rolled back. No server runs. -- **The graph:** fictional systems with zones, network links (`CONNECTS_TO`, with segmentation) and data flows (`SENDS`, `PAN` or `TOKEN`). For each check ScopeMoat writes per-direction `REACH` evidence and runs one Cypher 25 path query (`PATH_QUERY` in [scopemoat/reach.py](scopemoat/reach.py)) before and after the change. +- **The graph:** fictional systems with zones, network links (`CONNECTS_TO`, with segmentation) and data flows (`SENDS`, `PAN` or `TOKEN`). For each check ScopeMoat writes per-direction `REACH` evidence and runs Relate's Cypher 25 queries for every in-scope class before and after the change ([scopemoat/relate_scope.py](scopemoat/relate_scope.py); the transit path query is `PATH_QUERY` in [scopemoat/reach.py](scopemoat/reach.py)). - **The same file serves** the commit hook, `gate --explain`, the diagram above, Relate's own read-only MCP server (`relate serve --mcp stdio --database graph/brightline.rl --read-only`) and the browser explorer, which runs Relate's WebAssembly build. ### What Relate decides, and what Python decides @@ -65,12 +65,13 @@ A shallow clone skips the T4 rescore; a ZIP download (no git) skips the T4 and T | Decision | Who makes it | |---|---| | Which network links the staged Compose file adds | Python ([scopemoat/compose.py](scopemoat/compose.py)) | -| Which systems reach card data through other systems, and by which path | Relate: one Cypher query over `graph/brightline.rl` | -| Which edit opened the new path | Relate's row (`changes` column) | -| The other scoping rules, and BLOCK, PASS or REVIEW REQUIRED | Python rules ([scopemoat/rules_v5.py](scopemoat/rules_v5.py)), mapped to the PCI SSC guidance in [provider_reference/RULE_TO_SSC.md](provider_reference/RULE_TO_SSC.md) | +| Which systems are in scope on recorded facts (card data systems, the CDE, systems connected to it or securing it, and systems that reach it through others), before and after the change | Relate: Cypher queries over an in-memory Relate database that ScopeMoat loads from `graph/brightline.rl` (systems, data flows, security services) plus the per-direction `REACH` evidence it writes ([scopemoat/relate_scope.py](scopemoat/relate_scope.py)) | +| Which path puts a system in scope, and which edit opened it | Relate's row (`path` and `changes` columns) | +| BLOCK or PASS | Relate's in-scope classes. The Python rules ([scopemoat/rules_v5.py](scopemoat/rules_v5.py), mapped to the PCI SSC guidance in [provider_reference/RULE_TO_SSC.md](provider_reference/RULE_TO_SSC.md)) compute the same classes independently; if the two disagree, or Relate cannot answer, the gate returns REVIEW REQUIRED | +| REVIEW REQUIRED for unresolved evidence (the worst case, every unrecorded fact treated as open) | Python rules. Relate does not run this search: on Brightline it explores more than two million trails | | Refusing the commit | Git, through the local pre-commit hook | -No AI decides scope. [experiments/relate_classes.py](experiments/relate_classes.py) is a second implementation of every in-scope class in Cypher, and `verify.py` checks that it agrees with the Python rules. In this implementation, without Relate the demo change drops to REVIEW REQUIRED and loses its path. Substituting ScopeMoat's separate Python search for Relate reproduces BLOCK and the same path for this case, but without the Relate path line or the "Opened by" attribution. Run `.venv/bin/python experiments/relate_ablation.py` with `shipped`, `no_relate` or `python_transit` ([experiments/relate_ablation.py](experiments/relate_ablation.py)). +No AI decides scope. Relate's queries and the Python rules are two implementations of the same rules, and the gate needs both to agree; `verify.py` checks that they agree on every frozen state. Without Relate the demo change drops to REVIEW REQUIRED and loses its path. Replacing only Relate's transit query with ScopeMoat's separate Python search still gives BLOCK, because the in-scope classes still come from Relate's queries. Run `.venv/bin/python experiments/relate_ablation.py` with `shipped` (BLOCK), `no_relate` (REVIEW REQUIRED) or `python_transit` (BLOCK) ([experiments/relate_ablation.py](experiments/relate_ablation.py)). ## Checked against published answer keys @@ -107,7 +108,7 @@ The same rules against keys the author wrote: the 40 frozen cases; T4, the autho | Answer key (full title, year) | Compared | Result | File | |---|---|---|---| -| The author's answer key for 40 frozen cases, written before scoring | 40 changes | ScopeMoat: 36 exact, 0 false PASS. One-hop check: 24 exact, 15 false PASS. Plain reachability: 20 exact, 16 false PASS. Neither simpler check can return REVIEW REQUIRED, and 14 of the 40 expected verdicts are REVIEW. On the 26 expected BLOCK or PASS cases, one-hop is exact on 24 and ScopeMoat on 23 | [blind/baselines/SPLITS.txt](blind/baselines/SPLITS.txt) (lines 2-3), [AUDIT.md](blind/baselines/AUDIT.md) (line 7) | +| The author's answer key for 40 frozen cases, written before scoring | 40 changes | ScopeMoat: 36 exact, 0 false PASS. One-hop check: 24 exact, 15 false PASS. Plain reachability: 20 exact, 16 false PASS. Neither simpler check can return REVIEW REQUIRED, and 14 of the 40 expected verdicts are REVIEW. On the 26 expected BLOCK or PASS cases, one-hop is exact on 24 and ScopeMoat on 23 | [blind/baselines/SPLITS.txt](blind/baselines/SPLITS.txt) (lines 1-3), [AUDIT.md](blind/baselines/AUDIT.md) (line 7) | | The author's 12 frozen agent tasks (T4), claude-sonnet-5-5, 3 repeats, 36 runs per arm, blind-scored | the same agent without and with ScopeMoat's gate output | Unsafe ships (the benchmark's scored decision category): 0 of 36 without the gate output, 0 of 36 with it. Safe deliveries: 15 of 36 without, 12 of 36 with. Under the frozen win rule the gate arm did not win (3 fewer safe deliveries, all on T4-07, where the gate returned REVIEW REQUIRED on a design the frozen answer key rates PASS) | [t4/runs/live1/README.md](t4/runs/live1/README.md) (lines 3, 9-16) | | Twin pair P01 (from the T5 design; rule-derived label) | the demo change on two baselines that differ in one recorded fact | BLOCK becomes REVIEW REQUIRED; Relate's rows go from 8 to 0 | [experiments/twin_replay.py](experiments/twin_replay.py) | | The author's pre-registered agent A/B (T5), claude-sonnet-5-5, one repeat, 23 singles and 11 twin pairs | the same agent with the facts as text (arm A) or the same text plus a read-only Relate Cypher tool (arm B) | Registered: "H1: B gets more twin pairs fully right than A. H2: B has no more false PASS than A." and "H1 counts as supported only if B leads on pairs and p < 0.10". Twin pairs fully right: 11 of 11 without the Relate tool (arm A), 8 of 11 with it (arm B); 3 of arm B's answers were malformed JSON, which the registered scorer counts as failures. False PASS on singles: 2 of 23 (A), 0 of 23 (B). Exact verdicts on singles: 20 of 23 (A), 21 of 23 (B). No demonstrated difference on H1, as registered ("anything else is reported as no demonstrated difference, with the counts") (A alone right on 3 pairs, B alone on 0; p = 0.25); H2 holds. B made 12 Relate queries; in no state where the arms' verdicts differed did a query return a fact the answer used (one timed out), so no result is credited to the graph. The registered audit (S1, S2) found 140 of 140 checkable cited facts in A's answers and 146 of 147 in B's in the graph, and ScopeMoat enforcing its configured policy matched the key on 34 of 35 states with 0 false PASS. The run resumed after the daily spend cap; three files off the prompt and scoring path changed in between (listed in the commit). T5 tested giving the agent raw Cypher access; ScopeMoat's gate does not depend on it (the agent receives the gate's verdict, not the graph). | [t5/runs/fri4/report.json](t5/runs/fri4/report.json), [audit.json](t5/runs/fri4/audit.json), [t5/README.md](t5/README.md) | @@ -128,12 +129,12 @@ The 40-case key was written by the author, 17 of those cases were used to develo - [G-DIR](provider_reference/GAPS.md): when a one-way connection's control is unstated, the stated direction is lost. - [G-SEG](provider_reference/GAPS.md): "a connection exists, its control is not stated" is recorded as missing evidence. All 7 UNRESOLVED provider labels come from it. - C6b default forwarding ([GAPS.md](provider_reference/GAPS.md), [RULE_TO_SSC.md](provider_reference/RULE_TO_SSC.md)): a restricted hop with no relay fact forwards under `in_scope`. This is ScopeMoat's policy, not SSC text. The demo BLOCK depends on it, and so do two sensitivity variants. -- Segmentation is a recorded property, not linked to a test report. Firewalls, people and processes are not modeled. The commit gate understands one change type: services on plain Compose networks. Anything else is REVIEW REQUIRED, and `git commit --no-verify` skips the local hook. +- Segmentation is a recorded property, not linked to a test report. Firewalls, people and processes are not modeled. The commit gate understands one change type: services on plain Compose networks. Anything else is REVIEW REQUIRED, and `git commit --no-verify` skips the local hook. The gate models network membership, not application settings such as a database URL in an environment variable. The local hook runs the engine in your working tree. - A scoping aid on modeled graphs, not a QSA assessment. PASS means "no modeled scope expansion". ## Pull request check -The same gate runs on every pull request ([.github/workflows/scopemoat.yml](.github/workflows/scopemoat.yml), [ci/pr_check.py](ci/pr_check.py)). The result is the gate's own exit code: PASS succeeds, and BLOCK, REVIEW REQUIRED and ERROR fail. [Pull request #1](https://github.com/Innov8zig/ScopeMoat/pull/1) is the live demo. It is kept open and is not meant to be merged. +The same gate runs on every pull request ([.github/workflows/scopemoat.yml](.github/workflows/scopemoat.yml), [ci/pr_check.py](ci/pr_check.py)). The result is the gate's own exit code: PASS succeeds, and BLOCK, REVIEW REQUIRED and ERROR fail. [Pull request #1](https://github.com/Innov8zig/ScopeMoat/pull/1) is the live demo. It is kept open and is not meant to be merged. The check runs the base branch's engine, and a pull request that changes the gate itself (`scopemoat/`, `scopeguard/`, `ci/`, `.github/`, `requirements.txt`) is held for review. GitHub runs a pull request's own workflow file, so changes under `.github/` still need a human reviewer. ## Files @@ -156,7 +157,7 @@ Records under `blind/`, `t3/runs/`, `t4/runs/` and `provider_reference/results/` - Claude (Anthropic) helped write and test the code and the documents. claude-sonnet-5-5 is the coding agent under test in `t3/`, `t4/` and `t5/`. - ChatGPT (OpenAI) reviewed the engine and the Relate integration in hostile review rounds. Codex (OpenAI) independently re-ran the benchmark scorer's freeze candidates. -- No model decides a verdict: Relate finds the paths, and Python applies the scoping policy. +- No model decides a verdict: Relate's Cypher computes the in-scope classes and paths, the Python rules recheck them, and Python handles unresolved evidence. ## License and notices diff --git a/acceptance.py b/acceptance.py index ac3920c..db89ea6 100644 --- a/acceptance.py +++ b/acceptance.py @@ -1516,7 +1516,7 @@ def _labelled(o): # ---- L: the rename to ScopeMoat (Dec 1, 2026). The pre-rename name 'scopeguard' stays usable: frozen prototypes, # replay scripts and hooks installed before the rename import or run it. There is one implementation (scopemoat/). import importlib # noqa: E402 -_LMODS = ("cli", "compose", "engine", "environment", "gate", "generator", "mcp", "picture", "reach", "rules_v5", "store", "suggest", "chokepoints") +_LMODS = ("cli", "compose", "engine", "environment", "gate", "generator", "mcp", "picture", "reach", "rules_v5", "store", "suggest", "chokepoints", "relate_scope") _same = [(m, importlib.import_module("scopeguard." + m) is importlib.import_module("scopemoat." + m)) for m in _LMODS] check("L1 every scopeguard module is the scopemoat module itself (one implementation; a patch through the old name " "patches the engine ScopeMoat runs)", @@ -1825,6 +1825,112 @@ def _mtext(i): finally: shutil.rmtree(_c4dir, ignore_errors=True) +# D: the gate consumes Relate's confirmed scope (scopemoat/relate_scope.py), the Python rules must agree, and any +# disagreement or Relate failure refuses the change as REVIEW REQUIRED (never PASS). experiments/force_relate.py forces +# Relate's answer in one process only. +def _force(mode, *args): + return subprocess.run([sys.executable, "-m", "experiments.force_relate", mode, "--", *args], cwd=HERE, + capture_output=True, text=True, encoding="utf-8", timeout=300) + + +_d1 = _force("count", "check", "graph/brightline.rl", "changes/bi_to_orders.json") +check("D1 the gate asks Relate for the confirmed scope on the baseline and on the changed graph (2 calls), and the demo " + "change is BLOCK with Relate's path", + _d1.returncode == 1 and "known_scope calls=2" in _d1.stderr and "VERDICT: BLOCK: 1 system(s) enter scope" in _d1.stdout + and "Relate path: bi-dashboards -> orders-api -> checkout-api" in _d1.stdout, + f"exit {_d1.returncode}; {_d1.stderr.strip().splitlines()[-1] if _d1.stderr.strip() else 'no stderr'}") +_d2 = _force("drop", "check", "graph/brightline.rl", "changes/bi_to_orders.json") +check("D2 Relate's answer decides: if Relate's rows omit bi-dashboards, the same change is not BLOCK or PASS but REVIEW " + "REQUIRED (exit 2), naming the disagreement", + _d2.returncode == 2 and "Relate and the Python rules disagree on the confirmed scope" in _d2.stdout + and "changed bi-dashboards: Relate OUT, Python OTHER" in _d2.stdout, + f"exit {_d2.returncode}") +_d3 = _force("add", "check", "graph/brightline.rl", "changes/bi_to_orders.json") +check("D3 Python must agree: a system Relate adds that the Python rules do not put in scope makes the change REVIEW " + "REQUIRED (exit 2), naming it", + _d3.returncode == 2 and "changed wiki: Relate OTHER, Python OUT" in _d3.stdout, f"exit {_d3.returncode}") +_d4 = _force("unavailable", "check", "graph/brightline.rl", "changes/bi_to_orders.json") +check("D4 Relate unavailable: REVIEW REQUIRED (exit 2), never PASS", + _d4.returncode == 2 and "Relate could not compute the confirmed scope for this change" in _d4.stdout, + f"exit {_d4.returncode}") +_d5dir = tempfile.mkdtemp(prefix="acc-force-hook-") +try: + _d5 = os.path.join(_d5dir, "repo") + subprocess.run(["git", "clone", "-q", HERE, _d5], capture_output=True, timeout=300) + for _k, _v in (("user.email", "acc@example.com"), ("user.name", "acc")): + subprocess.run(["git", "config", _k, _v], cwd=_d5, capture_output=True) + subprocess.run([sys.executable, "-m", "scopemoat", "install-hook"], cwd=_d5, capture_output=True, timeout=120) + _hp = os.path.join(_d5, ".git", "hooks", "pre-commit") + with open(_hp, encoding="utf-8") as _f: + _hook = _f.read() + with open(_hp, "w", encoding="utf-8", newline="\n") as _f: + _f.write(_hook.replace("-m scopemoat gate", "-m experiments.force_relate drop -- gate")) + with open(os.path.join(HERE, "t3/runs/20261130T025027Z_bi_order_status/trace.json"), encoding="utf-8") as _f: + _comp = json.load(_f)["steps"][0]["compose"] + with open(os.path.join(_d5, "deploy", "compose.yaml"), "w", encoding="utf-8", newline="\n") as _f: + _f.write(_comp) + subprocess.run(["git", "add", "deploy/compose.yaml"], cwd=_d5, capture_output=True) + _head0 = subprocess.run(["git", "rev-parse", "HEAD"], cwd=_d5, capture_output=True, text=True).stdout + _d5c = subprocess.run(["git", "commit", "-m", "forced disagreement"], cwd=_d5, capture_output=True, text=True, + encoding="utf-8", timeout=300) + _head1 = subprocess.run(["git", "rev-parse", "HEAD"], cwd=_d5, capture_output=True, text=True).stdout + _d5out = _d5c.stdout + _d5c.stderr + check("D5 through the installed Git hook, a forced Relate/Python disagreement refuses the commit (exit 2) with the " + "diagnostic, and HEAD does not move", + _d5c.returncode != 0 and "Relate and the Python rules disagree on the confirmed scope" in _d5out + and "Commit blocked by ScopeMoat (exit 2)" in _d5out and _head0 == _head1, + f"commit exit {_d5c.returncode}; HEAD moved {_head0 != _head1}") +finally: + shutil.rmtree(_d5dir, ignore_errors=True) + +# E: the pull request check runs the base branch's engine, not the pull request's, and holds any pull request that +# changes the gate itself for review (ci/pr_check.py). Each case runs pr_check.py from a fresh base checkout. +_edir = tempfile.mkdtemp(prefix="acc-prcheck-") +try: + _er = os.path.join(_edir, "repo") + subprocess.run(["git", "clone", "-q", HERE, _er], capture_output=True, timeout=300) + + def _eg(*a): + return subprocess.run(["git", *a], cwd=_er, capture_output=True, text=True, encoding="utf-8") + + _eg("config", "user.email", "acc@example.com"), _eg("config", "user.name", "acc") + _ebase = _eg("rev-parse", "HEAD").stdout.strip() + with open(os.path.join(HERE, "t3/runs/20261130T025027Z_bi_order_status/trace.json"), encoding="utf-8") as _f: + _ecomp = json.load(_f)["steps"][0]["compose"] + + def _epr(name, edits): + _eg("checkout", "-q", "-B", name, _ebase) + for rel, fn in edits: + p = os.path.join(_er, rel) + with open(p, encoding="utf-8") as f: + s = f.read() + with open(p, "w", encoding="utf-8", newline="\n") as f: + f.write(fn(s)) + _eg("commit", "-q", "-am", name) + sha = _eg("rev-parse", "HEAD").stdout.strip() + _eg("checkout", "-q", "--detach", _ebase) + r = subprocess.run([sys.executable, "ci/pr_check.py", _ebase, sha], cwd=_er, capture_output=True, text=True, + encoding="utf-8", timeout=600, env={k: v for k, v in os.environ.items() if k != "PYTHONPATH"}) + _eg("reset", "-q", "--hard", _ebase), _eg("clean", "-qfd") + return r + + _bi = ("deploy/compose.yaml", lambda s: _ecomp) + _off = ("scopemoat/__main__.py", lambda s: "import sys\nsys.exit(0)\n") + _e1 = _epr("pr-bi", [_bi]) + check("E1 pull request check: the BI change alone is BLOCK (exit 1)", + _e1.returncode == 1 and "## ScopeMoat: BLOCK" in _e1.stdout, f"exit {_e1.returncode}") + _e2 = _epr("pr-bi-engine-off", [_bi, _off]) + check("E2 pull request check: the same change plus an edit that switches the gate off in the pull request's own " + "engine is still BLOCK (exit 1): the check runs the base branch's engine", + _e2.returncode == 1 and "## ScopeMoat: BLOCK" in _e2.stdout, f"exit {_e2.returncode}") + _e3 = _epr("pr-engine-comment", [("scopemoat/engine.py", lambda s: s + "\n# harmless comment\n")]) + check("E3 pull request check: a pull request that changes the gate itself (here a comment in scopemoat/engine.py) " + "is REVIEW REQUIRED (exit 2), naming the files", + _e3.returncode == 2 and "changes the gate itself" in _e3.stdout and "scopemoat/engine.py" in _e3.stdout, + f"exit {_e3.returncode}") +finally: + shutil.rmtree(_edir, ignore_errors=True) + print("[RECORD] T3 agent repair: t3/runs/20261130T025027Z_bi_order_status (replay: python -m t3.clean_replay)") print("[RECORD] T4 benchmark: t4/runs/live1/README.md (one paid batch, blind-scored; arm B did not win)") diff --git a/ci/pr_check.py b/ci/pr_check.py index 5a9c5b8..a3dec14 100644 --- a/ci/pr_check.py +++ b/ci/pr_check.py @@ -1,10 +1,16 @@ """ScopeMoat pull request check (GitHub Actions). -Runs the unchanged commit gate (python -m scopemoat gate) on a pull request: -the base branch is checked out as HEAD, so the engine, the store and the -baseline compose.yaml all come from the base branch, and the pull request's -changes are staged on top of it. The verdict and exit code are the gate's own -(0 PASS, 1 BLOCK, 2 REVIEW REQUIRED, 3 ERROR); this script adds no verdict logic. +Runs the commit gate (python -m scopemoat gate) on a pull request: the base +branch is checked out as HEAD, so the store and the baseline compose.yaml come +from the base branch, and the pull request's changes are staged on top of it. +The gate's code also comes from the base branch: scopemoat/ and scopeguard/ are +copied before the pull request is staged, and the gate runs from that copy +(python -P, so the working tree is not on the import path). A pull request that +changes the gate itself (scopemoat/, scopeguard/, ci/, .github/, +requirements.txt) is held for review even when the gate finds nothing. Otherwise +the verdict and exit code are the gate's own (0 PASS, 1 BLOCK, 2 REVIEW +REQUIRED, 3 ERROR). GitHub runs a pull request's own workflow file on +pull_request events, so changes to .github/ need a human reviewer regardless. When the gate refuses the change under the default policy, the script also judges the same staged change against a baseline built with the stricter @@ -14,11 +20,14 @@ Usage (from a checkout of the base commit): python ci/pr_check.py BASE_SHA HEAD_SHA """ import os +import shutil import subprocess import sys import tempfile -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +PROTECTED = ("scopemoat/", "scopeguard/", "ci/", ".github/", "requirements.txt") +ENGINE = None # copy of the base branch's scopemoat/ and scopeguard/, made before the pull request is staged EXPLORER = "https://innov8zig.github.io/ScopeMoat/explorer/" README = "https://github.com/Innov8zig/ScopeMoat#try-it-about-one-minute-from-clone-once-python-313-is-installed" @@ -41,22 +50,37 @@ def stage_pull_request(base, head): return git("diff", "--cached", "--name-only").split() +def snapshot_engine(): + """Copy the base branch's gate code out of the working tree, before the pull request is staged.""" + dst = tempfile.mkdtemp(prefix="scopemoat-base-engine-") + for pkg in ("scopemoat", "scopeguard"): + shutil.copytree(os.path.join(ROOT, pkg), os.path.join(dst, pkg), + ignore=shutil.ignore_patterns("__pycache__")) + return dst + + +def _engine_env(): + return {**os.environ, "PYTHONPATH": ENGINE} + + def run_gate(picture): - r = subprocess.run([sys.executable, "-m", "scopemoat", "gate", "--picture", picture], - capture_output=True, text=True) + r = subprocess.run([sys.executable, "-P", "-m", "scopemoat", "gate", "--picture", picture], + capture_output=True, text=True, env=_engine_env()) text = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if not l.startswith("Picture:")) return r.returncode, text.rstrip() def review_policy_view(): """Judge the same staged compose.yaml against a baseline built with --policy review.""" + if ENGINE not in sys.path: + sys.path.insert(0, ENGINE) from scopemoat import gate, store head_text = git("show", f"HEAD:{COMPOSE}") staged_text = git("show", f":{COMPOSE}") tmp = tempfile.mkdtemp(prefix="scopemoat-review-") path = os.path.join(tmp, "review.rl") - subprocess.run([sys.executable, "-m", "scopemoat", "build-store", path, "--policy", "review"], - capture_output=True, text=True, check=True) + subprocess.run([sys.executable, "-P", "-m", "scopemoat", "build-store", path, "--policy", "review"], + capture_output=True, text=True, check=True, env=_engine_env()) lines = [] conn, _ = store.open_baseline(path) try: @@ -87,10 +111,17 @@ def facts(text): def main(argv): + global ENGINE base, head = argv[1], argv[2] + if git("rev-parse", "HEAD").strip() != git("rev-parse", base).strip(): + raise SystemExit("check out the base commit first (git checkout --detach BASE_SHA)") + ENGINE = snapshot_engine() changed = stage_pull_request(base, head) pic = os.path.join(tempfile.mkdtemp(prefix="scopemoat-pic-"), "path.md") code, gate_out = run_gate(pic) + gate_files = [f for f in changed if f.startswith(PROTECTED) or f in PROTECTED] + if gate_files and code == 0: + code = 2 verdict = {0: "PASS", 1: "BLOCK", 2: "REVIEW REQUIRED"}.get(code, "ERROR") md = [f"## ScopeMoat: {verdict}", ""] if code == 0: @@ -104,11 +135,14 @@ def main(argv): "the model does not record.") else: md.append("The check could not reach a verdict, so it fails closed. No pass is reported.") + if gate_files: + md += ["", f"This pull request changes the gate itself ({', '.join(gate_files)}). The check ran the base branch's " + "engine, and holds the change for human review: a pull request cannot approve its own gate."] md += ["", f"Files in this pull request: {', '.join(changed) or '(none)'}", ""] if os.path.exists(pic): with open(pic, encoding="utf-8") as f: md += [f.read().strip(), ""] - md += ["Commit gate output (`python -m scopemoat gate`, engine and baseline from the base branch):", "", + md += ["Commit gate output (`python -m scopemoat gate`, engine, store and baseline from the base branch):", "", "```", gate_out, "```", ""] if code == 1 and "restricted_hops=in_scope" in gate_out: try: diff --git a/experiments/force_relate.py b/experiments/force_relate.py new file mode 100644 index 0000000..a5ef842 --- /dev/null +++ b/experiments/force_relate.py @@ -0,0 +1,37 @@ +"""Test harness: run the ScopeMoat CLI with Relate's confirmed scope forced, to prove the gate consumes it. + + python -m experiments.force_relate MODE -- + +MODE: + count no change; prints how many times the gate asked Relate for the confirmed scope (stderr) + drop Relate's answer for the changed graph omits bi-dashboards (Python still has it) + add Relate's answer for the changed graph adds a system Python does not put in scope (wiki) + unavailable Relate cannot answer within the search-size guard + +Used by acceptance.py (D1-D5). It patches only this process; nothing on disk changes. +""" +import sys + +from scopemoat import cli, relate_scope + +mode, args = sys.argv[1], sys.argv[sys.argv.index("--") + 1:] +orig, calls = relate_scope.known_scope, [] + + +def forced(m): + calls.append(1) + if mode == "unavailable": + raise relate_scope.Unavailable("forced by experiments/force_relate.py") + k = orig(m) + changed = len(calls) == 2 # rules_v5.evaluate asks for the baseline first, then the changed graph + if changed and mode == "drop": + k = {**k, "other": k["other"] - {"bi-dashboards"}, "transit": {s: p for s, p in k["transit"].items() if s != "bi-dashboards"}} + if changed and mode == "add": + k = {**k, "other": k["other"] | {"wiki"}} + return k + + +relate_scope.known_scope = forced +code = cli.main(args) +print(f"force_relate: mode={mode} known_scope calls={len(calls)}", file=sys.stderr) +sys.exit(code) diff --git a/experiments/relate_classes.py b/experiments/relate_classes.py index bf6bb30..34205ea 100644 --- a/experiments/relate_classes.py +++ b/experiments/relate_classes.py @@ -1,108 +1,4 @@ -"""Scope classes on recorded facts computed by Relate (Cypher), as an independent second implementation. - -The shipped gate is unchanged: it still classifies with rules_v5 (Python) and asks Relate only the R4/R4R transit -question (scopemoat/reach.py). This module computes every in-scope class on recorded facts with Relate queries -over the same per-direction evidence, so the two implementations can be compared (python -m experiments.relate_classes_parity): - - R1 card data systems: stores or processes PAN, or an endpoint of a PAN/SAD flow - R1S / R2 open link (segmentation none, either direction) to a card data system: CDE - R2C a possible link (none or restricted, either direction) to a CDE system: other in scope - R3 provides security services to a CDE system: other in scope - R4 / R4R reaches the CDE through other systems: reach.PATH_QUERY, unchanged - -What stays in Python, and why: the per-direction evidence (rules_v5.Model.directions, the same rows the gate writes) -and the worst-case set behind UNRESOLVED. The worst case treats every unrecorded fact as open, and Relate 1.4.0 -answers quantified path patterns by enumerating trails: on Brightline the worst-case transit search explores more -than two million trails (measured Dec 3, 2026), so it is not asked of Relate. -""" -import relate - -from scopemoat import reach - -R1_QUERY = """ -MATCH (s:System) -WHERE s.pan OR EXISTS { (s)-[f:SENDS]-(:System) WHERE f.data IN ['PAN', 'SAD'] AND f.self = false } -RETURN s.name AS system ORDER BY system -""" - -OPEN_TO_CHD_QUERY = """ -MATCH (s:System)-[r:REACH WHERE r.seg = 'none']-(c:System) -WHERE c.name IN $chd AND NOT s.name IN $chd -RETURN DISTINCT s.name AS system ORDER BY system -""" - -R2C_QUERY = """ -MATCH (s:System)-[r:REACH WHERE r.seg IN ['none', 'restricted']]-(c:System) -WHERE c.name IN $cde AND NOT s.name IN $cde -RETURN DISTINCT s.name AS system ORDER BY system -""" - -R3_QUERY = """ -MATCH (p:System)-[:SECURES]->(c:System) -WHERE c.name IN $cde AND NOT p.name IN $scope -RETURN DISTINCT p.name AS system ORDER BY system -""" - - -class Unavailable(RuntimeError): - """Relate could not answer within the search-size guard.""" - - -def inputs(m): - """Everything the queries read, as plain JSON-ready data (also exported for the browser explorer).""" - return { - "systems": [{"name": n, "zone": z or "", "pan": n in m.pan} for n, z in sorted(m.zone.items())], - "flows": [{"s": f["source"], "t": f["target"], "d": f["data"]} for f in m.flows], - "secures": [{"a": a, "b": b} for a, b in m.secures], - "rows": reach.evidence(m), - "policy": m.policy, - "max_hops": max(1, len(m.zone)), - } - - -LOAD = [ - ("UNWIND $systems AS n CREATE (:System {name: n.name, zone: n.zone, pan: n.pan})", "systems"), - ("UNWIND $flows AS f MATCH (a:System {name: f.s}), (b:System {name: f.t}) " - "CREATE (a)-[:SENDS {data: f.d, self: f.s = f.t}]->(b)", "flows"), - ("UNWIND $secures AS p MATCH (a:System {name: p.a}), (b:System {name: p.b}) CREATE (a)-[:SECURES]->(b)", "secures"), - ("UNWIND $rows AS r MATCH (a:System {name: r.x}), (b:System {name: r.y}) " - "CREATE (a)-[:REACH {rid: r.rid, seg: r.seg, op: r.op, relay: r.relay, ops: r.ops, change: r.change}]->(b)", "rows"), -] -MARK_CDE = "MATCH (s:System) SET s.reach_cde = s.name IN $cde" - - -def plan(): - """The query plan, in order. scopemoat/explorer runs these exact strings in Relate's WebAssembly build.""" - return {"load": [{"query": q, "param": k} for q, k in LOAD], "r1": R1_QUERY, "open_to_chd": OPEN_TO_CHD_QUERY, - "r2c": R2C_QUERY, "r3": R3_QUERY, "mark_cde": MARK_CDE, "path": reach.PATH_QUERY, - "eligible": list(reach.ELIGIBLE)} - - -def known_scope(m): - """{'cde': set, 'other': set, 'transit': {system: path}} on recorded facts, computed by Relate queries.""" - data = inputs(m) - c = relate.connect(":memory:") - try: - for q, k in LOAD: - c.execute(q, {k: data[k]}) - chd = {r["system"] for r in c.execute(R1_QUERY)} - cde = chd | {r["system"] for r in c.execute(OPEN_TO_CHD_QUERY, {"chd": sorted(chd)})} - other = {r["system"] for r in c.execute(R2C_QUERY, {"cde": sorted(cde)})} - other |= {r["system"] for r in c.execute(R3_QUERY, {"cde": sorted(cde), "scope": sorted(cde | other)})} - skip = sorted(cde | other) - if reach.search_size(data["rows"], cde, skip, m.policy, data["max_hops"]) > reach.SEARCH_CAP: - raise Unavailable("transit search above the search-size guard") - c.execute(MARK_CDE, {"cde": sorted(cde)}) - transit = {r["system"]: r["path"] for r in c.execute(reach.PATH_QUERY % {"max_hops": data["max_hops"]}, - {"eligible": list(reach.ELIGIBLE), "policy": m.policy, "skip": skip})} - return {"cde": cde, "other": other | set(transit), "transit": transit} - finally: - c.close() - - -def classes(m, worst): - """CDE / OTHER / UNRESOLVED / OUT for every system: in-scope classes from Relate, UNRESOLVED from `worst` - (the rules_v5 worst-case scope, computed in Python).""" - k = known_scope(m) - return {n: ("CDE" if n in k["cde"] else "OTHER" if n in k["other"] else "UNRESOLVED" if n in worst else "OUT") - for n in m.zone} +"""Moved to scopemoat/relate_scope.py: the commit gate now takes its confirmed scope from these Relate queries. +Kept as an alias so the parity check, the explorer build and older docs keep working.""" +from scopemoat.relate_scope import * # noqa: F401,F403 +from scopemoat.relate_scope import LOAD, MARK_CDE, Unavailable, classes, inputs, known_scope, plan # noqa: F401 diff --git a/explorer/data/scenarios.json b/explorer/data/scenarios.json index 1daff37..7ddb837 100644 --- a/explorer/data/scenarios.json +++ b/explorer/data/scenarios.json @@ -1,6 +1,6 @@ { - "commit": "7c88209", - "engine": "scopemoat/engine.py (committed; rules v5: scopemoat/rules_v5.py sha256 e02fb5cfdade)", + "commit": "55b298b", + "engine": "scopemoat/engine.py (committed; rules v5: scopemoat/rules_v5.py sha256 7927ee145cbf)", "relate_db": "1.4.0", "scenarios": [ { diff --git a/explorer/scope.html b/explorer/scope.html index 51ae69c..90b9fda 100644 --- a/explorer/scope.html +++ b/explorer/scope.html @@ -36,8 +36,8 @@

Relate computes the scope, in your browser

-

The commit gate asks Relate one question: which systems reach card data through other systems. This page goes further. It loads the systems, data flows and per-direction link evidence into Relate's WebAssembly build (1.4.0), runs the Cypher implementation of the scoping rules here in this tab, and compares every in-scope class with the Python rules the gate ships. No install, no account, no API key.

-

Back to the commit gate explorer · Query plan: experiments/relate_classes.py · Same comparison in Node: node explorer/classes_parity.mjs

+

The commit gate takes its confirmed scope from these Cypher queries, and the Python rules must agree. This page runs the same queries here in this tab: it loads the systems, data flows and per-direction link evidence into Relate's WebAssembly build (1.4.0), computes every in-scope class, and compares each one with the Python rules. No install, no account, no API key.

+

Back to the commit gate explorer · Query plan: scopemoat/relate_scope.py · Same comparison in Node: node explorer/classes_parity.mjs

Loading Relate...

diff --git a/explorer/scope.js b/explorer/scope.js index d261e43..515c1c8 100644 --- a/explorer/scope.js +++ b/explorer/scope.js @@ -32,7 +32,7 @@ function show(id) { function queries() { const p = data.plan; const items = [["Load (systems, flows, security services, REACH evidence)", p.load.map((l) => l.query).join("\n\n")], - ["R1", p.r1], ["R1S/R2", p.open_to_chd], ["R2C", p.r2c], ["R3", p.r3], ["Mark the CDE", p.mark_cde], ["R4/R4R (the commit gate's own query)", p.path]]; + ["R1", p.r1], ["R1S/R2", p.open_to_chd], ["R2C", p.r2c], ["R3", p.r3], ["Mark the CDE", p.mark_cde], ["R4/R4R", p.path]]; $("queries").innerHTML = items.map(([t, q]) => `
${esc(t)}
${esc(q.trim())}
`).join(""); } diff --git a/scopeguard/relate_scope.py b/scopeguard/relate_scope.py new file mode 100644 index 0000000..31273ee --- /dev/null +++ b/scopeguard/relate_scope.py @@ -0,0 +1,10 @@ +"""Pre-rename alias: scopeguard.relate_scope is scopemoat.relate_scope, the same module object (see scopeguard/__init__.py).""" +import sys + +if __name__ == "__main__": # python -m scopeguard.relate_scope + import runpy + runpy.run_module("scopemoat.relate_scope", run_name="__main__", alter_sys=True) +else: + import scopemoat.relate_scope as _real + sys.modules[__name__] = _real + sys.modules["scopeguard"]._sync() diff --git a/scopemoat/relate_scope.py b/scopemoat/relate_scope.py new file mode 100644 index 0000000..db93120 --- /dev/null +++ b/scopemoat/relate_scope.py @@ -0,0 +1,109 @@ +"""Scope classes on recorded facts computed by Relate (Cypher), as an independent second implementation. + +The commit gate takes its confirmed scope (which systems enter scope or move into the CDE) from these queries: +scopemoat/rules_v5.evaluate calls known_scope() on the baseline and on the changed model, and the Python rules +recompute the same sets independently. Any disagreement fails closed to REVIEW REQUIRED (never PASS). Parity over +every frozen state: python -m experiments.relate_classes_parity. + + R1 card data systems: stores or processes PAN, or an endpoint of a PAN/SAD flow + R1S / R2 open link (segmentation none, either direction) to a card data system: CDE + R2C a possible link (none or restricted, either direction) to a CDE system: other in scope + R3 provides security services to a CDE system: other in scope + R4 / R4R reaches the CDE through other systems: reach.PATH_QUERY, unchanged + +What stays in Python, and why: the per-direction evidence (rules_v5.Model.directions, the same rows the gate writes) +and the worst-case set behind UNRESOLVED. The worst case treats every unrecorded fact as open, and Relate 1.4.0 +answers quantified path patterns by enumerating trails: on Brightline the worst-case transit search explores more +than two million trails (measured Dec 3, 2026), so it is not asked of Relate. +""" +import relate + +from scopemoat import reach + +R1_QUERY = """ +MATCH (s:System) +WHERE s.pan OR EXISTS { (s)-[f:SENDS]-(:System) WHERE f.data IN ['PAN', 'SAD'] AND f.self = false } +RETURN s.name AS system ORDER BY system +""" + +OPEN_TO_CHD_QUERY = """ +MATCH (s:System)-[r:REACH WHERE r.seg = 'none']-(c:System) +WHERE c.name IN $chd AND NOT s.name IN $chd +RETURN DISTINCT s.name AS system ORDER BY system +""" + +R2C_QUERY = """ +MATCH (s:System)-[r:REACH WHERE r.seg IN ['none', 'restricted']]-(c:System) +WHERE c.name IN $cde AND NOT s.name IN $cde +RETURN DISTINCT s.name AS system ORDER BY system +""" + +R3_QUERY = """ +MATCH (p:System)-[:SECURES]->(c:System) +WHERE c.name IN $cde AND NOT p.name IN $scope +RETURN DISTINCT p.name AS system ORDER BY system +""" + + +class Unavailable(RuntimeError): + """Relate could not answer within the search-size guard.""" + + +def inputs(m): + """Everything the queries read, as plain JSON-ready data (also exported for the browser explorer).""" + return { + "systems": [{"name": n, "zone": z or "", "pan": n in m.pan} for n, z in sorted(m.zone.items())], + "flows": [{"s": f["source"], "t": f["target"], "d": f["data"]} for f in m.flows], + "secures": [{"a": a, "b": b} for a, b in m.secures], + "rows": reach.evidence(m), + "policy": m.policy, + "max_hops": max(1, len(m.zone)), + } + + +LOAD = [ + ("UNWIND $systems AS n CREATE (:System {name: n.name, zone: n.zone, pan: n.pan})", "systems"), + ("UNWIND $flows AS f MATCH (a:System {name: f.s}), (b:System {name: f.t}) " + "CREATE (a)-[:SENDS {data: f.d, self: f.s = f.t}]->(b)", "flows"), + ("UNWIND $secures AS p MATCH (a:System {name: p.a}), (b:System {name: p.b}) CREATE (a)-[:SECURES]->(b)", "secures"), + ("UNWIND $rows AS r MATCH (a:System {name: r.x}), (b:System {name: r.y}) " + "CREATE (a)-[:REACH {rid: r.rid, seg: r.seg, op: r.op, relay: r.relay, ops: r.ops, change: r.change}]->(b)", "rows"), +] +MARK_CDE = "MATCH (s:System) SET s.reach_cde = s.name IN $cde" + + +def plan(): + """The query plan, in order. scopemoat/explorer runs these exact strings in Relate's WebAssembly build.""" + return {"load": [{"query": q, "param": k} for q, k in LOAD], "r1": R1_QUERY, "open_to_chd": OPEN_TO_CHD_QUERY, + "r2c": R2C_QUERY, "r3": R3_QUERY, "mark_cde": MARK_CDE, "path": reach.PATH_QUERY, + "eligible": list(reach.ELIGIBLE)} + + +def known_scope(m): + """{'cde': set, 'other': set, 'transit': {system: path}} on recorded facts, computed by Relate queries.""" + data = inputs(m) + c = relate.connect(":memory:") + try: + for q, k in LOAD: + c.execute(q, {k: data[k]}) + chd = {r["system"] for r in c.execute(R1_QUERY)} + cde = chd | {r["system"] for r in c.execute(OPEN_TO_CHD_QUERY, {"chd": sorted(chd)})} + other = {r["system"] for r in c.execute(R2C_QUERY, {"cde": sorted(cde)})} + other |= {r["system"] for r in c.execute(R3_QUERY, {"cde": sorted(cde), "scope": sorted(cde | other)})} + skip = sorted(cde | other) + if reach.search_size(data["rows"], cde, skip, m.policy, data["max_hops"]) > reach.SEARCH_CAP: + raise Unavailable("transit search above the search-size guard") + c.execute(MARK_CDE, {"cde": sorted(cde)}) + transit = {r["system"]: r["path"] for r in c.execute(reach.PATH_QUERY % {"max_hops": data["max_hops"]}, + {"eligible": list(reach.ELIGIBLE), "policy": m.policy, "skip": skip})} + return {"cde": cde, "other": other | set(transit), "transit": transit} + finally: + c.close() + + +def classes(m, worst): + """CDE / OTHER / UNRESOLVED / OUT for every system: in-scope classes from Relate, UNRESOLVED from `worst` + (the rules_v5 worst-case scope, computed in Python).""" + k = known_scope(m) + return {n: ("CDE" if n in k["cde"] else "OTHER" if n in k["other"] else "UNRESOLVED" if n in worst else "OUT") + for n in m.zone} diff --git a/scopemoat/rules_v5.py b/scopemoat/rules_v5.py index dbee8e7..0e18b3b 100644 --- a/scopemoat/rules_v5.py +++ b/scopemoat/rules_v5.py @@ -16,7 +16,7 @@ import relate -from scopemoat import environment, reach +from scopemoat import environment, reach, relate_scope from scopemoat import engine as E from scopemoat.engine import Finding, Result @@ -1203,11 +1203,37 @@ def evaluate(conn, ops, replaces=None): r.reductions, r.review_groups, r.review_detail, r.basis_removed = [], {}, {}, {} r.reach = {"baseline": rb.record, "candidate": ra.record, "new": {}, "error": str(e)} return r + # Confirmed scope from Relate: every in-scope class on recorded facts, computed by Cypher + # (scopemoat/relate_scope.py), before and after the change. The BLOCK sets below come from Relate's rows; + # the Python rules (bb, ab) recompute them independently. Any disagreement fails closed to REVIEW. + try: + kb, ka = relate_scope.known_scope(before), relate_scope.known_scope(after) + except relate_scope.Unavailable as e: + r = Result(E.REVIEW, "Relate could not compute the confirmed scope for this change", + problems=[str(e)], notes=notes) + r.reductions, r.review_groups, r.review_detail, r.basis_removed = [], {}, {}, {} + r.reach = {"baseline": rb.record, "candidate": ra.record, "new": {}, "error": str(e)} + return r + def _relate_class(k): + return {n: ("CDE" if n in k["cde"] else "OTHER") for n in k["cde"] | k["other"]} + rel_b, rel_a = _relate_class(kb), _relate_class(ka) + py_b = {n: ("CDE" if f.category == "CDE" else "OTHER") for n, f in bb.items()} + py_a = {n: ("CDE" if f.category == "CDE" else "OTHER") for n, f in ab.items()} + if rel_b != py_b or rel_a != py_a: + diff = [f"{tag} {n}: Relate {rel.get(n, 'OUT')}, Python {py.get(n, 'OUT')}" + for tag, rel, py in (("baseline", rel_b, py_b), ("changed", rel_a, py_a)) + for n in sorted(set(rel) | set(py)) if rel.get(n) != py.get(n)] + r = Result(E.REVIEW, "Relate and the Python rules disagree on the confirmed scope", problems=diff, notes=notes) + r.reductions, r.review_groups, r.review_detail, r.basis_removed = [], {}, {}, {} + r.reach = {"baseline": rb.record, "candidate": ra.record, "new": {}, "error": "relate/python disagreement"} + return r bw, aw = scope_of(before, True), scope_of(after, True) cb = {n: (("CDE" if bb[n].category == "CDE" else "OTHER") if n in bb else ("UNRESOLVED" if n in bw else "OUT")) for n in before.zone} ca = {n: (("CDE" if ab[n].category == "CDE" else "OTHER") if n in ab else ("UNRESOLVED" if n in aw else "OUT")) for n in after.zone} - entered = {k: v for k, v in ab.items() if k not in bb} - moved = {k: v for k, v in ab.items() if k in bb and v.category == "CDE" and bb[k].category != "CDE"} + # Which systems enter scope or move into the CDE: decided on Relate's classes (rel_b, rel_a). The Findings + # attached (rule, path) are the Python rules' explanation of the same systems; the sets are equal by the check above. + entered = {k: v for k, v in ab.items() if k in rel_a and k not in rel_b} + moved = {k: v for k, v in ab.items() if k in rel_a and k in rel_b and rel_a[k] == "CDE" and rel_b[k] != "CDE"} reductions = sorted(n for n in before.zone if RANK[ca[n]] < RANK[cb[n]]) review, review_groups, review_detail = {}, {}, {} missing_links = set() # links whose missing segmentation evidence a witness depends on (port: old report line)