@christang/keel 5.84.0 → 5.86.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.
Files changed (37) hide show
  1. package/README.md +49 -5
  2. package/README.zh-CN.md +34 -0
  3. package/assets/bootstrap/AGENTS.md +2 -2
  4. package/assets/openspec/schemas/keel-spec-driven/schema.yaml +3 -3
  5. package/assets/openspec/schemas/keel-spec-driven/templates/tasks.md +3 -3
  6. package/bin/keel.js +60 -7
  7. package/npm-shrinkwrap.json +2 -2
  8. package/package.json +1 -1
  9. package/plugins/keel/.claude-plugin/plugin.json +1 -1
  10. package/plugins/keel/.codex-plugin/plugin.json +2 -1
  11. package/plugins/keel/agents/keel-single-task-goal-claude.md +1 -1
  12. package/plugins/keel/agents/keel-single-task-goal-codex.md +1 -1
  13. package/plugins/keel/hooks/codex.json +44 -0
  14. package/plugins/keel/scripts/codex-mail-hook.js +75 -0
  15. package/plugins/keel/scripts/mail-hook.js +11 -9
  16. package/plugins/keel/skills/keel-run-single-task-goal/SKILL.md +2 -2
  17. package/plugins/keel/skills/keel-run-single-task-goal/guidance.md +1 -1
  18. package/scripts/fake_slack.py +277 -0
  19. package/scripts/validate_codex_receiving.py +296 -0
  20. package/scripts/validate_plugin.py +1922 -227
  21. package/src/core/capabilities.js +2 -2
  22. package/src/core/chat/archive.js +234 -0
  23. package/src/core/chat/bridge.js +808 -0
  24. package/src/core/chat/cli.js +465 -0
  25. package/src/core/chat/config.js +64 -0
  26. package/src/core/chat/guards.js +96 -0
  27. package/src/core/chat/lifecycle.js +214 -0
  28. package/src/core/chat/migrate.js +142 -0
  29. package/src/core/chat/notice.js +216 -0
  30. package/src/core/chat/redact.js +37 -0
  31. package/src/core/chat/slack.js +104 -0
  32. package/src/core/chat/store.js +776 -0
  33. package/src/core/chat/view.js +169 -0
  34. package/src/core/config.js +36 -10
  35. package/src/core/mail.js +123 -433
  36. package/src/core/projection.js +43 -24
  37. package/src/core/task-contract.js +3 -3
@@ -23,7 +23,7 @@ in the transcript, `keel gate task-complete`, check the box. What changes is who
23
23
  ## Per-target activation notes
24
24
 
25
25
  - **Codex**: where a callable goal or subagent surface exists, activate one bounded goal for the
26
- selected task and use subagents only as bounded read-only helpers. Without a callable surface, paste
26
+ selected task; choose helpers or guarded implementation delegates under the task contract and host policy. Without a callable surface, paste
27
27
  the exact `keel project goal` command and treat the capability as advisory.
28
28
  - **Claude**: activate one `/goal` whose condition fits the 4,000-character budget. The evaluator sees
29
29
  the transcript only, so command and gate evidence has to appear there explicitly. If hooks are
