# Conflicts: # backend/plugins/manifest.py # sidecar/launch.py # sidecar/test_claude_args.py # sidecar/test_gcloud_reauth.py
600 lines
31 KiB
Python
600 lines
31 KiB
Python
"""Every claude launch path builds on _claude_args: the --settings payload
|
|
(stop guard hook + inbox opt-in) and the headless flags can't be missed by
|
|
one of spawn / resume / fork — the spawn path once was."""
|
|
|
|
import json
|
|
import pathlib
|
|
import re
|
|
|
|
import claude_env
|
|
import fork
|
|
import launch
|
|
import claude_launch
|
|
import routes_runs
|
|
from conftest import plugin_module
|
|
from config import CLAUDE_BIN, DISALLOWED_TOOLS, PERMISSION_MODE, STOP_GUARD_TIMEOUT_S
|
|
from claude_launch import _claude_args
|
|
|
|
SID = "11111111-2222-3333-4444-555555555555"
|
|
|
|
|
|
def _claude_runs():
|
|
"""harness-claude's run code (spawn / resume / fork) — the plugin's."""
|
|
return plugin_module("harness", "harness-claude", "runs")
|
|
|
|
|
|
def _pi():
|
|
return plugin_module("harness", "harness-pi", "driver")
|
|
|
|
|
|
def _pi_lean_args(lean, cwd, scope=None):
|
|
return _pi().lean_args(lean, cwd, scope, launch.lean_prompt)
|
|
|
|
|
|
def _settings(args):
|
|
assert args.count("--settings") == 1
|
|
return json.loads(args[args.index("--settings") + 1])
|
|
|
|
|
|
def test_spawn_and_resume_shapes_share_the_flags():
|
|
spawn = _claude_args("hi", "--session-id", SID)
|
|
resume = _claude_args("hi", "--resume", SID)
|
|
assert spawn[:5] == [CLAUDE_BIN, "-p", "hi", "--session-id", SID]
|
|
assert resume[:5] == [CLAUDE_BIN, "-p", "hi", "--resume", SID]
|
|
for a in (spawn, resume):
|
|
assert a[a.index("--output-format") + 1] == "json"
|
|
assert a[a.index("--permission-mode") + 1] == PERMISSION_MODE
|
|
if DISALLOWED_TOOLS:
|
|
assert " ".join(DISALLOWED_TOOLS) in a
|
|
s = _settings(a)
|
|
assert s["crossSessionInbound"] == "accept"
|
|
|
|
|
|
def test_settings_carry_the_stop_guard_hook():
|
|
s = _settings(_claude_args("hi", "--session-id", SID))
|
|
hooks = s["hooks"]["Stop"][0]["hooks"]
|
|
assert len(hooks) == 1
|
|
cmd = hooks[0]["command"]
|
|
assert cmd.endswith("stop_guard.py") and "python" in cmd
|
|
assert hooks[0]["timeout"] == STOP_GUARD_TIMEOUT_S
|
|
assert hooks[0]["type"] == "command"
|
|
|
|
|
|
def test_stop_guard_can_be_switched_off(monkeypatch):
|
|
# _claude_settings reads the flag from launch's own globals (it is bound
|
|
# there at import), so that is the module to patch — not config.
|
|
monkeypatch.setattr(claude_launch, "STOP_GUARD_ENABLED", False)
|
|
s = _settings(_claude_args("hi", "--session-id", SID))
|
|
assert "Stop" not in s.get("hooks", {}) and s["crossSessionInbound"] == "accept"
|
|
|
|
|
|
def test_settings_carry_the_bash_diff_hooks():
|
|
hooks = _settings(_claude_args("hi", "--session-id", SID))["hooks"]
|
|
for event, mode in (("PreToolUse", "pre"), ("PostToolUse", "post")):
|
|
(entry,) = [e for e in hooks[event] if "bash_diff.py" in e["hooks"][0]["command"]]
|
|
assert entry["matcher"] == "Bash"
|
|
assert entry["hooks"][0]["command"].endswith(f"bash_diff.py {mode}")
|
|
|
|
|
|
def test_a_scoped_run_diffs_only_inside_its_write_dirs():
|
|
hooks = claude_launch._claude_settings(["~/projects/guest-site"])["hooks"]
|
|
cmd = hooks["PostToolUse"][0]["hooks"][0]["command"]
|
|
assert cmd.endswith(" --within " + launch.os.path.expanduser("~/projects/guest-site"))
|
|
assert claude_launch._claude_settings([])["hooks"]["PreToolUse"][0]["hooks"][0][
|
|
"command"].endswith("--within /nonexistent")
|
|
assert "--within" not in claude_launch._claude_settings()["hooks"]["PreToolUse"][0]["hooks"][0][
|
|
"command"]
|
|
|
|
|
|
def test_bash_diff_can_be_switched_off(monkeypatch):
|
|
monkeypatch.setattr(claude_launch, "BASH_DIFF_ENABLED", False)
|
|
monkeypatch.setattr(claude_launch, "STOP_GUARD_ENABLED", False)
|
|
monkeypatch.setattr(claude_launch, "GUARD_ENABLED", False)
|
|
monkeypatch.setattr(claude_launch, "PLUGIN_HOOKS_ENABLED", False)
|
|
assert "hooks" not in _settings(_claude_args("hi", "--session-id", SID))
|
|
|
|
|
|
def test_every_launch_site_uses_the_builder():
|
|
# The builder lives in harness-claude's claude_launch.py; the three launch sites are spawn,
|
|
# resume and fork — the harness-claude plugin's runs.py.
|
|
src = "".join(open(m.__file__, encoding="utf-8").read()
|
|
for m in (launch, claude_launch, routes_runs, fork, _claude_runs()))
|
|
# the only literal `CLAUDE_BIN, "-p"` is the builder's own
|
|
assert len(re.findall(r'CLAUDE_BIN, "-p"', src)) == 1
|
|
assert src.count("_claude_args(prompt, ") == 3 # spawn, resume, fork
|
|
|
|
|
|
def test_run_env_exports_the_wait_ceiling(monkeypatch):
|
|
monkeypatch.setattr(claude_env, "BG_WAIT_CEILING_MS", "7200000")
|
|
env = claude_env._run_env(SID, None)
|
|
assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "7200000"
|
|
monkeypatch.setattr(claude_env, "BG_WAIT_CEILING_MS", "")
|
|
monkeypatch.delenv("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS", raising=False)
|
|
assert "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" not in claude_env._run_env(SID, None)
|
|
|
|
|
|
def test_run_env_never_carries_the_sidecar_token(monkeypatch):
|
|
monkeypatch.setenv("SIDECAR_TOKEN", "secret-bearer")
|
|
for account in (None, "personal"):
|
|
assert "SIDECAR_TOKEN" not in claude_env._run_env(SID, account)
|
|
|
|
|
|
def test_a_scope_swaps_bypass_for_dontask_and_confines_edits():
|
|
scope = {"writeDirs": ["~/projects/film", "/tmp"], "denyRead": ["~/.ssh/**"],
|
|
"systemPrompt": "guest rules", "remoteControl": False}
|
|
args = _claude_args("hi", "--session-id", SID, scope)
|
|
assert args[args.index("--permission-mode") + 1] == "dontAsk"
|
|
assert args[args.index("--permission-prompts") + 1] == "none"
|
|
assert args[args.index("--append-system-prompt") + 1] == "guest rules"
|
|
perms = _settings(args)["permissions"]
|
|
home = __import__("os").path.expanduser("~")
|
|
assert f"Edit(/{home}/projects/film/**)" in perms["allow"]
|
|
assert "Edit(//tmp/**)" in perms["allow"] and "Bash" in perms["allow"]
|
|
assert perms["deny"][0] == f"Read(/{home}/.ssh/**)"
|
|
# the project's own Claude config is never theirs to write
|
|
assert set(perms["deny"][1:]) == {
|
|
f"Edit(/{home}/projects/film/.claude/settings*.json)",
|
|
f"Edit(/{home}/projects/film/**/.claude/settings*.json)",
|
|
f"Edit(/{home}/projects/film/.mcp.json)", f"Edit(/{home}/projects/film/**/.mcp.json)",
|
|
"Edit(//tmp/.claude/settings*.json)", "Edit(//tmp/**/.claude/settings*.json)",
|
|
"Edit(//tmp/.mcp.json)", "Edit(//tmp/**/.mcp.json)"}
|
|
# the stop guard + inbox opt-in survive the merge
|
|
assert _settings(args)["crossSessionInbound"] == "accept"
|
|
assert claude_launch._remote_control("personal", scope) == []
|
|
|
|
|
|
def test_a_scope_read_dir_is_a_read_only_grant(monkeypatch):
|
|
scope = {"writeDirs": ["~/projects/film", "/tmp"],
|
|
"readDirs": ["/srv/data/guest-uploads/dom"],
|
|
"denyRead": ["/srv/data/uploads/**"]}
|
|
assert launch.valid_scope(scope) is scope
|
|
perms = _settings(_claude_args("hi", "--session-id", SID, scope))["permissions"]
|
|
assert "Read(//srv/data/guest-uploads/dom/**)" in perms["allow"]
|
|
assert not any(r.startswith("Edit(//srv/data/guest-uploads") for r in perms["allow"])
|
|
assert [r for r in perms["deny"] if r.startswith("Read(")] == ["Read(//srv/data/uploads/**)"]
|
|
sb = claude_launch._scope_settings({**scope, "sandbox": True})["sandbox"]["filesystem"]
|
|
assert "/srv/data/guest-uploads/dom" in sb["allowRead"]
|
|
assert "/srv/data/guest-uploads/dom" not in sb["allowWrite"]
|
|
|
|
|
|
def test_a_scope_git_author_sets_the_run_env():
|
|
scope = {"writeDirs": ["/tmp"], "gitAuthor": {"name": "Dom", "email": "dom@x.y"}}
|
|
assert launch.valid_scope(scope) is scope
|
|
assert _settings(_claude_args("hi", "--session-id", SID, scope))["env"] == {
|
|
"GIT_AUTHOR_NAME": "Dom", "GIT_AUTHOR_EMAIL": "dom@x.y", "AIA_GUEST": "guest"}
|
|
assert _settings(_claude_args("hi", "--session-id", SID, {"writeDirs": ["/tmp"]}))["env"] \
|
|
== {"AIA_GUEST": "guest"}
|
|
|
|
|
|
def test_bad_scope_is_refused():
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
for bad in ({"writeDirs": "/"}, {"nope": 1}, {"denyRead": [""]}, {"readDirs": "/x"},
|
|
{"gitAuthor": {"name": "Dom"}}, {"gitAuthor": "Dom"},
|
|
{"gitAuthor": {"name": "Dom", "email": "d@x", "x": "1"}}):
|
|
with pytest.raises(HTTPException):
|
|
launch.valid_scope(bad)
|
|
|
|
|
|
def test_extras_add_one_system_prompt_and_the_agents():
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
agents = {"work-context": {"description": "d", "prompt": "p", "model": "haiku",
|
|
"disallowedTools": ["Edit"]}}
|
|
a = _claude_args("hi", "--session-id", SID, append="Use work-context first.",
|
|
agents=agents)
|
|
assert a[a.index("--append-system-prompt") + 1] == "Use work-context first."
|
|
assert json.loads(a[a.index("--agents") + 1]) == agents
|
|
# a guest scope's prompt and the run's own go out as ONE flag
|
|
b = _claude_args("hi", "--resume", SID, {"systemPrompt": "You are helping Ana."},
|
|
append="Use work-context first.")
|
|
assert b.count("--append-system-prompt") == 1
|
|
assert b[b.index("--append-system-prompt") + 1] == \
|
|
"You are helping Ana.\n\nUse work-context first."
|
|
assert "--agents" not in _claude_args("hi", "--resume", SID)
|
|
assert claude_launch.valid_extras("x", agents) == ("x", agents)
|
|
# the clarifier's (2026-11-04): no CLAUDE.md, its own effort — listed in /health
|
|
lean = {"clarifier": {"description": "d", "prompt": "p", "omitClaudeMd": True,
|
|
"effort": "medium"}}
|
|
assert claude_launch.valid_extras(None, lean) == (None, lean)
|
|
assert {"omitClaudeMd", "effort"} <= set(claude_launch.AGENT_KEYS)
|
|
for bad in ({"Bad Name": {"description": "d", "prompt": "p"}},
|
|
{"a": {"description": "d", "prompt": "p", "omitClaudeMd": "yes"}},
|
|
{"a": {"description": "d", "prompt": "p", "effort": "huge"}},
|
|
{"a": {"description": "d"}},
|
|
{"a": {"description": "d", "prompt": "p", "permissionMode": "bypass"}},
|
|
{"a": {"description": "d", "prompt": "p", "tools": "Bash"}}):
|
|
with pytest.raises(HTTPException):
|
|
claude_launch.valid_extras(None, bad)
|
|
with pytest.raises(HTTPException):
|
|
claude_launch.valid_extras("x" * 9000, None)
|
|
|
|
|
|
def test_a_scoped_run_loses_the_owners_agents(tmp_path, monkeypatch):
|
|
"""A guest's run gets no SSH agent, D-Bus session or systemd user manager;
|
|
an owner run keeps them (deploys go through the agent)."""
|
|
seen = []
|
|
|
|
class Proc:
|
|
pid = 4242
|
|
|
|
def popen(args, **kw):
|
|
seen.append(kw["env"])
|
|
return Proc()
|
|
|
|
monkeypatch.setattr(launch, "LOG_DIR", tmp_path)
|
|
monkeypatch.setattr(launch.pids, "_procs", {}) # the fake Proc must not leak
|
|
monkeypatch.setattr(launch.subprocess, "Popen", popen)
|
|
monkeypatch.setattr(launch, "_probe_launch", lambda proc: None)
|
|
monkeypatch.setattr(launch.pids, "_pidfile", lambda sid: tmp_path / f"{sid}.pid")
|
|
monkeypatch.setattr(launch.pids, "_proc_starttime", lambda pid: 0)
|
|
monkeypatch.setenv("SSH_AUTH_SOCK", "/run/agent.sock")
|
|
monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/bus")
|
|
monkeypatch.setattr(launch.guest_git, "token_for", lambda *a: "tok-dom")
|
|
launch._launch(["true"], SID, str(tmp_path), scope={
|
|
"writeDirs": ["/tmp"], "git": {"user": "dom", "push": ["site"]}})
|
|
launch._launch(["true"], SID, str(tmp_path))
|
|
guest, owner = seen
|
|
assert "SSH_AUTH_SOCK" not in guest and "DBUS_SESSION_BUS_ADDRESS" not in guest
|
|
assert owner["SSH_AUTH_SOCK"] == "/run/agent.sock"
|
|
assert guest["CLAUDE_SESSION_ID"] == SID # the rest of the run env is there
|
|
# git pushes as the guest: every helper reset, then theirs answers
|
|
assert guest["GIT_CONFIG_KEY_0"] == "credential.helper" and guest["GIT_CONFIG_VALUE_0"] == ""
|
|
assert guest["GIT_CONFIG_VALUE_1"] == "" and "username=dom" in guest["GIT_CONFIG_VALUE_2"]
|
|
assert guest["AIA_GITEA_TOKEN"] == "tok-dom" and "AIA_GITEA_TOKEN" not in owner
|
|
|
|
|
|
def test_a_guest_run_is_capped_at_what_is_left_of_their_month():
|
|
args = claude_launch.scope_args(launch.valid_scope({"writeDirs": ["/tmp"], "maxBudgetUsd": 12.345}))
|
|
assert args[args.index("--max-budget-usd") + 1] == "12.35"
|
|
assert "--max-budget-usd" not in claude_launch.scope_args({"writeDirs": ["/tmp"]})
|
|
for bad in (0, -1, "5", True):
|
|
try:
|
|
launch.valid_scope({"maxBudgetUsd": bad})
|
|
except Exception as e:
|
|
assert getattr(e, "status_code", None) == 400
|
|
else:
|
|
raise AssertionError(bad)
|
|
|
|
|
|
def test_every_run_carries_the_guard():
|
|
"""An owner run's guard reports, a scoped one's blocks; a sandboxed scope
|
|
also reads its sandbox denials after each Bash call."""
|
|
owner = _settings(_claude_args("hi", "--session-id", SID))["hooks"]
|
|
guard_cmd = [h["hooks"][0]["command"] for h in owner["PreToolUse"]
|
|
if "guard.py" in h["hooks"][0]["command"]]
|
|
assert len(guard_cmd) == 1 and guard_cmd[0].endswith("pre --mode report")
|
|
assert not any("guard.py" in h["hooks"][0]["command"]
|
|
for h in owner.get("PostToolUse", []))
|
|
scoped = _settings(_claude_args("hi", "--session-id", SID, {
|
|
"writeDirs": ["/tmp"], "sandbox": True}))["hooks"]
|
|
(block,) = [h["hooks"][0]["command"] for h in scoped["PreToolUse"]
|
|
if "guard.py" in h["hooks"][0]["command"]]
|
|
assert "pre --mode block || printf %s " in block
|
|
# a guard that can't even start refuses the call (a scoped run fails closed)
|
|
import subprocess
|
|
broken = block.replace(str(claude_launch.GUARD), "/nonexistent/guard.py")
|
|
out = subprocess.run(["/bin/sh", "-c", broken], input="{}", capture_output=True, text=True)
|
|
assert json.loads(out.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny"
|
|
# …and one that runs speaks for itself: nothing appended to its answer
|
|
ok = subprocess.run(["/bin/sh", "-c", block], capture_output=True, text=True, input=json.dumps(
|
|
{"tool_name": "Bash", "tool_input": {"command": "ls"}}), env={"AI_AGENT_OUTBOX_URL": "x"})
|
|
assert ok.returncode == 0 and ok.stdout == ""
|
|
assert any(h["hooks"][0]["command"].endswith("post --mode block")
|
|
for h in scoped["PostToolUse"])
|
|
|
|
|
|
def test_the_guard_also_sees_monitor():
|
|
"""Monitor runs a shell command: it is on the guard's matcher, for the
|
|
owner's runs (reported) and a guest's (blocked, brokered)."""
|
|
for scope in (None, {"writeDirs": ["/tmp"]}):
|
|
pre = _settings(_claude_args("hi", "--session-id", SID, scope))["hooks"]["PreToolUse"]
|
|
(g,) = [h for h in pre if "guard.py" in h["hooks"][0]["command"]]
|
|
assert g["matcher"].split("|")[:2] == ["Bash", "Monitor"]
|
|
|
|
|
|
def test_hooks_start_isolated():
|
|
"""`python -I`: no PYTHONPATH / user site, no cwd on sys.path — nothing a
|
|
run's environment or folder names is imported by a hook."""
|
|
lean = launch.valid_lean({"allow": ["mail"]})
|
|
for a in (_claude_args("hi", "--session-id", SID),
|
|
_claude_args("hi", "--session-id", SID, {"writeDirs": ["/tmp"], "sandbox": True}),
|
|
_claude_args("job", "--session-id", SID, lean=lean)):
|
|
cmds = [h["command"] for entries in _settings(a)["hooks"].values()
|
|
for e in entries for h in e["hooks"]]
|
|
assert cmds and all(re.match(r"^\S*python\S* -I \S+\.py( |$)", c) for c in cmds), cmds
|
|
|
|
|
|
def test_each_hook_runs_under_isolated_mode(tmp_path):
|
|
"""…and each of the four still starts that way (stdlib only): run them."""
|
|
import subprocess, sys
|
|
here = pathlib.Path(launch.__file__).resolve().parent
|
|
hook = json.dumps({"session_id": SID, "tool_name": "Bash", "cwd": str(tmp_path),
|
|
"tool_input": {"command": "echo hi"}, "tool_use_id": "t1",
|
|
"transcript_path": str(tmp_path / "t.jsonl")})
|
|
for argv in (["guard.py", "pre", "--mode", "report"], ["allow_guard.py", "--allow", "echo"],
|
|
["bash_diff.py", "pre", "--within", str(tmp_path)], ["stop_guard.py"]):
|
|
script = claude_launch.STOP_GUARD if argv[0] == "stop_guard.py" else here / argv[0]
|
|
p = subprocess.run([sys.executable, "-I", str(script), *argv[1:]], input=hook,
|
|
capture_output=True, text=True, timeout=30, cwd=tmp_path,
|
|
env={"PATH": "/usr/bin:/bin", "HOME": str(tmp_path),
|
|
"PYTHONPATH": str(tmp_path), "AI_AGENT_OUTBOX_URL": "x"})
|
|
assert p.returncode == 0 and "Traceback" not in p.stderr, (argv, p.stderr)
|
|
|
|
|
|
def test_a_scoped_lab_run_ignores_the_projects_own_claude_settings(tmp_path, monkeypatch):
|
|
"""On the lab a guest's run loads the owner's user settings only, no MCP
|
|
server, and gets the project's CLAUDE.md as text (the CLI no longer reads
|
|
it); a guest's own computer keeps its project settings."""
|
|
(tmp_path / "CLAUDE.md").write_text("Use pnpm. See @docs/setup.md")
|
|
scope = {"writeDirs": [str(tmp_path)], "systemPrompt": "guest rules"}
|
|
monkeypatch.setattr(claude_launch, "ISOLATE_SCOPED", True)
|
|
a = _claude_args("hi", "--session-id", SID, scope, append="extra", cwd=str(tmp_path))
|
|
assert a[a.index("--setting-sources") + 1] == "user" and "--strict-mcp-config" in a
|
|
prompt = a[a.index("--append-system-prompt") + 1]
|
|
assert prompt.startswith("guest rules\n\nextra\n\n# This project's instructions (CLAUDE.md)")
|
|
assert "Use pnpm. See @docs/setup.md" in prompt and "not loaded" in prompt
|
|
# an owner's run is untouched
|
|
o = _claude_args("hi", "--session-id", SID, cwd=str(tmp_path))
|
|
assert "--setting-sources" not in o and "--strict-mcp-config" not in o
|
|
assert "--append-system-prompt" not in o
|
|
# a lean scoped run already loads no settings at all: one flag, not two
|
|
lean = launch.valid_lean({"tools": ["Bash"]})
|
|
l = _claude_args("job", "--session-id", SID, scope, lean=lean, cwd=str(tmp_path))
|
|
assert l.count("--setting-sources") == 1 and l[l.index("--setting-sources") + 1] == ""
|
|
# a guest's own computer (a worker): their project, their settings
|
|
monkeypatch.setattr(claude_launch, "ISOLATE_SCOPED", False)
|
|
w = _claude_args("hi", "--session-id", SID, scope, cwd=str(tmp_path))
|
|
assert "--setting-sources" not in w and "CLAUDE.md" not in w[w.index("--append-system-prompt") + 1]
|
|
|
|
|
|
def test_resume_and_fork_pass_the_cwd_to_the_builder():
|
|
"""…or a resumed guest run would lose its project's instructions."""
|
|
src = pathlib.Path(_claude_runs().__file__).read_text()
|
|
calls = [src[m.end():m.end() + 260] for m in re.finditer(r"_claude_args\(prompt,", src)]
|
|
assert len(calls) == 3 and all("cwd=cwd" in c for c in calls)
|
|
|
|
|
|
def test_project_md_is_never_read_through_a_link(tmp_path):
|
|
secret = tmp_path / "id_ed25519"
|
|
secret.write_text("PRIVATE KEY")
|
|
proj = tmp_path / "proj"
|
|
proj.mkdir()
|
|
assert claude_launch.project_md(str(proj)) is None # no file
|
|
(proj / "CLAUDE.md").symlink_to(secret) # a link to a key
|
|
assert claude_launch.project_md(str(proj)) is None
|
|
(proj / "CLAUDE.md").unlink()
|
|
outside = tmp_path / "outside"
|
|
outside.mkdir()
|
|
(outside / "CLAUDE.md").write_text("PRIVATE NOTES")
|
|
(proj / ".claude").symlink_to(outside) # a linked folder
|
|
assert claude_launch.project_md(str(proj)) is None
|
|
(proj / ".claude").unlink()
|
|
(proj / ".claude").mkdir()
|
|
(proj / ".claude" / "CLAUDE.md").write_text("in .claude")
|
|
assert "in .claude" in claude_launch.project_md(str(proj))
|
|
(proj / "CLAUDE.md").write_text("é" * 100_000) # capped, and says so
|
|
md = claude_launch.project_md(str(proj))
|
|
assert len(md.encode()) < claude_launch.PROJECT_MD_MAX + 600 and "[…cut" in md
|
|
os_mkfifo = getattr(__import__("os"), "mkfifo", None)
|
|
if os_mkfifo: # not a regular file
|
|
(proj / "CLAUDE.md").unlink()
|
|
os_mkfifo(proj / "CLAUDE.md")
|
|
assert "in .claude" in claude_launch.project_md(str(proj))
|
|
# the whole argument stays under one argv element's limit
|
|
(proj / "CLAUDE.md").unlink()
|
|
(proj / "CLAUDE.md").write_text("x" * 200_000)
|
|
args = claude_launch._system_prompt_args({"systemPrompt": "é" * 8000}, "é" * 8000, str(proj))
|
|
assert args == [] or len(args[1].encode()) < 128 * 1024
|
|
|
|
|
|
def test_a_no_bash_scope_runs_without_a_shell():
|
|
"""A guest's *No project* chat with its Bash switch off: neither Bash nor
|
|
Monitor is allowed, and neither is offered to the model."""
|
|
scope = {"writeDirs": ["/tmp"], "noBash": True}
|
|
assert launch.valid_scope(scope) is scope
|
|
a = _claude_args("hi", "--session-id", SID, scope)
|
|
perms = _settings(a)["permissions"]
|
|
assert "Bash" not in perms["allow"] and "Monitor" not in perms["allow"]
|
|
assert "WebSearch" in perms["allow"] and "Skill" in perms["allow"]
|
|
assert "Bash" in perms["deny"] and "Monitor" in perms["deny"]
|
|
off = a[a.index("--disallowed-tools") + 1].split()
|
|
assert {"Bash", "Monitor", *DISALLOWED_TOOLS} <= set(off)
|
|
# …and without the switch nothing changes
|
|
b = _claude_args("hi", "--session-id", SID, {"writeDirs": ["/tmp"]})
|
|
assert "Bash" in _settings(b)["permissions"]["allow"]
|
|
assert "Bash" not in (b[b.index("--disallowed-tools") + 1].split()
|
|
if "--disallowed-tools" in b else [])
|
|
# a lean run names its tools: Bash drops out of the list (claude and pi)
|
|
lean = launch.valid_lean({"tools": ["Bash", "Read", "WebSearch"]})
|
|
l = _claude_args("job", "--session-id", SID, scope, lean=lean)
|
|
assert l[l.index("--tools") + 1] == "Read,WebSearch"
|
|
assert _pi_lean_args(lean, "/tmp", scope)[
|
|
_pi_lean_args(lean, "/tmp", scope).index("--tools") + 1] == "read"
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
with pytest.raises(HTTPException):
|
|
launch.valid_scope({"writeDirs": ["/tmp"], "noBash": "yes"})
|
|
|
|
|
|
def test_a_scope_is_refused_where_it_would_be_dropped(monkeypatch):
|
|
"""opencode on spawn, pi and opencode on resume and fork: the sidecar used
|
|
to drop the scope without a word and start the run with full rights."""
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
monkeypatch.setattr(routes_runs, "_auth", lambda _a: None)
|
|
monkeypatch.setattr(fork, "_auth", lambda _a: None)
|
|
scope = {"writeDirs": ["/tmp"]}
|
|
started = []
|
|
# The drivers launch and stop through the sidecar's launch module.
|
|
monkeypatch.setattr(launch, "_launch", lambda *a, **k: started.append(a) or {})
|
|
monkeypatch.setattr(launch, "_stop_run", lambda *a, **k: started.append(a))
|
|
with pytest.raises(HTTPException) as e:
|
|
routes_runs.spawn(routes_runs.SpawnBody(prompt="hi", harness="opencode", cwd="/tmp",
|
|
scope=scope), None)
|
|
assert e.value.status_code == 400 and "scoped" in str(e.value.detail)
|
|
for harness in ("pi", "opencode"):
|
|
if harness == "opencode": # a guest's pi turn is scoped (harness-pi scope_args)
|
|
with pytest.raises(HTTPException) as e:
|
|
routes_runs.resume(routes_runs.ResumeBody(
|
|
sessionId=SID, prompt="hi", harness=harness, cwd="/tmp", scope=scope,
|
|
force=True), None)
|
|
assert e.value.status_code == 400
|
|
with pytest.raises(HTTPException) as e:
|
|
fork.fork(fork.ForkBody(sessionId=SID, srcSessionId=SID, prompt="hi", cutLine=1,
|
|
harness=harness, cwd="/tmp", scope=scope), None)
|
|
assert e.value.status_code == 400
|
|
assert started == [] # nothing stopped, nothing launched
|
|
|
|
|
|
def test_a_scoped_run_says_whose_it_is():
|
|
s = claude_launch._scope_settings({"writeDirs": ["/tmp"], "git": {"user": "dom", "push": []}})
|
|
assert s["env"]["AIA_GUEST"] == "dom"
|
|
assert "AIA_GUEST" not in _settings(_claude_args("hi", "--session-id", SID)).get("env", {})
|
|
|
|
|
|
def test_the_sandbox_hides_the_home_but_the_runs_folders(monkeypatch):
|
|
monkeypatch.setenv("SIDECAR_SANDBOX_DOMAINS", "extra.example")
|
|
sb = claude_launch._scope_settings({"writeDirs": ["~/projects/film", "/tmp"], "sandbox": True,
|
|
"sandboxDomains": ["domvidal.xyz", "*.domvidal.xyz"]})["sandbox"]
|
|
home = launch.os.path.expanduser("~")
|
|
assert sb["failIfUnavailable"] and not sb["allowUnsandboxedCommands"]
|
|
assert sb["filesystem"]["denyRead"] == [home]
|
|
assert f"{home}/projects/film" in sb["filesystem"]["allowRead"]
|
|
assert f"{home}/projects/film" in sb["filesystem"]["allowWrite"]
|
|
doms = sb["network"]["allowedDomains"]
|
|
assert "registry.npmjs.org" in doms and "*.domvidal.xyz" in doms and "extra.example" in doms
|
|
assert not any(d in doms for d in ("localhost", "127.0.0.1", "*"))
|
|
|
|
|
|
def test_a_lean_run_swaps_the_context_for_the_short_prompt():
|
|
lean = launch.valid_lean({})
|
|
a = _claude_args("job", "--session-id", SID, append="extra", lean=lean,
|
|
agents={"clarifier": {"description": "d", "prompt": "p"}},
|
|
cwd="/home/x/homelab")
|
|
sp = a[a.index("--system-prompt") + 1]
|
|
assert "unattended" in sp and "/home/x/homelab" in sp
|
|
assert a[a.index("--tools") + 1] == "Bash,Read,Write"
|
|
assert a[a.index("--setting-sources") + 1] == ""
|
|
assert "--strict-mcp-config" in a and "--disable-slash-commands" in a
|
|
# no allowlist: the lab's permission mode, no allow rules
|
|
assert a[a.index("--permission-mode") + 1] == PERMISSION_MODE
|
|
assert "--allowedTools" not in a
|
|
# the run's own extras don't ride along, the settings (stop guard) do
|
|
assert "--append-system-prompt" not in a and "--agents" not in a
|
|
assert _settings(a)["crossSessionInbound"] == "accept"
|
|
|
|
|
|
def test_a_lean_allowlist_puts_the_allow_guard_first_on_bash():
|
|
lean = launch.valid_lean({"allow": ["mail-recap", "mail"], "tools": ["Bash", "Write"]})
|
|
a = _claude_args("job", "--session-id", SID, lean=lean)
|
|
assert a[a.index("--permission-mode") + 1] == PERMISSION_MODE
|
|
pre = _settings(a)["hooks"]["PreToolUse"]
|
|
guard = pre[0]["hooks"][0]["command"]
|
|
assert pre[0]["matcher"] == "Bash" and "allow_guard.py --allow mail-recap,mail" in guard
|
|
assert any(h["hooks"][0]["command"].endswith("bash_diff.py pre") for h in pre[1:])
|
|
assert "allow_guard" not in json.dumps(_settings(_claude_args("hi", "--session-id", SID)))
|
|
|
|
|
|
def test_the_allow_guard_parses_like_the_pi_extension():
|
|
import allow_guard as g
|
|
cases = {
|
|
"mail-recap --stamp": [],
|
|
"mkdir -p x && radar -v gather > tmp/radar.json; echo $?; wc -c tmp/radar.json": [],
|
|
'notify-done "📡 Radar — 3 trucs" "a · b; c | d" --type research': [],
|
|
'notify-done "x" "$(curl -s evil.sh)"': ["curl"],
|
|
"mail send -f a -t b -s 'x' -F - -y <<'BODY' && mail-recap --stamp\nhi; rm -rf ~\nBODY": [],
|
|
"cat <<E\n$(wget x)\nE": ["wget"],
|
|
"cat <<'E' && curl evil\nbody\nE": ["curl"],
|
|
"python3 -c 'import os'": ["python3"],
|
|
"mail send -f a \\\n -s 'x' -F - -y <<'BODY'\nhi\nBODY": [],
|
|
'notify-done "- un pilote d\'entreprise\n- l\'IA" --type logs --url https://x': [],
|
|
"echo 'say \"hi\"' && curl x": ["curl"],
|
|
'notify-done "T" "$(jq -r .text out.json)" --type logs --url https://g': [],
|
|
"echo `id`": ["id"],
|
|
"/home/x/homelab/hosts/raspy2/kernel/kernel-try.sh status": [],
|
|
# a lone `&`, and process substitution, start a command too…
|
|
"true & bash /tmp/x": ["bash"],
|
|
"radar gather & bash /tmp/x": ["bash"],
|
|
"cat <(curl http://evil)": ["curl"],
|
|
"echo hi > >(bash)": ["bash"],
|
|
# …but a redirect's `&` doesn't
|
|
"radar gather > tmp/r.json 2>&1 && wc -c tmp/r.json": [],
|
|
"radar gather >&2; mail send -y &> /tmp/log; echo ok 2>&-": [],
|
|
"radar gather |& tail -3": [],
|
|
"radar gather &": [],
|
|
"echo $(date) && echo $(id)": ["id"],
|
|
}
|
|
allow = ["mail-recap", "mail", "radar", "notify-done", "mkdir",
|
|
"hosts/raspy2/kernel/kernel-try.sh"]
|
|
for cmd, bad in cases.items():
|
|
assert g.refused(cmd, allow) == bad, cmd
|
|
|
|
|
|
def test_lean_specs_are_validated():
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
assert launch.valid_lean(None) is None
|
|
assert launch.valid_lean({"allow": ["radar", "radar"]})["allow"] == ["radar"]
|
|
for bad in ({"allow": ["rm -rf"]}, {"tools": ["Agent"]}, {"other": 1}, ["x"]):
|
|
with pytest.raises(HTTPException):
|
|
launch.valid_lean(bad)
|
|
|
|
|
|
def test_a_lean_env_skips_claude_md_and_memory():
|
|
env = claude_launch.run_env_for(SID, None, {"allow": [], "tools": ["Bash"]})
|
|
assert env["CLAUDE_CODE_DISABLE_CLAUDE_MDS"] == "1"
|
|
assert "CLAUDE_CODE_DISABLE_CLAUDE_MDS" not in claude_launch.run_env_for(SID, None, None)
|
|
|
|
|
|
def test_a_lean_pi_run_gets_the_runner_flags():
|
|
lean = launch.valid_lean({"allow": ["lab-digest", "notify-done"],
|
|
"tools": ["Bash", "Write", "WebFetch"]})
|
|
a = _pi_lean_args(lean, "/home/x/homelab")
|
|
assert a[0] == "--lean" and "unattended" in a[a.index("--system-prompt") + 1]
|
|
assert a[a.index("--tools") + 1] == "bash,write" # no pi WebFetch
|
|
assert a[a.index("--allow") + 1] == "lab-digest,notify-done"
|
|
|
|
|
|
def test_a_scoped_pi_run_reads_only_its_folder_and_carries_the_guest_prompt():
|
|
"""A guest's scheduled job on pi (backend cron/guests.py): the guest's lines
|
|
after the lean prompt, reads narrowed to the cwd + writeDirs."""
|
|
lean = launch.valid_lean({"allow": ["web", "notify-done"], "tools": ["Bash", "Write"]})
|
|
scope = launch.valid_scope({"writeDirs": ["/tmp"], "systemPrompt": "## Who you are working for"})
|
|
a = _pi_lean_args(lean, "/home/x/.local/share/ai-agent/guest-jobs/arthur", scope)
|
|
prompt = a[a.index("--system-prompt") + 1]
|
|
assert "unattended" in prompt and prompt.endswith("## Who you are working for")
|
|
assert a[a.index("--read") + 1] == "/home/x/.local/share/ai-agent/guest-jobs/arthur:/tmp"
|
|
assert "--read" not in _pi_lean_args(lean, "/home/x")
|
|
|
|
|
|
def test_a_guests_own_pi_run_is_scoped(monkeypatch):
|
|
"""A model of the guest pool on pi (Settings → Models): the runner's
|
|
--scoped, the scope's system prompt, reads narrowed, Bash off on ask."""
|
|
monkeypatch.setattr(routes_runs, "_auth", lambda _a: None)
|
|
seen = {}
|
|
monkeypatch.setattr(launch, "_launch",
|
|
lambda args, *a, **k: seen.update(args=args, scope=k.get("scope")) or {})
|
|
scope = {"writeDirs": ["/tmp"], "readDirs": ["/srv/shared"], "systemPrompt": "guest rules",
|
|
"noBash": True}
|
|
routes_runs.spawn(routes_runs.SpawnBody(prompt="hi", harness="pi", cwd="/tmp",
|
|
model="ggml-org/qwen3.8-27b", scope=scope), None)
|
|
a = seen["args"]
|
|
assert "--scoped" in a and "--lean" not in a
|
|
assert a[a.index("--append-system-prompt") + 1] == "guest rules"
|
|
assert a[a.index("--read") + 1] == "/tmp:/tmp:/srv/shared"
|
|
assert "bash" not in a[a.index("--tools") + 1]
|
|
assert seen["scope"]["systemPrompt"] == "guest rules"
|
|
|
|
|
|
def test_a_guest_jobs_folder_is_made_on_its_first_run(tmp_path, monkeypatch):
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
monkeypatch.setattr(launch, "GUEST_JOBS_DIR", str(tmp_path / "guest-jobs"))
|
|
made = launch._run_cwd(str(tmp_path / "guest-jobs" / "arthur"))
|
|
assert pathlib.Path(made).is_dir()
|
|
with pytest.raises(HTTPException): # anywhere else must exist
|
|
launch._run_cwd(str(tmp_path / "elsewhere" / "arthur"))
|
|
with pytest.raises(HTTPException): # not a guest id
|
|
launch._run_cwd(str(tmp_path / "guest-jobs" / "Bad..Id"))
|