Skip to content

Official Codebase of 3DCodeVerse

Python

tracks/agents: enforce the write scopes the planner already draws

gaoypeng10ebefb0aed6
diff --git a/harness/codeverse/agents/antigravity.py b/harness/codeverse/agents/antigravity.py
index 67ad6829..7b06adfb 100644
--- a/harness/codeverse/agents/antigravity.py
+++ b/harness/codeverse/agents/antigravity.py
@@ -33,6 +33,7 @@ from codeverse.agents.cli_common import (
finish_session,
hardened_env,
invoke,
+ release_session,
tail,
watchdog_error,
)
@@ -157,36 +158,39 @@ class AntigravityAgent:
def run(self, job: AgentJob) -> AgentResult:
ok, why = self.available()
s = begin_session(job, self.kind)
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, _compose_prompt(s))
- proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
- env = parse_agy_json(proc.stdout)
- served = self.served_model()
- usage = usage_from_agy(env, served) if env else Usage(backend=self.kind, model=served)
- usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
- text = str(env.get("response", "")) if env else proc.stdout.strip()
- errors: list[str] = []
- if env is None:
- s.notes.append("no JSON envelope from agy; usage unknown (zeros), response taken from plain stdout")
- s.notes.append("agy is subscription-billed: cost_usd=0")
- if proc.timed_out:
- ok, reason = False, "timeout"
- errors.append(watchdog_error(proc))
- elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
- ok, reason = False, "error"
- errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
- f"stderr tail: {tail(proc.stderr, 1500)}")
- elif not text.strip():
- ok, reason = False, "error"
- errors.append("empty response")
- else:
- ok, reason = True, "completed"
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,
- rc=proc.rc, killed_reason=proc.killed_reason,
- conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
- )
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt(s))
+ proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
+ env = parse_agy_json(proc.stdout)
+ served = self.served_model()
+ usage = usage_from_agy(env, served) if env else Usage(backend=self.kind, model=served)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str(env.get("response", "")) if env else proc.stdout.strip()
+ errors: list[str] = []
+ if env is None:
+ s.notes.append("no JSON envelope from agy; usage unknown (zeros), response taken from plain stdout")
+ s.notes.append("agy is subscription-billed: cost_usd=0")
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(watchdog_error(proc))
+ elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
+ f"stderr tail: {tail(proc.stderr, 1500)}")
+ elif not text.strip():
+ ok, reason = False, "error"
+ errors.append("empty response")
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason,
+ conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
+ )
+ finally:
+ release_session(s)
def _compose_prompt(s: Session) -> str:
diff --git a/harness/codeverse/agents/claude_code.py b/harness/codeverse/agents/claude_code.py
index 0b3e011f..7d2da0cc 100644
--- a/harness/codeverse/agents/claude_code.py
+++ b/harness/codeverse/agents/claude_code.py
@@ -28,6 +28,7 @@ from codeverse.agents.cli_common import (
hardened_env,
invoke,
is_transient_failure,
+ release_session,
tail,
watchdog_error,
)
@@ -150,37 +151,40 @@ class ClaudeCodeAgent:
def run(self, job: AgentJob) -> AgentResult:
ok, why = self.available()
s = begin_session(job, self.kind)
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, job.prompt)
- proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
- env = parse_claude_json(proc.stdout)
- usage = usage_from_envelope(env, self.model) if env else Usage(backend=self.kind, model=self.model)
- usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
- text = str((env or {}).get("result") or "")
- turns = int((env or {}).get("num_turns") or 0)
- errors: list[str] = []
- if proc.timed_out:
- reason, ok = "timeout", False
- errors.append(watchdog_error(proc))
- elif env is None or proc.rc != 0:
- reason, ok = "error", False
- errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
- if is_transient_failure(proc.stderr, proc.stdout):
- reason = "budget" if "rate" in proc.stderr.lower() else "error"
- elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
- ok = False
- sub = str(env.get("subtype", ""))
- reason = "budget" if "max_turns" in sub else "error"
- errors.append(f"claude reported {sub or 'is_error'}: {tail(text, 800)}")
- else:
- reason, ok = "completed", True
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),
- errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,
- session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
- model_usage=(env or {}).get("modelUsage", {}),
- )
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, job.prompt)
+ proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
+ env = parse_claude_json(proc.stdout)
+ usage = usage_from_envelope(env, self.model) if env else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str((env or {}).get("result") or "")
+ turns = int((env or {}).get("num_turns") or 0)
+ errors: list[str] = []
+ if proc.timed_out:
+ reason, ok = "timeout", False
+ errors.append(watchdog_error(proc))
+ elif env is None or proc.rc != 0:
+ reason, ok = "error", False
+ errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
+ if is_transient_failure(proc.stderr, proc.stdout):
+ reason = "budget" if "rate" in proc.stderr.lower() else "error"
+ elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
+ ok = False
+ sub = str(env.get("subtype", ""))
+ reason = "budget" if "max_turns" in sub else "error"
+ errors.append(f"claude reported {sub or 'is_error'}: {tail(text, 800)}")
+ else:
+ reason, ok = "completed", True
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),
+ errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,
+ session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
+ model_usage=(env or {}).get("modelUsage", {}),
+ )
+ finally:
+ release_session(s)
__all__ = ["ClaudeCodeAgent", "parse_claude_json", "primary_served_model", "usage_from_envelope", "ALLOWED_TOOLS"]
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index 53e70698..de4dac4c 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -181,6 +181,38 @@ class Session:
attempt: int = 1
files_hint: frozenset[str] = frozenset()
live: _LiveSession | None = None
+ ws_lock: threading.RLock | None = None
+
+
+# --------------------------------------------------------------------------- serialisation
+#: agent kinds whose sessions are EXCLUSIVE per workspace. CLI agents have no
+#: write-time enforcement (FileTools guards only the in-process api-agent), and both
+#: session snapshots run ``git add -A`` — a late-starting session's ``pre:`` commit
+#: absorbs a sibling's in-flight writes, which makes concurrent provenance (and any
+#: per-path rollback, see :func:`_enforce_scope`) unfixable after the fact. So CLI
+#: sessions on one workspace are serialised; the main generator (api-agent) keeps its
+#: full parallelism because its writes are scope-checked as they happen.
+EXCLUSIVE_KINDS = frozenset({"claude-code", "codex", "gemini-cli", "agy"})
+
+_WS_SESSION_LOCKS: dict[str, threading.RLock] = {}
+_WS_SESSION_LOCKS_GUARD = threading.Lock()
+
+
+def _session_lock(ws: Workspace) -> threading.RLock:
+ """One re-entrant lock per workspace root. Re-entrant so a thread that begins a
+ session it never finishes (argv-building tests do) cannot deadlock itself; real
+ sessions begin, finish and release on their own worker thread."""
+ with _WS_SESSION_LOCKS_GUARD:
+ return _WS_SESSION_LOCKS.setdefault(str(ws.root), threading.RLock())
+
+
+def release_session(s: Session) -> None:
+ """Release ``s``'s workspace lock (idempotent). ``finish_session`` always calls it;
+ the CLI backends also call it in a ``finally`` so a session that crashes between
+ begin and finish cannot starve every later session on the same workspace."""
+ lock, s.ws_lock = s.ws_lock, None
+ if lock is not None:
+ lock.release()
def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, int]:
@@ -194,7 +226,11 @@ def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, in
def begin_session(job: AgentJob, kind: str) -> Session:
- """Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``)."""
+ """Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``).
+
+ For :data:`EXCLUSIVE_KINDS` the per-workspace session lock is taken BEFORE the
+ ``pre:`` commit and held until ``finish_session`` releases it — see the constant's
+ comment for why concurrent CLI sessions in one workspace are unfixable."""
ws = Workspace(job.workspace)
if not ws.root.is_dir():
raise FileNotFoundError(f"workspace does not exist: {ws.root}")
@@ -205,10 +241,45 @@ def begin_session(job: AgentJob, kind: str) -> Session:
traj = Trajectory(ws.trajectory_dir(label, round_index))
traj.write_prompt(job.prompt, job.system_append)
hints = frozenset(h for h in (str(x).strip() for x in job.files_hint) if h)
- live = _register(ws, label, hints)
- head_before = ws.commit(f"pre:{label}")
+ lock = _session_lock(ws) if kind in EXCLUSIVE_KINDS else None
+ if lock is not None:
+ lock.acquire()
+ try:
+ live = _register(ws, label, hints)
+ head_before = ws.commit(f"pre:{label}")
+ except BaseException:
+ if lock is not None:
+ lock.release()
+ raise
return Session(ws=ws, job=job, kind=kind, label=label, round_index=round_index,
- traj=traj, head_before=head_before, attempt=attempt, files_hint=hints, live=live)
+ traj=traj, head_before=head_before, attempt=attempt, files_hint=hints,
+ live=live, ws_lock=lock)
+
+
+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):
+ 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] = []
+ 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):
+ continue
+ out.append(f.path)
+ if out:
+ s.ws.restore_paths(s.head_before, out)
+ return out
def finish_session(
@@ -223,20 +294,36 @@ def finish_session(
**extra: Any,
) -> AgentResult:
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
- session — see :func:`attribute_changes`), write result.json."""
- s.ws.commit(f"agent:{s.label}")
- siblings = _sibling_hints(s.ws, s.live) if s.live is not None else frozenset()
- files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,
- own_hints=s.files_hint, sibling_hints=siblings)
- res = AgentResult(
- ok=ok, exit_reason=exit_reason, text=text, files_changed=files,
- transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
- usage=usage, duration_s=round(time.monotonic() - s.t0, 3), tool_calls=tool_calls,
- errors=list(errors or []),
- )
- s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,
- head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
- return res
+ 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`)."""
+ 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)")
+ errors.append(msg)
+ s.notes.append(msg)
+ s.ws.commit(f"agent:{s.label}")
+ siblings = _sibling_hints(s.ws, s.live) if s.live is not None else frozenset()
+ files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,
+ own_hints=s.files_hint, sibling_hints=siblings)
+ res = AgentResult(
+ ok=ok, exit_reason=exit_reason, text=text, files_changed=files,
+ transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
+ usage=usage, duration_s=round(time.monotonic() - s.t0, 3), tool_calls=tool_calls,
+ errors=errors,
+ )
+ s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,
+ head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
+ return res
+ finally:
+ release_session(s)
def failed(s: Session, reason: str, message: str, usage: Usage | None = None) -> AgentResult:
diff --git a/harness/codeverse/agents/codex.py b/harness/codeverse/agents/codex.py
index 0a8db957..f455183d 100644
--- a/harness/codeverse/agents/codex.py
+++ b/harness/codeverse/agents/codex.py
@@ -27,6 +27,7 @@ from codeverse.agents.cli_common import (
hardened_env,
invoke,
mcp_command_for,
+ release_session,
tail,
watchdog_error,
)
@@ -164,33 +165,36 @@ class CodexAgent:
def run(self, job: AgentJob) -> AgentResult:
ok, why = self.available()
s = begin_session(job, self.kind)
- if not ok:
- return failed(s, "error", why)
- prompt = _compose_prompt(job)
- via_stdin = len(prompt.encode("utf-8")) > STDIN_PROMPT_BYTES
- argv = self.build_argv(s, None if via_stdin else prompt)
- events = CodexEvents()
- proc = invoke(s, argv, self.build_env(s), prompt=prompt, stdout_name="stdout.jsonl",
- on_stdout=events.feed, stdin=prompt if via_stdin else None)
- usage = events.usage(self.model)
- usage.latency_ms = int(proc.duration_s * 1000)
- text = "\n\n".join(m for m in events.messages if m.strip())
- errors = list(events.errors)
- if proc.timed_out:
- ok, reason = False, "timeout"
- errors.append(watchdog_error(proc))
- elif proc.rc != 0 or events.n_events == 0:
- ok, reason = False, "error"
- errors.append(f"rc={proc.rc}; events={events.n_events}; stderr tail: {tail(proc.stderr, 1500)}")
- elif events.errors and events.turns_completed == 0:
- ok, reason = False, "error"
- else:
- ok, reason = True, "completed"
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,
- rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
- turns_completed=events.turns_completed, usage_raw=events.usage_raw,
- )
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = _compose_prompt(job)
+ via_stdin = len(prompt.encode("utf-8")) > STDIN_PROMPT_BYTES
+ argv = self.build_argv(s, None if via_stdin else prompt)
+ events = CodexEvents()
+ proc = invoke(s, argv, self.build_env(s), prompt=prompt, stdout_name="stdout.jsonl",
+ on_stdout=events.feed, stdin=prompt if via_stdin else None)
+ usage = events.usage(self.model)
+ usage.latency_ms = int(proc.duration_s * 1000)
+ text = "\n\n".join(m for m in events.messages if m.strip())
+ errors = list(events.errors)
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(watchdog_error(proc))
+ elif proc.rc != 0 or events.n_events == 0:
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; events={events.n_events}; stderr tail: {tail(proc.stderr, 1500)}")
+ elif events.errors and events.turns_completed == 0:
+ ok, reason = False, "error"
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
+ turns_completed=events.turns_completed, usage_raw=events.usage_raw,
+ )
+ finally:
+ release_session(s)
def _compose_prompt(job: AgentJob) -> str:
diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.py
index 1879e1c9..d5cb41d0 100644
--- a/harness/codeverse/agents/gemini_cli.py
+++ b/harness/codeverse/agents/gemini_cli.py
@@ -36,6 +36,7 @@ from codeverse.agents.cli_common import (
invoke,
is_quota_failure,
is_transient_failure,
+ release_session,
tail,
watchdog_error,
)
@@ -178,41 +179,44 @@ class GeminiCliAgent:
def run(self, job: AgentJob) -> AgentResult:
ok, why = self.available()
s = begin_session(job, self.kind)
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, _compose_prompt(job))
- pool = _key_pool(get_settings().gemini_api_keys)
try:
- key = pool.acquire()
- except KeyPoolExhausted as e: # every key throttled for the whole wait budget
- return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
- attempts = 0
- used: set[str] = set()
- usage_total = Usage(backend=self.kind, model=self.model)
- while True:
- attempts += 1
- used.add(key)
- proc = self._invoke(s, prompt, key, attempt=attempts)
- outcome = self._interpret(s, proc)
- usage_total = usage_total + outcome["usage"]
- pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
- pool.release() # one acquire per attempt: keep the pool's in-flight gauge honest
- if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
- break
- next_key = _retry_key(pool, used)
- if next_key is None:
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")
- break
- key = next_key
- how = "rotated key" if key not in used else "same key (no alternative available)"
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")
- s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
- usage_total.cost_usd = round(usage_total.cost_usd, 6)
- return finish_session(
- s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],
- usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],
- attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.get("session_id", ""),
- )
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt(job))
+ pool = _key_pool(get_settings().gemini_api_keys)
+ try:
+ key = pool.acquire()
+ except KeyPoolExhausted as e: # every key throttled for the whole wait budget
+ return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
+ attempts = 0
+ used: set[str] = set()
+ usage_total = Usage(backend=self.kind, model=self.model)
+ while True:
+ attempts += 1
+ used.add(key)
+ proc = self._invoke(s, prompt, key, attempt=attempts)
+ outcome = self._interpret(s, proc)
+ usage_total = usage_total + outcome["usage"]
+ pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
+ pool.release() # one acquire per attempt: keep the pool's in-flight gauge honest
+ if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
+ break
+ next_key = _retry_key(pool, used)
+ if next_key is None:
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")
+ break
+ key = next_key
+ how = "rotated key" if key not in used else "same key (no alternative available)"
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")
+ s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
+ usage_total.cost_usd = round(usage_total.cost_usd, 6)
+ return finish_session(
+ s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],
+ usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],
+ attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.get("session_id", ""),
+ )
+ finally:
+ release_session(s)
def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int) -> CompletedProc:
return invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempt,
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
index da548d3b..9c09fc6a 100644
--- a/harness/codeverse/contracts/agent.py
+++ b/harness/codeverse/contracts/agent.py
@@ -74,7 +74,8 @@ class AgentJob(BaseModel):
)
always_writable: list[str] = Field(
default_factory=list,
- description="files exempt from edit_only (the entry file: adding a part means importing it there)",
+ description="files exempt from edit_only (the entry file, and only when the task OWNS it — "
+ "see GenerationTask.owns_entry: adding a part means importing it there)",
)
read_only: list[str] = Field(
default_factory=list,
diff --git a/harness/codeverse/tracks/envelope.py b/harness/codeverse/tracks/envelope.py
index 94164776..7703f615 100644
--- a/harness/codeverse/tracks/envelope.py
+++ b/harness/codeverse/tracks/envelope.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import logging
import re
-from collections.abc import Callable
+from collections.abc import Callable, Collection
from pathlib import Path
from codeverse.contracts.agent import FileChange
@@ -130,6 +130,7 @@ def write_files(
files: dict[str, str],
*,
allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,
+ only: Collection[str] | None = None,
on_skip: Callable[[str, str], None] | None = None,
) -> list[FileChange]:
"""Write parsed files under the workspace; returns git-style FileChange rows.
@@ -137,7 +138,13 @@ def write_files(
A block whose path is unsafe, outside ``allowed_roots`` (flash models love
to add README.md / package.json despite the format rule) or unwritable is
SKIPPED — reported via ``on_skip`` — instead of aborting the whole write:
- the valid files were already paid for."""
+ the valid files were already paid for.
+
+ ``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a
+ path that ALREADY EXISTS and is not listed — new files stay allowed, mirroring
+ ``FileTools``: the single-shot envelope has no write-time gate, so this is where a
+ scoped task is stopped from rewriting a sibling's file."""
+ scope = {_clean_path(p) for p in only} if only is not None else None
changes: list[FileChange] = []
for raw, content in files.items():
try:
@@ -149,6 +156,12 @@ def write_files(
continue
dest = ws.root / rel
existed = dest.exists()
+ if scope is not None and existed and rel not in scope:
+ reason = f"out of scope: {rel} already exists and is not in this task's file list"
+ if on_skip is not None:
+ on_skip(raw, reason)
+ log.warning("skipping out-of-scope file from generator: %s", rel)
+ continue
try:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content if content.endswith("\n") else content + "\n")
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
index 8b198856..83b1589f 100644
--- a/harness/codeverse/tracks/generation.py
+++ b/harness/codeverse/tracks/generation.py
@@ -137,6 +137,13 @@ class GenerationTask(BaseModel):
default=False,
description="enforce files_hint as the only existing files this session may overwrite",
)
+ owns_entry: bool = Field(
+ default=False,
+ description="this task may write the language entry file even under edit_only (assembly / "
+ "whole-object / single-file tasks, and scoped refines whose prompt promises entry access). "
+ "A task whose files_hint names the entry owns it implicitly; part / zone / detail / asset "
+ "tasks default to False so parallel scoped sessions cannot race on the entry file",
+ )
phase: int = Field(
default=0,
ge=0,
@@ -298,7 +305,8 @@ def generate_files(
if events is not None:
events.emit("generate.skipped_path", label=task.label, path=path, reason=reason[:200])
- changes = write_files(ws, files, allowed_roots=allowed_roots, on_skip=_skip)
+ changes = write_files(ws, files, allowed_roots=allowed_roots,
+ only=_scope_only(ws, task), on_skip=_skip)
if events is not None:
events.emit(
"generate.done",
@@ -396,15 +404,7 @@ def run_agent_task(
# typed job context honoured by every CodingAgent: round → trajectory dir + ToolContext,
# language/track → spatial tool filtering, files_hint → per-session attribution of
# files_changed when tasks run concurrently in ONE workspace (see agents/cli_common).
- language = track = ""
- spec_path = ws.spec_path
- if spec_path.is_file():
- try:
- spec_d = ws.read_json(spec_path)
- language = str(spec_d.get("language", ""))
- track = str(spec_d.get("track", ""))
- except Exception: # noqa: BLE001 — best effort context only
- pass
+ language, track = _spec_lang_track(ws)
# extra mirrors the typed fields until every agent backend reads job.round/… directly
extra: dict[str, Any] = {
"round": task.round,
@@ -429,7 +429,7 @@ def run_agent_task(
files_hint=list(task.files_hint),
extra=extra,
edit_only=task.edit_only,
- always_writable=_always_writable(language),
+ always_writable=_always_writable(language, task),
read_only=_read_only(language),
images=list(task.images),
**({"max_turns": turns_cap} if turns_cap > 0 else {}),
@@ -592,14 +592,40 @@ def session_turns(res: Any) -> int:
return 0
-def _always_writable(language: str) -> list[str]:
- """The entry file is exempt from ``edit_only``: adding a part means importing it there."""
+def _spec_lang_track(ws: Workspace) -> tuple[str, str]:
+ """Best-effort ``(language, track)`` from the workspace's spec.json ("" when absent)."""
+ if not ws.spec_path.is_file():
+ return "", ""
+ try:
+ spec_d = ws.read_json(ws.spec_path)
+ except Exception: # noqa: BLE001 — best effort context only
+ return "", ""
+ return str(spec_d.get("language", "")), str(spec_d.get("track", ""))
+
+
+def _always_writable(language: str, task: GenerationTask) -> list[str]:
+ """The entry file, exempt from ``edit_only`` — but only for a task that OWNS it.
+
+ Owning tasks: ``owns_entry=True`` (assembly / whole-object / single-file tasks, and
+ scoped refines whose prompt promises entry access) or a ``files_hint`` naming the
+ entry. Part / zone / detail / asset tasks own nothing here — under the old
+ unconditional exemption, parallel scoped sessions raced on the entry file unopposed."""
from codeverse.contracts.common import ENTRY_FILE, Language
try:
- return [ENTRY_FILE[Language(language)]]
+ entry = ENTRY_FILE[Language(language)]
except (ValueError, KeyError):
return []
+ return [entry] if task.owns_entry or entry in task.files_hint else []
+
+
+def _scope_only(ws: Workspace, task: GenerationTask) -> set[str] | None:
+ """``write_files``'s scope for an ``edit_only`` single-shot task: the files_hint plus
+ the entry file when the task owns it (the envelope-path mirror of FileTools)."""
+ if not task.edit_only or not task.files_hint:
+ return None
+ language, _ = _spec_lang_track(ws)
+ return {f for f in task.files_hint if f} | set(_always_writable(language, task))
def _read_only(language: str) -> list[str]:
diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.py
index e5fa5845..44aa32d5 100644
--- a/harness/codeverse/tracks/graphics.py
+++ b/harness/codeverse/tracks/graphics.py
@@ -128,7 +128,8 @@ class GraphicsTrack(BaseTrack):
ctx, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
ctx.record_prompt("generate", prompt)
return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
- kind="baseline", temperature=0.6, thinking="medium", images=reference_images(ctx))]
+ kind="baseline", temperature=0.6, thinking="medium", owns_entry=True,
+ images=reference_images(ctx))]
def round_files_hint(self, ctx: RunContext) -> list[str]:
return graphics_expected_files(ctx)
@@ -145,5 +146,5 @@ class GraphicsTrack(BaseTrack):
current_files=current_files(ctx, files) if ctx.single_shot else {}))
ctx.record_prompt("refine", prompt)
return GenerationTask(label="refine", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
- kind="refine", temperature=0.5, thinking="medium",
+ kind="refine", temperature=0.5, thinking="medium", owns_entry=True,
images=reference_images(ctx) + judged_sheet(last))
diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.py
index fe3ffe01..5e440937 100644
--- a/harness/codeverse/tracks/scene.py
+++ b/harness/codeverse/tracks/scene.py
@@ -345,8 +345,10 @@ class SceneTrack(BaseTrack):
"The recipes printed in the first brief apply to every zone in this session.\n")
prompt = header + "\n\n---\n\n".join(briefs)
label = "zones_" + "_".join(to_snake(n) for n in names)
+ # the batch exclusively owns its zone files; env/scene/asset files belong to other sessions
return GenerationTask(label=label, prompt=prompt, system=self.system_prompt(ctx), files_hint=files,
- round=0, kind="zone", temperature=0.5, timeout_s=ctx.budget.timeout_s(ZONE_TIMEOUT_S, floor_s=180))
+ round=0, kind="zone", temperature=0.5, edit_only=True,
+ timeout_s=ctx.budget.timeout_s(ZONE_TIMEOUT_S, floor_s=180))
def _assemble_stage(self, ctx: RunContext) -> dict[str, Any]:
try:
@@ -359,7 +361,7 @@ class SceneTrack(BaseTrack):
prompt = render("tracks/scene_compose.j2", **self._ctx(ctx))
ctx.record_prompt("scene_compose", prompt)
task = GenerationTask(label="compose", prompt=prompt, system=self.system_prompt(ctx), files_hint=["src/scene.js"], round=0,
- kind="compose", temperature=0.4, images=reference_images(ctx))
+ kind="compose", temperature=0.4, owns_entry=True, images=reference_images(ctx))
task = self._deliver_skills(ctx, "compose", [task])[0]
res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
@@ -403,8 +405,9 @@ class SceneTrack(BaseTrack):
judge_summary=judge_digest(last),
current_files=current_files(ctx, files) if ctx.single_shot else {}))
ctx.record_prompt("scene_refine", prompt)
+ # parallel groups are file-disjoint by plan_refine_groups: enforce the split they promised
return GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
- files_hint=files, round=index, kind="refine", temperature=0.4,
+ files_hint=files, round=index, kind="refine", temperature=0.4, edit_only=parallel,
timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.py
index d58b86fc..e8b2a2d7 100644
--- a/harness/codeverse/tracks/scene_assets.py
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -230,7 +230,10 @@ def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: La
system=("You write ONE self-contained three.js ESM asset module. Raw three.js only; no DOM; no texture loading."
if language is Language.SCENE_THREEJS else
"You write ONE raw bpy script (src/model.py) that builds a single scene asset. No SDKs, no render/export calls."),
- files_hint=[rel], round=attempt, kind="asset", temperature=0.5, timeout_s=timeout_s)
+ files_hint=[rel], round=attempt, kind="asset", temperature=0.5, timeout_s=timeout_s,
+ # threejs assets share the scene workspace (a stray write would hit
+ # zones/env); blender heroes own their whole sub-workspace
+ edit_only=language is Language.SCENE_THREEJS)
return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
@@ -364,7 +367,8 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
asset_size=asset.approx_size_m, asset_file=files[0], asset_language=language.value, fix_instructions=instructions,
current_code=_read(ctx.ws, files[0]) if ctx.single_shot else ""))
task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, files_hint=files, round=1, kind="asset_fix",
- temperature=0.4, timeout_s=ctx.budget.timeout_s(ASSET_AGENT_TIMEOUT_S, floor_s=120))
+ temperature=0.4, edit_only=language is Language.SCENE_THREEJS,
+ timeout_s=ctx.budget.timeout_s(ASSET_AGENT_TIMEOUT_S, floor_s=120))
res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
if res.ok:
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
index 0ccf7922..beb86eaa 100644
--- a/harness/codeverse/tracks/static_object.py
+++ b/harness/codeverse/tracks/static_object.py
@@ -259,6 +259,8 @@ class StaticObjectTrack(BaseTrack):
temperature=0.5,
thinking="medium",
images=images,
+ # scope.files is this session's whole world; the entry belongs to assemble
+ edit_only=True,
)
)
entry = self.entry_files(ctx)
@@ -278,6 +280,7 @@ class StaticObjectTrack(BaseTrack):
temperature=0.3,
thinking="high",
images=images,
+ owns_entry=True, # the assembly session is the entry file's one owner
)
)
ctx.events.emit(
@@ -353,6 +356,7 @@ class StaticObjectTrack(BaseTrack):
thinking="medium",
images=reference_images(ctx) + judged_sheet(last),
edit_only=scoped,
+ owns_entry=True, # refine_object.j2 promises entry-file access even when scoped
)
# ------------------------------------------------------------------ detail round
@@ -401,6 +405,8 @@ class StaticObjectTrack(BaseTrack):
kind=DETAIL_KIND,
temperature=0.6,
thinking="high",
+ # detail is file-disjoint per scope; the entry gains no surface detail
+ edit_only=True,
)
)
else:
@@ -426,6 +432,7 @@ class StaticObjectTrack(BaseTrack):
kind=DETAIL_KIND,
temperature=0.6,
thinking="high",
+ owns_entry=True, # whole-object pass: files_hint is the full tree
)
)
ctx.record_prompt("detail", tasks[0].prompt)
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index 739aad46..eb9a0f55 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -14,6 +14,7 @@ import shutil
import subprocess
import threading
import time
+from collections.abc import Sequence
from pathlib import Path
from typing import Any
@@ -357,6 +358,17 @@ class Workspace:
self._git("checkout", "-q", commit, "--", *roots)
self._git("add", "-A")
+ def restore_paths(self, commit: str, paths: Sequence[str]) -> None:
+ """Make just ``paths`` match ``commit`` (worktree + index; everything else untouched).
+
+ Used by the CLI post-hoc write-scope check (``agents/cli_common.finish_session``):
+ an ``edit_only`` session's out-of-scope writes are rolled back to the session's own
+ ``pre:`` commit without disturbing its in-scope work. Every path must exist in
+ ``commit`` — the caller passes only modified/deleted paths, which by definition did."""
+ if not paths:
+ return
+ self._git("checkout", "-q", commit, "--", *paths)
+
def diff(self, a: str, b: str = "HEAD") -> str:
return self._git("diff", a, b, "--", "src", "public").stdout
diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.py
new file mode 100644
index 00000000..b9ae8f29
--- /dev/null
+++ b/harness/tests/agents/test_cli_write_scope.py
@@ -0,0 +1,143 @@
+"""CLI write-scope enforcement: per-workspace serialisation + post-hoc edit_only restore.
+
+CLI backends (claude-code / codex / gemini-cli / agy) have no write-time file gate —
+``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.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+import pytest
+
+from codeverse.agents.api_tools import FileTools, PathDenied
+from codeverse.agents.cli_common import EXCLUSIVE_KINDS, begin_session, finish_session
+from codeverse.contracts.agent import AgentJob
+from codeverse.contracts.common import Usage
+from codeverse.workspace import Workspace
+
+
+def _job(ws: Workspace, label: str, **kw) -> AgentJob:
+ return AgentJob(workspace=str(ws.root), prompt="p", label=label, extra={"round": 0}, **kw)
+
+
+def _finish(s, *, ok: bool = True):
+ return finish_session(s, ok=ok, exit_reason="completed", text="", usage=Usage())
+
+
+# --------------------------------------------------------------------------- serialisation
+def test_the_cli_kinds_are_exclusive_and_the_api_agent_is_not():
+ assert {"claude-code", "codex", "gemini-cli", "agy"} == EXCLUSIVE_KINDS
+ assert "api-agent" not in EXCLUSIVE_KINDS and "fake" not in EXCLUSIVE_KINDS
+
+
+def test_two_cli_sessions_on_one_workspace_are_serialized(tmp_ws: Workspace):
+ """Two threads, one workspace: the begin→finish windows must not overlap."""
+ windows: dict[str, tuple[float, float]] = {}
+ started = threading.Barrier(2)
+
+ def session(name: str) -> None:
+ started.wait(timeout=30) # both threads race begin_session together
+ s = begin_session(_job(tmp_ws, name), "codex")
+ t0 = time.monotonic()
+ (tmp_ws.src / f"{name}.py").write_text(f"# {name}\n")
+ time.sleep(0.15) # long enough that overlapping windows would be seen
+ t1 = time.monotonic()
+ _finish(s)
+ windows[name] = (t0, t1)
+
+ threads = [threading.Thread(target=session, args=(n,)) for n in ("a", "b")]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=60)
+ assert set(windows) == {"a", "b"}
+ (a0, a1), (b0, b1) = windows["a"], windows["b"]
+ assert a1 <= b0 or b1 <= a0, f"sessions interleaved: a={windows['a']} b={windows['b']}"
+
+
+def test_api_agent_sessions_do_not_take_the_lock(tmp_ws: Workspace):
+ s1 = begin_session(_job(tmp_ws, "s1"), "api-agent")
+ assert s1.ws_lock is None
+ s2 = begin_session(_job(tmp_ws, "s2"), "api-agent") # would deadlock if locked
+ _finish(s2)
+ _finish(s1)
+
+
+def test_same_thread_can_begin_again_without_finishing(tmp_ws: Workspace):
+ """The lock is re-entrant: argv-building tests begin sessions they never finish."""
+ s1 = begin_session(_job(tmp_ws, "s1"), "codex")
+ assert s1.ws_lock is not None
+ s2 = begin_session(_job(tmp_ws, "s2"), "codex")
+ _finish(s2)
+ _finish(s1) # double release stays idempotent via release_session
+
+
+# --------------------------------------------------------------------------- post-hoc scope
+def _scoped_ws(tmp_ws: Workspace) -> Workspace:
+ (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)
+ (tmp_ws.src / "model.py").write_text("# entry\n")
+ (tmp_ws.src / "parts" / "seat.py").write_text("# seat\n")
+ (tmp_ws.src / "parts" / "leg.py").write_text("# leg\n")
+ return tmp_ws
+
+
+def test_out_of_scope_cli_write_is_restored_and_fails_the_session(tmp_ws: Workspace):
+ ws = _scoped_ws(tmp_ws)
+ job = _job(ws, "detail_seat", edit_only=True, files_hint=["src/parts/seat.py"])
+ s = begin_session(job, "codex")
+ (ws.src / "parts" / "seat.py").write_text("# new seat\n") # hinted: kept
+ (ws.src / "parts" / "leg.py").write_text("# rewritten leg\n") # out of scope: restored
+ (ws.src / "parts" / "bolt.py").write_text("# new part\n") # new file: kept
+ res = _finish(s, ok=True)
+ assert not res.ok, "an out-of-scope write must fail the session"
+ assert any("out-of-scope" in e and "src/parts/leg.py" in e for e in res.errors), res.errors
+ assert (ws.src / "parts" / "leg.py").read_text() == "# leg\n", "restored to head_before"
+ assert (ws.src / "parts" / "seat.py").read_text() == "# new seat\n"
+ assert (ws.src / "parts" / "bolt.py").read_text() == "# new part\n"
+ assert sorted(f.path for f in res.files_changed) == ["src/parts/bolt.py", "src/parts/seat.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"])
+ s = begin_session(job, "gemini-cli")
+ (ws.src / "model.py").write_text("# hijacked entry\n")
+ res = _finish(s)
+ assert not res.ok and (ws.src / "model.py").read_text() == "# entry\n"
+
+ owned = _job(ws, "assemble", edit_only=True, files_hint=["src/parts/seat.py"],
+ always_writable=["src/model.py"])
+ s2 = begin_session(owned, "gemini-cli")
+ (ws.src / "model.py").write_text("# entry + import\n")
+ res2 = _finish(s2)
+ assert res2.ok and (ws.src / "model.py").read_text() == "# entry + import\n"
+
+
+def test_unscoped_cli_sessions_keep_the_old_behaviour(tmp_ws: Workspace):
+ ws = _scoped_ws(tmp_ws)
+ s = begin_session(_job(ws, "baseline"), "codex") # edit_only=False
+ (ws.src / "parts" / "leg.py").write_text("# fine\n")
+ res = _finish(s)
+ assert res.ok and (ws.src / "parts" / "leg.py").read_text() == "# fine\n"
+
+
+# --------------------------------------------------------------------------- FileTools mirror
+def test_filetools_denies_the_entry_without_ownership(tmp_path):
+ """The api-agent side of entry ownership: no ``always_writable`` (owns_entry=False)
+ means the entry file is just another out-of-scope existing file."""
+ ws = Workspace(tmp_path / "run").create()
+ (ws.root / "src" / "parts").mkdir(parents=True, exist_ok=True)
+ (ws.root / "src" / "model.py").write_text("# entry\n")
+ (ws.root / "src" / "parts" / "seat.py").write_text("# seat\n")
+ denied = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"])
+ with pytest.raises(PathDenied):
+ denied.write_file("src/model.py", "# hijack\n")
+ owner = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"],
+ always_writable=["src/model.py"])
+ assert not owner.write_file("src/model.py", "# entry + import\n").is_error
diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.py
new file mode 100644
index 00000000..8e629de4
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_write_scope.py
@@ -0,0 +1,227 @@
+"""Write-scope enforcement at the task layer.
+
+* the single-shot envelope (``write_files(only=...)``) skips a pre-existing path the
+ task does not own — new files stay allowed, the entry only when owned;
+* ``GenerationTask.owns_entry`` → ``AgentJob.always_writable`` wiring;
+* the constructors whose plans are file-disjoint by construction (scoped baseline,
+ zones, scoped detail, threejs assets, parallel refine groups) now set
+ ``edit_only=True`` so the split they promise is enforced, not just prompted.
+"""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import BuildResult, Measurement, PartMeasure
+from codeverse.contracts.chat import ChatResponse
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlan
+from codeverse.contracts.run import RoundRecord
+from codeverse.events import EventLog
+from codeverse.orchestrator.rounds import RefineTask, TaskGroup
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks.envelope import write_files
+from codeverse.tracks.generation import (
+ GenerationResult,
+ GenerationTask,
+ _always_writable,
+ generate_files,
+ run_agent_task,
+)
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.scene import SceneTrack, zone_file
+from codeverse.tracks.static_object import StaticObjectTrack
+from codeverse.workspace import Workspace
+
+from .conftest import make_spec
+from .fakes import FakeAgent, FakeRuntime, FakeServices
+
+
+# --------------------------------------------------------------------------- envelope
+def test_write_files_only_skips_existing_out_of_scope_paths(tmp_ws: Workspace):
+ (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)
+ (tmp_ws.src / "zones").mkdir(parents=True, exist_ok=True)
+ (tmp_ws.src / "parts" / "a.js").write_text("// old a\n")
+ (tmp_ws.src / "zones" / "q.js").write_text("// old q\n")
+ skipped: list[tuple[str, str]] = []
+ files = {"src/parts/a.js": "// new a", "src/zones/q.js": "// new q", "src/parts/new.js": "// new"}
+ changes = write_files(tmp_ws, files, only={"src/parts/a.js"},
+ on_skip=lambda p, r: skipped.append((p, r)))
+ assert [c.path for c in changes] == ["src/parts/a.js", "src/parts/new.js"]
+ assert (tmp_ws.src / "zones" / "q.js").read_text() == "// old q\n"
+ assert skipped == [("src/zones/q.js", skipped[0][1])] and "scope" in skipped[0][1]
+ # only=None keeps the old behaviour: everything valid is written
+ assert [c.path for c in write_files(tmp_ws, {"src/zones/q.js": "// new q"})] == ["src/zones/q.js"]
+
+
+class ScriptedModel:
+ """Yields ``(text, finish_reason)`` pairs in order (same as test_fix_generation)."""
+
+ def __init__(self, answers):
+ self.answers = list(answers)
+
+ def generate(self, req):
+ text, fr = self.answers.pop(0)
+ return ChatResponse(text=text, usage=Usage(backend="fake", cost_usd=0.001), finish_reason=fr)
+
+
+ANSWER = (
+ "=== FILE: src/parts/a.js ===\n// new a\n=== END FILE ===\n"
+ "=== FILE: src/object.js ===\n// new entry\n=== END FILE ===\n"
+ "=== FILE: src/parts/b.js ===\n// new b\n=== END FILE ===\n"
+ "=== FILE: src/parts/new.js ===\n// new part\n=== END FILE ==="
+)
+
+
+def _envelope_ws(tmp_path) -> Workspace:
+ ws = Workspace(tmp_path / "ws").create()
+ ws.write_json(ws.spec_path, {"language": "threejs", "track": "static_object"})
+ (ws.src / "parts").mkdir(parents=True, exist_ok=True)
+ (ws.src / "object.js").write_text("// entry\n")
+ (ws.src / "parts" / "a.js").write_text("// a\n")
+ (ws.src / "parts" / "b.js").write_text("// b\n")
+ return ws
+
+
+def test_generate_files_enforces_the_task_scope(tmp_path):
+ ws = _envelope_ws(tmp_path)
+ events = EventLog(tmp_path / "e.jsonl")
+ task = GenerationTask(label="refine_a", prompt="p", files_hint=["src/parts/a.js"], edit_only=True)
+ res = generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task, events=events)
+ assert res.ok and [c.path for c in res.files_changed] == ["src/parts/a.js", "src/parts/new.js"]
+ assert (ws.src / "parts" / "a.js").read_text() == "// new a\n"
+ assert (ws.src / "object.js").read_text() == "// entry\n", "the entry is not owned"
+ assert (ws.src / "parts" / "b.js").read_text() == "// b\n", "the sibling part is protected"
+ assert (ws.src / "parts" / "new.js").read_text() == "// new part\n", "new files stay allowed"
+ skips = [e for e in events.read() if e["event"] == "generate.skipped_path"]
+ assert {e["path"] for e in skips} == {"src/object.js", "src/parts/b.js"}
+ assert all("scope" in e["reason"] for e in skips)
+
+
+def test_generate_files_lets_an_owner_write_the_entry(tmp_path):
+ ws = _envelope_ws(tmp_path)
+ task = GenerationTask(label="refine_a", prompt="p", files_hint=["src/parts/a.js"],
+ edit_only=True, owns_entry=True)
+ res = generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task,
+ events=EventLog(tmp_path / "e.jsonl"))
+ assert res.ok and (ws.src / "object.js").read_text() == "// new entry\n"
+ assert (ws.src / "parts" / "b.js").read_text() == "// b\n", "b stays out of scope"
+
+
+def test_generate_files_without_edit_only_is_unchanged(tmp_path):
+ ws = _envelope_ws(tmp_path)
+ task = GenerationTask(label="baseline", prompt="p", files_hint=["src/parts/a.js"])
+ generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task,
+ events=EventLog(tmp_path / "e.jsonl"))
+ assert (ws.src / "object.js").read_text() == "// new entry\n"
+ assert (ws.src / "parts" / "b.js").read_text() == "// new b\n"
+
+
+# --------------------------------------------------------------------------- entry ownership
+def test_always_writable_requires_ownership():
+ part = GenerationTask(label="p", prompt="p", files_hint=["src/parts/seat.js"])
+ assert _always_writable("threejs", part) == []
+ assert _always_writable("threejs", part.model_copy(update={"owns_entry": True})) == ["src/object.js"]
+ hinted = GenerationTask(label="w", prompt="p", files_hint=["src/object.js", "src/parts/seat.js"])
+ assert _always_writable("threejs", hinted) == ["src/object.js"], "files_hint naming the entry owns it"
+ assert _always_writable("", part) == [] and _always_writable("nope", part) == []
+
+
+def test_run_agent_task_wires_entry_ownership_into_the_job(tmp_ws: Workspace):
+ tmp_ws.write_json(tmp_ws.spec_path, {"language": "threejs", "track": "static_object"})
+ agent = FakeAgent(lambda job, ws: {"src/parts/seat.js": "// seat\n"})
+ part = GenerationTask(label="detail_seat", prompt="p", files_hint=["src/parts/seat.js"], edit_only=True)
+ res = run_agent_task(tmp_ws, agent=agent, task=part)
+ assert res.ok and agent.jobs[0].edit_only is True and agent.jobs[0].always_writable == []
+ run_agent_task(tmp_ws, agent=agent, task=part.model_copy(update={"owns_entry": True, "label": "d2"}))
+ assert agent.jobs[1].always_writable == ["src/object.js"]
+
+
+# --------------------------------------------------------------------------- constructors
+def _big_plan(n: int = 8) -> StaticPlan:
+ parts = [PartPlan(name="Body", role="main mass", description="the shell",
+ bbox=BBox(center=(0, 0.5, 0), extents=(0.6, 1.0, 0.4)))]
+ for i in range(n - 1):
+ parts.append(PartPlan(name=f"Fitting{i}", role=f"fitting {i}", description="a fitting",
+ bbox=BBox(center=(0.05 * i, 0.2 + 0.05 * i, 0.1), extents=(0.05, 0.05, 0.05)),
+ attach_to="Body"))
+ return StaticPlan(object_name="Machine", summary="A machine, 0.6 x 0.4 x 1.0 m.",
+ overall_bbox=BBox(center=(0, 0.5, 0), extents=(0.6, 1.0, 0.4)), parts=parts,
+ acceptance=[])
+
+
+def _static_ctx(tmp_path, settings):
+ ws = Workspace(tmp_path / "runs" / "d").create()
+ track = StaticObjectTrack(services=FakeServices(), agent=FakeAgent(lambda job, ws: None),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS))
+ ctx = track.build_context(make_spec(language=Language.THREEJS, generator="fake-agent:m"),
+ ws, EventLog(ws.events_path), RunState(slug="d"))
+ ctx.plan = _big_plan()
+ return track, ctx
+
+
+def _round(i: int, score: float) -> RoundRecord:
+ j = Judgment(rubric="r", scores={}, overall=score, passed=score >= 0.8)
+ return RoundRecord(index=i, kind="refine", judgment=j, commit=f"c{i}",
+ build=BuildResult(ok=True, language="threejs"))
+
+
+def test_scoped_static_constructors_enforce_their_file_sets(tmp_path, settings):
+ track, ctx = _static_ctx(tmp_path, settings)
+ tasks = track.baseline_tasks(ctx)
+ parts, assemble = tasks[:-1], tasks[-1]
+ assert len(parts) >= 2
+ assert all(t.edit_only and not t.owns_entry for t in parts), "part sessions are scoped"
+ assert assemble.owns_entry and not assemble.edit_only, "assemble owns the entry"
+ # scoped detail: file-disjoint and enforced
+ last = _round(2, 0.62)
+ last.measurement = Measurement(bbox_min=(0, 0, 0), bbox_max=(1, 1, 1), extents=(1, 1, 1),
+ center=(0, 0, 0), tri_count=900, n_meshes=1, n_islands=1,
+ parts=[PartMeasure(name="Body", bbox_min=(0, 0, 0),
+ bbox_max=(0.6, 1.0, 0.4), tri_count=10, islands=1)])
+ detail, lines = track.detail_tasks(ctx, last, 3)
+ assert detail and lines
+ assert all(t.edit_only and not t.owns_entry for t in detail), "detail never touches the entry"
+ # refine keeps entry access: the prompt promises it ("edit the entry file to import a new part")
+ group = TaskGroup(tasks=[RefineTask(target="Body", kind="geometry", instruction="thicken",
+ priority=2, files=["src/parts/body.js"])],
+ files=["src/parts/body.js"])
+ rt = track._refine_task(ctx, group, last, 2, parallel=True)
+ assert rt.edit_only and rt.owns_entry
+
+
+def test_scene_constructors_enforce_their_file_sets(tmp_path, settings, monkeypatch):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ ws = Workspace(tmp_path / "runs" / "s").create()
+ track = SceneTrack(services=FakeServices(), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ ctx = track.build_context(make_spec(Track.SCENE, Language.SCENE_THREEJS),
+ ws, EventLog(ws.events_path), RunState())
+ ctx.plan = plan
+ zone = plan.zones[0]
+ zt = track._zone_task(ctx, [zone])
+ assert zt.edit_only and not zt.owns_entry and zt.files_hint == [zone_file(zone)]
+ if len(plan.zones) >= 2:
+ bt = track._zone_task(ctx, list(plan.zones[:2]))
+ assert bt.edit_only and bt.files_hint == [zone_file(z) for z in plan.zones[:2]]
+ last = RoundRecord(index=0, kind="baseline", build=BuildResult(ok=True, language="scene_threejs"))
+ group = TaskGroup(tasks=[RefineTask(target=zone.name, kind="geometry", instruction="denser",
+ priority=2, files=[zone_file(zone)])], files=[zone_file(zone)])
+ assert track._refine_task(ctx, group, last, 1, parallel=True).edit_only is True
+ assert track._refine_task(ctx, group, last, 1, parallel=False).edit_only is False
+
+ # threejs asset tasks share the scene workspace → scoped; blender heroes own a sub-workspace
+ import codeverse.tracks.scene_assets as scene_assets
+
+ captured: dict[str, GenerationTask] = {}
+
+ def fake_generate(ws, **kw):
+ captured["task"] = kw["task"]
+ return GenerationResult(ok=True, label=kw["task"].label)
+
+ monkeypatch.setattr(scene_assets, "generate", fake_generate)
+ assert plan.assets, "plan_example(SCENE) is expected to plan assets"
+ asset = plan.assets[0]
+ scene_assets._generate_asset(ctx, asset, "src/assets/koi.js", language=Language.SCENE_THREEJS, attempt=0)
+ assert captured["task"].edit_only is True and captured["task"].files_hint == ["src/assets/koi.js"]
+ scene_assets._generate_asset(ctx, asset, "src/model.py", language=Language.BLENDER, attempt=0)
+ assert captured["task"].edit_only is False