Files
roboco/tests/unit/services/test_prompter.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

1563 lines
56 KiB
Python

"""Unit tests for PrompterService.
Covers the live-intake draft → task flow (``create_task_from_draft`` /
``confirm_live_draft`` + the enum/priority/team coercion) and the pure
draft/description helpers. DB-backed tests use an in-memory async session via
conftest fixtures.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import patch
from uuid import UUID, uuid4
import pytest
from sqlalchemy import select
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
from roboco.db.tables import (
AgentTable,
ProductTable,
ProjectTable,
TaskTable,
)
from roboco.models.base import (
AgentRole,
AgentStatus,
Complexity,
TaskNature,
TaskStatus,
TaskType,
Team,
)
from roboco.seeds.initial_data import AGENT_UUIDS
from roboco.services import prompter as prompter_module
from roboco.services.base import ServiceError, ValidationError
from roboco.services.prompter import (
_HISTORY_DIGEST_PER_PROJECT_LIMIT,
_HISTORY_TITLE_EXCERPT_CAP,
PrompterService,
_cell_teams,
_clean_list,
_draft_cell_map,
_task_activity_date,
_title_excerpt,
build_history_digest,
compact_task_rows,
compose_description,
derive_scale,
get_prompter_service,
history_digest_layer,
parse_readiness,
)
# =============================================================================
# Pure function tests (no DB)
# =============================================================================
def test_parse_readiness_extracts_and_strips_tag() -> None:
content = (
"Here is my question about scope.\n\n"
'```roboco-meta\n{"covered": ["objective", "scope"], '
'"ready": true, "scale": "multi"}\n```'
)
clean, tag = parse_readiness(content)
assert clean == "Here is my question about scope."
assert tag is not None
assert tag.ready is True
assert tag.scale == "multi"
assert tag.covered == ["objective", "scope"]
# The control block must not leak into the user-visible text.
assert "roboco-meta" not in clean
def test_parse_readiness_absent_block_is_not_ready() -> None:
clean, tag = parse_readiness("Just a plain reply, no control block.")
assert clean == "Just a plain reply, no control block."
assert tag is None
def test_parse_readiness_malformed_json_is_graceful() -> None:
content = "Reply text.\n```roboco-meta\n{not valid json]\n```"
clean, tag = parse_readiness(content)
assert "roboco-meta" not in clean
assert clean == "Reply text."
assert tag is None
def test_parse_readiness_uses_last_block() -> None:
content = (
'```roboco-meta\n{"ready": false, "scale": "single"}\n```\n'
"Final answer.\n"
'```roboco-meta\n{"ready": true, "scale": "multi"}\n```'
)
clean, tag = parse_readiness(content)
assert tag is not None
assert tag.ready is True
assert tag.scale == "multi"
assert "roboco-meta" not in clean
def test_derive_scale_single_vs_multi() -> None:
assert derive_scale([{"team": "backend"}]) == "single"
assert derive_scale([{"team": "backend"}, {"team": "frontend"}]) == "multi"
# Non-cell teams (e.g. main_pm) do not count toward cell breadth.
assert derive_scale([{"team": "backend"}, {"team": "main_pm"}]) == "single"
assert derive_scale([]) == "single"
# -----------------------------------------------------------------------------
# the_work shape tolerance — the intake agent is an LLM and sometimes emits
# the_work as a list of bare team-name strings ("backend") instead of the
# documented {team, summary, items} objects. Every consumer must tolerate that
# without raising (regression: preview-batch used to 500 with
# "'str' object has no attribute 'get'").
# -----------------------------------------------------------------------------
def test_cell_teams_tolerates_bare_string_entries() -> None:
# The LLM emitted the_work as a list of team names, not objects.
assert _cell_teams(["backend", "frontend", "backend"]) == ["backend", "frontend"]
# A bare string that isn't a cell is skipped, just like a non-cell dict.
assert _cell_teams(["backend", "main_pm"]) == ["backend"]
assert _cell_teams(["nonsense"]) == []
def test_lead_cell_team_tolerates_bare_string_entries() -> None:
draft = {"the_work": ["frontend", "backend"]}
assert PrompterService._lead_cell_team(draft, default=Team.BACKEND) is Team.FRONTEND
# First valid cell wins; an invalid bare string is skipped.
draft = {"the_work": ["nonsense", "ux_ui"]}
assert PrompterService._lead_cell_team(draft, default=Team.BACKEND) is Team.UX_UI
def test_derive_scale_tolerates_bare_string_entries() -> None:
assert derive_scale(["backend"]) == "single"
assert derive_scale(["backend", "frontend"]) == "multi"
def test_compose_description_renders_bare_string_work_entries() -> None:
draft = {
"objective": "Fix the intake batch preview.",
"the_work": ["backend", "frontend"],
"acceptance_criteria": ["Preview no longer 500s"],
}
md = compose_description(draft)
# Each bare string renders as a cell heading; multi-cell gets the board-led line.
assert "## The Work" in md
assert "**Backend**" in md
assert "**Frontend**" in md
assert "Board-led" in md
def test_compose_description_single_cell_markdown() -> None:
draft = {
"objective": "Let humans track token usage.",
"what_this_builds": ["A usage panel on the Metrics page"],
"the_work": [
{
"team": "frontend",
"summary": "Render the usage panel",
"items": ["Add the chart", "Wire the API"],
}
],
"notes": ["Reuse the existing Metrics layout"],
"acceptance_criteria": ["Panel shows totals", "Panel filters by range"],
}
md = compose_description(draft)
assert "## Objective" in md
assert "## What This Builds" in md
assert "## The Work" in md
assert "**Frontend** — Render the usage panel" in md
assert "## Notes" in md
assert "## Success Criteria" in md
assert "- Panel shows totals" in md
# Single-cell tasks get no board-led lead line.
assert "Board-led" not in md
def test_compose_description_multi_cell_has_board_led_lead() -> None:
draft = {
"objective": "Ship the Prompter.",
"the_work": [
{"team": "backend", "summary": "Chat endpoint", "items": []},
{"team": "frontend", "summary": "Chat UI", "items": []},
{"team": "ux_ui", "summary": "Interaction design", "items": []},
],
"acceptance_criteria": ["It works end to end"],
}
md = compose_description(draft)
assert "Board-led" in md
assert "**Backend**" in md
assert "**UX/UI**" in md
def test_compose_description_falls_back_to_provided_description() -> None:
# Sparse structured fields → fall back to a model-provided description.
draft = {"description": "A perfectly adequate fallback description here."}
md = compose_description(draft)
assert md == "A perfectly adequate fallback description here."
def test_lead_cell_team_prefers_the_work_cell() -> None:
draft = {"the_work": [{"team": "frontend"}], "team": "backend"}
assert PrompterService._lead_cell_team(draft, default=Team.BACKEND) is Team.FRONTEND
# Empty the_work falls back to the provided default.
assert PrompterService._lead_cell_team({}, default=Team.BACKEND) is Team.BACKEND
def test_lead_cell_team_skips_invalid_cell_names() -> None:
# An off-enum cell name is skipped, not raised on; falls through to a valid one.
draft = {"the_work": [{"team": "nonsense"}, {"team": "frontend"}]}
assert PrompterService._lead_cell_team(draft, default=Team.BACKEND) is Team.FRONTEND
def test_coerce_draft_enums_defaults_invalid_values() -> None:
# Regression: the LLM emits off-enum values (e.g. task_type="feature"). The
# confirm must coerce to defaults, never raise — a bad enum guess must not
# 400 the launch and force the agent to self-correct in-chat.
draft = {
"team": "backend",
"task_type": "feature", # not a valid TaskType
"nature": "bogus", # not a valid TaskNature
"estimated_complexity": "enormous", # not a valid Complexity
}
team, task_type, nature, complexity = PrompterService._coerce_draft_enums(draft)
assert team is Team.BACKEND
assert task_type is TaskType.CODE
assert nature is TaskNature.TECHNICAL
assert complexity is Complexity.MEDIUM
def test_coerce_priority_maps_words_clamps_and_defaults() -> None:
# Regression: priority is the one non-enum field the agent guesses, and it
# guesses a word ("high") as often as a number — int("high") used to 500.
# word/number -> expected priority int (0=urgent .. 3=low).
cases: dict[object, int] = {
"urgent": 0,
"high": 1,
"medium": 2,
"low": 3,
1: 1,
"3": 3,
99: 3, # clamped into range
"nonsense": 2, # unrecognized -> default medium
None: 2, # missing -> default medium
}
for value, expected in cases.items():
assert PrompterService._coerce_priority(value) == expected
def test_coerce_draft_enums_keeps_valid_and_derives_missing_team() -> None:
# Valid values pass through; a missing team is derived from the_work.
draft = {
"task_type": "documentation",
"nature": "technical",
"estimated_complexity": "medium",
"the_work": [{"team": "frontend"}],
}
team, task_type, nature, complexity = PrompterService._coerce_draft_enums(draft)
assert team is Team.FRONTEND
assert task_type is TaskType.DOCUMENTATION
assert nature is TaskNature.TECHNICAL
assert complexity is Complexity.MEDIUM
# =============================================================================
# Factory
# =============================================================================
def test_get_prompter_service_no_db() -> None:
service = get_prompter_service()
assert isinstance(service, PrompterService)
assert service._db is None
def test_get_prompter_service_raises_without_db_for_session_methods() -> None:
service = get_prompter_service()
with pytest.raises(ServiceError, match="DB session"):
_ = service._session
# =============================================================================
# DB-backed: assignee routing + confirm_live_draft
# =============================================================================
@pytest.mark.asyncio
async def test_assignee_is_board_distinguishes_roles(db_session: Any) -> None:
"""Drives product team routing: a board reviewer keeps the root on the board.
A product confirmed via "Board review & Start" is assigned to a board
reviewer and must stay team=board so the CEO's Approve & Start gate appears;
one assigned to main-pm (or a cell dev) is not a board task.
"""
service = get_prompter_service(db=db_session)
def _agent(role: AgentRole) -> AgentTable:
return AgentTable(
id=uuid4(),
name="A",
slug=f"a-{uuid4().hex[:8]}",
role=role,
team=None,
status=AgentStatus.ACTIVE,
model_config={},
system_prompt="x",
capabilities=[],
permissions={},
metrics={},
)
po = _agent(AgentRole.PRODUCT_OWNER)
hom = _agent(AgentRole.HEAD_MARKETING)
dev = _agent(AgentRole.DEVELOPER)
db_session.add_all([po, hom, dev])
await db_session.flush()
assert await service._assignee_is_board(cast("UUID", po.id)) is True
assert await service._assignee_is_board(cast("UUID", hom.id)) is True
assert await service._assignee_is_board(cast("UUID", dev.id)) is False
# Unknown id is not a board agent — defensive, must not raise.
assert await service._assignee_is_board(uuid4()) is False
async def _seed_project_and_ceo(db_session: Any) -> tuple[UUID, UUID]:
"""Seed a system agent + project + CEO; return (project_id, ceo_id).
Returns plain ``UUID``s (not the ORM rows) so callers pass real uuids to the
service — no casting the ORM ``.id`` column type at the call site.
"""
system_id, project_id, ceo_id = uuid4(), uuid4(), uuid4()
system = AgentTable(
id=system_id,
name="System",
slug=f"system-{uuid4().hex[:8]}",
role=AgentRole.SYSTEM,
team=None,
status=AgentStatus.ACTIVE,
model_config={},
system_prompt="system",
capabilities=[],
permissions={},
metrics={},
)
db_session.add(system)
await db_session.flush()
project = ProjectTable(
id=project_id,
name="Intake Test Project",
slug=f"intake-{uuid4().hex[:8]}",
git_url="https://github.com/example/intake.git",
default_branch="main",
protected_branches=["main"],
assigned_cell=Team.BACKEND,
created_by=system_id,
is_active=True,
)
ceo = AgentTable(
id=ceo_id,
name="CEO",
slug=f"ceo-{uuid4().hex[:8]}",
role=AgentRole.CEO,
team=None,
status=AgentStatus.ACTIVE,
model_config={},
system_prompt="ceo",
capabilities=[],
permissions={},
metrics={},
)
db_session.add_all([project, ceo])
await db_session.flush()
# The "& Start" routes assign the draft to a fixed board/PM agent
# (product-owner for "Board review", main-pm for "Approve & Start"); those
# rows must exist for the assigned_to FK. merge() is idempotent, so this is
# safe whether or not another test already committed them on the shared DB.
for slug, role, team in (
("product-owner", AgentRole.PRODUCT_OWNER, None),
("main-pm", AgentRole.MAIN_PM, Team.MAIN_PM),
):
await db_session.merge(
AgentTable(
id=UUID(AGENT_UUIDS[slug]),
name=slug,
slug=slug,
role=role,
team=team,
status=AgentStatus.ACTIVE,
model_config={},
system_prompt=slug,
capabilities=[],
permissions={},
metrics={},
)
)
await db_session.flush()
return project_id, ceo_id
@pytest.mark.asyncio
async def test_confirm_live_draft_board_route_assigns_po(db_session: Any) -> None:
""" "Board review & Start" (default route) → PENDING, assigned to the Product
Owner so the orchestrator fires the PO + HoM review."""
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
draft = {
"title": "Add token metrics",
"objective": "See token usage at a glance.",
"acceptance_criteria": ["Dashboard shows total tokens"],
"team": "backend",
"the_work": [
{"team": "backend", "summary": "instrument", "items": ["count tokens"]}
],
}
task_id = await service.confirm_live_draft(draft, ceo_id, project_id=project_id)
row = await db_session.get(TaskTable, task_id)
assert row is not None
assert row.status == TaskStatus.PENDING # "& Start" — started now
assert row.assigned_to == UUID(AGENT_UUIDS["product-owner"]) # board review
assert row.source == "prompter"
assert row.confirmed_by_human is True
assert row.team == Team.BACKEND # lead cell from the_work
assert row.created_by == ceo_id
assert row.nature is not None and row.task_type is not None
@pytest.mark.asyncio
async def test_confirm_live_draft_main_pm_route_assigns_main_pm(
db_session: Any,
) -> None:
""" "Approve & Start" (route="main_pm") → PENDING, assigned to the Main PM."""
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
draft = {
"title": "Quick fix",
"acceptance_criteria": ["done"],
"team": "backend",
}
task_id = await service.confirm_live_draft(
draft, ceo_id, project_id=project_id, route="main_pm"
)
row = await db_session.get(TaskTable, task_id)
assert row.status == TaskStatus.PENDING
assert row.assigned_to == UUID(AGENT_UUIDS["main-pm"])
# A PM coordinates — a code task handed to the Main PM is coerced to
# planning (the PM/code invariant; the draft's team=backend is honored but
# the type is retyped so the combo never persists).
assert row.task_type == TaskType.PLANNING
@pytest.mark.asyncio
async def test_confirm_live_draft_product_routes_to_main_pm(db_session: Any) -> None:
"""A product-scoped draft via the "Approve & Start" path is a Main-PM root.
The board path (the ``route="board"`` default) keeps the root at
``team=board`` until the CEO approves; the Main-PM path is selected
explicitly with ``route="main_pm"``.
"""
_project_id, ceo_id = await _seed_project_and_ceo(db_session)
product_id = uuid4()
product = ProductTable(
id=product_id,
name="Intake Product",
slug=f"prod-{uuid4().hex[:8]}",
description="x",
created_by=ceo_id,
)
db_session.add(product)
await db_session.flush()
service = get_prompter_service(db=db_session)
draft = {
"title": "Board-led feature",
"acceptance_criteria": ["works end to end"],
"team": "backend",
}
task_id = await service.confirm_live_draft(
draft, ceo_id, product_id=product_id, route="main_pm"
)
row = await db_session.get(TaskTable, task_id)
assert row.team == Team.MAIN_PM
assert row.product_id == product_id
assert row.project_id is None
# A Main-PM coordination root is never code — intake coerces code->planning
# so main_pm + code can never coexist (the 2026-06-27 meltdown shape).
assert row.task_type == TaskType.PLANNING
# =============================================================================
# MegaTask: confirm_live_batch (umbrella + sequenced root-subtasks)
# =============================================================================
async def _seed_second_project(db_session: Any, ceo_id: UUID) -> UUID:
"""Seed a second project so a MegaTask can span multiple repos."""
project_id = uuid4()
db_session.add(
ProjectTable(
id=project_id,
name="Intake Test Project 2",
slug=f"intake2-{uuid4().hex[:8]}",
git_url="https://github.com/example/intake2.git",
default_branch="main",
protected_branches=["main"],
assigned_cell=Team.FRONTEND,
created_by=ceo_id,
is_active=True,
)
)
await db_session.flush()
return project_id
@pytest.mark.asyncio
async def test_confirm_live_batch_builds_umbrella_and_sequenced_subtasks(
db_session: Any,
) -> None:
"""A MegaTask creates one branchless umbrella + N root-subtasks across many
projects, with the collision-derived dependency edges wired so the
dependency-gate runs the waves in order."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
# A & B both add a migration → serial chain A→B (the migration rule orders
# them by priority then index). C is an independent frontend task in another
# project, so it runs in parallel with A in wave 0.
drafts: list[dict[str, Any]] = [
{
"title": "A: add table",
"acceptance_criteria": ["a"],
"team": "backend",
"project_id": str(project1),
"intends_to_touch": ["roboco/services/foo.py"],
"adds_migration": True,
},
{
"title": "B: extend table",
"acceptance_criteria": ["b"],
"team": "backend",
"project_id": str(project1),
"intends_to_touch": ["roboco/services/bar.py"],
"adds_migration": True,
},
{
"title": "C: frontend widget",
"acceptance_criteria": ["c"],
"team": "frontend",
"project_id": str(project2),
"intends_to_touch": ["panel/src/widget.tsx"],
},
]
with patch("roboco.services.prompter.redis.from_url", return_value=_FakeRedis()):
result = await service.confirm_live_batch(
"Three things",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-builds",
)
# A (migration) and C (independent) run in wave 0; B chains after A.
assert result["waves"] == [[0, 2], [1]]
ids = result["root_subtask_ids"]
assert len(ids) == len(drafts)
umbrella_id = UUID(result["umbrella_task_id"])
umbrella = await db_session.get(TaskTable, umbrella_id)
assert umbrella.batch_id is not None
assert umbrella.parent_task_id is None
assert umbrella.project_id is None and umbrella.product_id is None
assert umbrella.team == Team.MAIN_PM
assert umbrella.status == TaskStatus.PENDING
assert umbrella.branch_name is None # branchless
# A Main-PM coordination root is never code — the umbrella is planning-typed.
assert umbrella.task_type == TaskType.PLANNING
a, b, c = [await db_session.get(TaskTable, UUID(sid)) for sid in ids]
for sub in (a, b, c):
assert sub.parent_task_id == umbrella_id
assert sub.batch_id == umbrella.batch_id
assert sub.team == Team.MAIN_PM
assert sub.status == TaskStatus.PENDING
# Each root-subtask is a Main-PM coordination root: code->planning coerced
# at intake so main_pm + code can never coexist (the 2026-06-27 meltdown
# shape). It still gets its own branch + PR + submit_root + pr_review gate
# — the gate is branch-keyed, not task_type-keyed.
assert sub.task_type == TaskType.PLANNING
assert a.project_id == project1
assert b.project_id == project1
assert c.project_id == project2
# sequence = wave index: A and C in wave 0, B in wave 1.
assert (a.sequence, b.sequence, c.sequence) == (0, 1, 0)
# Dependency wiring: B waits on A; C is independent.
assert UUID(ids[0]) in b.dependency_ids
assert c.dependency_ids == []
@pytest.mark.asyncio
async def test_confirm_live_batch_board_route_holds_subtasks_in_backlog(
db_session: Any,
) -> None:
"""The "board" route sends the umbrella to the Product Owner for batch review
and holds the root-subtasks in BACKLOG until the umbrella is approved."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = [
{
"title": "One",
"acceptance_criteria": ["x"],
"team": "backend",
"project_id": str(project1),
},
{
"title": "Two",
"acceptance_criteria": ["y"],
"team": "frontend",
"project_id": str(project2),
},
]
with patch("roboco.services.prompter.redis.from_url", return_value=_FakeRedis()):
result = await service.confirm_live_batch(
"Two repos",
drafts,
ceo_id,
project_ids=[project1, project2],
route="board",
session_id="sess-board",
)
umbrella = await db_session.get(TaskTable, UUID(result["umbrella_task_id"]))
assert umbrella.team == Team.BOARD
assert umbrella.assigned_to == UUID(AGENT_UUIDS["product-owner"])
assert umbrella.status == TaskStatus.PENDING
sub = await db_session.get(TaskTable, UUID(result["root_subtask_ids"][0]))
assert sub.status == TaskStatus.BACKLOG # held until batch review approves
assert sub.team == Team.BOARD
@pytest.mark.asyncio
async def test_confirm_live_batch_rejects_empty(db_session: Any) -> None:
_project1, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
with pytest.raises(ValidationError):
await service.confirm_live_batch(
"Empty", [], ceo_id, project_ids=[uuid4(), uuid4()], session_id="sess-empty"
)
@pytest.mark.asyncio
async def test_confirm_live_batch_rejects_draft_outside_scope(db_session: Any) -> None:
"""A draft targeting a project NOT in the scoped project_ids is refused — the
intake agent only read the scoped repos."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
outside = uuid4() # never in scope
drafts = [
{"title": "A", "acceptance_criteria": ["a"], "project_id": str(project1)},
{"title": "B", "acceptance_criteria": ["b"], "project_id": str(outside)},
]
with pytest.raises(ValidationError, match="outside this MegaTask"):
await service.confirm_live_batch(
"Scoped",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-scope",
)
@pytest.mark.asyncio
async def test_confirm_live_batch_rejects_single_project(db_session: Any) -> None:
"""A degenerate batch whose drafts all target one project is not a MegaTask."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = [
{"title": "A", "acceptance_criteria": ["a"], "project_id": str(project1)},
{"title": "B", "acceptance_criteria": ["b"], "project_id": str(project1)},
]
with pytest.raises(ValidationError, match="at least two distinct projects"):
await service.confirm_live_batch(
"One repo",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-single",
)
# -----------------------------------------------------------------------------
# M13: confirm_live_batch idempotency guard (Redis SETNX + result sidecar)
# -----------------------------------------------------------------------------
class _FakeRedis:
"""In-memory store backing set(nx=True, ex=...) + get + aclose for the
MegaTask confirm idempotency guard + result sidecar."""
def __init__(self) -> None:
self._store: dict[str, str] = {}
self.set_calls: list[tuple[str, str, bool, int]] = []
async def set(
self, name: str, value: str, *, nx: bool = False, ex: int = 0
) -> bool:
self.set_calls.append((name, value, nx, ex))
if nx and name in self._store:
return False
self._store[name] = value
return True
async def get(self, name: str) -> str | None:
return self._store.get(name)
async def aclose(self) -> None:
return None
def _make_batch_drafts(project1: UUID, project2: UUID) -> list[dict[str, Any]]:
"""Minimal valid MegaTask batch: two drafts on two scoped projects."""
return [
{
"title": "A",
"acceptance_criteria": ["a"],
"team": "backend",
"project_id": str(project1),
"intends_to_touch": ["roboco/services/a.py"],
},
{
"title": "B",
"acceptance_criteria": ["b"],
"team": "frontend",
"project_id": str(project2),
"intends_to_touch": ["panel/src/b.tsx"],
},
]
@pytest.mark.asyncio
async def test_confirm_live_batch_idempotent_on_retry(db_session: Any) -> None:
"""A retry with the same session_id returns the first call's result and
does NOT mint a second umbrella + root-subtasks."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = _make_batch_drafts(project1, project2)
fake = _FakeRedis()
with patch("roboco.services.prompter.redis.from_url", return_value=fake):
r1 = await service.confirm_live_batch(
"Batch",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-retry",
)
r2 = await service.confirm_live_batch(
"Batch",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-retry",
)
assert r2["umbrella_task_id"] == r1["umbrella_task_id"]
assert r2["root_subtask_ids"] == r1["root_subtask_ids"]
# Exactly one umbrella + one set of root-subtasks exist for the session.
umbrellas = (
(
await db_session.execute(
select(TaskTable).where(
TaskTable.parent_task_id.is_(None),
TaskTable.batch_id.is_not(None),
)
)
)
.scalars()
.all()
)
assert len(umbrellas) == 1
assert str(umbrellas[0].id) == r1["umbrella_task_id"]
@pytest.mark.asyncio
async def test_confirm_live_batch_in_progress_raises_when_sidecar_absent(
db_session: Any,
) -> None:
"""Guard held but no result sidecar (first call still mid-build) → raise
'already in progress'; no second build attempted."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = _make_batch_drafts(project1, project2)
fake = _FakeRedis()
fake._store["roboco:megatask_confirm:sess-inflight"] = "1" # guard held, no sidecar
with (
patch("roboco.services.prompter.redis.from_url", return_value=fake),
pytest.raises(ServiceError, match="already in progress"),
):
await service.confirm_live_batch(
"Batch",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-inflight",
)
@pytest.mark.asyncio
async def test_confirm_live_batch_redis_unreachable_fails_closed(
db_session: Any,
) -> None:
"""Redis unreachable → ServiceError('idempotency guard unavailable'); no
build attempted (fail-closed, never fail-open)."""
class _BoomRedis:
async def set(self, *_a: Any, **_k: Any) -> bool:
raise OSError("redis down")
async def get(self, _name: str) -> str | None:
raise OSError("redis down")
async def aclose(self) -> None:
return None
def _boom_from_url(_url: str) -> _BoomRedis:
return _BoomRedis()
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = _make_batch_drafts(project1, project2)
with (
patch("roboco.services.prompter.redis.from_url", side_effect=_boom_from_url),
pytest.raises(ServiceError, match="idempotency guard unavailable"),
):
await service.confirm_live_batch(
"Batch",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-boom",
)
# -----------------------------------------------------------------------------
# M14: strip assigned_to from each sub-draft (no board-owned root-subtask deadlock)
# -----------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_confirm_live_batch_strips_assigned_to_from_drafts(
db_session: Any,
) -> None:
"""An LLM-authored draft carrying a hallucinated/injected board-role
``assigned_to`` must NOT create a board-owned CODE root-subtask — a board
role has no dev delivery verbs, so it would deadlock the umbrella. The
root-subtasks are coordination roots; assignment is the PM-activation
flow's call, not the draft's."""
project1, ceo_id = await _seed_project_and_ceo(db_session)
project2 = await _seed_second_project(db_session, ceo_id)
service = get_prompter_service(db=db_session)
drafts = _make_batch_drafts(project1, project2)
# Inject a board-role assignee on every draft (a hallucinated PO uuid).
po_uuid = UUID(AGENT_UUIDS["product-owner"])
for d in drafts:
d["assigned_to"] = str(po_uuid)
fake = _FakeRedis()
with patch("roboco.services.prompter.redis.from_url", return_value=fake):
result = await service.confirm_live_batch(
"Batch",
drafts,
ceo_id,
project_ids=[project1, project2],
route="main_pm",
session_id="sess-m14",
)
# The caller's drafts are untouched (the strip is on the copy).
for d in drafts:
assert d["assigned_to"] == str(po_uuid)
roots = (
(
await db_session.execute(
select(TaskTable).where(
TaskTable.id.in_([UUID(r) for r in result["root_subtask_ids"]])
)
)
)
.scalars()
.all()
)
assert roots, "expected root-subtasks to be created"
for r in roots:
assert r.assigned_to is None, (
f"root-subtask {r.id} wrongly assigned to {r.assigned_to}"
)
def test_preview_batch_computes_waves_without_creating() -> None:
"""preview_batch is pure: it returns the same waves confirm would wire, with
no DB session and no task creation."""
service = get_prompter_service() # no db — pure compute
drafts: list[dict[str, Any]] = [
{"title": "A", "adds_migration": True, "intends_to_touch": ["a.py"]},
{"title": "B", "adds_migration": True, "intends_to_touch": ["b.py"]},
{"title": "C", "intends_to_touch": ["c.py"]},
]
result = service.preview_batch(drafts)
# A & B chain on the migration rule; C is independent → [[0, 2], [1]].
assert result["waves"] == [[0, 2], [1]]
assert isinstance(result["warnings"], list)
def test_preview_batch_honours_declared_depends_on() -> None:
"""B1b: a draft's declared depends_on becomes a real edge even when the
collision surfaces are disjoint (the live S6 break: declared waves were
dropped because the intends_to_touch globs didn't overlap)."""
service = get_prompter_service()
drafts: list[dict[str, Any]] = [
{"title": "A", "intends_to_touch": ["a.py"]},
{"title": "B", "intends_to_touch": ["b.py"], "depends_on": [0]},
]
result = service.preview_batch(drafts)
assert result["waves"] == [[0], [1]]
def test_preview_batch_coerces_string_declared_indices() -> None:
"""The LLM sometimes emits depends_on indices as strings ("0")."""
service = get_prompter_service()
drafts: list[dict[str, Any]] = [
{"title": "A", "intends_to_touch": ["a.py"]},
{"title": "B", "intends_to_touch": ["b.py"], "depends_on": ["0"]},
]
result = service.preview_batch(drafts)
assert result["waves"] == [[0], [1]]
def test_preview_batch_rejects_out_of_range_declared_dep() -> None:
service = get_prompter_service()
drafts: list[dict[str, Any]] = [
{"title": "A", "intends_to_touch": ["a.py"], "depends_on": [9]},
]
with pytest.raises(ValidationError):
service.preview_batch(drafts)
def test_preview_batch_rejects_empty() -> None:
service = get_prompter_service()
with pytest.raises(ValidationError):
service.preview_batch([])
def test_preview_batch_tolerates_bare_string_the_work() -> None:
"""Regression: the LLM sometimes emits the_work as bare team-name strings.
preview_batch must not 500 on that shape (it did: 'str' has no 'get')."""
service = get_prompter_service()
drafts: list[dict[str, Any]] = [
{
"title": "A",
"project_id": str(uuid4()),
"the_work": ["backend"],
"intends_to_touch": ["a.py"],
},
{
"title": "B",
"project_id": str(uuid4()),
"the_work": ["backend", "frontend"],
"intends_to_touch": ["b.py"],
},
]
result = service.preview_batch(drafts)
assert isinstance(result["waves"], list)
assert isinstance(result["warnings"], list)
# =============================================================================
# Per-cell project map (multi-cell MegaTask root-subtask seam) — pure helpers
# =============================================================================
def _work(team: str, project_id: UUID | None) -> dict[str, Any]:
entry: dict[str, Any] = {"team": team, "summary": "s", "items": ["x"]}
if project_id is not None:
entry["project_id"] = str(project_id)
return entry
def test_draft_cell_map_collects_per_cell_projects_in_order() -> None:
"""A multi-cell draft yields one (team, project_id) per the_work entry,
in the_work order, de-duped by team."""
be_proj, fe_proj = uuid4(), uuid4()
draft = {
"the_work": [
_work("backend", be_proj),
_work("frontend", fe_proj),
]
}
assert _draft_cell_map(draft) == [(Team.BACKEND, be_proj), (Team.FRONTEND, fe_proj)]
def test_draft_cell_map_dedupes_repeated_team_keeping_first() -> None:
"""Two entries for the same cell (LLM noise) keep the first mapping — a
task_cell_projects row is unique per (task, team)."""
first, second = uuid4(), uuid4()
draft = {
"the_work": [
_work("backend", first),
_work("backend", second),
]
}
assert _draft_cell_map(draft) == [(Team.BACKEND, first)]
def test_draft_cell_map_skips_entries_without_project_id() -> None:
"""An entry with no project_id (single-cell legacy or a bare team string) is
skipped — the draft then falls back to its top-level project_id."""
be_proj = uuid4()
draft = {
"the_work": [
_work("backend", be_proj),
{"team": "frontend", "summary": "s", "items": []}, # no project_id
]
}
assert _draft_cell_map(draft) == [(Team.BACKEND, be_proj)]
def test_draft_cell_map_empty_when_no_entry_has_project_id() -> None:
"""A legacy single-cell draft (top-level project_id, bare-string the_work)
yields an empty map — the caller falls back to the top-level project_id."""
assert _draft_cell_map({"the_work": ["backend", "frontend"]}) == []
assert _draft_cell_map({"the_work": [{"team": "backend"}]}) == []
def test_draft_cell_map_skips_off_enum_teams_but_rejects_bad_uuids() -> None:
"""Off-enum team names are skipped (the intake agent is an LLM and can emit
a non-cell team), and an entry with no project_id is skipped (legacy
single-cell). But a present-but-malformed project_id is a hard error —
silently dropping it would collapse a 2-cell map to 1-cell and mis-route the
draft as a single-project task (#58)."""
good = uuid4()
draft = {
"the_work": [
_work("backend", good),
{"team": "marketing", "project_id": str(uuid4())}, # not a cell
_work("frontend", None), # missing project_id — skipped
]
}
assert _draft_cell_map(draft) == [(Team.BACKEND, good)]
bad = {
"the_work": [
_work("backend", good),
{"team": "ux_ui", "project_id": "not-a-uuid"}, # malformed — reject
]
}
with pytest.raises(ValidationError, match="Invalid project_id"):
_draft_cell_map(bad)
def test_validate_batch_scope_accepts_single_multi_cell_draft() -> None:
"""One 2-cell draft already spans ≥2 distinct projects → valid MegaTask."""
be_proj, fe_proj = uuid4(), uuid4()
drafts = [
{
"title": "S1",
"acceptance_criteria": ["a"],
"the_work": [
_work("backend", be_proj),
_work("frontend", fe_proj),
],
}
]
# Must not raise: 2 distinct projects across the one draft's cells.
PrompterService._validate_batch_scope(drafts, [be_proj, fe_proj])
def test_validate_batch_scope_rejects_out_of_scope_per_cell_project() -> None:
"""A per-cell project_id outside the scoped set is refused."""
in_scope, out_of_scope = uuid4(), uuid4()
drafts = [
{
"title": "S1",
"acceptance_criteria": ["a"],
"the_work": [
_work("backend", in_scope),
_work("frontend", out_of_scope),
],
}
]
with pytest.raises(ValidationError, match="outside this MegaTask"):
PrompterService._validate_batch_scope(drafts, [in_scope, uuid4()])
def test_validate_batch_scope_rejects_draft_with_no_project() -> None:
"""A draft with neither a per-cell map nor a top-level project_id is refused."""
drafts = [
{
"title": "S1",
"acceptance_criteria": ["a"],
"the_work": [_work("backend", None), _work("frontend", None)],
}
]
with pytest.raises(ValidationError, match="has no project"):
PrompterService._validate_batch_scope(drafts, [uuid4(), uuid4()])
def test_validate_batch_scope_distinct_count_spans_all_cells() -> None:
"""The ≥2 minimum counts distinct projects across ALL drafts' cells, not per
draft. Two single-cell drafts on the same project still fail (degenerate)."""
only = uuid4()
drafts = [
{
"title": "A",
"acceptance_criteria": ["a"],
"the_work": [_work("backend", only)],
},
{
"title": "B",
"acceptance_criteria": ["b"],
"the_work": [_work("frontend", only)], # same project, different cell
},
]
with pytest.raises(ValidationError, match="at least two distinct projects"):
PrompterService._validate_batch_scope(drafts, [only, uuid4()])
def test_validate_batch_scope_legacy_single_cell_drafts_still_work() -> None:
"""Back-compat: drafts using a top-level project_id (no the_work map) still
validate against the scope and the ≥2 distinct minimum."""
p1, p2 = uuid4(), uuid4()
drafts = [
{"title": "A", "acceptance_criteria": ["a"], "project_id": str(p1)},
{"title": "B", "acceptance_criteria": ["b"], "project_id": str(p2)},
]
PrompterService._validate_batch_scope(drafts, [p1, p2])
@pytest.mark.asyncio
async def test_resolve_owning_team_multi_cell_map_routes_to_main_pm() -> None:
"""A multi-cell ad-hoc map is a coordination root (mirrors a product root), so
it routes to the Main PM — never the lead cell (a cell PM can't delegate
cross-cell; that would deadlock the fan-out). No DB access on this branch."""
service = get_prompter_service() # no db — the cell-map branch never reads it
be_proj, fe_proj = uuid4(), uuid4()
draft = {
"the_work": [
_work("backend", be_proj),
_work("frontend", fe_proj),
]
}
team = await service._resolve_owning_team(
draft,
resolved_product_id=None,
resolved_assigned_to=None,
team_override=None,
default_lead=Team.BACKEND,
)
assert team is Team.MAIN_PM
@pytest.mark.asyncio
async def test_resolve_owning_team_single_cell_still_routes_to_lead_cell() -> None:
"""A single-cell project draft (no product, no multi-cell map) keeps its
legacy owner: the lead cell."""
service = get_prompter_service()
draft = {"the_work": [_work("backend", uuid4())]}
team = await service._resolve_owning_team(
draft,
resolved_product_id=None,
resolved_assigned_to=None,
team_override=None,
default_lead=Team.BACKEND,
)
assert team is Team.BACKEND
@pytest.mark.asyncio
async def test_resolve_owning_team_product_with_cell_map_stays_board(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""#160: a product draft that also carries a ≥2-cell the_work map is still a
product root — on the board-review path it stays team=board, not forced to
Main PM (which would strand it past the CEO Approve & Start gate)."""
service = get_prompter_service()
be_proj, fe_proj = uuid4(), uuid4()
draft = {"the_work": [_work("backend", be_proj), _work("frontend", fe_proj)]}
product_id = uuid4()
async def _is_board(_agent_id: UUID) -> bool:
return True
monkeypatch.setattr(service, "_assignee_is_board", _is_board)
team = await service._resolve_owning_team(
draft,
resolved_product_id=product_id,
resolved_assigned_to=uuid4(),
team_override=None,
default_lead=Team.BACKEND,
)
assert team is Team.BOARD
async def _not_board(_agent_id: UUID) -> bool:
return False
monkeypatch.setattr(service, "_assignee_is_board", _not_board)
team = await service._resolve_owning_team(
draft,
resolved_product_id=product_id,
resolved_assigned_to=uuid4(),
team_override=None,
default_lead=Team.BACKEND,
)
assert team is Team.MAIN_PM
def test_clean_list_extracts_dict_wrapped_items() -> None:
"""#159: _clean_list (via coerce_str_list) extracts text from the Claude
SDK's XML-ish dict wrappers (``<item>…</item>`` -> ``{"item": {"$text": …}}``)
instead of rendering ``str(dict)``. Pins the behavior so a regression to
``str(dict)`` in the rendered description is caught."""
out = _clean_list([{"item": {"$text": "build it"}}, "ship it", " ", ""])
assert out == ["build it", "ship it"]
@pytest.mark.asyncio
async def test_create_task_from_draft_preserves_product_with_one_cell_map(
db_session: Any,
) -> None:
"""#57: a draft carrying a top-level product_id AND a 1-cell the_work map
keeps the product — the lone cell map is redundant, not a signal to drop the
product and force the cell's project_id."""
_project_id, ceo_id = await _seed_project_and_ceo(db_session)
product_id = uuid4()
db_session.add(
ProductTable(
id=product_id,
name="One-cell product",
slug=f"prod-{uuid4().hex[:8]}",
description="x",
created_by=ceo_id,
)
)
await db_session.flush()
service = get_prompter_service(db=db_session)
draft = {
"title": "Board-led single-cell product",
"acceptance_criteria": ["done"],
"product_id": str(product_id),
"the_work": [_work("backend", uuid4())],
}
task = await service.create_task_from_draft(draft, ceo_id)
assert task.product_id == product_id
assert task.project_id is None
@pytest.mark.asyncio
async def test_create_task_from_draft_does_not_mutate_caller_draft(
db_session: Any,
) -> None:
"""#59: create_task_from_draft coerces + recomposes on a copy — the caller's
draft dict and its the_work unit dicts are left untouched (no in-place
rewrite of acceptance_criteria / items)."""
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
original_items = [" trim me ", "keep"]
draft: dict[str, Any] = {
"title": "No-mutation check",
"acceptance_criteria": ["done"],
"project_id": str(project_id),
"the_work": [
{"team": "backend", "summary": "s", "items": list(original_items)}
],
}
await service.create_task_from_draft(draft, ceo_id)
# The caller's the_work unit items were NOT coerced in place...
assert draft["the_work"][0]["items"] == original_items
# ...and the top-level acceptance_criteria was NOT replaced.
assert draft["acceptance_criteria"] == ["done"]
@pytest.mark.asyncio
async def test_create_task_from_draft_defaults_source_to_prompter(
db_session: Any,
) -> None:
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
draft = {
"title": "Default-source draft",
"acceptance_criteria": ["done"],
"project_id": str(project_id),
}
task = await service.create_task_from_draft(draft, ceo_id)
assert task.source == "prompter"
@pytest.mark.asyncio
async def test_create_task_from_draft_accepts_custom_source(
db_session: Any,
) -> None:
"""A non-intake caller (e.g. an approved roadmap item) stamps its own
source tag on the draft instead of the intake default."""
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
draft = {
"title": "Roadmap-sourced draft",
"acceptance_criteria": ["done"],
"project_id": str(project_id),
"source": "roadmap",
}
task = await service.create_task_from_draft(draft, ceo_id)
assert task.source == "roadmap"
assert task.confirmed_by_human is True # the CEO approval IS the confirmation
@pytest.mark.asyncio
async def test_create_task_from_draft_rejects_unwhitelisted_source(
db_session: Any,
) -> None:
"""An LLM-authored draft can't impersonate a privileged origin: a source
outside the whitelist falls back to 'prompter' (a 'release_manager' spoof
would otherwise wedge the release engine's one-open-proposal dedup)."""
project_id, ceo_id = await _seed_project_and_ceo(db_session)
service = get_prompter_service(db=db_session)
draft = {
"title": "Spoofed-source draft",
"acceptance_criteria": ["done"],
"project_id": str(project_id),
"source": "release_manager",
}
task = await service.create_task_from_draft(draft, ceo_id)
assert task.source == "prompter"
# =============================================================================
# Prompter memory v1 — history digest + compact search rows (pure, no DB)
# =============================================================================
def _task(title: str, **overrides: Any) -> TaskTable:
"""An unattached TaskTable instance — plain attribute assignment, no session.
Defaults to a completed backend task with no dates; pass ``completed_at`` /
``updated_at`` / ``created_at`` / ``status`` / ``team`` to override.
"""
fields: dict[str, Any] = {
"id": uuid4(),
"title": title,
"status": TaskStatus.COMPLETED,
"team": Team.BACKEND,
"completed_at": None,
"updated_at": None,
"created_at": None,
}
fields.update(overrides)
return TaskTable(**fields)
def test_task_activity_date_prefers_completed_at() -> None:
now = datetime.now(UTC)
task = _task(
"t",
completed_at=now,
updated_at=now - timedelta(days=1),
created_at=now - timedelta(days=2),
)
assert _task_activity_date(task) == now
def test_task_activity_date_falls_back_to_updated_at() -> None:
now = datetime.now(UTC)
task = _task(
"t", completed_at=None, updated_at=now, created_at=now - timedelta(days=1)
)
assert _task_activity_date(task) == now
def test_task_activity_date_falls_back_to_created_at() -> None:
now = datetime.now(UTC)
task = _task("t", completed_at=None, updated_at=None, created_at=now)
assert _task_activity_date(task) == now
def test_title_excerpt_leaves_short_titles_untouched() -> None:
assert _title_excerpt("Fix login bug") == "Fix login bug"
def test_title_excerpt_truncates_long_titles_with_ellipsis() -> None:
long_title = "A" * 100
excerpt = _title_excerpt(long_title)
assert len(excerpt) == _HISTORY_TITLE_EXCERPT_CAP
assert excerpt.endswith("…")
def test_build_history_digest_empty_is_blank() -> None:
assert build_history_digest([]) == ""
def test_build_history_digest_caps_at_limit_keeps_most_recent() -> None:
now = datetime.now(UTC)
# t0 oldest ... t19 newest.
ascending = [
_task(f"t{i}", created_at=now + timedelta(days=i), updated_at=None)
for i in range(20)
]
# Mimic the DB's most-recent-first ordering.
most_recent_first = list(reversed(ascending))
digest = build_history_digest(most_recent_first)
lines = digest.splitlines()
assert len(lines) == _HISTORY_DIGEST_PER_PROJECT_LIMIT
for i in range(5): # the 5 oldest are excluded
assert f"`{str(ascending[i].id)[:8]}`" not in digest
for i in range(5, 20): # the 15 most recent are present
assert f"`{str(ascending[i].id)[:8]}`" in digest
def test_build_history_digest_renders_oldest_first() -> None:
now = datetime.now(UTC)
a = _task("Task A", created_at=now - timedelta(days=2), updated_at=None)
b = _task("Task B", created_at=now - timedelta(days=1), updated_at=None)
c = _task("Task C", created_at=now, updated_at=None)
# DB order is most-recent-first: C, B, A.
digest = build_history_digest([c, b, a])
idx_a = digest.index("Task A")
idx_b = digest.index("Task B")
idx_c = digest.index("Task C")
assert idx_a < idx_b < idx_c
def test_compact_task_rows_shape() -> None:
now = datetime.now(UTC)
task = _task(
"Fix login bug",
status=TaskStatus.COMPLETED,
team=Team.BACKEND,
completed_at=now,
)
rows = compact_task_rows([task])
assert len(rows) == 1
row = rows[0]
assert set(row.keys()) == {"id", "title", "status", "team", "date"}
assert row["id"] == str(task.id)
assert row["title"] == "Fix login bug"
assert row["status"] == "completed"
assert row["team"] == "backend"
assert row["date"] == now.date().isoformat()
def test_compact_task_rows_preserves_none_team() -> None:
task = _task("No team", team=None, created_at=datetime.now(UTC))
rows = compact_task_rows([task])
assert rows[0]["team"] is None
# -----------------------------------------------------------------------------
# history_digest_layer — ambient-block assembly (project_history_digest stubbed)
# -----------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_history_digest_layer_empty_projects_returns_none() -> None:
assert await history_digest_layer(cast("AsyncSession", object()), []) is None
@pytest.mark.asyncio
async def test_history_digest_layer_single_project_has_no_header(
monkeypatch: pytest.MonkeyPatch,
) -> None:
async def _fake(_session: Any, _project: Any, *, _limit: int = 15) -> str | None:
return "- `abc12345` Some task (completed, 2026-01-01)"
monkeypatch.setattr(prompter_module, "project_history_digest", _fake)
project = SimpleNamespace(slug="roboco", id=uuid4())
text = await history_digest_layer(cast("AsyncSession", object()), [project])
assert text is not None
assert text.startswith("## Task History\n\n### Recent tasks\n")
assert "### Recent tasks —" not in text
@pytest.mark.asyncio
async def test_history_digest_layer_multi_project_headers_by_slug(
monkeypatch: pytest.MonkeyPatch,
) -> None:
projects = [
SimpleNamespace(slug="backend-svc", id=uuid4()),
SimpleNamespace(slug="frontend-app", id=uuid4()),
]
async def _fake(_session: Any, project: Any, *, _limit: int = 15) -> str | None:
return f"- `deadbeef` Task for {project.slug} (completed, 2026-01-01)"
monkeypatch.setattr(prompter_module, "project_history_digest", _fake)
text = await history_digest_layer(cast("AsyncSession", object()), projects)
assert text is not None
assert "### Recent tasks — `backend-svc`" in text
assert "### Recent tasks — `frontend-app`" in text
@pytest.mark.asyncio
async def test_history_digest_layer_skips_projects_with_no_tasks(
monkeypatch: pytest.MonkeyPatch,
) -> None:
has_tasks = SimpleNamespace(slug="has-tasks", id=uuid4())
no_tasks = SimpleNamespace(slug="empty-proj", id=uuid4())
async def _fake(_session: Any, project: Any, *, _limit: int = 15) -> str | None:
return (
"- `deadbeef` A task (completed, 2026-01-01)"
if project is has_tasks
else None
)
monkeypatch.setattr(prompter_module, "project_history_digest", _fake)
text = await history_digest_layer(
cast("AsyncSession", object()), [has_tasks, no_tasks]
)
assert text is not None
assert "has-tasks" in text
assert "empty-proj" not in text
@pytest.mark.asyncio
async def test_history_digest_layer_all_empty_returns_none(
monkeypatch: pytest.MonkeyPatch,
) -> None:
async def _fake(_session: Any, _project: Any, *, _limit: int = 15) -> str | None:
return None
monkeypatch.setattr(prompter_module, "project_history_digest", _fake)
projects = [
SimpleNamespace(slug="a", id=uuid4()),
SimpleNamespace(slug="b", id=uuid4()),
]
assert await history_digest_layer(cast("AsyncSession", object()), projects) is None