Files
roboco/tests/unit/services/test_release_executor.py
T
3849c1737e feat(video): switch 0.19.0 renderer Remotion → HyperFrames (HTML-native, Apache-2.0) (#314)
* feat(video): rewrite sidecar render core to HyperFrames (in place)

* feat(video): convert motion compositions from Remotion TSX to HyperFrames HTML

* refactor(video): rename render client to video_renderer_client (renderer-agnostic)

* chore(video): rename remotion-renderer prose in test_video_pipeline docstrings

* chore(video): rename sidecar to video-renderer + add system ffmpeg for HyperFrames

* chore(video): rename stray remotion-renderer refs in sidecar + py docstrings (controller cleanup)

* chore(video): fix stale Remotion API names in Dockerfile comment (controller cleanup)

* docs(video): rewrite video-engine prose for HyperFrames + add map entry + folded prose fixes

* docs(video): add trailing newline to docs/map/video-engine.md (controller cleanup)

* chore(video): drop internal spec refs + minio/test suppressions (folded hygiene)

* fix(video): reclaim outDir on createRenderJob throw + hide empty 4th highlight

Final whole-branch review (Opus) triaged two FIX items from the SDD nits
ledger; the rest ship as-is.

- render.js: a synchronous throw from createRenderJob (post-mkdtemp, not
  awaited) left an empty outDir on disk — the outer catch only reclaimed
  extractDir. Reclaim outDir too when it exists, and correct the stale
  comment that claimed the out dir was never created.
- {vertical,square}.html: the 4th highlights <li> lived in the DOM hidden
  only by JS, so a no-JS / failed-script render would show an empty bullet.
  Start it style="display:none" and reveal on populate, so an unscripted
  render shows nothing instead.

Vitest smoke (release-announcement.test.js) 4/4 green; render.js syntax
checked. Python suite untouched by this fix (JS/HTML only).

* fix(video): type _override_db yield as AsyncSession | None

T7 widened _build_app's db_session param to AsyncSession | None (to drop the
4x # type: ignore[arg-type] on the DB-independent _build_app(None, ...) calls)
but left the inner _override_db fixture typed AsyncIterator[AsyncSession] —
so 'yield db_session' yielded AsyncSession | None into a declared AsyncSession,
and mypy failed at test_video_routes.py:177 ('Incompatible types in yield').

The DB-independent media tests pass db_session=None deliberately: their route
uses a monkeypatched task service and never awaits the session, so yielding
None is safe at runtime. Type the override's yield as AsyncSession | None to
match — no cast, no # type: ignore, no assert, runtime behavior unchanged.
The 3 media tests (3 passed) and the 19 db-gated tests (skipped locally) hold.

* chore(gate): skip .superpowers scratch in markdown prose gate

reflow_md.py walks the filesystem via rglob('*.md') and skips tooling dirs
(.venv, .mypy_cache, .pytest_cache, ...) but not .superpowers/ — the
superpowers SDD workflow's scratch dir (briefs, reports, progress ledger,
all gitignored). A dev running SDD locally would hit a false markdown-prose
gate failure on those transient files. Add .superpowers to SKIP_DIRS,
consistent with the existing tooling-scratch exclusions.

* fix(video): validate composition_id to close path traversal (CodeQL)

compositionId flowed unvalidated from the POST body into path.join
under extractDir/motion/compositions/, so a '../..'-style value could
escape the composition dir (CodeQL: Uncontrolled data used in path
expression). Validate at the trust boundary in server.js
(/^[A-Za-z0-9_-]+$/) and add a path.resolve + startsWith containment
check in render.js so it stays safe regardless of caller.

* fix(mcp): send X-Agent-Token + X-Agent-Team from flow/do servers

flow_server._build_headers and do_server._build_headers constructed
only X-Agent-ID/Role/Correlation-ID, omitting X-Agent-Token and
X-Agent-Team (unlike ApiClient._get_agent_headers used by the other
MCP servers). Latent since the gateway refactor — surfaced when
ROBOCO_AGENT_AUTH_REQUIRED=true was armed on the NAS, 401-ing every
flow/do verb with 'Missing X-Agent-Token header'. Add both headers
(mirroring ApiClient) so the HMAC gate passes. Tests assert the
headers are now injected.

* [video-engine] Per-project video_engine_enabled opt-in toggle

Mirrors ci_watch_enabled (migration 048): the global
ROBOCO_VIDEO_ENGINE_ENABLED flag arms the subsystem; the new
projects.video_engine_enabled column (migration 063) opts a repo into
authoring against its motion/ dir. VideoEngine._opted_in_project no-ops
open_video_task at the single chokepoint covering all three trigger
paths (on-release, on-spotlight, CEO on-demand) until the operator
flips it in the panel edit-project dialog. Existing projects stay
opted out (server_default=false).

* fix(auth): send X-Agent-Token + X-Agent-Team from all agent->API call sites

The prior fix (6ed4e139) covered the flow/do MCP servers but missed four
other agent->orchestrator call sites that built the header dict by hand
and omitted X-Agent-Token and/or X-Agent-Team. With ROBOCO_AGENT_AUTH_REQUIRED
armed on the NAS, every one 401s:

