Files
roboco/tests/unit/runtime/test_agent_write_permissions.py
cfde4369b1 Token optimization levers — claim-scoped briefing, payload caps, role-scoped optimal, notification-spawn cooldown (#292)
* feat(gateway): claim-scoped context briefing — heavy sections only on context-acquisition verbs

* feat(gateway): cap unbounded LLM-facing payloads — embedded diffs, notification bodies, handoff journal content, north star

* feat(mcp): role-scope the optimal server's tool groups; index management becomes dev/test-only

* feat(mcp): cap per-result content on kb/error/learning search, mentor sources, rag citations

* refactor(gateway): extract heavy-briefing sections + clip helper to keep xenon ranks

* feat(orchestrator): cross-tick cooldown for notification-triggered spawns

* feat(usage,orchestrator): scope spawn-waste to anthropic sessions; cap agent Bash output via settings env

* docs: claim-scoped briefing, payload caps, optimal role-scoping, notification-spawn cooldown

* test(mcp): type the mixed-item cap fixture explicitly

* fix(orchestrator): lazy-init the notification-spawn cooldown store

* fix(lifecycle): admin-override claim reconciliation + PM request_changes verb (S6 postmortem B3+B4)

B3 — admin_set_status now reconciles claim ownership when leaving BLOCKED:
review/queue targets clear claimed_by/claimed_at/active_claimant_id and
consume the pre-block snapshot (a stale escalation claim was stranding the
next claimant: give_me_work handed the task out while note() bounced
not_authorized — the live b8fe0494 wedge). The pending/in_progress restore
path also syncs active_claimant_id, and a REST PATCH unassign releases the
claim with it.

B4 — new PM verb request_changes: awaiting_pm_review -> needs_revision with
concrete issues. The PM previously had no reject at merge review (only
complete/escalate), so an AC/scope violation looped i_am_blocked->escalate
4x live. Full vertical: lifecycle transition + ActionSpec + IntentSpec,
TaskService.request_changes (routes like a QA fail — original dev for a
leaf, revision PM for assembled; issues appended to dev_notes), verb-runner
compose, choreographer verb (spec gate + non-empty issues + soup check +
a2a delivery of the reject reason), HTTP routes on both PM flows, MCP tool,
journal:decision tracing, PM prompts, regenerated lifecycle artifacts.

* fix(panel): stop scorecard fetches for fallback-roster placeholder ids

useAgents() serves the static AGENT_ROSTER (ids "1".."22") while agent
definitions load; the Scorecards tab fetched a member scorecard per row
immediately, firing 22 guaranteed-422 requests per refetch cycle. Through
the browser's per-origin connection limit those queued every metrics-page
query behind them (~10s of skeletons on every tab). Gate the fetch on a
real member id (agent UUID or the "ceo" alias).

* Upgraded uv.lock

* fix(sequencing): declared deps become real edges + full loop-breaker coverage + assembled-branch freshness (S6 postmortem B1/B2/B6 + breaker)

B1a — code delegations REQUIRE a collision surface: new TASK_AT_DELEGATE
completeness spec (conditional FieldRequirement, when=('task_type','code'))
enforced at the gateway delegate gate. A no-surface code sibling is
'parallel to everything' by analyzer design, which is how two devs ran the
CEO's explicitly-ordered work out of order (f3e1afc5: seq#1 started before
seq#0, zero dependency edges). PM prompts updated; REST/manual creation
(TASK_AT_CREATE) unchanged.

B1b — the CEO's declared 'Depends on' lists become real edges: DraftSurface
gains declared_depends_on; SequencingService.analyze unions declared edges
(validated: self/out-of-range rejected) with the derived collision rules,
cycle-checked by the existing toposort. confirm_live_batch/preview_batch
map each draft's depends_on through (string indices coerced); intake tool
doc + prompter role prompt instruct verbatim copying. The live S6 root got
1 of its 3 declared in-batch edges and started alongside still-running R3.

Breaker coverage — the progress-aware respawn circuit breaker
(_pm_respawn_should_gate: strike counting, status-advance reset,
tracing-gap budget, DB durability, one-shot CEO notification) was consulted
by only 3 spawn paths; the doc/QA/dev/PR-review/PR-gate/revision/board
paths spawned unguarded at fixed cadence (the 26-respawn fe-doc loop,
~$7.20). Now consulted at every task-keyed spawn site (14 total).

B2 — assembled-branch freshness: submit_up/submit_root auto-sync the
assembled branch when it has fallen behind its base (children are terminal
at submit time, so the rebase is safe; master is never written). A rebase
conflict is a hard reject naming the files instead of a blind re-review —
kills the needs_revision↔awaiting_pr_review ping-pong of re-submitting a
stale head. Leaf i_am_done already had the behind-base gate; claim-time
fetch-fresh cut already existed.

B6 — documenter revision-pass loop: the awaiting_documentation bail
rejections (i_am_blocked/unclaim) now name the actual exit (i_documented
re-affirm) and the documenter prompt gets an explicit revision-pass rule.

* fix(orchestration): assembly-integrity gate + dispatcher heartbeat (incidents #11, #1)

Assembly integrity — submit_up/submit_root refuse when a completed child's
commits are not patch-present in the assembled branch (git cherry —
rebase-safe; branch pruned after merge or any git error fails open). Live
incident #11: a completed revert subtask's merge was lost from the cell
branch and the review gate re-flagged the exact violation the revert fixed,
spawning another revision cycle.

Dispatcher heartbeat — a dispatcher.alive audit row every 5 minutes from
the dispatch loop. The 2026-07-01 outage was 4h25m of fleet-wide silence
with no way to distinguish 'loop dead' from 'no work'; the loop's stdout
died with the container while audit_log survives. CHANGELOG for tonight's
full sweep included.

* style: ruff format for the orchestration sweep

* refactor(gateway): fold the assembled-submit guards + trim complexity under the xenon gate

_assembled_submit_guards combines the #11 integrity check and B2 freshen for
submit_up/submit_root; lifecycle's invalid-source remediate and git's
per-child cherry probe extracted into helpers. Test harnesses built via
__new__ stub the respawn tracker (the breaker now runs on their paths).

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-02 05:46:01 +02:00

125 lines
4.8 KiB
Python

"""#167: agents could never Edit/Write any file (smoke-10..14).
Root cause: _generate_agent_settings put ``Write(*)``/``Edit(*)`` in the
GLOBAL base_deny. Claude Code evaluates rules deny -> ask -> allow and the
first match wins, so a deny ALWAYS beats a more-specific allow (the glob
syntax has no negation). The global deny therefore unconditionally
shadowed every per-role workspace-scoped Write/Edit allow — every agent,
developers included, got "Edit exists but is not enabled in this context"
and fell back to destructive bash redirection (clobbering real files;
e.g. a 207-line README rewritten to a 3-line stub, which QA correctly
failed).
Second defect: the workspace allow used a SINGLE leading slash
(``Write(/data/...)``). Claude Code resolves a single ``/`` against the
settings.json project root, not the container filesystem root, so even
without the global deny the allow never matched. Absolute container
paths require the ``//`` form.
Fix: drop Write(*)/Edit(*) from base_deny (roles that must not write keep
their OWN Write(*)/Edit(*) deny); emit the workspace allow in the ``//``
absolute form.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import patch
from roboco.runtime.orchestrator import AgentOrchestrator
def _orch() -> AgentOrchestrator:
with patch.object(AgentOrchestrator, "__init__", return_value=None):
return AgentOrchestrator.__new__(AgentOrchestrator)
_WS = "/data/workspaces/roboco-api/backend/be-dev-1"
_CELL = "/data/workspaces/roboco-api/backend"
_WRITER_ROLES = ("developer", "documenter", "product_owner", "head_marketing")
_NON_WRITER_ROLES = ("qa", "cell_pm", "main_pm", "auditor")
def test_generated_settings_cap_bash_output() -> None:
"""Agent settings carry an explicit Bash-output cap — a gate/test dump
enters context once and is re-read at cache-read price every later turn."""
orch = _orch()
path = orch._generate_agent_settings(
agent_id="be-dev-1",
role="developer",
workspace_path=_WS,
cell_workspace_path=_CELL,
)
settings = json.loads(Path(path).read_text())
assert settings["env"]["BASH_MAX_OUTPUT_LENGTH"] == "20000"
def test_generated_settings_base_deny_has_no_global_write_edit() -> None:
"""The settings file a developer is spawned with must NOT globally
deny Write/Edit (that shadowed the workspace allow → unusable)."""
orch = _orch()
path = orch._generate_agent_settings(
agent_id="be-dev-1",
role="developer",
workspace_path=_WS,
cell_workspace_path=_CELL,
)
settings = json.loads(Path(path).read_text())
deny = settings["permissions"]["deny"]
allow = settings["permissions"]["allow"]
assert "Write(*)" not in deny, deny
assert "Edit(*)" not in deny, deny
# The security denies that DO rely on deny-always-wins must remain.
assert "Bash(git:*)" in deny, deny
assert any(".git/config" in d for d in deny), deny
# Workspace allow present and in the // absolute form.
assert f"Write(/{_WS}/**)" in allow, allow
assert f"Edit(/{_WS}/**)" in allow, allow
def test_writer_roles_use_double_slash_absolute_allow() -> None:
"""Every role that authors files emits Write/Edit allow rules in the
// absolute-filesystem form (single / silently never matches)."""
orch = _orch()
for role in _WRITER_ROLES:
perms = orch._get_role_permissions(
role=role, workspace_path=_WS, cell_workspace_path=_CELL
)
write_edit = [e for e in perms["allow"] if e.startswith(("Write(", "Edit("))]
assert write_edit, f"{role} should allow some Write/Edit: {perms}"
for entry in write_edit:
inner = entry[entry.index("(") + 1 :]
assert inner.startswith("//"), (
f"{role} allow rule must use // absolute form: {entry}"
)
def test_non_writer_roles_still_deny_write_edit() -> None:
"""Removing the GLOBAL deny must not let QA / PMs / auditor write —
they carry their own Write(*)/Edit(*) deny in the role config."""
orch = _orch()
for role in _NON_WRITER_ROLES:
perms = orch._get_role_permissions(
role=role, workspace_path=_WS, cell_workspace_path=_CELL
)
assert "Write(*)" in perms["deny"], f"{role}: {perms}"
assert "Edit(*)" in perms["deny"], f"{role}: {perms}"
def test_non_writer_generated_settings_block_write() -> None:
"""End-to-end: a cell_pm's generated settings still deny Write/Edit
(their own role deny survives the base_deny change)."""
orch = _orch()
path = orch._generate_agent_settings(
agent_id="be-pm",
role="cell_pm",
workspace_path=_WS,
cell_workspace_path=_CELL,
)
deny = json.loads(Path(path).read_text())["permissions"]["deny"]
assert "Write(*)" in deny, deny
assert "Edit(*)" in deny, deny