|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Exercise C-05 using unchanged released clients and fresh explicit stores. |
| 3 | +
|
| 4 | +This is an evidence harness, not a plugin or a native Cursor acceptance claim. |
| 5 | +Each invocation refuses an existing root. It never sets HOME/CODEX_HOME. |
| 6 | +""" |
| 7 | +import argparse |
| 8 | +from datetime import datetime, timezone |
| 9 | +import hashlib |
| 10 | +import json |
| 11 | +import os |
| 12 | +from pathlib import Path |
| 13 | +import platform |
| 14 | +import re |
| 15 | +import shutil |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +import time |
| 19 | + |
| 20 | +AGENT_SHA256 = "bff31dc42d6d1a99bf51291039d7719c6a48c2326e582e5e24eaa1eaf11e17ec" |
| 21 | +GREP_SHA256 = "95491857b6a115ce7f4ec2a9d24bd0f7b8efcc1a52bd1403b34a62dd704012ab" |
| 22 | +CONTENT = "Risk requires a Decision: approve a second supplier as the mitigation." |
| 23 | +TAG = "public-project-brief" |
| 24 | +ORIGINAL = "python3 validate_brief.py --chek --output outputs/native-rewrite.json" |
| 25 | +CORRECTED = "python3 validate_brief.py --check --output outputs/native-rewrite.json" |
| 26 | +BRIEF = b"# Public project brief\n\nRisk: supplier delays require a backup plan.\nDecision: approve a second supplier.\n" |
| 27 | +VALIDATOR = '''"""Harmless public validator; no model or network operation.""" |
| 28 | +import argparse |
| 29 | +import hashlib |
| 30 | +import json |
| 31 | +from pathlib import Path |
| 32 | +
|
| 33 | +def main(): |
| 34 | + parser = argparse.ArgumentParser(allow_abbrev=False) |
| 35 | + parser.add_argument("--check", action="store_true", required=True) |
| 36 | + parser.add_argument("--output", type=Path, required=True) |
| 37 | + args = parser.parse_args() |
| 38 | + source = Path(__file__).with_name("brief.md") |
| 39 | + data = source.read_bytes() |
| 40 | + text = data.decode("utf-8") |
| 41 | + if "Risk" not in text or "Decision" not in text: |
| 42 | + parser.error("brief requires Risk and Decision") |
| 43 | + result = {"source": source.name, "sha256": hashlib.sha256(data).hexdigest(), |
| 44 | + "bytes": len(data), "riskOccurrences": text.count("Risk"), |
| 45 | + "decisionOccurrences": text.count("Decision")} |
| 46 | + with args.output.open("x") as stream: |
| 47 | + json.dump(result, stream, indent=2) |
| 48 | + stream.write("\\n") |
| 49 | +
|
| 50 | +if __name__ == "__main__": |
| 51 | + main() |
| 52 | +''' |
| 53 | + |
| 54 | + |
| 55 | +def digest(data): |
| 56 | + return hashlib.sha256(data).hexdigest() |
| 57 | + |
| 58 | + |
| 59 | +def file_identity(path): |
| 60 | + data = path.read_bytes() |
| 61 | + return {"path": str(path), "bytes": len(data), "sha256": digest(data)} |
| 62 | + |
| 63 | + |
| 64 | +def write_json(path, value): |
| 65 | + with path.open("x", encoding="utf-8") as stream: |
| 66 | + json.dump(value, stream, indent=2, ensure_ascii=False) |
| 67 | + stream.write("\n") |
| 68 | + |
| 69 | + |
| 70 | +def assert_released_binary(path, expected): |
| 71 | + if path.is_symlink() or not path.is_file() or not os.access(path, os.X_OK): |
| 72 | + raise ValueError("Release binary must be an executable regular file") |
| 73 | + identity = file_identity(path) |
| 74 | + if identity["sha256"] != expected: |
| 75 | + raise ValueError("Release executable digest mismatch") |
| 76 | + return identity |
| 77 | + |
| 78 | + |
| 79 | +def qualify(root, agent, grep, output_name="native-rewrite.json"): |
| 80 | + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,100}\.json", output_name): |
| 81 | + raise ValueError("Output name must be a bounded plain JSON filename") |
| 82 | + original = ORIGINAL.replace("native-rewrite.json", output_name) |
| 83 | + corrected = CORRECTED.replace("native-rewrite.json", output_name) |
| 84 | + if not root.is_absolute() or root.exists() or root.is_symlink(): |
| 85 | + raise ValueError("Choose a fresh nonexistent absolute qualification root") |
| 86 | + if root.parent.resolve() != root.parent: |
| 87 | + raise ValueError("Qualification parent must be canonical, without symlink components") |
| 88 | + agent_id = assert_released_binary(agent, AGENT_SHA256) |
| 89 | + grep_id = assert_released_binary(grep, GREP_SHA256) |
| 90 | + python = Path(shutil.which("python3") or "").resolve(strict=True) |
| 91 | + if not python.is_file(): |
| 92 | + raise ValueError("python3 is unavailable") |
| 93 | + root.mkdir(mode=0o700) |
| 94 | + project, output = root / "project", root / "outputs" |
| 95 | + settings, memory = root / "settings", root / "memory" |
| 96 | + for path in (project, output, settings, memory, project / ".terraphim", |
| 97 | + project / "outputs", settings / "data", settings / "dashmap"): |
| 98 | + path.mkdir(mode=0o700) |
| 99 | + (project / "brief.md").write_bytes(BRIEF) |
| 100 | + (project / "validate_brief.py").write_text(VALIDATOR, encoding="utf-8") |
| 101 | + settings_file = settings / "settings.toml" |
| 102 | + settings_file.write_text( |
| 103 | + 'server_hostname = "127.0.0.1:8000"\n' |
| 104 | + 'api_endpoint = "http://localhost:8000/api"\ninitialized = "true"\n' |
| 105 | + f'default_data_path = {json.dumps(str(settings / "data"))}\n' |
| 106 | + '[profiles.dashmap]\ntype = "dashmap"\n' |
| 107 | + f'root = {json.dumps(str(settings / "dashmap"))}\n', encoding="utf-8") |
| 108 | + settings_file.chmod(0o600) |
| 109 | + inputs = [file_identity(p) for p in (project / "brief.md", project / "validate_brief.py", settings_file)] |
| 110 | + # Inherit original identity values unchanged; admit no provider/storage overrides. |
| 111 | + env = {k: os.environ[k] for k in ("HOME", "USER", "LOGNAME", "LANG") if k in os.environ} |
| 112 | + env.update({"PATH": str(python.parent) + ":/usr/bin:/bin:/usr/sbin:/sbin", |
| 113 | + "TERRAPHIM_SETTINGS_PATH": str(settings)}) |
| 114 | + receipt = { |
| 115 | + "status": "RUNNING", "startedAt": datetime.now(timezone.utc).isoformat(), |
| 116 | + "scope": "Fresh released CLI component execution; not native Cursor or hook activation", |
| 117 | + "requirements": ["C-05/CUR-05"], "host": platform.platform(), |
| 118 | + "root": str(root), "binaryInputs": {"agent": agent_id, "grep": grep_id}, |
| 119 | + "python": file_identity(python), "inputs": inputs, "commands": [], |
| 120 | + "storage": {"settingsDirectory": str(settings), "backend": "dashmap", |
| 121 | + "memoryDataOverride": str(memory), "learningProject": str(project / ".terraphim"), |
| 122 | + "homeAndCodexHomeModified": False, |
| 123 | + "inheritedEnvironmentNames": sorted(k for k in env if k != "TERRAPHIM_SETTINGS_PATH"), |
| 124 | + "memoryOverrideUsedOnlyForMemoryCommands": True}, |
| 125 | + "privacy": "Only public fixture argv/status and explicitly selected CLI/learning/output files; no environment values or general diagnostic logs", |
| 126 | + } |
| 127 | + |
| 128 | + def run(name, argv, *, memory_mode=False, selected_stdout=None, expected=0): |
| 129 | + child_env = dict(env) |
| 130 | + if memory_mode: |
| 131 | + child_env["TERRAPHIM_DEFAULT_DATA_PATH"] = str(memory) |
| 132 | + row = {"name": name, "argv": [str(x) for x in argv], "cwd": str(project), |
| 133 | + "startedAt": datetime.now(timezone.utc).isoformat(), "memoryOverride": memory_mode} |
| 134 | + receipt["commands"].append(row) |
| 135 | + started = time.monotonic() |
| 136 | + try: |
| 137 | + result = subprocess.run(row["argv"], cwd=project, env=child_env, |
| 138 | + capture_output=True, timeout=45, check=False) |
| 139 | + except subprocess.TimeoutExpired as exc: |
| 140 | + row.update({"status": "TIMEOUT", "elapsedSeconds": time.monotonic() - started, |
| 141 | + "stdoutSha256": digest(exc.stdout or b""), "stderrSha256": digest(exc.stderr or b"")}) |
| 142 | + raise AssertionError(f"{name} exceeded 45-second qualification limit") from exc |
| 143 | + row.update({"exitCode": result.returncode, "elapsedSeconds": time.monotonic() - started, |
| 144 | + "stdoutBytes": len(result.stdout), "stdoutSha256": digest(result.stdout), |
| 145 | + "stderrBytes": len(result.stderr), "stderrSha256": digest(result.stderr)}) |
| 146 | + if selected_stdout: |
| 147 | + selected = output / selected_stdout |
| 148 | + selected.write_bytes(result.stdout) |
| 149 | + row["selectedOutput"] = file_identity(selected) |
| 150 | + if result.returncode != expected: |
| 151 | + raise AssertionError(f"{name}: expected exit {expected}, observed {result.returncode}; diagnostics digests retained") |
| 152 | + return result |
| 153 | + |
| 154 | + def agent_run(name, args, **kwargs): |
| 155 | + return run(name, [agent, *args], **kwargs) |
| 156 | + |
| 157 | + def reported_path(data, prefix): |
| 158 | + matches = [line[len(prefix):] for line in data.decode("utf-8").splitlines() if line.startswith(prefix)] |
| 159 | + assert len(matches) == 1, "Expected one actual CLI-created file path" |
| 160 | + path = Path(matches[0]) |
| 161 | + assert path.resolve().is_relative_to(project / ".terraphim"), "Learning escaped explicit project" |
| 162 | + assert path.is_file() and not path.is_symlink() |
| 163 | + return path |
| 164 | + |
| 165 | + try: |
| 166 | + assert agent_run("agent-version", ["--version"], selected_stdout="agent-version.txt").stdout.strip() == b"terraphim-agent 1.21.20" |
| 167 | + assert run("grep-version", [grep, "--version"], selected_stdout="grep-version.txt").stdout.strip() == b"terraphim-grep 1.21.20" |
| 168 | + baseline = json.loads(agent_run("memory-baseline", ["--format", "json", "memory", "list"], |
| 169 | + memory_mode=True, selected_stdout="memory-baseline.json").stdout) |
| 170 | + assert baseline["status"] == "ok" and baseline["count"] == 0 and baseline["items"] == [] |
| 171 | + captured = json.loads(agent_run("memory-capture", ["--format", "json", "memory", "capture", |
| 172 | + "--content", CONTENT, "--provenance-tag", TAG], memory_mode=True, |
| 173 | + selected_stdout="captured-memory.json").stdout) |
| 174 | + assert captured["status"] == "ok" |
| 175 | + memory_id = captured["memory_id"] |
| 176 | + shown = json.loads(agent_run("memory-show-new-process", ["memory", "show", memory_id, "--json"], |
| 177 | + memory_mode=True, selected_stdout="saved-memory.json").stdout) |
| 178 | + assert shown["status"] == "ok" and shown["id"] == memory_id |
| 179 | + assert shown["memory_item"]["id"] == memory_id and shown["memory_item"]["content"] == CONTENT |
| 180 | + assert shown["memory_item"]["tags"] == ["provenance:" + TAG] |
| 181 | + store = memory / "terraphim/evolution/cli-agent.json" |
| 182 | + json.loads(store.read_text()) |
| 183 | + assert memory_id in store.read_text() and CONTENT in store.read_text() |
| 184 | + assert not (project / ".terraphim/learnings").exists() |
| 185 | + |
| 186 | + actual_failure = run("actual-validator-failure", ["/bin/sh", "-c", original], expected=2) |
| 187 | + assert b"--check" in actual_failure.stderr and b"required" in actual_failure.stderr |
| 188 | + assert not (project / "outputs" / output_name).exists() |
| 189 | + capture = agent_run("learn-capture", ["learn", "capture", "--error", actual_failure.stderr.decode("utf-8"), |
| 190 | + "--exit-code", str(actual_failure.returncode), original], selected_stdout="learning-path.txt") |
| 191 | + learning = reported_path(capture.stdout, "Captured learning: ") |
| 192 | + before = learning.read_bytes() |
| 193 | + (output / "learning-before-annotation.md").write_bytes(before) |
| 194 | + assert original in before.decode() and "source: Project" in before.decode() and "exit_code: 2" in before.decode() |
| 195 | + learning_id = re.search(r"^id: ([^\n]+)$", before.decode(), re.M).group(1) |
| 196 | + query = agent_run("learn-query", ["learn", "query", original, "--exact"], selected_stdout="learning-query.txt") |
| 197 | + assert b"[P] [cmd]" in query.stdout and original.encode() in query.stdout and b"(exit: 2)" in query.stdout |
| 198 | + assert re.search(r"^id: ([^\n]+)$", learning.read_text(), re.M).group(1) == learning_id |
| 199 | + agent_run("annotate-failure", ["learn", "correct", learning_id, "--correction", corrected]) |
| 200 | + annotated = learning.read_bytes() |
| 201 | + (output / "learning-after-annotation.md").write_bytes(annotated) |
| 202 | + assert corrected in annotated.decode() and before != annotated |
| 203 | + before_compiled = output / "compiled-before-rule.json" |
| 204 | + agent_run("compile-annotation-only", ["learn", "compile", "--output", before_compiled]) |
| 205 | + assert json.loads(before_compiled.read_text())["data"] == {} |
| 206 | + rule_result = agent_run("add-explicit-reviewed-rule", ["learn", "correction", "add", "--original", original, |
| 207 | + "--corrected", corrected, "--correction-type", "tool-preference", "--context", |
| 208 | + "Reviewed public validator fixture: the required option is --check; keep the chosen output path unchanged."], |
| 209 | + selected_stdout="correction-path.txt") |
| 210 | + rule = reported_path(rule_result.stdout, "Captured correction: ") |
| 211 | + assert original in rule.read_text() and corrected in rule.read_text() |
| 212 | + after_compiled = output / "compiled-reviewed-corrections.json" |
| 213 | + agent_run("compile-reviewed-rule", ["learn", "compile", "--output", after_compiled]) |
| 214 | + mappings = json.loads(after_compiled.read_text())["data"] |
| 215 | + assert len(mappings) == 1 and original in mappings |
| 216 | + exact_replacement = mappings[original]["display_value"] |
| 217 | + assert exact_replacement == corrected |
| 218 | + kg = output / "reviewed-kg" |
| 219 | + agent_run("export-reviewed-kg", ["learn", "export-kg", "--output", kg]) |
| 220 | + notes = sorted(kg.glob("*.md")) |
| 221 | + assert len(notes) == 1 |
| 222 | + note = notes[0].read_text() |
| 223 | + assert "synonyms:: " + original in note and corrected in note |
| 224 | + run("execute-exact-compiled-replacement", ["/bin/sh", "-c", exact_replacement]) |
| 225 | + actual_file = project / "outputs" / output_name |
| 226 | + actual = json.loads(actual_file.read_text()) |
| 227 | + assert actual == {"source": "brief.md", "sha256": digest(BRIEF), "bytes": len(BRIEF), |
| 228 | + "riskOccurrences": 1, "decisionOccurrences": 1} |
| 229 | + assert (project / "brief.md").read_bytes() == BRIEF |
| 230 | + assert settings_file.read_bytes() and file_identity(settings_file) == inputs[2] |
| 231 | + assert assert_released_binary(agent, AGENT_SHA256) == agent_id |
| 232 | + assert assert_released_binary(grep, GREP_SHA256) == grep_id |
| 233 | + receipt.update({"status": "PASS", "memoryId": memory_id, "memoryContent": CONTENT, |
| 234 | + "memoryTag": "provenance:" + TAG, "actualMemoryStore": file_identity(store), |
| 235 | + "learningId": learning_id, "actualLearningPath": str(learning), "actualCorrectionPath": str(rule), |
| 236 | + "annotationOnlyCompiledCount": 0, "explicitRuleCompiledCount": len(mappings), |
| 237 | + "originalCommand": original, "exactCompiledExecutedReplacement": exact_replacement, |
| 238 | + "failureExit": actual_failure.returncode, "validatorOutput": actual, |
| 239 | + "activation": False, "nativeCursor": "NOT_RUN"}) |
| 240 | + except Exception as exc: |
| 241 | + receipt.update({"status": "FAIL", "failureType": type(exc).__name__, "failure": str(exc)}) |
| 242 | + raise |
| 243 | + finally: |
| 244 | + receipt["finishedAt"] = datetime.now(timezone.utc).isoformat() |
| 245 | + receipt["files"] = [file_identity(p) for p in sorted(root.rglob("*")) if p.is_file()] |
| 246 | + receipt["harness"] = file_identity(Path(__file__).resolve()) |
| 247 | + write_json(root / "receipt.json", receipt) |
| 248 | + return receipt |
| 249 | + |
| 250 | + |
| 251 | +def main(): |
| 252 | + parser = argparse.ArgumentParser(description=__doc__) |
| 253 | + parser.add_argument("--root", required=True, type=Path) |
| 254 | + parser.add_argument("--agent", required=True, type=Path) |
| 255 | + parser.add_argument("--grep", required=True, type=Path) |
| 256 | + parser.add_argument("--output-name", default="native-rewrite.json") |
| 257 | + args = parser.parse_args() |
| 258 | + result = qualify(args.root, args.agent, args.grep, args.output_name) |
| 259 | + print(json.dumps({"status": result["status"], "receipt": str(args.root / "receipt.json"), |
| 260 | + "commands": len(result["commands"]), "nativeCursor": "NOT_RUN"})) |
| 261 | + |
| 262 | + |
| 263 | +if __name__ == "__main__": |
| 264 | + main() |
0 commit comments