Skip to content

Official Codebase of 3DCodeVerse

Python

harden the agent boundary: git config, gemini MCP, scene mounts, write_roots

gaoypeng00006a0ebb79
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index aed50d55..03cf5360 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -251,29 +251,35 @@ def begin_session(job: AgentJob, kind: str) -> Session:
def _enforce_scope(s: Session) -> list[str]:
- """Restore an ``edit_only`` session's out-of-scope writes; returns the restored paths.
-
- Post-hoc, because the CLI backends have no write-time file gate. A PRE-EXISTING
- file that changed and is neither in ``files_hint`` nor always-writable (the entry
- file, when the task owns it) is out of scope; new files stay allowed — the exact
- contract ``FileTools`` enforces for the api-agent. Only safe because sessions on
- one workspace are serialised (:data:`EXCLUSIVE_KINDS`): ``head_before`` holds no
- sibling's in-flight work, so restoring to it cannot destroy anyone else's files."""
- if not (s.job.edit_only and s.files_hint):
+ """Revert a CLI session's out-of-scope writes; returns the reverted paths.
+
+ Post-hoc, because the CLI backends have no write-time file gate. Two layers:
+ ``job.write_roots`` ALWAYS (what ``FileTools`` refuses outright for the api-agent —
+ a CLI session used to be able to write and commit a root-level ``conftest.py``),
+ then, for ``edit_only``, the narrowing to ``files_hint`` + ``always_writable``
+ (a pre-existing file outside it is out of scope; new files stay allowed). Only
+ safe because sessions on one workspace are serialised (:data:`EXCLUSIVE_KINDS`):
+ ``head_before`` holds no sibling's in-flight work."""
+ roots = tuple(r.strip("/") for r in s.job.write_roots if r.strip("/"))
+ narrow = (s.files_hint | frozenset(h for h in (str(x).strip() for x in s.job.always_writable) if h)
+ if (s.job.edit_only and s.files_hint) else frozenset())
+ if not roots and not narrow:
return []
- allowed = s.files_hint | frozenset(
- h for h in (str(x).strip() for x in s.job.always_writable) if h)
- out: list[str] = []
+ restore: list[str] = []
+ remove: list[str] = []
for f in s.ws.changed_files(s.head_before):
parts = Path(f.path).parts
if not parts or parts[0] in HARNESS_OWNED_DIRS or f.path in HARNESS_OWNED_FILES:
continue
- if f.status == "added" or _hinted(f.path, allowed):
+ if roots and not any(f.path == r or f.path.startswith(r + "/") for r in roots):
+ pass # outside write_roots: out of scope whatever its status
+ elif not narrow or f.status == "added" or _hinted(f.path, narrow):
continue
- out.append(f.path)
- if out:
- s.ws.restore_paths(s.head_before, out)
- return out
+ (remove if f.status == "added" else restore).append(f.path)
+ s.ws.restore_paths(s.head_before, restore)
+ for path in remove: # added files are not in head_before; the next `git add -A` stages the delete
+ (s.ws.root / path).unlink(missing_ok=True)
+ return sorted(restore + remove)
def finish_session(
@@ -290,17 +296,19 @@ def finish_session(
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
session — see :func:`attribute_changes`), write result.json.
- ``edit_only`` jobs are scope-checked here for the CLI backends (they have no
- write-time gate): out-of-scope changes to pre-existing files are restored to this
- session's own ``pre:`` commit and the session is failed (:func:`_enforce_scope`)."""
+ Write scope is enforced here for the CLI backends (they have no write-time gate):
+ writes outside ``write_roots`` (and, for ``edit_only``, outside ``files_hint``) are
+ reverted to this session's own ``pre:`` commit and the session is failed
+ (:func:`_enforce_scope`)."""
try:
errors = list(errors or [])
restored = _enforce_scope(s)
if restored:
ok = False
- msg = ("out-of-scope writes restored: " + ", ".join(sorted(restored))
- + f" — this edit_only session may only change {sorted(s.files_hint)} "
- "(new files, and the entry file when the task owns it, stay allowed)")
+ msg = ("out-of-scope writes reverted: " + ", ".join(restored)
+ + f" — this session may only write under {sorted(s.job.write_roots)}"
+ + (f", limited to {sorted(s.files_hint)} (new files, and the entry file when the "
+ "task owns it, stay allowed)" if s.job.edit_only and s.files_hint else ""))
errors.append(msg)
s.notes.append(msg)
s.ws.commit(f"agent:{s.label}")
diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.py
index d5cb41d0..8f91a93a 100644
--- a/harness/codeverse/agents/gemini_cli.py
+++ b/harness/codeverse/agents/gemini_cli.py
@@ -3,9 +3,9 @@
argv: ``gemini -p <prompt> -m <model> --approval-mode yolo --skip-trust --output-format json``
* env hardening: host secrets stripped, one pool key as ``GEMINI_API_KEY``,
- ``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` forcing api-key auth + dynamic model
- configuration (otherwise an unknown model is *silently* substituted), Node
- heap cap, no self-relaunch.
+ ``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` (per session, in the trajectory dir) forcing
+ api-key auth + dynamic model configuration (otherwise an unknown model is *silently*
+ substituted), the 3dcv MCP server and ``mcp.allowed``, Node heap cap, no self-relaunch.
* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{prompt,
input, candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost
via pricing). ``tokens.prompt`` is the TOTAL prompt size and ``tokens.input``
@@ -36,10 +36,12 @@ from codeverse.agents.cli_common import (
invoke,
is_quota_failure,
is_transient_failure,
+ mcp_command_for,
release_session,
tail,
watchdog_error,
)
+from codeverse.agents.materialize import MCP_SERVER_NAME, MCP_TOOL_TIMEOUT_MS
from codeverse.agents.watchdog import CompletedProc
from codeverse.config import get_settings
from codeverse.contracts.agent import AgentJob, AgentResult
@@ -71,11 +73,19 @@ def _key_pool(keys: list[str]) -> KeyPool:
return pool
-def write_system_settings(path: Path | None = None) -> Path:
- """Write the gemini-cli system-settings json (api-key auth + dynamic models) and return its path."""
+def write_system_settings(path: Path | None = None, *, mcp_command: list[str] | None = None) -> Path:
+ """Write the gemini-cli system-settings json (api-key auth + dynamic models) and return its path.
+
+ gemini-cli applies this file LAST and ``mcp.allowed`` REPLACES rather than merges, so the
+ 3dcv server and the allow-list belong here, not in the agent-writable
+ ``ws/.gemini/settings.json``: a server the agent planted there is Blocked."""
path = path or (get_settings().cache_dir / "gemini_cli_settings.json")
path.parent.mkdir(parents=True, exist_ok=True)
- want = json.dumps(SYSTEM_SETTINGS, indent=2)
+ data: dict[str, Any] = {**SYSTEM_SETTINGS, "mcp": {"allowed": [MCP_SERVER_NAME]}}
+ if mcp_command:
+ data["mcpServers"] = {MCP_SERVER_NAME: {"command": mcp_command[0], "args": list(mcp_command[1:]),
+ "timeout": MCP_TOOL_TIMEOUT_MS}}
+ want = json.dumps(data, indent=2)
if not path.is_file() or path.read_text() != want:
path.write_text(want)
return path
@@ -168,7 +178,11 @@ class GeminiCliAgent:
def build_env(self, s: Session, api_key: str) -> dict[str, str]:
env = hardened_env(s.ws, s.job)
env["GEMINI_API_KEY"] = api_key
- env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(write_system_settings())
+ # per SESSION, in the harness-owned trajectory dir: the command is per-run
+ # (``--workspace <ws>``) and it is rewritten immediately before every invoke
+ env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(write_system_settings(
+ s.traj.dir / "gemini_settings.json",
+ mcp_command=mcp_command_for(s.ws, s.job) if s.job.spatial_tools else None))
env["GEMINI_CLI_NO_RELAUNCH"] = "1"
node_opts = env.get("NODE_OPTIONS", "")
if "--max-old-space-size" not in node_opts:
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.py
index 7c73ca05..4e1b7dd0 100644
--- a/harness/codeverse/agents/materialize.py
+++ b/harness/codeverse/agents/materialize.py
@@ -5,8 +5,9 @@ One shared body is written to ``AGENTS.md`` (codex / generic), ``GEMINI.md``
the ``3dcv`` spatial tools, where the cookbook is, and the language contract.
MCP wiring:
-* gemini-cli → ``ws/.gemini/settings.json`` (merged) ``mcpServers.3dcv``
-* claude-code → ``ws/.mcp.json``
+* gemini-cli → the per-session system settings (``agents/gemini_cli.write_system_settings``);
+ ``ws/.gemini/settings.json`` is agent-writable, so it only carries the ``context`` block
+* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/claude_code.py``)
* codex → ``-c`` overrides returned in :class:`Materialized.codex_overrides`
* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.
@@ -61,7 +62,6 @@ class Materialized(BaseModel):
"""What :func:`materialize_workspace` wrote and how each CLI reaches the tools."""
body_files: list[str] = Field(default_factory=list)
- mcp_files: list[str] = Field(default_factory=list)
ignore_files: list[str] = Field(default_factory=list)
cookbook_path: str = ""
mcp_command: list[str] = Field(default_factory=list)
@@ -226,14 +226,12 @@ def materialize_workspace(
(ws.root / name).write_text(body)
out.body_files.append(str(ws.root / name))
+ # No MCP server is written into the workspace: every CLI gets 3dcv from a harness-owned
+ # per-session file, so an agent-planted server cannot reach the next round (audit 2026-08-27).
gemini_settings = ws.root / ".gemini" / "settings.json"
- claude_mcp = ws.root / ".mcp.json"
_merge_json(gemini_settings, {"context": dict(GEMINI_CONTEXT_SETTINGS)})
+ _drop_server(gemini_settings)
if spatial_tools:
- server = {"command": mcp_command[0], "args": list(mcp_command[1:]), "timeout": MCP_TOOL_TIMEOUT_MS}
- _merge_json(gemini_settings, {"mcpServers": {MCP_SERVER_NAME: server}})
- _merge_json(claude_mcp, {"mcpServers": {MCP_SERVER_NAME: {"type": "stdio", **server}}})
- out.mcp_files = [str(gemini_settings), str(claude_mcp)]
out.codex_overrides = codex_mcp_overrides(list(mcp_command))
out.agy_mcp = (
"Antigravity CLI only supports GLOBAL MCP registration (`agy mcp add ...`), which would "
@@ -241,8 +239,6 @@ def materialize_workspace(
"`python -m codeverse.cli.main tools <name> --json ...` shell fallback instead."
)
else:
- _drop_server(gemini_settings)
- _drop_server(claude_mcp)
out.agy_mcp = "spatial tools disabled"
ignore_text = "\n".join(IGNORE_LINES) + "\n"
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index 8cad8bed..10f21a93 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -56,6 +56,24 @@ _GITIGNORE_LINES = (
)
+#: prepended to every workspace git argv: an agent-planted hook / fsmonitor never runs.
+_GIT_SAFE_FLAGS = ("-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false")
+#: local (.git/config) config that makes git EXECUTE a program. ``-c`` cannot override a
+#: local ``filter.*`` / ``diff.*`` driver, so these are unset in place before every commit.
+_GIT_EXEC_SECTIONS = ("filter", "diff", "alias", "gpg", "credential")
+_GIT_EXEC_KEYS = ("core.hookspath", "core.fsmonitor", "core.sshcommand", "core.pager", "commit.gpgsign")
+
+
+def _git_home() -> str:
+ """HOME for workspace git: harness-owned, never the workspace (whose agent-written
+ ``.gitconfig`` git reads as its GLOBAL config). The cache_dir DEFAULT, spelled out:
+ workspace.py may not import config (tests/install/test_import_direction)."""
+ d = Path.home() / ".cache" / "codeverse" / "githome"
+ with contextlib.suppress(OSError): # a missing HOME is harmless; an unwritable one must not sink git
+ d.mkdir(parents=True, exist_ok=True)
+ return str(d)
+
+
class WorkspaceGitError(subprocess.CalledProcessError):
"""A git command in a run workspace failed, carrying git's own explanation.
@@ -90,6 +108,7 @@ class Workspace:
def __init__(self, root: Path | str):
self.root = Path(root).resolve()
+ self._cfg_mtime: int = -1 # .git/config mtime at the last _sanitise_git_config
# ----------------------------------------------------------------- paths
def rebase(self, stored: str | Path) -> Path:
@@ -289,10 +308,11 @@ class Workspace:
with self._lock:
for attempt in range(4):
proc = subprocess.run(
- ["git", *args], cwd=self.root, text=True, capture_output=True, check=False,
+ ["git", *_GIT_SAFE_FLAGS, *args], cwd=self.root, text=True, capture_output=True, check=False,
env={"GIT_AUTHOR_NAME": "3dcv", "GIT_AUTHOR_EMAIL": "3dcv@local",
"GIT_COMMITTER_NAME": "3dcv", "GIT_COMMITTER_EMAIL": "3dcv@local",
- "PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": str(self.root)},
+ "PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": _git_home(),
+ "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"},
)
if proc.returncode == 0 or "index.lock" not in (proc.stderr or ""):
break
@@ -301,8 +321,21 @@ class Workspace:
raise WorkspaceGitError(self.root, args, proc.returncode, proc.stderr or "")
return proc
+ def _sanitise_git_config(self) -> None:
+ """Unset the exec-capable keys an agent may have written into ``.git/config``.
+ Cached on the file's mtime, so the common path costs one stat."""
+ cfg = self.root / ".git" / "config"
+ mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0
+ if mtime == self._cfg_mtime:
+ return
+ names = self._git("config", "--local", "--list", "--name-only", check=False).stdout.split()
+ for name in {n for n in names if n.split(".", 1)[0] in _GIT_EXEC_SECTIONS or n in _GIT_EXEC_KEYS}:
+ self._git("config", "--local", "--unset-all", name, check=False)
+ self._cfg_mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0
+
def _git_init(self) -> None:
if (self.root / ".git").exists():
+ self._sanitise_git_config() # a resumed run: the agent has had the repo since
return
self._git("init", "-q")
self.ensure_gitignore()
@@ -325,6 +358,7 @@ class Workspace:
def commit(self, message: str) -> str:
"""Commit everything tracked (src/, public/, plan, ...) and return the sha."""
+ self._sanitise_git_config()
self._git("add", "-A")
self._git("commit", "-q", "-m", message, "--allow-empty")
return self._git("rev-parse", "HEAD").stdout.strip()
@@ -341,6 +375,7 @@ class Workspace:
def changed_files(self, since: str | None = None) -> list[FileChange]:
"""Files changed vs ``since`` (a commit) or vs HEAD (uncommitted work)."""
+ self._sanitise_git_config() # `add`/`diff` apply clean + textconv drivers
self._git("add", "-A", "-N") # register untracked so they show up in diff
args = ["diff", "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])
out = self._git(*args).stdout
@@ -387,6 +422,7 @@ class Workspace:
self._git("checkout", "-q", commit, "--", *paths)
def diff(self, a: str, b: str = "HEAD") -> str:
+ self._sanitise_git_config()
return self._git("diff", a, b, "--", "src", "public").stdout
def snapshot_src(self, dest: Path) -> None:
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index d5d4679f..7c8e4de1 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -372,16 +372,19 @@ npm i -g @openai/codex # codex (0.149.0 here)
own `login` flows) — test lightly. The harness handles the per-CLI quirks for
you; the ones worth knowing:
-* **gemini-cli** — the harness writes a *system settings* file to
- `~/.cache/codeverse/gemini_cli_settings.json` and passes it via
- `GEMINI_CLI_SYSTEM_SETTINGS_PATH`, forcing three things (do not undo them):
+* **gemini-cli** — the harness writes a *system settings* file per session into that
+ session's `trajectories/<label>_rNN/` dir and passes it via
+ `GEMINI_CLI_SYSTEM_SETTINGS_PATH`, forcing four things (do not undo them):
`security.auth.selectedType = "gemini-api-key"` (a pool key is injected as
`GEMINI_API_KEY`, other credential env is stripped),
`experimental.dynamicModelConfiguration = true` — without it an unknown model
id is *silently substituted* and the run is flagged
`exit_reason=model_substituted` — and `security.folderTrust.enabled = false`,
without which the workspace MCP servers are silently ignored even with
- `--skip-trust`, so the agent loses every spatial tool. A pre-existing OAuth
+ `--skip-trust`, so the agent loses every spatial tool. It also carries the `3dcv`
+ MCP server itself plus `mcp.allowed = ["3dcv"]`: this file is merged LAST and
+ `mcp.allowed` replaces, so a server the agent plants in the workspace's own
+ `.gemini/settings.json` is Blocked. A pre-existing OAuth
login of your own is overridden, not consumed.
* **codex** — MCP tools need `default_tools_approval_mode="approve"`, which the
harness passes on the command line.
@@ -564,7 +567,7 @@ rm -rf harness/3dcodeverse.egg-info harness/.pytest_cache harness/.ruff_cache
`~/.cache/codeverse` (or `cache_dir` / `CV3D_CACHE_DIR`) holds only regenerable
things: `renders/` and `judge_images/` (render + montage cache), `textures/` and
`texture_plans/` (texture-pass cache — deleting these costs real money to
-regenerate), `gpu_probe.json`, `gemini_cli_settings.json`, `browser_*.lock` (the shared
+regenerate), `gpu_probe.json`, `browser_*.lock` (the shared
headless-Chrome endpoint file — do not delete it while renders are running).
**Your data is not in either cache.** `runs/`, `bench/out/` and any exported
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index a0931e8f..54140eab 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -148,8 +148,9 @@ from codeverse.agents.materialize import materialize_workspace, Materialized, co
materialize_workspace(ws, *, agent_kind, contract_md, cookbook_rel, spatial_tools, mcp_command) -> Materialized
# writes AGENTS.md + GEMINI.md + CLAUDE.md (same body), ws/.3dcv/cookbook.md (Δ copied in: gemini-cli cannot read
# outside the workspace), .geminiignore/.aiexclude, and MCP wiring:
-# gemini-cli → ws/.gemini/settings.json {"mcpServers": {"3dcv": {...}}} + context.fileFiltering.respectGitIgnore=false
-# claude-code → ws/.mcp.json codex → Materialized.codex_overrides:
+# gemini-cli → ws/.gemini/settings.json only gets context.fileFiltering.respectGitIgnore=false; the 3dcv server
+# and mcp.allowed live in the per-session system settings (Δ that file is agent-writable — audit 2026-08-27)
+# claude-code → trajectories/<label>_rNN/mcp.json codex → Materialized.codex_overrides:
# -c mcp_servers.3dcv.command=… -c mcp_servers.3dcv.args=[…] -c mcp_servers.3dcv.default_tools_approval_mode="approve"
# (Δ without the approval mode every MCP tool call is elicited and auto-cancelled)
# agy → no per-workspace MCP; body documents `3dcv tools <name> --json … --workspace .` as the fallback
@@ -177,9 +178,10 @@ stderr.log, result.json}`; **Δ** a re-run of the same label+round lands in
`<label>.a2_rNN` (then `.a3` …) — the first attempt is never overwritten; `result.json`
records `attempt` + `job_label`. Each run makes two git commits (`pre:`/`agent:<label>`).
gemini-cli specifics: system settings file via `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
-(api-key auth, `dynamicModelConfiguration=true` else silent model substitution →
-`exit_reason="model_substituted"`, `folderTrust.enabled=false` else workspace MCP
-silently dropped). **Δ** `Usage.input_tokens` = `tokens.prompt` (TOTAL prompt incl.
+(written per session into the trajectory dir: api-key auth, `dynamicModelConfiguration=true`
+else silent model substitution → `exit_reason="model_substituted"`, `folderTrust.enabled=false`
+else workspace MCP silently dropped, plus `mcpServers.3dcv` + `mcp.allowed=["3dcv"]` — **Δ** it is
+applied LAST and `mcp.allowed` replaces, so an agent-planted server in ws/.gemini/settings.json is Blocked). **Δ** `Usage.input_tokens` = `tokens.prompt` (TOTAL prompt incl.
cached; `tokens.input` is the uncached count) and each served model is priced at its
own rate. KeyPoolExhausted never escapes `run()` (→ `exit_reason=budget`); retries
prefer a different key (10 s wait) before re-using the same one.
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index 8f5faa9f..ea61803b 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -77,7 +77,7 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60 --max-u
| `api-agent:gemini:gemini-3.7-flash` (default) | in-process tool loop with file tools + every spatial tool | cheapest agentic path; the only backend whose transcripts feed repair-pair mining |
| `single-shot:gemini:gemini-3.7-flash` | one structured-output call → multi-file envelope, no tools | fastest/cheapest; baseline for "raw model" deltas |
| `gemini-cli:gemini-3.7-flash` | `gemini -p … --approval-mode yolo --skip-trust --output-format json` | see gotchas below |
-| `claude-code:<model>` | `claude -p … --dangerously-skip-permissions --mcp-config ws/.mcp.json …` | local subscription — test lightly |
+| `claude-code:<model>` | `claude -p … --dangerously-skip-permissions --mcp-config trajectories/<label>_rNN/mcp.json --strict-mcp-config …` | local subscription — test lightly |
| `codex:<model>[@<effort>]` | `codex exec --json -C ws --sandbox workspace-write -c model_reasoning_effort=high … -c mcp_servers.3dcv.…` | subscription; MCP tools need `default_tools_approval_mode="approve"` (harness passes it); reasoning effort is always stated (`Settings.agents.codex_reasoning_effort`, default `high`; `codex:gpt-5.6-sol@medium` per id, `""` to defer to `~/.codex/config.toml`) |
| `agy:<model>` | `agy --print … --add-dir ws` | no per-workspace MCP: tools via `3dcv tools <name> --json … --workspace .`; no served-model or cost reporting |
| `gemini:* / anthropic:* / openai:*` | ChatModel for planner / judge / captioner / single-shot | Anthropic/OpenAI untested live here |
diff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.md
index 8e895c5f..bed4b2e3 100644
--- a/harness/docs/RUN_LAYOUT.md
+++ b/harness/docs/RUN_LAYOUT.md
@@ -28,7 +28,7 @@ runs/<slug>/
stages -> ../stages
trajectories -> ../trajectories
stages/ rounds/ trajectories/ physical homes (unchanged)
- _assets/ _cand/ AGENTS.md GEMINI.md CLAUDE.md .mcp.json …
+ _assets/ _cand/ AGENTS.md GEMINI.md CLAUDE.md .gemini/settings.json …
```
## Why the aliases point that way
diff --git a/harness/runtime_js/lib/host_env.mjs b/harness/runtime_js/lib/host_env.mjs
index c5a6b79f..e570436c 100644
--- a/harness/runtime_js/lib/host_env.mjs
+++ b/harness/runtime_js/lib/host_env.mjs
@@ -56,8 +56,13 @@ export function importMapHtml() {
export async function serveWorkspace(wsRoot, { hostHtml = '' } = {}) {
wsRoot = path.resolve(wsRoot);
const srv = await serve.serveDirs({
- root: wsRoot,
- mounts: { '/assets/': path.join(wsRoot, 'public', 'assets') },
+ // explicit mounts, no `root`: the workspace root also holds spec.json, run_state.json,
+ // events.jsonl, .git/ and artifacts/ — generated scene code must not be able to GET them.
+ mounts: {
+ '/src/': path.join(wsRoot, 'src'),
+ '/public/': path.join(wsRoot, 'public'),
+ '/assets/': path.join(wsRoot, 'public', 'assets'),
+ },
routes: { '/__host.html': { body: hostHtml, type: 'text/html; charset=utf-8' } },
});
return { server: srv.server, base: srv.base, close: srv.close };
diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.py
index b9ae8f29..c665f87a 100644
--- a/harness/tests/agents/test_cli_write_scope.py
+++ b/harness/tests/agents/test_cli_write_scope.py
@@ -4,8 +4,9 @@ CLI backends (claude-code / codex / gemini-cli / agy) have no write-time file ga
``FileTools`` guards only the in-process api-agent — and both session snapshots run
``git add -A``, so two concurrent CLI sessions in one workspace make provenance (and
any per-path rollback) unfixable. ``begin_session`` therefore serialises
-``EXCLUSIVE_KINDS`` per workspace, and ``finish_session`` restores an ``edit_only``
-session's out-of-scope writes to its own ``pre:`` commit and fails the session.
+``EXCLUSIVE_KINDS`` per workspace, and ``finish_session`` reverts writes outside
+``job.write_roots`` (always) and outside ``files_hint`` (``edit_only``) to the session's
+own ``pre:`` commit and fails the session.
"""
from __future__ import annotations
@@ -103,6 +104,28 @@ def test_out_of_scope_cli_write_is_restored_and_fails_the_session(tmp_ws: Worksp
assert sorted(f.path for f in res.files_changed) == ["src/parts/bolt.py", "src/parts/seat.py"]
+def test_write_roots_are_enforced_without_edit_only(tmp_ws: Workspace):
+ """``write_roots`` was enforced for the api-agent (api_tools) and single-shot but NOT
+ for CLI agents: ``_enforce_scope`` returned early unless edit_only+files_hint, so a
+ plain codex session wrote and COMMITTED root-level evil.py / conftest.py and
+ ``attribute_changes`` then hid them from files_changed (audit 2026-08-27)."""
+ ws = _scoped_ws(tmp_ws)
+ (ws.root / "notes.md").write_text("original\n")
+ s = begin_session(_job(ws, "baseline"), "codex") # edit_only=False, write_roots=["src", "public"]
+ (ws.src / "parts" / "leg.py").write_text("# in scope\n")
+ (ws.root / "evil.py").write_text("import os\n") # added outside write_roots → deleted
+ (ws.root / "conftest.py").write_text("# hook\n") # added outside write_roots → deleted
+ (ws.root / "notes.md").write_text("tampered\n") # modified outside write_roots → restored
+ res = _finish(s)
+ assert not res.ok, "an out-of-scope write must fail the session"
+ assert not (ws.root / "evil.py").exists() and not (ws.root / "conftest.py").exists()
+ assert (ws.root / "notes.md").read_text() == "original\n"
+ assert "evil.py" not in ws._git("ls-files").stdout, "and it must never be committed"
+ assert any("evil.py" in e and "conftest.py" in e for e in res.errors), res.errors
+ assert (ws.src / "parts" / "leg.py").read_text() == "# in scope\n", "in-scope work is kept"
+ assert [f.path for f in res.files_changed] == ["src/parts/leg.py"]
+
+
def test_entry_file_writes_need_ownership(tmp_ws: Workspace):
ws = _scoped_ws(tmp_ws)
job = _job(ws, "part", edit_only=True, files_hint=["src/parts/seat.py"])
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index 56d8529d..490d455d 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -22,7 +22,7 @@ assert "GEMINI_API_KEYS" not in os.environ
assert "FAKE_SERVICE_API_KEY" not in os.environ, "secret leaked"
assert os.path.isfile(os.environ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
if mode in ("fail_once", "fail_once_503", "fail_always"):
- marker = "attempts.txt"
+ marker = "artifacts/attempts.txt"
n = int(open(marker).read()) if os.path.exists(marker) else 0
open(marker, "w").write(str(n + 1))
if n == 0 or mode == "fail_always":
@@ -74,6 +74,36 @@ def test_success_path(tmp_ws: Workspace, agent: GeminiCliAgent):
assert "agent:t" in tmp_ws._git("log", "--oneline").stdout
+def test_agent_planted_mcp_server_never_reaches_the_cli(tmp_ws: Workspace, agent: GeminiCliAgent):
+ """``ws/.gemini/settings.json`` is agent-writable and gemini-cli merged its mcpServers,
+ so an agent could choose what the NEXT round's CLI launched (`gemini mcp list` in a
+ poisoned workspace tried to start it). 3dcv + ``mcp.allowed`` now live in the
+ per-session system settings, which is applied LAST and whose ``mcp.allowed``
+ REPLACES rather than merges (audit 2026-08-27)."""
+ from codeverse.agents.cli_common import begin_session, default_mcp_command, release_session
+ from codeverse.agents.materialize import materialize_workspace
+
+ materialize_workspace(tmp_ws, agent_kind="gemini-cli", contract_md="c", cookbook_rel="",
+ spatial_tools=True, mcp_command=default_mcp_command(tmp_ws))
+ planted = tmp_ws.root / ".gemini" / "settings.json"
+ data = json.loads(planted.read_text())
+ data["mcpServers"] = {"evil": {"command": "/tmp/evil"}}
+ data["mcp"] = {"allowed": ["evil"]}
+ planted.write_text(json.dumps(data))
+
+ s = begin_session(_job(tmp_ws), "gemini-cli")
+ try:
+ env = agent.build_env(s, "k1")
+ finally:
+ release_session(s)
+ path = Path(env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
+ settings = json.loads(path.read_text())
+ assert path.parent == s.traj.dir, "per session, in the harness-owned trajectory dir"
+ assert list(settings["mcpServers"]) == ["3dcv"] and settings["mcp"]["allowed"] == ["3dcv"]
+ assert "evil" not in json.dumps(settings)
+ assert settings["security"]["folderTrust"]["enabled"] is False
+
+
def test_model_substitution_detected(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
monkeypatch.setenv("FAKE_MODE", "substitute")
res = agent.run(_job(tmp_ws))
@@ -85,7 +115,7 @@ def test_transient_failure_retries_once_with_other_key(tmp_ws: Workspace, agent:
monkeypatch.setenv("FAKE_MODE", "fail_once")
res = agent.run(_job(tmp_ws))
assert res.ok, res.errors
- assert (tmp_ws.root / "attempts.txt").read_text() == "2"
+ assert (tmp_ws.artifacts / "attempts.txt").read_text() == "2"
rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
assert rec["attempts"] == 2 and (Path(res.transcript_path).parent / "stdout.2.json").exists()
lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
@@ -102,7 +132,7 @@ def test_single_key_transient_failure_retries_same_key_and_never_raises(tmp_ws:
monkeypatch.setenv("FAKE_MODE", "fail_once_503")
res = agent.run(_job(tmp_ws))
assert res.ok, res.errors
- assert (tmp_ws.root / "attempts.txt").read_text() == "2"
+ assert (tmp_ws.artifacts / "attempts.txt").read_text() == "2"
lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
assert [ln["key_tail"] for ln in lines if ln["kind"] == "invoke"] == ["only", "only"]
@@ -117,7 +147,7 @@ def test_single_key_quota_failure_returns_budget_without_retry(tmp_ws: Workspace
monkeypatch.setenv("FAKE_MODE", "fail_always")
res = agent.run(_job(tmp_ws))
assert not res.ok and res.exit_reason == "budget"
- assert (tmp_ws.root / "attempts.txt").read_text() == "1"
+ assert (tmp_ws.artifacts / "attempts.txt").read_text() == "1"
rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
assert rec["attempts"] == 1 and any("no usable key" in n for n in rec["notes"])
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index 21443380..0e977775 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -30,18 +30,17 @@ def test_writes_three_bodies_same_content(tmp_ws: Workspace):
assert len(res.body_files) == 3
-def test_mcp_configs_written_and_merged(tmp_ws: Workspace):
+def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):
+ """Only the ``context`` block goes into the agent-writable ws/.gemini/settings.json;
+ 3dcv reaches each CLI through a harness-owned per-session file (audit 2026-08-27)."""
gs = tmp_ws.root / ".gemini" / "settings.json"
gs.parent.mkdir(parents=True)
- gs.write_text(json.dumps({"mcpServers": {"other": {"command": "x"}}, "ui": {"theme": "dark"}}))
+ gs.write_text(json.dumps({"mcpServers": {"3dcv": {"command": "/tmp/evil"}}, "ui": {"theme": "dark"}}))
res = _mat(tmp_ws)
data = json.loads(gs.read_text())
- assert data["ui"]["theme"] == "dark" and "other" in data["mcpServers"]
- server = data["mcpServers"]["3dcv"]
- assert server["command"] == default_mcp_command(tmp_ws)[0]
- assert server["args"][:2] == ["-m", "codeverse.spatial.mcp_server"] and server["timeout"] == 600000
- mcp = json.loads((tmp_ws.root / ".mcp.json").read_text())
- assert mcp["mcpServers"]["3dcv"]["type"] == "stdio"
+ assert data["ui"]["theme"] == "dark"
+ assert "3dcv" not in data["mcpServers"], "an agent-planted 3dcv impostor must be dropped"
+ assert not (tmp_ws.root / ".mcp.json").exists(), "claude-code writes its own per-session mcp.json"
assert res.codex_overrides[1].startswith("mcp_servers.3dcv.command=")
assert "mcp_servers.3dcv.args=[" in res.codex_overrides[3]
assert "global" in res.agy_mcp.lower()
@@ -82,8 +81,8 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
def test_spatial_disabled_drops_server_and_documents_absence(tmp_ws: Workspace):
_mat(tmp_ws)
res = _mat(tmp_ws, spatial=False)
- assert res.mcp_files == []
- assert "3dcv" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text())["mcpServers"]
+ assert res.codex_overrides == []
+ assert "3dcv" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text()).get("mcpServers", {})
assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index 297888fc..db2688ba 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -197,6 +197,38 @@ def test_a_stale_index_lock_names_the_remedy(tmp_path):
assert "index.lock" in (ei.value.stderr or "")
+def test_a_planted_git_hook_or_filter_never_runs_on_a_commit(tmp_path):
+ """The workspace is agent-writable, and ``_git`` used to set HOME=<ws> — so
+ ws/.gitconfig WAS git's global config. Four repro-confirmed vectors executed with
+ harness privileges on ws.commit(): .git/hooks/pre-commit, a global core.hooksPath, a
+ global filter.*.clean + .gitattributes, and a LOCAL filter.*.clean (audit 2026-08-27)."""
+ ws = Workspace(tmp_path / "run").create()
+ fired = tmp_path / "fired"
+ shell = f"#!/bin/sh\necho x >> {fired}\n"
+ for d in (ws.root / ".git" / "hooks", ws.root / "evilhooks"):
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "pre-commit").write_text(shell)
+ (d / "pre-commit").chmod(0o755)
+ (ws.root / ".gitconfig").write_text(
+ f'[core]\n\thooksPath = {ws.root / "evilhooks"}\n'
+ f'[filter "pwn"]\n\tclean = sh -c \'echo g >> {fired}; cat\'\n')
+ (ws.root / ".gitattributes").write_text("*.py filter=pwn\n")
+ ws._git("config", "--local", "filter.pwn.clean", f"sh -c 'echo l >> {fired}; cat'")
+
+ (ws.src / "model.py").write_text("x = 1\n")
+ ws.commit("round 0")
+
+ assert not fired.exists(), f"a planted git hook/filter ran: {fired.read_text()!r}"
+ assert ws._git("config", "--local", "--get", "filter.pwn.clean", check=False).returncode != 0, \
+ "an exec-capable local key must be unset before the commit"
+
+ # finish_session reaches git through changed_files() (git add / git diff) BEFORE it commits
+ ws._git("config", "--local", "filter.pwn.clean", f"sh -c 'echo c >> {fired}; cat'")
+ (ws.src / "model.py").write_text("x = 2\n")
+ ws.changed_files()
+ assert not fired.exists(), f"a planted filter ran during changed_files(): {fired.read_text()!r}"
+
+
def test_show_itself_prints_the_relocated_sheet_not_the_stored_one(tmp_path):
"""Sign-off follow-up to SMOKE2. The reported command was `3dcv show`, but the fix
landed in ``cli/_fmt.py`` (which backs `3dcv status`) — ``cli/layout_cmd.py``'s
diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.py
index d45af58e..61f304bc 100644
--- a/harness/tests/threejs_render/test_runtime_js.py
+++ b/harness/tests/threejs_render/test_runtime_js.py
@@ -201,6 +201,35 @@ const {{ serveDirs }} = require({json.dumps(str(runtime_js_dir() / 'serve.cjs'))
assert out == {"ok": 200, "inside": 200, "leak": 404, "dirleak": 404}
+def test_scene_server_only_mounts_src_public_assets(tmp_path: Path):
+ """serveWorkspace used to pass ``root: wsRoot``, so generated scene code could GET
+ /spec.json, /run_state.json, /events.jsonl, /.git/config and /artifacts/** — a scene
+ could read the previous round's judge output (audit 2026-08-27)."""
+ ws = Workspace(tmp_path / "run").create()
+ (ws.src / "scene.js").write_text("export function createScene() {}\n")
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ (ws.public / "assets" / "a.glb").write_bytes(b"glTF1234")
+ (ws.public / "page.txt").write_text("public")
+ for name in ("spec.json", "run_state.json", "events.jsonl"):
+ (ws.root / name).write_text("{}\n")
+ (ws.artifacts / "judge").mkdir(parents=True, exist_ok=True)
+ (ws.artifacts / "judge" / "r00.json").write_text('{"score": 1}')
+ serve = ('/src/scene.js', '/public/page.txt', '/assets/a.glb', '/__host.html')
+ denied = ('/spec.json', '/run_state.json', '/events.jsonl', '/.git/config', '/artifacts/judge/r00.json')
+ script = tmp_path / "s.mjs"
+ script.write_text(f"""
+import {{ serveWorkspace }} from {json.dumps(str(runtime_js_dir() / 'lib' / 'host_env.mjs'))};
+const srv = await serveWorkspace({json.dumps(str(ws.root))}, {{ hostHtml: '<html>host</html>' }});
+const out = {{}};
+for (const p of {json.dumps([*serve, *denied])}) out[p] = (await fetch(srv.base + p)).status;
+await srv.close();
+console.log(JSON.stringify(out));
+""")
+ out = run_node(script, [], timeout_s=60).last_json
+ assert [out[p] for p in serve] == [200] * len(serve), out
+ assert [out[p] for p in denied] == [404] * len(denied), out
+
+
def test_cli_safe_name_rejects_path_tricks(tmp_path: Path):
"""lib/cli.mjs safeName guards every filename composed from a camera/view name."""
script = tmp_path / "n.mjs"