mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
fix(run-hardening): break PM decision-gate, stale-agent, and empty-diff loops (#255)
Forensic triage of a 24h run reconstructed the dominant gateway.rejected loops from the audit_log. After earlier deploys fixed the i_will_plan crash and the open_pr push-gap, three real, recurring-capable burn loops remained. This fixes them at the architecture level, not by prompt-nagging. journal:decision write-then-gate (the dominant completion-path blocker): PM decision-point verbs required a separate note(scope='decision') call before the verb, which loaded/weak models forget to chain — so complete and unblock hit a tracing_gap (journal:decision missing) and respawn-looped, stranding finished tasks forever. Each verb now auto-records its OWN rationale as the journal:decision before the gate runs (the proven i_am_blocked -> write_struggle pattern), so the gate passes off real, persisted reasoning. unblock gains a required `reason` (threaded MCP tool -> request schema -> routes -> choreographer); delegate derives the decision from its title + description; complete/submit_up/submit_root/escalate_up/ escalate_to_ceo reuse their existing notes/reason. The gate still runs as defense-in-depth; the auto-record is idempotent within the decision window and best-effort. Adds JournalService.write_decision and Choreographer._ensure_pm_decision. open_pr empty-diff 422: an overlapping-decomposition leaf with zero commits vs its base makes GitHub 422 "No commits between ...". The generic invalid_state "retry" looped the dev 15x on one task. open_pr now steers to a terminal i_am_blocked hand-off so the PM completes or cancels the redundant leaf. owns_task stale-agent loop (41x): a superseded agent (task reassigned away) calling i_am_done/open_pr got a PRECONDITION_OWNERSHIP tracing_gap it read as a fixable precondition and retried forever. Both verbs now short-circuit with the clear not_authorized "no longer yours -> give_me_work" steer that resume/unclaim already use. RAG docs updated for the new unblock(reason) signature; CHANGELOG entries added under 0.11.0 (unreleased). open_pr refactored into _open_pr_preflight_rejection + _open_pr_failure_env to stay within the return-count and complexity budgets. Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -16,6 +16,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A PM that forgot to journal its decision no longer stalls a finished task forever.** Every PM decision-point verb (`unblock`, `complete`, `submit_up` / `submit_root`, `escalate_up` / `escalate_to_ceo`) required a *separate* `note(scope='decision')` call to be made **before** the verb — and loaded or weak models reliably forget to chain that prior side-effect, so the verb hit a `tracing_gap` (`journal:decision` missing), the agent retried, and a task whose work was actually done sat stranded in a reject → respawn loop (the dominant remaining completion-path blocker in a 24h run; one live case: a corrected PR that could not be merged because the Main PM's `unblock` kept failing the gate). The verb now auto-records its **own rationale** as the `journal:decision` the gate needs, *before* the gate runs — the same write-then-gate pattern already used for `i_am_blocked → write_struggle` and for the `qa_notes` / `pr_reviewer_notes` sections — so the gate passes off real, persisted reasoning instead of demanding a redundant bookkeeping call. `complete` / `submit_up` / `submit_root` / `escalate_*` reuse the `notes` / `reason` the PM already passes; `unblock` now takes a required `reason` (threaded MCP tool → request schema → routes → choreographer); `delegate` derives the decision from the subtask's title + description. The gate still runs as defense-in-depth, the auto-record is idempotent within the decision window and best-effort (a journal hiccup falls back to the prior reject, never a crash), and the recorded decision is the PM's real words — so accountability is preserved, not bypassed.
|
||||
|
||||
- **An empty-diff subtask no longer loops a developer on "open a PR".** When overlapping decomposition leaves a leaf branch with zero commits relative to its base (its work was actually delivered by the parent or a sibling), `open_pr` pushed the branch and GitHub refused the PR with a `422 "No commits between …"`. That was surfaced as a generic `invalid_state` whose remediation said "retry", so the developer re-issued `open_pr` over and over (observed 15× on a single task) and never progressed. `open_pr` now recognizes the empty-diff 422 and returns a terminal hand-off instead: it tells the developer not to retry — the branch has no diff, so the work was delivered by the parent — and to call `i_am_blocked` so the PM can complete or cancel the redundant leaf.
|
||||
|
||||
- **A reassigned developer no longer retries `i_am_done` / `open_pr` forever.** When a task is reassigned out from under a still-running agent (a pool release, reaper unclaim, or escalation redirect), the agent's later `i_am_done` or `open_pr` failed the spec's ownership precondition as a `tracing_gap` (`owns_task` missing) — which reads like a *fixable* precondition, so the superseded agent kept retrying the same verb (41 such rejections in one run). Both verbs now short-circuit a non-owner with the same clear `not_authorized` "this task is no longer yours — call `give_me_work()`" steer that `resume` and `unclaim` already use, so a superseded agent is told plainly to fetch new work or go idle instead of looping.
|
||||
|
||||
- **A Main PM blocking its own coordination root no longer hands the whole root to the Board (a respawn catch-22).** Root cause: the generic escalation chain points `main-pm → product-owner`, and `i_am_blocked` / escalate REASSIGNS the task to that chain target. The board-advisory guard that refuses such a hand-off only covered descendant cell tasks (it required `parent_task_id`), so a top-level Main-PM **coordination root** slipped through and the entire root was reassigned to the Product Owner and marked blocked. A Board role has no `unblock` verb at all (only notify / note / triage / i_am_idle) and the unblock gate is assignee-only, so it could neither resolve the blocker nor hand it off — it just spam-notified the CEO while the blocked-task dispatcher respawned it every tick (one live incident burned an estimated 6400+ tool calls on a single root). Fixed at both layers: the escalation / reassign / revival guard now also refuses a Board owner for a `main_pm` coordination task (root or MegaTask root-subtask) and diverts it to the pool for a role-matched (Main-PM) re-claim — the upstream cure — via a single shared `_board_cannot_own` predicate; and, as a defense-in-depth backstop, the orchestrator's blocker dispatcher no longer treats a Board role as a blocker resolver (it returns no resolver, so a mis-owned blocked task is skipped rather than respawned onto a role that physically cannot act).
|
||||
|
||||
- **A racing state change mid-verb no longer crashes a PM into a respawn loop.** The gateway's verb runner guards the *initial* task/agent against `None`, but its composed atomic actions reassign the working task from each step (`i_will_plan` runs claim → set_plan → start). When a concurrent agent transitioned the row between the verb's precondition gate and execution — e.g. a racing `i_am_blocked` moved a coordination root from `needs_revision` to `blocked` — `claim()` found no valid transition and returned `None`, then the next step dereferenced `None.id` and crashed with the opaque `'NoneType' object has no attribute 'id'`, surfaced to the agent as a cryptic "verb runner failed" so the PM respawn-looped on the wedged root. The runner now re-checks after *each* composed action and fails fast with an actionable `INVALID_STATE` that tells the agent the row changed under it and to re-fetch and re-issue its verb (the savepoint rolls the partial sequence back).
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
- Plan and start a parent task via `i_will_plan(task_id, plan)` (this also auto-creates the parent branch)
|
||||
- Create subtasks via `delegate(parent_task_id, title, description, body)`
|
||||
- Triage your cell's queue via `triage()`
|
||||
- Unblock blocked tasks via `unblock(task_id, restore=True)`
|
||||
- Unblock blocked tasks via `unblock(task_id, reason, restore=True)` — `reason` (why the block is cleared) is recorded as your `journal:decision`, so no separate `note(scope='decision')` call is needed
|
||||
- Complete tasks via `complete(task_id, notes)` — this merges the PR (a leaf subtask's PR into your cell branch, or your assembled cell→root PR into the root branch after it clears the gate). No separate `merge_pr` tool exists; the choreographer does it.
|
||||
- Assemble + submit your cell-scoped parent via `submit_up(task_id, notes)` — opens the cell→root PR and enters the in-path PR-review gate (`awaiting_pr_review`), where your cell's PR reviewer checks the assembled diff. After `pr_pass`, you `complete` it to merge.
|
||||
- Send `notify` (ack-required notifications) — devs/QA/doc cannot
|
||||
|
||||
@@ -59,7 +59,9 @@ delegate(parent_task_id, title, description, assigned_to, team, task_type,
|
||||
# create a subtask; covers_parent_criteria maps
|
||||
# it to the parent ACs it is responsible for
|
||||
reassign(task_id, assigned_to) # move a subtask to a different agent
|
||||
unblock(task_id) # blocked -> in_progress (PM only)
|
||||
unblock(task_id, reason) # blocked -> in_progress (PM only); reason is
|
||||
# recorded as your journal:decision (no separate
|
||||
# note needed)
|
||||
submit_up(task_id, notes) # open cell->root PR; -> awaiting_pr_review
|
||||
# (the cell PR reviewer gates it; after pr_pass
|
||||
# the same Cell PM completes + merges)
|
||||
|
||||
@@ -95,6 +95,6 @@ Include:
|
||||
2. Investigate: read the task, journals, and channel messages
|
||||
3. Decide, or escalate further with `escalate_up`
|
||||
4. Communicate the decision (`say` / `dm` / `notify`)
|
||||
5. Unblock if needed: `unblock(task_id)`
|
||||
5. Unblock if needed: `unblock(task_id, reason)`
|
||||
|
||||
CRITICAL: Verbal resolution is NOT enough. To clear a block you MUST call `unblock(task_id)`.
|
||||
CRITICAL: Verbal resolution is NOT enough. To clear a block you MUST call `unblock(task_id, reason)`. The `reason` (why you are clearing the block) is recorded as your `journal:decision` — no separate `note(scope='decision')` call is required.
|
||||
|
||||
@@ -119,7 +119,9 @@ async def unblock(
|
||||
x_agent_id: _AgentIdHeader,
|
||||
choreographer: _ChoreographerDep,
|
||||
) -> dict:
|
||||
env = await choreographer.unblock(x_agent_id, body.task_id, restore=body.restore)
|
||||
env = await choreographer.unblock(
|
||||
x_agent_id, body.task_id, body.reason, restore=body.restore
|
||||
)
|
||||
return envelope_to_response(env, request)
|
||||
|
||||
|
||||
|
||||
@@ -152,7 +152,9 @@ async def unblock(
|
||||
x_agent_id: _AgentIdHeader,
|
||||
choreographer: _ChoreographerDep,
|
||||
) -> dict:
|
||||
env = await choreographer.unblock(x_agent_id, body.task_id, restore=body.restore)
|
||||
env = await choreographer.unblock(
|
||||
x_agent_id, body.task_id, body.reason, restore=body.restore
|
||||
)
|
||||
return envelope_to_response(env, request)
|
||||
|
||||
|
||||
|
||||
@@ -174,6 +174,14 @@ class TriageRequest(BaseModel):
|
||||
|
||||
class UnblockRequest(BaseModel):
|
||||
task_id: UUID
|
||||
reason: str = Field(
|
||||
...,
|
||||
min_length=10,
|
||||
description=(
|
||||
"Why the block is cleared — recorded as the PM's journal:decision "
|
||||
"so no separate note(scope='decision') call is needed."
|
||||
),
|
||||
)
|
||||
restore: bool = True
|
||||
|
||||
|
||||
|
||||
@@ -420,9 +420,14 @@ def triage_all() -> dict[str, Any]:
|
||||
return _post(_role_path("triage_all"), {})
|
||||
|
||||
|
||||
def unblock(task_id: str, restore: bool = True) -> dict[str, Any]:
|
||||
"""PM: unblock a task. restore=True (default) restores pre_block_state."""
|
||||
return _post(_role_path("unblock"), {"task_id": task_id, "restore": restore})
|
||||
def unblock(task_id: str, reason: str, restore: bool = True) -> dict[str, Any]:
|
||||
"""PM: unblock a task. `reason` states why the block is cleared and is
|
||||
recorded as your decision (no separate note needed). restore=True
|
||||
(default) restores pre_block_state."""
|
||||
return _post(
|
||||
_role_path("unblock"),
|
||||
{"task_id": task_id, "reason": reason, "restore": restore},
|
||||
)
|
||||
|
||||
|
||||
def complete(task_id: str, notes: str) -> dict[str, Any]:
|
||||
|
||||
@@ -1495,33 +1495,16 @@ class Choreographer:
|
||||
),
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str)
|
||||
try:
|
||||
role = spec_module.Role(role_str)
|
||||
except ValueError:
|
||||
return await self._emit_rejection(
|
||||
Envelope.not_authorized(
|
||||
message=f"unknown role '{role_str}'",
|
||||
remediate="role is not declared in the lifecycle spec",
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str),
|
||||
agent_id=agent_id,
|
||||
task_id=task_id,
|
||||
verb="open_pr",
|
||||
)
|
||||
spec_ctx = spec_module.Context(
|
||||
actor_id=agent_id,
|
||||
actor_slug=getattr(agent, "slug", None) if agent is not None else None,
|
||||
original_developer_slug=_extract_original_developer(t),
|
||||
)
|
||||
decision = spec_module.can_invoke_intent(role, "open_pr", t, spec_ctx)
|
||||
if not decision.allowed:
|
||||
if rejection := self._open_pr_preflight_rejection(
|
||||
agent_id, task_id, t, role_str, briefing, spec_ctx
|
||||
):
|
||||
return await self._emit_rejection(
|
||||
Envelope.from_decision(decision, briefing=briefing).with_introspection(
|
||||
task=t, role=role_str
|
||||
),
|
||||
agent_id=agent_id,
|
||||
task_id=task_id,
|
||||
verb="open_pr",
|
||||
rejection, agent_id=agent_id, task_id=task_id, verb="open_pr"
|
||||
)
|
||||
await self._touch(task_id)
|
||||
runner = self._verb_runner()
|
||||
@@ -1529,11 +1512,7 @@ class Choreographer:
|
||||
await runner.run_intent("open_pr", t, agent, spec_ctx)
|
||||
except Exception as exc:
|
||||
return await self._emit_rejection(
|
||||
Envelope.invalid_state(
|
||||
message=f"verb runner failed: {exc}",
|
||||
remediate="check workspace + retry; if persistent, escalate",
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str),
|
||||
self._open_pr_failure_env(exc, t, briefing, role_str),
|
||||
agent_id=agent_id,
|
||||
task_id=task_id,
|
||||
verb="open_pr",
|
||||
@@ -1542,6 +1521,88 @@ class Choreographer:
|
||||
agent_id, task_id, t, briefing, role_str
|
||||
)
|
||||
|
||||
def _open_pr_preflight_rejection(
|
||||
self,
|
||||
agent_id: UUID,
|
||||
task_id: UUID,
|
||||
t: Any,
|
||||
role_str: str,
|
||||
briefing: dict[str, Any],
|
||||
spec_ctx: Any,
|
||||
) -> Envelope | None:
|
||||
"""Role + reassignment + spec-gate rejection for open_pr (or None).
|
||||
|
||||
A stale/superseded agent (task reassigned away) is steered to
|
||||
give_me_work with a clear not_authorized BEFORE the spec gate would
|
||||
emit an owns_task tracing_gap the agent retries forever (same pattern
|
||||
as i_am_done / resume).
|
||||
"""
|
||||
try:
|
||||
role = spec_module.Role(role_str)
|
||||
except ValueError:
|
||||
return Envelope.not_authorized(
|
||||
message=f"unknown role '{role_str}'",
|
||||
remediate="role is not declared in the lifecycle spec",
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str)
|
||||
reassigned = self._reassigned_rejection(
|
||||
_ReassignedCtx(
|
||||
task=t,
|
||||
agent_id=agent_id,
|
||||
task_id=task_id,
|
||||
role_str=role_str,
|
||||
briefing=briefing,
|
||||
upstream_hint=(
|
||||
"this task was reassigned away from you; you are no longer "
|
||||
"its owner. Call give_me_work() to find your current task, "
|
||||
"or i_am_idle() if there is none. Do NOT retry open_pr."
|
||||
),
|
||||
)
|
||||
)
|
||||
if reassigned is not None:
|
||||
return reassigned
|
||||
decision = spec_module.can_invoke_intent(role, "open_pr", t, spec_ctx)
|
||||
if not decision.allowed:
|
||||
return Envelope.from_decision(
|
||||
decision, briefing=briefing
|
||||
).with_introspection(task=t, role=role_str)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _open_pr_failure_env(
|
||||
exc: Exception, t: Any, briefing: dict[str, Any], role_str: str
|
||||
) -> Envelope:
|
||||
"""Map an open_pr runner failure to its rejection envelope.
|
||||
|
||||
Empty-diff subtask: a branch with zero commits relative to its base
|
||||
makes GitHub 422 with "No commits between ...". open_pr can never
|
||||
succeed here (an overlapping-decomposition leaf whose work was
|
||||
delivered by the parent), so a generic invalid_state "retry" loops the
|
||||
dev forever (15x on one task in a single run). Steer to a terminal
|
||||
i_am_blocked hand-off so the PM completes/cancels the redundant leaf;
|
||||
every other failure keeps the generic retry hint.
|
||||
"""
|
||||
if "No commits between" in str(exc):
|
||||
return Envelope.invalid_state(
|
||||
message=(
|
||||
"this branch has no commits relative to its base — there is "
|
||||
"nothing to open a PR for"
|
||||
),
|
||||
remediate=(
|
||||
"do NOT retry open_pr — your branch has no diff, so this "
|
||||
"leaf's work was almost certainly delivered by its parent "
|
||||
"task. Call i_am_blocked(reason='no commits to PR — work "
|
||||
"delivered via parent') so your PM can complete or cancel "
|
||||
"this redundant leaf."
|
||||
),
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str)
|
||||
return Envelope.invalid_state(
|
||||
message=f"verb runner failed: {exc}",
|
||||
remediate="check workspace + retry; if persistent, escalate",
|
||||
context_briefing=briefing,
|
||||
).with_introspection(task=t, role=role_str)
|
||||
|
||||
async def _open_pr_success_envelope(
|
||||
self,
|
||||
agent_id: UUID,
|
||||
@@ -1646,12 +1707,35 @@ class Choreographer:
|
||||
# standard tracing/field gates beforehand.
|
||||
if str(t.status) == "verifying" and t.assigned_to == agent_id:
|
||||
return await self._i_am_done_resume_from_verifying(ctx)
|
||||
# Stale/superseded agent: the task was reassigned out from under this
|
||||
# agent (PM reassign / reaper unclaim / escalation redirect) while its
|
||||
# container kept running. Without this, the spec gate's
|
||||
# PRECONDITION_OWNERSHIP emits an owns_task *tracing_gap*, which the
|
||||
# agent reads as a fixable precondition and retries i_am_done forever
|
||||
# (41 such loops in one run). A clear "no longer yours" not_authorized
|
||||
# steers to give_me_work — terminal for this agent. (resume/unclaim
|
||||
# already do this; i_am_done did not.) Folded into the soup/spec return
|
||||
# below to stay within the return-count budget.
|
||||
reassigned = self._reassigned_rejection(
|
||||
_ReassignedCtx(
|
||||
task=t,
|
||||
agent_id=agent_id,
|
||||
task_id=task_id,
|
||||
role_str=role_str,
|
||||
briefing=briefing,
|
||||
upstream_hint=(
|
||||
"this task was reassigned away from you; you are no longer "
|
||||
"its owner. Call give_me_work() to find your current task, "
|
||||
"or i_am_idle() if there is none. Do NOT retry i_am_done."
|
||||
),
|
||||
)
|
||||
)
|
||||
# i_am_done notes is optional and supplementary (the real summary lives
|
||||
# in commits + journal:reflect), so guard it lightly — a banned token
|
||||
# ('wip'/'x') is soup, but a terse real word like 'done' is fine.
|
||||
soup = self._free_text_soup(checks=(("notes", notes, 4),))
|
||||
decision = spec_module.can_invoke_intent(role, "i_am_done", t, spec_ctx)
|
||||
if env := self._soup_or_decision_env(soup, decision, briefing):
|
||||
if env := (reassigned or self._soup_or_decision_env(soup, decision, briefing)):
|
||||
return await self._reject_i_am_done(ctx, env)
|
||||
if gate_rejection := await self._i_am_done_gate(ctx):
|
||||
return gate_rejection
|
||||
@@ -2146,6 +2230,48 @@ class Choreographer:
|
||||
return None
|
||||
return await self._build_tracing_gap(agent_id, task_id, result.missing, task=t)
|
||||
|
||||
async def _ensure_pm_decision(
|
||||
self, agent_id: UUID, task_id: UUID, rationale: str | None
|
||||
) -> None:
|
||||
"""Auto-record a journal:decision from a PM verb's own rationale.
|
||||
|
||||
The write-then-gate pattern (mirrors i_am_blocked → write_struggle):
|
||||
a PM verb that already carries a substantive rationale — complete /
|
||||
submit_up / submit_root ``notes``, escalate ``reason``, or a
|
||||
synthesized unblock context line — records it as the decision
|
||||
*before* the journal:decision tracing gate runs. A loaded or weak
|
||||
model that forgot the separate note(scope='decision') call then no
|
||||
longer stalls in a tracing_gap → respawn loop; the gate still runs
|
||||
as defense-in-depth and now passes off the just-written entry.
|
||||
|
||||
Idempotent within the decision window: when a fresh decision already
|
||||
satisfies the gate, no duplicate is written. Best-effort — a journal
|
||||
write failure is logged and swallowed so the verb falls through to
|
||||
the normal gate (which rejects as before), never crashing the verb.
|
||||
"""
|
||||
from roboco.config import settings as _settings
|
||||
|
||||
text = (rationale or "").strip()
|
||||
if not text:
|
||||
return
|
||||
try:
|
||||
latest = await self.journal.latest_decision_at(agent_id, task_id)
|
||||
window = _settings.pm_decision_window_seconds
|
||||
if (
|
||||
latest is not None
|
||||
and (datetime.now(UTC) - latest).total_seconds() <= window
|
||||
):
|
||||
return
|
||||
await self.journal.write_decision(
|
||||
agent_id=agent_id, task_id=task_id, content=text
|
||||
)
|
||||
except Exception as exc: # best-effort; gate rejects normally on failure
|
||||
logger.warning(
|
||||
"auto-record pm decision failed",
|
||||
error=str(exc),
|
||||
task_id=str(task_id),
|
||||
)
|
||||
|
||||
async def _check_pm_decision_required(
|
||||
self, verb: str, agent_id: UUID, task_id: UUID, t: Any
|
||||
) -> Envelope | None:
|
||||
@@ -3696,6 +3822,14 @@ class Choreographer:
|
||||
task_id=parent_task_id,
|
||||
verb="delegate",
|
||||
)
|
||||
# Write-then-gate: the delegated subtask's title + description (the
|
||||
# PM's own articulation of the work) is recorded as the
|
||||
# journal:decision the tracing guard below requires.
|
||||
await self._ensure_pm_decision(
|
||||
pm_agent_id,
|
||||
parent_task_id,
|
||||
f"Delegating subtask '{inputs.title}': {inputs.description}",
|
||||
)
|
||||
# Spec gate passed. Run delegate-specific guards the spec doesn't
|
||||
# model: tracing (journal:decision), chain validation, enum
|
||||
# coercion + assignee-vs-task_type, and parent-ownership/subtask-cap.
|
||||
@@ -4885,6 +5019,9 @@ class Choreographer:
|
||||
because its remediation enumerates the non-terminal subtask ids
|
||||
— strictly richer than the foundation hint.
|
||||
"""
|
||||
# Write-then-gate: the bubble-up rationale (notes, already validated
|
||||
# >= min by the ownership guard) becomes the journal:decision.
|
||||
await self._ensure_pm_decision(pm_agent_id, task_id, notes)
|
||||
if env := await self._check_submit_up_gates(pm_agent_id, task_id, notes):
|
||||
return env
|
||||
if env := await self._subtasks_not_terminal_envelope(
|
||||
@@ -5020,9 +5157,11 @@ class Choreographer:
|
||||
)
|
||||
|
||||
async def unblock(
|
||||
self, pm_agent_id: UUID, task_id: UUID, *, restore: bool = True
|
||||
self, pm_agent_id: UUID, task_id: UUID, reason: str, *, restore: bool = True
|
||||
) -> Envelope:
|
||||
"""PM unblocks task; restore=True (default) returns to pre_block_state."""
|
||||
"""PM unblocks task; ``reason`` documents why the block is cleared and
|
||||
is recorded as the journal:decision the gate requires. restore=True
|
||||
(default) returns to pre_block_state."""
|
||||
t = await self.task.get(task_id)
|
||||
if t is None:
|
||||
return await self._emit_rejection(
|
||||
@@ -5073,6 +5212,11 @@ class Choreographer:
|
||||
verb="unblock",
|
||||
)
|
||||
|
||||
# Write-then-gate: the PM's unblock reason is recorded as the
|
||||
# journal:decision the gate below requires, so a PM that didn't
|
||||
# pre-call note(scope='decision') doesn't stall in a tracing_gap
|
||||
# respawn loop.
|
||||
await self._ensure_pm_decision(pm_agent_id, task_id, reason)
|
||||
if env := await self._check_pm_decision_required(
|
||||
"unblock", pm_agent_id, task_id, t
|
||||
):
|
||||
@@ -5167,6 +5311,9 @@ class Choreographer:
|
||||
),
|
||||
context_briefing=await self._briefing_for(pm_agent_id, task_id),
|
||||
)
|
||||
# Write-then-gate: the PM's merge rationale (notes) becomes the
|
||||
# journal:decision the gate requires — no separate note() call needed.
|
||||
await self._ensure_pm_decision(pm_agent_id, task_id, notes)
|
||||
if env := await self._check_complete_gates(pm_agent_id, task_id, notes):
|
||||
return env
|
||||
if env := (
|
||||
@@ -5589,6 +5736,9 @@ class Choreographer:
|
||||
main_pm_agent_id, root_task_id
|
||||
),
|
||||
)
|
||||
# Write-then-gate: the Main PM's root-close rationale (notes) becomes
|
||||
# the journal:decision the gate requires.
|
||||
await self._ensure_pm_decision(main_pm_agent_id, root_task_id, notes)
|
||||
if env := await self._check_complete_gates(
|
||||
main_pm_agent_id, root_task_id, notes
|
||||
):
|
||||
@@ -5821,6 +5971,9 @@ class Choreographer:
|
||||
verb="escalate_up",
|
||||
)
|
||||
|
||||
# Write-then-gate: the escalation reason becomes the journal:decision
|
||||
# the preflight gate requires.
|
||||
await self._ensure_pm_decision(pm_agent_id, task_id, reason)
|
||||
preflight = await self._escalate_up_preflight(
|
||||
pm_agent_id, t, me, briefing, role_str
|
||||
)
|
||||
@@ -5994,6 +6147,9 @@ class Choreographer:
|
||||
# Verb-body preflight: journal:decision presence, then the parent-AC
|
||||
# backstop (a root may not escalate to the CEO with parent ACs that no
|
||||
# completed subtask covered — inert until coverage is declared).
|
||||
# Write-then-gate: the escalation reason becomes the journal:decision
|
||||
# the gate below requires.
|
||||
await self._ensure_pm_decision(agent_id, task_id, reason)
|
||||
env = await self._check_pm_decision_required(
|
||||
"escalate_to_ceo", agent_id, task_id, t
|
||||
) or await self._parent_acs_covered_envelope(
|
||||
|
||||
@@ -948,6 +948,37 @@ class JournalService(BaseService):
|
||||
)
|
||||
return await self.add_struggle(agent_id, params)
|
||||
|
||||
async def write_decision(
|
||||
self,
|
||||
*,
|
||||
agent_id: UUID,
|
||||
task_id: UUID,
|
||||
content: str,
|
||||
) -> JournalEntry | None:
|
||||
"""Write a DECISION_LOG entry for (agent, task) with `content` as the
|
||||
rationale body. Title is derived from the first line of content
|
||||
(truncated to 100 chars).
|
||||
|
||||
Mirrors ``write_struggle``: lets a PM verb persist a decision from
|
||||
its own rationale argument (the write-then-gate pattern) so the
|
||||
journal:decision tracing gate is satisfied without a separate
|
||||
note(scope='decision') call. The ``content`` becomes both the
|
||||
rationale and the chosen-summary so the entry reads coherently in
|
||||
journal lists and RAG retrieval.
|
||||
"""
|
||||
first_line = content.strip().splitlines()[0] if content.strip() else "Decision"
|
||||
title = first_line[:100]
|
||||
params = DecisionLogParams(
|
||||
title=title,
|
||||
context="",
|
||||
options=[],
|
||||
chosen=title,
|
||||
rationale=content,
|
||||
consequences=[],
|
||||
task_id=task_id,
|
||||
)
|
||||
return await self.add_decision_log(agent_id, params)
|
||||
|
||||
async def write_entry(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -915,7 +915,9 @@ async def test_block_then_unblock_restore(
|
||||
assert blocked.assigned_to == cell_pm_agent.id
|
||||
assert blocked.blocker_raised_by == dev_agent.id
|
||||
|
||||
env = await c.unblock(cell_pm_agent.id, task.id, restore=True)
|
||||
env = await c.unblock(
|
||||
cell_pm_agent.id, task.id, "block resolved upstream; restoring", restore=True
|
||||
)
|
||||
assert env.error is None, f"unblock failed: {env.message}"
|
||||
assert env.status == Status.IN_PROGRESS.value
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ async def test_unblock_dispatches_task_id_with_restore_true() -> None:
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/flow/cell_pm/unblock",
|
||||
json={"task_id": _TASK_ID},
|
||||
json={"task_id": _TASK_ID, "reason": "block resolved upstream; restoring"},
|
||||
headers=_HEADERS,
|
||||
)
|
||||
|
||||
@@ -107,6 +107,7 @@ async def test_unblock_dispatches_task_id_with_restore_true() -> None:
|
||||
mock_chore.unblock.assert_awaited_once()
|
||||
call_kwargs = mock_chore.unblock.call_args.kwargs
|
||||
assert call_kwargs["restore"] is True
|
||||
assert mock_chore.unblock.call_args.args[2] == "block resolved upstream; restoring"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -120,7 +121,11 @@ async def test_unblock_with_restore_false() -> None:
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/flow/cell_pm/unblock",
|
||||
json={"task_id": _TASK_ID, "restore": False},
|
||||
json={
|
||||
"task_id": _TASK_ID,
|
||||
"reason": "block resolved upstream; restoring",
|
||||
"restore": False,
|
||||
},
|
||||
headers=_HEADERS,
|
||||
)
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ async def test_unblock_dispatches_task_id_with_restore_true() -> None:
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/flow/main_pm/unblock",
|
||||
json={"task_id": _TASK_ID},
|
||||
json={"task_id": _TASK_ID, "reason": "block resolved upstream; restoring"},
|
||||
headers=_HEADERS,
|
||||
)
|
||||
|
||||
@@ -127,6 +127,7 @@ async def test_unblock_dispatches_task_id_with_restore_true() -> None:
|
||||
mock_chore.unblock.assert_awaited_once()
|
||||
call_kwargs = mock_chore.unblock.call_args.kwargs
|
||||
assert call_kwargs["restore"] is True
|
||||
assert mock_chore.unblock.call_args.args[2] == "block resolved upstream; restoring"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -559,12 +559,15 @@ async def test_i_am_done_blocks_when_journal_reflect_missing() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_i_am_done_not_assigned_returns_tracing_gap() -> None:
|
||||
"""Spec's PRECONDITION_OWNERSHIP rejects with tracing_gap (owns_task).
|
||||
async def test_i_am_done_reassigned_steers_to_give_me_work() -> None:
|
||||
"""A stale agent (task reassigned away) gets a clear not_authorized that
|
||||
steers to give_me_work — NOT the owns_task tracing_gap it would retry.
|
||||
|
||||
Pre-spec migration the verb returned not_authorized via an inline
|
||||
ownership check; that's now driven by the spec's extra precondition
|
||||
so the rejection_kind is tracing_gap.
|
||||
A reassignment short-circuit runs before the spec gate (matching
|
||||
resume/unclaim), so a superseded agent is told plainly that the task is
|
||||
no longer its own and to fetch new work, instead of reading the
|
||||
PRECONDITION_OWNERSHIP tracing_gap as a fixable precondition and looping
|
||||
i_am_done forever (the observed owns_task burn-loop).
|
||||
"""
|
||||
agent_id = uuid4()
|
||||
other_agent = uuid4()
|
||||
@@ -587,8 +590,9 @@ async def test_i_am_done_not_assigned_returns_tracing_gap() -> None:
|
||||
|
||||
env = await c.i_am_done(agent_id, task_id, "completed the work")
|
||||
body = env.as_dict()
|
||||
assert body["error"] == "tracing_gap"
|
||||
assert "owns_task" in body["missing"]
|
||||
assert body["error"] == "not_authorized"
|
||||
assert "no longer assigned" in (body.get("message") or "").lower()
|
||||
assert "give_me_work" in (body.get("remediate") or "")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -857,7 +857,7 @@ async def test_unblock_task_not_found() -> None:
|
||||
task_svc.get.return_value = None
|
||||
deps = _make_deps(task=task_svc)
|
||||
c = Choreographer(deps)
|
||||
env = await c.unblock(pm_id, task_id)
|
||||
env = await c.unblock(pm_id, task_id, "block resolved upstream; restoring")
|
||||
body = env.as_dict()
|
||||
assert body["error"] == "not_found"
|
||||
|
||||
|
||||
@@ -154,7 +154,9 @@ async def test_unblock_restores_pre_block_state() -> None:
|
||||
deps = _make_deps(task=task_svc, journal=journal_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.unblock(pm_id, task_id, restore=True)
|
||||
env = await c.unblock(
|
||||
pm_id, task_id, "block resolved upstream; restoring", restore=True
|
||||
)
|
||||
assert env.error is None
|
||||
assert env.status == "awaiting_documentation"
|
||||
task_svc.unblock_with_restore.assert_awaited_once_with(pm_id, task_id, restore=True)
|
||||
@@ -182,7 +184,7 @@ async def test_unblock_default_restores() -> None:
|
||||
c = Choreographer(deps)
|
||||
|
||||
# restore omitted -> defaults to True
|
||||
env = await c.unblock(pm_id, task_id)
|
||||
env = await c.unblock(pm_id, task_id, "block resolved upstream; restoring")
|
||||
assert env.status == "awaiting_qa"
|
||||
|
||||
|
||||
@@ -199,7 +201,7 @@ async def test_unblock_blocks_without_journal_decision() -> None:
|
||||
deps = _make_deps(task=task_svc, journal=journal_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.unblock(pm_id, task_id)
|
||||
env = await c.unblock(pm_id, task_id, "block resolved upstream; restoring")
|
||||
body = env.as_dict()
|
||||
assert body["error"] == "tracing_gap"
|
||||
assert "journal:decision" in body["missing"]
|
||||
@@ -215,7 +217,7 @@ async def test_unblock_wrong_state_returns_invalid_state() -> None:
|
||||
deps = _make_deps(task=task_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.unblock(pm_id, task_id)
|
||||
env = await c.unblock(pm_id, task_id, "block resolved upstream; restoring")
|
||||
body = env.as_dict()
|
||||
assert body["error"] == "invalid_state"
|
||||
|
||||
@@ -241,7 +243,9 @@ async def test_unblock_restore_false_returns_legacy_message() -> None:
|
||||
deps = _make_deps(task=task_svc, journal=journal_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.unblock(pm_id, task_id, restore=False)
|
||||
env = await c.unblock(
|
||||
pm_id, task_id, "block resolved upstream; restoring", restore=False
|
||||
)
|
||||
body = env.as_dict()
|
||||
assert body["status"] == "in_progress"
|
||||
assert "re-engage" in body["next"].lower()
|
||||
@@ -267,7 +271,7 @@ async def test_unblock_refused_while_a_dependency_is_unfinished() -> None:
|
||||
deps = _make_deps(task=task_svc, journal=journal_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.unblock(pm_id, task_id)
|
||||
env = await c.unblock(pm_id, task_id, "block resolved upstream; restoring")
|
||||
body = env.as_dict()
|
||||
|
||||
assert body["error"] == "invalid_state"
|
||||
|
||||
@@ -359,13 +359,13 @@ async def test_i_am_done_proceeds_when_all_gates_pass() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_i_am_done_blocks_unauthorized() -> None:
|
||||
"""Spec's PRECONDITION_OWNERSHIP rejects with tracing_gap when the
|
||||
caller does not own the task.
|
||||
"""A caller that does not own the task gets a clear not_authorized that
|
||||
steers to give_me_work — not the owns_task tracing_gap it would retry.
|
||||
|
||||
Pre-spec migration the verb returned a separate not_authorized
|
||||
envelope from an inline ownership check; the spec now drives this
|
||||
decision via PRECONDITION_OWNERSHIP, which surfaces as tracing_gap
|
||||
with the `owns_task` missing token.
|
||||
A reassignment short-circuit runs before the spec gate, so a stale /
|
||||
superseded agent is told plainly the task is no longer its own (instead
|
||||
of reading PRECONDITION_OWNERSHIP's tracing_gap as a fixable precondition
|
||||
and looping i_am_done — the observed owns_task burn-loop).
|
||||
"""
|
||||
agent_id = uuid4()
|
||||
other_id = uuid4()
|
||||
@@ -381,5 +381,6 @@ async def test_i_am_done_blocks_unauthorized() -> None:
|
||||
|
||||
env = await c.i_am_done(agent_id, task_id, "done")
|
||||
body = env.as_dict()
|
||||
assert body["error"] == "tracing_gap"
|
||||
assert "owns_task" in body["missing"]
|
||||
assert body["error"] == "not_authorized"
|
||||
assert "no longer assigned" in (body.get("message") or "").lower()
|
||||
assert "give_me_work" in (body.get("remediate") or "")
|
||||
|
||||
@@ -117,7 +117,14 @@ async def test_open_pr_pushes_and_opens_pr() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_pr_rejects_when_not_assigned() -> None:
|
||||
async def test_open_pr_reassigned_steers_to_give_me_work() -> None:
|
||||
"""A stale agent (task reassigned away) gets a clear not_authorized that
|
||||
steers to give_me_work — NOT the owns_task tracing_gap it would retry.
|
||||
|
||||
The reassignment short-circuit runs before the spec gate, so the agent
|
||||
never sees the misleading 'fixable precondition' framing that drove the
|
||||
observed open_pr owns_task retry-loops.
|
||||
"""
|
||||
aid = uuid4()
|
||||
other = uuid4()
|
||||
tid = uuid4()
|
||||
@@ -141,10 +148,48 @@ async def test_open_pr_rejects_when_not_assigned() -> None:
|
||||
|
||||
git_svc.push_branch.assert_not_awaited()
|
||||
git_svc.create_pr.assert_not_awaited()
|
||||
# Spec's PRECONDITION_OWNERSHIP surfaces as tracing_gap (owns_task missing)
|
||||
# rather than the previous bespoke not_authorized message.
|
||||
assert env.error == "tracing_gap"
|
||||
assert env.missing == ["owns_task"]
|
||||
assert env.error == "not_authorized"
|
||||
assert "no longer assigned" in (env.message or "").lower()
|
||||
assert "give_me_work" in (env.remediate or "")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_pr_empty_diff_steers_to_blocked_not_retry() -> None:
|
||||
"""An empty-diff subtask (branch has no commits vs base → GitHub 422
|
||||
'No commits between') gets a terminal i_am_blocked steer, not a generic
|
||||
'retry' invalid_state that loops the dev forever."""
|
||||
aid = uuid4()
|
||||
tid = uuid4()
|
||||
t = MagicMock(
|
||||
id=tid,
|
||||
status="in_progress",
|
||||
assigned_to=aid,
|
||||
plan="x",
|
||||
commits=[{"sha": "abc"}],
|
||||
pr_number=None,
|
||||
parent_task_id=None,
|
||||
branch_name="feature/backend/abc12345",
|
||||
)
|
||||
task_svc = AsyncMock()
|
||||
task_svc.get.side_effect = [t, t]
|
||||
task_svc.agent_for.return_value = MagicMock(role="developer", team="backend")
|
||||
_wire_savepoint(task_svc)
|
||||
git_svc = AsyncMock()
|
||||
git_svc.push_branch.return_value = ("feature/backend/abc12345", 1)
|
||||
git_svc.create_pr.side_effect = Exception(
|
||||
'GitHub API refused PR creation (422): {"message":"Validation Failed",'
|
||||
'"errors":[{"message":"No commits between feature/backend/abc12345 and '
|
||||
'feature/backend/abc12345--child"}]}'
|
||||
)
|
||||
deps = _make_deps(task=task_svc, git=git_svc)
|
||||
c = Choreographer(deps)
|
||||
|
||||
env = await c.open_pr(aid, tid)
|
||||
|
||||
assert env.error == "invalid_state"
|
||||
assert "no commits" in (env.message or "").lower()
|
||||
assert "i_am_blocked" in (env.remediate or "")
|
||||
assert "do not retry" in (env.remediate or "").lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Tests for ``_ensure_pm_decision`` — the write-then-gate auto-record.
|
||||
|
||||
A PM verb that carries a substantive rationale (complete/submit_up/
|
||||
submit_root ``notes``, escalate ``reason``, or a synthesized unblock line)
|
||||
records it as the journal:decision the tracing gate requires *before* the
|
||||
gate runs. This removes the dominant stall where a loaded/weak-model PM
|
||||
forgot the separate note(scope='decision') call and looped on a
|
||||
tracing_gap → respawn. The gate itself is unchanged (see
|
||||
test_pm_decision_window.py) — this only ensures a fresh decision exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from roboco.config import settings as _roboco_settings
|
||||
from roboco.services.gateway.choreographer import (
|
||||
Choreographer,
|
||||
ChoreographerDeps,
|
||||
)
|
||||
|
||||
|
||||
def _make_deps(**overrides: Any) -> ChoreographerDeps:
|
||||
"""Async-mock every service the Choreographer depends on."""
|
||||
base = {
|
||||
"task": AsyncMock(),
|
||||
"work_session": AsyncMock(),
|
||||
"git": AsyncMock(),
|
||||
"a2a": AsyncMock(),
|
||||
"journal": AsyncMock(),
|
||||
"audit": AsyncMock(),
|
||||
"evidence_repo": AsyncMock(),
|
||||
}
|
||||
base.update(overrides)
|
||||
task = base["task"]
|
||||
task.session = MagicMock()
|
||||
task.session.begin_nested = MagicMock(
|
||||
return_value=MagicMock(
|
||||
__aenter__=AsyncMock(return_value=None),
|
||||
__aexit__=AsyncMock(return_value=False),
|
||||
)
|
||||
)
|
||||
return ChoreographerDeps(**base)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_writes_decision_when_none_exists() -> None:
|
||||
agent_id, task_id = uuid4(), uuid4()
|
||||
journal = AsyncMock()
|
||||
journal.latest_decision_at.return_value = None
|
||||
c = Choreographer(_make_deps(journal=journal))
|
||||
|
||||
await c._ensure_pm_decision(agent_id, task_id, "Merging PR #120; all ACs verified")
|
||||
|
||||
journal.write_decision.assert_awaited_once()
|
||||
_args, kwargs = journal.write_decision.call_args
|
||||
assert kwargs["agent_id"] == agent_id
|
||||
assert kwargs["task_id"] == task_id
|
||||
assert "Merging PR #120" in kwargs["content"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skips_when_fresh_decision_already_exists() -> None:
|
||||
journal = AsyncMock()
|
||||
journal.latest_decision_at.return_value = datetime.now(UTC) - timedelta(seconds=60)
|
||||
c = Choreographer(_make_deps(journal=journal))
|
||||
|
||||
await c._ensure_pm_decision(uuid4(), uuid4(), "rationale text here")
|
||||
|
||||
journal.write_decision.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_writes_when_existing_decision_is_stale() -> None:
|
||||
journal = AsyncMock()
|
||||
journal.latest_decision_at.return_value = datetime.now(UTC) - timedelta(
|
||||
seconds=_roboco_settings.pm_decision_window_seconds + 1
|
||||
)
|
||||
c = Choreographer(_make_deps(journal=journal))
|
||||
|
||||
await c._ensure_pm_decision(uuid4(), uuid4(), "fresh rationale around this point")
|
||||
|
||||
journal.write_decision.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_noop_on_empty_rationale() -> None:
|
||||
journal = AsyncMock()
|
||||
c = Choreographer(_make_deps(journal=journal))
|
||||
|
||||
await c._ensure_pm_decision(uuid4(), uuid4(), " ")
|
||||
await c._ensure_pm_decision(uuid4(), uuid4(), None)
|
||||
|
||||
journal.latest_decision_at.assert_not_awaited()
|
||||
journal.write_decision.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_swallows_write_failure_best_effort() -> None:
|
||||
"""A journal write failure must not crash the verb — the gate then
|
||||
rejects normally (the pre-fix behaviour), never a 500."""
|
||||
journal = AsyncMock()
|
||||
journal.latest_decision_at.return_value = None
|
||||
journal.write_decision.side_effect = RuntimeError("db down")
|
||||
c = Choreographer(_make_deps(journal=journal))
|
||||
|
||||
# Must not raise.
|
||||
await c._ensure_pm_decision(uuid4(), uuid4(), "rationale that triggers a write")
|
||||
@@ -368,12 +368,16 @@ def test_unblock_with_restore_true(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
fake_client = _make_fake_client({"status": "in_progress"})
|
||||
|
||||
with patch("httpx.Client", return_value=fake_client):
|
||||
result = srv.unblock("task-uuid")
|
||||
result = srv.unblock("task-uuid", "block resolved upstream; restoring")
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
args, kwargs = fake_client.post.call_args
|
||||
assert "/api/v1/flow/cell_pm/unblock" in args[0]
|
||||
assert kwargs["json"] == {"task_id": "task-uuid", "restore": True}
|
||||
assert kwargs["json"] == {
|
||||
"task_id": "task-uuid",
|
||||
"reason": "block resolved upstream; restoring",
|
||||
"restore": True,
|
||||
}
|
||||
|
||||
|
||||
def test_unblock_with_restore_false(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@@ -384,11 +388,17 @@ def test_unblock_with_restore_false(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
fake_client = _make_fake_client({"status": "in_progress"})
|
||||
|
||||
with patch("httpx.Client", return_value=fake_client):
|
||||
result = srv.unblock("task-uuid", restore=False)
|
||||
result = srv.unblock(
|
||||
"task-uuid", "block resolved upstream; restoring", restore=False
|
||||
)
|
||||
|
||||
assert result["status"] == "in_progress"
|
||||
_args, kwargs = fake_client.post.call_args
|
||||
assert kwargs["json"] == {"task_id": "task-uuid", "restore": False}
|
||||
assert kwargs["json"] == {
|
||||
"task_id": "task-uuid",
|
||||
"reason": "block resolved upstream; restoring",
|
||||
"restore": False,
|
||||
}
|
||||
|
||||
|
||||
def test_complete_passes_notes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -115,6 +115,44 @@ async def test_write_struggle_handles_empty_content_gracefully() -> None:
|
||||
assert params.title == "Struggle"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_write_decision_calls_add_decision_log_with_task_id() -> None:
|
||||
"""write_decision delegates to add_decision_log with a DECISION_LOG entry.
|
||||
|
||||
Title comes from the first content line (truncated to 100 chars); the
|
||||
full content is carried in the rationale field so the auto-recorded
|
||||
decision reads coherently in journal lists and RAG retrieval.
|
||||
"""
|
||||
svc = JournalService(MagicMock(flush=AsyncMock()))
|
||||
add_decision_mock = AsyncMock(
|
||||
return_value=MagicMock(type=JournalEntryType.DECISION_LOG)
|
||||
)
|
||||
_bind(svc, "add_decision_log", add_decision_mock)
|
||||
agent_id = uuid4()
|
||||
task_id = uuid4()
|
||||
content = "Completing PR #120: all 3 acceptance criteria verified\nmore detail"
|
||||
out = await svc.write_decision(agent_id=agent_id, task_id=task_id, content=content)
|
||||
assert out is not None
|
||||
add_decision_mock.assert_awaited_once()
|
||||
args, _kwargs = add_decision_mock.call_args
|
||||
assert args[0] == agent_id
|
||||
params = args[1]
|
||||
assert params.task_id == task_id
|
||||
assert params.title == "Completing PR #120: all 3 acceptance criteria verified"
|
||||
assert content in params.rationale
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_write_decision_handles_empty_content_gracefully() -> None:
|
||||
svc = JournalService(MagicMock(flush=AsyncMock()))
|
||||
add_decision_mock = AsyncMock(return_value=MagicMock())
|
||||
_bind(svc, "add_decision_log", add_decision_mock)
|
||||
await svc.write_decision(agent_id=uuid4(), task_id=uuid4(), content="")
|
||||
args, _kwargs = add_decision_mock.call_args
|
||||
params = args[1]
|
||||
assert params.title == "Decision"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# latest_decision_at — windowed-satisfaction support for the PM-decision gate
|
||||
# (C8). Returns the `created_at` of the newest DECISION_LOG entry for an
|
||||
|
||||
Reference in New Issue
Block a user