diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a293e7d..8f2bade 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,6 +106,15 @@ jobs: --python "$wheel_python" --expected-version "$expected" python "$GITHUB_WORKSPACE/scripts/run_cursor_coverage_demo.py" \ --python "$wheel_python" --output "$RUNNER_TEMP/cursor-coverage-demo.json" + python "$GITHUB_WORKSPACE/scripts/run_approval_demo.py" \ + --python "$wheel_python" --output-dir "$RUNNER_TEMP/approval-demo" + - name: Retain the deletion approval replay + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: approval-demo-${{ matrix.os }} + path: ${{ runner.temp }}/approval-demo/ + if-no-files-found: error + retention-days: 7 - name: Retain the installed coverage demo evidence uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: diff --git a/README.md b/README.md index 6777fb7..e7bdaf4 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,10 @@ decisions. No model API or runtime dependencies are needed. [Setup demo](#quick-start) · [Workflow diagram](#what-it-helps-you-review) · [Score history demo](#score-history-demo) · [Visual gallery](https://github.com/LE0-Lin/AgentConfigScore/blob/main/docs/visual-tour.md) +[Deletion approval prototype](https://github.com/LE0-Lin/AgentConfigScore/blob/main/docs/ai-safety-challenge.md): +replay a lost approval requirement, repair its coverage, and try a separate +approval-gated executor on disposable files. Includes scripted cases and explicit host trust boundaries. + The demo uses v0.24.0 on a local fixture. Adding a remote-shell instruction lowers the score from 100 to 82, identifies `AGENTS.md:5`, and fails the new-error gate. The gallery also includes an instruction move drawn from a diff --git a/README.simplified.md b/README.simplified.md index 35b3edd..2d8e3ee 100644 --- a/README.simplified.md +++ b/README.simplified.md @@ -8,6 +8,8 @@ [安装演示](#快速开始) · [分数历史演示](#分数历史演示) · [完整演示图集](docs/visual-tour.md) +[删除审批原型](docs/ai-safety-challenge.md):复跑审批要求失去覆盖、修复覆盖的配置检查,再体验独立示例执行器对临时文件的审批与删除。包含脚本化案例和明确的宿主信任边界。 + 演示使用 v0.24.0 扫描本地样例。新增远程脚本指令后,分数从 100 降到 82,工具定位到 `AGENTS.md:5`,新增错误门禁返回 1。图集还保留了取材自已合并 PR 的文件迁移演示,展示前后同为 100 分时的路径复核。[复跑精简 PR 案例](examples/instruction-move/README.md)。 AgentConfigScore 检查 `AGENTS.md`、`CLAUDE.md`、Cursor、Copilot、Gemini 等配置,并比较改动前后的基线,回答一个具体问题:**这次改动是否引入了已知规则能检测到的风险?** diff --git a/README.traditional.md b/README.traditional.md index 6243983..094cab1 100644 --- a/README.traditional.md +++ b/README.traditional.md @@ -8,6 +8,8 @@ [安裝示範](#快速開始) · [分數歷史示範](#分數歷史示範) · [完整示範圖集](docs/visual-tour.md) +[刪除審批原型](docs/ai-safety-challenge.md):重現審批要求失去涵蓋、修復涵蓋的設定檢查,再體驗獨立範例執行器對暫存檔案的審批與刪除。包含指令碼化案例與明確的主機信任邊界。 + 示範使用 v0.24.0 掃描本機範例。新增遠端指令碼指令後,分數從 100 降到 82,工具定位到 `AGENTS.md:5`,新增錯誤閘門回傳 1。圖集也保留了取材自已合併 PR 的檔案移動示範,展示前後同為 100 分時的路徑審閱。[重現精簡 PR 範例](examples/instruction-move/README.md)。 AgentConfigScore 檢查 `AGENTS.md`、`CLAUDE.md`、Cursor、Copilot、Gemini 等設定,並與改動前的基準比較,回答一個具體問題:**這次改動是否引入了已知規則能偵測到的風險?** diff --git a/docs/README.md b/docs/README.md index f445ba3..a8e4074 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ read the result, and troubleshoot a failing gate. - [Maintainer setup, actionable next steps and PR results](maintainer-workflow.md) (v0.24.0+) - [Unscored instruction-file best-practice checklist](best-practices.md) - [Visual tour](visual-tour.md) +- [Deletion approval prototype: configuration review and a separate host gate](ai-safety-challenge.md) - [Instruction templates](../examples/README.md) - [Opt-in deletion safeguard review and completion](guardrail-suggestions.md) (v0.24.0+) - [Cursor rule activation for declared file context](cursor-scope.md) (v0.25.0+, unscored) diff --git a/docs/ai-safety-challenge.md b/docs/ai-safety-challenge.md new file mode 100644 index 0000000..ad9922f --- /dev/null +++ b/docs/ai-safety-challenge.md @@ -0,0 +1,89 @@ +# Preserve a deletion approval requirement across a change + +**A reproducible prototype for reviewing a configuration regression and refusing +an unapproved tool operation.** The example combines the released ACS static +checker with a small, separate host executor operating on real disposable files. + +```mermaid +flowchart LR + A[Rule glob changes] --> B[Installed ACS comparison] + B --> C[Lost active directive: review fails] + C --> D[Restore target coverage: review passes] + E[Agent delete_file request] --> F[Host approval gate] + G[Trusted operator issues scoped approval] --> F + F --> H[Missing or invalid approval: refuse] + F --> I[Matching approval: delete one temporary file] +``` + +## 1. Catch the configuration regression + +The baseline rule is `.cursor/rules/deletion.mdc`: + +```markdown +--- +globs: "workspace/**" +alwaysApply: false +--- +Never delete files without approval. +``` + +The candidate changes only line 2 to `globs: "docs/**"`. The instruction still +exists, and both scans score 100, but it no longer covers the declared target +`workspace/obsolete.txt`. Installed ACS v0.26.1 reports one recognized active +directive lost, with the original source at line 5, and exits 1 under the +explicit `--fail-on-lost-directives --fail-on-unknown` review policy. Restoring +coverage exits 0. This is a bounded attachment prediction, not an observation of +the model's context or a claim that the model will comply. + +## 2. Gate the tool operation before its effect + +The host owns a temporary workspace and exposes one operation: `delete_file`. +A separate operator interface issues an opaque, expiring, single-use approval +bound to the exact relative path and reviewed file state. The agent cannot +authorize itself by adding `approved: true`. It can present an issued token; +the host looks up the grant and validates it before calling single-file unlink. + +The console lets a person approve or refuse a disposable-file deletion. The +automated replay simulates the operator with a trusted harness and exercises +12 scripted tool-request scenarios. It verifies real filesystem outcomes, +including a valid deletion, refused repetition and preservation of unrelated +files. These are known development cases, not live-agent or independent +accuracy measurements. + +## Run and inspect + +Clone [the repository](https://github.com/LE0-Lin/AgentConfigScore), then: + +```bash +python -m pip install agent-config-score==0.26.1 +python scripts/run_approval_demo.py --output-dir approval-demo-result +python examples/approval-gate/try_gate.py +``` + +The output directory must be new. The first command sequence produces full JSON +and Markdown evidence. The last command opens the local operator console; +only freshly created demo files can be deleted. Normal temporary-directory +cleanup follows either an approved operation or refusal. + +- [Retained replay with installed source identity](../examples/approval-gate/recorded/result.md) +- [Full JSON: static source lines, execution decisions and input hashes](../examples/approval-gate/recorded/result.json) +- [Executor, API contract, tests and trust boundary](../examples/approval-gate/README.md) +- [Gate regression tests](../tests/test_approval_gate_demo.py) +- [Cross-platform installed-wheel CI](../.github/workflows/ci.yml) + +## Scope of the prototype + +The contribution is a reviewable link between an existing configuration +regression check and a minimal approval-gated operation, with failure and repair +controls. ACS remains a static CLI and CI gate. The executor is separate +repository example code; installing ACS does not intercept agent actions. + +The host must keep the workspace stable and deny the agent other filesystem or +code-execution channels. This is not an OS sandbox or a defense against a +concurrent attacker changing paths between checks and unlink. Operator +authentication and a secure approval interface belong to the real host. Only +one regular file up to 1 MiB is supported; approval state is process-local. + +The existing [native Cursor smoke test](../benchmarks/cursor-native-v1/README.md) +is separate evidence about selected rule-marker behavior. It does not validate +this executor or turn these scripted scenarios into real-world safety results. diff --git a/examples/README.md b/examples/README.md index be32049..710b37d 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,5 +1,10 @@ # Copy-ready instruction examples +For an approval-gated operation alongside configuration review, try the +[deletion approval prototype](approval-gate/README.md). Its separate host +executor operates only on disposable files in the demo; it does not add runtime +interception to the ACS package. + For a runnable explanation of the regression gate rather than an instruction template, see the [design lab](regression-lab/README.md). It compares five known synthetic before/after scenarios under three explicitly defined gate settings; diff --git a/examples/approval-gate/README.md b/examples/approval-gate/README.md new file mode 100644 index 0000000..1652cfa --- /dev/null +++ b/examples/approval-gate/README.md @@ -0,0 +1,112 @@ +# Deletion approval: configuration review and execution + +This prototype pairs two separately enforced checks: + +1. Installed **ACS v0.26.1** reviews a Cursor rule change. Narrowing the glob + stops the declared deletion-approval instruction from covering the selected + target. Both standalone scores remain 100; the opt-in review exits 1. +2. The independent example host executor in [gate.py](gate.py) refuses a + `delete_file` request until it has matching operator approval. It checks the + actual filesystem after each scripted request. + +The runnable example uses local temporary files, no model API, no network and +no new runtime dependencies. See the [challenge walkthrough](../../docs/ai-safety-challenge.md) +and [recorded replay](recorded/result.md). + +## Try the operator console + +From a checkout of this repository, using Python 3.10+: + +```bash +python examples/approval-gate/try_gate.py +``` + +The first request is refused. The console then shows the disposable file and +asks the operator to type `DELETE`. Refusal leaves the file present until normal +temporary-workspace cleanup. Approval actually deletes that one file. Existing +user paths cannot be supplied to this console. The operator console must remain +outside the agent's tool access. + +## Reproduce both layers + +Install ACS in your selected Python environment, then run from the checkout: + +```bash +python -m pip install agent-config-score==0.26.1 +python scripts/run_approval_demo.py --output-dir approval-demo-result +``` + +`approval-demo-result` must not exist. Use `--python /absolute/path/to/python` +when ACS is installed in another environment. The subprocess uses isolated +Python from a temporary working directory, so repository sources cannot silently +replace the installed ACS. It is offline after installation. The example and +runner are repository files, separate from the installed wheel. + +Completion writes `result.json` with installed source identity, normalized-text +SHA-256 input hashes, full static comparisons and execution decisions, plus +`result.md` for reading. Exit 0 means the registered synthetic scenarios and +their filesystem postconditions matched; exit 2 means replay or output failed. +Do not treat a partial output directory after failure as completed evidence. + +The 12 scripted execution scenarios cover missing approval, self-approval, +invented tokens, expiry, target mismatch, changed content, file replacement, +different sessions, traversal, unregistered tools, authorized deletion and replay. +Approvals in this replay come from the **trusted test harness**, not a human or +a live agent. Two files are actually deleted: the authorized case and the replay +setup. Every scenario checks that unrelated sentinels are preserved. + +```bash +python -m unittest discover -s tests -p test_approval_gate_demo.py -v +``` + +Additional tests cover root/parent replacement, hard links, symbolic links when +permitted, invalid lifetimes, size limits and filesystem failure. A filesystem +error returns `error` with `executed: null` (outcome requires inspection), not a +successful refusal. Once execution is attempted, that grant is consumed even on +an I/O error; another attempt requires fresh approval. + +## Approval contract + +The trusted host obtains separate operator and tool handles: + +```python +operator, delete_file = create_session(disposable_workspace) +# Operator reviews the proposed relative path and file content outside agent access. +token = operator.approve("obsolete.txt", ttl_seconds=30) +result = delete_file({"tool": "delete_file", "path": "obsolete.txt", "approval": token}) +``` + +Only `delete_file` belongs in the agent registry. `Operator.approve` is the +trusted issuance API; it does not itself authenticate a human. The host must +perform that authentication/review before calling it. `approved: true` is +rejected. An opaque token is bound to the session, exact portable relative path, +parent identities, file identity, size, modification time, content digest, +host-clock expiry (maximum 60 seconds) and one attempt. POSIX ctime is also +checked; Python 3.12 exposes differing legacy ctime semantics on Windows, so +Windows uses the other recorded signals. No raw token is written to reports. + +## Trust boundary and limitations + +- **Exclusively owned, stable local workspace.** No other process may mutate + files or ancestors during approval/execution. Python checks followed by unlink + are not an atomic defense against hostile concurrent filesystem changes. + The lock serializes this example's own operations only. +- **Tool-only agent access.** The agent cannot execute arbitrary Python, run a + shell, access host filesystem APIs, inspect operator state or call another + deletion channel. In-process Python handles are not a security isolation + boundary. A real deployment must enforce this separation outside agent control. +- **One regular file.** The gate refuses directories, recursive deletion, + symlinks/reparse points, hard links, nonportable paths and files above 1 MiB. + It is intentionally unsuitable as a general file-management API. +- **Process-local grants.** Restart forgets approvals. Persistent identity, + distributed execution, signed audit storage, approval UI security, OS sandboxing + and adversarial races are not implemented. +- **Separate layers.** Static ACS predicts declared instruction availability; + it does not inspect these calls or prove the agent followed the instruction. + This example enforces approval only for its registered operation. Rule text + is never evaluated as executable policy. The wrapper is not a shipped ACS + runtime capability. + +These are development controls, not independent accuracy evidence or a claim +that arbitrary irreversible actions are prevented. Production adoption needs +review of the host, its tools, approver authentication and execution boundary. diff --git a/examples/approval-gate/config/base/.cursor/rules/deletion.mdc b/examples/approval-gate/config/base/.cursor/rules/deletion.mdc new file mode 100644 index 0000000..e96a5cb --- /dev/null +++ b/examples/approval-gate/config/base/.cursor/rules/deletion.mdc @@ -0,0 +1,5 @@ +--- +globs: "workspace/**" +alwaysApply: false +--- +Never delete files without approval. diff --git a/examples/approval-gate/config/base/workspace/obsolete.txt b/examples/approval-gate/config/base/workspace/obsolete.txt new file mode 100644 index 0000000..dd348e7 --- /dev/null +++ b/examples/approval-gate/config/base/workspace/obsolete.txt @@ -0,0 +1 @@ +Disposable fixture content. The static comparison does not delete this file. diff --git a/examples/approval-gate/config/narrowed/.cursor/rules/deletion.mdc b/examples/approval-gate/config/narrowed/.cursor/rules/deletion.mdc new file mode 100644 index 0000000..71d0534 --- /dev/null +++ b/examples/approval-gate/config/narrowed/.cursor/rules/deletion.mdc @@ -0,0 +1,5 @@ +--- +globs: "docs/**" +alwaysApply: false +--- +Never delete files without approval. diff --git a/examples/approval-gate/config/narrowed/workspace/obsolete.txt b/examples/approval-gate/config/narrowed/workspace/obsolete.txt new file mode 100644 index 0000000..dd348e7 --- /dev/null +++ b/examples/approval-gate/config/narrowed/workspace/obsolete.txt @@ -0,0 +1 @@ +Disposable fixture content. The static comparison does not delete this file. diff --git a/examples/approval-gate/config/repaired/.cursor/rules/deletion.mdc b/examples/approval-gate/config/repaired/.cursor/rules/deletion.mdc new file mode 100644 index 0000000..e96a5cb --- /dev/null +++ b/examples/approval-gate/config/repaired/.cursor/rules/deletion.mdc @@ -0,0 +1,5 @@ +--- +globs: "workspace/**" +alwaysApply: false +--- +Never delete files without approval. diff --git a/examples/approval-gate/config/repaired/workspace/obsolete.txt b/examples/approval-gate/config/repaired/workspace/obsolete.txt new file mode 100644 index 0000000..dd348e7 --- /dev/null +++ b/examples/approval-gate/config/repaired/workspace/obsolete.txt @@ -0,0 +1 @@ +Disposable fixture content. The static comparison does not delete this file. diff --git a/examples/approval-gate/gate.py b/examples/approval-gate/gate.py new file mode 100644 index 0000000..18bc2a7 --- /dev/null +++ b/examples/approval-gate/gate.py @@ -0,0 +1,162 @@ +"""Small, tool-only deletion gate for an exclusively owned local demo workspace. + +This is example host code, not an ACS runtime feature or an OS sandbox. An agent +must have access only to the returned tool callable, never the operator handle, +host interpreter, filesystem APIs or another deletion tool. The host must prevent +concurrent filesystem mutation. See README.md for the complete trust boundary. +""" +from __future__ import annotations + +import hashlib +import math +import os +from pathlib import Path +import re +import secrets +import stat +import threading +import time + + +MAX_FILE_BYTES = 1024 * 1024 + + +class Refused(ValueError): + pass + + +def _is_alias(info) -> bool: + return stat.S_ISLNK(info.st_mode) or bool(getattr(info, "st_file_attributes", 0) & 0x400) + + +def _identity(info) -> tuple: + return info.st_dev, info.st_ino + + +class _State: + def __init__(self, root: Path, clock): + if _is_alias(root.lstat()) or not root.is_dir(): + raise Refused("workspace_not_regular_directory") + self.root = root.resolve() + self.root_identity = _identity(self.root.lstat()) + self.clock = clock + self.grants = {} + self.lock = threading.Lock() + + def target(self, value) -> Path: + if (type(value) is not str or not value or len(value) > 512 + or not re.fullmatch(r"[A-Za-z0-9_./-]+", value)): + raise Refused("invalid_relative_path") + parts = value.split("/") + if any(not p or p in {".", ".."} or p.endswith(".") or len(p) > 128 + or p.split(".")[0].upper() in {"CON", "PRN", "AUX", "NUL", *[f"COM{i}" for i in range(1, 10)], + *[f"LPT{i}" for i in range(1, 10)]} for p in parts): + raise Refused("invalid_relative_path") + root_info = self.root.lstat() + if _is_alias(root_info) or _identity(root_info) != self.root_identity or not stat.S_ISDIR(root_info.st_mode): + raise Refused("workspace_changed") + target = self.root.joinpath(*parts) + if not target.is_relative_to(self.root): + raise Refused("outside_workspace") + return target + + def snapshot(self, path: str) -> tuple: + target = self.target(path) + parents = [] + current = self.root + for part in path.split("/")[:-1]: + current = current / part + info = current.lstat() + if _is_alias(info) or not stat.S_ISDIR(info.st_mode): + raise Refused("aliased_or_invalid_parent") + parents.append(_identity(info)) + before = target.lstat() + if _is_alias(before) or not stat.S_ISREG(before.st_mode) or before.st_nlink != 1: + raise Refused("target_not_single_regular_file") + if before.st_size > MAX_FILE_BYTES: + raise Refused("target_size_limit") + descriptor = os.open(target, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)) + with os.fdopen(descriptor, "rb") as source: + opened = os.fstat(source.fileno()) + if (_identity(opened) != _identity(before) or not stat.S_ISREG(opened.st_mode) + or opened.st_nlink != 1): + raise Refused("target_changed") + raw = source.read(MAX_FILE_BYTES + 1) + after = os.fstat(source.fileno()) + # Windows 3.12 path stat and fd stat expose different legacy ctime + # semantics. Identity + mtime + size + content still bind the grant; + # retain ctime as an additional mutation signal on POSIX only. + stamp = lambda s: (_identity(s), s.st_size, s.st_mtime_ns, + s.st_ctime_ns if os.name != "nt" else None) + if len(raw) > MAX_FILE_BYTES or stamp(before) != stamp(after) or stamp(target.lstat()) != stamp(after): + raise Refused("target_changed") + return tuple(parents), stamp(after), hashlib.sha256(raw).hexdigest() + + +class Operator: + """Trusted host/operator handle. Never place this in the agent tool registry.""" + + def __init__(self, state): + self._state = state + + def approve(self, path: str, *, ttl_seconds=30) -> str: + if (type(ttl_seconds) not in (int, float) or not math.isfinite(ttl_seconds) + or not 0 < ttl_seconds <= 60): + raise Refused("invalid_approval_lifetime") + with self._state.lock: + snapshot = self._state.snapshot(path) + token = secrets.token_urlsafe(32) + self._state.grants[token] = {"path": path, "snapshot": snapshot, + "expires": self._state.clock() + ttl_seconds, "used": False} + return token + + +class DeleteTool: + """The only registered agent operation in this demonstration.""" + + def __init__(self, state): + self._state = state + + def __call__(self, request) -> dict: + def denied(reason): + return {"decision": "denied", "reason": reason, "executed": False} + + if type(request) is not dict or set(request) - {"tool", "path", "approval"}: + return denied("invalid_request_schema") + if request.get("tool") != "delete_file": + return denied("unregistered_tool") + try: + with self._state.lock: + target = self._state.target(request.get("path")) + token = request.get("approval") + if token is None: + return denied("approval_required") + if type(token) is not str or len(token) > 128: + return denied("invalid_approval") + grant = self._state.grants.get(token) + if grant is None: + return denied("invalid_approval") + if grant["used"]: + return denied("approval_already_used") + if self._state.clock() >= grant["expires"]: + return denied("approval_expired") + if request["path"] != grant["path"]: + return denied("approval_target_mismatch") + if self._state.snapshot(request["path"]) != grant["snapshot"]: + return denied("approved_state_changed") + # Consume before the effect; I/O failure also needs fresh approval. + grant["used"] = True + target.unlink() + return {"decision": "executed", "reason": "matching_operator_approval", "executed": True} + except Refused as error: + return denied(str(error)) + except OSError: + # No raw paths, OS messages or approval tokens in shareable results. + # An OS error is not proof that no effect occurred; require inspection. + return {"decision": "error", "reason": "filesystem_error", "executed": None} + + +def create_session(root: Path, *, clock=time.monotonic) -> tuple[Operator, DeleteTool]: + """Register the approved root once. Approval state is local to this session.""" + state = _State(root, clock) + return Operator(state), DeleteTool(state) diff --git a/examples/approval-gate/recorded/result.json b/examples/approval-gate/recorded/result.json new file mode 100644 index 0000000..791c94d --- /dev/null +++ b/examples/approval-gate/recorded/result.json @@ -0,0 +1,696 @@ +{ + "schema_version": 1, + "evidence_tier": "synthetic_development_demo", + "operator": "trusted_harness_simulation", + "live_agent_run": false, + "independent_accuracy_estimate": null, + "host": { + "system": "Windows", + "python": "3.12.0" + }, + "text_inputs_sha256_lf": { + "examples/approval-gate/gate.py": "ef987d4870fb62a3e81bd89f4d8e5dc7ebe4a6ccb1b8bb14eaab8e123e6d102b", + "examples/approval-gate/try_gate.py": "be14858511e0b56867f674ad1b74b9d2ae3cec8693172ac39d3cdea5d5ae55bb", + "scripts/run_approval_demo.py": "d9e8443305198cabc29b56b120c7edcfc95f5a9bfe568c5243331fe4468ca64b", + "tests/test_approval_gate_demo.py": "8ad2bc66d5b5d1fe9e310e9523310b8c9fb689d87d199eb5c7c3a48f82a55830", + "examples/approval-gate/config/base/workspace/obsolete.txt": "16b4c67fecc27158bd6f0bbb2650eeb862b87dc665fe4675486acbd3708c0bf5", + "examples/approval-gate/config/narrowed/workspace/obsolete.txt": "16b4c67fecc27158bd6f0bbb2650eeb862b87dc665fe4675486acbd3708c0bf5", + "examples/approval-gate/config/repaired/workspace/obsolete.txt": "16b4c67fecc27158bd6f0bbb2650eeb862b87dc665fe4675486acbd3708c0bf5", + "examples/approval-gate/config/base/.cursor/rules/deletion.mdc": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da", + "examples/approval-gate/config/narrowed/.cursor/rules/deletion.mdc": "fe59ba24cefda4a7d65c7bd7a91b1dc27250b8ab51baec84aa34f4930ed4e938", + "examples/approval-gate/config/repaired/.cursor/rules/deletion.mdc": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da" + }, + "static": { + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "cases": [ + { + "case": "narrowed", + "exit": 1, + "standalone_scores": [ + 100, + 100 + ], + "report": { + "schema_version": 1, + "analysis": "cursor_file_context_comparison", + "profile": "cursor-file-context-v1", + "comparison_profile": "cursor-activation-delta-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "observed_agent_context": false, + "targets_existence_checked": false, + "comparison_inputs": { + "base": "supplied_tree", + "head": "supplied_tree" + }, + "base": { + "schema_version": 1, + "analysis": "cursor_file_context", + "profile": "cursor-file-context-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "targets_existence_checked": false, + "observed_agent_context": false, + "activation_inputs": "declared_file_paths_only", + "unmodelled_inputs": [ + "manual_mentions", + "model_selection", + "user_team_rules", + "runtime_settings", + "other_instruction_formats" + ], + "rules": [ + { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "active", + "reason": "declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [ + "workspace/obsolete.txt" + ], + "source_sha256": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da", + "directive_analysis": "bounded_prose", + "recognized_directives": 1 + } + ], + "opposing_directives": [], + "summary": { + "rules": 1, + "other_supported_sources": 0, + "active": 1, + "inactive": 0, + "unknown": 0, + "uninterpreted_bodies": 0, + "active_signals": 0, + "uncertain_signals": 0 + } + }, + "head": { + "schema_version": 1, + "analysis": "cursor_file_context", + "profile": "cursor-file-context-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "targets_existence_checked": false, + "observed_agent_context": false, + "activation_inputs": "declared_file_paths_only", + "unmodelled_inputs": [ + "manual_mentions", + "model_selection", + "user_team_rules", + "runtime_settings", + "other_instruction_formats" + ], + "rules": [ + { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "inactive", + "reason": "no_declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [], + "source_sha256": "fe59ba24cefda4a7d65c7bd7a91b1dc27250b8ab51baec84aa34f4930ed4e938", + "directive_analysis": "bounded_prose", + "recognized_directives": 0 + } + ], + "opposing_directives": [], + "summary": { + "rules": 1, + "other_supported_sources": 0, + "active": 0, + "inactive": 1, + "unknown": 0, + "uninterpreted_bodies": 0, + "active_signals": 0, + "uncertain_signals": 0 + } + }, + "rule_changes": [ + { + "file": ".cursor/rules/deletion.mdc", + "change": "modified", + "transition": "active_to_inactive", + "base": { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "active", + "reason": "declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [ + "workspace/obsolete.txt" + ], + "source_sha256": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da", + "directive_analysis": "bounded_prose", + "recognized_directives": 1 + }, + "head": { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "inactive", + "reason": "no_declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [], + "source_sha256": "fe59ba24cefda4a7d65c7bd7a91b1dc27250b8ab51baec84aa34f4930ed4e938", + "directive_analysis": "bounded_prose", + "recognized_directives": 0 + }, + "trigger_targets_lost": [ + "workspace/obsolete.txt" + ], + "trigger_targets_gained": [], + "automatic_attachment_lost": true + } + ], + "directive_changes": [ + { + "polarity": "neg", + "directive_sha256": "bbc6dc1fda0b056e3ec305db6585e1f83a865e60ae38a773aab699640ab5946c", + "transition": "active_to_inactive", + "base": { + "availability": "active", + "sources": [ + { + "file": ".cursor/rules/deletion.mdc", + "line": 5, + "polarity": "neg", + "activation": "active" + } + ], + "uninterpreted_sources": [] + }, + "head": { + "availability": "inactive", + "sources": [ + { + "file": ".cursor/rules/deletion.mdc", + "line": 5, + "polarity": "neg", + "activation": "inactive" + } + ], + "uninterpreted_sources": [] + }, + "recognized_active_lost": true, + "recognized_active_gained": false + } + ], + "summary": { + "rules_added": 0, + "rules_removed": 0, + "rules_modified": 1, + "automatic_attachment_losses": 1, + "baseline_active_directives": 1, + "retained_active_directives": 0, + "recognized_active_losses": 1, + "recognized_active_gains": 0, + "uncertain_directives": 0, + "unknown_rules": 0, + "uninterpreted_noninactive_bodies": 0, + "has_unknown": false + }, + "review_gate": { + "fail_on_lost_directives": true, + "fail_on_unknown": true, + "failed": true, + "reasons": [ + "recognized_active_directives_lost" + ] + } + } + }, + { + "case": "repaired", + "exit": 0, + "standalone_scores": [ + 100, + 100 + ], + "report": { + "schema_version": 1, + "analysis": "cursor_file_context_comparison", + "profile": "cursor-file-context-v1", + "comparison_profile": "cursor-activation-delta-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "observed_agent_context": false, + "targets_existence_checked": false, + "comparison_inputs": { + "base": "supplied_tree", + "head": "supplied_tree" + }, + "base": { + "schema_version": 1, + "analysis": "cursor_file_context", + "profile": "cursor-file-context-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "targets_existence_checked": false, + "observed_agent_context": false, + "activation_inputs": "declared_file_paths_only", + "unmodelled_inputs": [ + "manual_mentions", + "model_selection", + "user_team_rules", + "runtime_settings", + "other_instruction_formats" + ], + "rules": [ + { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "active", + "reason": "declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [ + "workspace/obsolete.txt" + ], + "source_sha256": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da", + "directive_analysis": "bounded_prose", + "recognized_directives": 1 + } + ], + "opposing_directives": [], + "summary": { + "rules": 1, + "other_supported_sources": 0, + "active": 1, + "inactive": 0, + "unknown": 0, + "uninterpreted_bodies": 0, + "active_signals": 0, + "uncertain_signals": 0 + } + }, + "head": { + "schema_version": 1, + "analysis": "cursor_file_context", + "profile": "cursor-file-context-v1", + "tool": { + "name": "AgentConfigScore", + "version": "0.26.1", + "source_fingerprint": { + "format": "acs-python-source-v1", + "sha256": "d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5", + "files": [ + "__init__.py", + "__main__.py", + "cli.py", + "config.py", + "doctor.py", + "entrypoint.py", + "feedback.py", + "gitdiff.py", + "guardrails.py", + "history.py", + "initializer.py", + "provenance.py", + "regression.py", + "rules.py", + "sarif.py", + "scanner.py", + "scopes.py" + ] + } + }, + "status": "completed", + "scored": false, + "targets": [ + "workspace/obsolete.txt" + ], + "targets_existence_checked": false, + "observed_agent_context": false, + "activation_inputs": "declared_file_paths_only", + "unmodelled_inputs": [ + "manual_mentions", + "model_selection", + "user_team_rules", + "runtime_settings", + "other_instruction_formats" + ], + "rules": [ + { + "file": ".cursor/rules/deletion.mdc", + "mode": "patterns", + "activation": "active", + "reason": "declared_target_matches", + "pattern_count": 1, + "metadata_lines": { + "globs": 2, + "alwaysApply": 3 + }, + "body_line": 5, + "matched_targets": [ + "workspace/obsolete.txt" + ], + "source_sha256": "c62b9bfb9cc145093f6d2251c375b1da6a9f60ca31f8e32f503157c001efe8da", + "directive_analysis": "bounded_prose", + "recognized_directives": 1 + } + ], + "opposing_directives": [], + "summary": { + "rules": 1, + "other_supported_sources": 0, + "active": 1, + "inactive": 0, + "unknown": 0, + "uninterpreted_bodies": 0, + "active_signals": 0, + "uncertain_signals": 0 + } + }, + "rule_changes": [], + "directive_changes": [], + "summary": { + "rules_added": 0, + "rules_removed": 0, + "rules_modified": 0, + "automatic_attachment_losses": 0, + "baseline_active_directives": 1, + "retained_active_directives": 1, + "recognized_active_losses": 0, + "recognized_active_gains": 0, + "uncertain_directives": 0, + "unknown_rules": 0, + "uninterpreted_noninactive_bodies": 0, + "has_unknown": false + }, + "review_gate": { + "fail_on_lost_directives": true, + "fail_on_unknown": true, + "failed": false, + "reasons": [] + } + } + } + ] + }, + "execution": [ + { + "case": "missing_approval", + "decision": "denied", + "reason": "approval_required", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "self_approval", + "decision": "denied", + "reason": "invalid_request_schema", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "invented_token", + "decision": "denied", + "reason": "invalid_approval", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "expired", + "decision": "denied", + "reason": "approval_expired", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "wrong_target", + "decision": "denied", + "reason": "approval_target_mismatch", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "changed_content", + "decision": "denied", + "reason": "approved_state_changed", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "replaced_file", + "decision": "denied", + "reason": "approved_state_changed", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "different_session", + "decision": "denied", + "reason": "invalid_approval", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "outside_workspace", + "decision": "denied", + "reason": "invalid_relative_path", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "unregistered_tool", + "decision": "denied", + "reason": "unregistered_tool", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "authorized", + "decision": "executed", + "reason": "matching_operator_approval", + "executed": true, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + }, + { + "case": "replay", + "decision": "denied", + "reason": "approval_already_used", + "executed": false, + "filesystem_postcondition_verified": true, + "unrelated_files_preserved": true + } + ], + "actual_temporary_file_deletions": 2, + "limitations": [ + "Static analysis predicts declared attachment; it does not observe this execution.", + "The gate is separate example host code, not an ACS runtime enforcement feature.", + "The host owns a stable local workspace and exposes only the registered delete tool.", + "Arbitrary host code, shell access and concurrent filesystem attackers are out of scope." + ] +} diff --git a/examples/approval-gate/recorded/result.md b/examples/approval-gate/recorded/result.md new file mode 100644 index 0000000..66f452f --- /dev/null +++ b/examples/approval-gate/recorded/result.md @@ -0,0 +1,37 @@ +# Deletion approval replay + +Synthetic development scenarios; operator approvals are simulated by the trusted harness. +No live model was called. These results are not an accuracy or real-world safety estimate. + +Installed ACS: 0.26.1 +Source fingerprint: `d6b3b079d6a8ab0d870020abe5f6489b59536c5a6602e2083dfc80b0c97d1ed5` + +| Configuration change | Scores (base/head) | Lost active directives | Review exit | +|---|---|---|---| +| narrowed | [100, 100] | 1 | 1 | +| repaired | [100, 100] | 0 | 0 | + +| Scripted tool request | Decision | Reason | Filesystem checked | +|---|---|---|---| +| missing_approval | denied | `approval_required` | yes | +| self_approval | denied | `invalid_request_schema` | yes | +| invented_token | denied | `invalid_approval` | yes | +| expired | denied | `approval_expired` | yes | +| wrong_target | denied | `approval_target_mismatch` | yes | +| changed_content | denied | `approved_state_changed` | yes | +| replaced_file | denied | `approved_state_changed` | yes | +| different_session | denied | `invalid_approval` | yes | +| outside_workspace | denied | `invalid_relative_path` | yes | +| unregistered_tool | denied | `unregistered_tool` | yes | +| authorized | executed | `matching_operator_approval` | yes | +| replay | denied | `approval_already_used` | yes | + +Two real file deletions occurred inside disposable temporary directories: the authorized case and the replay setup. +Rejected requests preserved the target; every scenario preserved the unrelated-file sentinels. + +## Boundaries + +- Static analysis predicts declared attachment; it does not observe this execution. +- The gate is separate example host code, not an ACS runtime enforcement feature. +- The host owns a stable local workspace and exposes only the registered delete tool. +- Arbitrary host code, shell access and concurrent filesystem attackers are out of scope. diff --git a/examples/approval-gate/try_gate.py b/examples/approval-gate/try_gate.py new file mode 100644 index 0000000..9629d0c --- /dev/null +++ b/examples/approval-gate/try_gate.py @@ -0,0 +1,39 @@ +"""Try the operator console with a disposable file; no existing user files accepted.""" +from pathlib import Path +from tempfile import TemporaryDirectory + +from gate import create_session + + +def main(): + with TemporaryDirectory(prefix="acs-approval-console-") as directory: + root = Path(directory).resolve() + target = root / "obsolete.txt" + target.write_text("Disposable demonstration file.\n", encoding="utf-8") + operator, delete = create_session(root) + request = {"tool": "delete_file", "path": "obsolete.txt"} + result = delete(request) + assert result["decision"] == "denied" and target.is_file() + print("Agent request: delete_file obsolete.txt") + print("Without approval:", result["reason"], "(file still exists)") + print("Operator review: obsolete.txt contains", repr(target.read_text(encoding="utf-8"))) + print("Only this freshly created temporary file can be selected by this console.") + try: + answer = input("Type DELETE to authorize this one deletion; anything else refuses: ") + except (EOFError, KeyboardInterrupt): + answer = "" + if answer != "DELETE": + print("Operator refused. No delete_file operation was performed.") + else: + token = operator.approve("obsolete.txt") + result = delete({**request, "approval": token}) + if result["decision"] != "executed" or target.exists(): + print("Deletion did not complete; no success is claimed.") + return 2 + print("Approved operation executed. Verified: temporary target no longer exists.") + print("Disposable workspace cleanup follows, independent of the tool decision.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/run_approval_demo.py b/scripts/run_approval_demo.py new file mode 100644 index 0000000..115a1e7 --- /dev/null +++ b/scripts/run_approval_demo.py @@ -0,0 +1,203 @@ +"""Replay static configuration checks and a host-side deletion approval example. + +Scripted development scenarios; no model, network, or external repository calls. +Actual deletions are restricted to fresh TemporaryDirectory workspaces. +""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLE = ROOT / "examples/approval-gate" +SPEC = importlib.util.spec_from_file_location("approval_demo_gate", EXAMPLE / "gate.py") +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def sha(path): + # Repository evidence hashes use normalized text for cross-platform checkouts. + return hashlib.sha256(path.read_text(encoding="utf-8").encode("utf-8")).hexdigest() + + +def static_replay(python: Path) -> dict: + env = os.environ.copy() + for name in ("PYTHONPATH", "PYTHONHOME"): + env.pop(name, None) + env.update(PYTHONNOUSERSITE="1", PYTHONIOENCODING="utf-8") + identity = None + with TemporaryDirectory(prefix="acs-approval-static-") as cwd: + def invoke(args, expected): + nonlocal identity + result = subprocess.run([str(python), "-I", "-X", "utf8", "-m", "agent_config_score", + *args, "--json"], cwd=cwd, env=env, capture_output=True, + text=True, encoding="utf-8", timeout=45) + require(result.returncode == expected and not result.stderr, + "Installed ACS command did not complete with its expected exit") + data = json.loads(result.stdout) + require(data.get("tool", {}).get("source_fingerprint", {}).get("sha256"), + "Missing installed source identity") + if identity is None: + identity = data["tool"] + require(identity == data["tool"], "Mixed installed tool identities") + return data + + base = EXAMPLE / "config/base" + rows = [] + body = (base / ".cursor/rules/deletion.mdc").read_text(encoding="utf-8").split("---", 2)[2] + for case, expected, losses in (("narrowed", 1, 1), ("repaired", 0, 0)): + head = EXAMPLE / "config" / case + require((head / ".cursor/rules/deletion.mdc").read_text(encoding="utf-8").split("---", 2)[2] == body, + "Static demonstration must preserve the instruction body") + report = invoke(["scope", "compare", str(base), str(head), "--target", "workspace/obsolete.txt", + "--fail-on-lost-directives", "--fail-on-unknown"], expected) + summary = report["summary"] + require(report["status"] == "completed" and not summary["has_unknown"] + and summary["recognized_active_losses"] == losses, + "Static comparison disagrees with the development expectation") + scores = [invoke([str(tree)], 0)["score"] for tree in (base, head)] + require(scores == [100, 100], "Standalone score control changed") + rows.append({"case": case, "exit": expected, "standalone_scores": scores, "report": report}) + return {"tool": identity, "cases": rows} + + +def execution_replay() -> list: + rows = [] + cases = ("missing_approval", "self_approval", "invented_token", "expired", "wrong_target", + "changed_content", "replaced_file", "different_session", "outside_workspace", + "unregistered_tool", "authorized", "replay") + expected = ("approval_required", "invalid_request_schema", "invalid_approval", "approval_expired", + "approval_target_mismatch", "approved_state_changed", "approved_state_changed", + "invalid_approval", "invalid_relative_path", "unregistered_tool", + "matching_operator_approval", "approval_already_used") + for case, reason in zip(cases, expected): + with TemporaryDirectory(prefix="acs-approval-execution-") as directory: + parent = Path(directory).resolve() + root = parent / "workspace" + root.mkdir() + target = root / "obsolete.txt" + target.write_bytes(b"reviewed content\n") + other = root / "other.txt" + other.write_bytes(b"other content\n") + outside = parent / "outside.txt" + outside.write_bytes(b"preserve outside\n") + clock = [100.0] + # Trusted harness simulates the operator. This is NOT human-approval evidence. + operator, delete = GATE.create_session(root, clock=lambda: clock[0]) + token = operator.approve("obsolete.txt", ttl_seconds=1) + request = {"tool": "delete_file", "path": "obsolete.txt", "approval": token} + if case == "missing_approval": + request.pop("approval") + elif case == "self_approval": + request.pop("approval") + request["approved"] = True + elif case == "invented_token": + request["approval"] = "invented-token" + elif case == "expired": + clock[0] = 101.0 + elif case == "wrong_target": + request["path"] = "other.txt" + elif case == "changed_content": + target.write_bytes(b"content changed after review\n") + elif case == "replaced_file": + replacement = root / "replacement.txt" + replacement.write_bytes(target.read_bytes()) + os.replace(replacement, target) + elif case == "different_session": + _, delete = GATE.create_session(root, clock=lambda: clock[0]) + elif case == "outside_workspace": + request["path"] = "../outside.txt" + elif case == "unregistered_tool": + request["tool"] = "shell" + elif case == "replay": + first = delete(request) + require(first["executed"] and not target.exists(), "Replay setup deletion failed") + target.write_bytes(b"new file, new intent\n") + before = target.read_bytes() + result = delete(request) + require(result["reason"] == reason, "Execution scenario disagrees with expectation: " + case) + successful = case == "authorized" + require(result["decision"] == ("executed" if successful else "denied") + and result["executed"] == successful, "Unexpected execution status: " + case) + require((not target.exists()) if successful else target.read_bytes() == before, + "Target filesystem postcondition failed: " + case) + require(other.read_bytes() == b"other content\n" and outside.read_bytes() == b"preserve outside\n", + "Unrelated-file preservation failed: " + case) + # Persist neither tokens nor private temp paths. + rows.append({"case": case, **result, "filesystem_postcondition_verified": True, + "unrelated_files_preserved": True}) + return rows + + +def replay(python: Path) -> dict: + static = static_replay(python) + execution = execution_replay() + inputs = [EXAMPLE / "gate.py", EXAMPLE / "try_gate.py", Path(__file__).resolve(), + ROOT / "tests/test_approval_gate_demo.py", + *sorted((EXAMPLE / "config").rglob("*.txt")), + *sorted((EXAMPLE / "config").rglob("*.mdc"))] + return {"schema_version": 1, "evidence_tier": "synthetic_development_demo", + "operator": "trusted_harness_simulation", "live_agent_run": False, + "independent_accuracy_estimate": None, + "host": {"system": platform.system(), "python": platform.python_version()}, + "text_inputs_sha256_lf": {p.relative_to(ROOT).as_posix(): sha(p) for p in inputs}, + "static": static, "execution": execution, + "actual_temporary_file_deletions": 2, + "limitations": ["Static analysis predicts declared attachment; it does not observe this execution.", + "The gate is separate example host code, not an ACS runtime enforcement feature.", + "The host owns a stable local workspace and exposes only the registered delete tool.", + "Arbitrary host code, shell access and concurrent filesystem attackers are out of scope."]} + + +def markdown(report) -> str: + lines = ["# Deletion approval replay", "", "Synthetic development scenarios; operator approvals are simulated by the trusted harness.", + "No live model was called. These results are not an accuracy or real-world safety estimate.", "", + f"Installed ACS: {report['static']['tool']['version']}", + f"Source fingerprint: `{report['static']['tool']['source_fingerprint']['sha256']}`", "", + "| Configuration change | Scores (base/head) | Lost active directives | Review exit |", + "|---|---|---|---|"] + for row in report["static"]["cases"]: + lines.append(f"| {row['case']} | {row['standalone_scores']} | {row['report']['summary']['recognized_active_losses']} | {row['exit']} |") + lines += ["", "| Scripted tool request | Decision | Reason | Filesystem checked |", "|---|---|---|---|"] + for row in report["execution"]: + lines.append(f"| {row['case']} | {row['decision']} | `{row['reason']}` | yes |") + lines += ["", "Two real file deletions occurred inside disposable temporary directories: the authorized case and the replay setup.", + "Rejected requests preserved the target; every scenario preserved the unrelated-file sentinels.", "", + "## Boundaries", "", *["- " + item for item in report["limitations"]], ""] + return "\n".join(lines) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--python", type=Path, default=Path(sys.executable), help="Python with ACS already installed") + parser.add_argument("--output-dir", type=Path, required=True, help="New report directory; existing paths are refused") + args = parser.parse_args(argv) + try: + # Reserve before effects; an existing report is never overwritten. + args.output_dir.mkdir(parents=False, exist_ok=False) + report = replay(args.python.absolute()) + (args.output_dir / "result.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + (args.output_dir / "result.md").write_text(markdown(report), encoding="utf-8") + except (ValueError, OSError, KeyError, TypeError, subprocess.TimeoutExpired) as exc: + print(f"Approval demo failed ({type(exc).__name__}); no completed evidence should be inferred.", file=sys.stderr) + return 2 + print("Completed: 2 static comparisons; 12 scripted execution scenarios; filesystem postconditions verified.") + print("Operator simulation; temporary files only. Read result.md and result.json for boundaries and source identities.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_approval_gate_demo.py b/tests/test_approval_gate_demo.py new file mode 100644 index 0000000..8539f88 --- /dev/null +++ b/tests/test_approval_gate_demo.py @@ -0,0 +1,153 @@ +import importlib.util +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("approval_gate_example", ROOT / "examples/approval-gate/gate.py") +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +class ApprovalGateTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory(prefix="acs-approval-test-") + self.addCleanup(temp.cleanup) + self.parent = Path(temp.name).resolve() + self.root = self.parent / "workspace" + self.root.mkdir() + self.file = self.root / "obsolete.txt" + self.file.write_bytes(b"reviewed content\n") + self.outside = self.parent / "outside.txt" + self.outside.write_bytes(b"preserve outside\n") + self.clock = [100.0] + self.operator, self.delete = GATE.create_session(self.root, clock=lambda: self.clock[0]) + + def request(self, **changes): + return {"tool": "delete_file", "path": "obsolete.txt", **changes} + + def test_missing_and_forged_authority_cannot_delete(self): + for changes, reason in (({}, "approval_required"), ({"approval": "invented-token"}, "invalid_approval"), + ({"approved": True}, "invalid_request_schema"), + ({"approval": {"approved": True}}, "invalid_approval")): + with self.subTest(changes=changes): + result = self.delete(self.request(**changes)) + self.assertEqual(result["reason"], reason) + self.assertFalse(result["executed"]) + self.assertEqual(self.file.read_bytes(), b"reviewed content\n") + + def test_registered_delete_and_single_use_approval(self): + token = self.operator.approve("obsolete.txt") + self.assertTrue(self.delete(self.request(approval=token))["executed"]) + self.assertFalse(self.file.exists()) + self.file.write_bytes(b"new file, new intent\n") + result = self.delete(self.request(approval=token)) + self.assertEqual(result["reason"], "approval_already_used") + self.assertEqual(self.file.read_bytes(), b"new file, new intent\n") + self.assertEqual(self.outside.read_bytes(), b"preserve outside\n") + + def test_expiry_boundary_is_rejected(self): + token = self.operator.approve("obsolete.txt", ttl_seconds=1) + self.clock[0] = 101.0 + self.assertEqual(self.delete(self.request(approval=token))["reason"], "approval_expired") + self.assertTrue(self.file.exists()) + + def test_request_path_and_session_are_bound(self): + (self.root / "other.txt").write_bytes(b"other\n") + token = self.operator.approve("obsolete.txt") + self.assertEqual(self.delete(self.request(path="other.txt", approval=token))["reason"], "approval_target_mismatch") + _, other_session = GATE.create_session(self.root) + self.assertEqual(other_session(self.request(approval=token))["reason"], "invalid_approval") + self.assertTrue(self.file.exists()) + self.assertTrue((self.root / "other.txt").exists()) + + def test_changed_content_requires_new_approval(self): + token = self.operator.approve("obsolete.txt") + self.file.write_bytes(b"changed content\n") + self.assertEqual(self.delete(self.request(approval=token))["reason"], "approved_state_changed") + self.assertEqual(self.file.read_bytes(), b"changed content\n") + + def test_replacement_with_identical_bytes_requires_new_approval(self): + token = self.operator.approve("obsolete.txt") + replacement = self.root / "replacement.txt" + replacement.write_bytes(self.file.read_bytes()) + os.replace(replacement, self.file) + self.assertEqual(self.delete(self.request(approval=token))["reason"], "approved_state_changed") + self.assertTrue(self.file.exists()) + + def test_replaced_parent_directory_requires_new_approval(self): + (self.root / "nested").mkdir() + (self.root / "nested/file.txt").write_bytes(b"a") + token = self.operator.approve("nested/file.txt") + # Explicit, verified sibling destinations inside this disposable fixture. + (self.root / "nested").rename(self.root / "old-nested") + (self.root / "nested").mkdir() + (self.root / "nested/file.txt").write_bytes(b"a") + result = self.delete(self.request(path="nested/file.txt", approval=token)) + self.assertEqual(result["reason"], "approved_state_changed") + self.assertTrue((self.root / "nested/file.txt").exists()) + + def test_paths_and_unregistered_tools_are_refused(self): + token = self.operator.approve("obsolete.txt") + for path in ("../outside.txt", str(self.outside), "C:/outside.txt", "nested\\file.txt", + "a/../obsolete.txt", "./obsolete.txt", "obsolete.txt:stream", "NUL.txt", "a//b", "obsolete.txt."): + with self.subTest(path=path): + self.assertFalse(self.delete(self.request(path=path, approval=token))["executed"]) + self.assertEqual(self.delete(self.request(tool="shell", approval=token))["reason"], "unregistered_tool") + self.assertTrue(self.file.exists()) + self.assertEqual(self.outside.read_bytes(), b"preserve outside\n") + + def test_hard_link_and_directory_are_not_approvable(self): + (self.root / "directory").mkdir() + with self.assertRaises(GATE.Refused): + self.operator.approve("directory") + try: + os.link(self.file, self.root / "alias.txt") + except OSError: + self.skipTest("hard links unavailable on this filesystem") + with self.assertRaises(GATE.Refused): + self.operator.approve("obsolete.txt") + self.assertTrue(self.file.exists()) + + def test_file_and_parent_symlink_cannot_reach_outside(self): + try: + (self.root / "linked.txt").symlink_to(self.outside) + (self.root / "linked-dir").symlink_to(self.parent, target_is_directory=True) + except OSError: + self.skipTest("symlink creation not permitted") + for path in ("linked.txt", "linked-dir/outside.txt"): + with self.subTest(path=path), self.assertRaises(GATE.Refused): + self.operator.approve(path) + self.assertEqual(self.outside.read_bytes(), b"preserve outside\n") + + def test_root_replacement_is_refused(self): + token = self.operator.approve("obsolete.txt") + self.root.rename(self.parent / "old-workspace") + self.root.mkdir() + self.file.write_bytes(b"new workspace content") + self.assertEqual(self.delete(self.request(approval=token))["reason"], "workspace_changed") + self.assertEqual(self.file.read_bytes(), b"new workspace content") + + def test_io_failure_is_error_and_does_not_allow_reuse(self): + token = self.operator.approve("obsolete.txt") + with patch.object(Path, "unlink", side_effect=PermissionError("private host detail")): + result = self.delete(self.request(approval=token)) + self.assertEqual(result, {"decision": "error", "reason": "filesystem_error", "executed": None}) + self.assertEqual(self.delete(self.request(approval=token))["reason"], "approval_already_used") + self.assertTrue(self.file.exists()) + self.assertNotIn(token, str(result)) + + def test_invalid_lifetimes_and_large_files_are_refused(self): + for ttl in (True, 0, -1, float("inf"), float("nan"), 61, "30"): + with self.subTest(ttl=ttl), self.assertRaises(GATE.Refused): + self.operator.approve("obsolete.txt", ttl_seconds=ttl) + self.file.write_bytes(b"x" * (GATE.MAX_FILE_BYTES + 1)) + with self.assertRaises(GATE.Refused): + self.operator.approve("obsolete.txt") + + +if __name__ == "__main__": + unittest.main()