@@ -0,0 +1,277 @@
1
+ """A local stand-in for the Slack Web API and Socket Mode, for Keel's tests.
2
+
3
+ Issue #187: `keel chat bridge` talks to Slack. Its validation scenarios run
4
+ against this server instead, so they need no workspace, no token, and no
5
+ network — the mock sits at the system boundary, and Keel's own modules run
6
+ for real. It models only what the bridge uses, with the shapes Slack's public
7
+ documentation gives (design A2): a real run is the evidence that Slack agrees.
8
+
9
+ Web API: `POST /api/<method>` with a JSON or form body answers `ok: true` and
10
+ records the call. `chat.postMessage` assigns increasing `ts` values and keeps
11
+ the message, with its metadata, for `conversations.history`.
12
+ `apps.connections.open` returns a `ws://` URL served by the same process.
13
+
14
+ Socket Mode: the server speaks just enough RFC 6455 to push envelopes to a
15
+ connected client and collect its acknowledgements.
16
+
17
+ Tests drive the server through methods on `FakeSlack`, not over HTTP.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hashlib
24
+ import json
25
+ import socket
26
+ import struct
27
+ import threading
28
+ import time
29
+ import urllib.parse
30
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
31
+
32
+ WS_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
33
+
34
+
35
+ def ws_frame(text: str) -> bytes:
36
+ data = text.encode("utf-8")
37
+ header = bytearray([0x81])
38
+ if len(data) < 126:
39
+ header.append(len(data))
40
+ elif len(data) < 65536:
41
+ header.append(126)
42
+ header += struct.pack(">H", len(data))
43
+ else:
44
+ header.append(127)
45
+ header += struct.pack(">Q", len(data))
46
+ return bytes(header) + data
47
+
48
+
49
+ class FakeSlack:
50
+ def __init__(self) -> None:
51
+ self.calls: list[dict] = []
52
+ self.messages: dict[str, list[dict]] = {}
53
+ self.rate_limit_next: list[tuple[str, int]] = []
54
+ self.lock = threading.Lock()
55
+ # Later than any `ts` a test writes by hand, so what this server assigns
56
+ # always sorts after the events a test pushed itself.
57
+ self.next_ts = 1_900_000_000
58
+ self.sockets: list[socket.socket] = []
59
+ self.acks: list[str] = []
60
+ self.connections_opened = 0
61
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
62
+ self.port = self.server.server_address[1]
63
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
64
+
65
+ # --- lifecycle -----------------------------------------------------------
66
+
67
+ def __enter__(self) -> "FakeSlack":
68
+ self.thread.start()
69
+ return self
70
+
71
+ def __exit__(self, *exc: object) -> None:
72
+ self.drop_connections()
73
+ self.server.shutdown()
74
+ self.server.server_close()
75
+
76
+ @property
77
+ def api_base(self) -> str:
78
+ return f"http://127.0.0.1:{self.port}/api"
79
+
80
+ # --- test controls -------------------------------------------------------
81
+
82
+ def rate_limit(self, method: str, retry_after: int) -> None:
83
+ """Answer the next call of `method` with HTTP 429 and Retry-After."""
84
+ with self.lock:
85
+ self.rate_limit_next.append((method, retry_after))
86
+
87
+ def calls_to(self, method: str) -> list[dict]:
88
+ with self.lock:
89
+ return [call for call in self.calls if call["method"] == method and not call.get("rate_limited")]
90
+
91
+ def add_history(self, channel: str, message: dict) -> dict:
92
+ """A message Slack holds that the bridge has not been told about."""
93
+ with self.lock:
94
+ stored = {"ts": self._ts(), "type": "message", **message}
95
+ self.messages.setdefault(channel, []).append(stored)
96
+ return stored
97
+
98
+ def push(self, payload: dict, kind: str = "events_api") -> str:
99
+ """Send one Socket Mode envelope to every connected client."""
100
+ with self.lock:
101
+ envelope_id = f"env-{self._ts()}"
102
+ self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}))
103
+ return envelope_id
104
+
105
+ def push_raw(self, message: dict) -> None:
106
+ self._broadcast(json.dumps(message))
107
+
108
+ def drop_connections(self) -> None:
109
+ for sock in list(self.sockets):
110
+ try:
111
+ sock.shutdown(socket.SHUT_RDWR)
112
+ except OSError:
113
+ pass
114
+ try:
115
+ sock.close()
116
+ except OSError:
117
+ pass
118
+ self.sockets.clear()
119
+
120
+ @staticmethod
121
+ def wait_for(predicate, timeout: float = 10.0) -> bool:
122
+ deadline = time.time() + timeout
123
+ while time.time() < deadline:
124
+ if predicate():
125
+ return True
126
+ time.sleep(0.05)
127
+ return bool(predicate())
128
+
129
+ # --- internals -----------------------------------------------------------
130
+
131
+ def _ts(self) -> str:
132
+ self.next_ts += 1
133
+ return f"{self.next_ts}.000100"
134
+
135
+ def _broadcast(self, text: str) -> None:
136
+ frame = ws_frame(text)
137
+ for sock in list(self.sockets):
138
+ try:
139
+ sock.sendall(frame)
140
+ except OSError:
141
+ pass
142
+
143
+ def _answer(self, method: str, params: dict) -> tuple[int, dict, dict]:
144
+ with self.lock:
145
+ for index, (limited, retry_after) in enumerate(self.rate_limit_next):
146
+ if limited == method:
147
+ del self.rate_limit_next[index]
148
+ self.calls.append({"method": method, "params": params, "rate_limited": True, "at": time.time()})
149
+ return 429, {"Retry-After": str(retry_after)}, {"ok": False, "error": "ratelimited"}
150
+ self.calls.append({"method": method, "params": params, "at": time.time()})
151
+ if method == "auth.test":
152
+ return 200, {}, {"ok": True, "user_id": "UBOT", "bot_id": "BBOT", "team_id": "T1"}
153
+ if method == "apps.connections.open":
154
+ self.connections_opened += 1
155
+ return 200, {}, {"ok": True, "url": f"ws://127.0.0.1:{self.port}/socket"}
156
+ if method == "chat.postMessage":
157
+ metadata = params.get("metadata")
158
+ if isinstance(metadata, str):
159
+ metadata = json.loads(metadata)
160
+ message = {
161
+ "ts": self._ts(),
162
+ "type": "message",
163
+ "text": params.get("text", ""),
164
+ "username": params.get("username"),
165
+ "bot_id": "BBOT",
166
+ "metadata": metadata,
167
+ }
168
+ if params.get("thread_ts"):
169
+ message["thread_ts"] = params["thread_ts"]
170
+ self.messages.setdefault(params.get("channel", ""), []).append(message)
171
+ return 200, {}, {"ok": True, "channel": params.get("channel"), "ts": message["ts"], "message": message}
172
+ if method in ("conversations.history", "conversations.replies"):
173
+ channel = params.get("channel", "")
174
+ oldest = float(params.get("oldest") or 0)
175
+ found = [m for m in self.messages.get(channel, []) if float(m["ts"]) > oldest]
176
+ if method == "conversations.replies":
177
+ root = params.get("ts")
178
+ found = [m for m in self.messages.get(channel, []) if m.get("thread_ts") == root or m["ts"] == root]
179
+ if params.get("latest"):
180
+ latest = float(params["latest"])
181
+ inclusive = str(params.get("inclusive", "")).lower() in ("1", "true")
182
+ found = [m for m in found if float(m["ts"]) < latest or (inclusive and float(m["ts"]) == latest)]
183
+ include = str(params.get("include_all_metadata", "")).lower() in ("1", "true")
184
+ shown = [m if include else {k: v for k, v in m.items() if k != "metadata"} for m in found]
185
+ return 200, {}, {"ok": True, "messages": list(reversed(shown)), "has_more": False}
186
+ return 200, {}, {"ok": True}
187
+
188
+ def _handler(self):
189
+ fake = self
190
+
191
+ class Handler(BaseHTTPRequestHandler):
192
+ protocol_version = "HTTP/1.1"
193
+
194
+ def log_message(self, *args: object) -> None:
195
+ return
196
+
197
+ def do_GET(self) -> None: # noqa: N802 - http.server API
198
+ if self.path.startswith("/socket"):
199
+ self._upgrade()
200
+ return
201
+ query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
202
+ self._api({k: v[0] for k, v in query.items()})
203
+
204
+ def do_POST(self) -> None: # noqa: N802 - http.server API
205
+ length = int(self.headers.get("Content-Length") or 0)
206
+ raw = self.rfile.read(length).decode("utf-8")
207
+ if "json" in (self.headers.get("Content-Type") or ""):
208
+ params = json.loads(raw or "{}")
209
+ else:
210
+ params = {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()}
211
+ self._api(params)
212
+
213
+ def _api(self, params: dict) -> None:
214
+ method = urllib.parse.urlparse(self.path).path.rsplit("/", 1)[-1]
215
+ params["_auth"] = self.headers.get("Authorization", "")
216
+ status, headers, body = fake._answer(method, params)
217
+ data = json.dumps(body).encode("utf-8")
218
+ self.send_response(status)
219
+ self.send_header("Content-Type", "application/json")
220
+ self.send_header("Content-Length", str(len(data)))
221
+ for key, value in headers.items():
222
+ self.send_header(key, value)
223
+ self.end_headers()
224
+ self.wfile.write(data)
225
+
226
+ def _upgrade(self) -> None:
227
+ key = self.headers.get("Sec-WebSocket-Key", "")
228
+ accept = base64.b64encode(hashlib.sha1((key + WS_MAGIC).encode()).digest()).decode()
229
+ self.send_response(101, "Switching Protocols")
230
+ self.send_header("Upgrade", "websocket")
231
+ self.send_header("Connection", "Upgrade")
232
+ self.send_header("Sec-WebSocket-Accept", accept)
233
+ self.end_headers()
234
+ self.wfile.flush()
235
+ sock = self.connection
236
+ try:
237
+ sock.sendall(ws_frame(json.dumps({"type": "hello", "num_connections": len(fake.sockets) + 1})))
238
+ except OSError:
239
+ return
240
+ fake.sockets.append(sock)
241
+ self.close_connection = True
242
+ self._read_frames(sock)
243
+
244
+ def _read_frames(self, sock: socket.socket) -> None:
245
+ stream = self.rfile
246
+ while True:
247
+ try:
248
+ head = stream.read(2)
249
+ if not head or len(head) < 2:
250
+ break
251
+ opcode = head[0] & 0x0F
252
+ length = head[1] & 0x7F
253
+ if length == 126:
254
+ length = struct.unpack(">H", stream.read(2))[0]
255
+ elif length == 127:
256
+ length = struct.unpack(">Q", stream.read(8))[0]
257
+ mask = stream.read(4) if head[1] & 0x80 else b"\0\0\0\0"
258
+ data = bytearray(stream.read(length))
259
+ except (OSError, ValueError, struct.error):
260
+ break
261
+ for index in range(len(data)):
262
+ data[index] ^= mask[index % 4]
263
+ if opcode == 0x8:
264
+ break
265
+ if opcode != 0x1:
266
+ continue
267
+ try:
268
+ message = json.loads(data.decode("utf-8"))
269
+ except (UnicodeDecodeError, json.JSONDecodeError):
270
+ continue
271
+ if isinstance(message, dict) and message.get("envelope_id"):
272
+ with fake.lock:
273
+ fake.acks.append(message["envelope_id"])
274
+ if sock in fake.sockets:
275
+ fake.sockets.remove(sock)
276
+
277
+ return Handler
@@ -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()