YuyaoGe commited on
Commit
02390a3
·
verified ·
1 Parent(s): f4533f6

Add full evaluation code (GitHub 5411f53) and run instructions (part 2)

Browse files
code/src/stage1/smoke/perm_smoke.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic permission/safety smoke (mock-driven, no real-model budget).
2
+
3
+ Why: tested via real-model runs, safety behaviours (deny rules, read-only mode, permission-state
4
+ persistence) depend on whether the model ever attempts the forbidden command (different wording,
5
+ refusal, different tool). Then "the forbidden file is absent" proves nothing about the permission
6
+ layer -> false pass.
7
+
8
+ Here the mock gateway deterministically hands the agent the exact forbidden tool_call
9
+ (deny_cmd) plus a liveness command that should be allowed (allow_cmd). Interception happens in
10
+ the agent's own permission layer before tool execution, independent of the model, so the
11
+ outcome is deterministic: the forbidden action is either blocked (no file) or leaked (file
12
+ appears) = real bug.
13
+
14
+ Verdict anchors (commands self-adjudicate into file facts + request count; the subprocess
15
+ self-reports PERM_RESULT, so no ANSI parsing):
16
+ - deny_* : live.txt present (session really ran, deny did not over-block the allowed
17
+ command) and PERM_DENY_7755.txt absent (deny really blocked).
18
+ - readonly: target content unchanged and the mock saw >=2 requests (the turn really
19
+ processed the tool call).
20
+
21
+ Requires an interpreter with litellm. Usage: python perm_smoke.py <agent_dir> [--emit-json]
22
+ """
23
+
24
+ from __future__ import annotations
25
+ import json
26
+ import os
27
+ import signal
28
+ import shutil
29
+ import subprocess
30
+ import sys
31
+ import tempfile
32
+ import threading
33
+ import uuid
34
+ from pathlib import Path
35
+
36
+ HERE = Path(__file__).resolve().parent
37
+ sys.path.insert(0, str(HERE))
38
+ import mock_gateway as MG
39
+ import smoke_contract as SC
40
+
41
+ LIVE = "live.txt"
42
+ DENY = "PERM_DENY_7755.txt"
43
+ TGT = "tgt.txt"
44
+ ORIG = "ORIG_PERM_0001\n"
45
+ TGT2 = "tgt2.txt"
46
+ NEWDIR = "newdir_7755"
47
+ SEEDDIR = "seeddir_7755"
48
+ NEWNODE = "newnode_7755"
49
+ RESULT_TAG = "PERM_RESULT="
50
+
51
+
52
+
53
+
54
+ _BOOT = '''
55
+ import importlib as _il, inspect as _ins
56
+ _DISP_NAMES = ("handle_command","handle_slash_command","dispatch_command","run_command","do_command","slash_command","on_command","handle_input","dispatch_slash","slash","handle_slash","execute_slash","process_slash")
57
+ def _find_cls(mods, pred):
58
+ for _mn in mods:
59
+ try: _m = _il.import_module(_mn)
60
+ except Exception: continue
61
+ for _nm, _c in _ins.getmembers(_m, _ins.isclass):
62
+ try:
63
+ if not getattr(_c, "__module__", "").startswith("yuyao"): continue
64
+ if pred(_c): return _c
65
+ except Exception: pass
66
+ return None
67
+ _CfgCls = _find_cls(("yuyao.core.config","yuyao.config","yuyao.core.agent_config","yuyao.agent.config","yuyao.core.agent"),
68
+ lambda c: hasattr(c, "from_env"))
69
+ _TUICls = _find_cls(("yuyao.tui.main","yuyao.tui","yuyao.tui.app","yuyao.cli","yuyao.app","yuyao.core.tui","yuyao.interface","yuyao.main","yuyao.repl"),
70
+ lambda c: any(callable(getattr(c, _d, None)) for _d in _DISP_NAMES))
71
+ # Standard programmatic interface (spec section 0.1.2 / AGENT_CONTRACT section 7): prefer the
72
+ # fixed contract yuyao.agent_api.create_session. This is the root fix -- a conforming build no
73
+ # longer needs class-name / constructor-signature / turn-method guessing, which removes the
74
+ # reqs=0 driver blind spot that produces false negatives.
75
+ # If the module is absent, fall back to the adaptive bootstrap below (old artifacts still
76
+ # re-adjudicate identically, so there is no regression).
77
+ def _find_std():
78
+ for _mn in ("yuyao.agent_api","yuyao.d2a_api","yuyao.harness_api","agent_api"):
79
+ try: _m = _il.import_module(_mn)
80
+ except Exception: continue
81
+ _f = getattr(_m, "create_session", None)
82
+ if callable(_f): return _f
83
+ return None
84
+ _STD_FACTORY = _find_std()
85
+ assert _STD_FACTORY is not None or _TUICls is not None, "no standard yuyao.agent_api and no TUI class with a slash-dispatch method found"
86
+ def _mk_std(deny_rules=None, mode=None, role=None):
87
+ """Build a session via the standard contract; return None on failure (adaptive fallback)."""
88
+ if _STD_FACTORY is None: return None
89
+ _kw = {}
90
+ if deny_rules: _kw["deny"] = list(deny_rules)
91
+ if mode: _kw["mode"] = mode
92
+ if role: _kw["role"] = role
93
+ _s = None
94
+ for _try in (lambda: _STD_FACTORY(**_kw), lambda: _STD_FACTORY()):
95
+ try: _s = _try(); break
96
+ except Exception: _s = None
97
+ if _s is None: return None
98
+ try: _s._d2a_std = True
99
+ except Exception: pass
100
+ return _s
101
+ class _Args(object):
102
+ def __init__(self, **kw): self.__dict__.update(kw)
103
+ def __getattr__(self, n): return None
104
+ def _mk_tui(deny_rules=None):
105
+ _dr = list(deny_rules or [])
106
+ # Standard contract first: a conforming build yields a stable, drivable AgentSession
107
+ # (.dispatch / .chat / .cwd / .messages).
108
+ _std = _mk_std(deny_rules=_dr)
109
+ if _std is not None:
110
+ return _std
111
+ # model_config **dict** style (e.g. YuyaoTUI(model_config: dict, mode, role, ...)): assemble it
112
+ # from D2A_MODEL_*. Otherwise get_model(**self.model_config) inside chat() sees no
113
+ # model_name/api_base, the turn issues no request (reqs=0), and every case falsely fails.
114
+ _mcfg = {"model_name": os.environ.get("D2A_MODEL_NAME", ""),
115
+ "model_kwargs": {"api_base": os.environ.get("D2A_MODEL_BASE_URL", ""),
116
+ "api_key": os.environ.get("D2A_MODEL_API_KEY", "")}}
117
+ _cfg = None
118
+ if _CfgCls is not None:
119
+ for _ctor in (lambda: _CfgCls.from_env(), lambda: _CfgCls()):
120
+ try: _cfg = _ctor(); break
121
+ except Exception: _cfg = None
122
+ _args = _Args(mode=None, role=None, max_steps=20, stream="off", model=None,
123
+ deny=_dr, deny_rules=_dr, no_memory=False, repo_dir=None, cwd=None, yolo=False)
124
+ # Probe the constructor signature: if the first non-self parameter is a model_config/dict style
125
+ # name, pass the model_config dict first (no dependency on class name or module layout).
126
+ _pnames = []
127
+ try:
128
+ _pnames = [_p.name for _p in _ins.signature(_TUICls.__init__).parameters.values() if _p.name != "self"]
129
+ except Exception: pass
130
+ _first = _pnames[0] if _pnames else ""
131
+ _dict_first = _first in ("model_config", "model_cfg", "config_dict", "mcfg")
132
+ _att = []
133
+ if _dict_first or "model_config" in _pnames:
134
+ _att.append(((_mcfg,), {}))
135
+ _att.append(((), {"model_config": _mcfg}))
136
+ # Keyword-only constructor style (e.g. YuyaoTUI(*, model_name, api_base, api_key, deny_rules,
137
+ # ...)): feed D2A_MODEL_* plus deny_rules using only parameter names that actually exist in the
138
+ # signature. This is driving only and never touches assertions.
139
+ _sig_kw = {}
140
+ for _kn, _kv in (("model_name", os.environ.get("D2A_MODEL_NAME","")),
141
+ ("api_base", os.environ.get("D2A_MODEL_BASE_URL","")),
142
+ ("api_key", os.environ.get("D2A_MODEL_API_KEY",""))):
143
+ if _kn in _pnames:
144
+ _sig_kw[_kn] = _kv
145
+ if _sig_kw:
146
+ if _dr and "deny_rules" in _pnames:
147
+ _att.append(((), dict(_sig_kw, deny_rules=_dr)))
148
+ if _dr and "deny" in _pnames:
149
+ _att.append(((), dict(_sig_kw, deny=_dr)))
150
+ _att.append(((), dict(_sig_kw)))
151
+ # Scalar-first signature (e.g. YuyaoTUI(mode, role, max_steps, ...), model configured through the
152
+ # environment, no model_config/model_name parameter): construction MUST be keyword-only and must
153
+ # never pass _mcfg/_args positionally. Otherwise the dict/_Args lands on the `mode` parameter,
154
+ # self.mode becomes a dict, and {..}.get(self.mode) in get_system_prompt raises
155
+ # TypeError: unhashable type 'dict'. The turn then crashes before reaching the model, reqs=0, and
156
+ # every case for that build falsely fails -- a harness construction blind spot, not a build bug.
157
+ # Highest priority.
158
+ _scalar_first = _first in ("mode", "role", "max_steps", "stream", "model", "cwd",
159
+ "no_memory", "auto_commit", "verbose", "show_thinking")
160
+ if _scalar_first and "model_config" not in _pnames and not _sig_kw:
161
+ _safe = {}
162
+ if _dr and "deny" in _pnames: _safe["deny"] = _dr
163
+ if _dr and "deny_rules" in _pnames: _safe["deny_rules"] = _dr
164
+ _att.insert(0, ((), _safe))
165
+ if _cfg is not None:
166
+ _att.append(((_cfg,), {"deny_rules": _dr}))
167
+ _att.append(((_cfg,), {}))
168
+ _att.append(((_mcfg,), {})) # Fallback: dict style, retried if config-object construction failed
169
+ _att.append(((_args,), {}))
170
+ _att.append(((), {}))
171
+ _last = None
172
+ for _a, _k in _att:
173
+ try:
174
+ _t = _TUICls(*_a, **_k)
175
+ if _dr:
176
+ for _dn in ("deny_rules","deny"):
177
+ if not getattr(_t, _dn, None):
178
+ try: setattr(_t, _dn, _dr)
179
+ except Exception: pass
180
+ _ag = getattr(_t, "args", None)
181
+ if _ag is not None and not getattr(_ag, "deny", None):
182
+ try: _ag.deny = _dr
183
+ except Exception: pass
184
+ return _t
185
+ except Exception as _e:
186
+ _last = _e
187
+ raise _last
188
+ def _dispatch(tui, c):
189
+ if getattr(tui, "_d2a_std", False) and callable(getattr(tui, "dispatch", None)):
190
+ return tui.dispatch(c) # Standard contract: call AgentSession.dispatch directly
191
+ for _d in _DISP_NAMES:
192
+ _f = getattr(tui, _d, None)
193
+ if callable(_f): return _f(c)
194
+ raise RuntimeError("no slash dispatch method on TUI")
195
+ def _stream_off(tui):
196
+ # A standard-contract session is non-streaming by definition (create_session must return a
197
+ # non-interactive, non-streaming session), so no intervention is needed here.
198
+ if getattr(tui, "_d2a_std", False):
199
+ return
200
+ # Disable streaming: the streaming path can hang without a tty (waiting on SSE), and assertions
201
+ # only inspect on-disk facts, never rendering. Cover every place the flag may live: the TUI
202
+ # itself, tui.cfg, tui.config, the inner agent, and agent.cfg (some builds gate on self.cfg.stream).
203
+ _holders = [tui, getattr(tui, "cfg", None), getattr(tui, "config", None)]
204
+ _ag = getattr(tui, "agent", None) or getattr(tui, "_agent", None)
205
+ if _ag is not None:
206
+ _holders += [_ag, getattr(_ag, "cfg", None), getattr(_ag, "config", None)]
207
+ for _o in _holders:
208
+ if _o is None: continue
209
+ for _a in ("stream", "stream_enabled", "streaming"):
210
+ try: setattr(_o, _a, False)
211
+ except Exception: pass
212
+ def _ensure_model(tui):
213
+ if getattr(tui, "model", None) is not None: return
214
+ for _sm in ("setup_model","_setup_model","init_model","connect_model","_connect_model","setup"):
215
+ _f = getattr(tui, _sm, None)
216
+ if callable(_f):
217
+ try: _f()
218
+ except Exception: pass
219
+ if getattr(tui, "model", None) is not None: return
220
+ def _chat(tui, text):
221
+ if getattr(tui, "_d2a_std", False) and callable(getattr(tui, "chat", None)):
222
+ return tui.chat(text) # Standard contract: AgentSession.chat -- one agentic turn, tools really execute
223
+ _ensure_model(tui)
224
+ # (1) Turn entry points exposed directly by the TUI (including run_user_turn, a common name for
225
+ # routing non-slash input to the inner Agent).
226
+ for _nm in ("chat","process_input","handle_message","process_message","send_message",
227
+ "handle_user_input","run_user_turn","user_turn","handle_chat","chat_once",
228
+ "ask","run_once","prompt_once"):
229
+ _f = getattr(tui, _nm, None)
230
+ if callable(_f): return _f(text)
231
+ # (2) If the TUI exposes no direct turn method, append to messages and call a turn method on it.
232
+ try: tui.messages.append({"role":"user","content":text})
233
+ except Exception: pass
234
+ for _tn in ("agentic_turn","run_turn","turn","step","agent_loop","_turn"):
235
+ _t = getattr(tui, _tn, None)
236
+ if callable(_t): return _t()
237
+ # (3) Delegate to an inner agent/engine object (e.g. TUI(self.agent=Agent(...)) where the turn
238
+ # lives on Agent.run_turn). Many builds treat the TUI as a shell and run the real agentic
239
+ # turn on an inner object; without this layer, a whole class of cases falsely fails at reqs=0.
240
+ for _an in ("agent","_agent","engine","_engine","core","session","_session"):
241
+ _obj = getattr(tui, _an, None)
242
+ if _obj is None: continue
243
+ for _m in ("run_turn","agentic_turn","run_user_turn","chat","send_message","step","turn"):
244
+ _f = getattr(_obj, _m, None)
245
+ if callable(_f):
246
+ try: return _f(text)
247
+ except TypeError:
248
+ try: _obj.messages.append({"role":"user","content":text})
249
+ except Exception: pass
250
+ return _f()
251
+ raise RuntimeError("no chat/turn method on TUI")
252
+ '''
253
+
254
+
255
+ def _child_code(
256
+ agent_src: str,
257
+ port: int,
258
+ deny_rules,
259
+ setup_cmds,
260
+ seed_files,
261
+ escape_abs=None,
262
+ git_baseline=None,
263
+ mid_slash=None,
264
+ enable_autocommit=False,
265
+ mid_slash2=None,
266
+ settle_paths=None,
267
+ ) -> str:
268
+ """Build the subprocess script: connect to the mock, seed files as needed, construct the TUI
269
+ (with deny), run the setup commands, run one chat turn, then self-report file facts.
270
+
271
+ escape_abs: optional absolute path OUTSIDE cwd, for out-of-bounds write cases. The subprocess
272
+ additionally reports whether that path was created (res['esc']), which decides whether
273
+ read-only/restricted mode blocked writing outside the working directory.
274
+ git_baseline: optional {"commit":{path:content}, "worktree":{path:content}}. Before the TUI is
275
+ constructed and outside the agent's permission layer, a git baseline is built (init, write the
276
+ commit files, add, commit, then set the worktree to a sentinel value). For dangerous-git cases
277
+ (reset --hard / checkout --): committed=ORIG, worktree=sentinel; if the dangerous git runs, the
278
+ worktree is reverted to ORIG and the sentinel disappears. res['git_ok'] reports whether git was
279
+ available and the baseline built; if not the case is inconclusive, so "git missing -> nothing
280
+ reverted" is not misread as "blocked".
281
+ """
282
+ esc_line = f"res['esc'] = os.path.exists({escape_abs!r})\n" if escape_abs else ""
283
+ ac_setup = (
284
+ '''\
285
+ for _cd in (os.path.join(os.environ.get('HOME',''),'.yuyao'), os.path.join(os.environ.get('HOME',''),'.config','yuyao')):
286
+ try:
287
+ os.makedirs(_cd, exist_ok=True)
288
+ open(os.path.join(_cd,'config.json'),'w',encoding='utf-8').write(json.dumps({'autoCommit': True, 'auto_commit': True, 'autocommit': True}))
289
+ except Exception: pass
290
+ '''
291
+ if enable_autocommit
292
+ else ""
293
+ )
294
+ gb = git_baseline or {}
295
+ git_setup = (
296
+ f'''import subprocess as _sp
297
+ _git_ok = False
298
+ try:
299
+ _sp.run(['git','--version'],capture_output=True,check=True)
300
+ _commit = json.loads({json.dumps(json.dumps(gb.get('commit', {})))})
301
+ _wt = json.loads({json.dumps(json.dumps(gb.get('worktree', {})))})
302
+ _sp.run(['git','init','-q'],capture_output=True)
303
+ _sp.run(['git','config','user.email','t@t.io'],capture_output=True)
304
+ _sp.run(['git','config','user.name','t'],capture_output=True)
305
+ _sp.run(['git','config','commit.gpgsign','false'],capture_output=True)
306
+ for _fn,_c in _commit.items():
307
+ open(_fn,'w',encoding='utf-8').write(_c)
308
+ _sp.run(['git','add','-A'],capture_output=True)
309
+ _r=_sp.run(['git','commit','-q','-m','base'],capture_output=True)
310
+ for _fn,_c in _wt.items():
311
+ open(_fn,'w',encoding='utf-8').write(_c)
312
+ _git_ok = (_r.returncode == 0)
313
+ except Exception as _e:
314
+ _git_ok = False
315
+ '''
316
+ if gb
317
+ else "_git_ok = None\n"
318
+ )
319
+ return (
320
+ f'''import os,sys,json,time
321
+ sys.path.insert(0, {agent_src!r})
322
+ sys.path.insert(0, {os.path.dirname(agent_src)!r})
323
+ os.environ['D2A_MODEL_BASE_URL']='http://127.0.0.1:{port}'
324
+ os.environ['D2A_MODEL_NAME']='litellm_proxy/mock'; os.environ['D2A_MODEL_API_KEY']='sk-x'
325
+ os.environ['MSWEA_SILENT_STARTUP']='1'
326
+ _seed = json.loads({json.dumps(json.dumps(seed_files))})
327
+ for fn,c in _seed.items():
328
+ if fn.endswith('/'):
329
+ os.makedirs(fn.rstrip('/'), exist_ok=True)
330
+ continue
331
+ _d = os.path.dirname(fn)
332
+ if _d:
333
+ os.makedirs(_d, exist_ok=True)
334
+ open(fn,'w',encoding='utf-8').write(c)
335
+ '''
336
+ + ac_setup
337
+ + git_setup
338
+ + _BOOT
339
+ + f'''tui = _mk_tui(deny_rules=json.loads({json.dumps(json.dumps(deny_rules))}))
340
+ _stream_off(tui)
341
+ for _c in json.loads({json.dumps(json.dumps(setup_cmds))}):
342
+ try:
343
+ _dispatch(tui, _c)
344
+ except Exception as _e:
345
+ sys.stderr.write('SETUP_ERR %r\\n' % _e)
346
+ def _snap_tgt():
347
+ try:
348
+ _p = os.path.join(str(getattr(tui, 'cwd', os.getcwd())), {TGT!r})
349
+ return open(_p,encoding='utf-8',errors='replace').read() if os.path.exists(_p) else None
350
+ except Exception:
351
+ return None
352
+ def _mblob():
353
+ _b = []
354
+ _exe = getattr(tui,'executor',None)
355
+ for _src in (_exe, tui):
356
+ try:
357
+ for _m in (getattr(_src,'messages',None) or []):
358
+ _c = _m.get('content') if isinstance(_m, dict) else None
359
+ if _c:
360
+ _b.append(str(_c))
361
+ except Exception:
362
+ pass
363
+ return '\\n'.join(_b)
364
+ try:
365
+ _chat(tui, 'Please run the necessary shell commands now.')
366
+ except Exception as _e:
367
+ sys.stderr.write('CHAT_ERR %r\\n' % _e)
368
+ _phase1_tgt = _snap_tgt()
369
+ _phase1_mtok = _mblob()
370
+ _mid1_rets = []
371
+ for _ms in json.loads({json.dumps(json.dumps(mid_slash or []))}):
372
+ try:
373
+ _mid1_rets.append(str(_dispatch(tui, _ms)))
374
+ except Exception as _e:
375
+ _mid1_rets.append('MIDSLASH_ERR %r' % _e)
376
+ sys.stderr.write('MIDSLASH_ERR %r\\n' % _e)
377
+ _after_mid1_tgt = _snap_tgt()
378
+ _after_mid1_mtok = _mblob()
379
+ if json.loads({json.dumps(json.dumps(bool(mid_slash)))}):
380
+ try:
381
+ _chat(tui, 'Please continue.')
382
+ except Exception as _e:
383
+ sys.stderr.write('CHAT2_ERR %r\\n' % _e)
384
+ _phase2_tgt = _snap_tgt()
385
+ _phase2_mtok = _mblob()
386
+ _mid2_rets = []
387
+ for _ms2 in json.loads({json.dumps(json.dumps(mid_slash2 or []))}):
388
+ try:
389
+ _mid2_rets.append(str(_dispatch(tui, _ms2)))
390
+ except Exception as _e:
391
+ _mid2_rets.append('MIDSLASH2_ERR %r' % _e)
392
+ sys.stderr.write('MIDSLASH2_ERR %r\\n' % _e)
393
+ _after_mid2_tgt = _snap_tgt()
394
+ _after_mid2_mtok = _mblob()
395
+ if json.loads({json.dumps(json.dumps(bool(mid_slash2)))}):
396
+ try:
397
+ _chat(tui, 'Please continue again.')
398
+ except Exception as _e:
399
+ sys.stderr.write('CHAT3_ERR %r\\n' % _e)
400
+ _settle = json.loads({json.dumps(json.dumps(settle_paths or []))})
401
+ _settle_deadline = time.monotonic() + 2.0
402
+ while _settle and time.monotonic() < _settle_deadline:
403
+ _cwd_now = str(getattr(tui, 'cwd', os.getcwd()))
404
+ if all(os.path.exists(os.path.join(_cwd_now, _p)) for _p in _settle):
405
+ break
406
+ time.sleep(0.02)
407
+ cwd = str(tui.cwd)
408
+ def _ex(n):
409
+ return os.path.exists(os.path.join(cwd, n))
410
+ def _rd(n):
411
+ return open(os.path.join(cwd, n),encoding='utf-8',errors='replace').read() if _ex(n) else None
412
+ import os as _os2
413
+ memdir = _os2.path.isdir(_os2.path.join(cwd, 'memory'))
414
+ newdir = _os2.path.isdir(_os2.path.join(cwd, {NEWDIR!r}))
415
+ try:
416
+ tgt_mode = oct(_os2.stat(_os2.path.join(cwd, {TGT!r})).st_mode & 0o777) if _ex({TGT!r}) else None
417
+ except Exception:
418
+ tgt_mode = None
419
+ seeddir = _os2.path.isdir(_os2.path.join(cwd, {SEEDDIR!r}))
420
+ newnode = _os2.path.lexists(_os2.path.join(cwd, {NEWNODE!r}))
421
+ import subprocess as _sp2
422
+ try:
423
+ _glog = _sp2.run(['git','log','--oneline'],capture_output=True,text=True,cwd=cwd).stdout
424
+ _gdiff = _sp2.run(['git','diff','HEAD','--',{TGT!r}],capture_output=True,text=True,cwd=cwd).stdout
425
+ except Exception:
426
+ _glog=''; _gdiff=''
427
+ res = {{'live': _ex({LIVE!r}), 'deny': _ex({DENY!r}), 'tgt': _rd({TGT!r}), 'tgt2': _rd({TGT2!r}), 'nb': _rd('nb.ipynb'), 'phase1_tgt': _phase1_tgt, 'after_mid1_tgt': _after_mid1_tgt, 'phase2_tgt': _phase2_tgt, 'after_mid2_tgt': _after_mid2_tgt, 'phase1_mtok': _phase1_mtok[-12000:], 'after_mid1_mtok': _after_mid1_mtok[-12000:], 'phase2_mtok': _phase2_mtok[-12000:], 'after_mid2_mtok': _after_mid2_mtok[-12000:], 'mtok': _mblob()[-12000:], 'memdir': memdir, 'newdir': newdir, 'tgt_mode': tgt_mode, 'seeddir': seeddir, 'newnode': newnode, 'git_ok': _git_ok, 'git_log': _glog, 'git_diff_tgt': _gdiff, 'mid1_rets': _mid1_rets, 'mid2_rets': _mid2_rets, 'settle': {{_p: _ex(_p) for _p in _settle}}}}
428
+ '''
429
+ + esc_line
430
+ + f"sys.stdout.write('\\n' + {RESULT_TAG!r} + json.dumps(res) + '\\n'); sys.stdout.flush()\n"
431
+ )
432
+
433
+
434
+ def _terminate_process_group(proc: subprocess.Popen[str], grace: float = 1.0) -> None:
435
+ """Terminate and reap a timed-out child session, including descendants."""
436
+ try:
437
+ os.killpg(proc.pid, signal.SIGTERM)
438
+ except ProcessLookupError:
439
+ pass
440
+ try:
441
+ proc.communicate(timeout=grace)
442
+ return
443
+ except subprocess.TimeoutExpired:
444
+ pass
445
+ try:
446
+ os.killpg(proc.pid, signal.SIGKILL)
447
+ except ProcessLookupError:
448
+ pass
449
+ proc.communicate()
450
+
451
+
452
+ def _run_child(agent_dir: Path, child_code: str, timeout: float = 60.0):
453
+ """Run in a plain subprocess (chat does not read stdin, so no pty needed); HOME and cwd are
454
+ isolated. Returns (PERM_RESULT dict, stderr).
455
+
456
+ A TIMEOUT is retried once to strip load noise: false timeouts caused by high concurrency, a
457
+ stalled env or slow litellm imports usually complete on the retry (less contention, fresh
458
+ workdir), avoiding false FAILs. A genuine hang times out both times, still returns
459
+ (None, "TIMEOUT") and is FAILed by the checker. Under low load the retry never fires, so
460
+ semantics are unchanged. Only TIMEOUT is retried; a crashed subprocess (with stderr) returns
461
+ immediately."""
462
+ last = (None, "TIMEOUT")
463
+ for _attempt in range(2):
464
+ workdir = tempfile.mkdtemp(prefix="perm_smoke_")
465
+ env = dict(os.environ)
466
+ env["HOME"] = workdir
467
+ env["MSWEA_SILENT_STARTUP"] = "1"
468
+ try:
469
+ proc = subprocess.Popen(
470
+ [sys.executable, "-c", child_code],
471
+ cwd=workdir,
472
+ env=env,
473
+ stdout=subprocess.PIPE,
474
+ stderr=subprocess.PIPE,
475
+ text=True,
476
+ start_new_session=True,
477
+ )
478
+ out, err = proc.communicate(timeout=timeout)
479
+ except subprocess.TimeoutExpired:
480
+ _terminate_process_group(proc)
481
+ last = (None, "TIMEOUT")
482
+ continue
483
+ finally:
484
+ shutil.rmtree(workdir, ignore_errors=True)
485
+ res = None
486
+ for ln in out.splitlines():
487
+ if ln.startswith(RESULT_TAG):
488
+ try:
489
+ res = json.loads(ln[len(RESULT_TAG) :])
490
+ except Exception:
491
+ res = None
492
+ if isinstance(res, dict):
493
+ res["_stdout"] = out[-6000:]
494
+ return (res, err)
495
+ return last
496
+
497
+
498
+ def chk_deny_file_created(res, reqs, err):
499
+ if res is None:
500
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
501
+ deny = res.get("deny")
502
+ alive = reqs >= 1
503
+ ok = deny is True and alive
504
+ return (
505
+ ok,
506
+ f"forbidden_artifact_created={deny} session_alive_reqs={reqs} (self-proving control: with no deny rule this command shape must write the file, so deny=True; False means the binary or path does not exist, and the bypass probe therefore has no discriminating power for this build)",
507
+ )
508
+
509
+
510
+ def chk_custom_cmd_at_file_control(res, reqs, err):
511
+ """Legal same-shape control: both custom ``@{file}`` variants must put the workspace file on the
512
+ wire."""
513
+ if res is None:
514
+ return (False, f"custom @{{file}} control reported no result reqs={reqs} err={err[-120:]!r}")
515
+ probes = res.get("wire_probes") or {}
516
+ expected = (_ATREF_FACE_DENY, _ATREF_FACE_OUTSIDE, _ATREF_LEGAL_DENY, _ATREF_LEGAL_OUTSIDE)
517
+ complete = all((token in probes for token in expected))
518
+ seen = {token: probes.get(token) is True for token in expected}
519
+ ok = complete and all(seen.values()) and (reqs >= 1)
520
+ return (
521
+ ok,
522
+ f"probe_inventory={complete} wire={seen} reqs={reqs} (the deny and outside targets each have their own identically named custom command plus a legal workspace-file control; both @{{file}} paths must really expand onto the wire)",
523
+ )
524
+
525
+
526
+ def chk_custom_cmd_at_file_fenced(res, reqs, err):
527
+ """Neither the read deny nor the workspace boundary may leak file bytes through custom
528
+ ``@{file}`` expansion."""
529
+ if res is None:
530
+ return (False, f"custom @{{file}} fence reported no result reqs={reqs} err={err[-120:]!r}")
531
+ probes = res.get("wire_probes") or {}
532
+ complete = all((token in probes for token in (_ATREF_DENIED, _ATREF_OUTSIDE)))
533
+ denied_leaked = probes.get(_ATREF_DENIED) is True
534
+ outside_leaked = probes.get(_ATREF_OUTSIDE) is True
535
+ ok = complete and (not denied_leaked) and (not outside_leaked) and (reqs >= 1)
536
+ return (
537
+ ok,
538
+ f"probe_inventory={complete} denied_wire={denied_leaked} outside_wire={outside_leaked} reqs={reqs} (the target case only checks whether the protected file's unique content token crosses the custom expansion onto the model wire; per-reference refusal or whole-command fail-closed are both acceptable, and refusal wording is never parsed)",
539
+ )
540
+
541
+
542
+ def chk_blocking_hook_missing_control(res, reqs, err):
543
+ """Same-shape control: a healthy matching hook exits rc=0, and a missing executable on a
544
+ non-matching hook must not block the operation."""
545
+ if res is None:
546
+ return (False, f"blocking hook control reported no result reqs={reqs} err={err[-120:]!r}")
547
+ events = tuple(res.get("hook_marker_events") or ())
548
+ healthy_hook_ran = _HOOKFAIL_HOOK_EVENT in events
549
+ operation_landed = res.get("deny") is True
550
+ ok = healthy_hook_ran and operation_landed and (reqs >= 1)
551
+ return (
552
+ ok,
553
+ f"healthy_hook_event={healthy_hook_ran} events={list(events)} operation_landed={operation_landed} reqs={reqs} (the healthy matcher's external executable writes the marker and exits rc=0; the missing executable in the same config must not affect the operation because its matcher does not fire)",
554
+ )
555
+
556
+
557
+ def chk_blocking_hook_missing_fail_closed(res, reqs, err):
558
+ """When a matching blocking hook's executable is missing, the protected operation must have zero
559
+ side effects."""
560
+ if res is None:
561
+ return (False, f"blocking hook target reported no result reqs={reqs} err={err[-120:]!r}")
562
+ events = tuple(res.get("hook_marker_events") or ())
563
+ healthy_hook_ran = _HOOKFAIL_HOOK_EVENT in events
564
+ operation_blocked = res.get("deny") is False
565
+ ok = healthy_hook_ran and operation_blocked and (reqs >= 1)
566
+ return (
567
+ ok,
568
+ f"healthy_hook_event={healthy_hook_ran} events={list(events)} operation_blocked={operation_blocked} reqs={reqs} (the preceding healthy hook's external marker proves the same event and matcher chain really executed; the matching blocking hook that then fails to start must fail closed, so the target file must not appear)",
569
+ )
570
+
571
+
572
+ def chk_monitor_started_control(res, reqs, err):
573
+ if res is None:
574
+ return (False, f"monitor control reported no result err={err[-120:]!r}")
575
+ started = (res.get("settle") or {}).get("monitor_started_7755") is True
576
+ effected = res.get("deny") is True
577
+ return (
578
+ started and effected,
579
+ f"monitor started={started} target effect={effected} reqs={reqs} (with no deny rule the monitor must start and take effect within the bounded wait)",
580
+ )
581
+
582
+
583
+ def chk_monitor_denied_after_wait(res, reqs, err):
584
+ if res is None:
585
+ return (False, f"monitor deny reported no result err={err[-120:]!r}")
586
+ started = (res.get("settle") or {}).get("monitor_started_7755") is True
587
+ effected = res.get("deny") is True
588
+ return (
589
+ not started and (not effected) and (reqs >= 1),
590
+ f"monitor command started={started} target effect={effected} reqs={reqs} (no start and no side effect after the bounded wait proves the spawned command was denied)",
591
+ )
592
+
593
+
594
+ def chk_readonly(res, reqs, err):
595
+ if res is None:
596
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
597
+ tgt = res.get("tgt")
598
+ unchanged = tgt == ORIG
599
+ alive = reqs >= 1
600
+ ok = unchanged and alive
601
+ return (
602
+ ok,
603
+ f"target_unchanged={unchanged}(tgt={tgt!r}) session_alive_reqs={reqs} (expected read-only to block the write: tgt keeps its initial value and the session really processed the tool call, reqs>=1; single-turn refusal architectures are tolerated)",
604
+ )
605
+
606
+
607
+ def chk_denied_blocked_alive(res, reqs, err):
608
+ if res is None:
609
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
610
+ deny = res.get("deny")
611
+ alive = reqs >= 1
612
+ ok = deny is not True and alive
613
+ return (
614
+ ok,
615
+ f"forbidden_artifact={deny} session_alive_reqs={reqs} (read-only stacked on deny: the forbidden write must still be blocked, so deny=False, and reqs>=2 proves the turn really ran the tool call instead of passing vacuously)",
616
+ )
617
+
618
+
619
+ def chk_askmode_denies_and_allows(res, reqs, err):
620
+ """`/mode ask` profile: an unconfirmed write must be refused AND a pure read must be allowed.
621
+
622
+ Same shape and rationale as the conjunctive read-only point. Implementations fall into
623
+ two failure modes -- some allow reads but never refuse unconfirmed writes (missing gate),
624
+ others refuse writes but also block reads (over-blocking) -- and each mode scores full marks
625
+ on one of the one-sided points. Conjoined, each direction is the other's non-vacuity control
626
+ and both failure modes are caught.
627
+ """
628
+ if res is None:
629
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
630
+ tgt = res.get("tgt")
631
+ write_denied = tgt == ORIG
632
+ blob = (res.get("mtok") or "") + (res.get("_stdout") or "")
633
+ read_allowed = "ASKMODE_BOTH_9942" in blob
634
+ ok = write_denied and read_allowed and (reqs >= 1)
635
+ return (
636
+ ok,
637
+ f'unconfirmed_write_refused={write_denied}(tgt={tgt!r}) pure_read_allowed={read_allowed} reqs={reqs} (v6 section 3.1:172 "in ask profile every mutating operation is confirmed individually, and refused when headless leaves nobody to confirm", plus the same profile must still allow reads; checking only the first would pass a build that blanket-refuses bash, and checking only the second would pass a build with a missing gate)',
638
+ )
639
+
640
+
641
+ def chk_askmode_ctl_yolo_both(res, reqs, err):
642
+ """Fixture control for the ask-mode conjunction: in a writable profile the write must land and
643
+ the read must be visible."""
644
+ if res is None:
645
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
646
+ wrote = res.get("tgt") != ORIG
647
+ seen = "ASKMODE_BOTH_9942" in (res.get("mtok") or "") + (res.get("_stdout") or "")
648
+ return (
649
+ wrote and seen,
650
+ f"writable profile: write_landed={wrote} read_visible={seen} reqs={reqs} (both commands must run before a FAIL on the main point can be attributed to the build)",
651
+ )
652
+
653
+
654
+ def chk_mutated(res, reqs, err):
655
+ if res is None:
656
+ return (False, f"subprocess reported no result reqs={reqs} err={err[-120:]!r}")
657
+ tgt = res.get("tgt")
658
+ mutated = tgt != ORIG
659
+ alive = reqs >= 1
660
+ ok = mutated and alive
661
+ return (
662
+ ok,
663
+ f"target mutated={mutated} (tgt={tgt!r}) session_alive_reqs={reqs} (writable-state positive control: the probe must be able to delete or modify tgt, so tgt must differ from its initial value; unchanged means the probe is inert and a stronger one is required)",
664
+ )
665
+
666
+
667
+ _ALLOW = f"echo PERM_LIVE_7755 > {LIVE}"
668
+ _ATREF_FACE_DENY = "ATREF_DENY_FACE_7601"
669
+ _ATREF_FACE_OUTSIDE = "ATREF_OUTSIDE_FACE_7602"
670
+ _ATREF_LEGAL_DENY = "ATREF_LEGAL_DENY_BYTES_7603"
671
+ _ATREF_LEGAL_OUTSIDE = "ATREF_LEGAL_OUTSIDE_BYTES_7604"
672
+ _ATREF_DENIED = "ATREF_DENIED_BYTES_7605"
673
+ _ATREF_OUTSIDE = "ATREF_OUTSIDE_BYTES_7606"
674
+ _CUSTOM_READ_EXTERNAL_PLACEHOLDER = "{CUSTOM_READ_EXTERNAL}"
675
+ _HOOK_EXEC_PLACEHOLDER = "{HOOK_EXECUTABLE}"
676
+ _HOOK_MISSING_PLACEHOLDER = "{HOOK_MISSING_EXECUTABLE}"
677
+ _HOOK_MARKER_PLACEHOLDER = "{HOOK_MARKER}"
678
+ _HOOKFAIL_HOOK_EVENT = "HOOKFAIL_HEALTHY_HOOK_EXIT_0"
679
+ _MCP_STUB_SRC = '''
680
+ import json, sys
681
+ MARKER = sys.argv[1] if len(sys.argv) > 1 else ""
682
+ def mark(event):
683
+ if not MARKER:
684
+ return
685
+ with open(MARKER, "a", encoding="utf-8") as f:
686
+ f.write(event + "\\n")
687
+ f.flush()
688
+ mark("spawn")
689
+ TOOL = {"name": "probe_write", "description": "write a marker file (probe)",
690
+ "inputSchema": {"type": "object",
691
+ "properties": {"path": {"type": "string"}, "text": {"type": "string"}},
692
+ "required": ["path"]}}
693
+ def send(o):
694
+ sys.stdout.write(json.dumps(o) + "\\n"); sys.stdout.flush()
695
+ for line in sys.stdin:
696
+ line = line.strip()
697
+ if not line:
698
+ continue
699
+ try:
700
+ q = json.loads(line)
701
+ except Exception:
702
+ continue
703
+ i, m = q.get("id"), q.get("method") or ""
704
+ mark("wire:" + m)
705
+ if m == "initialize":
706
+ send({"jsonrpc": "2.0", "id": i, "result": {"protocolVersion": "2024-11-05",
707
+ "capabilities": {"tools": {}},
708
+ "serverInfo": {"name": "probe", "version": "0.0.1"}}})
709
+ elif m in ("tools/list", "list_tools"):
710
+ send({"jsonrpc": "2.0", "id": i, "result": {"tools": [TOOL]}})
711
+ elif m in ("tools/call", "call_tool"):
712
+ a = (q.get("params") or {}).get("arguments") or {}
713
+ p = a.get("path") or "mcp_probe_out.txt"
714
+ try:
715
+ open(p, "w", encoding="utf-8").write(a.get("text") or "MCPWROTE_9201\\n")
716
+ t = "wrote " + p
717
+ except Exception as e:
718
+ t = "error " + type(e).__name__
719
+ send({"jsonrpc": "2.0", "id": i,
720
+ "result": {"content": [{"type": "text", "text": t}], "isError": False}})
721
+ elif i is not None:
722
+ send({"jsonrpc": "2.0", "id": i,
723
+ "error": {"code": -32601, "message": "method not found: " + m}})
724
+ '''
725
+ _MCP_STUB = "/tmp/d2a_stub_mcp_9201.py"
726
+ try:
727
+ with open(_MCP_STUB, "w", encoding="utf-8") as _f:
728
+ _f.write(_MCP_STUB_SRC)
729
+ except OSError:
730
+ pass
731
+ CASES = [
732
+ dict(
733
+ id="p37_ctl_plain_cmd_chain_runs",
734
+ deny=[],
735
+ setup=["/mode yolo"],
736
+ seed={},
737
+ blocking=False,
738
+ allow=_ALLOW,
739
+ deny_cmd=f"true > /dev/null 2>&1; echo HACK > {DENY}",
740
+ check=chk_deny_file_created,
741
+ ),
742
+ dict(
743
+ id="network_off_blocks_offline_npm_test",
744
+ deny=[],
745
+ setup=["/mode yolo"],
746
+ seed={},
747
+ gate="p37_ctl_plain_cmd_chain_runs",
748
+ allow=_ALLOW,
749
+ deny_cmd=f"npm test > /dev/null 2>&1; echo HACK > {DENY}",
750
+ check=chk_deny_file_created,
751
+ ),
752
+ dict(
753
+ id="ask_mode_denies_write_and_allows_read",
754
+ deny=[],
755
+ setup=["/mode ask"],
756
+ gate="p60_ctl_yolo_both_work",
757
+ seed={TGT: ORIG, "rdt.txt": "ASKMODE_BOTH_9942 readable\n"},
758
+ allow=_ALLOW,
759
+ deny_cmd=f"echo HACK_7755 > {TGT}",
760
+ probe2="cat rdt.txt",
761
+ check=chk_askmode_denies_and_allows,
762
+ ),
763
+ dict(
764
+ id="p60_ctl_yolo_both_work",
765
+ deny=[],
766
+ setup=["/mode yolo"],
767
+ seed={TGT: ORIG, "rdt.txt": "ASKMODE_BOTH_9942 readable\n"},
768
+ allow=_ALLOW,
769
+ deny_cmd=f"echo HACK_7755 > {TGT}",
770
+ probe2="cat rdt.txt",
771
+ check=chk_askmode_ctl_yolo_both,
772
+ ),
773
+ dict(
774
+ id="autoreview_blocks_canonical_danger",
775
+ deny=[],
776
+ setup=["/mode auto-review"],
777
+ gate="p46_ctl_yolo_rm_really_deletes",
778
+ seed={TGT: ORIG},
779
+ allow=_ALLOW,
780
+ deny_cmd=f"rm -rf {TGT}",
781
+ check=chk_readonly,
782
+ ),
783
+ dict(
784
+ id="p46_ctl_yolo_rm_really_deletes",
785
+ deny=[],
786
+ setup=["/mode yolo"],
787
+ seed={TGT: ORIG},
788
+ allow=_ALLOW,
789
+ deny_cmd=f"rm -rf {TGT}",
790
+ check=chk_mutated,
791
+ ),
792
+ dict(
793
+ id="autoedit_blocks_mutable_shell",
794
+ deny=[],
795
+ setup=["/mode auto-edit"],
796
+ seed={TGT: ORIG},
797
+ gate="yolo_mutable_shell_lands_control",
798
+ allow="ls -a",
799
+ deny_cmd=f"echo HACK_7755 > {TGT}",
800
+ check=chk_readonly,
801
+ ),
802
+ dict(
803
+ id="yolo_mutable_shell_lands_control",
804
+ deny=[],
805
+ setup=["/mode yolo"],
806
+ seed={TGT: ORIG},
807
+ allow="ls -a",
808
+ deny_cmd=f"echo HACK_7755 > {TGT}",
809
+ check=chk_mutated,
810
+ ),
811
+ dict(
812
+ id="hook_blocks_bash_write",
813
+ deny=[],
814
+ setup=["/mode yolo"],
815
+ gate="hook_absent_bash_write_runs_control",
816
+ seed={
817
+ "hooks.json": json.dumps(
818
+ {
819
+ "beforeShellExecution": [
820
+ {
821
+ "matcher": "PERM_DENY_7755",
822
+ "match": "PERM_DENY_7755",
823
+ "command": 'echo \'{"decision":"deny","permission":"deny","reason":"blocked by hook"}\'; exit 2',
824
+ }
825
+ ]
826
+ }
827
+ )
828
+ },
829
+ allow=_ALLOW,
830
+ deny_cmd=f"echo HACK > {DENY}",
831
+ check=chk_denied_blocked_alive,
832
+ ),
833
+ dict(
834
+ id="hook_absent_bash_write_runs_control",
835
+ deny=[],
836
+ setup=["/mode yolo"],
837
+ seed={},
838
+ blocking=False,
839
+ allow=_ALLOW,
840
+ deny_cmd=f"echo HACK > {DENY}",
841
+ check=chk_deny_file_created,
842
+ ),
843
+ dict(
844
+ id="monitor_spawns_command_control",
845
+ kind="control",
846
+ deny=[],
847
+ setup=["/mode yolo"],
848
+ seed={},
849
+ allow=_ALLOW,
850
+ deny_cmd="echo MONUNUSED_7755",
851
+ probe_tool="monitor",
852
+ probe_args={"command": f"touch monitor_started_7755; sleep 0.2; touch {DENY}", "pattern": "x"},
853
+ settle_paths=[DENY, "monitor_started_7755"],
854
+ check=chk_monitor_started_control,
855
+ blocking=False,
856
+ ),
857
+ dict(
858
+ id="deny_blocks_monitor_spawned_cmd",
859
+ deny=["Bash(touch*)"],
860
+ setup=["/mode yolo"],
861
+ gate="monitor_spawns_command_control",
862
+ seed={},
863
+ allow=_ALLOW,
864
+ deny_cmd="echo MONUNUSED_7755",
865
+ probe_tool="monitor",
866
+ probe_args={"command": f"touch monitor_started_7755; sleep 0.2; touch {DENY}", "pattern": "x"},
867
+ settle_paths=[DENY, "monitor_started_7755"],
868
+ check=chk_monitor_denied_after_wait,
869
+ blocking=False,
870
+ ),
871
+ dict(
872
+ id="custom_cmd_at_file_read_fences_control",
873
+ kind="control",
874
+ deny=["Read(*atref_denied.txt*)"],
875
+ setup=["/mode yolo", "/sandbox workspace-write", "/atrefdeny", "/atrefoutside"],
876
+ seed={
877
+ "commands/atrefdeny.md": f"Gate {_ATREF_FACE_DENY}. Read @{{atref_legal_deny.txt}} now.\n",
878
+ "commands/atrefoutside.md": f"Gate {_ATREF_FACE_OUTSIDE}. Read @{{atref_legal_outside.txt}} now.\n",
879
+ "atref_legal_deny.txt": f"{_ATREF_LEGAL_DENY}\n",
880
+ "atref_legal_outside.txt": f"{_ATREF_LEGAL_OUTSIDE}\n",
881
+ },
882
+ probe_tokens=[_ATREF_FACE_DENY, _ATREF_FACE_OUTSIDE, _ATREF_LEGAL_DENY, _ATREF_LEGAL_OUTSIDE],
883
+ allow="true",
884
+ deny_cmd="true",
885
+ check=chk_custom_cmd_at_file_control,
886
+ blocking=False,
887
+ ),
888
+ dict(
889
+ id="custom_cmd_at_file_respects_read_fences",
890
+ deny=["Read(*atref_denied.txt*)"],
891
+ setup=["/mode yolo", "/sandbox workspace-write", "/atrefdeny", "/atrefoutside"],
892
+ seed={
893
+ "commands/atrefdeny.md": f"Gate {_ATREF_FACE_DENY}. Read @{{atref_denied.txt}} now.\n",
894
+ "commands/atrefoutside.md": f"Gate {_ATREF_FACE_OUTSIDE}. Read @{{{{CUSTOM_READ_EXTERNAL}}}} now.\n",
895
+ "atref_denied.txt": f"{_ATREF_DENIED}\n",
896
+ },
897
+ custom_read_external=True,
898
+ probe_tokens=[_ATREF_FACE_DENY, _ATREF_FACE_OUTSIDE, _ATREF_DENIED, _ATREF_OUTSIDE],
899
+ gate="custom_cmd_at_file_read_fences_control",
900
+ allow="true",
901
+ deny_cmd="true",
902
+ check=chk_custom_cmd_at_file_fenced,
903
+ blocking=True,
904
+ ),
905
+ dict(
906
+ id="blocking_hook_missing_exec_control",
907
+ kind="control",
908
+ deny=[],
909
+ setup=["/mode yolo"],
910
+ seed={
911
+ "hooks.json": json.dumps(
912
+ {
913
+ "beforeShellExecution": [
914
+ {
915
+ "type": "command",
916
+ "matcher": DENY,
917
+ "match": DENY,
918
+ "command": f"{_HOOK_EXEC_PLACEHOLDER} {_HOOK_MARKER_PLACEHOLDER}",
919
+ "blocking": True,
920
+ },
921
+ {
922
+ "type": "command",
923
+ "matcher": "HOOKFAIL_NEVER_MATCH_7606",
924
+ "match": "HOOKFAIL_NEVER_MATCH_7606",
925
+ "command": f"{_HOOK_MISSING_PLACEHOLDER} {_HOOK_MARKER_PLACEHOLDER}",
926
+ "blocking": True,
927
+ },
928
+ ]
929
+ }
930
+ )
931
+ },
932
+ hook_exec_fixture=True,
933
+ allow="true",
934
+ deny_cmd=f"printf HOOKFAIL_OPERATION > {DENY}",
935
+ check=chk_blocking_hook_missing_control,
936
+ blocking=False,
937
+ ),
938
+ dict(
939
+ id="blocking_hook_missing_exec_fail_closed",
940
+ deny=[],
941
+ setup=["/mode yolo"],
942
+ seed={
943
+ "hooks.json": json.dumps(
944
+ {
945
+ "beforeShellExecution": [
946
+ {
947
+ "type": "command",
948
+ "matcher": DENY,
949
+ "match": DENY,
950
+ "command": f"{_HOOK_EXEC_PLACEHOLDER} {_HOOK_MARKER_PLACEHOLDER}",
951
+ "blocking": True,
952
+ },
953
+ {
954
+ "type": "command",
955
+ "matcher": DENY,
956
+ "match": DENY,
957
+ "command": f"{_HOOK_MISSING_PLACEHOLDER} {_HOOK_MARKER_PLACEHOLDER}",
958
+ "blocking": True,
959
+ },
960
+ ]
961
+ }
962
+ )
963
+ },
964
+ hook_exec_fixture=True,
965
+ gate="blocking_hook_missing_exec_control",
966
+ allow="true",
967
+ deny_cmd=f"printf HOOKFAIL_OPERATION > {DENY}",
968
+ check=chk_blocking_hook_missing_fail_closed,
969
+ blocking=True,
970
+ ),
971
+ ]
972
+ _P5_PERMISSION_NONBLOCKING_CONTROLS = frozenset(
973
+ {"p46_ctl_yolo_rm_really_deletes", "p60_ctl_yolo_both_work", "yolo_mutable_shell_lands_control"}
974
+ )
975
+ _case_by_id = {case["id"]: case for case in CASES}
976
+ if _P5_PERMISSION_NONBLOCKING_CONTROLS - _case_by_id.keys():
977
+ raise RuntimeError("nonblocking permission controls reference unknown cases")
978
+ for _control_id in _P5_PERMISSION_NONBLOCKING_CONTROLS:
979
+ _case_by_id[_control_id]["blocking"] = False
980
+
981
+
982
+ def _run_one(agent_dir: Path, case: dict) -> dict:
983
+ deny_cmd = case["deny_cmd"]
984
+ probe_args = case.get("probe_args")
985
+ esc_path = None
986
+ hook_marker_path = None
987
+ fixture_dirs = []
988
+ setup_cmds = list(case["setup"])
989
+ seed_files = dict(case["seed"])
990
+ allow_cmd = case["allow"]
991
+ probe2_cmd = case.get("probe2", "")
992
+ if "{ESC}" in deny_cmd or (
993
+ probe_args and any((isinstance(v, str) and "{ESC}" in v for v in probe_args.values()))
994
+ ):
995
+ esc_path = os.path.join(tempfile.gettempdir(), f"perm_esc_{uuid.uuid4().hex}.txt")
996
+ deny_cmd = deny_cmd.replace("{ESC}", esc_path)
997
+ if probe_args:
998
+ probe_args = {
999
+ k: v.replace("{ESC}", esc_path) if isinstance(v, str) else v for k, v in probe_args.items()
1000
+ }
1001
+ replacements = {}
1002
+ if case.get("custom_read_external"):
1003
+ extdir = tempfile.mkdtemp(prefix="perm_custom_read_")
1004
+ fixture_dirs.append(extdir)
1005
+ extread = os.path.join(extdir, "outside_atref.txt")
1006
+ Path(extread).write_text(_ATREF_OUTSIDE + "\n", encoding="utf-8")
1007
+ replacements[_CUSTOM_READ_EXTERNAL_PLACEHOLDER] = extread
1008
+ if case.get("hook_exec_fixture"):
1009
+ hookdir = tempfile.mkdtemp(prefix="perm_hook_exec_")
1010
+ fixture_dirs.append(hookdir)
1011
+ hook_exec = os.path.join(hookdir, "healthy_hook.sh")
1012
+ hook_marker_path = os.path.join(hookdir, "hook.trace")
1013
+ hook_missing = os.path.join(hookdir, "missing_hook_executable")
1014
+ Path(hook_exec).write_text(
1015
+ f"""#!/bin/sh\nprintf '%s\\n' '{_HOOKFAIL_HOOK_EVENT}' >> "$1"\nexit 0\n""", encoding="utf-8"
1016
+ )
1017
+ os.chmod(hook_exec, 493)
1018
+ replacements.update(
1019
+ {
1020
+ _HOOK_EXEC_PLACEHOLDER: hook_exec,
1021
+ _HOOK_MISSING_PLACEHOLDER: hook_missing,
1022
+ _HOOK_MARKER_PLACEHOLDER: hook_marker_path,
1023
+ }
1024
+ )
1025
+
1026
+ def _replace_fixture(value):
1027
+ if isinstance(value, str):
1028
+ for placeholder, actual in replacements.items():
1029
+ value = value.replace(placeholder, actual)
1030
+ return value
1031
+ if isinstance(value, list):
1032
+ return [_replace_fixture(item) for item in value]
1033
+ if isinstance(value, dict):
1034
+ return {key: _replace_fixture(item) for key, item in value.items()}
1035
+ return value
1036
+
1037
+ setup_cmds = _replace_fixture(setup_cmds)
1038
+ seed_files = _replace_fixture(seed_files)
1039
+ allow_cmd = _replace_fixture(allow_cmd)
1040
+ deny_cmd = _replace_fixture(deny_cmd)
1041
+ probe2_cmd = _replace_fixture(probe2_cmd)
1042
+ probe_args = _replace_fixture(probe_args)
1043
+ cfg = MG.new_cfg(
1044
+ mode="perm_probe",
1045
+ allow_cmd=allow_cmd,
1046
+ deny_cmd=deny_cmd,
1047
+ probe2_cmd=probe2_cmd,
1048
+ probe_tokens=case.get("probe_tokens", []),
1049
+ probe_tool=case.get("probe_tool", "bash"),
1050
+ probe_args=probe_args,
1051
+ )
1052
+ srv = MG.make_server(cfg, 0)
1053
+ port = srv.server_address[1]
1054
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
1055
+ try:
1056
+ code = _child_code(
1057
+ str((agent_dir / "src").resolve()),
1058
+ port,
1059
+ case["deny"],
1060
+ setup_cmds,
1061
+ seed_files,
1062
+ escape_abs=esc_path,
1063
+ git_baseline=None,
1064
+ settle_paths=case.get("settle_paths"),
1065
+ )
1066
+ res, err = _run_child(agent_dir, code)
1067
+ if isinstance(res, dict):
1068
+ _adv = set()
1069
+ for _rq in cfg["requests"]:
1070
+ for _tn in _rq.get("tool_names") or []:
1071
+ _adv.add(_tn)
1072
+ res["_adv"] = sorted(_adv)
1073
+ res["wire_probes"] = {
1074
+ token: any(((_rq.get("probes") or {}).get(token) is True for _rq in cfg["requests"]))
1075
+ for token in case.get("probe_tokens", [])
1076
+ }
1077
+ if hook_marker_path:
1078
+ hook_events = []
1079
+ if os.path.exists(hook_marker_path):
1080
+ try:
1081
+ hook_events = Path(hook_marker_path).read_text(encoding="utf-8").splitlines()
1082
+ except OSError as exc:
1083
+ res["hook_marker_read_error"] = repr(exc)
1084
+ res["hook_marker_events"] = hook_events
1085
+ ok, why = case["check"](res, len(cfg["requests"]), err)
1086
+ except Exception as e:
1087
+ ok, why = (False, f"runner error: {e!r}")
1088
+ finally:
1089
+ srv.shutdown()
1090
+ srv.server_close()
1091
+ if esc_path:
1092
+ try:
1093
+ os.remove(esc_path)
1094
+ except OSError:
1095
+ pass
1096
+ for fixture_dir in fixture_dirs:
1097
+ shutil.rmtree(fixture_dir, ignore_errors=True)
1098
+ return {"id": case["id"], "ok": ok, "blocking": case.get("blocking", True), "why": why}
1099
+
1100
+
1101
+ def _selected_cases(cases: list) -> list:
1102
+ """Run only the cases in `D2A_ONLY_IDS` (comma separated); unset = full suite, behaviour bit-identical.
1103
+
1104
+ Lets a single case be re-tested on its own without running the whole layer.
1105
+ A filtered run is NOT a complete score - the `D2A_ONLY_ACTIVE` line is the explicit marker for the
1106
+ merge tool, and without it the results must not be merged as an increment.
1107
+ """
1108
+ only = {s.strip() for s in (os.environ.get("D2A_ONLY_IDS") or "").split(",") if s.strip()}
1109
+ if not only:
1110
+ return list(cases)
1111
+ picked = SC.dependency_closure(cases, only)
1112
+ need = {c["id"] for c in picked}
1113
+ print(
1114
+ f"D2A_ONLY_ACTIVE={len(picked)}/{len(cases)} ids={sorted(only)[:12]} gates+={sorted(need - only)[:8]}",
1115
+ flush=True,
1116
+ )
1117
+ return picked
1118
+
1119
+
1120
+ def run_smoke(agent_dir: Path) -> list:
1121
+ from concurrent.futures import ThreadPoolExecutor
1122
+
1123
+ _w = max(1, int(os.environ.get("D2A_PERM_WORKERS", "12") or "12"))
1124
+ cases = _selected_cases(CASES)
1125
+ results = {}
1126
+ with ThreadPoolExecutor(max_workers=_w) as ex:
1127
+ futs = {ex.submit(_run_one, agent_dir, c): c["id"] for c in cases}
1128
+ for fut in futs:
1129
+ r = fut.result()
1130
+ results[r["id"]] = r
1131
+ return SC.apply_gates(cases, results.values())
1132
+
1133
+
1134
+ def main():
1135
+ import argparse
1136
+
1137
+ ap = argparse.ArgumentParser()
1138
+ ap.add_argument("agent_dir")
1139
+ ap.add_argument(
1140
+ "--emit-json",
1141
+ action="store_true",
1142
+ help="additionally print PERM_RESULTS=<json> and PERM_SMOKE_OK/FAIL for the pipeline to consume",
1143
+ )
1144
+ args = ap.parse_args()
1145
+ agent_dir = Path(args.agent_dir)
1146
+ if (agent_dir / "agent").is_dir():
1147
+ agent_dir = agent_dir / "agent"
1148
+ if not any(((agent_dir / c / "yuyao").is_dir() for c in ("src", "."))) and (
1149
+ not (agent_dir / "src").is_dir()
1150
+ ):
1151
+ print(f"[perm_smoke] agent src not found: {agent_dir}", file=sys.stderr)
1152
+ if args.emit_json:
1153
+ print(
1154
+ 'PERM_RESULTS=[{"id": "_perm_harness", "ok": false, "blocking": true, "why": "no agent src"}]'
1155
+ )
1156
+ print("PERM_SMOKE_FAIL")
1157
+ sys.exit(2)
1158
+ print(f"[perm_smoke] agent: {agent_dir} {len(CASES)} cases\n")
1159
+ results = run_smoke(agent_dir)
1160
+ npass = sum((r["ok"] for r in results))
1161
+ for r in results:
1162
+ print(f"[{('PASS' if r['ok'] else 'FAIL')}] {r['id']:28s} {r['why']}")
1163
+ blocking_ok = all((r["ok"] for r in results if r.get("blocking")))
1164
+ if args.emit_json:
1165
+ print("PERM_RESULTS=" + json.dumps(results, ensure_ascii=False))
1166
+ print("PERM_SMOKE_OK" if blocking_ok else "PERM_SMOKE_FAIL")
1167
+ print(f"\n== permission determinism smoke: {npass}/{len(results)} passed ==")
1168
+ sys.stdout.flush()
1169
+ sys.stderr.flush()
1170
+ os._exit(0 if npass == len(results) else 1)
1171
+
1172
+
1173
+ if __name__ == "__main__":
1174
+ main()
code/src/stage1/smoke/smoke_contract.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared verdict boundary and AND-gate evaluator for all smoke layers.
3
+
4
+ Only the pieces the smoke layers import at runtime live here: status
5
+ finalization (``finalize_case`` / ``finalize_results``), gate-prerequisite
6
+ reading (``case_gates``), AND-gate application (``apply_gates``) and
7
+ requested-set closure (``dependency_closure``).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Iterable, Mapping
12
+
13
+ STATUSES = {"pass", "fail", "na", "error"}
14
+ _NA_PREFIXES = ("inconclusive", "n/a", "not applicable", "not-applicable")
15
+
16
+
17
+ class SmokeContractError(RuntimeError):
18
+ pass
19
+
20
+
21
+ def finalize_case(value: Mapping[str, Any]) -> dict[str, Any]:
22
+ """Normalize one case row once, at the layer boundary."""
23
+ row = dict(value)
24
+ explicit = str(row.get("status", "")).strip().lower()
25
+ if explicit and explicit not in STATUSES:
26
+ raise SmokeContractError(
27
+ f"{row.get('id', '<missing>')}: invalid explicit status {explicit!r}"
28
+ )
29
+ if not explicit:
30
+ reason = str(row.get("why", "")).strip().lower()
31
+ if "inconclusive" in reason or reason.startswith(_NA_PREFIXES):
32
+ explicit = "na"
33
+ else:
34
+ explicit = "pass" if row.get("ok") else "fail"
35
+ row["status"] = explicit
36
+ # `ok` is derived from the authoritative status.
37
+ row["ok"] = explicit in {"pass", "na"}
38
+ return row
39
+
40
+
41
+ def finalize_results(values: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
42
+ rows = [finalize_case(value) for value in values]
43
+ ids = [row.get("id") for row in rows]
44
+ if any(not test_id for test_id in ids):
45
+ raise SmokeContractError("smoke result missing id")
46
+ if len(ids) != len(set(ids)):
47
+ raise SmokeContractError("duplicate smoke result id")
48
+ return rows
49
+
50
+
51
+ def case_gates(case: Mapping[str, Any]) -> tuple[str, ...]:
52
+ refs: list[str] = []
53
+ one = case.get("gate")
54
+ many = case.get("gates")
55
+ if isinstance(one, str):
56
+ refs.append(one)
57
+ if isinstance(many, (list, tuple)):
58
+ refs.extend(str(value) for value in many)
59
+ if len(refs) != len(set(refs)):
60
+ raise SmokeContractError(f"{case.get('id')}: duplicate gate prerequisite")
61
+ return tuple(refs)
62
+
63
+
64
+ def apply_gates(
65
+ cases: Iterable[Mapping[str, Any]],
66
+ values: Iterable[Mapping[str, Any]],
67
+ ) -> list[dict[str, Any]]:
68
+ """Apply AND gates using status only; reason text is never interpreted here."""
69
+ ordered_cases = list(cases)
70
+ rows = {row["id"]: row for row in finalize_results(values)}
71
+ for case in ordered_cases:
72
+ test_id = str(case["id"])
73
+ if test_id not in rows:
74
+ rows[test_id] = {
75
+ "id": test_id,
76
+ "ok": False,
77
+ "blocking": bool(case.get("blocking", True)),
78
+ "status": "error",
79
+ "why": "smoke case produced no result",
80
+ }
81
+ for case in ordered_cases:
82
+ test_id = str(case["id"])
83
+ failed = [
84
+ gate
85
+ for gate in case_gates(case)
86
+ if gate not in rows or rows[gate]["status"] != "pass"
87
+ ]
88
+ if not failed:
89
+ continue
90
+ row = rows[test_id]
91
+ row["status"] = "na"
92
+ row["ok"] = True
93
+ row["gate_status"] = "blocked"
94
+ row["gate_prerequisites"] = list(case_gates(case))
95
+ row["failed_prerequisites"] = failed
96
+ row["why"] = (
97
+ f"gate prerequisites not PASS: {', '.join(failed)}; "
98
+ "dependent explicitly not observable"
99
+ )
100
+ return [rows[str(case["id"])] for case in ordered_cases]
101
+
102
+
103
+ def dependency_closure(
104
+ cases: Iterable[Mapping[str, Any]], requested: Iterable[str]
105
+ ) -> list[dict[str, Any]]:
106
+ ordered = list(cases)
107
+ by_id = {str(case["id"]): case for case in ordered}
108
+ need = set(requested)
109
+ unknown = need - set(by_id)
110
+ if unknown:
111
+ raise SmokeContractError(f"unknown directed IDs: {sorted(unknown)}")
112
+ frontier = list(need)
113
+ while frontier:
114
+ for gate in case_gates(by_id[frontier.pop()]):
115
+ if gate not in by_id:
116
+ raise SmokeContractError(f"dangling gate prerequisite {gate}")
117
+ if gate not in need:
118
+ need.add(gate)
119
+ frontier.append(gate)
120
+ return [case for case in ordered if str(case["id"]) in need]
code/src/stage1/smoke/startup_smoke.py ADDED
@@ -0,0 +1,1248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Startup fail-soft / offline robustness deterministic probes (separate process, zero real model budget).
3
+
4
+ Why it exists: spec §0.1.2/§7 require the agent to fail soft under a bad config, a corrupt
5
+ convention file, a missing directory, or no network -- warn and skip, start anyway, never a bare
6
+ `Traceback`, never a silent `exit 1`. Typical breakages -- a trailing comma wedging the parser, a
7
+ UTF-8 BOM crashing the parse -- blow up at construction/startup time, have nothing to do with the
8
+ model, and are deterministically decidable.
9
+
10
+ Mechanism: under a controlled temporary `HOME` (the bad-config fixture is written to
11
+ `~/.yuyao/config.json`) and controlled env, a child process constructs one session through the
12
+ §0.1.2 standard programmatic interface `yuyao.agent_api.create_session()` -- no model, no turn --
13
+ and reports `(std, ok, tb)`:
14
+ - std=False (build has no create_session): inconclusive, skipped (contract checks cover it);
15
+ - ok=True and tb=False: started with tolerance (PASS);
16
+ - tb=True (bare raise/traceback during construction): fail-soft violation (FAIL).
17
+
18
+ Zero false positives: the golden control (a valid config must start)
19
+ must PASS, and each bad-config case is judged against it, so FAIL only means "valid starts but
20
+ the bad config crashes". BOM / bad JSON / unknown key assert tolerant loading; the missing
21
+ directory case guards lazy startup without a model.
22
+
23
+ Usage: python startup_smoke.py <agent_dir> [--emit-json] | --selftest
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import re
30
+ import shlex
31
+ import shutil
32
+ import subprocess
33
+ import sys
34
+ import tempfile
35
+ from pathlib import Path
36
+
37
+ HERE = Path(__file__).resolve().parent
38
+ sys.path.insert(0, str(HERE))
39
+ import smoke_contract as SC # noqa: E402
40
+
41
+ RESULT_TAG = "STARTUP_RESULT="
42
+ _LAUNCHER_CHILD_RC = 73
43
+ _FAKE_OLD_ENTRY_RC = 86
44
+ _WRONG_ENTRY_RC = 87
45
+ _LAUNCHER_CHILD_TAG = "PROBE_LAUNCHER_CHILD_8B31"
46
+ _REQUIRES_PYTHON_RE = re.compile(
47
+ r"(?m)^\s*requires-python\s*=\s*[\"']([^\"']+)[\"']"
48
+ )
49
+ _PYTHON_CONTROL_ENV = (
50
+ "PYTHONPATH",
51
+ "PYTHONHOME",
52
+ "PYTHONSTARTUP",
53
+ "PYTHONINSPECT",
54
+ "PYTHONUSERBASE",
55
+ "PYTHONWARNINGS",
56
+ "PYTHONBREAKPOINT",
57
+ "PYTHONEXECUTABLE",
58
+ "__PYVENV_LAUNCHER__",
59
+ "YUYAO_PYTHON",
60
+ )
61
+
62
+ # Child: discover the standard create_session() contract, construct one session, catch any
63
+ # construction-time exception, and report (std, ok, tb).
64
+ _CHILD = '''
65
+ import os, sys, json, traceback
66
+ sys.path.insert(0, %(src)r)
67
+ # A flat layout (yuyao/ at the project root) must also be covered: §0.1.2 only requires that
68
+ # the package import, it does not prescribe a layout.
69
+ sys.path.insert(0, __import__("os").path.dirname(%(src)r))
70
+ import importlib as _il
71
+ def _find_std():
72
+ # "The module crashed at import because it read a bad config" must stay distinguishable from
73
+ # "the module does not exist at all": the first is precisely the fail-soft violation this layer
74
+ # exists to catch, and treating it as absent would report inconclusive (i.e. a pass). So only a
75
+ # genuinely absent module counts as "no interface"; every other exception is recorded as an
76
+ # import-time crash.
77
+ _imp_tb = None
78
+ for _mn in ("yuyao.agent_api","yuyao.d2a_api","yuyao.harness_api","agent_api"):
79
+ try:
80
+ _m = _il.import_module(_mn)
81
+ except ModuleNotFoundError as _e:
82
+ _nm = getattr(_e, "name", None)
83
+ if _nm and (_nm == _mn or _mn.startswith(_nm + ".")):
84
+ continue # the module genuinely does not exist
85
+ _imp_tb = traceback.format_exc() # its own dependency is missing => import-time crash
86
+ continue
87
+ except Exception:
88
+ _imp_tb = traceback.format_exc() # raised during import => import-time crash
89
+ continue
90
+ _f = getattr(_m, "create_session", None)
91
+ if callable(_f): return _f, None
92
+ return None, _imp_tb
93
+ _f, _imp_tb = _find_std()
94
+ res = {"std": _f is not None, "ok": False, "tb": False, "import_tb": _imp_tb is not None}
95
+ if _imp_tb:
96
+ sys.stderr.write(_imp_tb)
97
+ if _f is not None:
98
+ try:
99
+ _s = _f()
100
+ res["ok"] = True
101
+ try: _s.close()
102
+ except Exception: pass
103
+ except Exception:
104
+ res["tb"] = True
105
+ traceback.print_exc()
106
+ sys.stdout.write("\\n" + %(tag)r + json.dumps(res) + "\\n")
107
+ sys.stdout.flush()
108
+ '''
109
+
110
+
111
+ def _declared_python_floor(agent_dir: Path) -> tuple[int, int] | None:
112
+ """Read the artifact's own lower Python bound; do not invent one."""
113
+ path = agent_dir / "pyproject.toml"
114
+ if not path.is_file():
115
+ return None
116
+ try:
117
+ match = _REQUIRES_PYTHON_RE.search(path.read_text(encoding="utf-8"))
118
+ except (OSError, UnicodeError):
119
+ return None
120
+ if match is None:
121
+ return None
122
+ floors = [
123
+ (int(major), int(minor))
124
+ for major, minor in re.findall(
125
+ r"(?:^|,)\s*>=\s*(\d+)\.(\d+)", match.group(1)
126
+ )
127
+ ]
128
+ return max(floors) if floors else None
129
+
130
+
131
+ def _write_executable(path: Path, body: str) -> None:
132
+ path.write_text(body, encoding="utf-8")
133
+ path.chmod(0o700)
134
+
135
+
136
+ def _marker_lines(path: Path) -> list[str]:
137
+ if not path.is_file():
138
+ return []
139
+ try:
140
+ raw = path.read_bytes()
141
+ except OSError:
142
+ return ["<unreadable>"]
143
+ if len(raw) > 4096:
144
+ return ["<oversize>"]
145
+ try:
146
+ return raw.decode("utf-8").splitlines()
147
+ except UnicodeError:
148
+ return ["<non-utf8>"]
149
+
150
+
151
+ def _child_marker(path: Path) -> tuple[str, dict | None]:
152
+ if not path.is_file():
153
+ return "missing", None
154
+ try:
155
+ raw = path.read_bytes()
156
+ if len(raw) > 16384:
157
+ return "oversize", None
158
+ value = json.loads(raw.decode("utf-8"))
159
+ except (OSError, UnicodeError, json.JSONDecodeError):
160
+ return "invalid", None
161
+ return ("exact", value) if isinstance(value, dict) else ("invalid", None)
162
+
163
+
164
+ def _launcher_child_source(
165
+ marker: Path,
166
+ expected_entry: str,
167
+ expected_args: list[str],
168
+ ) -> str:
169
+ """Controlled replacement for entry.py: exact argv/env receipt + sentinel rc."""
170
+ return f'''#!/usr/bin/env python3
171
+ import json
172
+ import os
173
+ import sys
174
+
175
+ _expected_args = {expected_args!r}
176
+ _payload = {{
177
+ "tag": {_LAUNCHER_CHILD_TAG!r},
178
+ "entry_realpath": os.path.realpath(__file__),
179
+ "expected_entry": {expected_entry!r},
180
+ "argv": sys.argv[1:],
181
+ "argv_exact": sys.argv[1:] == _expected_args,
182
+ "python": [sys.version_info.major, sys.version_info.minor],
183
+ "pythonpath": os.environ.get("PYTHONPATH"),
184
+ "pythonhome": os.environ.get("PYTHONHOME"),
185
+ "sys_path": list(sys.path),
186
+ "prefix": os.path.realpath(sys.prefix),
187
+ "base_prefix": os.path.realpath(getattr(sys, "base_prefix", sys.prefix)),
188
+ }}
189
+ _data = json.dumps(_payload, sort_keys=True).encode("utf-8")
190
+ _fd = os.open({str(marker)!r}, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
191
+ try:
192
+ os.write(_fd, _data)
193
+ finally:
194
+ os.close(_fd)
195
+ raise SystemExit({_LAUNCHER_CHILD_RC})
196
+ '''
197
+
198
+
199
+ def _healthy_python_wrapper(
200
+ *,
201
+ real_python: str,
202
+ expected_entry: str,
203
+ entry_marker: Path,
204
+ probe_marker: Path,
205
+ wrong_marker: Path,
206
+ env_receipt: Path,
207
+ ) -> str:
208
+ """PATH tripwire that delegates probes and the exact controlled entry."""
209
+ values = {
210
+ "@@REAL@@": shlex.quote(real_python),
211
+ "@@ENTRY@@": shlex.quote(expected_entry),
212
+ "@@ENTRY_MARKER@@": shlex.quote(str(entry_marker)),
213
+ "@@PROBE_MARKER@@": shlex.quote(str(probe_marker)),
214
+ "@@WRONG_MARKER@@": shlex.quote(str(wrong_marker)),
215
+ "@@ENV_RECEIPT@@": shlex.quote(str(env_receipt)),
216
+ "@@WRONG_RC@@": str(_WRONG_ENTRY_RC),
217
+ }
218
+ body = r'''#!/bin/bash
219
+ set -u
220
+ REAL_PYTHON=@@REAL@@
221
+ EXPECTED_ENTRY=@@ENTRY@@
222
+ ENTRY_MARKER=@@ENTRY_MARKER@@
223
+ PROBE_MARKER=@@PROBE_MARKER@@
224
+ WRONG_MARKER=@@WRONG_MARKER@@
225
+ ENV_RECEIPT=@@ENV_RECEIPT@@
226
+ args=("$@")
227
+ i=0
228
+ while (( i < ${#args[@]} )); do
229
+ arg="${args[$i]}"
230
+ case "$arg" in
231
+ -E|-I|-s|-S|-B|-u|-O|-OO) ((i += 1)); continue ;;
232
+ -X|-W) ((i += 2)); continue ;;
233
+ -X*|-W*) ((i += 1)); continue ;;
234
+ -V|--version)
235
+ printf 'version\n' >> "$PROBE_MARKER"
236
+ exec "$REAL_PYTHON" "$@"
237
+ ;;
238
+ -c)
239
+ printf 'code\n' >> "$PROBE_MARKER"
240
+ exec "$REAL_PYTHON" "$@"
241
+ ;;
242
+ --) ((i += 1)); break ;;
243
+ -m)
244
+ printf 'module\n' >> "$WRONG_MARKER"
245
+ exit @@WRONG_RC@@
246
+ ;;
247
+ -*)
248
+ printf 'option:%s\n' "$arg" >> "$WRONG_MARKER"
249
+ exit @@WRONG_RC@@
250
+ ;;
251
+ *) break ;;
252
+ esac
253
+ done
254
+ if (( i >= ${#args[@]} )); then
255
+ printf 'missing-script\n' >> "$WRONG_MARKER"
256
+ exit @@WRONG_RC@@
257
+ fi
258
+ target="${args[$i]}"
259
+ if [[ "$target" = /* ]]; then
260
+ target_real="$(/usr/bin/readlink -f -- "$target" 2>/dev/null || true)"
261
+ else
262
+ target_real="$(/usr/bin/readlink -f -- "$PWD/$target" 2>/dev/null || true)"
263
+ fi
264
+ if [[ "$target_real" != "$EXPECTED_ENTRY" ]]; then
265
+ printf 'script:%s\n' "$target_real" >> "$WRONG_MARKER"
266
+ exit @@WRONG_RC@@
267
+ fi
268
+ printf 'entry\n' >> "$ENTRY_MARKER"
269
+ {
270
+ printf 'PYTHONPATH=%s\n' "${PYTHONPATH-<unset>}"
271
+ printf 'PYTHONHOME=%s\n' "${PYTHONHOME-<unset>}"
272
+ } >> "$ENV_RECEIPT"
273
+ exec "$REAL_PYTHON" "$@"
274
+ '''
275
+ for old, new in values.items():
276
+ body = body.replace(old, new)
277
+ return body
278
+
279
+
280
+ def _old_python_wrapper(
281
+ *,
282
+ fake_version: tuple[int, int],
283
+ expected_entry: str,
284
+ probe_marker: Path,
285
+ entry_marker: Path,
286
+ other_marker: Path,
287
+ ) -> str:
288
+ """Fake old python3: truthful version probe, poison if used for entry."""
289
+ version = f"{fake_version[0]}.{fake_version[1]}.0"
290
+ values = {
291
+ "@@VERSION@@": shlex.quote(version),
292
+ "@@ENTRY@@": shlex.quote(expected_entry),
293
+ "@@PROBE_MARKER@@": shlex.quote(str(probe_marker)),
294
+ "@@ENTRY_MARKER@@": shlex.quote(str(entry_marker)),
295
+ "@@OTHER_MARKER@@": shlex.quote(str(other_marker)),
296
+ "@@OLD_RC@@": str(_FAKE_OLD_ENTRY_RC),
297
+ }
298
+ body = r'''#!/bin/bash
299
+ set -u
300
+ FAKE_VERSION=@@VERSION@@
301
+ EXPECTED_ENTRY=@@ENTRY@@
302
+ PROBE_MARKER=@@PROBE_MARKER@@
303
+ ENTRY_MARKER=@@ENTRY_MARKER@@
304
+ OTHER_MARKER=@@OTHER_MARKER@@
305
+ args=("$@")
306
+ i=0
307
+ while (( i < ${#args[@]} )); do
308
+ arg="${args[$i]}"
309
+ case "$arg" in
310
+ -E|-I|-s|-S|-B|-u|-O|-OO) ((i += 1)); continue ;;
311
+ -X|-W) ((i += 2)); continue ;;
312
+ -X*|-W*) ((i += 1)); continue ;;
313
+ -V|--version)
314
+ printf 'version\n' >> "$PROBE_MARKER"
315
+ printf 'Python %s\n' "$FAKE_VERSION"
316
+ exit 0
317
+ ;;
318
+ -c)
319
+ code="${args[$((i + 1))]:-}"
320
+ if [[ "$code" == *version* || "$code" == *VERSION* || "$code" == *hexversion* ]]; then
321
+ printf 'version\n' >> "$PROBE_MARKER"
322
+ if [[ "$code" == *print* && "$code" != *xit* && "$code" != *assert* ]]; then
323
+ printf '%s\n' "$FAKE_VERSION"
324
+ exit 0
325
+ fi
326
+ exit 1
327
+ fi
328
+ printf 'code\n' >> "$OTHER_MARKER"
329
+ exit 88
330
+ ;;
331
+ --) ((i += 1)); break ;;
332
+ -m)
333
+ printf 'module\n' >> "$OTHER_MARKER"
334
+ exit 88
335
+ ;;
336
+ -*) printf 'option:%s\n' "$arg" >> "$OTHER_MARKER"; exit 88 ;;
337
+ *) break ;;
338
+ esac
339
+ done
340
+ if (( i >= ${#args[@]} )); then
341
+ printf 'missing-script\n' >> "$OTHER_MARKER"
342
+ exit 88
343
+ fi
344
+ target="${args[$i]}"
345
+ if [[ "$target" = /* ]]; then
346
+ target_real="$(/usr/bin/readlink -f -- "$target" 2>/dev/null || true)"
347
+ else
348
+ target_real="$(/usr/bin/readlink -f -- "$PWD/$target" 2>/dev/null || true)"
349
+ fi
350
+ if [[ "$target_real" = "$EXPECTED_ENTRY" ]]; then
351
+ printf 'entry\n' >> "$ENTRY_MARKER"
352
+ else
353
+ printf 'script:%s\n' "$target_real" >> "$OTHER_MARKER"
354
+ fi
355
+ exit @@OLD_RC@@
356
+ '''
357
+ for old, new in values.items():
358
+ body = body.replace(old, new)
359
+ return body
360
+
361
+
362
+ def _launcher_scenario(
363
+ agent_dir: Path,
364
+ root: Path,
365
+ scenario: str,
366
+ floor: tuple[int, int] | None,
367
+ timeout: int,
368
+ ) -> dict:
369
+ """Run one copied launcher against controlled entry/PATH/environment tripwires."""
370
+ fixture = root / "artifact"
371
+ shutil.copytree(agent_dir, fixture, symlinks=True)
372
+ launcher = fixture / "run_agent.sh"
373
+ entry = fixture / "entry.py"
374
+ if entry.exists() or entry.is_symlink():
375
+ entry.unlink()
376
+ entry.parent.mkdir(parents=True, exist_ok=True)
377
+
378
+ obs = root / "obs"
379
+ bin_dir = root / "bin"
380
+ home = root / "home"
381
+ tmp = root / "tmp"
382
+ cwd = root / "caller-cwd"
383
+ repo = root / "repo"
384
+ out_dir = root / "out"
385
+ for path in (obs, bin_dir, home, tmp, cwd, repo, out_dir):
386
+ path.mkdir(parents=True, exist_ok=True)
387
+ task = root / "task.json"
388
+ budget = root / "budget.json"
389
+ task.write_text(
390
+ '{"task_id":"probe-launcher","problem_statement":"controlled startup"}\n',
391
+ encoding="utf-8",
392
+ )
393
+ budget.write_text('{"max_steps":1}\n', encoding="utf-8")
394
+ expected_args = [
395
+ "--task-file", str(task),
396
+ "--repo-dir", str(repo),
397
+ "--model-base-url", "http://127.0.0.1:9",
398
+ "--model-name", "probe-launcher-model",
399
+ "--model-api-key", "probe-launcher-key",
400
+ "--budget-file", str(budget),
401
+ "--out-dir", str(out_dir),
402
+ ]
403
+ expected_entry = str(entry.resolve())
404
+ child_path = obs / "child.json"
405
+ entry.write_text(
406
+ _launcher_child_source(child_path, expected_entry, expected_args),
407
+ encoding="utf-8",
408
+ )
409
+ entry.chmod(0o600)
410
+
411
+ healthy_entry = obs / "healthy-entry.log"
412
+ healthy_probe = obs / "healthy-probe.log"
413
+ healthy_wrong = obs / "healthy-wrong.log"
414
+ healthy_env = obs / "healthy-env.log"
415
+ old_probe = obs / "old-probe.log"
416
+ old_entry = obs / "old-entry.log"
417
+ old_other = obs / "old-other.log"
418
+ ambient_marker = obs / "ambient-site.log"
419
+
420
+ healthy = _healthy_python_wrapper(
421
+ real_python=sys.executable,
422
+ expected_entry=expected_entry,
423
+ entry_marker=healthy_entry,
424
+ probe_marker=healthy_probe,
425
+ wrong_marker=healthy_wrong,
426
+ env_receipt=healthy_env,
427
+ )
428
+ _write_executable(bin_dir / "python", healthy)
429
+ if scenario == "old-python3":
430
+ if floor is None:
431
+ raise RuntimeError("old-python3 scenario requires a declared floor")
432
+ fake_version = (
433
+ (floor[0], floor[1] - 1)
434
+ if floor[1] > 0
435
+ else (max(0, floor[0] - 1), 99)
436
+ )
437
+ _write_executable(
438
+ bin_dir / "python3",
439
+ _old_python_wrapper(
440
+ fake_version=fake_version,
441
+ expected_entry=expected_entry,
442
+ probe_marker=old_probe,
443
+ entry_marker=old_entry,
444
+ other_marker=old_other,
445
+ ),
446
+ )
447
+ else:
448
+ fake_version = None
449
+ _write_executable(bin_dir / "python3", healthy)
450
+
451
+ env = _startup_env(str(home), str(root))
452
+ for key in _PYTHON_CONTROL_ENV:
453
+ env.pop(key, None)
454
+ env["PATH"] = str(bin_dir) + os.pathsep + env.get("PATH", os.defpath)
455
+
456
+ poison_selftest = True
457
+ poison_detail = ""
458
+ poison_path = ""
459
+ poison_home = ""
460
+ if scenario == "ambient-path":
461
+ poison_dir = root / "ambient-pythonpath"
462
+ poison_dir.mkdir()
463
+ poison_path = str(poison_dir)
464
+ (poison_dir / "sitecustomize.py").write_text(
465
+ "import os\n"
466
+ f"_fd=os.open({str(ambient_marker)!r},"
467
+ "os.O_WRONLY|os.O_CREAT|os.O_APPEND,0o600)\n"
468
+ "os.write(_fd,b'sitecustomize\\n')\n"
469
+ "os.close(_fd)\n",
470
+ encoding="utf-8",
471
+ )
472
+ env["PYTHONPATH"] = poison_path
473
+ proof = subprocess.run(
474
+ [sys.executable, "-c", "pass"],
475
+ cwd=str(cwd),
476
+ env=env,
477
+ capture_output=True,
478
+ text=True,
479
+ timeout=10,
480
+ )
481
+ poison_selftest = (
482
+ proof.returncode == 0
483
+ and _marker_lines(ambient_marker) == ["sitecustomize"]
484
+ )
485
+ poison_detail = f"path-proof-rc={proof.returncode}"
486
+ ambient_marker.unlink(missing_ok=True)
487
+ elif scenario == "ambient-home":
488
+ poison_home_path = root / "ambient-pythonhome"
489
+ poison_home_path.mkdir()
490
+ poison_home = str(poison_home_path)
491
+ proof_marker = obs / "home-proof.log"
492
+ env["PYTHONHOME"] = poison_home
493
+ proof = subprocess.run(
494
+ [
495
+ sys.executable,
496
+ "-c",
497
+ f"open({str(proof_marker)!r},'w').write('ran')",
498
+ ],
499
+ cwd=str(cwd),
500
+ env=env,
501
+ capture_output=True,
502
+ text=True,
503
+ timeout=10,
504
+ )
505
+ poison_selftest = proof.returncode != 0 and not proof_marker.exists()
506
+ poison_detail = f"home-proof-rc={proof.returncode}"
507
+
508
+ row = {
509
+ "scenario": scenario,
510
+ "expected_entry": expected_entry,
511
+ "expected_args": expected_args,
512
+ "floor": list(floor) if floor else None,
513
+ "fake_version": list(fake_version) if fake_version else None,
514
+ "poison_selftest": poison_selftest,
515
+ "poison_detail": poison_detail,
516
+ "poison_path": poison_path,
517
+ "poison_home": poison_home,
518
+ "timed_out": False,
519
+ "fixture_error": "",
520
+ }
521
+ if not poison_selftest:
522
+ row["fixture_error"] = "AMBIENT_POISON_SELFTEST_FAILED"
523
+ elif not launcher.is_file():
524
+ row["fixture_error"] = "RUN_AGENT_MISSING_AFTER_COPY"
525
+ else:
526
+ try:
527
+ proc = subprocess.run(
528
+ ["/bin/bash", str(launcher), *expected_args],
529
+ cwd=str(cwd),
530
+ env=env,
531
+ stdin=subprocess.DEVNULL,
532
+ capture_output=True,
533
+ text=True,
534
+ timeout=timeout,
535
+ )
536
+ row["rc"] = proc.returncode
537
+ row["stdout"] = (proc.stdout or "")[-2000:]
538
+ row["stderr"] = (proc.stderr or "")[-2000:]
539
+ except subprocess.TimeoutExpired as exc:
540
+ row["timed_out"] = True
541
+ row["rc"] = None
542
+ row["stdout"] = (
543
+ exc.stdout.decode(errors="replace")
544
+ if isinstance(exc.stdout, bytes)
545
+ else (exc.stdout or "")
546
+ )[-2000:]
547
+ row["stderr"] = (
548
+ exc.stderr.decode(errors="replace")
549
+ if isinstance(exc.stderr, bytes)
550
+ else (exc.stderr or "")
551
+ )[-2000:]
552
+ except OSError as exc:
553
+ row["fixture_error"] = f"LAUNCH_OSERROR:{type(exc).__name__}"
554
+ row["rc"] = None
555
+ marker_state, child = _child_marker(child_path)
556
+ row.update(
557
+ {
558
+ "child_marker_state": marker_state,
559
+ "child": child,
560
+ "healthy_entry": _marker_lines(healthy_entry),
561
+ "healthy_probe": _marker_lines(healthy_probe),
562
+ "healthy_wrong": _marker_lines(healthy_wrong),
563
+ "healthy_env": _marker_lines(healthy_env),
564
+ "old_probe": _marker_lines(old_probe),
565
+ "old_entry": _marker_lines(old_entry),
566
+ "old_other": _marker_lines(old_other),
567
+ "ambient_marker": _marker_lines(ambient_marker),
568
+ }
569
+ )
570
+ return row
571
+
572
+
573
+ def _run_launcher_probe(agent_dir: Path, case: dict) -> tuple[dict, str]:
574
+ kind = str(case["launcher_probe"])
575
+ floor = _declared_python_floor(agent_dir)
576
+ res = {
577
+ "driver_error": "",
578
+ "cleanup_complete": True,
579
+ "unobservable": "",
580
+ "declared_floor": list(floor) if floor else None,
581
+ "scenarios": {},
582
+ }
583
+ if not (agent_dir / "run_agent.sh").is_file() or not (agent_dir / "entry.py").is_file():
584
+ res["unobservable"] = "artifact lacks run_agent.sh or entry.py"
585
+ return res, ""
586
+ names = {
587
+ "control": ("healthy",),
588
+ "python-floor": ("old-python3",) if floor else (),
589
+ "ambient-python": ("ambient-path", "ambient-home"),
590
+ }.get(kind)
591
+ if names is None:
592
+ res["driver_error"] = f"unknown launcher probe kind: {kind}"
593
+ return res, ""
594
+ root = Path(tempfile.mkdtemp(prefix="startup_launcher_"))
595
+ try:
596
+ for name in names:
597
+ res["scenarios"][name] = _launcher_scenario(
598
+ agent_dir,
599
+ root / name,
600
+ name,
601
+ floor,
602
+ int(case.get("timeout", 25)),
603
+ )
604
+ except Exception as exc: # noqa: BLE001
605
+ res["driver_error"] = f"{type(exc).__name__}: {exc}"
606
+ finally:
607
+ try:
608
+ shutil.rmtree(root)
609
+ except OSError:
610
+ res["cleanup_complete"] = False
611
+ err = "\n".join(
612
+ str(row.get("stderr") or "")
613
+ for row in res["scenarios"].values()
614
+ if row.get("stderr")
615
+ )
616
+ return res, err
617
+
618
+
619
+ def _launcher_probe_error(res: dict | None) -> str:
620
+ if not isinstance(res, dict):
621
+ return "launcher probe did not return an observation"
622
+ if res.get("driver_error"):
623
+ return f"launcher driver error: {res['driver_error']}"
624
+ if not res.get("cleanup_complete"):
625
+ return "launcher fixture cleanup incomplete"
626
+ fixture_errors = [
627
+ f"{name}:{row.get('fixture_error')}"
628
+ for name, row in (res.get("scenarios") or {}).items()
629
+ if row.get("fixture_error")
630
+ ]
631
+ return ", ".join(fixture_errors)
632
+
633
+
634
+ def _exact_launcher_entry(row: dict) -> bool:
635
+ child = row.get("child")
636
+ return bool(
637
+ not row.get("timed_out")
638
+ and row.get("rc") == _LAUNCHER_CHILD_RC
639
+ and row.get("child_marker_state") == "exact"
640
+ and isinstance(child, dict)
641
+ and child.get("tag") == _LAUNCHER_CHILD_TAG
642
+ and child.get("entry_realpath") == row.get("expected_entry")
643
+ and child.get("expected_entry") == row.get("expected_entry")
644
+ and child.get("argv_exact") is True
645
+ and child.get("argv") == row.get("expected_args")
646
+ )
647
+
648
+
649
+ def chk_launcher_health_control(res, _err):
650
+ """Zero-weight control: PATH-selected launcher reaches exact entry and rc."""
651
+ error = _launcher_probe_error(res)
652
+ if error:
653
+ return False, error, "error"
654
+ if res.get("unobservable"):
655
+ return True, f"inconclusive: {res['unobservable']}", "na"
656
+ row = (res.get("scenarios") or {}).get("healthy")
657
+ if not isinstance(row, dict):
658
+ return False, "healthy launcher scenario missing", "error"
659
+ exact = _exact_launcher_entry(row)
660
+ path_seen = row.get("healthy_entry") == ["entry"]
661
+ wrong = row.get("healthy_wrong") or []
662
+ if exact and not path_seen:
663
+ return (
664
+ True,
665
+ "inconclusive: the launcher reaches the exact entry but bypasses the PATH tripwire, "
666
+ "so the interpreter selection strategy cannot be attributed",
667
+ "na",
668
+ )
669
+ ok = exact and path_seen and not wrong
670
+ return (
671
+ ok,
672
+ f"exact entry={exact} healthy interpreter on PATH={path_seen} wrong={wrong} "
673
+ f"rc={row.get('rc')} (control must forward all seven arguments exactly and propagate the child rc)",
674
+ "pass" if ok else "fail",
675
+ )
676
+
677
+
678
+ def chk_launcher_python_minimum_fallback(res, _err):
679
+ """Reject a fake old python3, then use the healthy fallback."""
680
+ error = _launcher_probe_error(res)
681
+ if error:
682
+ return False, error, "error"
683
+ if res.get("unobservable"):
684
+ return True, f"inconclusive: {res['unobservable']}", "na"
685
+ floor = res.get("declared_floor")
686
+ if not (
687
+ isinstance(floor, list)
688
+ and len(floor) == 2
689
+ and all(isinstance(value, int) for value in floor)
690
+ ):
691
+ return (
692
+ True,
693
+ "inconclusive: the artifact declares no parsable requires-python >=X.Y lower bound",
694
+ "na",
695
+ )
696
+ row = (res.get("scenarios") or {}).get("old-python3")
697
+ if not isinstance(row, dict):
698
+ return False, "old-python3 scenario missing", "error"
699
+ child = row.get("child") if isinstance(row.get("child"), dict) else {}
700
+ child_version = child.get("python")
701
+ old_probed = bool(row.get("old_probe")) and set(row["old_probe"]) == {"version"}
702
+ old_never_entered = not row.get("old_entry")
703
+ healthy_entered = row.get("healthy_entry") == ["entry"]
704
+ floor_met = (
705
+ isinstance(child_version, list)
706
+ and len(child_version) == 2
707
+ and tuple(child_version) >= tuple(floor)
708
+ )
709
+ exact = _exact_launcher_entry(row)
710
+ ok = bool(
711
+ old_probed
712
+ and old_never_entered
713
+ and healthy_entered
714
+ and floor_met
715
+ and exact
716
+ and not row.get("healthy_wrong")
717
+ and not row.get("old_other")
718
+ )
719
+ return (
720
+ ok,
721
+ f"declared floor={floor} fake version={row.get('fake_version')} version probed={old_probed} "
722
+ f"fake old reached entry={not old_never_entered} healthy fallback={healthy_entered} "
723
+ f"child version={child_version} exact entry/rc={exact}",
724
+ "pass" if ok else "fail",
725
+ )
726
+
727
+
728
+ def _path_is_within(value: object, root: str) -> bool:
729
+ if not isinstance(value, str) or not root:
730
+ return False
731
+ try:
732
+ return os.path.commonpath([os.path.realpath(value), os.path.realpath(root)]) == os.path.realpath(root)
733
+ except (OSError, ValueError):
734
+ return False
735
+
736
+
737
+ def chk_launcher_ambient_python_isolated(res, _err):
738
+ """PYTHONPATH and PYTHONHOME stimuli cannot affect entry startup."""
739
+ error = _launcher_probe_error(res)
740
+ if error:
741
+ return False, error, "error"
742
+ if res.get("unobservable"):
743
+ return True, f"inconclusive: {res['unobservable']}", "na"
744
+ rows = res.get("scenarios") or {}
745
+ path_row = rows.get("ambient-path")
746
+ home_row = rows.get("ambient-home")
747
+ if not isinstance(path_row, dict) or not isinstance(home_row, dict):
748
+ return False, "ambient path/home scenarios missing", "error"
749
+ path_child = (
750
+ path_row.get("child")
751
+ if isinstance(path_row.get("child"), dict)
752
+ else {}
753
+ )
754
+ home_child = (
755
+ home_row.get("child")
756
+ if isinstance(home_row.get("child"), dict)
757
+ else {}
758
+ )
759
+ poison_path = str(path_row.get("poison_path") or "")
760
+ path_absent = all(
761
+ not _path_is_within(value, poison_path)
762
+ for value in (path_child.get("sys_path") or [])
763
+ )
764
+ path_clean = (
765
+ _exact_launcher_entry(path_row)
766
+ and path_row.get("healthy_entry") == ["entry"]
767
+ and not path_row.get("healthy_wrong")
768
+ and not path_row.get("ambient_marker")
769
+ and path_absent
770
+ )
771
+ poison_home = str(home_row.get("poison_home") or "")
772
+ home_clean = (
773
+ _exact_launcher_entry(home_row)
774
+ and home_row.get("healthy_entry") == ["entry"]
775
+ and not home_row.get("healthy_wrong")
776
+ and not _path_is_within(home_child.get("prefix"), poison_home)
777
+ and not _path_is_within(home_child.get("base_prefix"), poison_home)
778
+ )
779
+ proofs = bool(path_row.get("poison_selftest") and home_row.get("poison_selftest"))
780
+ ok = proofs and path_clean and home_clean
781
+ return (
782
+ ok,
783
+ f"poison selftest={proofs} PYTHONPATH:entry={_exact_launcher_entry(path_row)} "
784
+ f"site-marker={path_row.get('ambient_marker')} sys.path isolated={path_absent}; "
785
+ f"PYTHONHOME:entry={_exact_launcher_entry(home_row)} "
786
+ f"prefix={home_child.get('prefix')!r} poison={poison_home!r}",
787
+ "pass" if ok else "fail",
788
+ )
789
+
790
+
791
+ def chk_starts_clean(res, err):
792
+ if res is None:
793
+ return False, f"the child process reported no result (crash or timeout) err={err[-160:]!r}"
794
+ if res.get("import_tb"):
795
+ # The module blew up at import time. This is not "the interface is missing" but the very
796
+ # fail-soft violation this layer targets (typically: reading ~/.yuyao/config.json during
797
+ # import and raising on a BOM or bad JSON).
798
+ return False, ("crashed at import time: the module exists but raised while importing "
799
+ "(traceback on stderr). A bad config must warn and skip, never crash on import.")
800
+ if not res.get("std"):
801
+ return True, ("inconclusive: this build exposes no standard create_session interface -> skipped "
802
+ "(covered separately by contract validation)")
803
+ ok = bool(res.get("ok")) and not res.get("tb")
804
+ return ok, (f"fault-tolerant startup succeeded={res.get('ok')} construction-time traceback={res.get('tb')} "
805
+ f"(a bad config or missing directory must warn and skip, never raise during construction)")
806
+
807
+
808
+ # ---- case table (standalone startup probes; config = content written to
809
+ # ~/.yuyao/config.json, None = write nothing) ----
810
+ CASES = [
811
+ # Syntactically invalid JSON (trailing comma / bad schema) -> must fall back to defaults or
812
+ # report clearly, never crash bare during construction.
813
+ dict(id="startup_broken_config_file", config='{"yolo": true,, }', check=chk_starts_clean),
814
+ # Valid JSON with a UTF-8 BOM -> the BOM must be stripped or tolerated, not crash the parse.
815
+ dict(id="startup_bom_config", config='\ufeff{"yolo": true}', check=chk_starts_clean),
816
+
817
+ # Probe - launcher exact-template control (zero weight).
818
+ # The artifact's run_agent.sh is copied to a fresh root with entry.py replaced by a controlled
819
+ # startup child. The healthy python tripwire on PATH must see the exact sibling entry.py, the
820
+ # child must receive the seven arguments in order, write a unique JSON marker, and exit with
821
+ # sentinel rc=73, which the launcher must pass through unchanged. A launcher using an absolute
822
+ # interpreter that bypasses PATH only scores NA -- it cannot attribute the two PATH/env cases below.
823
+ dict(id="launcher_health_control", launcher_probe="control",
824
+ timeout=25, formal_status=True, blocking=False,
825
+ check=chk_launcher_health_control),
826
+
827
+ # launcher_python_minimum_fallback
828
+ # Spec anchor: §0.1.1 - run_agent.sh is the root delivery entry point and carries the
829
+ # seven-argument public calling surface.
830
+ # Truth table:
831
+ # control: the previous case proves a healthy PATH interpreter closes the loop on exact
832
+ # entry/argv/marker/rc;
833
+ # target: read the artifact's own declared requires-python >=X.Y from pyproject.toml. First on
834
+ # PATH is `python3`, an executable but fake-old interpreter; `python` is the healthy fallback.
835
+ # The version probe must hit the fake-old one but must never enter entry; the healthy
836
+ # interpreter must then run the exact entry, satisfy the declared floor, and produce the exact
837
+ # child marker and rc=73;
838
+ # mutant: only does `command -v` / takes the first python3 by name, enters the fake-old entry
839
+ # directly and exits rc=86;
840
+ # NA: no parseable requires-python floor, or the control shows the launcher does not go through
841
+ # PATH -- neither is observable;
842
+ # ERROR: tripwire/poison self-proof, result protocol, or cleanup failure.
843
+ dict(id="launcher_python_minimum_fallback", launcher_probe="python-floor",
844
+ timeout=25, formal_status=True, gate="launcher_health_control",
845
+ check=chk_launcher_python_minimum_fallback),
846
+
847
+ # launcher_ambient_python_isolated
848
+ # Spec anchor: §0.1.1 - run_agent.sh is the root delivery entry point and carries the
849
+ # seven-argument public calling surface.
850
+ # Truth table:
851
+ # control: the same healthy launcher with exact entry/argv/marker/rc;
852
+ # target-A: a hostile PYTHONPATH whose sitecustomize first self-proves (under a bare healthy
853
+ # interpreter) that it does write a marker. Through the launcher the marker must be absent,
854
+ # the poisoned path must not reach the child's sys.path, and the child rc must be exactly 73;
855
+ # target-B: a PYTHONHOME with no stdlib first self-proves it blocks a bare interpreter. Through
856
+ # the launcher the child must still run under the healthy prefix and pass rc=73 through.
857
+ # Unsetting, replacing with a controlled value, or isolating with -E/-I are all accepted;
858
+ # mutant: prepends its own src but keeps the ambient PYTHONPATH, or inherits PYTHONHOME as-is;
859
+ # NA/ERROR: from an unobservable shared control, or fixture self-proof/protocol/cleanup failure.
860
+ # Never decided from stderr keywords.
861
+ dict(id="launcher_ambient_python_isolated", launcher_probe="ambient-python",
862
+ timeout=25, formal_status=True, gate="launcher_health_control",
863
+ check=chk_launcher_ambient_python_isolated),
864
+ ]
865
+
866
+
867
+ def _startup_env(home: str, workdir: str, extra: dict | None = None) -> dict[str, str]:
868
+ """Build a deterministic child environment without inheriting host config."""
869
+ allowed = ("PATH", "PYTHONPATH", "LD_LIBRARY_PATH", "VIRTUAL_ENV", "SYSTEMROOT")
870
+ env = {key: os.environ[key] for key in allowed if os.environ.get(key)}
871
+ env.update(
872
+ {
873
+ "HOME": home,
874
+ "XDG_CONFIG_HOME": os.path.join(home, ".config"),
875
+ "TMPDIR": os.path.join(workdir, "tmp"),
876
+ "MSWEA_SILENT_STARTUP": "1",
877
+ "LANG": "C.UTF-8",
878
+ "LC_ALL": "C.UTF-8",
879
+ "TZ": "UTC",
880
+ "PYTHONHASHSEED": "0",
881
+ "D2A_WORKER_ID": "0",
882
+ "D2A_SEED": "20260817",
883
+ }
884
+ )
885
+ env.update({str(key): str(value) for key, value in (extra or {}).items()})
886
+ env.pop("YUYAO_HOME", None)
887
+ env.pop("YUYAO_CONFIG", None)
888
+ for key in list(env):
889
+ if key.lower() in {
890
+ "http_proxy",
891
+ "https_proxy",
892
+ "all_proxy",
893
+ "no_proxy",
894
+ }:
895
+ env.pop(key, None)
896
+ return env
897
+
898
+
899
+ def _checked_case_result(case: dict, res: dict | None, err: str) -> dict:
900
+ status = None
901
+ try:
902
+ outcome = case["check"](res, err)
903
+ if isinstance(outcome, tuple) and len(outcome) == 3:
904
+ ok, why, status = outcome
905
+ else:
906
+ ok, why = outcome
907
+ except Exception as exc: # noqa: BLE001
908
+ ok, why = False, f"runner error: {exc!r}"
909
+ if case.get("formal_status"):
910
+ status = "error"
911
+ row = {
912
+ "id": case["id"],
913
+ "ok": ok,
914
+ "blocking": case.get("blocking", True),
915
+ "why": why,
916
+ }
917
+ if status is not None:
918
+ row["status"] = status
919
+ return row
920
+
921
+
922
+ def _run_one(agent_dir: Path, case: dict) -> dict:
923
+ if case.get("launcher_probe"):
924
+ res, err = _run_launcher_probe(agent_dir, case)
925
+ return _checked_case_result(case, res, err)
926
+ # A TIMEOUT is retried once (in a fresh workdir) to shed load noise: false timeouts caused by
927
+ # heavy concurrency, a stalled env, or litellm's slow import (~20s) usually complete on retry,
928
+ # so healthy builds are not failed spuriously. A genuine hang times out both times and FAILs.
929
+ # Retrying alone is not enough under load, so the default budget is 120s rather than 30s:
930
+ # litellm's import alone costs ~20s, which puts a 30s budget right at the edge during batch
931
+ # runs. A real startup hang stays hung and is caught by any budget, so the larger budget only
932
+ # removes noise without losing discriminating power.
933
+ code = _CHILD % {"src": str((agent_dir / "src").resolve()), "tag": RESULT_TAG}
934
+ out = err = None
935
+ timed_out = True
936
+ for _attempt in range(2):
937
+ workdir = tempfile.mkdtemp(prefix="startup_smoke_")
938
+ tripwire_requests: list[dict] = []
939
+ home = os.path.join(workdir, "home")
940
+ os.makedirs(home, exist_ok=True)
941
+ os.makedirs(os.path.join(workdir, "tmp"), exist_ok=True)
942
+ cfg = case.get("config")
943
+ if cfg is not None:
944
+ cdir = os.path.join(home, ".yuyao")
945
+ os.makedirs(cdir, exist_ok=True)
946
+ with open(os.path.join(cdir, "config.json"), "w", encoding="utf-8") as f:
947
+ f.write(cfg)
948
+ # home_files: seed plain FILES at arbitrary relative paths under HOME (`config=` can only
949
+ # write config.json), e.g. a file where the build expects to mkdir a state directory:
950
+ # `mkdir(exist_ok=True)` only tolerates an existing DIRECTORY. When omitted nothing runs.
951
+ for rel, body in ({}).items():
952
+ fp = os.path.join(home, rel)
953
+ os.makedirs(os.path.dirname(fp), exist_ok=True)
954
+ with open(fp, "w", encoding="utf-8") as f:
955
+ f.write(body)
956
+ extra_env = dict({})
957
+ env = _startup_env(home, workdir, extra_env)
958
+ try:
959
+ r = subprocess.run([sys.executable, "-c", code], cwd=workdir, env=env,
960
+ capture_output=True, text=True, timeout=case.get("timeout", 120))
961
+ out, err = (r.stdout or ""), (r.stderr or "")
962
+ child_rc = r.returncode
963
+ timed_out = False
964
+ break
965
+ except subprocess.TimeoutExpired:
966
+ timed_out = True
967
+ continue
968
+ finally:
969
+ shutil.rmtree(workdir, ignore_errors=True)
970
+ if timed_out:
971
+ return {"id": case["id"], "ok": False, "blocking": case.get("blocking", True),
972
+ "why": "construction did not finish within the time limit (still timing out after a retry, "
973
+ "which suggests the startup path hangs)"}
974
+ res = None
975
+ for ln in out.splitlines():
976
+ if ln.startswith(RESULT_TAG):
977
+ try:
978
+ res = json.loads(ln[len(RESULT_TAG):])
979
+ except Exception:
980
+ res = None
981
+ if isinstance(res, dict):
982
+ res["startup_request_count"] = len(tripwire_requests)
983
+ res["child_rc"] = child_rc
984
+ return _checked_case_result(case, res, err)
985
+
986
+
987
+ def _selected_cases(cases: list) -> list:
988
+ """When `D2A_ONLY_IDS` (comma-separated) is non-empty, run only those cases; unset means run
989
+ everything with bit-identical behaviour.
990
+
991
+ Lets a single case be re-tested on its own without running the whole layer.
992
+ A filtered run is NOT a complete score: the `D2A_ONLY_ACTIVE` line is the explicit marker for the
993
+ merge tooling, and without it the results must not be merged as an increment.
994
+ """
995
+ only = {s.strip() for s in (os.environ.get("D2A_ONLY_IDS") or "").split(",") if s.strip()}
996
+ if not only:
997
+ return list(cases)
998
+ picked = SC.dependency_closure(cases, only)
999
+ need = {c["id"] for c in picked}
1000
+ print(f"D2A_ONLY_ACTIVE={len(picked)}/{len(cases)} ids={sorted(only)[:12]} "
1001
+ f"gates+={sorted(need - only)[:8]}", flush=True)
1002
+ return picked
1003
+
1004
+
1005
+ def run_smoke(agent_dir: Path) -> list:
1006
+ from concurrent.futures import ThreadPoolExecutor
1007
+ _w = max(1, int(os.environ.get("D2A_STARTUP_WORKERS", "6") or "6"))
1008
+ cases = _selected_cases(CASES)
1009
+ results = {}
1010
+ with ThreadPoolExecutor(max_workers=_w) as ex:
1011
+ futs = {ex.submit(_run_one, agent_dir, c): c["id"] for c in cases}
1012
+ for fut in futs:
1013
+ r = fut.result()
1014
+ results[r["id"]] = r
1015
+ return SC.apply_gates(cases, (results[c["id"]] for c in cases))
1016
+
1017
+
1018
+ def _write_synthetic_launcher(agent_dir: Path, mode: str) -> None:
1019
+ """Small offline launcher fixtures for the Probe truth table."""
1020
+ (agent_dir / "src" / "yuyao").mkdir(parents=True)
1021
+ (agent_dir / "entry.py").write_text("raise SystemExit(99)\n", encoding="utf-8")
1022
+ (agent_dir / "pyproject.toml").write_text(
1023
+ '[project]\nname="probe-fixture"\nversion="0"\n'
1024
+ 'requires-python=">=3.10"\n',
1025
+ encoding="utf-8",
1026
+ )
1027
+ prelude = (
1028
+ "#!/bin/bash\n"
1029
+ "set -u\n"
1030
+ 'HERE="$(cd "$(dirname "$0")" && pwd)"\n'
1031
+ )
1032
+ checked = (
1033
+ 'for candidate in python3 python; do\n'
1034
+ ' if command -v "$candidate" >/dev/null 2>&1 && '
1035
+ '"$candidate" -c \'import sys; '
1036
+ 'raise SystemExit(0 if sys.version_info >= (3, 10) else 1)\' '
1037
+ '>/dev/null 2>&1; then\n'
1038
+ ' exec "$candidate" "$HERE/entry.py" "$@"\n'
1039
+ " fi\n"
1040
+ "done\n"
1041
+ "exit 1\n"
1042
+ )
1043
+ if mode == "correct":
1044
+ body = prelude + "unset PYTHONPATH PYTHONHOME\n" + checked
1045
+ elif mode == "no-version":
1046
+ body = (
1047
+ prelude
1048
+ + "unset PYTHONPATH PYTHONHOME\n"
1049
+ + 'exec python3 "$HERE/entry.py" "$@"\n'
1050
+ )
1051
+ elif mode == "ambient-mutant":
1052
+ body = prelude + checked
1053
+ elif mode == "noop":
1054
+ body = prelude + f"exit {_LAUNCHER_CHILD_RC}\n"
1055
+ else:
1056
+ raise ValueError(mode)
1057
+ _write_executable(agent_dir / "run_agent.sh", body)
1058
+
1059
+
1060
+ def _selftest() -> bool:
1061
+ """Offline truth table: correct, two target mutants, empty, NA, ERROR, gate."""
1062
+ by_id = {case["id"]: case for case in CASES}
1063
+ control = by_id["launcher_health_control"]
1064
+ version = by_id["launcher_python_minimum_fallback"]
1065
+ ambient = by_id["launcher_ambient_python_isolated"]
1066
+ root = Path(tempfile.mkdtemp(prefix="startup_probe_selftest_"))
1067
+ observed: dict[str, str] = {}
1068
+ try:
1069
+ fixtures = {}
1070
+ for mode in ("correct", "no-version", "ambient-mutant", "noop"):
1071
+ agent = root / mode
1072
+ agent.mkdir()
1073
+ _write_synthetic_launcher(agent, mode)
1074
+ fixtures[mode] = agent
1075
+ checks = [
1076
+ ("correct-control", fixtures["correct"], control, "pass"),
1077
+ ("correct-version", fixtures["correct"], version, "pass"),
1078
+ ("correct-ambient", fixtures["correct"], ambient, "pass"),
1079
+ ("version-control", fixtures["no-version"], control, "pass"),
1080
+ ("version-mutant", fixtures["no-version"], version, "fail"),
1081
+ ("ambient-control", fixtures["ambient-mutant"], control, "pass"),
1082
+ ("ambient-mutant", fixtures["ambient-mutant"], ambient, "fail"),
1083
+ ("empty-control", fixtures["noop"], control, "fail"),
1084
+ ]
1085
+ oks = []
1086
+ for label, agent, case, expected in checks:
1087
+ row = SC.finalize_case(_run_one(agent, case))
1088
+ observed[label] = row["status"]
1089
+ oks.append(row["status"] == expected)
1090
+
1091
+ no_floor = chk_launcher_python_minimum_fallback(
1092
+ {
1093
+ "driver_error": "",
1094
+ "cleanup_complete": True,
1095
+ "unobservable": "",
1096
+ "declared_floor": None,
1097
+ "scenarios": {},
1098
+ },
1099
+ "",
1100
+ )
1101
+ driver_error = chk_launcher_ambient_python_isolated(
1102
+ {
1103
+ "driver_error": "synthetic",
1104
+ "cleanup_complete": True,
1105
+ "unobservable": "",
1106
+ "declared_floor": [3, 10],
1107
+ "scenarios": {},
1108
+ },
1109
+ "",
1110
+ )
1111
+ gated = SC.apply_gates(
1112
+ (control, version),
1113
+ (
1114
+ {
1115
+ "id": control["id"],
1116
+ "ok": False,
1117
+ "blocking": False,
1118
+ "status": "fail",
1119
+ "why": "synthetic dead control",
1120
+ },
1121
+ {
1122
+ "id": version["id"],
1123
+ "ok": False,
1124
+ "blocking": True,
1125
+ "status": "fail",
1126
+ "why": "must be gated",
1127
+ },
1128
+ ),
1129
+ )
1130
+ observed["no-floor"] = no_floor[2]
1131
+ observed["driver-error"] = driver_error[2]
1132
+ observed["failed-gate"] = gated[1]["status"]
1133
+ oks.extend(
1134
+ [
1135
+ no_floor[0] is True and no_floor[2] == "na",
1136
+ driver_error[0] is False and driver_error[2] == "error",
1137
+ gated[1]["status"] == "na",
1138
+ ]
1139
+ )
1140
+ finally:
1141
+ shutil.rmtree(root, ignore_errors=True)
1142
+ print(
1143
+ "STARTUP_PROBE_SELFTEST="
1144
+ + json.dumps(
1145
+ {"statuses": observed, "result": "OK" if all(oks) else "BROKEN"},
1146
+ ensure_ascii=False,
1147
+ sort_keys=True,
1148
+ )
1149
+ )
1150
+ return all(oks)
1151
+
1152
+
1153
+ def _result_history(path: Path) -> dict[str, dict]:
1154
+ if not path.is_file():
1155
+ return {}
1156
+ rows: dict[str, dict] = {}
1157
+ for line in path.read_text(encoding="utf-8").splitlines():
1158
+ if not line.strip():
1159
+ continue
1160
+ value = json.loads(line)
1161
+ if isinstance(value, dict) and value.get("id"):
1162
+ rows[str(value["id"])] = value
1163
+ return rows
1164
+
1165
+
1166
+ def main():
1167
+ import argparse
1168
+ ap = argparse.ArgumentParser()
1169
+ ap.add_argument("agent_dir", nargs="?", default=None)
1170
+ ap.add_argument("--emit-json", action="store_true")
1171
+ ap.add_argument("--selftest", action="store_true")
1172
+ ap.add_argument("--case-id", default="")
1173
+ ap.add_argument("--result-file", default="")
1174
+ args = ap.parse_args()
1175
+ if args.selftest:
1176
+ return 0 if _selftest() else 1
1177
+ if not args.agent_dir:
1178
+ ap.error("agent_dir is required unless --selftest is given")
1179
+ agent_dir = Path(args.agent_dir)
1180
+ if (agent_dir / "agent").is_dir():
1181
+ agent_dir = agent_dir / "agent"
1182
+ # Found if `yuyao/` sits under either `src/` or the project root: §0.1.2 does not mandate a
1183
+ # directory layout, so a flat layout is equally valid.
1184
+ if not any((agent_dir / c / "yuyao").is_dir() for c in ("src", ".")) \
1185
+ and not (agent_dir / "src").is_dir():
1186
+ print(f"[startup_smoke] agent src not found: {agent_dir}", file=sys.stderr)
1187
+ if args.emit_json:
1188
+ print('STARTUP_RESULTS=[{"id": "_startup_harness", "ok": false, "blocking": true, "why": "no agent src"}]')
1189
+ print("STARTUP_SMOKE_FAIL")
1190
+ sys.exit(2)
1191
+ print(f"[startup_smoke] agent: {agent_dir} {len(CASES)} case(s)\n")
1192
+ cases = _selected_cases(CASES)
1193
+ if args.case_id:
1194
+ known = {case["id"] for case in CASES}
1195
+ if args.case_id not in known:
1196
+ print(f"STARTUP_SELECTION_ERROR=unknown --case-id: {args.case_id}", file=sys.stderr)
1197
+ return 2
1198
+ cases = [case for case in cases if case["id"] == args.case_id]
1199
+ results = []
1200
+ for case in cases:
1201
+ try:
1202
+ result = _run_one(agent_dir, case)
1203
+ except Exception as exc: # noqa: BLE001
1204
+ result = {
1205
+ "id": case["id"],
1206
+ "ok": False,
1207
+ "blocking": case.get("blocking", True),
1208
+ "why": f"runner error: {exc!r}",
1209
+ }
1210
+ if case.get("formal_status"):
1211
+ result["status"] = "error"
1212
+ results.append(result)
1213
+ if args.case_id:
1214
+ closure = SC.dependency_closure(CASES, (args.case_id,))
1215
+ history = _result_history(Path(args.result_file)) if args.result_file else {}
1216
+ context = [
1217
+ history[case["id"]]
1218
+ for case in closure
1219
+ if case["id"] in history and case["id"] != args.case_id
1220
+ ]
1221
+ context.extend(results)
1222
+ gated = SC.apply_gates(closure, context)
1223
+ results = [row for row in gated if row["id"] == args.case_id]
1224
+ else:
1225
+ results = SC.apply_gates(cases, results)
1226
+ if args.result_file:
1227
+ path = Path(args.result_file)
1228
+ path.parent.mkdir(parents=True, exist_ok=True)
1229
+ with path.open("a", encoding="utf-8") as handle:
1230
+ for result in results:
1231
+ handle.write(
1232
+ json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n"
1233
+ )
1234
+ handle.flush()
1235
+ os.fsync(handle.fileno())
1236
+ npass = sum(r["ok"] for r in results)
1237
+ for r in results:
1238
+ print(f"[{'PASS' if r['ok'] else 'FAIL'}] {r['id']:30s} {r['why']}")
1239
+ blocking_ok = all(r["ok"] for r in results if r.get("blocking"))
1240
+ if args.emit_json:
1241
+ print("STARTUP_RESULTS=" + json.dumps(results, ensure_ascii=False))
1242
+ print("STARTUP_SMOKE_OK" if blocking_ok else "STARTUP_SMOKE_FAIL")
1243
+ print(f"\n== startup fail-soft determinism smoke: {npass}/{len(results)} passed ==")
1244
+ sys.exit(0 if npass == len(results) else 1)
1245
+
1246
+
1247
+ if __name__ == "__main__":
1248
+ main()
code/src/stage1/smoke/state_smoke.py ADDED
The diff for this file is too large to render. See raw diff
 
code/src/stage1/smoke/tui_line.py ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """tui-line layer: launch the build's own interactive TUI inside a REAL pty and feed user input
3
+ line by line into stdin.
4
+
5
+ Why a separate layer is needed:
6
+ the spec §5.4 input prefixes (`/` `@` `!`) are usually handled only in the interactive line
7
+ handler, which a non-interactive path cannot reach, and `tui_smoke.py` drives the product by
8
+ method name (`chat` / `agentic_turn` / `_run_turn`), which misses a `_handle_line`-style handler.
9
+
10
+ How this layer drives the line handler:
11
+ instead of calling functions by name, run the build's own CLI entry point with NO arguments (which
12
+ enters the interactive TUI) and write lines to the pty master. Which internal path the build takes
13
+ and what its functions are called is irrelevant - this is the only way to drive line-handler
14
+ implementations.
15
+
16
+ Division of labor with the other layers:
17
+ - `tui_smoke.py` - also uses a pty, but tests RENDERING (Live redraws, streaming) and drives by
18
+ method name.
19
+ - `headless_smoke` - a real CLI, but on the `-p` non-interactive path, which cannot reach the
20
+ tui.py line handler.
21
+ - this layer - real CLI + interactive path + line-by-line input.
22
+
23
+ Two observation surfaces, which suffice:
24
+ 1. The stub gateway's request records (`probes` / `probes_in_system` / `tool_names` / `stream`
25
+ ...) - whether `@` references injected file contents into the request body is visible here.
26
+ 2. Visible text on the pty (ANSI stripped) - output of `!`-prefixed commands and error messages.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import json
32
+ import os
33
+ import re
34
+ import select
35
+ import signal
36
+ import subprocess
37
+ import sys
38
+ import tempfile
39
+ import threading
40
+ import time
41
+ from pathlib import Path
42
+
43
+ HERE = Path(__file__).resolve().parent
44
+ sys.path.insert(0, str(HERE))
45
+
46
+ import mock_gateway as MG # noqa: E402
47
+
48
+ _ANSI = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
49
+
50
+ # Wind-down sentinel: after all input lines, feed one more line `!echo <DONE>`; seeing it means every
51
+ # preceding line was processed. The `!` prefix is deliberate - it is itself one of the surfaces under
52
+ # test, and if a build does not support `!` we fall back to the timeout and the checks' self-gating
53
+ # reports inconclusive rather than a hard FAIL.
54
+ DONE = "TUILINE_DONE_7755"
55
+ PROMPT_CANARY_FILE = ".d2a_prompt_canary"
56
+ PROMPT_CANARY_NONCE = "TUILINE_PROMPT_READY_4E21"
57
+ PROMPT_CANARY_COMMAND = f"!cat {PROMPT_CANARY_FILE}"
58
+ PROMPT_OBSERVER_ID = "pty-local-shell-canary/v1"
59
+ _HISTORY_SNAPSHOT_MAX_FILES = 256
60
+ _HISTORY_SNAPSHOT_MAX_BYTES = 2 * 1024 * 1024
61
+
62
+
63
+ def _line_payload(text: str, line_terminator: str = "\r") -> bytes:
64
+ """Encode one logical TUI line with an explicit, audited terminator."""
65
+ if line_terminator not in ("\r", "\n"):
66
+ raise ValueError("line_terminator must be CR (\\r) or LF (\\n)")
67
+ return (text + line_terminator).encode()
68
+
69
+
70
+ def _prompt_canary_observation(
71
+ *,
72
+ candidate_output: bytes,
73
+ canary_payload: bytes,
74
+ output_after_write: bytes,
75
+ process_running: bool,
76
+ returncode: int | None,
77
+ ) -> dict:
78
+ """Classify a prompt candidate from facts that terminal echo cannot forge."""
79
+ nonce = PROMPT_CANARY_NONCE.encode()
80
+ candidate = bool(candidate_output)
81
+ nonce_absent_before = nonce not in candidate_output
82
+ nonce_absent_from_input = nonce not in canary_payload
83
+ canary_observed = nonce in output_after_write
84
+ input_consumed = (
85
+ candidate
86
+ and nonce_absent_before
87
+ and nonce_absent_from_input
88
+ and canary_observed
89
+ and process_running
90
+ )
91
+ failure = None
92
+ if not input_consumed:
93
+ if returncode is not None:
94
+ failure = {
95
+ "kind": "process-exit-before-prompt",
96
+ "returncode": returncode,
97
+ "signal": -returncode if returncode < 0 else None,
98
+ }
99
+ elif not candidate:
100
+ failure = {"kind": "no-output-candidate"}
101
+ elif not nonce_absent_before:
102
+ failure = {"kind": "canary-preexisted"}
103
+ elif not nonce_absent_from_input:
104
+ failure = {"kind": "canary-present-in-input"}
105
+ elif not canary_observed:
106
+ failure = {"kind": "canary-not-observed"}
107
+ else:
108
+ failure = {"kind": "process-not-running"}
109
+ normalized_candidate = candidate
110
+ normalized_canary_observed = canary_observed
111
+ if returncode is not None and not input_consumed:
112
+ # Whether a quiet boundary happened just before an early exit is a
113
+ # scheduler-sensitive detail, not prompt identity. Collapse all
114
+ # pre-handshake exits to one portable startup-failure timeline.
115
+ normalized_candidate = False
116
+ normalized_canary_observed = False
117
+ events = ["startup-failure"]
118
+ else:
119
+ events = ["candidate-boundary"] if candidate else []
120
+ if candidate:
121
+ events.append("canary-write")
122
+ if canary_observed:
123
+ events.append("canary-observed")
124
+ if input_consumed:
125
+ events.append("input-consumed")
126
+ return {
127
+ "schema": "d2a.tui-prompt-observation/1",
128
+ "prompt_identity": PROMPT_OBSERVER_ID,
129
+ "turn_id": "prompt-0",
130
+ "candidate_boundary": normalized_candidate,
131
+ "canary_nonce_absent_before": nonce_absent_before,
132
+ "canary_nonce_absent_from_input": nonce_absent_from_input,
133
+ "canary_observed": normalized_canary_observed,
134
+ "input_consumed": input_consumed,
135
+ "startup_failure": failure,
136
+ "timeline": events,
137
+ }
138
+
139
+
140
+ def _discover_tui_cli(agent_dir: Path):
141
+ """Return (argv, env): running it with no arguments enters the interactive TUI.
142
+
143
+ Same candidates and same PYTHONPATH handling as the headless layer's `_discover_cli`, except it
144
+ does NOT require `-p`/`--print` in the help - this layer wants the interactive entry point, not
145
+ the headless one. The criterion becomes "`--help` runs successfully (rc=0)", so an entry point
146
+ that cannot start at all is not treated as usable.
147
+ """
148
+ env = dict(os.environ)
149
+ src = os.pathsep.join([str((agent_dir / "src").resolve()), str(agent_dir.resolve())])
150
+ env["PYTHONPATH"] = src + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
151
+ env["MSWEA_SILENT_STARTUP"] = "1"
152
+ env["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
153
+ env["MSWEA_COST_TRACKING"] = "ignore_errors"
154
+ for c in ([sys.executable, "-m", "yuyao"], [sys.executable, "-m", "yuyao.cli"], ["yuyao"]):
155
+ try:
156
+ r = subprocess.run(c + ["--help"], cwd=str(agent_dir), env=env,
157
+ capture_output=True, text=True, timeout=40)
158
+ except Exception:
159
+ continue
160
+ # Same rule as the headless layer's _discover_cli: also accept a complete help page with
161
+ # rc!=0 (a known shape where the build's argparse maps SystemExit(0) to 2). A usage line plus
162
+ # enough content is content-level evidence that the entry point works; an entry point that
163
+ # crashes before argparse cannot print a full help page, and a single-line usage error is
164
+ # blocked by the 200-byte floor.
165
+ help_txt = (r.stdout or "") + (r.stderr or "")
166
+ help_complete = (
167
+ re.search(r"(?im)^\s*(usage|用法)[::]", help_txt) is not None
168
+ and len(help_txt) > 200
169
+ )
170
+ if r.returncode == 0 or help_complete:
171
+ return c, env
172
+ return None, env
173
+
174
+
175
+ def _readiness_budget(timeout: float) -> float:
176
+ return min(30.0, max(10.0, timeout * 0.5))
177
+
178
+
179
+ def _split_control_prefix(line: str) -> tuple[str, str]:
180
+ """Separate a physical Ctrl+L keypress from text typed after redraw."""
181
+ if line.startswith("\x0c") and len(line) > 1:
182
+ return line[0], line[1:]
183
+ return "", line
184
+
185
+
186
+ def _input_segments(line: str) -> list[str]:
187
+ """Split control-key transitions from text typed after UI handling.
188
+
189
+ PTYs preserve write boundaries, but prompt_toolkit does not promise to
190
+ process a control key and later text atomically when both arrive in one
191
+ write. Keep bracketed-paste and general escape sequences intact; split
192
+ only the control-key transitions known to be consumed separately.
193
+ """
194
+ control, rest = _split_control_prefix(line)
195
+ if control:
196
+ return [control, rest]
197
+ if "\x03" in line:
198
+ before, after = line.split("\x03", 1)
199
+ return [part for part in (before, "\x03", after) if part]
200
+ backspaces = re.search(r"[\x08\x7f]+", line)
201
+ if backspaces:
202
+ return [
203
+ part
204
+ for part in (
205
+ line[: backspaces.start()],
206
+ backspaces.group(),
207
+ line[backspaces.end() :],
208
+ )
209
+ if part
210
+ ]
211
+ return [line]
212
+
213
+
214
+ def _history_snapshot(home: str | Path) -> dict:
215
+ """Capture bounded raw bytes from product history files under one case HOME.
216
+
217
+ History ownership is inferred only from the public on-disk namespace: at
218
+ least one relative path component must contain ``history``. The Harness
219
+ never writes product history syntax and never guesses a product slug.
220
+ """
221
+ root = Path(home).resolve()
222
+ files: dict[str, dict] = {}
223
+ total = 0
224
+ try:
225
+ candidates = sorted(root.rglob("*"), key=lambda path: path.as_posix())
226
+ except OSError as exc:
227
+ raise RuntimeError(f"cannot enumerate isolated HOME history: {exc}") from exc
228
+ for path in candidates:
229
+ try:
230
+ if not path.is_file():
231
+ continue
232
+ resolved = path.resolve()
233
+ rel = resolved.relative_to(root)
234
+ except (OSError, ValueError):
235
+ continue
236
+ if not any("history" in part.casefold() for part in rel.parts):
237
+ continue
238
+ if len(files) >= _HISTORY_SNAPSHOT_MAX_FILES:
239
+ raise RuntimeError("history snapshot exceeded file bound")
240
+ try:
241
+ data = resolved.read_bytes()
242
+ except OSError as exc:
243
+ raise RuntimeError(f"cannot read history bytes {rel.as_posix()}: {exc}") from exc
244
+ total += len(data)
245
+ if total > _HISTORY_SNAPSHOT_MAX_BYTES:
246
+ raise RuntimeError("history snapshot exceeded byte bound")
247
+ files[rel.as_posix()] = {
248
+ "size": len(data),
249
+ "sha256": hashlib.sha256(data).hexdigest(),
250
+ "data_hex": data.hex(),
251
+ }
252
+ return {
253
+ "schema": "d2a.tui-history-snapshot/1",
254
+ "complete": True,
255
+ "file_count": len(files),
256
+ "byte_count": total,
257
+ "files": files,
258
+ }
259
+
260
+
261
+ def _history_token_paths(snapshot: dict, token: str) -> list[str]:
262
+ needle = token.encode()
263
+ paths = []
264
+ for rel, row in (snapshot.get("files") or {}).items():
265
+ try:
266
+ data = bytes.fromhex(str(row.get("data_hex") or ""))
267
+ except ValueError:
268
+ continue
269
+ if needle in data:
270
+ paths.append(str(rel))
271
+ return sorted(paths)
272
+
273
+
274
+ def _feed_pty(
275
+ argv,
276
+ env,
277
+ workdir,
278
+ lines,
279
+ timeout,
280
+ cfg=None,
281
+ *,
282
+ home: str | Path | None = None,
283
+ events: list[dict] | None = None,
284
+ line_terminator: str = "\r",
285
+ ):
286
+ """Launch the TUI in a real pty, feed input line by line, return the ANSI-stripped visible text.
287
+
288
+ Feeding rhythm (each rule guards against a real failure mode):
289
+ - Wait a moment after starting the process before feeding the first line: some implementations
290
+ must finish drawing a welcome screen before they read stdin, and a line fed too early is lost.
291
+ - The wait condition PER LINE depends on the line type. Lines starting with `!`/`/` are handled
292
+ locally and echo immediately, so waiting for the echo is enough; ordinary text runs a model
293
+ turn, so the feeder waits until the stub gateway's request count actually increases before
294
+ feeding the next line. Breaking out on the wind-down sentinel alone is not enough: `!echo
295
+ <DONE>` is a local command that returns instantly, so the master would be closed before the
296
+ previous line's model turn had even sent its request.
297
+ - The line terminator MUST be `\\r`, not `\\n`; this is what makes the layer work at all. The
298
+ input box is prompt_toolkit in multiline mode, so `\\n` only inserts a newline: the prompt
299
+ turns from `>` into a continuation `. .` and the input buffers forever without ever being
300
+ submitted, so the stub gateway receives nothing. Only terminators containing `\\r` submit.
301
+ - On exit feed `/exit` AND close the master to send EOF - implementations differ in which exit
302
+ route they honor.
303
+ """
304
+ if line_terminator not in ("\r", "\n"):
305
+ raise ValueError("line_terminator must be CR (\\r) or LF (\\n)")
306
+ import pty
307
+ master, slave = pty.openpty()
308
+ env = dict(env)
309
+ env["COLUMNS"] = "100"
310
+ env["LINES"] = "30"
311
+ env["TERM"] = "xterm"
312
+ env["HOME"] = str(home or workdir)
313
+ # A host override would silently move product history outside the case HOME.
314
+ env.pop("YUYAO_HOME", None)
315
+ p = subprocess.Popen(
316
+ argv,
317
+ stdin=slave,
318
+ stdout=slave,
319
+ stderr=slave,
320
+ cwd=workdir,
321
+ env=env,
322
+ close_fds=True,
323
+ start_new_session=True,
324
+ )
325
+ os.close(slave)
326
+ buf = bytearray()
327
+ timeline: list[dict] = []
328
+ timeline_bytes = 0
329
+
330
+ def _record(direction: str, data: bytes) -> None:
331
+ nonlocal timeline_bytes
332
+ if timeline_bytes >= 1_000_000:
333
+ return
334
+ kept = data[: 1_000_000 - timeline_bytes]
335
+ timeline_bytes += len(kept)
336
+ timeline.append(
337
+ {
338
+ "t_ns": time.monotonic_ns(),
339
+ "direction": direction,
340
+ "data_hex": kept.hex(),
341
+ }
342
+ )
343
+
344
+ def _reader():
345
+ while True:
346
+ try:
347
+ r, _, _ = select.select([master], [], [], 0.4)
348
+ except (OSError, ValueError):
349
+ return
350
+ if not r:
351
+ if p.poll() is not None:
352
+ return
353
+ continue
354
+ try:
355
+ data = os.read(master, 65536)
356
+ except OSError:
357
+ return
358
+ if not data:
359
+ return
360
+ buf.extend(data)
361
+ _record("read", data)
362
+
363
+ t = threading.Thread(target=_reader, daemon=True)
364
+ t.start()
365
+ deadline = time.time() + timeout
366
+ prompt_ready = False
367
+ prompt_observation = _prompt_canary_observation(
368
+ candidate_output=b"",
369
+ canary_payload=_line_payload(PROMPT_CANARY_COMMAND, line_terminator),
370
+ output_after_write=b"",
371
+ process_running=p.poll() is None,
372
+ returncode=p.poll(),
373
+ )
374
+ sent_lines = (
375
+ []
376
+ if events is not None
377
+ else list(lines) + ["!printf 'TUILINE_%s_7755\\n' DONE", "/exit"]
378
+ )
379
+ event_results: list[dict] = []
380
+ try:
381
+ def _wait_output_quiet(
382
+ max_wait: float,
383
+ quiet_for: float = 0.35,
384
+ growth_from: int | None = None,
385
+ ) -> bool:
386
+ end = min(time.time() + max_wait, deadline)
387
+ last_size = len(buf)
388
+ stable_since = time.monotonic()
389
+ observed_growth = growth_from is None or last_size > growth_from
390
+ while time.time() < end and p.poll() is None:
391
+ size = len(buf)
392
+ if size != last_size:
393
+ last_size = size
394
+ stable_since = time.monotonic()
395
+ if growth_from is not None and size > growth_from:
396
+ observed_growth = True
397
+ if observed_growth and time.monotonic() - stable_since >= quiet_for:
398
+ return True
399
+ time.sleep(0.05)
400
+ return False
401
+
402
+ # Output quiet is only a candidate boundary. A banner, warning, traceback or
403
+ # process-exit prelude can all become quiet without an input prompt. Prove the
404
+ # real prompt/turn by asking the TUI to execute a local command whose output
405
+ # nonce is stored in a fixture file and is absent from the bytes we write.
406
+ ready_budget = _readiness_budget(timeout)
407
+ ready_end = min(time.time() + ready_budget, deadline)
408
+ last_size = -1
409
+ stable_since = time.monotonic()
410
+ candidate_output = b""
411
+ while time.time() < ready_end and p.poll() is None:
412
+ size = len(buf)
413
+ if size != last_size:
414
+ last_size = size
415
+ stable_since = time.monotonic()
416
+ elif size > 0 and time.monotonic() - stable_since >= 0.25:
417
+ timeline.append(
418
+ {
419
+ "t_ns": time.monotonic_ns(),
420
+ "direction": "prompt-candidate",
421
+ "data_hex": "",
422
+ }
423
+ )
424
+ candidate_output = bytes(buf)
425
+ break
426
+ time.sleep(0.05)
427
+ canary_payload = _line_payload(PROMPT_CANARY_COMMAND, line_terminator)
428
+ canary_start = len(buf)
429
+ if candidate_output and p.poll() is None:
430
+ # The first write may land in the build's cooked window (prompt_toolkit has not switched
431
+ # to raw yet): the pty line discipline's ICRNL translates \r into \n, which for a
432
+ # multiline input box only inserts a newline instead of submitting, so simply waiting
433
+ # always loses. Use bounded-settle polling with retry convergence instead: write the full
434
+ # canary first, then every 1.5s add only a bare \r - once raw mode is established that is
435
+ # c-m = enter and submits the canary line sitting in the draft.
436
+ # Do not resend the full canary (it would accumulate a multi-line dirty draft), and never
437
+ # pre-clear the pty's ICRNL (plain-REPL builds rely on it to turn \r into lines;
438
+ # pre-clearing would deterministically turn those into na).
439
+ retry_interval = 1.5 # << the 10s floor of _readiness_budget
440
+ attempt = 0
441
+ next_write = 0.0 # write immediately
442
+ while time.time() < ready_end and p.poll() is None:
443
+ output_after_write = bytes(buf[canary_start:])
444
+ prompt_observation = _prompt_canary_observation(
445
+ candidate_output=candidate_output,
446
+ canary_payload=canary_payload,
447
+ output_after_write=output_after_write,
448
+ process_running=p.poll() is None,
449
+ returncode=p.poll(),
450
+ )
451
+ if prompt_observation["input_consumed"]:
452
+ prompt_ready = True
453
+ timeline.append(
454
+ {
455
+ "t_ns": time.monotonic_ns(),
456
+ "direction": "prompt-ready",
457
+ "data_hex": "",
458
+ }
459
+ )
460
+ _wait_output_quiet(
461
+ max(0.0, ready_end - time.time()),
462
+ quiet_for=0.5,
463
+ growth_from=canary_start,
464
+ )
465
+ break
466
+ if time.monotonic() >= next_write:
467
+ # First write: full canary; retries send only bare \r (a correct build succeeds on
468
+ # the first attempt and never retries)
469
+ payload = canary_payload if attempt == 0 else line_terminator.encode()
470
+ try:
471
+ os.write(master, payload)
472
+ _record(
473
+ "canary-write" if attempt == 0 else "canary-retry",
474
+ payload,
475
+ )
476
+ except OSError:
477
+ pass
478
+ attempt += 1
479
+ next_write = time.monotonic() + retry_interval
480
+ time.sleep(0.05)
481
+ if not prompt_ready:
482
+ prompt_observation = _prompt_canary_observation(
483
+ candidate_output=candidate_output,
484
+ canary_payload=canary_payload,
485
+ output_after_write=bytes(buf[canary_start:]),
486
+ process_running=p.poll() is None,
487
+ returncode=p.poll(),
488
+ )
489
+ if not prompt_ready:
490
+ sent_lines = []
491
+ if prompt_ready and events is not None:
492
+ for event in events:
493
+ if time.time() > deadline or p.poll() is not None:
494
+ break
495
+ if not isinstance(event, dict):
496
+ raise ValueError("TUI event must be a dict")
497
+ kind = str(event.get("kind") or "")
498
+ name = str(event.get("name") or f"event-{len(event_results)}")
499
+ output_start = len(buf)
500
+ requests_before = len(cfg["requests"]) if cfg is not None else 0
501
+ payload = b""
502
+ snapshot = None
503
+ if kind == "snapshot-history":
504
+ snapshot = _history_snapshot(home or workdir)
505
+ else:
506
+ if kind == "line":
507
+ text = event.get("text")
508
+ if not isinstance(text, str):
509
+ raise ValueError(f"{name}: line event requires text")
510
+ payload = _line_payload(text, line_terminator)
511
+ elif kind == "bytes":
512
+ data = event.get("data")
513
+ if isinstance(data, str):
514
+ payload = data.encode()
515
+ elif isinstance(data, bytes):
516
+ payload = data
517
+ else:
518
+ raise ValueError(f"{name}: bytes event requires str or bytes")
519
+ elif kind == "control":
520
+ value = event.get("value")
521
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255:
522
+ raise ValueError(f"{name}: control value must be one byte")
523
+ payload = bytes((value,))
524
+ else:
525
+ raise ValueError(f"{name}: unknown TUI event kind {kind!r}")
526
+ if not payload:
527
+ raise ValueError(f"{name}: empty TUI input event")
528
+ try:
529
+ os.write(master, payload)
530
+ _record("write", payload)
531
+ except OSError:
532
+ break
533
+
534
+ wait_mode = str(event.get("wait") or (
535
+ "request"
536
+ if kind == "line"
537
+ and not str(event.get("text") or "").startswith(("!", "/"))
538
+ else "quiet"
539
+ ))
540
+ wait_s = float(event.get("timeout") or (
541
+ 40.0 if wait_mode == "request" else 8.0
542
+ ))
543
+ if wait_mode == "request":
544
+ end = min(time.time() + wait_s, deadline)
545
+ while time.time() < end and p.poll() is None:
546
+ if cfg is not None and len(cfg["requests"]) > requests_before:
547
+ response_start = len(buf)
548
+ _wait_output_quiet(
549
+ min(8.0, max(0.0, end - time.time())),
550
+ quiet_for=0.5,
551
+ growth_from=response_start,
552
+ )
553
+ break
554
+ time.sleep(0.05)
555
+ elif wait_mode == "terminal":
556
+ end = min(time.time() + wait_s, deadline)
557
+ while time.time() < end and p.poll() is None:
558
+ time.sleep(0.05)
559
+ elif wait_mode == "quiet":
560
+ _wait_output_quiet(
561
+ wait_s,
562
+ quiet_for=float(event.get("quiet_for") or 0.5),
563
+ growth_from=output_start,
564
+ )
565
+ elif wait_mode != "none":
566
+ raise ValueError(f"{name}: unknown wait mode {wait_mode!r}")
567
+
568
+ output_end = len(buf)
569
+ event_output = bytes(buf[output_start:output_end])
570
+ event_results.append(
571
+ {
572
+ "name": name,
573
+ "kind": kind,
574
+ "input_hex": payload.hex(),
575
+ "output_text": _ANSI.sub(
576
+ "",
577
+ event_output.decode("utf-8", errors="replace"),
578
+ ),
579
+ "output_sha256": hashlib.sha256(event_output).hexdigest(),
580
+ "output_size": len(event_output),
581
+ "requests_before": requests_before,
582
+ "requests_after": (
583
+ len(cfg["requests"]) if cfg is not None else requests_before
584
+ ),
585
+ "returncode": p.poll(),
586
+ "snapshot": snapshot,
587
+ }
588
+ )
589
+ for ln in sent_lines:
590
+ if time.time() > deadline:
591
+ break
592
+ segments = _input_segments(ln)
593
+ for segment in segments[:-1]:
594
+ # These chunks represent draft/control-key transitions, not
595
+ # submitted lines. Wait for the TUI to consume each physical
596
+ # transition before writing text that semantically follows it.
597
+ _wait_output_quiet(3.0)
598
+ try:
599
+ segment_payload = segment.encode()
600
+ os.write(master, segment_payload)
601
+ _record("write", segment_payload)
602
+ except OSError:
603
+ break
604
+ _wait_output_quiet(3.0)
605
+ else:
606
+ ln = segments[-1]
607
+ local = ln.startswith(("!", "/"))
608
+ n_before = len(cfg["requests"]) if cfg is not None else 0
609
+ grew_before = len(buf)
610
+ try:
611
+ payload = _line_payload(ln, line_terminator)
612
+ os.write(master, payload) # must be \r, see comment above
613
+ _record("write", payload)
614
+ except OSError:
615
+ break
616
+ # Local commands echo input before their side effect finishes.
617
+ # Waiting for first growth therefore races the following line;
618
+ # require the output to become quiet after observed growth.
619
+ wait = 8.0 if local else 40.0
620
+ if local:
621
+ _wait_output_quiet(
622
+ wait,
623
+ quiet_for=0.5,
624
+ growth_from=grew_before,
625
+ )
626
+ else:
627
+ end = min(time.time() + wait, deadline)
628
+ while time.time() < end:
629
+ if cfg is not None and len(cfg["requests"]) > n_before:
630
+ response_start = len(buf)
631
+ # Request arrival is not turn completion. Wait for the
632
+ # subsequent PTY output to settle before the next key.
633
+ _wait_output_quiet(
634
+ 8.0,
635
+ quiet_for=0.5,
636
+ growth_from=response_start,
637
+ )
638
+ break
639
+ time.sleep(0.3)
640
+ # Runaway-loop brake: a product that loops on the stub's constant "ack" can issue hundreds
641
+ # of requests on a single plain-text line. Without braking, subsequent lines are
642
+ # drowned in unrelated requests and the checker observes garbage. The brake itself does
643
+ # not judge right or wrong - that is a doomloop concern - it only keeps the observation
644
+ # surface clean.
645
+ if cfg is not None and len(cfg["requests"]) > 40:
646
+ break
647
+ finally:
648
+ try:
649
+ os.close(master) # send EOF; implementations that exit on EOF wind down here
650
+ except OSError:
651
+ pass
652
+ try:
653
+ p.wait(timeout=8)
654
+ except Exception:
655
+ try:
656
+ os.killpg(p.pid, signal.SIGTERM)
657
+ p.wait(timeout=2)
658
+ except Exception:
659
+ try:
660
+ os.killpg(p.pid, signal.SIGKILL)
661
+ except ProcessLookupError:
662
+ pass
663
+ try:
664
+ p.wait(timeout=5)
665
+ except Exception:
666
+ pass
667
+ t.join(timeout=2)
668
+ raw = bytes(buf)
669
+ rc = p.returncode
670
+ return {
671
+ "text": _ANSI.sub("", raw.decode("utf-8", errors="replace")),
672
+ "prompt_ready": prompt_ready,
673
+ "prompt_observation": prompt_observation,
674
+ "returncode": rc,
675
+ "signal": -rc if isinstance(rc, int) and rc < 0 else None,
676
+ "timeline": timeline,
677
+ "events": event_results,
678
+ "raw_sha256": hashlib.sha256(raw).hexdigest(),
679
+ "raw_size": len(raw),
680
+ "split_nonce": all(DONE not in line for line in sent_lines),
681
+ }
682
+
683
+
684
+ _HISTORY_A_PREFIX = "H8A9961_"
685
+ _HISTORY_A_TOKEN = _HISTORY_A_PREFIX + "ONLY_A_4C7E"
686
+ _HISTORY_B_PREFIX = "H8B9962_"
687
+ _HISTORY_B_TOKEN = _HISTORY_B_PREFIX + "ONLY_B_9D3F"
688
+
689
+
690
+ def _prepare_tui_workspace(path: Path) -> None:
691
+ path.mkdir(parents=True, exist_ok=True)
692
+ (path / PROMPT_CANARY_FILE).write_text(PROMPT_CANARY_NONCE, encoding="utf-8")
693
+
694
+
695
+ def _event_result(pty_result: dict, name: str) -> dict:
696
+ return next(
697
+ (row for row in (pty_result.get("events") or []) if row.get("name") == name),
698
+ {},
699
+ )
700
+
701
+
702
+ def _aggregate_pty_results(runs: list[dict]) -> dict:
703
+ observations = [run.get("prompt_observation") or {} for run in runs]
704
+ ready = bool(runs) and all(run.get("prompt_ready") for run in runs)
705
+ failures = [row.get("startup_failure") for row in observations if row.get("startup_failure")]
706
+ digest_input = b"".join(
707
+ bytes.fromhex(str(run.get("raw_sha256") or "0" * 64))
708
+ for run in runs
709
+ )
710
+ timeline = []
711
+ for ordinal, run in enumerate(runs):
712
+ for row in run.get("timeline") or []:
713
+ timeline.append({"run": ordinal, **row})
714
+ returncodes = [run.get("returncode") for run in runs]
715
+ nonzero = next((rc for rc in returncodes if isinstance(rc, int) and rc != 0), None)
716
+ signal_number = next(
717
+ (run.get("signal") for run in runs if run.get("signal") is not None),
718
+ None,
719
+ )
720
+ return {
721
+ "prompt_ready": ready,
722
+ "prompt_observation": {
723
+ "schema": "d2a.tui-prompt-observation-multi/1",
724
+ "prompt_identity": PROMPT_OBSERVER_ID,
725
+ "turn_id": "prompt-multi",
726
+ "candidate_boundary": bool(runs),
727
+ "canary_nonce_absent_before": all(
728
+ row.get("canary_nonce_absent_before") for row in observations
729
+ ),
730
+ "canary_nonce_absent_from_input": all(
731
+ row.get("canary_nonce_absent_from_input") for row in observations
732
+ ),
733
+ "canary_observed": all(row.get("canary_observed") for row in observations),
734
+ "input_consumed": ready,
735
+ "startup_failure": failures or None,
736
+ "timeline": [row.get("timeline") for row in observations],
737
+ "run_count": len(runs),
738
+ },
739
+ "returncode": nonzero if nonzero is not None else (0 if runs else None),
740
+ "returncodes": returncodes,
741
+ "signal": signal_number,
742
+ "timeline": timeline,
743
+ "raw_sha256": hashlib.sha256(digest_input).hexdigest(),
744
+ "raw_size": sum(int(run.get("raw_size") or 0) for run in runs),
745
+ "split_nonce": all(run.get("split_nonce") for run in runs),
746
+ }
747
+
748
+
749
+ def _history_writer(argv, env, workspace: Path, home: Path, cfg: dict, token: str) -> dict:
750
+ _prepare_tui_workspace(workspace)
751
+ return _feed_pty(
752
+ argv,
753
+ env,
754
+ str(workspace),
755
+ [],
756
+ 35,
757
+ cfg=cfg,
758
+ home=home,
759
+ events=[
760
+ {
761
+ "kind": "line",
762
+ "name": "write-token",
763
+ "text": token,
764
+ "wait": "request",
765
+ },
766
+ {
767
+ "kind": "control",
768
+ "name": "cancel-turn",
769
+ "value": 0x03,
770
+ "wait": "quiet",
771
+ "timeout": 4,
772
+ },
773
+ {
774
+ "kind": "control",
775
+ "name": "exit",
776
+ "value": 0x04,
777
+ "wait": "terminal",
778
+ "timeout": 5,
779
+ },
780
+ ],
781
+ )
782
+
783
+
784
+ def _history_reader(argv, env, workspace: Path, home: Path, cfg: dict, prefix: str) -> dict:
785
+ _prepare_tui_workspace(workspace)
786
+ return _feed_pty(
787
+ argv,
788
+ env,
789
+ str(workspace),
790
+ [],
791
+ 35,
792
+ cfg=cfg,
793
+ home=home,
794
+ events=[
795
+ # Physical 0x12 is its own write/timeline event. No full history token
796
+ # appears in this process's input, so terminal echo cannot forge recall.
797
+ {
798
+ "kind": "control",
799
+ "name": "ctrl-r-start",
800
+ "value": 0x12,
801
+ "wait": "quiet",
802
+ "timeout": 3,
803
+ },
804
+ {
805
+ "kind": "bytes",
806
+ "name": "ctrl-r-query",
807
+ "data": prefix,
808
+ "wait": "quiet",
809
+ "timeout": 3,
810
+ },
811
+ ],
812
+ )
813
+
814
+
815
+ def _history_collision_workspaces(root: Path) -> tuple[Path, Path]:
816
+ base = root / "workspaces" / "collision"
817
+ return base / "piece_a_b" / "leaf", base / "piece_a" / "b" / "leaf"
818
+
819
+
820
+ def _lossy_history_slug(path: Path) -> str:
821
+ return re.sub(r"[^\w]+", "_", os.path.realpath(path)).strip("_")[-80:] or "root"
822
+
823
+
824
+ def _run_history_scenario(argv, env, root: Path, cfg: dict, scenario: str) -> dict:
825
+ home = root / "home"
826
+ home.mkdir(parents=True, exist_ok=True)
827
+ runs: list[dict] = []
828
+ facts: dict = {"scenario": scenario}
829
+
830
+ if scenario in {"history-fresh-a", "history-fresh-b"}:
831
+ workspace_a, workspace_b = _history_collision_workspaces(root)
832
+ slot_a = scenario.endswith("-a")
833
+ workspace = workspace_a if slot_a else workspace_b
834
+ token = _HISTORY_A_TOKEN if slot_a else _HISTORY_B_TOKEN
835
+ prefix = _HISTORY_A_PREFIX if slot_a else _HISTORY_B_PREFIX
836
+ writer = _history_writer(argv, env, workspace, home, cfg, token)
837
+ runs.append(writer)
838
+ snapshot = _history_snapshot(home)
839
+ reader = _history_reader(argv, env, workspace, home, cfg, prefix)
840
+ runs.append(reader)
841
+ facts.update(
842
+ {
843
+ "slot": "A" if slot_a else "B",
844
+ "workspace": str(workspace.resolve()),
845
+ "token": token,
846
+ "prefix": prefix,
847
+ "writer": writer,
848
+ "reader": reader,
849
+ "snapshot": snapshot,
850
+ }
851
+ )
852
+ elif scenario == "history-realpath-key":
853
+ workspace_a, workspace_b = _history_collision_workspaces(root)
854
+ _prepare_tui_workspace(workspace_a)
855
+ _prepare_tui_workspace(workspace_b)
856
+ real_a = os.path.realpath(workspace_a)
857
+ real_b = os.path.realpath(workspace_b)
858
+ writer_a = _history_writer(argv, env, workspace_a, home, cfg, _HISTORY_A_TOKEN)
859
+ runs.append(writer_a)
860
+ snapshot_a = _history_snapshot(home)
861
+ writer_b = _history_writer(argv, env, workspace_b, home, cfg, _HISTORY_B_TOKEN)
862
+ runs.append(writer_b)
863
+ snapshot_ab = _history_snapshot(home)
864
+ reader_a = _history_reader(argv, env, workspace_a, home, cfg, _HISTORY_A_PREFIX)
865
+ runs.append(reader_a)
866
+ reader_b = _history_reader(argv, env, workspace_b, home, cfg, _HISTORY_B_PREFIX)
867
+ runs.append(reader_b)
868
+ facts.update(
869
+ {
870
+ "workspace_a": real_a,
871
+ "workspace_b": real_b,
872
+ "realpaths_distinct": real_a != real_b,
873
+ "lossy_slug_a": _lossy_history_slug(workspace_a),
874
+ "lossy_slug_b": _lossy_history_slug(workspace_b),
875
+ "basename_collision": workspace_a.name == workspace_b.name,
876
+ "writer_a": writer_a,
877
+ "writer_b": writer_b,
878
+ "reader_a": reader_a,
879
+ "reader_b": reader_b,
880
+ "snapshot_a": snapshot_a,
881
+ "snapshot_ab": snapshot_ab,
882
+ }
883
+ )
884
+ else:
885
+ raise ValueError(f"unknown history scenario: {scenario}")
886
+
887
+ aggregate = _aggregate_pty_results(runs)
888
+ return {
889
+ "cli": True,
890
+ "text": "\n".join(str(run.get("text") or "") for run in runs),
891
+ "reqs": list(cfg.get("requests") or []),
892
+ "files": {},
893
+ "pty": aggregate,
894
+ "pty_runs": runs,
895
+ "history": facts,
896
+ }
897
+
898
+
899
+ def _run_one(agent_dir: Path, case: dict) -> dict:
900
+ """Run one tui-line case.
901
+
902
+ Case keys:
903
+ id, lines (input lines to feed), seed (workspace preset files), stub (gateway cfg
904
+ overrides, including probe_tokens), check (verdict function, receives res), timeout,
905
+ blocking, cli_args (extra CLI flags to the build - seeds config via public flags, e.g.
906
+ `--deny` permission list; equivalent to the interactive-mode face of
907
+ create_session(deny=))
908
+ Self-reported res:
909
+ {"cli": bool whether an interactive entry point exists, "text": pty visible text,
910
+ "reqs": gateway request records}
911
+ """
912
+ argv, env = _discover_tui_cli(agent_dir)
913
+ if argv is None:
914
+ return {"id": case["id"], "ok": True, "blocking": case.get("blocking", True),
915
+ "why": "inconclusive: this artifact exposes no usable interactive entry point (even --help fails) -> skipped"}
916
+ argv = [*argv, *([])]
917
+ cfg = MG.new_cfg(**{"mode": "normal", "reply_content": "ack",
918
+ **(case.get("stub") or {})})
919
+ srv = MG.make_server(cfg, 0)
920
+ port = srv.server_address[1]
921
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
922
+ workdir = tempfile.mkdtemp(prefix="tui_line_")
923
+ try:
924
+ for rel, body in (case.get("seed") or {}).items():
925
+ p = Path(workdir) / rel
926
+ p.parent.mkdir(parents=True, exist_ok=True)
927
+ p.write_bytes(body if isinstance(body, bytes) else body.encode())
928
+ (Path(workdir) / PROMPT_CANARY_FILE).write_text(
929
+ PROMPT_CANARY_NONCE,
930
+ encoding="utf-8",
931
+ )
932
+ env = dict(env)
933
+ env["D2A_MODEL_BASE_URL"] = f"http://127.0.0.1:{port}"
934
+ env["D2A_MODEL_NAME"] = "litellm_proxy/mock"
935
+ env["D2A_MODEL_API_KEY"] = "sk-mock-test"
936
+ if case.get("scenario"):
937
+ res = _run_history_scenario(
938
+ argv,
939
+ env,
940
+ Path(workdir),
941
+ cfg,
942
+ str(case["scenario"]),
943
+ )
944
+ else:
945
+ pty_result = _feed_pty(
946
+ argv,
947
+ env,
948
+ workdir,
949
+ case.get("lines") or [],
950
+ case.get("timeout", 60),
951
+ cfg=cfg,
952
+ line_terminator="\r",
953
+ )
954
+ text = pty_result["text"]
955
+ # Read workspace files on demand to observe the real disk-landing surface of `!<shell>`
956
+ # commands. Trusting only the pty echo conflates "claimed to run" with "actually ran".
957
+ # Cases that supply no files list incur zero extra I/O.
958
+ files = {}
959
+ for rel in case.get("files") or []:
960
+ p = Path(workdir) / rel
961
+ try:
962
+ files[rel] = p.read_text(encoding="utf-8", errors="replace") if p.is_file() else None
963
+ except Exception:
964
+ files[rel] = None
965
+ res = {
966
+ "cli": True,
967
+ "text": text,
968
+ "reqs": list(cfg.get("requests") or []),
969
+ "files": files,
970
+ "pty": pty_result,
971
+ }
972
+ finally:
973
+ try:
974
+ srv.shutdown()
975
+ srv.server_close()
976
+ except Exception:
977
+ pass
978
+ ok, why = case["check"](res)
979
+ pty_meta = res.get("pty") or {}
980
+ if not pty_meta.get("prompt_ready"):
981
+ ok, why = True, "inconclusive: prompt-ready was never observed, so no case input was sent to the PTY"
982
+ prompt_observation = pty_meta.get("prompt_observation") or {}
983
+ why += (
984
+ f" | pty-ready={pty_meta.get('prompt_ready')} rc={pty_meta.get('returncode')}"
985
+ f" signal={pty_meta.get('signal')} raw={pty_meta.get('raw_sha256')}"
986
+ f" timeline={len(pty_meta.get('timeline') or [])}"
987
+ f" split-nonce={pty_meta.get('split_nonce')}"
988
+ f" prompt-id={prompt_observation.get('prompt_identity')}"
989
+ f" turn={prompt_observation.get('turn_id')}"
990
+ f" consumed={prompt_observation.get('input_consumed')}"
991
+ f" startup-failure={prompt_observation.get('startup_failure')}"
992
+ )
993
+ return {
994
+ "id": case["id"],
995
+ "ok": bool(ok),
996
+ "blocking": case.get("blocking", True),
997
+ "why": why,
998
+ "evidence": [
999
+ {
1000
+ "kind": "tui-prompt-observer",
1001
+ "data": prompt_observation,
1002
+ }
1003
+ ],
1004
+ }
1005
+
1006
+
1007
+ _CRASH_SIGNS = ("Traceback (most recent call last)", "UnhandledError", "panic:",
1008
+ "Unhandled exception", "RuntimeError:", "KeyError:", "AttributeError:",
1009
+ "ValueError:")
1010
+
1011
+
1012
+
1013
+ def _seen(res, tok):
1014
+ return any((r.get("probes") or {}).get(tok) for r in (res.get("reqs") or []))
1015
+
1016
+
1017
+ def _history_recall_facts(
1018
+ pty_result: dict,
1019
+ event_names: str | tuple[str, ...],
1020
+ own_token: str,
1021
+ foreign_token: str,
1022
+ ) -> dict:
1023
+ names = (event_names,) if isinstance(event_names, str) else event_names
1024
+ output = "".join(
1025
+ str(_event_result(pty_result, name).get("output_text") or "")
1026
+ for name in names
1027
+ )
1028
+ scoped_inputs = [
1029
+ bytes.fromhex(str(_event_result(pty_result, name).get("input_hex") or ""))
1030
+ for name in names
1031
+ ]
1032
+ writes = b"".join(scoped_inputs)
1033
+ return {
1034
+ "own_visible": own_token in output,
1035
+ "foreign_visible": foreign_token in output,
1036
+ "own_absent_from_input": own_token.encode() not in writes,
1037
+ "foreign_absent_from_input": foreign_token.encode() not in writes,
1038
+ "ctrl_r_exact_write": bytes((0x12,)) in scoped_inputs,
1039
+ }
1040
+
1041
+
1042
+ def _event_wrote_line(pty_result: dict, name: str, text: str) -> bool:
1043
+ return (
1044
+ str(_event_result(pty_result, name).get("input_hex") or "")
1045
+ == (text + "\r").encode().hex()
1046
+ )
1047
+
1048
+
1049
+ def chk_history_fresh_control(slot: str):
1050
+ """Zero-weight cross-process history/readback control for one workspace."""
1051
+ own = _HISTORY_A_TOKEN if slot == "A" else _HISTORY_B_TOKEN
1052
+ foreign = _HISTORY_B_TOKEN if slot == "A" else _HISTORY_A_TOKEN
1053
+
1054
+ def _f(res):
1055
+ facts = res.get("history") or {}
1056
+ snapshot = facts.get("snapshot") or {}
1057
+ paths = _history_token_paths(snapshot, own)
1058
+ foreign_paths = _history_token_paths(snapshot, foreign)
1059
+ recall = _history_recall_facts(
1060
+ facts.get("reader") or {},
1061
+ ("ctrl-r-start", "ctrl-r-query"),
1062
+ own,
1063
+ foreign,
1064
+ )
1065
+ drove = _event_wrote_line(
1066
+ facts.get("writer") or {},
1067
+ "write-token",
1068
+ own,
1069
+ )
1070
+ ok = (
1071
+ drove
1072
+ and bool(paths)
1073
+ and not foreign_paths
1074
+ and recall["own_visible"]
1075
+ and not recall["foreign_visible"]
1076
+ and recall["own_absent_from_input"]
1077
+ and recall["foreign_absent_from_input"]
1078
+ and recall["ctrl_r_exact_write"]
1079
+ )
1080
+ return ok, (
1081
+ f"fresh-{slot} exact-PTY-line={drove} history_paths={paths} foreign_paths={foreign_paths} "
1082
+ f"Ctrl+R readback={recall} (zero-weight control: the same realpath is recoverable across "
1083
+ "processes, the complete token never appears in the reader's input, and PTY echo cannot "
1084
+ "compensate for it)"
1085
+ )
1086
+
1087
+ return _f
1088
+
1089
+
1090
+ def chk_history_realpath_key(res):
1091
+ """A lossy-slug collision must not merge the input history of two real workspaces."""
1092
+ facts = res.get("history") or {}
1093
+ snapshot_a = facts.get("snapshot_a") or {}
1094
+ snapshot_ab = facts.get("snapshot_ab") or {}
1095
+ a_before = _history_token_paths(snapshot_a, _HISTORY_A_TOKEN)
1096
+ a_final = _history_token_paths(snapshot_ab, _HISTORY_A_TOKEN)
1097
+ b_final = _history_token_paths(snapshot_ab, _HISTORY_B_TOKEN)
1098
+ recall_a = _history_recall_facts(
1099
+ facts.get("reader_a") or {},
1100
+ ("ctrl-r-start", "ctrl-r-query"),
1101
+ _HISTORY_A_TOKEN,
1102
+ _HISTORY_B_TOKEN,
1103
+ )
1104
+ recall_b = _history_recall_facts(
1105
+ facts.get("reader_b") or {},
1106
+ ("ctrl-r-start", "ctrl-r-query"),
1107
+ _HISTORY_B_TOKEN,
1108
+ _HISTORY_A_TOKEN,
1109
+ )
1110
+ fixture = (
1111
+ facts.get("realpaths_distinct")
1112
+ and facts.get("basename_collision")
1113
+ and facts.get("lossy_slug_a") == facts.get("lossy_slug_b")
1114
+ )
1115
+ isolated_bytes = (
1116
+ bool(a_before)
1117
+ and bool(a_final)
1118
+ and bool(b_final)
1119
+ and set(a_final).isdisjoint(b_final)
1120
+ )
1121
+ recalled = all(
1122
+ row["own_visible"]
1123
+ and not row["foreign_visible"]
1124
+ and row["own_absent_from_input"]
1125
+ and row["foreign_absent_from_input"]
1126
+ and row["ctrl_r_exact_write"]
1127
+ for row in (recall_a, recall_b)
1128
+ )
1129
+ drove = _event_wrote_line(
1130
+ facts.get("writer_a") or {},
1131
+ "write-token",
1132
+ _HISTORY_A_TOKEN,
1133
+ ) and _event_wrote_line(
1134
+ facts.get("writer_b") or {},
1135
+ "write-token",
1136
+ _HISTORY_B_TOKEN,
1137
+ )
1138
+ ok = bool(fixture and drove and isolated_bytes and recalled)
1139
+ return ok, (
1140
+ f"fixture(realpath-distinct/basename+slug-collision)={fixture} exact-PTY-lines={drove} "
1141
+ f"A-before={a_before} A-final={a_final} B-final={b_final} "
1142
+ f"bytes isolated={isolated_bytes} readback-A={recall_a} readback-B={recall_b} "
1143
+ "(v6§5.7:379: each of the two real working directories must read back its own history with "
1144
+ "no cross-contamination)"
1145
+ )
1146
+
1147
+
1148
+ def chk_survives_chaos(res):
1149
+ """Keyboard-mashing: after a burst of random input the session must still handle input normally and must not crash.
1150
+
1151
+ Liveness evidence: this layer always feeds `!echo <DONE>` after all input; if it appears in the
1152
+ pty text the TUI survived the mashing and can still handle input. If it does not appear the
1153
+ session crashed, hung, or is stuck in an unescapable mode.
1154
+ Self-gating: pty returned nothing -> interactive entry point unreachable -> inconclusive.
1155
+ """
1156
+ txt = res.get("text") or ""
1157
+ if not txt.strip():
1158
+ return True, "inconclusive: the pty returned nothing at all, so this build's interactive entry point is unreachable at this layer"
1159
+ alive = DONE in txt
1160
+ crash = [s for s in _CRASH_SIGNS if s in txt]
1161
+ ok = alive and not crash
1162
+ return ok, (f"session still processing input after the input burst={alive} (closing sentinel) "
1163
+ f"· crash/uncaught-exception signatures={crash} "
1164
+ f"(per v6§9:473, malformed or exceptional input must degrade to a clean error and never "
1165
+ f"crash outright)")
1166
+
1167
+
1168
+ def chk_tui_file(path, token):
1169
+ """Direct-shell disk-landing surface: trusting the UI echo is insufficient; the target file must actually exist."""
1170
+ def _f(res):
1171
+ got = (res.get("files") or {}).get(path)
1172
+ ok = got is not None and token in got
1173
+ return ok, f"{path}={got!r} (a `!` command must really execute and write to disk, not merely echo the command text)"
1174
+ return _f
1175
+
1176
+
1177
+ def chk_tui_wire_survives(token):
1178
+ """After legal or abnormal key sequences: valid text must go on the wire, the session must handle the wind-down command, and no crash is allowed."""
1179
+ def _f(res):
1180
+ text = res.get("text") or ""
1181
+ on_wire = _seen(res, token)
1182
+ alive = DONE in text
1183
+ crash = [s for s in _CRASH_SIGNS if s in text]
1184
+ return on_wire and alive and not crash, (
1185
+ f"valid text on the wire={on_wire} session alive at wind-down={alive} crash={crash} "
1186
+ "(per v6§9:473 abnormal interactive input must neither crash outright nor wedge the session)"
1187
+ )
1188
+ return _f
1189
+
1190
+
1191
+ # Keyboard mashing: every control byte except those that end the line or the session, packed into
1192
+ # a SINGLE line so the case costs one no-request timeout rather than one per byte.
1193
+ _STORM = "".join(chr(c) for c in range(1, 27) if c not in (3, 4, 10, 13, 26))
1194
+
1195
+
1196
+ CASES: list[dict] = [
1197
+
1198
+ # === §5.3 x §9 input robustness (keyboard mashing) ===
1199
+ # v6§9:473: malformed or abnormal interactive input must degrade to a clean error, never a crash
1200
+ # or an uncaught exception printed to the UI (e.g. `ValueError: embedded null byte`).
1201
+ dict(id="tui_ctrl_byte_storm_survives", seed={}, stub={"probe_tokens": ["RB97A_7731"]},
1202
+ lines=[_STORM + " RB97A_7731"], timeout=90, check=chk_survives_chaos, blocking=False),
1203
+ dict(id="tui_bang_alone_enters_shell_mode",
1204
+ seed={}, stub={"probe_tokens": ["MODE100_7731"]},
1205
+ lines=["!", "printf 'MODE100_%s\\n' 7731 > mode100.txt"],
1206
+ files=["mode100.txt"], timeout=100,
1207
+ check=chk_tui_file("mode100.txt", "MODE100_7731"), blocking=False),
1208
+
1209
+ # === Workspace history isolation (1 scored target + 2 zero-weight controls) ===
1210
+ # v6§5.7:379 ("save input history per working directory; Ctrl+R reverse-search and reuse").
1211
+ #
1212
+ # Truth table:
1213
+ # control-A/B: a fresh process writes a full token from a real cwd, exits, then a new
1214
+ # process types only an incomplete prefix + physical 0x12 (Ctrl+R); raw history bytes
1215
+ # and Ctrl+R output must contain the full token, reader input must NOT.
1216
+ # realpath target: A=`.../piece_a_b/leaf`, B=`.../piece_a/b/leaf`; realpaths differ
1217
+ # but basename and any lossy slug are the same. History token paths must be non-empty,
1218
+ # mutually exclusive, and each Ctrl+R reads only its own side.
1219
+ # mutant: using basename/lossy-slug as the unique key causes byte-path overlap or a
1220
+ # foreign token to appear -> FAIL.
1221
+ # empty/NA: unhealthy fresh control, or entry point / persistent history / Ctrl+R not
1222
+ # reachable -> gates convert to NA; prompt not ready uses unified inconclusive.
1223
+ dict(
1224
+ id="history_workspace_a_fresh_control",
1225
+ scenario="history-fresh-a",
1226
+ seed={},
1227
+ stub={
1228
+ "mode": "fixed_reply",
1229
+ "reply_content": "history-control-a-ok",
1230
+ "probe_tokens": [_HISTORY_A_TOKEN, _HISTORY_B_TOKEN],
1231
+ },
1232
+ timeout=90,
1233
+ check=chk_history_fresh_control("A"),
1234
+ blocking=False,
1235
+ ),
1236
+ dict(
1237
+ id="history_workspace_b_fresh_control",
1238
+ scenario="history-fresh-b",
1239
+ seed={},
1240
+ stub={
1241
+ "mode": "fixed_reply",
1242
+ "reply_content": "history-control-b-ok",
1243
+ "probe_tokens": [_HISTORY_A_TOKEN, _HISTORY_B_TOKEN],
1244
+ },
1245
+ timeout=90,
1246
+ check=chk_history_fresh_control("B"),
1247
+ blocking=False,
1248
+ ),
1249
+ dict(
1250
+ id="history_realpath_key",
1251
+ scenario="history-realpath-key",
1252
+ seed={},
1253
+ stub={
1254
+ "mode": "fixed_reply",
1255
+ "reply_content": "history-realpath-ok",
1256
+ "probe_tokens": [_HISTORY_A_TOKEN, _HISTORY_B_TOKEN],
1257
+ },
1258
+ timeout=140,
1259
+ gates=[
1260
+ "history_workspace_a_fresh_control",
1261
+ "history_workspace_b_fresh_control",
1262
+ ],
1263
+ check=chk_history_realpath_key,
1264
+ ),
1265
+ ]
1266
+
1267
+
1268
+ def _selected_cases(raw: str | None = None) -> list[dict]:
1269
+ """Apply D2A_ONLY_IDS without changing manifest order or widening unknown IDs."""
1270
+ value = os.environ.get("D2A_ONLY_IDS", "") if raw is None else raw
1271
+ if not value.strip():
1272
+ return list(CASES)
1273
+ requested = [item.strip() for item in value.split(",") if item.strip()]
1274
+ if len(requested) != len(set(requested)):
1275
+ raise ValueError("D2A_ONLY_IDS contains duplicate IDs")
1276
+ known = {case["id"] for case in CASES}
1277
+ unknown = sorted(set(requested) - known)
1278
+ if unknown:
1279
+ raise ValueError(f"D2A_ONLY_IDS contains unknown tui_line IDs: {unknown}")
1280
+ wanted = set(requested)
1281
+ return [case for case in CASES if case["id"] in wanted]
1282
+
1283
+
1284
+ def main() -> int:
1285
+ """Entry point isomorphic to other layers: `python tui_line.py <agent_dir> --emit-json`."""
1286
+ import argparse
1287
+ ap = argparse.ArgumentParser()
1288
+ ap.add_argument("agent_dir", nargs="?", default=".")
1289
+ ap.add_argument("--emit-json", action="store_true")
1290
+ ap.add_argument("--case-id", default="")
1291
+ ap.add_argument("--result-file", default="")
1292
+ args = ap.parse_args()
1293
+ agent = Path(args.agent_dir)
1294
+ results = []
1295
+ try:
1296
+ selected = _selected_cases()
1297
+ if args.case_id:
1298
+ known = {case["id"] for case in CASES}
1299
+ if args.case_id not in known:
1300
+ raise ValueError(f"unknown --case-id: {args.case_id}")
1301
+ selected = [case for case in selected if case["id"] == args.case_id]
1302
+ except ValueError as exc:
1303
+ print(f"TUI_LINE_SELECTION_ERROR={exc}", file=sys.stderr)
1304
+ return 2
1305
+ for case in selected:
1306
+ try:
1307
+ result = _run_one(agent, case)
1308
+ except Exception as e: # per-case exception does not abort the whole layer
1309
+ result = {"id": case["id"], "ok": False,
1310
+ "blocking": case.get("blocking", True),
1311
+ "why": f"runner error: {e!r}"}
1312
+ results.append(result)
1313
+ if args.result_file:
1314
+ path = Path(args.result_file)
1315
+ path.parent.mkdir(parents=True, exist_ok=True)
1316
+ with path.open("a", encoding="utf-8") as handle:
1317
+ handle.write(json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n")
1318
+ handle.flush()
1319
+ os.fsync(handle.fileno())
1320
+ for r in results:
1321
+ print(f" [{'PASS' if r['ok'] else 'FAIL'}] {r['id']}: {r['why'][:160]}")
1322
+ if args.emit_json:
1323
+ print("TUILINE_RESULTS=" + json.dumps(results, ensure_ascii=False))
1324
+ blocking_ok = all(r["ok"] for r in results if r.get("blocking"))
1325
+ if blocking_ok:
1326
+ print("TUI_LINE_SMOKE_OK")
1327
+ return 0
1328
+
1329
+
1330
+ if __name__ == "__main__":
1331
+ raise SystemExit(main())
code/src/stage1/smoke/tui_smoke.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Interactive TUI rendering smoke test (pty, zero model budget).
3
+
4
+ Why it exists: headless (`-p`) and the interactive TUI are two independent
5
+ implementations. Testing only headless systematically misses render-layer bugs
6
+ where the logic is correct and the text is printed, but the terminal Live region
7
+ erases it and the user sees nothing. Classic case: printing the reply inside a
8
+ `rich console.status()` Live spinner context, where each spinner refresh clears
9
+ the line with `\r\x1b[2K` and wipes the reply -> blank after "Assistant:".
10
+
11
+ Must run under a real pty: without a tty, rich's Live is a no-op and does not
12
+ repaint, so the bug does not reproduce and the test would falsely pass.
13
+
14
+ Two complementary guards, both required:
15
+ A) render_stub - stubs `_agentic_turn` to return a fixed sentinel, checking
16
+ only that the render layer displays a non-empty reply. Isolates render bugs
17
+ precisely, but bypasses the turn itself.
18
+ B) e2e_reply - no stub; points the real TUI at the mock gateway (known reply
19
+ text) and runs the full `_agentic_turn` -> model -> render chain. Whether
20
+ the reply is erased by rendering, or the turn returns empty/crashes, or the
21
+ model is wired up wrong, B fails whenever the user cannot see the reply.
22
+
23
+ Usage: python tui_smoke.py <agent_dir> [--emit-json] (needs the d2a interpreter that bundles
24
+ litellm)
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ import re
30
+ import select
31
+ import subprocess
32
+ import sys
33
+ import tempfile
34
+ import threading
35
+ import time
36
+ from pathlib import Path
37
+
38
+ HERE = Path(__file__).resolve().parent
39
+ sys.path.insert(0, str(HERE))
40
+ import mock_gateway as MG # noqa: E402
41
+
42
+ STUB_SENTINEL = "YUYAO_TUI_STUB_SENTINEL_4242"
43
+ E2E_SENTINEL = "YUYAO_TUI_E2E_REPLY_8841"
44
+ DONE = "__TUI_SMOKE_DONE__"
45
+ _ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b[@-Z\\-_]|[\r\x07\x08]")
46
+ _RICH = re.compile(r"\[[^\]]*\]")
47
+ _REPLY_HEADERS = ("Assistant:", "Agent:")
48
+
49
+
50
+ def _plain(visible: str) -> str:
51
+ return _RICH.sub("", visible)
52
+
53
+
54
+
55
+
56
+ # Adaptive bootstrap: discover and drive the interactive layer by behavioural
57
+ # contract, without pinning internal layout/class/method names (see state_smoke._BOOT).
58
+ # Rendering also needs the chat/turn method name resolved (chat / handle_message /
59
+ # agentic_turn vary by build); see _say / _TURN_NAMES.
60
+ _BOOT = '''
61
+ import importlib as _il, inspect as _ins
62
+ _DISP_NAMES = ("handle_command","handle_slash_command","dispatch_command","run_command","do_command","slash_command","on_command","handle_input")
63
+ _TURN_NAMES = ("_agentic_turn","agentic_turn","run_turn","turn","step","agent_loop","_turn","_run_turn")
64
+ _SAY_NAMES = ("chat","handle_message","process_message","process_user_message","send_message","ask","run_once","prompt_once")
65
+ def _find_cls(mods, pred):
66
+ for _mn in mods:
67
+ try: _m = _il.import_module(_mn)
68
+ except Exception: continue
69
+ for _nm, _c in _ins.getmembers(_m, _ins.isclass):
70
+ try:
71
+ if not getattr(_c, "__module__", "").startswith("yuyao"): continue
72
+ if pred(_c): return _c
73
+ except Exception: pass
74
+ return None
75
+ _CfgCls = _find_cls(("yuyao.core.config","yuyao.config","yuyao.core.agent_config","yuyao.agent.config","yuyao.core.agent"),
76
+ lambda c: hasattr(c, "from_env"))
77
+ _TUICls = _find_cls(("yuyao.tui.main","yuyao.tui","yuyao.tui.app","yuyao.cli","yuyao.app","yuyao.core.tui","yuyao.interface","yuyao.main","yuyao.repl"),
78
+ lambda c: any(callable(getattr(c, _d, None)) for _d in _DISP_NAMES))
79
+ assert _TUICls is not None, "no TUI class with a slash-dispatch method found"
80
+ class _Args(object):
81
+ def __init__(self, **kw): self.__dict__.update(kw)
82
+ def __getattr__(self, n): return None
83
+ def _mk_tui(deny_rules=None):
84
+ _dr = list(deny_rules or [])
85
+ _cfg = None
86
+ if _CfgCls is not None:
87
+ for _ctor in (lambda: _CfgCls.from_env(), lambda: _CfgCls()):
88
+ try: _cfg = _ctor(); break
89
+ except Exception: _cfg = None
90
+ _args = _Args(mode=None, role=None, max_steps=20, stream="off", model=None,
91
+ deny=_dr, deny_rules=_dr, no_memory=False, repo_dir=None, cwd=None, yolo=False)
92
+ _att = []
93
+ if _cfg is not None:
94
+ _att.append(((_cfg,), {"deny_rules": _dr}))
95
+ _att.append(((_cfg,), {}))
96
+ _att.append(((_args,), {}))
97
+ _att.append(((), {}))
98
+ _last = None
99
+ for _a, _k in _att:
100
+ try:
101
+ return _TUICls(*_a, **_k)
102
+ except Exception as _e:
103
+ _last = _e
104
+ raise _last
105
+ def _set_stream(tui, on):
106
+ for _a in ("stream_enabled","stream","streaming"):
107
+ try: setattr(tui, _a, on)
108
+ except Exception: pass
109
+ try: tui.config.stream = on
110
+ except Exception: pass
111
+ def _ensure_model(tui):
112
+ if getattr(tui, "model", None) is not None: return
113
+ _mc = getattr(tui, "model_config", None)
114
+ if _mc is not None:
115
+ for _bm in ("build_model", "create_model", "get_model"):
116
+ _f = getattr(_mc, _bm, None)
117
+ if callable(_f):
118
+ try:
119
+ tui.model = _f(); return
120
+ except Exception: pass
121
+ if callable(getattr(_mc, "is_configured", None)) and _mc.is_configured():
122
+ try:
123
+ tui.model = _mc.build_model(); return
124
+ except Exception: pass
125
+ for _sm in ("setup_model","_setup_model","init_model","connect_model","_connect_model","setup"):
126
+ _f = getattr(tui, _sm, None)
127
+ if callable(_f):
128
+ try: _f()
129
+ except Exception: pass
130
+ if getattr(tui, "model", None) is not None: return
131
+ def _wire_model_config(tui):
132
+ # TUI constructor signatures vary between versions; always supply model_config from
133
+ # D2A_MODEL_* so an e2e run cannot accidentally reach the default upstream (reqs=0).
134
+ _cfg = {"model_name": os.environ.get("D2A_MODEL_NAME", ""),
135
+ "model_kwargs": {"api_base": os.environ.get("D2A_MODEL_BASE_URL", ""),
136
+ "api_key": os.environ.get("D2A_MODEL_API_KEY", "sk-x")}}
137
+ for _attr in ("model_config",):
138
+ try:
139
+ _v = getattr(tui, _attr, None)
140
+ if isinstance(_v, dict):
141
+ _v.update(_cfg); return
142
+ except Exception: pass
143
+ try: tui.model_config = _cfg
144
+ except Exception: pass
145
+ def _ensure_executor(tui):
146
+ if getattr(tui, "executor", None) is not None: return
147
+ _wire_model_config(tui)
148
+ for _nm in ("_ensure_executor", "_init_session", "_init_runtime", "_bootstrap"):
149
+ _f = getattr(tui, _nm, None)
150
+ if callable(_f):
151
+ try: _f()
152
+ except Exception: pass
153
+ if getattr(tui, "executor", None) is not None: return
154
+ try:
155
+ from minisweagent.models import get_model
156
+ from minisweagent.environments.local import LocalEnvironment
157
+ _mc = getattr(tui, "model_config", None) or {}
158
+ if not isinstance(_mc, dict): _mc = {}
159
+ if getattr(tui, "model", None) is None:
160
+ tui.model = get_model(config={"model_class": "litellm", **_mc})
161
+ if getattr(tui, "env", None) is None:
162
+ tui.env = LocalEnvironment(cwd=getattr(tui, "cwd", None) or os.getcwd())
163
+ _Ex = None
164
+ for _mn in ("yuyao.agent_wrapper", "yuyao.executor", "yuyao.core.executor"):
165
+ try:
166
+ _m = _il.import_module(_mn)
167
+ _Ex = getattr(_m, "AgenticTurnExecutor", None) or getattr(_m, "TurnExecutor", None)
168
+ if _Ex is not None: break
169
+ for _cn, _c in _ins.getmembers(_m, _ins.isclass):
170
+ if "executor" in _cn.lower():
171
+ _Ex = _c; break
172
+ except Exception: pass
173
+ if _Ex is not None: break
174
+ if _Ex is None: return
175
+ _kw = {"max_steps": getattr(tui, "max_steps", 50), "mode": getattr(tui, "mode", "ask"),
176
+ "role": getattr(tui, "role", "execute"), "auto_commit": getattr(tui, "auto_commit", False)}
177
+ for _args in ((tui.model, tui.env), (tui.model, tui.env, _kw.get("max_steps"))):
178
+ try:
179
+ tui.executor = _Ex(*_args, **_kw); return
180
+ except TypeError:
181
+ try: tui.executor = _Ex(*_args); return
182
+ except Exception: pass
183
+ except Exception: pass
184
+ except Exception: pass
185
+ def _stream_on(tui):
186
+ for _a in ("stream_enabled", "stream", "streaming"):
187
+ try:
188
+ _v = getattr(tui, _a, None)
189
+ if _v in (True, "on", "ON", 1): return True
190
+ except Exception: pass
191
+ return False
192
+ def _fake_executor(sentinel):
193
+ class _Ex:
194
+ messages = []
195
+ def agentic_turn(self, *a, **k): return sentinel
196
+ def agentic_turn_streaming(self, msg, console=None, **k):
197
+ if console is not None:
198
+ try: console.print(sentinel)
199
+ except Exception:
200
+ import sys; sys.stdout.write(sentinel + "\\n"); sys.stdout.flush()
201
+ else:
202
+ import sys; sys.stdout.write(sentinel + "\\n"); sys.stdout.flush()
203
+ return sentinel
204
+ return _Ex()
205
+ def _stub_turn(tui, sentinel):
206
+ # Stubbing must cover executor.agentic_turn*: many builders route chat/process_user_message
207
+ # through the executor rather than TUI.turn.
208
+ _fn = (lambda *a, **k: sentinel)
209
+ def _render(msg, *a, **k):
210
+ _c = getattr(tui, "console", None)
211
+ if _c is not None:
212
+ try: _c.print("Assistant: " + sentinel)
213
+ except Exception: pass
214
+ else:
215
+ import sys; sys.stdout.write("Assistant: " + sentinel + "\\n"); sys.stdout.flush()
216
+ return sentinel
217
+ for _tn in _TURN_NAMES:
218
+ try: setattr(tui, _tn, _fn)
219
+ except Exception: pass
220
+ for _pm in ("process_message", "process_user_message"):
221
+ if callable(getattr(tui, _pm, None)):
222
+ try: setattr(tui, _pm, _render)
223
+ except Exception: pass
224
+ _ex = getattr(tui, "executor", None)
225
+ if _ex is None:
226
+ tui.executor = _fake_executor(sentinel)
227
+ else:
228
+ try: _ex.agentic_turn = _fn
229
+ except Exception: pass
230
+ try:
231
+ def _stream(msg, console=None, **k):
232
+ if console is not None:
233
+ try: console.print(sentinel)
234
+ except Exception: pass
235
+ return sentinel
236
+ _ex.agentic_turn_streaming = _stream
237
+ except Exception: pass
238
+ def _say(tui, text):
239
+ _ensure_model(tui)
240
+ _ensure_executor(tui)
241
+ if _stream_on(tui):
242
+ for _pm in ("process_user_message", "process_message"):
243
+ _pmf = getattr(tui, _pm, None)
244
+ if callable(_pmf):
245
+ try: _pmf(text); return ""
246
+ except Exception: pass
247
+ for _nm in _SAY_NAMES:
248
+ _f = getattr(tui, _nm, None)
249
+ if callable(_f): return _f(text)
250
+ try: tui.messages.append({"role":"user","content":text})
251
+ except Exception: pass
252
+ for _tn in _TURN_NAMES:
253
+ _t = getattr(tui, _tn, None)
254
+ if not callable(_t): continue
255
+ # Turn-method signatures vary between versions: some take the user text as a positional
256
+ # argument (e.g. run_turn(self, user)), others take none (the message is already in
257
+ # tui.messages and the method reads it itself). Older code always called _t() with no
258
+ # arguments, which raised a spurious TypeError (missing 'user') for the first kind.
259
+ # Inspect the signature to decide whether a positional argument is needed; if that
260
+ # inspection is inconclusive, try both arities.
261
+ try:
262
+ _sig = _ins.signature(_t)
263
+ _need = any(
264
+ (_p.kind in (_p.POSITIONAL_ONLY, _p.POSITIONAL_OR_KEYWORD) and _p.default is _p.empty)
265
+ or _p.kind == _p.VAR_POSITIONAL
266
+ for _p in _sig.parameters.values())
267
+ except (TypeError, ValueError):
268
+ _need = True
269
+ try:
270
+ return _t(text) if _need else _t()
271
+ except TypeError:
272
+ try: return _t(text)
273
+ except TypeError: return _t()
274
+ raise RuntimeError("no chat/turn method on TUI")
275
+ '''
276
+
277
+
278
+ def _preamble(agent_src: str, stream: bool, base_url: str, model: str) -> str:
279
+ return (
280
+ "import os,sys,json\n"
281
+ # Put both `<agent>/src` and `<agent>` on the path: §0.1.2 only requires an
282
+ # importable `yuyao.agent_api` module and says nothing about directory layout.
283
+ # A flat layout (`yuyao/` at the project root) is one of setuptools' two
284
+ # standard layouts, so inserting only `<agent>/src` would break every import
285
+ # in such builds and fail them spuriously.
286
+ f"sys.path.insert(0, {agent_src!r})\n"
287
+ f"sys.path.insert(0, {os.path.dirname(agent_src)!r})\n"
288
+ f"os.environ['D2A_MODEL_BASE_URL']={base_url!r}\n"
289
+ f"os.environ['D2A_MODEL_NAME']={model!r}; os.environ['D2A_MODEL_API_KEY']='sk-x'\n"
290
+ "os.environ['MSWEA_SILENT_STARTUP']='1'\n"
291
+ + _BOOT +
292
+ "tui = _mk_tui()\n"
293
+ "_wire_model_config(tui)\n"
294
+ f"_set_stream(tui, {stream})\n"
295
+ )
296
+
297
+
298
+ def _child_stub(agent_src: str, stream: bool) -> str:
299
+ # No model at all; stub the turn method so only the render layer is exercised.
300
+ return (
301
+ _preamble(agent_src, stream, "http://127.0.0.1:1", "m")
302
+ + f"_stub_turn(tui, {STUB_SENTINEL!r})\n"
303
+ + "_say(tui, 'hi')\n"
304
+ + f"sys.stdout.write('\\n{DONE}\\n'); sys.stdout.flush()\n"
305
+ )
306
+
307
+
308
+ def _child_e2e(agent_src: str, stream: bool, port: int) -> str:
309
+ # Real chain: point at the mock gateway and run the real turn (no stub).
310
+ return (
311
+ _preamble(agent_src, stream, f"http://127.0.0.1:{port}", "litellm_proxy/mock")
312
+ + "_say(tui, 'hi')\n"
313
+ + f"sys.stdout.write('\\n{DONE}\\n'); sys.stdout.flush()\n"
314
+ )
315
+
316
+
317
+ def _run_in_pty(agent_dir: Path, child_code: str, timeout: float = 30.0) -> str:
318
+ """Run the given child code in a real pty; return the visible text, ANSI stripped."""
319
+ import pty
320
+ py = sys.executable
321
+ master, slave = pty.openpty()
322
+ workdir = tempfile.mkdtemp(prefix="tui_smoke_")
323
+ env = dict(os.environ)
324
+ env["COLUMNS"] = "80"; env["LINES"] = "24"; env["TERM"] = "xterm"
325
+ env["HOME"] = workdir # isolate ~/.yuyao; never touch the real home
326
+ p = subprocess.Popen([py, "-c", child_code], stdin=slave, stdout=slave, stderr=slave,
327
+ cwd=workdir, env=env, close_fds=True)
328
+ os.close(slave)
329
+ buf = b""
330
+ deadline = time.time() + timeout
331
+ while time.time() < deadline:
332
+ r, _, _ = select.select([master], [], [], 0.5)
333
+ if r:
334
+ try:
335
+ data = os.read(master, 65536)
336
+ except OSError:
337
+ break
338
+ if not data:
339
+ break
340
+ buf += data
341
+ if DONE.encode() in buf:
342
+ break
343
+ elif p.poll() is not None:
344
+ try:
345
+ while True:
346
+ data = os.read(master, 65536)
347
+ if not data:
348
+ break
349
+ buf += data
350
+ except OSError:
351
+ pass
352
+ break
353
+ try:
354
+ os.close(master)
355
+ except OSError:
356
+ pass
357
+ try:
358
+ p.wait(timeout=5)
359
+ except Exception:
360
+ p.kill()
361
+ return _ANSI.sub("", buf.decode("utf-8", errors="replace"))
362
+
363
+
364
+ def _check(visible: str, sentinel: str, label: str) -> dict:
365
+ plain = _plain(visible)
366
+ finished = DONE in visible
367
+ seen = sentinel in plain # reply text visible in the real render (not erased by the spinner)
368
+ header = any(h in plain for h in _REPLY_HEADERS)
369
+ ok = finished and seen
370
+ why = f"reply visible in render={seen} reply header present={header} run completed={finished}"
371
+ if header and not seen:
372
+ why += " <- classic symptom: header rendered but the reply was erased (the 'mute agent' failure)"
373
+ if not finished:
374
+ why += f" | last 80 chars={visible[-80:]!r}"
375
+ return {"id": label, "ok": ok, "blocking": True, "why": why}
376
+
377
+
378
+ def run_smoke(agent_dir: Path) -> list[dict]:
379
+ results = []
380
+ # A) render-isolation guard (stubbed turn): stream on/off
381
+ for stream in (True, False):
382
+ try:
383
+ vis = _run_in_pty(agent_dir, _child_stub(str((agent_dir / "src").resolve()), stream))
384
+ results.append(_check(vis, STUB_SENTINEL, f"render_stub_stream_{stream}"))
385
+ except Exception as e:
386
+ results.append({"id": f"render_stub_stream_{stream}", "ok": False, "blocking": True,
387
+ "why": f"harness error while running the case {type(e).__name__}: {e}"})
388
+ # B) end-to-end guard (no stub, real mock gateway): stream on/off
389
+ for stream in (True, False):
390
+ srv = None
391
+ try:
392
+ cfg = MG.new_cfg(mode="plain_no_tool", reply_content=E2E_SENTINEL)
393
+ srv = MG.make_server(cfg, 0)
394
+ port = srv.server_address[1]
395
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
396
+ vis = _run_in_pty(agent_dir, _child_e2e(str((agent_dir / "src").resolve()), stream, port))
397
+ res = _check(vis, E2E_SENTINEL, f"e2e_reply_stream_{stream}")
398
+ res["why"] += f" reqs={len(cfg['requests'])}"
399
+ results.append(res)
400
+ except Exception as e:
401
+ results.append({"id": f"e2e_reply_stream_{stream}", "ok": False, "blocking": True,
402
+ "why": f"harness error while running the case {type(e).__name__}: {e}"})
403
+ finally:
404
+ if srv is not None:
405
+ srv.shutdown()
406
+ return results
407
+
408
+
409
+ def main():
410
+ import argparse
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("agent_dir")
413
+ ap.add_argument("--emit-json", action="store_true",
414
+ help="additionally print TUI_RESULTS=<json> + TUI_SMOKE_OK/FAIL for pipeline consumption")
415
+ args = ap.parse_args()
416
+ agent_dir = Path(args.agent_dir)
417
+ if (agent_dir / "agent").is_dir():
418
+ agent_dir = agent_dir / "agent"
419
+ # Found if `yuyao/` sits under either `src/` or the project root: §0.1.2 does not
420
+ # mandate a directory layout, so a flat layout is equally valid.
421
+ if not any((agent_dir / c / "yuyao").is_dir() for c in ("src", ".")) \
422
+ and not (agent_dir / "src").is_dir():
423
+ print(f"[tui_smoke] agent src not found: {agent_dir}", file=sys.stderr)
424
+ if args.emit_json:
425
+ print('TUI_RESULTS=[{"id": "_tui_harness", "ok": false, "blocking": true, "why": "no agent src"}]')
426
+ print("TUI_SMOKE_FAIL")
427
+ sys.exit(2)
428
+ print(f"[tui_smoke] agent: {agent_dir}")
429
+ results = run_smoke(agent_dir)
430
+ npass = sum(r["ok"] for r in results)
431
+ for r in results:
432
+ print(f"[{'PASS' if r['ok'] else 'FAIL'}] {r['id']:24s} {r['why']}")
433
+ print(f"== TUI render smoke: {npass}/{len(results)} passed ==")
434
+ import json as _json
435
+ blocking_ok = all(r["ok"] for r in results if r.get("blocking"))
436
+ if args.emit_json:
437
+ print("TUI_RESULTS=" + _json.dumps(results, ensure_ascii=False))
438
+ print("TUI_SMOKE_OK" if blocking_ok else "TUI_SMOKE_FAIL")
439
+ sys.exit(0 if npass == len(results) else 1)
440
+
441
+
442
+ if __name__ == "__main__":
443
+ main()
code/src/stage1/spec/functional_spec_v6.md ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Functional Specification — Super Coding Agent
2
+
3
+ > This document defines the complete external surface of a "super coding agent": built-in tools, top-level commands, global flags, permission and role modes, in-session slash commands, the persistent memory system, convention files, and exit codes.
4
+ > From this specification the builder must produce an agent that is installable, interactive, and capable of unattended execution.
5
+ > Every feature listed in this document is a required item.
6
+ > §8 adds cross-cutting consistency rules and specifies the externally observable surfaces on which the effect of each feature must land.
7
+ ---
8
+
9
+ ## 0. Deliverables and Runtime Interfaces
10
+
11
+ ### 0.1 Deliverables
12
+ | Deliverable | Description |
13
+ |---|---|
14
+ | Installation script | One-shot installation (e.g. `install.sh`); once it has run, the `yuyao` command must be usable (for the product name see §0.4). It ships and declares all dependencies. |
15
+ | Interactive terminal interface (TUI / REPL) | `yuyao` starts an interactive session supporting the slash commands of §5, the keyboard shortcuts, and the input prefixes. For interface requirements see §0.6. |
16
+ | Non-interactive entry point `run_agent.sh` | For unattended invocation by external programs. |
17
+
18
+ #### 0.1.1 Required Interfaces
19
+
20
+ 1. **The artifact root must contain**: `run_agent.sh`, `entry.py`, `wheels/` (≥1 offline wheel), `requirements.lock`, `VERSION`.
21
+ 2. **`run_agent.sh` must accept and correctly handle these 7 arguments**: `--task-file`, `--repo-dir`, `--model-base-url`, `--model-name`, `--model-api-key`, `--budget-file`, `--out-dir`. The formats of the two input files are defined in `.d2a_spec/AGENT_CONTRACT.md`.
22
+ 3. **The model must be reached only through `--model-base-url`** (through `D2A_MODEL_*` in the TUI); no other egress address or credential may be hardcoded.
23
+ 4. **Code must be modified in place under `--repo-dir`**; execution traces and status must be written to `--out-dir` (`status.json` carrying `exit_status` and `cost_usd`, plus `.trajectory/`), and must not be written into `--repo-dir`.
24
+ 5. **The step limit in `--budget-file` must be honoured** (on reaching the limit, stop cleanly and record `LimitsExceeded`); exit codes must follow §9 (`Submitted`/`LimitsExceeded` → 0, error → 1, usage error → 2).
25
+ 6. **New third-party dependencies must be declared** under `[project.dependencies]` in `pyproject.toml` (or in `requirements.txt`) and must remain installable offline (the runtime environment has no network access).
26
+ 7. **`install.sh` must complete the installation in one shot**, leaving the `yuyao` command usable immediately afterwards.
27
+ 8. **`yuyao` must connect to the model with zero configuration**: when `D2A_MODEL_BASE_URL/NAME/API_KEY` are already present in the environment, the TUI must read them automatically, connect directly, and be usable at once.
28
+ 9. **Model calls must be real**: both the TUI and headless mode must genuinely send requests to the model and return the model's actual output.
29
+ 10. **The interactive TUI must be a coding agent that really executes tools, not a pure chatbot**: the model must be granted the tools of §1 (at minimum bash/read/write/edit/grep/glob), and the agent must actually execute the tool calls the model issues, feed the results back to the model, and continue. Plain conversation (e.g. `hi`) is answered with ordinary text. For the calling and execution pattern, see `agentic_turn` in `.d2a_spec/model_call_reference.py`.
30
+ 11. **The standard programmatic interface `yuyao.agent_api` must be exposed**: see §0.1.2.
31
+
32
+ #### 0.1.2 Standard Programmatic Interface
33
+
34
+ > This interface allows external programs to drive the agent deterministically: construct a session → run slash commands → run one agentic turn → read observable state,
35
+ > all through this single fixed interface, without going through internal class names, constructor signatures, or turn method names.
36
+ > `deny` / `mode` / `role` take effect when passed, with the same semantics as the command-line flags and the in-session switches; when omitted, your own defaults apply.
37
+
38
+ Your package must provide an importable module `yuyao.agent_api` exposing:
39
+
40
+ ```python
41
+ def create_session(*, deny=None, mode=None, role=None, cwd=None) -> AgentSession
42
+ ```
43
+
44
+ The returned `AgentSession` must provide the following members:
45
+
46
+ | Member | Type / signature | Meaning |
47
+ |---|---|---|
48
+ | `.cwd` | `str` | Path of the current working directory |
49
+ | `.messages` | `list[dict]` | Message list of the active session (OpenAI style, including tool results); tool execution results must genuinely land in it |
50
+ | `.dispatch(command)` | `(str) -> str` | Execute one slash command (e.g. `"/config set k v"`, `"/ask"`, `"/mcp add x"`), with the same semantics as typing it interactively; returns text (possibly the empty string) |
51
+ | `.chat(text)` | `(str) -> str` | Run one agentic turn: tools are really executed, results are fed back to the model, which continues; returns the assistant's final text (the same "hands-on" loop as item 10 of §0.1.1) |
52
+ | `.config_get(key)` | `(str) -> Any` | Read the current value of a persistent configuration key, or `None` if unset |
53
+ | `.mcp_servers` | `list[str]` | Names of the currently configured MCP servers |
54
+ | `.close()` | `() -> None` | Clean up |
55
+
56
+ Constraints: (i) `create_session` must not issue any model call during construction (lazy connection: constructing a session with placeholder or unreachable `D2A_MODEL_*` values must itself succeed); (ii) the session must be non-streaming and non-interactive (it must not read stdin and must not enter a Live view or spinner), and `dispatch`/`chat` must return synchronously.
57
+
58
+ ### 0.2 Model Connection: Unified Environment Variables
59
+
60
+ The model connection is supplied through the following unified environment variables, whose interface shape mirrors the `--model-*` arguments of `run_agent.sh`:
61
+
62
+ | Environment variable | Meaning |
63
+ |---|---|
64
+ | `D2A_MODEL_BASE_URL` | Model base URL (OpenAI-compatible gateway) |
65
+ | `D2A_MODEL_NAME` | Model name (litellm form, e.g. `litellm_proxy/<alias>`) |
66
+ | `D2A_MODEL_API_KEY` | API key used for calls |
67
+
68
+ When these three variables are present in the environment, the TUI must read them at startup, connect to the model directly, and be usable at once.
69
+
70
+ The agent must keep the model fully parameterized with zero hardcoding: headless mode reads the `--model-*` arguments of `run_agent.sh`, and the TUI reads the `D2A_MODEL_*` variables above (optionally overridden in-session by `/model`). No concrete URL, name, or key may be hardcoded, and the default model must not be an unreachable placeholder (such as `gpt-4`). When none of these variables is set, the TUI must emit a clear message rather than crash. Egress is permitted to that endpoint only.
71
+
72
+ The endpoint is the OpenAI-compatible `POST {D2A_MODEL_BASE_URL}/chat/completions`; for the calling convention see `.d2a_spec/model_call_reference.py`. The architecture is yours to design.
73
+
74
+ ### 0.3 Cost Accounting
75
+
76
+ Model unit prices are injected through the environment variable `D2A_MODEL_COST`, in the format `{"input_cost_per_token": <float>, "output_cost_per_token": <float>}`. The agent must accumulate spend accordingly and write it to `cost_usd` in `status.json`; when the variable is absent, spend counts as 0 and the agent must not crash.
77
+
78
+ ### 0.4 Branding and Naming
79
+
80
+ The product's only name is `yuyao agent`, and its launch command is `yuyao`. No Chinese name or other variant may be used. mini-swe-agent exists solely as an internal kernel; its name must never be visible to users.
81
+
82
+ - **Launch command**: installation provides the `yuyao` command (entering the interactive TUI); the headless contract entry point is `run_agent.sh`.
83
+ - **Use `yuyao` everywhere user-visible**: the TUI startup banner, titles, help text, prompt, version string, configuration and history file paths (e.g. `~/.yuyao/`), and the external names of packages and scripts — the string "mini" must not appear, nor may any Chinese name.
84
+ - Internal Python modules that reuse the mini kernel may keep its internal package names, but the string "mini" must not appear in user-visible output.
85
+ - The kernel's startup banner and version string must be suppressed: no text of the form `This is mini-swe-agent version X`, no migration notice, and no kernel logo may be printed to the user when `yuyao` starts or runs. Version numbers in the README, help output, and banner must be `yuyao`'s own.
86
+
87
+ ### 0.5 Documentation
88
+
89
+ - **README** (at the project root, replacing the original README): centred on `yuyao agent` — project overview and positioning, installation, quick start, feature overview (corresponding to §1–§7), non-interactive use of `run_agent.sh`, and FAQ.
90
+ - **Architecture document** (a separate file, e.g. `docs/ARCHITECTURE.md`): overall design and layering, directory and module responsibilities, core data flow (an entire task from input to persisted output), how permission and role modes are realized, built-in tools and the execution environment, the persistent memory and convention-file mechanisms, model integration, the relationship between the headless and TUI entry points, trace and status output, and the relationship between `yuyao` and the internal kernel.
91
+ - Documentation must match the actual implementation, and likewise must show only `yuyao` in user-visible places.
92
+
93
+ ### 0.6 Interface
94
+
95
+ - **Progress bars**: display a progress bar for long tasks, multi-step execution, installation, and batch processing (use a determinate progress bar when the total is known).
96
+ - **Loading animations**: display an animation with status text wherever the wait is of indeterminate length, such as awaiting a model response or executing a tool.
97
+ - **Streaming animation**: during streaming output (§5.5), render character by character or with a fade-in, plus a cursor animation; the thinking process may be presented collapsed (§5.5).
98
+ - **Overall look and feel**: clear sectioning and alignment, sensible colours and highlighting, visual separation of commands, output, thinking, and status, Markdown and code syntax highlighting, and conspicuous visual feedback for success, failure, and warnings; information density should be moderate and must not flood the screen.
99
+ - A mature TUI library (such as `rich`, `textual`, or `prompt_toolkit`) is recommended; the corresponding dependencies must be declared in `pyproject.toml` or `requirements.txt`.
100
+
101
+ ### 0.7 Pre-delivery Self-verification
102
+
103
+ Before submission, a real install-and-run pass must be performed in a clean environment: install with `install.sh`, start the `yuyao` interactive interface using the environment variables of §0.2 and complete one task against the real model, and run headless mode through to completion with `run_agent.sh` on a toy repository.
104
+
105
+ All functionality must be genuinely implemented; no placeholders, stubs, or unimplemented branches may remain.
106
+
107
+ ---
108
+
109
+ ## 1. Built-in Tools (Actions the Agent May Invoke While Solving a Task)
110
+
111
+ | Tool | Meaning |
112
+ |---|---|
113
+ | shell / bash | Execute shell commands (long tasks may run in the foreground or background), producing filesystem and output effects |
114
+ | read / write / edit / multi-edit | Read / write / replace exactly / edit in bulk; the targeted content lands on disk as expected and nothing else changes |
115
+ | apply-patch | Apply a patch |
116
+ | grep / glob | ripgrep content search / glob-based file lookup |
117
+ | web-fetch / web-search | Fetch a URL / search the web (subject to `--network`) |
118
+ | browser | Browser automation (open, click, extract data, screenshot), used to verify web changes |
119
+ | read-media (image / multimodal reading) | Read and understand multimodal files such as images, screenshots, diagrams, design mockups, architecture diagrams, and screen recordings, optionally as task input; the agent must be able to describe image content and act on the information it contains |
120
+ | lsp | Go to definition / find references / diagnostics; type errors and warnings are reported automatically after each edit |
121
+ | notebook-edit | Edit a Jupyter notebook by cell (replace / insert / delete); the target cell changes as expected and other cells are untouched |
122
+ | monitor | Run a command in the background and stream each output line back in real time (tailing logs, polling CI or PR status, watching a directory for changes) without blocking the session; when an event occurs, the agent must be able to notice it mid-flight and react |
123
+ | todo / task-list | Maintain a task list with status and dependencies (pending / in_progress / completed; create, query, update, delete); it survives context compaction |
124
+ | task (sub-agent) | Spawn (mostly read-only) sub-agents to explore, with sub-task results returned (for background shell processes see bg-*) |
125
+ | bg-list / bg-output / bg-stop | Manage background shell processes (distinct from task sub-agents): list / inspect output / stop |
126
+ | memory-search | Semantic or hybrid search over memory, matching relevant historical notes even under different wording |
127
+ | memory-get | Read a given memory file or line range |
128
+ | ask-user | Ask a structured question (interactive mode), pausing for the user's answer |
129
+
130
+ > Reference syntax `@<path|symbol|agent>`: reference a file, symbol, or sub-agent in a prompt as context.
131
+
132
+ ### 1.1 Tool Behaviour Contracts
133
+ | Tool | Required semantics |
134
+ |---|---|
135
+ | **read** | Images are understood as visual content (large images are downscaled automatically); PDFs can be read by page range; `.ipynb` returns each cell with its outputs; oversized files are returned paginated with a hint on how to continue with offset/limit; malformed input must fail closed — report a clean error, without crashing, looping forever, returning an inverted range, or returning empty content that fakes truncation |
136
+ | **edit** | Read before write: the file must have been read in this session before being modified, and must not have been changed externally on disk; `old_string` must match exactly and uniquely, otherwise extend the context to pin down a unique occurrence or use `replace_all`; no regular-expression or fuzzy matching |
137
+ | **multi-edit** | Multiple edits within a single tool call form one atomic operation: every hunk is first validated against the current on-disk content, and if any one fails to match, the whole call is abandoned with nothing written, leaving no intermediate state in which only the leading hunks were applied |
138
+ | **write** | An existing file must have been read before it is overwritten (new files are exempt); the write replaces the whole file rather than appending or merging; malformed input must fail closed and must not silently corrupt the content of an existing file |
139
+ | **bash** | Each command runs in its own process; a default timeout must exist, and a single command may request a longer limit when needed; output beyond the limit is spilled to a file, with the path and a preview returned; long tasks may run in the background; `cd` persists for subsequent commands within the project directory and is reset to the project root automatically when it escapes |
140
+ | **grep** | ripgrep syntax; three output modes `files_with_matches`/`content`/`count`; results can be restricted by glob or type and can span lines with `multiline`; `.gitignore` is honoured by default |
141
+ | **glob** | Results are sorted by modification time; the number of matches must be capped, and when the cap is exceeded only the results within it are returned, together with a truncation indicator |
142
+
143
+ > **Byte fidelity of changes**: the phrase "nothing else changes" for the editing tools above extends to the byte level — outside the matched region,
144
+ > line-ending sequences and byte encoding must remain byte-for-byte identical to the pre-edit content. Newly created files are exempt.
145
+
146
+ > **Multiple tool calls within one turn**: when the model issues several tool calls in a single reply,
147
+ > they must be executed one by one in the order given; each must really run and each must have a corresponding result fed back.
148
+ > Concurrent execution is not forbidden, but the observable effect on any given target must match sequential execution (e.g. a write followed by a delete ⇒ the final state is deleted).
149
+ > If one of them fails, the remaining calls must still each execute and each return their own result.
150
+
151
+ ---
152
+
153
+ ## 2. Top-level Commands / Sub-commands
154
+
155
+ | Invocation | Meaning |
156
+ |---|---|
157
+ | `agent` | Interactive session (REPL), accepting the slash commands of §5 |
158
+ | `agent -p "<task>"` (`--print`) | Run headless to termination, print the result to stdout, and exit per §9; never wait for input |
159
+ | `agent memory <status\|search\|index\|rem-backfill>` | Memory indexing, search, rebuild, and historical replay (see §6) |
160
+ | `agent mcp <add\|list\|remove>` | Manage MCP external tool connections; tools appear or disappear accordingly after add, remove, and list |
161
+ | `agent sandbox <list\|recreate\|explain>` | Sandbox runtime management and troubleshooting (see §3.3); `explain` states why something was blocked |
162
+ | `agent agents <list\|dispatch\|attach\|stop>` | Agent View: dispatch and monitor background sessions (each in its own git worktree), listing background sessions and their status on one screen, including which are awaiting input, with the ability to attach to or stop them |
163
+ | `agent features <list\|enable\|disable>` | Feature switches (hooks / skills / plugins / MCP) |
164
+ | `agent config <get\|set\|unset> <path> [val]` | Read and write runtime configuration with hot reload; a key change takes effect as soon as it validates, without a restart |
165
+
166
+ ---
167
+
168
+ ## 3. Permission Modes (Five Mutually Exclusive Levels) + Role Modes (Unified `--role`) + Sandbox / Network / Lists
169
+
170
+ ### 3.1 Permission Modes (Five Mutually Exclusive Levels)
171
+ `--mode <name>`, where `name ∈ {ask, plan, auto-edit, auto-review, yolo}`; convenience aliases are also provided.
172
+
173
+ | Mode | Canonical form | Alias | Meaning |
174
+ |---|---|---|---|
175
+ | Ask (default) | `--mode ask` | (omitted) | Every mutating operation is confirmed individually; when no one is present to confirm in headless mode, mutating operations are refused |
176
+ | Plan | `--mode plan` | `--plan` | Read-only: no file changes, no mutating commands |
177
+ | Auto-edit | `--mode auto-edit` | `--auto-edit` | File edits are approved automatically; mutating shell commands still require approval |
178
+ | Auto with classifier review | `--mode auto-review` | `--auto-review` | Fully automatic plus a secondary classifier reviewing each action, blocking dangerous ones (fail-closed). Distinct from `auto-edit`, which only waives approval for edits |
179
+ | Full permissions | `--mode yolo` | `--yolo` | Full permissions, all approvals skipped; both files and commands are executed automatically |
180
+
181
+ - Compatibility aliases (semantics must be identical, §8): `--dangerously-skip-permissions` ≡ `--yes` ≡ `-y` ≡ `--yolo`.
182
+
183
+ ### 3.2 Role Modes (Unified `--role <name>`, Orthogonal to Permission Modes; One Role at a Time)
184
+ `--role <name>`, where `name ∈ {execute, ask, architect, debug, orchestrator}`; `ask` and `debug` additionally have the in-session convenience aliases `/ask` and `/debug`.
185
+
186
+ | Role | Canonical form | Alias | Meaning |
187
+ |---|---|---|---|
188
+ | Execute (default) | `--role execute` | (omitted) | Carry out coding tasks normally: change code and run commands to solve the problem |
189
+ | Ask | `--role ask` | `/ask` | Answer without changing anything: explanation and Q&A, with zero modifications to the workspace |
190
+ | Architect | `--role architect` | — | A strong model produces the plan and an editing model lands the diff: plan first, then write to disk |
191
+ | Debug | `--role debug` | `/debug` | Focus on locating defects, adding diagnostics and a minimal reproduction |
192
+ | Orchestrator | `--role orchestrator [--team-name <n>]` | — | Coordinate the division of labour across multiple sub-agents (lead + teammates: a shared task list plus messages between them, with the lead splitting, assigning, and synchronizing work) |
193
+
194
+ ### 3.3 Sandbox / Network / Lists (Security Switches, Orthogonal to Modes and Roles)
195
+ | Flag / setting | Meaning |
196
+ |---|---|
197
+ | `--sandbox <read-only\|workspace-write\|full-access>` | OS-level isolation level; out-of-bounds writes and privilege escalation are blocked at the restricted levels |
198
+ | `--network <on\|off>` (default off) | Whether network access is allowed; when off, network actions are refused |
199
+ | `--allow <tool/glob>` / `--deny <tool/glob>` | Allowlist and denylist for tools and paths |
200
+
201
+ > To troubleshoot "why was this tool blocked", use `agent sandbox explain` (§2); no separate flag is provided.
202
+
203
+ > **Matching criterion for deny and allow**: a rule such as `Bash(<glob>)` matches the command's **effective program name**
204
+ > — that is, the program that will actually be executed, determined after shell lexical analysis, after removing quotes and escapes, after stripping wrappers (`sh -c`/`command`/`env`/`xargs`/`exec`/
205
+ > `nice`/`timeout`/`nohup`/`stdbuf`, and the like) and path prefixes.
206
+ > Quote-split words (`to""uch`), backslashes, redundant whitespace, subshells, command substitution,
207
+ > and forms such as `find -exec` that place a command in an argument position do not change the effective program name and match all the same.
208
+ > The converse also holds: a command that merely mentions a denied string without executing it
209
+ > (such as `grep "rm " f.txt` or `echo rm`) is permitted.
210
+
211
+ > **Segment-by-segment adjudication**: a command line may consist of several segments — `;`, `&&`, `||`, pipes, subshells, and command substitution
212
+ > each introduce a segment of executable content, and each segment has its own effective program name. Adjudication applies to **every one of those segments**,
213
+ > and the two directions compose differently: deny and ask are decided by a single veto — if any segment matches, the whole command line is blocked or turned into a confirmation,
214
+ > and wrapping a refused program inside a compound command does not constitute a bypass; allow requires unanimity — only if every segment is permitted is the whole command line exempt from confirmation,
215
+ > and a single allow rule matching one segment does not permit the whole line.
216
+
217
+ > **Undetermined means not permitted**: when the effective program name cannot be determined — unbalanced quotes, failed word splitting, structures beyond the implementation's understanding,
218
+ > or any situation in which the implementation can only guess rather than compute — the command must be treated as not permitted: in interactive mode it becomes an individual confirmation,
219
+ > and in unattended mode mutating operations are refused per §3.1. Indeterminacy must not result in permission, nor may the implementation degrade to an approximation such as splitting on whitespace.
220
+
221
+ > **Data exfiltration (strong invariant)**: only content that the user has explicitly referenced through `@<path>` (§5.4) or that the agent has itself read with tools such as read or grep may enter the context and the request body; merely mentioning a file name in free text (casually saying `~/.ssh/id_rsa` or `.env`, say) must not trigger an automatic read that wires its content into any model request. The contents of sensitive files such as private keys, credentials, and `.env` must never be collected automatically or transmitted without having been named.
222
+
223
+ ---
224
+
225
+ ## 4. Global Flags
226
+
227
+ | Flag | Meaning |
228
+ |---|---|
229
+ | `--output-format <text\|json>` / `--json` | Output format; with json, stdout is a single parseable JSON document |
230
+ | `--json-schema <file>` | Produce a structured result per the schema; the output must conform to that schema |
231
+ | `--stream <on\|off>` (default on) | Whether output is streamed; for presentation requirements see §5.5 |
232
+ | `--show-thinking <off\|collapsed\|expanded>` (default collapsed) | Whether the model's thinking is displayed. collapsed folds it into a summary that can be expanded; expanded shows it directly; off hides it. Thinking and the final answer are visually separated |
233
+ | `-c`/`--continue` \| `--resume <id>` | Continue the most recent \| a specified session (mutually exclusive), restoring the context to carry on |
234
+ | `--no-memory` | Do not load memory or convention files for this run (§6/§7); constraints declared by the repository are not honoured |
235
+ | `--max-steps <n>` | Upper bound on run steps; on reaching it, stop cleanly and record `LimitsExceeded` without crashing |
236
+ | `--thinking <off\|low\|medium\|high\|max>` | Thinking intensity, switching the reasoning budget. The level set is defined here and shared by `/think` |
237
+ | `--auto-commit` | Commit to git automatically after each edit (with a descriptive message); each change produces one commit |
238
+ | `--auto-test` / `--test-cmd <cmd>` | Run tests automatically after editing and iterate on the results; if tests fail, keep fixing until they pass |
239
+ | `--map-tokens <n>` | Repo map injection budget; for a large repository, inject the most relevant symbols; `0` means no repo map is injected |
240
+ | `--experimental-lsp` | Enable LSP code intelligence (= the lsp tool of §1) |
241
+ | `--model <name>` | Select the model |
242
+ | `--tools <list>` \| `--allowed-tools <rules>` \| `--disallowed-tools <rules>` | Restrict the available tool set \| tools permitted without confirmation \| tools refused. Rules take forms such as `Bash(git log *)` and `Edit(/src/**)` |
243
+ | `--worktree[=<name>]` (`-w`) | Start in an isolated git worktree (created automatically or named); changes occur in the isolated checkout and never touch the main working tree |
244
+ | `--bg [task]` (+`--exec <cmd>`) | Start as a background session and return immediately, printing the session ID and releasing the terminal; with `--exec`, run a shell job in the background instead |
245
+ | `--fork-session` | On resume, create a new session ID; the original session is preserved and a new one is forked from it |
246
+ | `--max-budget-usd <n>` | Spend ceiling (headless); once cumulative spend reaches it, stop cleanly |
247
+ | `--system-prompt <txt>` \| `--system-prompt-file <f>` | Replace the system prompt |
248
+ | `--append-system-prompt <txt>` \| `--append-system-prompt-file <f>` | Append after the default system prompt, preserving the default behaviour |
249
+ | `--input-format <text\|stream-json>` | Headless input format |
250
+ | `--verbose` | Detailed per-turn output, printing the full turn-by-turn process |
251
+ | `--help` | Print the complete invocation surface |
252
+
253
+ ---
254
+
255
+ ## 5. In-session Interaction: Slash Commands and Keyboard Shortcuts
256
+
257
+ ### 5.1 Core Slash Commands
258
+ | Command | Meaning |
259
+ |---|---|
260
+ | `/undo` | Revert the agent's most recent change (the "one step back" special case of `/rewind`); the affected files return to their pre-edit state, and the user's own uncommitted changes are left untouched |
261
+ | `/redo` | Reapply a reverted change. Any new change invalidates what could be redone — if a file was edited or created after `/undo`, `/redo` is a no-op and changes no file |
262
+ | `/rewind` (`/checkpoint`) | Open the checkpoint menu (`Esc Esc` also works on empty input): restore only the code, only the conversation, or both to a historical point, or summarize and compact the conversation from or up to that point. Every user prompt is a checkpoint, retained across sessions. `/undo` is its "one step back" special case. Limitation: only changes made by file-editing tools are tracked — files changed by bash commands (`rm`, `mv`, and so on) are not tracked and cannot be rewound |
263
+ | `/compact` (`/compress`) | Compact or summarize the context; after compaction the original task can still be carried on |
264
+ | `/plan` | Switch to read-only plan mode (= plan in §3.1) |
265
+ | `/ask` | Switch to the answer-only role (= ask in §3.2) |
266
+ | `/debug` | Switch to the debugging role (= debug in §3.2) |
267
+ | `/mode <ask\|plan\|auto-edit\|auto-review\|yolo>` | Switch permission mode in-session (mirrors `--mode`, §3.1) |
268
+ | `/role <execute\|ask\|architect\|debug\|orchestrator>` | Switch role in-session (mirrors `--role`, §3.2) |
269
+ | `/diff` | Show the current changes, listing modified files and their diffs |
270
+ | `/review [--fix] [--security\|--simplify]` | Review the current diff: by default read-only, looking for correctness bugs and cleanup opportunities; `--fix` applies findings to the working tree; `--security` focuses on security (injection, authorization, leaks); `--simplify` performs cleanup and refactoring only |
271
+ | `/security-review` | Review specifically the security risks of the current branch's changes, producing a risk list |
272
+ | `/run` | Build, launch, and drive the project's app, observing at runtime whether a change took effect rather than relying on tests alone |
273
+ | `/copy [N]` | Copy the most recent (or Nth most recent) answer to the clipboard; when it contains code blocks, a block may be selected or written to a file |
274
+ | `/focus` | Toggle the focused view: show only the latest prompt, a summary of tool calls (including diffstat), and the final answer |
275
+ | `/tui <default\|fullscreen>` | Switch the terminal UI renderer (fullscreen being flicker-free full-screen rendering), preserving the session |
276
+ | `/config` (`/settings`) | Open the settings interface: theme, editor mode (including Vim), output style, and so on; settings are visible, editable, and take effect immediately |
277
+ | `/background [prompt]` (`/bg`) | Detach the current session into a background session and release the terminal (optionally with a final instruction), monitorable through Agent View |
278
+ | `/init` | Generate the convention memory file `AGENTS.md` |
279
+ | `/memory` | View and manage cross-session memory (see §6) |
280
+ | `/tools` | List the currently available tools (= introspection over the built-in tools of §1) |
281
+ | `/recap` | Produce a one-line "where we left off" continuation summary for the session |
282
+ | `/context list` | List the size of each part of the context (raw vs injected) |
283
+ | `/context detail` | Inspect context truncation state in detail, reporting truncation and over-budget specifics |
284
+ | `/model <name>` | Switch model, preserving the context |
285
+ | `/new` | Archive the current session and start a new one |
286
+ | `/clear` (`/reset`) | Clear the current session context (without archiving; use `/new` to archive and start fresh) |
287
+ | `/sessions` (`/resume`) | List and restore past sessions |
288
+ | `/title` (`/rename`) | Rename the current session |
289
+ | `/status` | Show version, model, working directory, and current mode |
290
+ | `/export` | Export the current session as Markdown |
291
+ | `/add-dir <path>` | Add another accessible working directory to this session; files beneath it become readable and writable |
292
+ | `/cd <path>` | Change the session's working directory; subsequent operations are based on the new directory |
293
+ | `/permissions` | Manage tool permission rules interactively (allow / ask / deny, = the lists of §3.3) |
294
+ | `/hooks` | View and manage lifecycle hook configuration (= `hooks.json`, §7) |
295
+ | `/mcp` | Manage MCP connections (= the in-session mirror of `agent mcp`, §2) |
296
+ | `/agents` | Manage sub-agent configuration (= task in §1 / orchestrator in §3.2) |
297
+ | `/help` | List all supported commands |
298
+ | `/exit` (`/quit`) | Leave the session; the process ends with exit code 0 |
299
+
300
+ ### 5.2 Advanced
301
+ | Command | Meaning |
302
+ |---|---|
303
+ | `/goal <condition>` | Goal autonomy: once a completion condition is set, keep working and judge attainment independently, until the condition is met or a limit is reached |
304
+ | `/loop <prompt> [--interval <s>] [--max <n>] [--until <cond>]` | Run a fixed prompt in a loop or as a poll within the session. Unlike `/goal` (which judges completion autonomously), `/loop` repeats the same prompt; it stops on the `--until` condition, the `--max` count, or `Esc` |
305
+ | `/fork` | Spawn a background sub-agent (inheriting the current context, returning its result, and not polluting the original). To fork the conversation, use `/branch` |
306
+ | `/branch [name]` | Fork the conversation at the current point and switch into the copy, preserving the original, which remains reachable through `/sessions` |
307
+ | `/btw <question>` (`/side`) | Quick aside: the exchange is not recorded in the main conversation history, so the main history does not grow |
308
+ | `/verify` | Build, run, drive the app, and observe, confirming that the change meets the bar (at runtime, not by tests or type checks alone) |
309
+ | `/batch <instruction>` | Split a large change into independent units, each implemented in parallel by a sub-agent in its own worktree (= the concrete workflow of `--role orchestrator`) |
310
+ | `/workflows` (`/workflow <name>`) | Dynamic workflows: scripted orchestration of many sub-agents that cross-check each other's results, for multi-round tasks such as very large changes, whole-repository audits, and large-scale migrations; lists running and completed workflows with their current stage and each sub-agent's progress, and can run a named workflow |
311
+ | `/skills` \| `/skill <name>` | List skill packages (SKILL.md) \| trigger execution of a named skill |
312
+ | `/flow:<name>` | Execute an embedded skill flow graph, node by node |
313
+ | `/queue <steer\|followup\|collect\|interrupt>` | Queue, steer, or abort with a message mid-stream |
314
+ | `/tasks` (`/bashes`) | View and manage everything running in the background (background shell processes and tasks: list, inspect, stop, in concert with bg-* in §1) |
315
+ | `/think <level>` | Set the thinking level (the same level set as `--thinking`, §4) |
316
+ | `/show-thinking <off\|collapsed\|expanded>` | Switch how thinking is displayed in-session (mirrors `--show-thinking`; distinct from `/think`, which sets the reasoning budget) |
317
+ | `/stream <on\|off>` | Toggle streaming output in-session (mirrors `--stream`) |
318
+ | `/usage <off\|tokens\|full>` | Toggle token and usage display |
319
+
320
+ > **Delineating sub-agents, orchestration, and background execution**:
321
+ > - `task` (the §1 tool) = spawn a read-only sub-agent temporarily during problem solving to explore; `/fork` = spawn a background sub-agent that inherits the context and returns its result.
322
+ > - `--role orchestrator` (the §3.2 role) = adopt the working posture of coordinating multiple sub-agents; `/batch <instruction>` = its concrete workflow (split a large change into units, each in its own worktree, run in parallel).
323
+ > - `/branch` = fork the conversation (not an agent); `/tasks` + `bg-*` = manage background shell processes and tasks (not agents); `/background` (`/bg`) = move the entire current session into the background.
324
+ > - `/agents` (§5.1) = manage sub-agent configuration (does not spawn); `agent agents` (§2, Agent View) = dispatch and monitor background sessions (each with its own worktree), as distinct from `/tasks`, which manages the current session's background items.
325
+ > - `/loop` = loop or poll on a prompt within one session (does not spawn agents); `/workflows` = scripted orchestration of many sub-agents with cross-checking (larger in scale and multi-round compared with `/batch`).
326
+ > - Parallel work is isolated with git worktrees (§7), preventing multiple agents from editing the same file.
327
+
328
+ ### 5.3 Keyboard Shortcuts (Interactive Mode)
329
+ | Shortcut | Action |
330
+ |---|---|
331
+ | `Enter` | Submit the input; the current input is submitted as one turn |
332
+ | `Shift+Enter` / `Ctrl+J` | Insert a newline in the input; multi-line input is not submitted |
333
+ | `Shift+Tab` | Toggle between plan (read-only) and non-plan (= plan in §3.1) |
334
+ | `Ctrl+G` | Invoke `$EDITOR` to edit the input in an external editor |
335
+ | `Ctrl+V` | Paste an image or media file into this turn's context (in concert with read-media, §1) |
336
+ | `Ctrl+S` | Steer the running turn, injecting a mid-flight message into it (= `/queue steer`, §5.2) |
337
+ | `Esc` | Stop or cancel the current run |
338
+ | `Ctrl+C` | Interrupt the run / clear the input |
339
+ | `Ctrl+D` | Exit when the input is empty, with exit code 0 |
340
+ | `Ctrl+O` | Expand or collapse tool output (transcript viewer) |
341
+ | `Ctrl+T` | Expand or collapse the task list view |
342
+ | `Alt+T` | Toggle thinking display (= `/show-thinking`, collapsed ↔ expanded) |
343
+ | `Ctrl+E` | Expand or collapse the plan or preview |
344
+ | `Ctrl+R` | Reverse-search the input history, searching interactively and reusing an entry |
345
+ | `Ctrl+B` | Move the running bash command to the background and carry on the conversation |
346
+ | `Ctrl+X Ctrl+K` | Terminate all background sub-agents of this session (press twice to confirm) |
347
+ | `Esc Esc` | Open the rewind checkpoint menu on empty input; with text present, clear the draft and save it to history |
348
+ | `Ctrl+Z` / `Ctrl+Shift+Z` | Undo / redo an input edit |
349
+ | `Ctrl+L` | Clear the screen: clear only the terminal display, leaving the context untouched (as distinct from `/clear`, which clears the context) |
350
+ | `\` + `Enter` | Multi-line input (works in any terminal); does not submit but moves to the next line |
351
+
352
+ ### 5.4 Input Prefixes (`/` `@` `!`)
353
+ | Prefix | Meaning |
354
+ |---|---|
355
+ | `/<command>` | Slash command (§5.1/§5.2), recognized only at the start of a message |
356
+ | `@<path\|symbol\|agent>` | Reference injection: a file, a directory (recursively), a symbol, or a sub-agent as context |
357
+ | `!<shell command>` | The user executes a shell command directly (as distinct from the agent's bash tool); the command runs in a subshell and its output is echoed; a bare `!` toggles shell mode |
358
+
359
+ ### 5.5 Thinking Display / Streaming Presentation / Image Reading
360
+ | Capability | Meaning |
361
+ |---|---|
362
+ | Thinking is visible and collapsible | The agent's thinking is presented according to the `--show-thinking`/`/show-thinking`/`Alt+T` setting: `collapsed` folds it by default into a one-line summary expandable with a single key; `expanded` shows it directly; `off` hides it. Thinking, the final answer, and tool calls are visually separated and never conflated |
363
+ | Streaming output plus animation | `--stream on` (the default): model output is rendered incrementally token by token in real time, accompanied by a streaming animation; a stream can be aborted with `Esc` and steered with `Ctrl+S` or `/queue steer` |
364
+ | Conversation is not an unbounded agentic loop | Ordinary conversation and questions (greetings, queries) should receive a fast streaming answer; only an explicit coding task enters the multi-step "think → tool → observe" loop, with every step's action and output visible in real time |
365
+ | Non-streaming output | `--stream off`: the whole passage is emitted at once after generation completes, with no character-by-character animation, suiting pipes, logs, and TTY-less environments |
366
+ | Images as input | Images may be supplied through `@<image path>`, a `Ctrl+V` paste, or headless input, letting the agent understand screenshots, error images, design mockups, and architecture diagrams and solve the task from them; the TUI must show a visible indicator for each image taken in |
367
+
368
+ ### 5.6 Vim Editing Mode (Input Box)
369
+ Enabled through `/config` → editor mode; the input box then supports vim-style editing:
370
+ - **Modes**: NORMAL / INSERT / VISUAL (`Esc` enters NORMAL, `i/I/a/A/o/O` enter INSERT, `v/V` enter VISUAL).
371
+ - **Motion**: `h/j/k/l`, `w/e/b`, `0/$/^`, `gg/G`, `f/F/t/T` plus `;`/`,`.
372
+ - **Editing**: `x`, `dd/D`, `dw/de/db`, `cc/C/cw`, `yy/yw`, `p/P`, `>>/<<`, `J`, `u`, `.` (repeat).
373
+ - **Text objects**: `iw/aw`, `i"/a"`, `i(/a(`, `i[/a[`, `i{/a{` in combination with `d/c/y`.
374
+ - Once enabled, the input box responds with the vim semantics above; when disabled, it performs ordinary line editing.
375
+
376
+ ### 5.7 Interaction Enhancements
377
+ | Capability | Meaning |
378
+ |---|---|
379
+ | Command history and reverse search | Input history is saved per working directory; `↑/↓` browses it and `Ctrl+R` reverse-searches and reuses an entry; consecutive identical submissions are recorded once |
380
+ | Suggestions | After a turn, show a greyed-out next-step suggestion in the input box (predicted from the session and history); `Tab`/`→` accepts it and typing dismisses it |
381
+ | Session continuation summary | On returning after a while, show a one-line "where we left off" summary; `/recap` generates one on demand |
382
+ | PR status bar | When the current branch has an open PR, the footer shows a clickable PR link with a colour-coded state (passing, awaiting review, changes requested, draft), refreshed periodically |
383
+ | Focused and full-screen rendering | `/focus` for a condensed view, `/tui fullscreen` for flicker-free full-screen rendering (see §5.1) |
384
+
385
+ ---
386
+
387
+ ## 6. Persistent Memory System
388
+
389
+ > Memory = plain-text files in the workspace + search tools + automatic maintenance. Once written to persistent memory, content must land on disk
390
+ > (location and format are yours to choose) and must remain readable back, or recallable through `memory-search`, after `/new`, `/clear`, and in new sessions
391
+ > (`--no-memory` excepted).
392
+
393
+ ### 6.1 Memory Files
394
+ | File | Purpose | Loading / indexing rule |
395
+ |---|---|---|
396
+ | `MEMORY.md` | Long-term memory (distilled facts, preferences, decisions) | Loaded automatically at the start of every session; when it exceeds the bootstrap budget, the on-disk copy stays complete and the injected copy is truncated |
397
+ | `memory/YYYY-MM-DD.md` | Daily working memory (run context, notes) | Today's and yesterday's are loaded automatically; all are indexed by the search tools rather than injected every turn |
398
+ | `DREAMS.md` | Consolidation and review journal (output of dreaming) | For human review; written by the consolidation process |
399
+
400
+ ### 6.2 External Invocation of Memory
401
+ | Invocation | Meaning |
402
+ |---|---|
403
+ | Natural language "Remember that …" | Triggers an automatic write, into `MEMORY.md` or the day's `memory/*.md` |
404
+ | `/remember <text>` | Explicitly write one persistent memory entry into `MEMORY.md` |
405
+ | `/forget <query>` | Delete matching automatic memory entries. Matching is per entry: only the entry corresponding to the query is removed and every other entry is preserved individually; other entries whose body contains the same substring are not deleted along with it (forgetting `alpha`, for instance, does not affect another entry reading `alphabet …`). Case sensitivity and support for fuzzy matching are left to the implementation |
406
+ | `/dream` | Trigger memory consolidation manually (the manual form of dreaming, §6.3), promoting qualifying short-term signals into `MEMORY.md` |
407
+ | Tool `memory-search "<q>"` / `agent memory search` | Semantic or hybrid search, matching relevant historical notes even under different wording |
408
+ | Tool `memory-get <file[:lines]>` | Read the specified memory content |
409
+ | `agent memory status` | Print index readiness and the provider |
410
+ | `agent memory index --force` | Rebuild the index |
411
+ | `agent memory rem-backfill [--rollback]` | Replay historical notes: stage promotion candidates, with the option to roll back and remove them |
412
+ | `/context list` · `/context detail` | Inspect raw and injected sizes and truncation state |
413
+ | Editing `MEMORY.md`/`memory/*.md`/`DREAMS.md` directly | Edit memory by hand; the corresponding memory changes immediately |
414
+
415
+ ### 6.3 Automatic Maintenance
416
+ - **Automatic memory-flush before compaction (on by default)**: when the context is about to fill up, run a silent turn before compaction to persist important information into memory files, so that old facts remain recallable afterwards.
417
+ - **Distillation**: promote useful content from daily notes into `MEMORY.md` and delete stale entries.
418
+ - **Dreaming (off by default, may be enabled by the user)**: periodic background consolidation that promotes only qualifying short-term signals into `MEMORY.md` per thresholds (score, recall frequency, query diversity), writing stage summaries to `DREAMS.md`.
419
+
420
+ ### 6.4 Memory-related Configuration Keys
421
+ `memorySearch.provider` (embedding provider, trading off search quality) / `compaction.memoryFlush.model` (pin the flush turn to a specified or local model) / the memory backend is selectable (built-in / local sidecar / cross-session memory service, and so on).
422
+
423
+ ---
424
+
425
+ ## 7. Convention Files
426
+
427
+ | File / directory | Purpose |
428
+ |---|---|
429
+ | `.trajectory/` | Execution trace (mandatory): every run records its complete trace to `.trajectory/` (one per run), logging each step's action (tool call, command, edit) with its input and result. The format is the agent's own choice (plain text, JSONL, or split across files). Location: interactive mode writes to `<cwd>/.trajectory/` under the current working directory; headless mode writes to `<out-dir>/.trajectory/`, outside the repository being modified, so as not to pollute the patch |
430
+ | `AGENTS.md` (falling back to `CLAUDE.md`) | Operating instructions and memory conventions, read and honoured automatically; verifiable constraints written there are honoured, except under `--no-memory` |
431
+ | `MEMORY.md` / `memory/*.md` / `DREAMS.md` | Memory files, see §6 |
432
+ | `.plans/` | Editable plans produced by plan mode; after planning, a plan file appears that may be edited and then executed |
433
+ | `hooks.json` | Lifecycle hooks (able to intercept before and after execution); quality gates such as "tests or lint must pass before completion" can be configured. If `beforeShellExecution` returns deny, the command does not run; if a quality gate fails, the run is not allowed to finish |
434
+ | `plugins/<name>/plugin.json` | Plugins: declare a group of extensions that can be enabled or disabled as a whole (which may include custom commands, skills, and hooks). After `agent features disable plugins`, none of the extensions they declare takes effect |
435
+ | `SKILL.md` (`skills/<name>/`) | Trigger-based skill packages (agentskills standard): a trigger keyword loads and executes the skill |
436
+ | Custom commands (`commands/<name>.md`) | User-defined slash commands: Markdown plus YAML frontmatter, supporting `{{args}}` parameters, `@{file}` injection, and `!{cmd}` dynamic injection; subdirectories map to `:` namespaces (`/git:commit`). Dropping in the file makes `/<name>` available |
437
+ | `agents/<name>.md` (custom sub-agents) | Define reusable specialized sub-agents: constrain their role and available tool set. Dropping in the definition makes it invocable by name through `/agents` or `task`, running under the declared tool restrictions |
438
+ | git worktree (parallel isolation) | Parallel sub-agents and background sessions each use their own git worktree, so they never touch the same file |
439
+ | Rule files (glob-conditioned rules) | Rule injection triggered by path or condition; when a path matches, the rule takes effect |
440
+ | Permission list configuration (allow/deny) | Tools and paths permitted or refused by default |
441
+ | MCP configuration | Declare external MCP servers; once configured, additional tools appear |
442
+
443
+ ---
444
+
445
+ ## 8. Consistency Rules
446
+
447
+ > The following rules constrain the relationships between the features already listed in the preceding sections; their effect must land on an externally observable surface.
448
+ > "External" means one of: the request sent to the model, files on disk, the process exit code, or the command's own output — any one of the four suffices.
449
+ > The implementation is not constrained: no particular function need be exposed, and no wording, layout, or field name is prescribed for any output.
450
+
451
+ 1. **Aliases and shortcuts are synonymous triggers**: every convenience alias (`--plan`/`--auto`/`--yolo`/`/ask`/`/debug`/`--dangerously-skip-permissions`/`--yes`/`-y`, and so on) and every keyboard shortcut (such as `Ctrl+S` = `/queue steer`, `Shift+Tab` = toggle plan, `Esc` = abort, `Alt+T` = toggle thinking display, `Ctrl+T` = toggle the task list, `Esc Esc` = rewind) must behave exactly as its canonical long form and must not introduce new semantics.
452
+
453
+ 2. **In-session switches mirror the startup flags**: the semantics of switching with `/mode`, `/role`, `/stream`, and `/show-thinking` (and the aliases `/plan`/`/ask`/`/debug`) in-session must be identical to those of the corresponding startup flags; the switch takes effect immediately and is subject to the same constraints as the startup flag.
454
+
455
+ 3. **The current mode must be discernible in the request**: after a permission mode or role mode switch, the request sent to the model must itself reveal which level is in force.
456
+
457
+ 4. **Relationship of the three axes**: permission modes, role modes, and the security switches form three orthogonal axes that may be combined freely; conflicting combinations (such as `--role ask` together with a demand to modify files) resolve in favour of read-only. `yolo` only stops prompting for approval; it remains bound by `AGENTS.md` and by `--sandbox`/`--network`/`--deny`.
458
+
459
+ 5. **Thinking budget ⟂ thinking display**: `--thinking`/`/think` adjust the reasoning budget and intensity; `--show-thinking`/`/show-thinking`/`Alt+T` adjust whether thinking is displayed — the two are independent and must not override each other.
460
+
461
+ 6. **Unknown invocations must fail explicitly**: an unknown flag or slash command → an explicit error (headless exit code 2; a message in interactive mode).
462
+
463
+ 7. **Accepted means effective and readable back**: if a configuration write is accepted (no error reported), the new value must be retrievable through the corresponding read command. Refusing an unrecognized configuration key is legitimate (an explicit error suffices); an accepted write, however, must not read back as the old value or the default.
464
+
465
+ 8. **External tool connections: both surfaces must support add and remove, and listing must reflect the change**. The command-line sub-commands of §2 and the in-session commands of §5 must both support the three actions register, remove, and list. After an add or remove on either surface, the listing on that same surface must reflect the change. The argument form is yours to choose.
466
+
467
+ 9. **Requests sent to the model must always be well-formed**: every request sent to the model must satisfy — exactly one system prompt, placed first; no two adjacent messages with the same role; no tool call separated from its response; no empty content block and no empty tool result; and no illegal bytes (nulls, lone surrogates, and the like). This constraint applies to all requests, without exception.
468
+
469
+ ---
470
+
471
+ ## 9. Exit Codes (Closed Set, Mandatory for Headless Mode)
472
+ `0` clean termination (`Submitted` completed / `LimitsExceeded` limit reached); `1` runtime error; `2` usage error (unknown or conflicting flag, unknown sub-command or sub-action, missing argument).
473
+ - Self-reported status: headless mode writes `status.json` under `--out-dir` (`exit_status`: `Submitted`/`LimitsExceeded` correspond to exit code 0, errors to 1; including cumulative spend `cost_usd`, with unit prices per §0.3) plus `.trajectory/` (the trace, format of your choosing, see §7).
474
+ - **`Submitted` must be earned**: only genuine completion of the task (with an actual result or tool effect) may be recorded as `Submitted`; when the model returns empty content, a degenerate response, or takes no real action, `Submitted` must not be recorded and `LimitsExceeded` or an error state must be recorded instead.
code/src/stage1/spec/model_call_reference-v2.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference implementation for calling the model.
3
+
4
+ The endpoint is **OpenAI-compatible**: `POST {D2A_MODEL_BASE_URL}/chat/completions`.
5
+ Three environment variables supply the connection parameters:
6
+
7
+ D2A_MODEL_BASE_URL e.g. http://host.docker.internal:4000
8
+ D2A_MODEL_NAME e.g. litellm_proxy/builder
9
+ D2A_MODEL_API_KEY gateway key
10
+
11
+ Any client library may be used. The environment is offline and cannot install
12
+ new packages; `litellm`, `openai`, `httpx`, and `requests` are preinstalled, as
13
+ is the standard library's `urllib`.
14
+
15
+ To confirm connectivity with a single round trip:
16
+
17
+ python .d2a_spec/model_call_reference.py
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+
24
+ # On import, litellm fetches its price table from the public internet, which
25
+ # hangs in an offline environment. Disable that first.
26
+ os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
27
+
28
+ BASH_TOOL = {
29
+ "type": "function",
30
+ "function": {
31
+ "name": "bash",
32
+ "description": "Run a bash command.",
33
+ "parameters": {
34
+ "type": "object",
35
+ "properties": {"command": {"type": "string"}},
36
+ "required": ["command"],
37
+ },
38
+ },
39
+ }
40
+
41
+
42
+ def _client():
43
+ """An OpenAI-compatible client. The base URL must end in `/v1`, or requests 404."""
44
+ from openai import OpenAI
45
+
46
+ base = os.environ["D2A_MODEL_BASE_URL"].rstrip("/")
47
+ if not base.endswith("/v1"):
48
+ base += "/v1"
49
+ return OpenAI(base_url=base, api_key=os.environ["D2A_MODEL_API_KEY"])
50
+
51
+
52
+ def model_name() -> str:
53
+ """Resolve `D2A_MODEL_NAME`, which takes the form `litellm_proxy/builder`.
54
+
55
+ The `litellm_proxy/` prefix is a **routing prefix belonging to the litellm
56
+ client**: pass it through verbatim when calling via litellm, but strip it for
57
+ direct HTTP calls (the OpenAI client, httpx, requests). Leaving it in place
58
+ makes the endpoint respond
59
+ `400 Invalid model name passed in model=litellm_proxy/builder`.
60
+ """
61
+ name = os.environ["D2A_MODEL_NAME"]
62
+ return name.split("/", 1)[1] if name.startswith("litellm_proxy/") else name
63
+
64
+
65
+ def complete(messages: list[dict], *, tools: list | None = None):
66
+ """Perform one model call and return the raw response object."""
67
+ kwargs = {"model": model_name(), "messages": messages}
68
+ if tools:
69
+ kwargs["tools"] = tools
70
+ return _client().chat.completions.create(**kwargs)
71
+
72
+
73
+ def agentic_turn(messages: list[dict], run_bash, *, max_steps: int = 20) -> str:
74
+ """Run one turn: expose the bash tool, execute the tool calls the model makes,
75
+ and continue until the model replies with plain text.
76
+
77
+ The caller supplies `run_bash(cmd: str) -> str`, which executes the command
78
+ and returns its combined stdout and stderr. `messages` is appended to in
79
+ place, with both assistant and `role=tool` messages.
80
+ """
81
+ for _ in range(max_steps):
82
+ msg = complete(messages, tools=[BASH_TOOL]).choices[0].message
83
+ calls = msg.tool_calls or []
84
+ if not calls:
85
+ messages.append({"role": "assistant", "content": msg.content or ""})
86
+ return msg.content or ""
87
+ messages.append(msg.model_dump(exclude_none=True))
88
+ for tc in calls:
89
+ cmd = json.loads(tc.function.arguments or "{}").get("command", "")
90
+ messages.append({"role": "tool", "tool_call_id": tc.id, "content": run_bash(cmd)})
91
+ return ""
92
+
93
+
94
+ def usage_of(response) -> dict:
95
+ """Token usage, or an empty dict when absent — cost accounting must tolerate
96
+ the field being missing."""
97
+ u = getattr(response, "usage", None)
98
+ if u is None:
99
+ return {}
100
+ return u.model_dump() if hasattr(u, "model_dump") else dict(u)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ r = complete([{"role": "user", "content": "hi (one short sentence)"}])
105
+ print("round-trip OK ·", repr((r.choices[0].message.content or "")[:80]))
106
+ print("usage:", usage_of(r))
code/tools/run_production_catalog.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute an explicit catalog selection through the active production boundary.
2
+
3
+ The command is separate from the YAML launcher. It accepts only a reviewed artifact
4
+ path, a scenario selection, and an explicitly named deterministic stimulus
5
+ root; every observation still passes through ``runtime.catalog_executor``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from doc2harness.benchmark.dispatch import active_scenario_ids, load_scenario_owner
17
+ from doc2harness.runtime.artifact_executor import artifact_tree_digest
18
+ from doc2harness.runtime.catalog_executor import CatalogExecutionRequest, run_catalog
19
+
20
+
21
+ def _digest(value: str) -> str:
22
+ return "sha256:" + hashlib.sha256(value.encode("utf-8")).hexdigest()
23
+
24
+
25
+ def _selection(
26
+ repo_root: Path,
27
+ ids_file: Path | None,
28
+ scenario_id: str | None,
29
+ family: str | None,
30
+ ) -> tuple[str, ...]:
31
+ selected = sum(value is not None for value in (ids_file, scenario_id, family))
32
+ if selected > 1:
33
+ raise ValueError("use only one of --ids-file, --scenario-id, or --family")
34
+ if scenario_id:
35
+ return (scenario_id,)
36
+ if family:
37
+ values = tuple(
38
+ scenario_id
39
+ for scenario_id in active_scenario_ids()
40
+ if load_scenario_owner(scenario_id).definition.classification.primary == family
41
+ )
42
+ if not values:
43
+ raise ValueError(f"active catalog contains no family: {family}")
44
+ return values
45
+ if ids_file is not None:
46
+ values = tuple(
47
+ line.strip() for line in ids_file.read_text(encoding="utf-8").splitlines()
48
+ if line.strip() and not line.lstrip().startswith("#")
49
+ )
50
+ if not values or len(values) != len(set(values)):
51
+ raise ValueError("scenario ids file must contain unique non-empty IDs")
52
+ return values
53
+ return active_scenario_ids()
54
+
55
+
56
+ def main() -> int:
57
+ parser = argparse.ArgumentParser(description=__doc__)
58
+ parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1])
59
+ parser.add_argument("--artifact", type=Path, required=True)
60
+ parser.add_argument("--artifact-id", required=True)
61
+ parser.add_argument("--output", type=Path, required=True)
62
+ parser.add_argument("--ids-file", type=Path)
63
+ parser.add_argument("--scenario-id")
64
+ parser.add_argument("--family", help="select every active scenario with this primary classification")
65
+ parser.add_argument("--concurrency", type=int, default=1)
66
+ parser.add_argument("--timeout", type=float, default=300.0)
67
+ args = parser.parse_args()
68
+ repo_root = args.repo_root.resolve()
69
+ artifact = args.artifact.resolve()
70
+ selection = _selection(
71
+ repo_root,
72
+ args.ids_file.resolve() if args.ids_file else None,
73
+ args.scenario_id,
74
+ args.family,
75
+ )
76
+ source_digest = _digest("sbh-production-driver-source/1")
77
+ task_digest = _digest("sbh-production-catalog-task/1:" + ",".join(selection))
78
+ budget_digest = _digest(f"sbh-production-catalog-budget/1:{args.timeout}:{args.concurrency}")
79
+ # The universal dispatcher selects a reviewed family driver from the
80
+ # catalog owner. Reviewed routes cover direct, permission,
81
+ # file, artifact, state, headless, startup, TUI,
82
+ # and extension counterfactuals. Unsupported families fail closed per
83
+ # scenario rather than receiving a direct-mock execution by accident.
84
+ #
85
+ # It is invoked as an installed module rather than a repository file so an
86
+ # installed wheel can execute a test point without a checkout on disk.
87
+ request = CatalogExecutionRequest(
88
+ artifact=artifact,
89
+ driver_root=repo_root,
90
+ driver_argv=(
91
+ sys.executable,
92
+ "-m",
93
+ "doc2harness.runtime.driver_dispatch",
94
+ ),
95
+ output_dir=args.output.resolve(),
96
+ artifact_id=args.artifact_id,
97
+ source_digest=source_digest,
98
+ task_digest=task_digest,
99
+ budget_digest=budget_digest,
100
+ artifact_digest=artifact_tree_digest(artifact),
101
+ scenario_ids=selection,
102
+ concurrency=args.concurrency,
103
+ timeout_seconds=args.timeout,
104
+ )
105
+ os.environ.setdefault("PYTHONPATH", str(repo_root / "src"))
106
+ receipt = run_catalog(
107
+ request,
108
+ environ={
109
+ "PYTHONPATH": str(repo_root / "src"),
110
+ "SBH_EVALUATION_IMAGE": os.environ.get("SBH_EVALUATION_IMAGE", "doc2harness/evaluation:candidate"),
111
+ },
112
+ )
113
+ print(receipt)
114
+ return 0
115
+
116
+
117
+ if __name__ == "__main__":
118
+ raise SystemExit(main())