@christang/keel 5.83.0 → 5.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env python3
2
+ """Public-interface checks for Codex hooks; native tests are opt-in."""
3
+ import argparse
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import selectors
8
+ import shlex
9
+ import shutil
10
+ import subprocess
11
+ import tempfile
12
+ import threading
13
+ import time
14
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ PLUGIN = ROOT / "plugins/keel"
18
+ CLI = ROOT / "bin/keel.js"
19
+ RECEIVER = PLUGIN / "scripts/codex-mail-hook.js"
20
+
21
+
22
+ def run(args, cwd=ROOT, env=None, input=None, check=True, timeout=30):
23
+ result = subprocess.run(args, cwd=cwd, env=env, input=input, text=True,
24
+ capture_output=True, timeout=timeout)
25
+ if check and result.returncode:
26
+ raise AssertionError(f"{args}: exit {result.returncode}\n{result.stdout}{result.stderr}")
27
+ return result
28
+
29
+
30
+ def mail(repo, *args, role="receiver"):
31
+ env = dict(os.environ, KEEL_MAIL_ROLE=role)
32
+ return run(["node", str(CLI), "mail", *args], cwd=repo, env=env)
33
+
34
+
35
+ def inbox(repo):
36
+ return {str(p.relative_to(repo)): p.read_bytes()
37
+ for p in (repo / ".git/keel-mailbox").rglob("*") if p.is_file()}
38
+
39
+
40
+ def invoke(repo, event, provider=None, timeout_ms=None):
41
+ env = dict(os.environ, KEEL_MAIL_ROLE="receiver",
42
+ KEEL_CLI=provider or shlex.join(["node", str(CLI)]))
43
+ if timeout_ms:
44
+ env["KEEL_HOOK_TIMEOUT_MS"] = str(timeout_ms)
45
+ result = run(["node", str(RECEIVER), event], cwd=repo, env=env,
46
+ input=json.dumps({"cwd": str(repo), "hook_event_name": event}))
47
+ assert not result.stderr, result.stderr
48
+ return json.loads(result.stdout) if result.stdout.strip() else None
49
+
50
+
51
+ def behavior():
52
+ manifest = json.loads((PLUGIN / ".codex-plugin/plugin.json").read_text())
53
+ assert manifest.get("hooks") == "./hooks/codex.json", "Codex still uses the args-only shared hooks"
54
+ hooks = json.loads((PLUGIN / "hooks/codex.json").read_text())["hooks"]
55
+ assert set(hooks) == {"SessionStart", "PreToolUse", "UserPromptSubmit"}
56
+ assert not any(field in json.dumps(hooks) for field in ["asyncRewake", "watchPaths", "FileChanged"])
57
+ commands = [h["command"] for groups in hooks.values() for g in groups for h in g["hooks"]]
58
+ for script in ["session-start.js", "pretooluse-guard.js", "codex-mail-hook.js"]:
59
+ assert any(script in command for command in commands), script
60
+ with tempfile.TemporaryDirectory(prefix="keel-codex-mail-") as raw:
61
+ repo = Path(raw)
62
+ run(["git", "init", "-q", str(repo)])
63
+ assert invoke(repo, "session-start") is None
64
+ assert invoke(repo, "user-prompt-submit") is None
65
+ sent = json.loads(mail(repo, "send", "--to", "receiver", "--subject", "delivery probe",
66
+ "--body", "PRIVATE_BODY_NOT_CONTEXT", "--json", role="sender").stdout)
67
+ before = inbox(repo)
68
+ for event, native in [("session-start", "SessionStart"),
69
+ ("user-prompt-submit", "UserPromptSubmit"),
70
+ ("user-prompt-submit", "UserPromptSubmit")]:
71
+ output = invoke(repo, event)
72
+ assert set(output) == {"hookSpecificOutput"}
73
+ specific = output["hookSpecificOutput"]
74
+ assert set(specific) == {"hookEventName", "additionalContext"}
75
+ assert specific["hookEventName"] == native
76
+ text = specific["additionalContext"]
77
+ for expected in [sent["id"], "sender", "delivery probe", "keel mail read", "not", "authorization"]:
78
+ assert expected in text, (expected, text)
79
+ assert "PRIVATE_BODY_NOT_CONTEXT" not in text
80
+ assert inbox(repo) == before, "notice consumed or changed mail"
81
+ mail(repo, "read", "--id", sent["id"])
82
+ assert invoke(repo, "user-prompt-submit") is None
83
+ unbound = dict(os.environ)
84
+ unbound.pop("KEEL_MAIL_ROLE", None)
85
+ unbound["KEEL_CLI"] = shlex.join(["node", str(CLI)])
86
+ assert not run(["node", str(RECEIVER), "session-start"], cwd=repo,
87
+ env=unbound, input=json.dumps({"cwd": str(repo)})).stdout.strip()
88
+ for name, source in [
89
+ ("exit", "process.exit(1)"),
90
+ ("invalid", "process.stdout.write('not JSON')"),
91
+ ("wrong-shape", "process.stdout.write(JSON.stringify({decision:'block'}))"),
92
+ ("timeout", "setTimeout(()=>{},2000)"),
93
+ ("blocked", "process.exit(2)"),
94
+ ]:
95
+ boundary = repo / f"{name}.js"
96
+ boundary.write_text(source)
97
+ output = invoke(repo, "user-prompt-submit", shlex.join(["node", str(boundary)]), 50)
98
+ assert set(output) == {"systemMessage"}, output
99
+ assert "keel mail list" in output["systemMessage"]
100
+ print("codex-receiving: startup/next-input, repeated non-consuming notices, quiet inboxes and failure fallback passed")
101
+
102
+
103
+ def hooks_list(repo, env):
104
+ """Ask the real app-server to discover hooks; no turn or model is started."""
105
+ process = subprocess.Popen(["codex", "app-server", "--stdio"], cwd=repo, env=env,
106
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
107
+ stderr=subprocess.DEVNULL, text=True, bufsize=1)
108
+ selector = selectors.DefaultSelector()
109
+ selector.register(process.stdout, selectors.EVENT_READ)
110
+ def rpc(number, method, params):
111
+ process.stdin.write(json.dumps({"id": number, "method": method, "params": params}) + "\n")
112
+ process.stdin.flush()
113
+ deadline = time.monotonic() + 20
114
+ while time.monotonic() < deadline:
115
+ if selector.select(1):
116
+ line = process.stdout.readline()
117
+ if not line:
118
+ raise AssertionError("Codex app-server exited before hooks/list")
119
+ value = json.loads(line)
120
+ if value.get("id") == number:
121
+ assert "error" not in value, value
122
+ return value["result"]
123
+ raise AssertionError(f"Codex app-server timed out: {method}")
124
+ try:
125
+ rpc(1, "initialize", {"clientInfo": {"name": "keel-receiving-probe", "version": "1"},
126
+ "capabilities": {"experimentalApi": True}})
127
+ process.stdin.write('{"method":"initialized"}\n'); process.stdin.flush()
128
+ return rpc(2, "hooks/list", {"cwds": [str(repo)]})["data"][0]
129
+ finally:
130
+ selector.close()
131
+ process.terminate(); process.wait(timeout=5)
132
+
133
+
134
+ def native():
135
+ assert shutil.which("codex"), "native probe requires the Codex CLI"
136
+ requests = []
137
+ class Capture(BaseHTTPRequestHandler):
138
+ def do_POST(self):
139
+ requests.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
140
+ # Deliberately stop at the model boundary: no model or other agent
141
+ # runs, no tool is requested, and no remote inference is contacted.
142
+ body = b'{"error":{"message":"Keel probe captured the request; no model executes","type":"invalid_request_error"}}'
143
+ self.send_response(400); self.send_header("Content-Type", "application/json")
144
+ self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
145
+ def log_message(self, *args):
146
+ pass
147
+ with tempfile.TemporaryDirectory(prefix="keel-native-codex-") as raw:
148
+ base = Path(raw); repo = base / "consumer"; home = base / "codex-home"
149
+ repo.mkdir(); home.mkdir(); run(["git", "init", "-q", str(repo)])
150
+ shutil.copytree(PLUGIN, repo / "plugins/keel")
151
+ market = repo / ".agents/plugins/marketplace.json"
152
+ market.parent.mkdir(parents=True)
153
+ market.write_bytes((ROOT / ".agents/plugins/marketplace.json").read_bytes())
154
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Capture)
155
+ worker = threading.Thread(target=server.serve_forever, daemon=True); worker.start()
156
+ try:
157
+ config = f'''model = "keel-probe"
158
+ model_provider = "keel_probe"
159
+ [model_providers.keel_probe]
160
+ name = "Keel local request capture"
161
+ base_url = "http://127.0.0.1:{server.server_port}/v1"
162
+ wire_api = "responses"
163
+ requires_openai_auth = false
164
+ request_max_retries = 0
165
+ stream_max_retries = 0
166
+ [projects.{json.dumps(str(repo))}]
167
+ trust_level = "trusted"
168
+ '''
169
+ (home / "config.toml").write_text(config)
170
+ env = dict(os.environ, CODEX_HOME=str(home), KEEL_MAIL_ROLE="receiver",
171
+ KEEL_CLI=shlex.join(["node", str(CLI)]))
172
+ env.pop("OPENAI_API_KEY", None)
173
+ run(["node", str(CLI), "--init", "--target", "codex"], cwd=repo, env=env)
174
+ run(["codex", "plugin", "marketplace", "add", str(repo)], cwd=repo, env=env)
175
+ run(["codex", "plugin", "add", "keel@keel-marketplace"], cwd=repo, env=env)
176
+ found = hooks_list(repo, env)
177
+ assert not found["errors"], found
178
+ hooks = found["hooks"]
179
+ assert len(hooks) == 4, hooks
180
+ assert all(h["trustStatus"] == "untrusted" for h in hooks), hooks
181
+ assert all(".js" in h["command"] for h in hooks), hooks
182
+ assert {h["eventName"] for h in hooks} == {"preToolUse", "sessionStart", "userPromptSubmit"}
183
+ sent = json.loads(mail(repo, "send", "--to", "receiver", "--subject", "native-delivery-proof",
184
+ "--body", "BODY_MUST_STAY_LOCAL", "--json", role="sender").stdout)
185
+ before = inbox(repo)
186
+ command = ["codex", "exec", "--ephemeral", "--json", "--sandbox", "read-only",
187
+ "-C", str(repo), "Keel runtime probe: do not execute tools."]
188
+ untrusted = run(command, cwd=repo, env=env, check=False, timeout=40)
189
+ assert requests, f"No local model request: {untrusted.stderr}"
190
+ assert "native-delivery-proof" not in json.dumps(requests[-1]), "untrusted hook ran"
191
+ requests.clear()
192
+ # The only bypass is this isolated invocation, after reviewing the
193
+ # repository's hook sources. Never write personal persisted trust.
194
+ trusted = run(command[:2] + ["--dangerously-bypass-hook-trust"] + command[2:],
195
+ cwd=repo, env=env, check=False, timeout=40)
196
+ assert requests, f"No trusted local model request: {trusted.stderr}"
197
+ text = json.dumps(requests[-1])
198
+ for expected in [sent["id"], "native-delivery-proof", "keel mail read", "authorization",
199
+ "Keel session projection (disposable", "context status: idle"]:
200
+ assert expected in text, (expected, trusted.stdout, trusted.stderr)
201
+ assert text.count("native-delivery-proof") >= 2, "startup and prompt contexts were not both delivered"
202
+ assert "BODY_MUST_STAY_LOCAL" not in text
203
+ assert inbox(repo) == before, "native hook consumed mail"
204
+ assert all(h["trustStatus"] == "untrusted" for h in hooks_list(repo, env)["hooks"])
205
+ print(run(["codex", "--version"], cwd=repo, env=env).stdout.strip())
206
+ print("native: four executable hooks discovered; untrusted hooks skipped; disposable idle projection and startup/prompt notices reached the real Codex model request; inbox unchanged; no model executed or persisted trust granted")
207
+ finally:
208
+ server.shutdown(); server.server_close(); worker.join(timeout=5)
209
+
210
+
211
+ def consumer():
212
+ """The current test driver owns the full Keel flow; Codex is not a delegate."""
213
+ with tempfile.TemporaryDirectory(prefix="keel-codex-consumer-") as raw:
214
+ repo = Path(raw)
215
+ run(["git", "init", "-q", str(repo)])
216
+ env = dict(os.environ, CODEX_HOME=str(repo / "codex-home"))
217
+ def cli(*args):
218
+ return run(["node", str(CLI), *args], cwd=repo, env=env)
219
+ cli("--init", "--target", "codex")
220
+ doctor = cli("--doctor", "--target", "codex").stdout
221
+ assert "OpenSpec action skills: ok" in doctor, doctor
222
+ assert "OpenSpec commands: ok" in doctor, doctor
223
+ assert "overlay: ok" in doctor, doctor
224
+ assert "guard enforcement: manual" in doctor, doctor
225
+ name = "codex-acceptance-probe"
226
+ cli("openspec", "new", "change", name)
227
+ change = repo / "openspec/changes" / name
228
+ (change / "proposal.md").write_text("## Why\nPublic deterministic behavior proof in a clean Codex consumer.\n")
229
+ (change / "design.md").write_text("## Decisions\n- D1 — A public executable must print `hello keel`. Basis: disposable acceptance fixture.\n")
230
+ spec = change / "specs/greeting/spec.md"
231
+ spec.parent.mkdir(parents=True)
232
+ spec.write_text('''## ADDED Requirements
233
+ ### Requirement: Public greeting
234
+ The executable SHALL print exactly `hello keel`.
235
+ #### Scenario: Greeting runs
236
+ - **WHEN** `node hello.js` runs
237
+ - **THEN** stdout is exactly `hello keel` followed by one newline.
238
+ ''')
239
+ (change / "tasks.md").write_text('''## 1. Probe
240
+ - [ ] 1.1 Print the public greeting
241
+ - Covers:
242
+ - D1
243
+ - greeting / Public greeting
244
+ - Touch:
245
+ - hello.js
246
+ - Verify:
247
+ - Strategy: vertical-tdd
248
+ - M1: `node hello.js` prints exactly `hello keel`.
249
+ - Evidence:
250
+ - Contract: pending
251
+ ## Invalidates
252
+ - None.
253
+ ## Expectation Coverage
254
+ - E1: D1 and greeting / Public greeting are observed through node. Covered by: 1.1
255
+ ''')
256
+ started = json.loads(cli("gate", "task-start", ".", "--change", name, "--task", "1.1",
257
+ "--target", "codex", "--record", "--json").stdout)
258
+ assert started["status"] == "pass", started
259
+ assert not (repo / "keel/guard.json").exists(), "Codex claimed an automatic guard"
260
+ red = run(["node", "hello.js"], cwd=repo, check=False)
261
+ assert red.returncode != 0
262
+ (repo / "hello.js").write_text('console.log("hello keel");\n')
263
+ green = run(["node", "hello.js"], cwd=repo)
264
+ assert green.stdout == "hello keel\n"
265
+ tasks = (change / "tasks.md").read_text()
266
+ for key, value in {
267
+ "M1": "Exit 0, public node output exactly hello keel.",
268
+ "M1.red": "Exit 1, MODULE_NOT_FOUND before implementation.",
269
+ "M1.green": "Exit 0, public node output exactly hello keel.",
270
+ "Status": "pass", "Acceptance check": "Node executed the public greeting and output matched exactly.",
271
+ "Scope check": "Only hello.js was written as the product; task record lives in its own change.",
272
+ "Findings": "none",
273
+ }.items():
274
+ tasks = tasks.replace(f"- {key}: pending", f"- {key}: {value}")
275
+ (change / "tasks.md").write_text(tasks)
276
+ completed = json.loads(cli("gate", "task-complete", ".", "--change", name,
277
+ "--task", "1.1", "--json").stdout)
278
+ assert completed["status"] == "pass", completed
279
+ (change / "tasks.md").write_text(tasks.replace("- [ ]", "- [x]"))
280
+ closed = json.loads(cli("gate", "change-close", ".", "--change", name,
281
+ "--action", "archive", "--json").stdout)
282
+ assert closed["status"] == "pass", closed
283
+ print("consumer: clean Codex init/doctor, proposal, recorded task-start, public red/green behavior, Review, task-complete and change-close passed; guard enforcement remained manual")
284
+
285
+
286
+ if __name__ == "__main__":
287
+ parser = argparse.ArgumentParser()
288
+ parser.add_argument("--native", action="store_true")
289
+ parser.add_argument("--consumer", action="store_true")
290
+ args = parser.parse_args()
291
+ if args.native:
292
+ native()
293
+ elif args.consumer:
294
+ consumer()
295
+ else:
296
+ behavior()