- agent_sdk/server.py: the session-end post-mortem flush
  (/api/journals/me/entries), A2A persistence + offline fallback
  (/api/a2a/*), and the stopped-without-transition auto-substitute
  (/api/tasks/auto-substitute) — all sent only X-Agent-ID/Role, so each
  401'd 'Missing X-Agent-Token'. Add a shared _agent_headers() helper
  (mirroring flow_server._build_headers) and route all four through it.
- agent_sdk/secretary_driver.py: _headers() sent the token but not the
  team, so the HMAC gate 401'd with signature mismatch (secretary is
  board-team; token signed with team='board', verified with team='').
  Add the team header.
- mcp/git_readonly.py: the read-only git MCP sent only X-Agent-ID/Role
  — no token, no team — so /api/git/* 401'd once auth was armed. Convert
  the static _HEADERS to a _headers() helper with team + token.
- runtime/orchestrator.py: the cell-PM auto-submit self-API call acted
  as a PM with a hand-built {X-Agent-ID, X-Agent-Role} dict — no token,
  no team — 401ing under auth-required. Add _agent_api_headers(uuid,
  role) mirroring _system_api_headers, and use it.

Tests: _agent_headers round-trip (token + team, team-omitted when None),
_agent_api_headers carries a signed PM token + team.

* [auth] Omit UNSIGNED self-call token in dev mode + video-engine test mypy fix

_agent_api_headers sent the UNSIGNED sentinel when ROBOCO_AGENT_AUTH_SECRET
was unset, but the dev-mode middleware rejects a presented-but-unverifiable
token with 401 signature mismatch (while accepting a missing one). The
cell-PM auto-submit self-call 401'd in every dev run, regressing
test_auto_submit_cuts_the_pm_turn. Attach the token only when a secret is
set. Also fix the FromClause.update mypy error in the per-project
video-engine opt-out test (ORM row load + flush).

* [auth] Omit UNSIGNED agent token at every agent->API call site

The orchestrator injects ROBOCO_AGENT_TOKEN=UNSIGNED when the HMAC secret
is unset at spawn. The API middleware rejects a presented-but-unverifiable
token with 401 'signature mismatch' even in dev mode (auth not required),
so forwarding UNSIGNED turned every flow/do/SDK/secretary/git verb into a
401 — the live pr_reviewer/i_am_idle signature-mismatch loop. Omit the
header when the token is the UNSIGNED sentinel at all five agent-side
header builders; dev accepts a missing token, prod 401s with 'Missing
X-Agent-Token' (the clear respawn-with-secret signal). Add a structlog
diagnostic on the middleware reject path so the next mismatch logs the
exact (id, role, team, token_unsigned, auth_required) inputs.

* [auth] Self-heal stale agent tokens at orchestrator startup

A token is signed once at spawn. If ROBOCO_AGENT_AUTH_SECRET drifts
afterwards (a .env change, a compose recreate that reloads the
orchestrator's env without recreating agent containers, an image
redeploy), the surviving agent keeps sending its old token and the
middleware 401s every verb with 'signature mismatch'. The container
stays alive heartbeating, so the reaper never reclaims it and no fresh
agent spawns: the fleet stalls.

_heal_stale_agent_tokens runs at startup (before _readopt_running_agents)
and kills each running agent container whose baked-in token no longer
verifies against the current secret, so normal dispatch re-spawns it
with a freshly signed token. Inert when the secret is unset (dev):
verify fails for every token without a secret, so the heal would kill
the whole fleet without this gate. Best-effort: a probe failure leaves
the container alone (the reaper still covers it).

* [auth] Sign agent token over the UUID, not the slug (pr_reviewer 401 root cause)

The token was signed over the agent slug (_append_agent_auth_env) while the
MCP servers send X-Agent-ID as the agent UUID (_generate_mcp_config, since
453a7ae2 — gateway v1 parses X-Agent-ID as Annotated[UUID]). The middleware
verified HMAC(uuid:role:team) against a slug-signed token → 'signature
mismatch', token_unsigned=false. Latent for 2 months until 6ed4e139/53391f22
made the MCP servers forward the token.

The c0328971 startup heal missed it: docker exec printenv reads the
container-level ROBOCO_AGENT_ID (the slug), so the heal verified the
slug-signed token against the slug → matched → didn't kill the stale
container, which kept 401ing (its MCP server sends the UUID).

Fix: sign the token over the UUID, set the container ROBOCO_AGENT_ID to the
UUID too (so the SDK server — which inherits container env, not the MCP
manifest env — sends UUID consistently), and resolve the container-env id to
its UUID in _heal_stale_agent_tokens so pre-fix stale containers are evicted
on next restart. Regression test: test_heal_kills_slug_env_container_with_slug_signed_token.

* [scan] gate A2A/notification/stream agent-id deps under cloud auth (C1)

* [scan] omit UNSIGNED agent token from MCP server headers (H1)

* [scan] fail loud when cloud auth and nginx CEO-token are both armed (H2)

* [scan] cache last-known-good auth-probe result in panel proxy (C2)

* [respawn] Tripped breaker self-heals after a cooldown

A DB-durable PM-respawn counter (migration 051 / e2f7097a) wedges forever
once tripped: the only reset was a task status change, which can't happen
while the breaker blocks the spawn. So a deploy that fixes the underlying
loop (auth/prompt/schema) couldn't clear the wedge without manual DELETE
surgery on respawn_tracker — the 2026-07-06 pr-reviewer-1 loop, where the
auth fix cleared the 401 but count=63 survived restart and kept skipping
the dispatcher spawn for an external-PR task.

Freeze last_check at the trip tick and, after pm_respawn_trip_cooldown_seconds
(default 300), let ONE spawn through. A still-wedged task re-trips after the
threshold (bounded re-burn ~3 spawns per window); a fixed one advances and
the status-change path fully resets. Restore re-stamps last_check to now, so
a freshly restored row still trips immediately — durability preserved, which
is why the migration-051 persistence tests still pass.

* [scan] fix test_deps callsites for cloud-auth-gate signature change (C1 followup)

* [scan] per-IP rate limit on /auth/login under cloud auth (L31)

* [scan] Phase 1 auth/security fixes under 0.19.0 CHANGELOG

* [scan] secretary token signs over real team (board) not empty — fixes /api/secretary/* 401 (L31-class)

* [scan] LoginRateLimiter: key off X-Forwarded-For first hop + redis-down fail-open test

nginx is the single entry point; request.client.host is the nginx peer IP,
collapsing every external client into one limiter bucket (self-DoS amp).
Read the downstream client IP from X-Forwarded-For (first hop) / X-Real-IP,
falling back to the peer. Adds coverage for the XFF keying, the redis-down
fail-open branch, and drops a redundant asyncio marker on a sync-TestClient
test.

* [scan] nits: describe login_max_attempts + replace cast with assert in get_current_agent_slug

login_max_attempts was the only bare cloud-auth field; add a Field
description matching the surrounding idiom. Replace cast('str', ctx.slug)
with a runtime assert that fails loud if the cloud-auth ctx invariant
breaks, and drop the now-unused cast import.

* [scan] secretary token: use get_agent_team resolver + complete spawn-shutdown mock team (0dfd45ca followup)

* [scan] require agent HMAC token under cloud_auth (close v1 flow/do header-trust)

* [scan] _require_ceo accepts CEO session cookie under cloud_auth

* [scan] HTTP require_panel_token accepts session cookie under cloud_auth

* [scan] gate /api/settings behind panel token

* [scan] gate unauthenticated /api read routes (agents/a2a-tasks/kanban/usage/rate-limits)

* [scan] hoist deferred test imports to top-level (clear PLC0415)

* [scan] Phase 1b e2e smoke + CHANGELOG

* [scan] add_dependency rejects self-reference + cycle (M18)

* [scan] WorkSessionService.create translates IntegrityError to ConflictError (H10)

* [scan] _qa_or_doc_claim locks the task row FOR UPDATE (M19)

* [scan] docs_complete + mark_pr_created lock the task row FOR UPDATE (H4)

* [scan] gate complete() IN_PROGRESS on leaf/branchless only (H3)

* [scan] _unclaim_from_blocked clears stale pre-block snapshot (H5)

* [scan] admin_set_status terminal guard + skip revision bump under force (M20)

* [scan] cell_pm_complete idempotent pre-check before merge (H7)

* [scan] wrap gateway post-runner side effects in try/except (H6)

* [scan] pass_qa/fail_qa accept AWAITING_QA only (L29)

* [scan] mark_pr_created passes audit_agent_id (L30)

* [scan] phase 2 e2e smoke - one scenario per finding

* [scan] phase 2 quality gate

ruff format + check: green
mypy roboco/: green (357 files)
pytest unit+integration: 6905 passed, 10 pre-existing DB-contamination
  failures (pass in isolation)
e2e smoke: 11 passed, 4 cross-scenario workspace-contamination failures
  (all 6 state-machine scenarios pass individually)

Quality-gate fixes:
- move function-local imports to module top (PLC0415)
- fix M19 regression: submit_for_qa clears active_claimant_id so the
  competing-claimant guard lets the QA claim through
- fix H7 regression: _StubGit gains is_pr_merged_for_task
- fix M19 unit tests: mock session.execute for the FOR UPDATE lock
- e2e H3: notes >= 20 chars; e2e H5: rich i_will_work_on inputs +
  PM unclaims (block reassigns to PM)

* [scan] move active_claimant_id clear into pass_qa/fail_qa + admin_set_status (M19 follow-on)

Phase 2 opus whole-branch review found the M19 follow-on clear lived in
the gateway wrappers (qa_pass/qa_fail) not the transition methods
(pass_qa/fail_qa) themselves. The direct REST routes POST /pass-qa and
POST /fail-qa call the transitions directly, bypassing the wrappers and
leaving the QA's stale active_claimant_id set in AWAITING_DOCUMENTATION
/ NEEDS_REVISION — the competing-claimant guard then rejects the next
legitimate documenter/QA claim. admin_set_status had the same gap for a
non-blocked override into a review/queue state (IN_PROGRESS->AWAITING_QA
left the dev's id, blocking qa_claim).

Root-cause fix: move the clear INTO pass_qa and fail_qa (mirroring
submit_for_qa), add a clear in admin_set_status when
new_status in _REVIEW_QUEUE_STATES and from_status != BLOCKED, and drop
the now-redundant clears + flushes from the qa_pass/qa_fail wrappers.
Every caller is covered; the wrappers keep their actor-mismatch warnings.

Covering tests: test_pass_qa_clears_active_claimant_for_doc_claim
(asserts a subsequent doc_claim succeeds), test_fail_qa_clears_active_claimant,
test_admin_set_status_into_review_queue_clears_active_claimant,
test_admin_set_status_non_review_queue_keeps_active_claimant. Updated
the two wrapper unit tests that asserted the wrapper clears (now the
transition's job).

* [C3] unindex_journal_entry + call from delete_entry

JournalService.delete_entry deleted the DB row but never de-indexed the
RAG chunks, so deleted/private journal content bled forever into RAG
answers and claim-time briefings. Add OptimalService.unindex_journal_entry
mirroring unindex_playbook (vector-store delete_by_source + tracking-row
delete via get_db_context, both idempotent + best-effort), and call it
from delete_entry after the row commit inside a try/except so a de-index
failure never errors the delete.

* [M25] learning_id hashes full content to avoid collision

The memory distiller emits lessons with a fixed 'Problem: …' opening
shape, so two distinct lessons whose first 100 chars match collided on
learning_id = f"lrn-{md5(content[:100])[:12]}". replace_on_reingest then
routed both to the same source URI and the second ingest's replace_chunks
DELETE wiped the first lesson's chunks — silent data loss.

Hash the full content (widening the hex slice 12→16) so distinct bodies
get distinct ids and each retains its chunks.

* [H13] reject non-internal local_llm_base_url at config load

* [M28] bulk-insert learning broadcast instead of N+1

* [M27] mark_read/mark_all_read stamp only the unread rows seen at call time

mark_read and mark_all_read used to zero the unread counter FIRST, then run
a bulk UPDATE … WHERE read_at IS NULL that stamped every inbound unread row.
A send_chat_message committing between the counter-zero and the UPDATE
inserted a new read_at NULL row that the UPDATE then stamped as read — the
new message was silently consumed while the counter stayed 0.

Mirrors get_unread_messages (same file): SELECT the unread message IDs at
call time, UPDATE exactly those IDs, then recompute the unread counter from
the DB via the existing _reset_unread_counter helper. A message arriving
mid-call is not in the selected ID set, so the UPDATE skips it and the
recomputed counter keeps it unread.

* [H12] dedup: exact to_agents predicate + purpose discriminator + ack DEL

* [M23] playbook indexed_ok/indexed_at + startup reconcile of unindexed approved

* [M24] RAG indexing dead-letter + janitor reclaim + failed_index_count health

* [L23] institutional_memory_status sentinel distinguishes below-floor/empty/error/disabled

* [L26] sweep_expired_notifications re-escalates stale unacked ack-required

* [phase3] e2e smoke + CHANGELOG for 0.19.0

* [M24] _reindex_journal_entry honors is_private (C1 review fix)

Dead-letter replay mirrors the original journal._schedule_rag_index path:
a private entry is never indexed into the shared JOURNALS corpus, and a
private learning is still recorded into LEARNINGS as non-shareable.
Previously the replay always called index_journal_entry and skipped
record_learning for private learnings, leaking private content on replay
and dropping the legitimate non-shared learning. Three regression tests.

* [H11] clone via git -c http.extraheader, not URL-embedded PAT

* [H11] _sync_read_clone fetch via http.extraheader, not URL-embedded PAT

Sibling site to the clone fix: the conventions read-clone refresh ran
'git fetch --tags <https://TOKEN@host> <branch>', exposing the PAT in the
fetch argv on the orchestrator host. Mirrors the clone site's per-call
'-c http.extraheader=Authorization: Basic …' prefix + bare URL. SSH URLs
and tokenless public repos unchanged.

* [H11] release_executor clone+push via http.extraheader; delete _inject_token_into_url

* [H8] rebase_onto_base gates on clean tree like pull

* [H9] _link_commit_to_task flushes, doesn't commit out-of-band

* [M38] _pr_is_merged returns None on HTTPError; caller assumes merged

* [M39] _cherry_unmerged_entry marker grep anchored to commit-prefix

* [L1] thread actor_agent_id through update_pr_for_task

* [H8] fix rebase test mocks for clean-tree gate

H8 inserted a 'git status --porcelain' dirty-tree gate at the top of
rebase_onto_base (mirroring pull). The 3 rebase control-flow tests mocked
_run_git with a side_effect list matching the OLD call sequence (no
leading status call), so every call shifted by one and the assertions
missed. Prepend a clean-status result to each list so the gate passes
and the fetch/checkout/reset/rebase/diff/abort/push sequence aligns.
Verified: 16 passed (was 3 failed/13 passed post-H8, 16 passed pre-H8).

* [L2] push --force-with-lease instead of bare --force

* [L1] refresh stale workspace-resolution docstrings

pr_target and _workspace_for_branch still documented the actor →
assigned_to → created_by fallback chain that L1 removed from
_resolve_workspace_agent_id. Update both to the post-L1 actor →
assigned_to → None resolver (project.workspace_path as the final
fallback) so a future reader doesn't rely on a fallback that no
longer exists.

* [M37] merge_pr locks the work_session row FOR UPDATE

* [phase4] e2e smoke + CHANGELOG for 0.19.0

* [phase4] fix M37 test flake + document H8 skip

The opus whole-branch review flagged the M37 concurrency tests as
~50% flaky: both asserted caller A wins the FOR UPDATE race, but
which caller wins the lock is non-deterministic. When B won, the
'assert a_row.merged_by == a_merger' branch flipped false even
though the production code (M37) was correct — exactly one merger
recorded, audit trail intact. Assert the invariant instead: both
rows COMPLETED, both report the same merged_by, value in
{a_merger, b_merger}. Applied to both the unit test and the e2e
twin. Also documents the H8 e2e skip in the module docstring (the
report claimed it was documented there but it wasn't) and drops
the internal 'Phase 4' label from the docstring header in favor of
the public '0.19.0' version anchor.

* [H24] wait_for_ci polls through the window on non-success

* [H25,L34] release mutex orphan-sweep on start + shared redis client

* [M1] tiktok _refresh commits rotated tokens in an independent session

* [H25] drop new type:ignore in orphan-sweep test (constraint cleanup)

* [M2] feature-spotlight re-arms when exploration stale past 2x interval with no live HoM spawn

* [M6,M7] mark_seen after meaningful+project; persist since_id cursor in redis

* [M3,M5] reject() guards COMPLETED; edited_body deferred into the single-flight lock

* [M4] bound list_completed_video_tasks + ix_tasks_source_status_created index (migration 066)

* [M8,M9,L9] pass head_sha to CI gate; _run_git 30s timeout; _commits_since split maxsplit 2

* [M10,L35] dedupe dep_update by (git_url, command); fold redundant per-project queries

* [L36] gather ci_watch telemetry sweep instead of sequential iteration

* [L11] document self_heal fingerprint is stable per-signal by design

* [M11] engine-loop liveness watchdog: heartbeat + 2x-interval staleness alert

* [M21] video render loop commits per-task, not one trailing commit

* [M22] _detect_stuck_tasks skips held-CEO-source tasks

* [L6] video_renderer_client._save writes temp + atomic rename

* [phase5] e2e smoke + CHANGELOG for 0.19.0

* [M11] instrument x_mentions + roadmap engine loops with liveness heartbeats

* [phase5] fix-wave: correct e2e M11 unit-test filename + strengthen failed-cycle heartbeat assertion

* [C4] panel WS: shared /ws/system socket + long-tail retry + pong watchdog

* [H15] video-post-queue caption derived per render (mirror x-post-queue)

* [C4-fix] panel WS: discriminating long-tail tests + drop dead freeze block + evict dead shared conn on manual disconnect

Finding 1 (Critical, websocket.test.ts): the two long-tail-retry tests fired onopen between close cycles, which reset reconnectAttempts to 0 each cycle, so they passed under the pre-fix 3-attempt gate. Rewrote both to NEVER fire onopen between closes, so attempts accumulates: test 1 asserts state stays 'reconnecting' past attempt 3 (old gate would flip 'disconnected' terminal); test 2 asserts a new socket is constructed within 30000ms at attempt 7 where uncapped 5000*1.5^7 ~= 85s (old uncapped code would leave the timer unexpired). Verified both FAIL on a reverted old-shape connection.ts and PASS on the fixed code.

Finding 2 (Important, connection.ts): the 'if (raw >= cap) this.reconnectAttempts = exp' block was a no-op (exp was just read from the same field) and the unconditional increment afterwards grew the counter regardless. Deleted the dead block; kept the Math.min cap on the delay. Replaced the misleading ponytail comment with an accurate one: delay is capped, counter grows unbounded but delay is bounded.

Finding 3 (Important, use-websocket.ts): manual disconnect() tore down the shared conn for all subscribers but left the dead (manualClose=true, never reconnects) entry in _sharedSockets, so a later mount hit the reuse branch, attached a subscriber, replayed 'disconnected', and never called connect(). Added a urlRef and _sharedSockets.delete(url) in the manual disconnect callback so a later mount reopens a fresh conn.

* [H16] settings Save wired to settingsApi (persist + read back)

* [H17] tasks page passes status/team/limit to useTasks (server-side filter)

* [H18] useAgents roster re-derives on live-status change (statusEpoch in queryKey)

* [M40] useMetrics reads agent counts from useAgentStatus cache (dedupe poll)

* [H18] tighten useAgents statusEpoch comment (drop spec ref)

* [M40] drop spec ref + tighten useMetrics comment

* [M41] scorecard refetchInterval 60s -> 5min (25 req/min -> 5)

* [M42] feature-flag off-transition confirm + pending-keys Set

* [M43] X/TikTok credentials clear-behind confirm dialog

* [M44] rate-limit syncFromApi merges (keep fresher hitAt) + A2A reconnect invalidation

* [phase6] proxy.ts cookie-check comment + CHANGELOG Fixed entries

* [phase6] drop stale WS pin-attempts comment + fix tasks-page lead-in

* [H21] type DelegateRequest.estimated_complexity as Complexity (reject critical)

* [H22] type SoftBlockRequest.resolver_type as BlockerResolverType (no silent AGENT fallback)

* [H23] serialize TaskTable.documents into TaskResponse (DocRefResponse)

* [L27] delete SubstituteRequest phantom suggested_role/suggested_team fields

* [L14] Envelope.not_found defaults remediate (guide re-fetch + re-issue)

* [L28] delete unused ListResponse generic (dead code; pagination deferred)

* [H19] _delegate_static_guards allow cell_projects roots (cross-cell MegaTask)

* [M13] MegaTask confirm-batch idempotency key from session_id (SETNX guard + result sidecar)

* [M14] strip assigned_to from MegaTask drafts (no board-owned root-subtask deadlock)

* [H20] thin_routes receiver-gate add/add_all/merge (no false block on set/cache.add)

* [M16] tighten noqa code-capture to [A-Z0-9, ]+ (no false block on natural prose)

* [M45] conventions read-clone force-refetch on read (no 30s stale map window)

* [L25] conventions._resolve returns (root, sha); ORM mutated on the event loop

* [M15] open_conventions_pr force-pushes disposable scaffold branch (no silent None)

* [L24] roadmap cycle completion emits status-transition audit

* [Phase7] CHANGELOG: 15 schema/conventions/MegaTask/API fixed (H21-H23,L27,L14,L28,H19,M13,M14,H20,M16,M45,L25,M15,L24)

* [Phase7] lint gate hygiene: shorten docstring (E501), sort imports (I001), hoist AuditLogTable import (PLC0415)

* [H14] Enable the GROK provider row in _apply_grok so routing reaches the GrokCliProvider

* [M31] Route GROK active-token resolution to usage.json so live usage reflects grok agents

* [M32] Pass cache read/write tokens to calculate_cost in the usage sweep so live cost reflects Anthropic cache spend

* [M33] Park Ollama-Cloud rate limits via a marker map so a glm-5.2:cloud 429 parks instead of crash-respawning

* [M34] Sweep orphan agent_spawn_sessions at startup so crashed-run tokens roll into usage/cost summaries

* [L12] Persist revisit_resets (migration 067) so the PM-respawn breaker's revisit counter survives a restart

* [L18] Date-gate the Sonnet-5 promo revert so billing returns to list rates after 2026-08-31

* [L20] Warn when ROBOCO_GROK_RUN_LOG yields no session id instead of silently falling back to a zero-usage env id

* [phase8] CHANGELOG: LLM provider routing, usage capture, billing fixes

* [phase8] Trailing ruff format hygiene (orchestrator marker tuples, token-sweep test signatures)

* [phase8] Fix mypy: rename GROK-branch tokens var so transcript fallback stays reachable

* [M35] Add an expiring agent-token format (iat/exp) with backward-compatible verify

* [M35] Wire agent-token TTL at spawn (config + orchestrator + grok) so tokens are bounded

* [M36] Add JWT jti claim and re-mint the sliding cookie only near expiry so a stolen cookie's exp is fixed

* [M36] Redis jti revocation: read_token rejects revoked jtis and logout revokes the current jti

* [phase9] CHANGELOG: bound agent tokens + sliding-cookie re-mint window + jti revocation

* [scan-fix] mypy: type-annotate test files for make-quality gate

CI's make quality runs mypy roboco/ tests/; the scan-fix program's local
gate ran mypy roboco/ only, so test files were never type-checked. Fix all
67 errors across 23 test files with real annotations/casts/asserts/dead-code
removal — no # type: ignore / # noqa added.

* [e2e] Per-test DB isolation + dispatcher re-claim before PM complete

* [scan] Regenerate verb tables for delegate Complexity type

* [scan] Reduce 9 xenon C-ranks to B (auth, orchestrator, gateway, services)

* [scan] Restore short-circuit time.time() in verify_agent_token (security path)

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-07 10:09:23 +02:00

536 lines
19 KiB
Python

"""ReleaseExecutor: fail-closed bump → gate → commit → CI → publish (post-approval).
The executor's correctness is its ORDERING + fail-closed aborts: a red gate
aborts before any commit, a red release-commit CI aborts before publish, and a
green path publishes exactly once. Tested against a fake ops that records the
call sequence; the production git/gh ops is exercised live (CEO-gated).
"""
from __future__ import annotations
import base64
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
import pytest
from roboco.config import settings
from roboco.services import release_executor as re
from roboco.services.release_executor import (
ReleaseExecutor,
ReleaseResult,
_GitReleaseOps,
_ReleaseContext,
_resolve_release_ci_workflow,
)
from roboco.services.release_readiness import ReleaseReadinessReport
if TYPE_CHECKING:
from pathlib import Path
_PLAN = ["pyproject.toml", "roboco/__init__.py", "CHANGELOG.md"]
_VERSION = "0.13.0"
_ONE = 1
def _report() -> ReleaseReadinessReport:
return ReleaseReadinessReport(
proposed_version=_VERSION,
bump_kind="minor",
change_summary=["feat: a thing"],
drafted_changelog=(
f"## [{_VERSION}] - 2026-06-25\n\n### Added\n- a thing (#1)\n"
),
version_bump_plan=list(_PLAN),
gaps=[],
migration_notes=[],
gate_state="green",
)
class _FakeOps:
"""Records the call sequence; flags drive gate/CI/already-published outcomes."""
def __init__(
self,
*,
already: bool = False,
gate: bool = True,
ci: bool = True,
commit_raises: str | None = None,
publish_raises: str | None = None,
):
self._already = already
self._gate = gate
self._ci = ci
self._commit_raises = commit_raises
self._publish_raises = publish_raises
# Half-landed (publish_failed retry) detection: a prior
# ``chore(release): {version}`` commit already on the branch. Set on the
# instance (not via __init__ — keeps the constructor under the arg-count
# gate) by tests that exercise the retry path.
self._existing_sha: str | None = None
self.calls: list[str] = []
self.bumped_plan: list[str] | None = None
self.bumped_version: str | None = None
self.halflanded_check = False
async def is_already_published(self, _version: str) -> bool:
self.calls.append("check")
return self._already
async def release_commit_sha(self, _version: str) -> str | None:
# Half-landed detection: a prior `chore(release): {version}` commit
# already on the branch means a publish_failed retry must NOT re-run the
# bump→changelog→gate→commit pipeline. Recorded via a flag (not calls)
# so the green-path call-sequence assertion is unaffected.
self.halflanded_check = True
return self._existing_sha
async def apply_version_bumps(self, plan: list[str], new_version: str) -> list[str]:
self.calls.append("bump")
self.bumped_plan = list(plan)
self.bumped_version = new_version
return list(plan)
async def write_changelog_entry(self, _entry: str) -> None:
self.calls.append("changelog")
async def run_gate(self) -> bool:
self.calls.append("gate")
return self._gate
async def commit_and_push(self, _version: str) -> str:
self.calls.append("commit")
if self._commit_raises is not None:
raise RuntimeError(self._commit_raises)
return "deadbeef"
async def wait_for_ci(self, _commit_sha: str) -> bool:
self.calls.append("ci")
return self._ci
async def publish_release(self, version: str, _notes: str) -> str:
self.calls.append("publish")
if self._publish_raises is not None:
raise RuntimeError(self._publish_raises)
return f"https://github.com/x/roboco/releases/tag/v{version}"
@pytest.mark.asyncio
async def test_green_path_publishes_once() -> None:
ops = _FakeOps()
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "published"
assert result.release_url is not None
assert result.commit_sha == "deadbeef"
assert ops.calls.count("publish") == _ONE
assert ops.calls == [
"check",
"bump",
"changelog",
"gate",
"commit",
"ci",
"publish",
]
@pytest.mark.asyncio
async def test_bump_targets_the_canonical_set() -> None:
ops = _FakeOps()
result = await ReleaseExecutor(ops).execute(_report())
assert ops.bumped_plan == _PLAN
assert ops.bumped_version == _VERSION
assert result.files_changed == _PLAN
@pytest.mark.asyncio
async def test_red_gate_aborts_before_commit() -> None:
ops = _FakeOps(gate=False)
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "gate_failed"
assert "commit" not in ops.calls
assert "publish" not in ops.calls
@pytest.mark.asyncio
async def test_red_ci_aborts_before_publish() -> None:
ops = _FakeOps(ci=False)
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "ci_failed"
assert "commit" in ops.calls
assert "publish" not in ops.calls
@pytest.mark.asyncio
async def test_already_published_is_a_noop() -> None:
ops = _FakeOps(already=True)
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "already_published"
assert "bump" not in ops.calls
assert "commit" not in ops.calls
assert "publish" not in ops.calls
@pytest.mark.asyncio
async def test_commit_push_failure_returns_structured_commit_failed() -> None:
"""#88: a RuntimeError from commit_and_push (gpgsign/pre-commit/non-ff
push) becomes a structured ``commit_failed`` result — not a 500 bubbling
out of ``approve``. Fail-closed: publish never runs."""
ops = _FakeOps(commit_raises="release push failed: non-fast-forward")
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "commit_failed"
assert result.commit_sha is None
assert result.release_url is None
assert "commit_failed" in result.detail or "push failed" in result.detail
assert "publish" not in ops.calls
assert "ci" not in ops.calls
@pytest.mark.asyncio
async def test_publish_failure_returns_structured_publish_failed() -> None:
"""#88: a RuntimeError from ``gh release create`` (auth/quota/network) becomes
a structured ``publish_failed`` result. The commit is already pushed and CI
is green, so the release is half-landed — the CEO can retry ``gh release
create`` for the same version (the executor is idempotent on the commit
side). No 500."""
ops = _FakeOps(publish_raises="gh release create failed: forbidden")
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "publish_failed"
assert result.commit_sha == "deadbeef"
assert result.release_url is None
assert "gh release create failed" in result.detail
assert ops.calls.count("publish") == _ONE
def test_release_result_carries_outcome_fields() -> None:
result = ReleaseResult(
status="published",
version=_VERSION,
files_changed=list(_PLAN),
commit_sha="abc",
release_url="https://example/releases/v0.13.0",
detail="ok",
)
assert result.version == _VERSION
assert result.files_changed == _PLAN
assert result.release_url is not None
@pytest.mark.asyncio
async def test_half_landed_retry_skips_bump_and_republishes_only() -> None:
"""#87: a publish_failed retry (commit pushed + CI green, no tag yet) must
NOT re-run bump/changelog/gate/commit — that would re-insert the changelog
entry above the already-present ``## [X.Y.Z]`` heading (duplicate) and land a
second ``chore(release): X.Y.Z`` commit. The executor detects the
half-landed state via ``release_commit_sha`` (a prior release commit already
on the branch) and jumps straight to wait_for_ci + publish."""
ops = _FakeOps()
ops._existing_sha = "existingbeef"
result = await ReleaseExecutor(ops).execute(_report())
assert result.status == "published"
assert result.commit_sha == "existingbeef"
assert result.release_url is not None
assert ops.halflanded_check is True
assert "bump" not in ops.calls
assert "changelog" not in ops.calls
assert "gate" not in ops.calls
assert "commit" not in ops.calls
assert ops.calls == ["check", "ci", "publish"]
@pytest.mark.asyncio
async def test_wait_for_ci_scoped_to_release_commit_not_branch_latest(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""#318: a later commit landing on master during the ~40min wait must not
mask the release commit's green CI. ``wait_for_ci`` scopes the GitHub query
to the release commit_sha (``head_sha=``), so the branch-latest run (a later
sha) can't make the gate poll forever and false-fail as ci_failed."""
commit_sha = "release_commit_abc"
later_sha = "later_landed_def"
async def _fake_get_ci(_slug: str, **_kwargs: object) -> dict[str, str]:
# Mimic GitHub's head_sha filter: a run for the release sha only when
# asked for it (head_sha=commit_sha); the branch-latest (later commit)
# run otherwise. The release gate MUST scope to commit_sha to see green.
if _kwargs.get("head_sha") == commit_sha:
return {
"head_sha": commit_sha,
"conclusion": "success",
"run_url": "u",
"run_name": "n",
"branch": "master",
"completed_at": "t",
}
return {
"head_sha": later_sha,
"conclusion": "success",
"run_url": "u2",
"run_name": "n2",
"branch": "master",
"completed_at": "t2",
}
monkeypatch.setattr(
"roboco.services.git.get_git_service",
lambda _session: SimpleNamespace(get_latest_ci_conclusion=_fake_get_ci),
)
monkeypatch.setattr(re, "_CI_MAX_POLLS", 2)
async def _no_sleep(_secs: float) -> None:
return None
monkeypatch.setattr(re.asyncio, "sleep", _no_sleep)
ctx = _ReleaseContext(
slug="roboco-api",
default_branch="master",
root=tmp_path,
git_url="x",
git_prefix=[],
ci_workflow="ci.yml",
)
ops = _GitReleaseOps(session=MagicMock(), ctx=ctx)
ok = await ops.wait_for_ci(commit_sha)
assert ok is True
@pytest.mark.asyncio
async def test_wait_for_ci_polls_through_rerun(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A completed non-success conclusion on the release sha must not abort the
poll — a failed first attempt while a GitHub re-run is still in_progress
(excluded from the status=completed filter) can still flip the same
head_sha to success. Only ``conclusion == "success"`` returns True; loop
exhaustion returns False."""
commit_sha = "release_commit_abc"
seq = ["failure", "failure", "success"]
expected_polls = len(seq)
calls = {"n": 0}
async def _fake_get_ci(_slug: str, **kwargs: object) -> dict[str, object]:
i = min(calls["n"], len(seq) - 1)
calls["n"] += 1
return {
"head_sha": kwargs.get("head_sha", commit_sha),
"conclusion": seq[i],
"run_url": "u",
"run_name": "n",
"branch": "master",
"completed_at": "t",
}
monkeypatch.setattr(
"roboco.services.git.get_git_service",
lambda _session: SimpleNamespace(get_latest_ci_conclusion=_fake_get_ci),
)
monkeypatch.setattr(re, "_CI_MAX_POLLS", 5)
async def _no_sleep(_secs: float) -> None:
return None
monkeypatch.setattr(re.asyncio, "sleep", _no_sleep)
ctx = _ReleaseContext(
slug="roboco-api",
default_branch="master",
root=tmp_path,
git_url="x",
git_prefix=[],
ci_workflow="ci.yml",
)
ops = _GitReleaseOps(session=MagicMock(), ctx=ctx)
ok = await ops.wait_for_ci(commit_sha)
assert ok is True
assert calls["n"] == expected_polls
@pytest.mark.asyncio
async def test_wait_for_ci_exhausts_window_on_persistent_failure(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A definitive failure that never re-runs waits the full window then
returns False — keeps polling, never early-returns on non-success."""
commit_sha = "release_commit_abc"
max_polls = 3
calls = {"n": 0}
async def _fake_get_ci(_slug: str, **kwargs: object) -> dict[str, object]:
calls["n"] += 1
return {
"head_sha": kwargs.get("head_sha", commit_sha),
"conclusion": "failure",
"run_url": "u",
"run_name": "n",
"branch": "master",
"completed_at": "t",
}
monkeypatch.setattr(
"roboco.services.git.get_git_service",
lambda _session: SimpleNamespace(get_latest_ci_conclusion=_fake_get_ci),
)
monkeypatch.setattr(re, "_CI_MAX_POLLS", max_polls)
async def _no_sleep(_secs: float) -> None:
return None
monkeypatch.setattr(re.asyncio, "sleep", _no_sleep)
ctx = _ReleaseContext(
slug="roboco-api",
default_branch="master",
root=tmp_path,
git_url="x",
git_prefix=[],
ci_workflow="ci.yml",
)
ops = _GitReleaseOps(session=MagicMock(), ctx=ctx)
ok = await ops.wait_for_ci(commit_sha)
assert ok is False
assert calls["n"] == max_polls
def test_release_ci_workflow_decoupled_from_self_heal_setting(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""#402: the release CI gate must not inherit ``self_heal_ci_workflow``'s
empty-string tuning (documented valid for single-workflow repos), which would
degrade the fail-closed gate to the all-workflows mode git.py itself flags as
unreliable. The release gate always resolves a named workflow (default
``ci.yml``), never None."""
# The dangerous tuning an operator might apply for self-heal on a
# single-workflow repo — must NOT leak into the release gate.
monkeypatch.setattr(settings, "self_heal_ci_workflow", "")
monkeypatch.setattr(settings, "release_ci_workflow", "ci.yml")
assert _resolve_release_ci_workflow() == "ci.yml"
monkeypatch.setattr(settings, "release_ci_workflow", "release.yml")
assert _resolve_release_ci_workflow() == "release.yml"
# An empty release setting never falls through to None — always the default.
monkeypatch.setattr(settings, "release_ci_workflow", "")
assert _resolve_release_ci_workflow() == "ci.yml"
# --------------------------------------------------------------------------- #
# H11: the PAT must never appear in a git subprocess argv. The release clone
# and the release push carry the token via ``-c http.extraheader=Authorization:
# Basic <base64(x-access-token:TOKEN)>`` and a bare URL — never URL-embedded.
# --------------------------------------------------------------------------- #
def _basic_auth(token: str) -> str:
return base64.b64encode(f"x-access-token:{token}".encode()).decode()
class _DoneProc:
"""A subprocess that completes immediately with a fixed rc + stdout."""
def __init__(self, out: bytes = b"", returncode: int = 0) -> None:
self.returncode = returncode
self._out = out
async def communicate(self) -> tuple[bytes, bytes]:
return (self._out, b"")
def kill(self) -> None:
return None
async def wait(self) -> int:
return self.returncode
@pytest.mark.asyncio
async def test_release_clone_argv_uses_extraheader_not_url_token(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""H11: the release-clone argv carries the PAT via ``-c http.extraheader``,
never URL-embedded (``/proc/<pid>/cmdline`` would expose a URL token)."""
token = "ghp_SECRETCLONE"
git_url = "https://github.com/org/roboco.git"
expected_basic = _basic_auth(token)
git_prefix = ["-c", f"http.extraheader=Authorization: Basic {expected_basic}"]
captured: list[list[str]] = []
async def _exec(*args: str, **_kwargs: object) -> _DoneProc:
captured.append(list(args))
return _DoneProc()
monkeypatch.setattr(re.asyncio, "create_subprocess_exec", _exec)
monkeypatch.setattr(settings, "workspaces_root", str(tmp_path))
await re._prepare_release_clone("roboco-api", git_url, git_prefix, "master")
clone_argv = next(a for a in captured if "clone" in a)
assert f"https://{token}@" not in " ".join(clone_argv), (
f"raw token leaked into clone argv URL: {clone_argv}"
)
assert token not in clone_argv, f"raw token in clone argv: {clone_argv}"
assert git_url in clone_argv, f"bare git_url missing from clone argv: {clone_argv}"
assert "-c" in clone_argv
c_idx = clone_argv.index("-c")
assert (
clone_argv[c_idx + 1]
== f"http.extraheader=Authorization: Basic {expected_basic}"
)
assert "clone" in clone_argv[c_idx + 2 :]
@pytest.mark.asyncio
async def test_release_push_argv_uses_extraheader_not_url_token(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""H11: the release push argv carries the PAT via ``-c http.extraheader``
and pushes to the bare URL — never ``https://TOKEN@host/...``."""
token = "ghp_SECRETPUSH"
git_url = "https://github.com/org/roboco.git"
expected_basic = _basic_auth(token)
git_prefix = ["-c", f"http.extraheader=Authorization: Basic {expected_basic}"]
captured: list[list[str]] = []
# commit_and_push issues: add -A, commit -S -m, rev-parse HEAD, push.
responses = iter(
[
_DoneProc(b""), # add -A
_DoneProc(b""), # commit
_DoneProc(b"deadbeef\n"), # rev-parse HEAD
_DoneProc(b"ok"), # push
]
)
async def _exec(*args: str, **_kwargs: object) -> _DoneProc:
captured.append(list(args))
return next(responses)
monkeypatch.setattr(re.asyncio, "create_subprocess_exec", _exec)
ctx = _ReleaseContext(
slug="roboco-api",
default_branch="master",
root=tmp_path,
git_url=git_url,
git_prefix=git_prefix,
ci_workflow=None,
)
ops = _GitReleaseOps(session=MagicMock(), ctx=ctx)
sha = await ops.commit_and_push("0.13.0")
assert sha == "deadbeef"
push_argv = next(a for a in captured if "push" in a)
assert f"https://{token}@" not in " ".join(push_argv), (
f"raw token leaked into push argv URL: {push_argv}"
)
assert token not in push_argv, f"raw token in push argv: {push_argv}"
assert git_url in push_argv, f"bare git_url missing from push argv: {push_argv}"
assert "-c" in push_argv
c_idx = push_argv.index("-c")
assert (
push_argv[c_idx + 1]
== f"http.extraheader=Authorization: Basic {expected_basic}"
)
assert "push" in push_argv[c_idx + 2 :]