Feature: prompter gold upgrade (#84)

* feat(prompter): make the assistant a RoboCo insider and fully wire launch

The Prompter's intelligence lived in two thin static prompts, so it asked
generic checklist questions and produced a flat task. The launch path was
also only half-wired: the panel called the generic task-create endpoint with
no project, bypassing the Prompter's own confirm flow.

Interview brain
- Rewrite the chat system prompt with RoboCo's org model, the task-spec
  standard, a dimensions playbook, and a reflect-back, 1-2-questions-per-turn,
  auto-stop discipline.
- Inject the live projects/products list each turn so the assistant grounds
  questions in real surfaces and resolves the target itself.
- Replace the brittle phrase-match readiness with a parsed roboco-meta control
  block (parse_readiness); the block is stripped from the visible reply and the
  turn now returns draft_ready + scale.

Structured GOLD draft
- Add first-class draft fields (objective, what_this_builds, the_work, notes)
  carried in the existing draft_data JSONB — no migration.
- Compose the GOLD markdown description deterministically from those fields
  (compose_description); the model never hand-formats the body.

Adaptive routing + wired launch
- Confirm now runs through the Prompter confirm endpoint with the human's
  project/product choice and edited structured draft.
- Single-cell targets a project and the cell team; a multi-cell feature targets
  a product and becomes a Main-PM coordination root that fans out.

Frontend
- Turn-envelope draft_ready (drop the duplicated phrase-match), structured
  draft card, confirm dialog with a project/product picker and a per-cell
  The Work editor, and the corrected priority labels (0 highest .. 3 lowest).

* fix(prompter): commit session writes so they survive across requests

Session create returned 201 but the row was never durably committed, so the
immediately-following /messages call could not find it and 404'd. The prompter
routes were the only write surface that never called db.commit() — every other
write route (tasks, a2a, groups, docs, product) commits explicitly rather than
rely on the request-teardown auto-commit, which is sensitive to middleware and
teardown ordering under the production server.

- Commit explicitly in all four prompter write routes (create session, send
  message, get/generate draft, confirm).
- Fix _get_session's NotFoundError: it passed a full sentence as resource_type,
  producing the doubled "... not found not found" message; now uses the
  (resource_type, resource_id) signature.
- Panel: when a message hits a session the server no longer has, start a fresh
  session and retry once instead of dead-ending on a stale id.

Add a regression test that gives each request its own non-committing session —
the real cross-request boundary the shared-session integration tests never
crossed. It reproduces the production 404 without the route commit and passes
with it.

* refactor(prompter): drop the "GOLD" jargon for plain wording

"GOLD" was informal shorthand for "a good/well-formed spec" that should never
have been baked into the LLM prompts, comments, and docstrings as if it were a
defined term. Replace it everywhere with plain language ("a well-formed task",
"a complete task spec", "the markdown description", "structured spec fields").
No behaviour change.

* feat(intake): add the intake interviewer agent role (static definition)

Phase 1 of the intake-agent feature: a new first-class `prompter` role — the
intake interviewer the CEO chats with to draft a task. This commit defines the
role across every foundation layer (no runtime yet); spawning + the live
session come next.

- identity: Role.PROMPTER, RoleLevel.INTAKE (lowest authority), an AGENTS row
  (intake-1) on the board team, ROLE_LEVEL entry. Deliberately NOT in
  BOARD_ROLES — it interviews, it does not review.
- lifecycle: gets i_am_idle like every agent (its only verb); no
  delivery-lifecycle intents.
- journaling: ReadTier.OWN — isolated, reads only its own journal.
- role_config: human-only manifest — note + evidence only, no say/dm/notify/
  channels; allows_subagent=True (research), allows_write=False.
- agents_config derives it automatically and correctly excludes it from
  TASK_CREATOR_ROLES (it drafts, it never creates tasks).
- seed presentation ("Intake"); regenerated lifecycle artifacts.
- role system prompt: read the code first, single-CEO awareness, propose
  rather than interrogate — written against the failures we saw.
- docs: roster count 19 -> 20, org charts, verb-surface table, usage roster.

All foundation drift checks pass; role/manifest/permission tests green.

* feat(intake): migrate agentrole enum to add 'prompter'

ALTER TYPE agentrole ADD VALUE IF NOT EXISTS 'prompter' so the intake agent
row seeds/spawns against a migrated production DB. Forward-only (postgres
can't drop enum values), guarded for offline mode — matches migration 012.

* style(intake): ruff format the role additions

* fix(intake): unguard the agentrole migration so it renders offline

The enum-migration-parity test renders 'alembic upgrade head --sql' (offline)
and greps for ALTER TYPE ... ADD VALUE. The is_offline_mode() guard skipped
emitting it, so the parity check couldn't see 'prompter'. Drop the guard —
PG16 permits ADD VALUE in a transaction, same as migration 020's backfill.

* feat(intake): the live-session driver (Claude Agent SDK loop)

Phase 2 begins. The intake agent isn't a one-shot `claude -p`; it's a live
Claude Code session the human chats with. This driver is the container's loop:
open one long-lived claude-agent-sdk ClaudeSDKClient, then per human message
run a turn (query + receive_response) and stream its events out, keeping
conversation context in-process — verified against the real SDK (v0.2.94).

- StreamChunk + normalize(): map SDK messages (StreamEvent text deltas,
  AssistantMessage text/thinking/tool_use blocks, ResultMessage→session_id) to
  panel-facing chunks. Duck-typed, so it works on real SDK objects and on test
  fakes alike — SDK-free, fully unit-tested.
- IntakeDriver.run(): the loop, with injected session/source/sink seams; a turn
  failure surfaces as an error chunk without killing the session.
- SdkIntakeSession + build_intake_options: the only SDK-coupled code (lazy
  import; needs the live claude binary, so excluded from coverage).
- Add claude-agent-sdk dependency + mypy ignore-missing-stubs.

Relay, panel SSE, and the persistent on-demand spawn are the next steps.

* Updated uv.lock

* feat(intake): the panel<->agent live bridge (registry, routes, entrypoint, image)

Wires the live intake chat end to end (Phase 2 integration layer):

- prompter_live.py: the orchestrator-side per-session registry — open/close,
  push (agent->panel), stream (SSE drain), deliver (panel->container). In-process
  (the orchestrator is single-process). 7 unit tests.
- routes/prompter_live.py: GET /live/{id}/stream (SSE), POST /live/{id}/messages
  (deliver), POST /live/{id}/events (relay in); registered under /api/prompter.
  5 integration tests.
- agent_sdk/intake_main.py: the container entrypoint — a POST /turn receiver
  (the driver's MessageSource) + a relay-poster EventSink + the ClaudeSDKClient
  session, run concurrently. 4 unit tests on the wiring helpers.
- docker/agent-prompter.Dockerfile: FROM base, ENTRYPOINT = the driver (not the
  one-shot `claude` the other agents use).

Remaining for Phase 2: the orchestrator persistent-spawn path (scope->workspace
clone, CMD = driver, registry.open on spawn, reap-on-confirm) — the deploy-side
piece, best finalized against a buildable image.

* feat(intake): orchestrator persistent spawn + start/stop for the live chat

Add the task-free spawn path for the intake (prompter) agent: one fixed
intake-1 container running the Agent-SDK driver (image ENTRYPOINT, not
claude -p), one live session at a time.

- spawn_intake_session clones the scope's repo(s) via WorkspaceService
  (project -> one; product -> each distinct project, primary first),
  composes the intake-1 prompt, resolves the model, and builds docker run
  via _build_intake_run_cmd: no settings/hook mount (driver owns 9000),
  no MCP config, no -w; registers the live relay and best-effort delivers
  the opening message once the receiver is up.
- reap_intake_session closes the relay and stops the container.
- Routes: POST /live/start (project XOR product) and POST /live/{id}/stop.
- ROLE_MODEL_MAP[prompter]=opus; intake-1 -> roboco-agent-prompter image map.
- Replace the budget-sweep try/except/continue with _fetch_budget_status,
  which logs the swallow at debug instead of silently dropping it.

25 new tests; docker + the clone are mocked. End-to-end container spawn is
pending a built image and the stack.

* feat(intake): wire /prompter to the live agent — scope form + SSE chat

Replace the Ollama chat loop on /prompter with the spawned-agent flow.

- IntakeForm: pick scope (project XOR product) + opening message + Start
  before the chat; the agent clones that scope and reads the real code.
- use-prompter rewritten as the live brain (lib/api/prompter-live.ts): Start
  spawns via POST /live/start, then an EventSource on /live/{id}/stream
  streams the agent working — token deltas fill the assistant bubble,
  tool_use/thinking drive a live activity line, a draft event renders the
  existing DraftProposalCard. Messages go via POST /live/{id}/messages.
- Chat UX unchanged (Keep Chatting / Review & Confirm / ConfirmDialog reused);
  reap-on-confirm and reap-on-leave call POST /live/{id}/stop.
- Drop the dead Ollama prompterApi client; trim prompter.ts to shared types.

Frontend gate green (tsc --noEmit, lint, build). The draft event + the
/live/{id}/confirm endpoint are the Phase 4 backend seam.

* feat(intake): confirm draft -> backlog task + agent draft emission

Complete the live intake vertical: the agent proposes a structured draft and
Review & Confirm turns it into a task.

- Draft emission: the prompter prompt instructs the agent to emit a fenced
  roboco-draft JSON block when the spec is ready; the driver parses it into a
  'draft' event over the existing relay -> the panel's DraftProposalCard. The
  panel strips the raw block from the chat bubble.
- Fix a double-text bug: with include_partial_messages the reply arrives as
  both StreamEvent deltas and the final AssistantMessage; the driver now takes
  text from deltas only and the AssistantMessage for thinking/tool_use/draft.
- POST /live/{id}/confirm -> confirm_live_draft, reusing a draft->task core
  extracted from confirm_draft; reaps the session on success.
- Both prompter confirm paths create at BACKLOG, not pending: backlog is the
  holding area a draft waits in until it's reviewed and promoted to pending
  (TaskService.activate). The legacy Ollama confirm was creating at pending,
  skipping that gate — fixed.
- Remove the dead 'context' bootstrap param from the Ollama session-create
  chain (schema + route + method + tests), superseded by the live scope form.
- No suppressions: replace every type:ignore/noqa across the intake surface
  with a real fix (ORM .id -> UUID(str(x)); fakes -> monkeypatch.setattr;
  lazy imports -> pyproject per-file ignore; union-attr -> recipients[0]).

Full make quality green; frontend tsc + lint green.

* build(intake): add the agent-prompter image builder to compose

The orchestrator references roboco-agent-prompter (AGENT_IMAGES + the
_ensure_agent_image dockerfile map) and docker/agent-prompter.Dockerfile
exists, but docker-compose.yml built every other agent image up front and
left this one out — so the image wasn't pre-built for a stack bring-up.

Mirror the other specialized agent-*-image builders: build from
docker/agent-prompter.Dockerfile, tag roboco-agent-prompter, depend on
agent-base-image.

* Created docker-compose.yaml for the NAS

* fix(intake): non-blocking /live/start so spawn never times out

The start POST awaited the whole spawn — workspace clone + first-time image
build + docker run — which blew past the panel's 60s HTTP timeout ('Request
timed out. The server may be busy.') and triggered a duplicate send. Found on
the 2026-06-09 NAS smoke.

- start_intake_session opens the live relay synchronously, then spawns the
  container in the background (_spawn_intake_container_guarded). The route
  returns the session id immediately; the panel opens the SSE stream right away.
- A background spawn failure is pushed onto the relay as an 'error' event and
  closes the session, so the panel shows it instead of hanging.
- spawn_intake_session stays as the synchronous variant for direct callers/tests.
- Panel shows a 'Preparing the agent…' indicator until the first event arrives.

18 intake-spawn tests green; tsc + lint green. E2E re-validates on next smoke.

* fix(intake): propose_draft MCP tool + lock the agent down

Smoke 2026-06-09 exposed two compounding problems: the agent never reliably
emitted the draft (it narrated the spec instead of typing the magic fence), and
it had inherited the CEO's entire Claude Code env — Write/Edit/Bash + Gmail/
Notion/Calendar/Drive MCP — because bypassPermissions ignored the allowlist and
the mounted ~/.claude leaked the host MCP config.

- propose_draft: build_intake_options now registers an in-process SDK MCP tool
  (create_sdk_mcp_server + @tool). The agent calls it to submit the draft; the
  driver turns that ToolUseBlock into a 'draft' event (_is_propose_draft /
  _draft_from_tool_input, tolerant of nested/flat/JSON-string input). The fenced
  roboco-draft block stays as a fallback.
- Lockdown: strict_mcp_config=True + setting_sources=[] (ignore host MCP +
  settings); permission_mode 'dontAsk' + a can_use_tool gate enforcing a hard
  allowlist (Read/Grep/Glob/Task + propose_draft) replaces bypassPermissions.
- Prompt: call propose_draft (not a fence); the draft's downstream chain is
  backlog -> Board (PO + HoM) -> CEO approve -> Main PM, and the agent's job ends
  at the draft (it never routes or hands off).

SDK API verified against the installed claude-agent-sdk. Driver detection unit-
tested; the SDK-construction is validated on the next NAS smoke (incl. that
setting_sources=[] doesn't break the mounted-~/.claude auth).

* fix(intake): panel UX cluster from the smoke (#3/#4/#6/#12)

- #3 message boundaries: a tool call now ends the current text bubble, so the
  agent's words before and after a tool render as separate messages instead of
  one merged wall (the 'two waves merged into one bubble' the CEO saw).
- #4 activity indicator: promoted from tiny grey text to a prominent primary-
  tinted pill so 'watch it work' is actually visible.
- #12 End chat: a header button (any chat state) reaps the agent and resets to
  the form, reusing startAnother (which already stops the session). Backend
  POST /live/{id}/stop already existed.
- #6 log noise: the opening-message delivery retry logs at debug, not error —
  those failures are expected until the container receiver is up.
- Also fix a latent test gap from the #1 commit: the live-route test's fake
  orchestrator now exposes start_intake_session (the route's non-blocking entry).

Frontend tsc + lint green; live-route + prompter_live tests green.

* fix(intake): render markdown in the chat bubbles (#8)

The agent emits rich markdown (### headers, **bold**, tables, lists) but the
bubble rendered raw text, so it was illegible (CEO-flagged on the smoke). Render
assistant content with react-markdown + remark-gfm (GFM tables) in a prose
container. Adds react-markdown + remark-gfm to the panel.

* feat(intake): #14 — two start routes (Board review vs straight to Main PM)

Per the CEO spec, the draft confirm now starts the task at PENDING with an
explicit assignment instead of parking it at backlog:

- route="board" (Board review & Start): assigned to the Product Owner, so the
  orchestrator dispatches the full Board review (PO + Head of Marketing) before
  the Main PM picks it up.
- route="main_pm" (Approve & Start): assigned straight to the Main PM, who
  delegates to the cells (Board review skipped).

create_task_from_draft gains status + assigned_to params (default BACKLOG, so the
legacy confirm_draft is unchanged); confirm_live_draft + the /live/{id}/confirm
request carry the route. Service tests cover both routes.

* feat(intake): #14 draft-card buttons — Board review vs Approve & Start

Three buttons on the draft card now (CEO spec): Keep chatting / Board review &
Start / Approve & Start. The two action buttons confirm directly with their
route — launchTask(route) sends route to POST /live/{id}/confirm, which starts
the task at pending assigned to the Board (PO+HoM) or straight to the Main PM.

Supersedes the ConfirmDialog review step (scope is chosen up front in the form),
so it's removed from the page flow. The ConfirmDialog component + its sub-editors
are now unused — flagged for a follow-up cleanup, left in place to avoid churn.

tsc + lint green.

* fix(intake): keep the live SSE stream bound to its relay session

The orchestrator opened the relay session twice per live chat — once on the
request path (before the start call returns) and again inside the background
container spawn. The SSE stream binds to the session's queue the moment the
panel connects, so the second open swapped in a fresh queue and stranded the
stream: the agent replied normally, but its events went to the new queue while
the panel kept reading the old one, so the chat looked frozen on "Preparing…".

The second open was always redundant (the relay is opened by the caller before
the spawn). Remove it, and make open() idempotent so a live session is never
replaced out from under a stream that is already connected to it.

* fix(intake): draft-card launch buttons silently did nothing

The launch path required a `description` field, but the prompter draft schema
intentionally has none — it sends `objective` + the structured spec and the
backend composes the description (compose_description). `editableDraft.description`
was therefore undefined, so `description.trim()` inside launch validation threw a
TypeError that propagated out of the button's onClick. Clicking "Board review &
Start" / "Approve & Start" did nothing, with no feedback — the wall blocking the
whole confirm → task → reap flow.

- Map a proposed draft's description from `objective` as a fallback.
- Make launch validation null-safe.
- Replace the silent early-return with a toast that names what's missing, so a
  blocked launch is never a dead, feedback-less button again.

* fix(intake): steer the agent to ask inline, not via AskUserQuestion

The intake's job is to ask clarifying questions, so it reached for the
AskUserQuestion tool — which isn't wired to the live chat panel and isn't in its
allowlist. The bare deny left it to stumble ("let me clarify… — no worries, let
me just lay it out") and waste a visible turn.

- Prompt: spell out that it asks by writing in the chat (the human reads every
  message live) and that no question/prompt tool is available to it.
- Gate: give AskUserQuestion a specific deny message that nudges it to ask inline,
  so even a reflex attempt degrades gracefully.

Also refresh the now-stale "what happens after propose_draft" section: the draft
card has three choices (Keep chatting / Board review & Start / Approve & Start)
and produces a pending task — not the old two-button "backlog" description.

* feat(intake): copy buttons on agent messages and the draft card

The CEO asked for a way to save the agent's plan/spec elsewhere "just in case" —
a cheap manual backstop until refresh-durability lands.

- New CopyButton: async Clipboard API when available, plus a legacy
  textarea+execCommand fallback. The fallback is load-bearing — the panel is
  served over plain http on a LAN IP, where navigator.clipboard is absent
  (clipboard needs a secure context), so the modern API alone would never copy.
- Copy button under each assistant message (copies its text).
- Copy button on the draft card (copies the full spec as markdown: title,
  objective, what-this-builds, the-work per cell, notes, success criteria).

* feat(intake): unbuffer logs + log each turn so the container isn't a black box

Debugging the intake smoke was painful for two reasons: (a) the orchestrator
block-buffered stdout, so `docker logs` lagged minutes behind reality, and (b)
the intake container logged only "session opened" then went silent for the whole
conversation (the chat streams to the relay, not stdout).

- Set PYTHONUNBUFFERED=1 on the orchestrator and agent-base images so structured
  logs reach `docker logs` in real time instead of in large delayed chunks.
- Log each intake turn: "turn received" (with char count) and "turn streamed"
  (chunk count + whether a draft was emitted), so the container logs show the
  conversation's shape at a glance.

* chore(intake): remove the dead ConfirmDialog draft editor

The three-button draft card (Keep chatting / Board review & Start / Approve &
Start) replaced the old review-modal confirm flow, leaving ConfirmDialog and its
sub-editors (StringListEditor, TheWorkEditor) referenced by nothing but the
barrel export. Remove the three files and the export — typecheck + lint confirm
no remaining references.

* fix(intake): coerce bad draft enums on confirm instead of hard-failing

The intake agent is an LLM and will emit off-enum values — e.g. task_type="feature",
which is not a valid TaskType (code/documentation/research/planning/design/
administrative). `_coerce_draft_enums` called `TaskType(value)` directly, which
raised, and the confirm 400'd with "Draft has invalid or missing required fields:
'feature' is not a valid TaskType". That forced the agent to discover the valid
values and self-correct in-chat — unacceptable: clicking "Approve & Start" must
never blow up on a cosmetic enum guess.

Coerce each enum to a sane default on invalid/missing (task_type→code,
nature→technical, complexity→medium); team falls back to the first valid cell in
the_work, then backend. `_lead_cell_team` now skips invalid cell names too. The
confirm/launch action no longer hard-fails on an enum the model got wrong.

* fix(intake): draft card no longer renders above the user's latest message

attachDraft fell back to "the last assistant message anywhere" when the current
turn had no streamed text yet (propose_draft called first). That last message was
often the PREVIOUS turn's — sitting above the user's "Yes, propose it" — so the
draft card rendered above the user's message. Attach only to the current turn's
streaming message; otherwise append a fresh assistant message so the card always
lands at the bottom of the thread.

* test(intake): guard draft enum coercion + invalid-cell skipping

Regression tests for the confirm-time enum coercion: an off-enum task_type
("feature") / nature / complexity coerce to code/technical/medium instead of
raising, and _lead_cell_team skips invalid cell names. Locks in that a bad enum
guess from the agent can never 400 the launch again.

* fix(intake): stop the agent fumbling through Claude Code meta-tools

In smoke it reflexively probed CC built-ins before reaching propose_draft —
plan mode + ExitPlanMode (it announced a written plan and waited instead of
emitting the draft), ToolSearch, Write — each correctly denied by the lockdown
but stumbly, and it only proposed after explicit CEO nudges.

- Gate: ExitPlanMode now gets a specific deny nudge ("you don't use plan mode;
  call propose_draft"), and the generic deny names the actual toolset instead
  of a bare "not available", so any probe degrades into guidance.
- Prompt: forbid plan mode/ExitPlanMode/ToolSearch explicitly and spell out
  "you do not plan and wait — call propose_draft directly when the spec is
  ready," plus an anti-pattern bullet.

* feat(intake): make the container logs transparent mid-turn

`docker logs` on the intake container was a black box: only turn start/end, while
the agent read the codebase and spawned 20+ subagents invisibly (the conversation
streams to the relay, not stdout), and the benign 3x ~/.claude.json warning was
the only thing visible.

- Driver logs each tool call mid-turn ("Intake tool use" with the tool name) and
  the draft emission, plus a tools count in the turn-streamed summary. Text deltas
  stay unlogged (they'd spam). Now the logs show the turn's real shape.
- Pre-create ~/.claude.json ({}) at container boot so the CLI's "config not found"
  warning (printed 3x, self-healed anyway) stops drowning the real logs.

* fix(intake): render markdown in user messages + scope copy to code blocks

Two display fixes from the smoke:
- User messages collapsed newlines (plain {content} in a div) and rendered no
  markdown — a "1.\n2.\n3." answer showed as one run-on line. Render user AND
  assistant bubbles through a shared GFM markdown body that inherits the bubble's
  text color, so lists / newlines / styling render correctly on both.
- Copy was blanketed on every assistant message; scope it to KEY parts — a copy
  button on fenced code blocks (the draft card keeps its own). Removed the
  per-message button.

* fix(intake): prevent duplicate tasks from a double-click on launch

Clicking a draft launch button twice fired two confirms and created duplicate
tasks. Add a synchronous re-entry guard (a ref — no stale-closure window) at the
top of launchTask so a second click returns immediately, and disable + spin the
draft-card buttons while a launch is in flight so it's visually clear it's working.

* docs(how-to): lead task creation with the Task Assistant flow

Rewrite "1 · It starts with you" to walk the Prompter/Task Assistant path —
scope form, the agent reading the codebase, its grounded analysis, the draft
card, and the created task — then flow into the Board review. Replaces the old
manual task-definition form shots.

Image placeholder: images/prompter_draft_card.png (the 3-button card) is
referenced but not yet captured — TODO comment marks it for the next smoke run.
A second comment flags an optional re-capture of prompter_run_2 after the
markdown-rendering fix.

* fix(intake): restore assistant message text contrast

The markdown refactor dropped `dark:prose-invert` and made text inherit the
bubble's color, but the assistant bubble had no explicit text color — so its text
rendered near-invisible (dark-on-dark on bg-muted). Give the assistant bubble an
explicit text-foreground; the user bubble already carries text-primary-foreground,
and [&_*]:!text-inherit now resolves to a readable color on both.

* fix(intake): coerce draft priority too — confirm 500'd on priority="high"

The enum-coercion fix covered task_type/nature/complexity/team, but priority is a
non-enum int field handled by `int(draft_data.get("priority", 2))`, and the agent
guesses a word ("high") as readily as a number — so int("high") raised ValueError
and the confirm 500'd. Same class of bug, one field missed.

Add _coerce_priority: map words (urgent/high/medium/low → 0/1/2/3), clamp numbers
to 0-3, default to 2 (medium) on anything else. The launch can no longer crash on
any field the LLM guessed. + regression test.

* fix(intake): draft card shows distinct cells, not one badge per work item

the_work has one entry per work item, so a cell with several items rendered its
badge repeatedly ("Board-led across Backend Backend Backend Frontend Frontend
…"). De-dupe to distinct teams so the card reads "Board-led across Backend
Frontend" — and the "Cell:" vs "Board-led across" label keys off distinct count.

* docs(how-to): hero the teaser gif + resolve the Prompter/Task Assistant thread

- Move the 12s teaser gif to the top as the hero — it was buried between the
  "prefer video" link and the first screenshot.
- Name the connection: the Task Assistant IS the Prompter, so section 1 (using
  the tool) and the rest (RoboCo building it) read as one story — you use the
  tool the company built for itself, then watch the build.
- Re-anchor the section 1 → Board transition to follow the Prompter's own
  journey, instead of implying section 1's example task is the one reviewed next.

* Included images for how-to.md

* docs(how-to): align agent count to 20 (matches README + CLAUDE.md)

The how-to said "18 agents" with UX/UI at one dev and no Intake — stale against
the authoritative count. Bump 18→20 (prose + spelled-out eighteen→twenty), give
UX/UI 2 devs, and add the Intake line to the org tree (Intake leads section 1, so
it belongs in the tree). README + CLAUDE.md already say 20.

* ci(release): publish all RoboCo images to GHCR + Docker Hub

The release published only the orchestrator to GHCR. Build and push the full set
the stack needs — agent-base, the 8 agent images, orchestrator, and panel — to
BOTH ghcr.io/rennf93/* and docker.io/renzof93/*, at :<version> and :latest, so
consumers can pull instead of compose-building.

- agent-base builds first (the agent images build FROM roboco-agent-base, a local
  tag), then the rest; push only after every build succeeds.
- Image names mirror the docker-compose `image:` values 1:1.
- Free disk on the runner first (11 images is space-heavy).
- Needs a DOCKERHUB_TOKEN repo secret for the Docker Hub login.
- SECURITY.md updated to reference both registries.

* ci(release): use short SHA as the image tag on manual dispatch

A workflow_dispatch runs against a branch, and the branch name (e.g.
feature/prompter-gold-upgrade) was used verbatim as the image tag — but "/" is
illegal in a Docker tag, so the first build failed instantly with "invalid
reference format". Releases still tag from the release tag; manual dispatch now
always uses the short SHA, which is a valid tag.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-06-09 17:08:34 +02:00
committed by GitHub
co-authored by Renn F
parent ae65bff883
commit 9f8834155a
63 changed files with 5607 additions and 832 deletions
+402
View File
@@ -0,0 +1,402 @@
"""Intake agent driver — a long-lived Claude Code session the human chats with.
The intake (``prompter``) agent is not a one-shot ``claude -p`` like every other
RoboCo agent; it is an interactive session. This driver is the container's
entrypoint: it opens ONE ``claude-agent-sdk`` ``ClaudeSDKClient`` (Claude Code
held open), then loops — pull the human's next message, stream the agent's reply
(token deltas, tool calls), wait for the next message — keeping conversation
context in-process. The container stays alive for the whole chat and is reaped
when the draft becomes a task.
The SDK call surface is isolated in ``SdkIntakeSession`` (lazy import, so this
module imports without ``claude-agent-sdk`` installed). The loop
(``IntakeDriver``) and event normalization are SDK-free and unit-tested with
fakes.
"""
from __future__ import annotations
import json
import re
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Protocol
import structlog
if TYPE_CHECKING:
from contextlib import AbstractAsyncContextManager
logger = structlog.get_logger()
# The intake agent emits the finished structured task draft as a fenced block
# (see the prompter system prompt). The driver mines it from the complete reply
# and surfaces it as one ``draft`` chunk for the panel's draft card.
_DRAFT_FENCE = re.compile(r"```roboco-draft\s*\n(.*?)```", re.DOTALL)
# ---------------------------------------------------------------------------
# Normalized stream chunk — what the panel SSE consumes. SDK-free.
# ---------------------------------------------------------------------------
@dataclass
class StreamChunk:
"""One normalized event in the agent's live reply.
``kind`` is the panel-facing event type; the rest is payload. Decoupled
from the SDK's message classes so the relay/panel never import the SDK.
"""
kind: str # text|thinking|tool_use|tool_result|turn_end|system|draft|error
text: str = ""
tool: str = ""
data: dict[str, Any] = field(default_factory=dict)
def _coerce_draft(data: Any) -> dict[str, Any] | None:
"""Return ``data`` as a draft dict (with a string ``title``), else ``None``.
Accepts a dict, or a JSON string the agent may have passed.
"""
if isinstance(data, str):
try:
data = json.loads(data)
except (ValueError, TypeError):
return None
if isinstance(data, dict) and isinstance(data.get("title"), str):
return data
return None
def _extract_draft(text: str) -> dict[str, Any] | None:
"""Parse a fenced ``roboco-draft`` JSON block out of the agent's reply.
A fallback to the ``propose_draft`` tool: returns the parsed object (a dict
with a string ``title``) or ``None`` when no well-formed block is present.
"""
match = _DRAFT_FENCE.search(text)
if match is None:
return None
return _coerce_draft(match.group(1))
def _draft_from_tool_input(tool_input: Any) -> dict[str, Any] | None:
"""Pull the draft out of a ``propose_draft`` tool call's input.
Tolerant of both shapes the agent might use: the draft nested under a
``draft`` key, or the draft fields passed flat as the input itself.
"""
if not isinstance(tool_input, dict):
return None
return _coerce_draft(tool_input.get("draft", tool_input))
def _is_propose_draft(name: str) -> bool:
"""True for the intake ``propose_draft`` tool, however the SDK namespaces it."""
return name == "propose_draft" or name.endswith("__propose_draft")
def _blocks_to_chunks(content: list[Any]) -> list[StreamChunk]:
"""Map an assistant message's content blocks to chunks (duck-typed).
Text is deliberately NOT re-emitted here: with ``include_partial_messages``
the live token deltas (``StreamEvent``) already streamed it, so re-emitting
the complete ``TextBlock`` would render every reply twice on the panel.
The canonical draft signal is the agent calling the **``propose_draft``**
tool — that ToolUseBlock becomes a single ``draft`` chunk. As a fallback (if
the agent types the spec instead of calling the tool) the complete text is
also mined for a fenced ``roboco-draft`` block. thinking + other tool_use
(which do NOT arrive as deltas) are emitted as before.
"""
chunks: list[StreamChunk] = []
text_parts: list[str] = []
draft: dict[str, Any] | None = None
for block in content or []:
if hasattr(block, "thinking"): # ThinkingBlock
chunks.append(StreamChunk(kind="thinking", text=str(block.thinking)))
elif hasattr(block, "name") and hasattr(block, "input"): # ToolUseBlock
name = str(block.name)
tool_input = getattr(block, "input", {})
if _is_propose_draft(name):
draft = draft or _draft_from_tool_input(tool_input)
else:
chunks.append(
StreamChunk(kind="tool_use", tool=name, data={"input": tool_input})
)
elif hasattr(block, "text"): # TextBlock — already streamed; mine for a draft
text_parts.append(str(block.text))
draft = draft or _extract_draft("".join(text_parts))
if draft is not None:
chunks.append(StreamChunk(kind="draft", data=draft))
return chunks
def _stream_event_to_chunks(msg: Any) -> list[StreamChunk]:
"""Extract a live text delta from a partial StreamEvent (token streaming)."""
event = getattr(msg, "event", None) or {}
delta = event.get("delta") if isinstance(event, dict) else None
if isinstance(delta, dict) and delta.get("type") == "text_delta":
text = str(delta.get("text", ""))
if text:
return [StreamChunk(kind="text", text=text)]
return []
def normalize(msg: Any) -> list[StreamChunk]:
"""Map a single ``claude-agent-sdk`` message to panel-facing chunks.
Duck-typed on type name + attributes so it works on real SDK messages and
on test fakes alike (no SDK import required).
"""
name = type(msg).__name__
if name == "StreamEvent":
return _stream_event_to_chunks(msg)
if name == "AssistantMessage":
return _blocks_to_chunks(getattr(msg, "content", []))
if name == "ResultMessage":
return [
StreamChunk(
kind="turn_end",
data={
"session_id": getattr(msg, "session_id", None),
"cost_usd": getattr(msg, "total_cost_usd", None),
},
)
]
if name == "SystemMessage":
return [
StreamChunk(kind="system", data={"subtype": getattr(msg, "subtype", "")})
]
return []
# ---------------------------------------------------------------------------
# Session seam — one conversational turn -> a stream of chunks.
# ---------------------------------------------------------------------------
class IntakeSession(Protocol):
"""A live agent session. ``send`` runs one turn and streams its chunks."""
def send(self, text: str) -> AsyncIterator[StreamChunk]: ...
# A factory that yields an async-context-managed IntakeSession (opens/closes
# the underlying client). Injected so the driver loop is testable with a fake.
SessionFactory = Callable[[], "AbstractAsyncContextManager[IntakeSession]"]
# Source of the human's messages (e.g. the in-container inbox). Returns None to
# signal shutdown (container being reaped).
MessageSource = Callable[[], Awaitable[str | None]]
# Where normalized chunks go (the relay -> panel SSE).
EventSink = Callable[[StreamChunk], Awaitable[None]]
# ---------------------------------------------------------------------------
# The driver loop — SDK-free, unit-tested with fakes.
# ---------------------------------------------------------------------------
class IntakeDriver:
"""Owns the chat loop for the lifetime of one intake session."""
def __init__(
self,
session_factory: SessionFactory,
next_message: MessageSource,
emit: EventSink,
) -> None:
self._session_factory = session_factory
self._next_message = next_message
self._emit = emit
self.log = logger.bind(component="intake_driver")
async def run(self) -> None:
"""Open the session and process human turns until shutdown.
One ``ClaudeSDKClient`` is held open across all turns (context persists
in-process). The loop ends when ``next_message`` returns ``None``.
"""
async with self._session_factory() as session:
self.log.info("Intake session opened")
turns = 0
while True:
text = await self._next_message()
if text is None:
self.log.info("Intake session closing", turns=turns)
return
turns += 1
self.log.info("Intake turn received", turn=turns, chars=len(text))
await self._run_turn(session, text)
async def _run_turn(self, session: IntakeSession, text: str) -> None:
"""Stream one turn's chunks to the sink, logging each tool call.
The conversation streams to the relay (panel), not stdout — so without
this, ``docker logs`` on the intake container is a black box between turn
start and end even while the agent reads the codebase and spawns subagents.
Logging each ``tool_use`` (and the draft) shows the turn's real shape;
text deltas are intentionally NOT logged (they'd spam). A failure ends as
an error chunk.
"""
chunks = 0
tools = 0
drafted = False
try:
async for chunk in session.send(text):
chunks += 1
if chunk.kind == "tool_use":
tools += 1
self.log.info("Intake tool use", tool=chunk.tool)
elif chunk.kind == "draft":
drafted = True
self.log.info("Intake draft emitted")
await self._emit(chunk)
except Exception as exc:
self.log.error("Intake turn failed", error=str(exc), chunks=chunks)
await self._emit(StreamChunk(kind="error", text=str(exc)))
else:
self.log.info(
"Intake turn streamed", chunks=chunks, tools=tools, drafted=drafted
)
# ---------------------------------------------------------------------------
# SDK adapter — the only SDK-coupled code (lazy import). Verified against
# claude-agent-sdk; not exercised in the gate (needs the live claude binary).
# ---------------------------------------------------------------------------
# The intake agent's hard tool allowlist: read-only built-ins + the draft tool.
_INTAKE_BASE_TOOLS: tuple[str, ...] = ("Read", "Grep", "Glob", "Task")
def build_intake_options(
*,
system_prompt: str,
cwd: str,
model: str | None = None,
) -> Any: # pragma: no cover - thin SDK construction
"""Build locked-down ``ClaudeAgentOptions`` for the intake session.
Isolation/security (smoke 2026-06-09 #11): the intake agent must NOT inherit
the host's personal Claude Code env (Gmail/Notion MCP, Write/Edit/Bash). So:
- ``strict_mcp_config=True`` + ``setting_sources=[]`` → ignore the host's
``~/.claude.json`` / ``settings.json``; use ONLY the MCP server below.
- ``permission_mode="dontAsk"`` (NOT ``bypassPermissions``) + a ``can_use_tool``
gate → a hard allowlist (Read/Grep/Glob/Task + ``propose_draft``), no prompts.
Draft emission (#10): the agent calls the ``propose_draft`` MCP tool, which the
driver turns into a ``draft`` event — deterministic, not a fragile text fence.
NOTE: ``setting_sources=[]`` must be validated against the mounted-``~/.claude``
auth on the next smoke; if auth breaks, narrow it instead of removing it.
"""
from claude_agent_sdk import (
ClaudeAgentOptions,
PermissionResultAllow,
PermissionResultDeny,
create_sdk_mcp_server,
tool,
)
@tool(
"propose_draft",
"Submit the finished task draft for the human to review and confirm. Call "
"this once the spec is complete. Pass a JSON object: title, objective, "
"what_this_builds[], the_work[] ({team, summary, items}), notes[], "
"acceptance_criteria[], team, scale, task_type, nature, "
"estimated_complexity, priority.",
{"draft": dict},
)
async def _propose_draft(_args: dict[str, Any]) -> dict[str, Any]:
# The driver intercepts this tool call (ToolUseBlock) and emits the draft
# event; the handler only acknowledges so the agent knows it landed.
return {
"content": [
{"type": "text", "text": "Draft submitted — the human can review it."}
]
}
server = create_sdk_mcp_server(
name="intake", version="1.0.0", tools=[_propose_draft]
)
async def _gate(tool_name: str, _input: dict[str, Any], _ctx: Any) -> Any:
if tool_name in _INTAKE_BASE_TOOLS or _is_propose_draft(tool_name):
return PermissionResultAllow()
# The intake's job is to ask questions, so it reaches for AskUserQuestion
# by reflex. It isn't wired to the live chat panel (and isn't allowed), so
# nudge it to just ask inline rather than leave it to stumble on a bare deny.
if tool_name == "AskUserQuestion" or tool_name.endswith("AskUserQuestion"):
return PermissionResultDeny(
message=(
"AskUserQuestion isn't available here — just write your "
"questions as a normal chat message; the human reads every "
"reply live."
)
)
# Plan mode is a Claude Code workflow the intake keeps slipping into; its
# "plan" is the propose_draft draft, so steer it straight there.
if tool_name == "ExitPlanMode" or tool_name.endswith("ExitPlanMode"):
return PermissionResultDeny(
message=(
"You don't use plan mode. When your spec is ready, call "
"propose_draft to produce the reviewable draft card — don't "
"announce a plan and wait."
)
)
# Generic deny, but guiding: the agent reflexively probes Claude Code
# built-ins (Write, ToolSearch, …). Tell it what it actually has.
return PermissionResultDeny(
message=(
f"{tool_name} is not available to the intake agent. Your only tools "
"are Read, Grep, Glob, Task, and propose_draft. Ask the human inline; "
"when the spec is ready, call propose_draft."
)
)
return ClaudeAgentOptions(
system_prompt=system_prompt,
cwd=cwd,
mcp_servers={"intake": server},
allowed_tools=[*_INTAKE_BASE_TOOLS, "mcp__intake__propose_draft"],
model=model,
include_partial_messages=True, # live token streaming
permission_mode="dontAsk",
strict_mcp_config=True,
setting_sources=[],
can_use_tool=_gate,
)
class SdkIntakeSession: # pragma: no cover - requires the live claude binary
"""``IntakeSession`` backed by a real ``ClaudeSDKClient``.
Async context manager: connects the client on enter, disconnects on exit.
``send`` runs one turn (query + receive_response) and yields normalized
chunks. The conversation context lives in the client across turns.
"""
def __init__(self, options: Any) -> None:
self._options = options
self._client: Any = None
async def __aenter__(self) -> SdkIntakeSession:
from claude_agent_sdk import ClaudeSDKClient
self._client = ClaudeSDKClient(options=self._options)
await self._client.connect()
return self
async def __aexit__(self, *exc: object) -> None:
if self._client is not None:
await self._client.disconnect()
async def send(self, text: str) -> AsyncIterator[StreamChunk]:
await self._client.query(text)
async for msg in self._client.receive_response():
for chunk in normalize(msg):
yield chunk
+163
View File
@@ -0,0 +1,163 @@
"""Container entrypoint for the intake (``prompter``) agent — the live session.
Runs as the agent-prompter container's command. Wires the ``IntakeDriver`` to:
- an in-process HTTP **receiver** (`POST /turn`) the orchestrator delivers the
human's messages to — this is the driver's ``MessageSource``;
- a **relay** ``EventSink`` that POSTs each ``StreamChunk`` to the
orchestrator's `/live/{session}/events` endpoint.
One long-lived ``ClaudeSDKClient`` (opened by the driver's ``SdkIntakeSession``)
holds the whole conversation. The container stays up until reaped.
The wiring helpers are unit-tested; ``main()`` (env + uvicorn + SDK) is not — it
needs the live container.
"""
from __future__ import annotations
import asyncio
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import TYPE_CHECKING
import httpx
import structlog
from fastapi import FastAPI
from pydantic import BaseModel, Field
from roboco.agent_sdk.intake_driver import (
IntakeDriver,
StreamChunk,
build_intake_options,
)
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Awaitable, Callable
logger = structlog.get_logger()
_RECEIVER_PORT = 9000 # ROBOCO_SDK_PORT — the orchestrator delivers messages here
class _Turn(BaseModel):
text: str = Field(..., min_length=1)
def make_message_source(
queue: asyncio.Queue[str | None],
) -> Callable[[], Awaitable[str | None]]:
"""A ``MessageSource`` backed by the receiver queue. ``None`` ends the loop."""
async def _next() -> str | None:
return await queue.get()
return _next
def make_relay_sink(
base_url: str, session_id: str, client: httpx.AsyncClient
) -> Callable[[StreamChunk], Awaitable[None]]:
"""An ``EventSink`` that POSTs each chunk to the orchestrator relay."""
url = f"{base_url}/api/prompter/live/{session_id}/events"
async def _emit(chunk: StreamChunk) -> None:
try:
await client.post(
url,
json={
"kind": chunk.kind,
"text": chunk.text,
"tool": chunk.tool,
"data": chunk.data,
},
)
except Exception as exc:
logger.error("Relay POST failed", session_id=session_id, error=str(exc))
return _emit
def build_receiver(queue: asyncio.Queue[str | None]) -> FastAPI:
"""The in-container HTTP receiver: `POST /turn` enqueues the human's message."""
app = FastAPI()
@app.post("/turn")
async def turn(body: _Turn) -> dict[str, bool]:
await queue.put(body.text)
return {"queued": True}
@app.get("/health")
async def health() -> dict[str, str]:
return {"status": "ok"}
return app
async def main() -> None: # pragma: no cover - needs the live container + SDK
"""Wire receiver + driver and run them concurrently for the chat's lifetime."""
import uvicorn
# Silence the Claude CLI's "configuration file not found at ~/.claude.json"
# warning (printed 3x at startup) that otherwise drowns the container logs.
# The CLI self-heals the file anyway; pre-creating an empty config just stops
# the noise before the SDK spawns the CLI. Best-effort — never fail the boot.
claude_json = Path.home() / ".claude.json"
if not claude_json.exists():
try:
claude_json.write_text("{}", encoding="utf-8")
except OSError as exc:
logger.warning("Could not pre-create ~/.claude.json", error=str(exc))
session_id = os.environ["ROBOCO_PROMPTER_SESSION_ID"]
base_url = os.environ.get("ROBOCO_API_URL", "http://roboco-orchestrator:8000")
cwd = os.environ.get("ROBOCO_WORKSPACE", "/data/workspace")
system_prompt = Path("/app/system-prompt.md").read_text(encoding="utf-8")
model = os.environ.get("CLAUDE_CODE_SUBAGENT_MODEL") or None
queue: asyncio.Queue[str | None] = asyncio.Queue()
client = httpx.AsyncClient(timeout=30.0)
# Tools + MCP + lockdown are all decided inside build_intake_options now
# (hard allowlist + the propose_draft tool + host-env isolation).
options = build_intake_options(
system_prompt=system_prompt,
cwd=cwd,
model=model,
)
from roboco.agent_sdk.intake_driver import SdkIntakeSession
@asynccontextmanager
async def session_factory() -> AsyncIterator[SdkIntakeSession]:
async with SdkIntakeSession(options) as session:
yield session
driver = IntakeDriver(
session_factory,
make_message_source(queue),
make_relay_sink(base_url, session_id, client),
)
# Bind all interfaces so the orchestrator reaches the receiver on the docker
# network. Built from octets (bandit B104 false positive — same as the SDK
# sidecar); override via ROBOCO_SDK_BIND_HOST for local dev.
bind_host = os.environ.get("ROBOCO_SDK_BIND_HOST", ".".join(["0"] * 4))
server = uvicorn.Server(
uvicorn.Config(
build_receiver(queue),
host=bind_host,
port=_RECEIVER_PORT,
log_level="warning",
)
)
logger.info("Intake container starting", session_id=session_id)
try:
await asyncio.gather(server.serve(), driver.run())
finally:
await client.aclose()
if __name__ == "__main__": # pragma: no cover
asyncio.run(main())
+7
View File
@@ -31,6 +31,7 @@ from roboco.api.routes.orchestrator import router as orchestrator_router
from roboco.api.routes.product import router as product_router
from roboco.api.routes.project import router as project_router
from roboco.api.routes.prompter import router as prompter_router
from roboco.api.routes.prompter_live import router as prompter_live_router
from roboco.api.routes.provider import router as provider_router
from roboco.api.routes.sessions import router as sessions_router
from roboco.api.routes.stream import router as stream_router
@@ -318,6 +319,12 @@ def create_app() -> FastAPI:
prefix=f"{api_prefix}/prompter",
tags=["Prompter"],
)
# Prompter live chat — panel <-> spawned intake agent (SSE + relay)
app.include_router(
prompter_live_router,
prefix=f"{api_prefix}/prompter",
tags=["Prompter"],
)
# Work Sessions
app.include_router(
+36 -25
View File
@@ -26,8 +26,8 @@ from roboco.api.schemas.prompter import (
PrompterDraftTask,
PrompterMessageRequest,
PrompterMessageResponse,
PrompterSessionCreateRequest,
PrompterSessionResponse,
PrompterTurnResponse,
TaskConfirmRequest,
TaskDraftResponse,
)
@@ -70,23 +70,24 @@ def _translate_error(e: ServiceError) -> HTTPException:
status_code=status.HTTP_201_CREATED,
)
async def create_session(
data: PrompterSessionCreateRequest,
db: DbSession,
agent: CurrentAgentContext,
) -> PrompterSessionResponse:
"""Create a new Prompter conversation session linked to the authenticated agent."""
service = get_prompter_service(db)
try:
session = await service.create_session(
agent_id=agent.agent_id,
context=data.context,
)
session = await service.create_session(agent_id=agent.agent_id)
except ServiceError as e:
raise _translate_error(e) from e
# Commit explicitly: the rest of the write surface (tasks, a2a, ...) does
# the same rather than rely on the request-teardown auto-commit, which is
# sensitive to middleware/teardown ordering. Without this the 201 is
# returned but the row may never persist, so the next request 404s.
await db.commit()
return PrompterSessionResponse(
id=session.id, # type: ignore[arg-type]
agent_id=session.agent_id, # type: ignore[arg-type]
id=UUID(str(session.id)),
agent_id=UUID(str(session.agent_id)),
status=session.status,
created_at=session.created_at,
updated_at=session.updated_at,
@@ -95,21 +96,22 @@ async def create_session(
@router.post(
"/sessions/{session_id}/messages",
response_model=list[PrompterMessageResponse],
response_model=PrompterTurnResponse,
)
async def send_message(
session_id: UUID,
data: PrompterMessageRequest,
db: DbSession,
agent: CurrentAgentContext,
) -> list[PrompterMessageResponse]:
) -> PrompterTurnResponse:
"""
Accept a user message, append it and an AI assistant response to the
conversation, and return the updated message list.
conversation, and return the updated message list plus the readiness
signal (``draft_ready`` and the coarse ``scale`` hint) for this turn.
"""
service = get_prompter_service(db)
try:
messages = await service.send_message(
turn = await service.send_message(
session_id=session_id,
agent_id=agent.agent_id,
content=data.content,
@@ -117,17 +119,22 @@ async def send_message(
)
except ServiceError as e:
raise _translate_error(e) from e
await db.commit()
return [
PrompterMessageResponse(
id=msg.id, # type: ignore[arg-type]
session_id=msg.session_id, # type: ignore[arg-type]
role=msg.role,
content=msg.content,
created_at=msg.created_at,
)
for msg in messages
]
return PrompterTurnResponse(
messages=[
PrompterMessageResponse(
id=UUID(str(msg.id)),
session_id=UUID(str(msg.session_id)),
role=msg.role,
content=msg.content,
created_at=msg.created_at,
)
for msg in turn.messages
],
draft_ready=turn.draft_ready,
scale=turn.scale,
)
@router.get(
@@ -153,6 +160,8 @@ async def get_draft(
)
except ServiceError as e:
raise _translate_error(e) from e
# Persist a newly generated draft (no-op when it was already cached).
await db.commit()
# Parse the stored draft_data into PrompterDraftTask for validation
try:
@@ -168,11 +177,11 @@ async def get_draft(
) from exc
return TaskDraftResponse(
id=draft_record.id, # type: ignore[arg-type]
session_id=draft_record.session_id, # type: ignore[arg-type]
id=UUID(str(draft_record.id)),
session_id=UUID(str(draft_record.session_id)),
draft=draft_task,
confirmed_at=draft_record.confirmed_at,
task_id=draft_record.task_id, # type: ignore[arg-type]
task_id=UUID(str(draft_record.task_id)) if draft_record.task_id else None,
created_at=draft_record.created_at,
)
@@ -203,10 +212,12 @@ async def confirm_draft(
product_id=data.product_id,
assigned_to=data.assigned_to,
extra=data.overrides,
draft=data.draft.model_dump(mode="json") if data.draft else None,
),
)
except ServiceError as e:
raise _translate_error(e) from e
await db.commit()
return {"task_id": str(task_id)}
+230
View File
@@ -0,0 +1,230 @@
"""Live intake chat — the panel <-> spawned-agent bridge.
Endpoints over the in-process ``PrompterLiveRegistry``:
- ``POST /live/start`` — spawn the intake container for a scope.
- ``GET /live/{session_id}/stream`` — SSE: the agent's live events to the panel.
- ``POST /live/{session_id}/messages`` — the human's message in (panel -> agent).
- ``POST /live/{session_id}/stop`` — reap the session (panel close / confirm).
- ``POST /live/{session_id}/events`` — the agent's events in (container -> relay).
Streaming/messaging require the session to be live (its ``prompter`` container
spawned, which calls ``registry.open``). Auth is intentionally light here —
sessions are keyed by an opaque id on a trusted network; token enforcement is
Phase 5.
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Literal
from uuid import UUID, uuid4
from fastapi import APIRouter, HTTPException, Request, status
from pydantic import BaseModel, Field, model_validator
from sse_starlette import EventSourceResponse
from roboco.api.deps import CurrentAgentContext, DbSession, get_orchestrator
from roboco.services.base import NotFoundError, ServiceError, ValidationError
from roboco.services.prompter import get_prompter_service
from roboco.services.prompter_live import get_live_registry
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
router = APIRouter()
def _translate_service_error(e: ServiceError) -> HTTPException:
"""Service error → HTTP status (mirrors the legacy prompter route)."""
if isinstance(e, NotFoundError):
return HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"error": "not_found", "message": e.message},
)
if isinstance(e, ValidationError):
return HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"error": "validation_error",
"message": e.message,
"field": e.field,
},
)
return HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={"error": "internal_error", "message": e.message},
)
class StartLiveRequest(BaseModel):
"""Open a live intake chat scoped to a project XOR a product."""
project_id: UUID | None = None
product_id: UUID | None = None
initial_message: str | None = Field(default=None, min_length=1)
@model_validator(mode="after")
def _exactly_one_scope(self) -> StartLiveRequest:
if bool(self.project_id) == bool(self.product_id):
raise ValueError("provide exactly one of project_id / product_id")
return self
class StartLiveResponse(BaseModel):
"""The new session's id — the panel opens its stream and posts messages to it."""
session_id: str
class LiveMessageRequest(BaseModel):
"""The human's message in an active intake chat."""
text: str = Field(..., min_length=1)
class AgentEvent(BaseModel):
"""One normalized event the container relays (mirrors driver.StreamChunk)."""
kind: str
text: str = ""
tool: str = ""
data: dict[str, Any] = Field(default_factory=dict)
@router.post(
"/live/start",
response_model=StartLiveResponse,
status_code=status.HTTP_201_CREATED,
)
async def start_live(body: StartLiveRequest, db: DbSession) -> StartLiveResponse:
"""Spawn the intake agent for a new chat and return its session id.
The panel then opens ``/live/{session_id}/stream`` and posts messages to
``/live/{session_id}/messages``. An ``initial_message`` is delivered to the
agent automatically once its container is reachable.
"""
project_slug: str | None = None
if body.project_id is not None:
from roboco.services.project import get_project_service
project = await get_project_service(db).get(body.project_id)
if project is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Project {body.project_id} not found",
)
project_slug = project.slug
session_id = uuid4().hex
try:
# Non-blocking: opens the relay + spawns the container in the background,
# so this request returns immediately (no 60s timeout on clone/build/run).
await get_orchestrator().start_intake_session(
session_id,
project_slug=project_slug,
product_id=str(body.product_id) if body.product_id else None,
initial_message=body.initial_message,
)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to start intake session: {exc}",
) from exc
return StartLiveResponse(session_id=session_id)
@router.get("/live/{session_id}/stream")
async def stream(session_id: str, request: Request) -> EventSourceResponse:
"""Stream the agent's live events (token deltas, tool calls) to the panel."""
registry = get_live_registry()
async def events() -> AsyncGenerator[dict[str, Any]]:
async for event in registry.stream(session_id):
if await request.is_disconnected():
break
yield {"event": event.get("kind", "message"), "data": json.dumps(event)}
return EventSourceResponse(events(), ping=15)
@router.post("/live/{session_id}/messages")
async def send_message(session_id: str, body: LiveMessageRequest) -> dict[str, bool]:
"""Deliver the human's message to the running intake agent."""
delivered = await get_live_registry().deliver(session_id, body.text)
if not delivered:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"error": "not_found",
"message": f"No live intake session {session_id} (spawn it first).",
},
)
return {"delivered": True}
@router.post("/live/{session_id}/stop")
async def stop_live(session_id: str) -> dict[str, bool]:
"""Reap the live intake session (panel close, or draft confirmed)."""
await get_orchestrator().reap_intake_session(session_id)
return {"stopped": True}
class LiveConfirmRequest(BaseModel):
"""Confirm the agent's draft → a task, scoped to exactly one target.
``route`` is which start button the human pressed: ``"board"`` (Board review
& Start → PO + HoM review first) or ``"main_pm"`` (Approve & Start → straight
to the Main PM).
"""
project_id: UUID | None = None
product_id: UUID | None = None
draft: dict[str, Any]
route: Literal["board", "main_pm"] = "board"
@model_validator(mode="after")
def _exactly_one_target(self) -> LiveConfirmRequest:
if bool(self.project_id) == bool(self.product_id):
raise ValueError("provide exactly one of project_id / product_id")
return self
@router.post("/live/{session_id}/confirm", status_code=status.HTTP_201_CREATED)
async def confirm_live(
session_id: str,
body: LiveConfirmRequest,
db: DbSession,
agent: CurrentAgentContext,
) -> dict[str, str]:
"""Turn the agent's confirmed draft into a started (pending) task, then reap.
Per ``route``: "Board review & Start" assigns it to the Board (PO + HoM
review first); "Approve & Start" assigns it straight to the Main PM.
Attributed to the confirming agent (the CEO). On success the live session is
reaped — the chat is over once the draft is a task.
"""
service = get_prompter_service(db)
try:
task_id = await service.confirm_live_draft(
body.draft,
agent.agent_id,
project_id=body.project_id,
product_id=body.product_id,
route=body.route,
)
except ServiceError as e:
raise _translate_service_error(e) from e
await db.commit()
# The draft is now a task — reap the agent + close the relay stream.
await get_orchestrator().reap_intake_session(session_id)
return {"task_id": str(task_id)}
@router.post("/live/{session_id}/events")
async def relay_event(session_id: str, event: AgentEvent) -> dict[str, bool]:
"""Relay one agent event from the container onto the session's stream."""
return {"pushed": get_live_registry().push(session_id, event.model_dump())}
+68 -9
View File
@@ -45,15 +45,6 @@ class ChatMessage(BaseModel):
# =============================================================================
class PrompterSessionCreateRequest(BaseModel):
"""Request body for POST /api/prompter/sessions."""
context: dict[str, Any] = Field(
default_factory=dict,
description="Optional bootstrap context (project_id, team, etc.)",
)
class PrompterSessionResponse(BaseModel):
"""Response for session creation and retrieval."""
@@ -88,6 +79,21 @@ class PrompterMessageResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
class PrompterTurnResponse(BaseModel):
"""Result of a chat turn: the full message list plus the readiness signal.
Carries ``draft_ready`` (and the coarse ``scale`` hint) so the frontend
consumes the backend's judgement instead of re-deriving it by string match.
"""
messages: list[PrompterMessageResponse]
draft_ready: bool = False
scale: str | None = Field(
default=None,
description="Coarse size hint from the assistant: 'single' or 'multi'",
)
class TaskConfirmRequest(BaseModel):
"""Request body for POST /api/prompter/sessions/{id}/confirm.
@@ -111,6 +117,14 @@ class TaskConfirmRequest(BaseModel):
default_factory=dict,
description="Additional fields to override in the draft before task creation",
)
draft: "PrompterDraftTask | None" = Field(
default=None,
description=(
"The human-edited structured draft. When present it replaces the "
"stored draft (after re-validation and description re-composition) "
"before the task is created."
),
)
# =============================================================================
@@ -118,11 +132,35 @@ class TaskConfirmRequest(BaseModel):
# =============================================================================
class CellWork(BaseModel):
"""One cell's slice of a task's work — the per-cell breakdown of The Work.
For a single-cell task there is exactly one entry; a board-led feature
carries one entry per participating cell.
"""
team: Team = Field(
..., description="The cell (or coordinating team) doing this work"
)
summary: str = Field(
..., min_length=1, description="One-line summary of this cell's slice"
)
items: list[str] = Field(
default_factory=list, description="Concrete deliverables for this cell"
)
class PrompterDraftTask(BaseModel):
"""A task draft produced by the Prompter.
Mirrors TaskCreate fields so the frontend can POST /api/tasks
with confirmed_by_human=True after human review.
The structured spec fields (``objective``, ``what_this_builds``,
``the_work``, ``notes``) are first-class in this contract but persisted
inside the existing ``draft_data`` JSONB column — no migration. The backend
composes ``description`` deterministically from them; ``acceptance_criteria``
renders as Success Criteria.
"""
title: str = Field(..., min_length=1, max_length=200)
@@ -133,6 +171,23 @@ class PrompterDraftTask(BaseModel):
task_type: TaskType = Field(...)
nature: TaskNature = Field(...)
estimated_complexity: Complexity = Field(...)
# Structured spec fields — optional for backward compatibility.
objective: str | None = Field(
default=None,
description="The outcome this task delivers, in one or two sentences",
)
what_this_builds: list[str] = Field(
default_factory=list, description="Concrete artifacts this task produces"
)
the_work: list[CellWork] = Field(
default_factory=list,
description="Per-cell breakdown; length drives single vs multi-cell",
)
notes: list[str] = Field(
default_factory=list,
description="Constraints, reuse pointers, things to confirm with the human",
)
project_id: str | None = Field(
default=None,
description=(
@@ -161,6 +216,10 @@ class PrompterDraftTask(BaseModel):
confirmed_by_human: bool = False
# Resolve TaskConfirmRequest.draft now that PrompterDraftTask exists.
TaskConfirmRequest.model_rebuild()
class TaskDraftResponse(BaseModel):
"""Response for GET /api/prompter/sessions/{id}/draft."""
+12
View File
@@ -28,6 +28,7 @@ class Role(StrEnum):
PRODUCT_OWNER = "product_owner"
HEAD_MARKETING = "head_marketing"
AUDITOR = "auditor"
PROMPTER = "prompter" # intake interviewer — talks only to the human, drafts tasks
CEO = "ceo"
SYSTEM = "system" # sentinel only — used for orchestrator-generated rows
@@ -53,6 +54,7 @@ CELL_TEAMS: frozenset[Team] = frozenset({Team.BACKEND, Team.FRONTEND, Team.UX_UI
class RoleLevel(IntEnum):
SYSTEM = -1
INTAKE = 0 # read-only intake interviewer — lowest real-agent authority
DEV = 1
QA = 2
DOCUMENTER = 3
@@ -189,6 +191,15 @@ AGENTS: dict[str, AgentRow] = {
"auditor": AgentRow(
"auditor", Role.AUDITOR, Team.BOARD, _u("00000000-0000-0000-0004-000000000004")
),
# Intake interviewer — CEO-adjacent (board team), but NOT a board reviewer
# (deliberately absent from BOARD_ROLES). Spawned on demand to chat with the
# human and draft a task; talks to no other agent.
"intake-1": AgentRow(
"intake-1",
Role.PROMPTER,
Team.BOARD,
_u("00000000-0000-0000-0004-000000000005"),
),
}
@@ -213,6 +224,7 @@ ROLE_LEVEL: dict[Role, RoleLevel] = {
Role.PRODUCT_OWNER: RoleLevel.BOARD,
Role.HEAD_MARKETING: RoleLevel.BOARD,
Role.AUDITOR: RoleLevel.AUDITOR,
Role.PROMPTER: RoleLevel.INTAKE,
Role.CEO: RoleLevel.CEO,
}
+3
View File
@@ -58,6 +58,9 @@ ROLE_READ_TIERS: dict[Role, ReadTier] = {
Role.PRODUCT_OWNER: ReadTier.ALL_CELLS,
Role.HEAD_MARKETING: ReadTier.ALL_CELLS,
Role.AUDITOR: ReadTier.ALL,
# Intake interviewer is isolated — talks only to the human, reads only its
# own journal.
Role.PROMPTER: ReadTier.OWN,
Role.CEO: ReadTier.ALL,
}
+6 -1
View File
@@ -906,7 +906,12 @@ _INTENT_VERBS: dict[str, IntentSpec] = {
| _QA_ROLES
| _DOC_ROLES
| _PM_ROLES
| {Role.PRODUCT_OWNER, Role.HEAD_MARKETING, Role.AUDITOR}
| {
Role.PRODUCT_OWNER,
Role.HEAD_MARKETING,
Role.AUDITOR,
Role.PROMPTER,
}
),
description=(
"Signal you have no active work. PMs auto-pause owned in_progress tasks."
+2
View File
@@ -107,4 +107,6 @@ ROLE_MODEL_MAP: dict[str, str] = {
"product_owner": "opus",
"head_marketing": "opus",
"ceo": "opus",
# Intake interviewer — reads real code and drafts the spec; needs to be sharp.
"prompter": "opus",
}
+454 -12
View File
@@ -26,7 +26,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
import httpx
if TYPE_CHECKING:
from collections.abc import Callable
from collections.abc import Callable, Coroutine
from roboco.services.llm import AgentRoute
from roboco.services.task import TaskService
@@ -69,6 +69,12 @@ AgentConfig = OrchestratorAgentConfig
AGENT_NETWORK = "roboco_default"
AGENT_BASE_IMAGE = "roboco-agent-base"
# The intake (prompter) agent: a single seeded, board-adjacent interviewer.
# Unlike delivery agents it is never dispatched and runs ONE persistent
# container at a time (single CEO → one live chat). See the INTAKE section
# below and roboco/agent_sdk/intake_main.py.
INTAKE_AGENT_ID = "intake-1"
# Role -> Image mapping
# Specialized images extend the base with role-specific tools
AGENT_IMAGES: dict[str, str] = {
@@ -95,6 +101,8 @@ AGENT_IMAGES: dict[str, str] = {
"product-owner": "roboco-agent-pm",
"head-marketing": "roboco-agent-pm",
"auditor": "roboco-agent-pm",
# Intake — persistent Agent-SDK driver, not a one-shot `claude -p`.
INTAKE_AGENT_ID: "roboco-agent-prompter",
}
@@ -129,6 +137,21 @@ class _SlaBreach:
sla_seconds: int
@dataclass(frozen=True)
class _IntakeRunSpec:
"""Inputs for ``_build_intake_run_cmd``, bundled to keep the signature small."""
container_name: str
image: str
hosts: dict[str, str | None]
session_id: str
cwd: str
cli_model: str
api_url: str
provider_base_url: str | None
provider_auth_token: str | None
def _read_project_slug(task: dict[str, Any]) -> str | None:
"""Extract project slug from a task payload shape-tolerantly."""
slug = task.get("project_slug")
@@ -636,6 +659,7 @@ class AgentOrchestrator:
"roboco-agent-qa-fe": "agent-qa-fe.Dockerfile",
"roboco-agent-doc": "agent-doc.Dockerfile",
"roboco-agent-ux": "agent-ux.Dockerfile",
"roboco-agent-prompter": "agent-prompter.Dockerfile",
}
dockerfile = dockerfile_map.get(image)
if dockerfile:
@@ -2451,6 +2475,395 @@ class AgentOrchestrator:
git_context=self._task_git_context(task),
)
# =========================================================================
# INTAKE (PROMPTER) LIVE SESSION
#
# The intake agent is not task-driven and is never dispatched. It is a
# persistent Claude-Agent-SDK driver the CEO chats with live (the container
# entrypoint is roboco.agent_sdk.intake_main). One fixed container —
# `intake-1`, the seeded board-adjacent interviewer — serves one live
# session at a time (single CEO; one-session-per-CEO).
#
# This spawn is a DELIBERATELY separate path from spawn_agent: no task, no
# readiness gate, no `claude -p` CLI args (the image ENTRYPOINT is the
# driver), no settings.json/hook mount (the driver owns the receiver on
# port 9000, not the inbox sidecar), and no MCP/gateway surface (the live
# agent reads code with Read/Grep/Glob and talks only to the human).
# =========================================================================
async def start_intake_session(
self,
session_id: str,
*,
project_slug: str | None = None,
product_id: str | None = None,
initial_message: str | None = None,
) -> None:
"""Non-blocking start: open the relay now, spawn the container in the bg.
The panel's ``POST /live/start`` returns immediately rather than blocking
on the workspace clone + first-time image build + ``docker run`` (which
can exceed the HTTP timeout the cause of the "Request timed out" the
panel showed). The panel opens the SSE stream right away; the agent's
first reply arrives once the container is up. A spawn failure is pushed
onto the relay as an ``error`` event and closes the session, so the panel
shows it instead of hanging. Exactly one of ``project_slug`` /
``product_id`` must be given.
"""
if bool(project_slug) == bool(product_id):
raise ValueError(
"intake scope requires exactly one of project_slug / product_id"
)
self._open_intake_relay(session_id)
self._schedule_bg(
self._spawn_intake_container_guarded(
session_id,
project_slug=project_slug,
product_id=product_id,
initial_message=initial_message,
)
)
async def spawn_intake_session(
self,
session_id: str,
*,
project_slug: str | None = None,
product_id: str | None = None,
initial_message: str | None = None,
) -> AgentInstance:
"""Spawn the intake container for one live chat, **synchronously**.
Opens the relay then clones + launches the container, awaiting the whole
thing. Prefer ``start_intake_session`` on the request path; this blocking
variant is for direct/internal callers and tests. Exactly one of
``project_slug`` / ``product_id`` must be given.
"""
if bool(project_slug) == bool(product_id):
raise ValueError(
"intake scope requires exactly one of project_slug / product_id"
)
self._open_intake_relay(session_id)
return await self._spawn_intake_container(
session_id,
project_slug=project_slug,
product_id=product_id,
initial_message=initial_message,
)
@staticmethod
def _open_intake_relay(session_id: str) -> None:
"""Register the live relay session so the SSE stream connects immediately."""
from roboco.services.prompter_live import get_live_registry
get_live_registry().open(session_id, INTAKE_AGENT_ID)
async def _spawn_intake_container_guarded(
self,
session_id: str,
*,
project_slug: str | None,
product_id: str | None,
initial_message: str | None,
) -> None:
"""Background container spawn; surface failures on the relay, not silently."""
from roboco.services.prompter_live import get_live_registry
try:
await self._spawn_intake_container(
session_id,
project_slug=project_slug,
product_id=product_id,
initial_message=initial_message,
)
except Exception as exc:
logger.error(
"Intake container spawn failed", session_id=session_id, error=str(exc)
)
registry = get_live_registry()
registry.push(
session_id,
{"kind": "error", "text": f"Couldn't start the intake agent: {exc}"},
)
registry.close(session_id)
async def _spawn_intake_container(
self,
session_id: str,
*,
project_slug: str | None,
product_id: str | None,
initial_message: str | None,
) -> AgentInstance:
"""Clone the scope, launch the SDK-driver container, track the instance.
The relay must already be open (``_open_intake_relay``). Heavy + slow
(clone + first-time image build + docker run) keep it off the request
path via ``start_intake_session``.
"""
# Single live session: reap any prior intake container before spawning.
if INTAKE_AGENT_ID in self._instances:
await self.stop_agent(INTAKE_AGENT_ID, graceful=False)
cwd, cloned = await self._clone_intake_scope(project_slug, product_id)
prompt_path = self._generate_composed_prompt(INTAKE_AGENT_ID)
route = await self._resolve_agent_route(INTAKE_AGENT_ID)
cli_model = _resolve_agent_cli_model(
route.provider_type.value, route.model_name
)
api_url = (
"http://roboco-orchestrator:8000"
if PROJECT_HOST_PATH
else f"http://127.0.0.1:{settings.port}"
)
await self._ensure_agent_image(INTAKE_AGENT_ID)
container_name = f"roboco-agent-{INTAKE_AGENT_ID}"
await self._remove_container(container_name)
cmd = self._build_intake_run_cmd(
_IntakeRunSpec(
container_name=container_name,
image=get_agent_image(INTAKE_AGENT_ID),
hosts=self._resolve_intake_host_paths(),
session_id=session_id,
cwd=cwd,
cli_model=cli_model,
api_url=api_url,
provider_base_url=route.base_url,
provider_auth_token=route.auth_token,
)
)
container_id = await self._run_container_cmd(cmd)
config = AgentConfig(
agent_id=INTAKE_AGENT_ID,
blueprint_path=prompt_path,
model=route.model_name,
git_context=None,
)
instance = AgentInstance(
agent_id=INTAKE_AGENT_ID,
state=AgentState.ACTIVE,
config=config,
current_task_id=None,
)
instance.container_id = container_id
instance.started_at = datetime.now(UTC)
instance.last_activity = datetime.now(UTC)
self._instances[INTAKE_AGENT_ID] = instance
# The relay was already opened on the request path (start_intake_session /
# spawn_intake_session) BEFORE the panel connected its SSE stream. Do NOT
# re-open here: a second open would swap in a fresh queue and orphan that
# already-connected stream (the agent's replies would push to the new queue
# while the browser keeps reading the old one). open() is idempotent now as
# a guard, but the redundant call is gone regardless.
logger.info(
"Intake session spawned",
session_id=session_id,
container_id=container_id[:12],
cwd=cwd,
repos=len(cloned),
)
self._fire_audit(
event_type="agent.spawned",
agent_slug=INTAKE_AGENT_ID,
details={"session_id": session_id, "cwd": cwd, "repos": cloned},
)
if initial_message:
self._schedule_intake_first_message(session_id, initial_message)
return instance
async def reap_intake_session(self, session_id: str) -> None:
"""End a live chat: close the relay stream and stop the container."""
from roboco.services.prompter_live import get_live_registry
get_live_registry().close(session_id)
await self.stop_agent(INTAKE_AGENT_ID, graceful=True)
logger.info("Intake session reaped", session_id=session_id)
async def _clone_intake_scope(
self, project_slug: str | None, product_id: str | None
) -> tuple[str, list[str]]:
"""Clone the chat scope's repo(s); return (container cwd, all paths).
``project`` one repo; ``product`` each distinct cell project (the
Main-PM-style distinct-repo set, kept in its deterministic team order so
the primary is stable). The agent's cwd is the primary project's intake
workspace; for a product the sibling repos sit alongside it under
``/data/workspaces`` and are readable via Grep/Glob/Read.
"""
from roboco.db.base import get_session_factory
from roboco.services.workspace import WorkspaceService
team = get_agent_team(INTAKE_AGENT_ID) or "board"
factory = get_session_factory()
async with factory() as db:
slugs = await self._intake_scope_slugs(db, project_slug, product_id)
ws = WorkspaceService(db)
for slug in slugs:
await ws.ensure_workspace(slug, INTAKE_AGENT_ID)
# Container-side paths (the workspaces tree is mounted at
# /data/workspaces inside the container, regardless of the host root).
paths = [_agent_workspace_path(slug, team, INTAKE_AGENT_ID) for slug in slugs]
return paths[0], paths
@staticmethod
async def _intake_scope_slugs(
db: Any, project_slug: str | None, product_id: str | None
) -> list[str]:
"""Resolve the chat scope to the project slug(s) to clone."""
if project_slug:
return [project_slug]
if not product_id:
raise ValueError("intake scope requires project_slug or product_id")
from uuid import UUID
from roboco.services.product import ProductService
from roboco.services.project import get_project_service
project_ids = await ProductService(db).distinct_project_ids(UUID(product_id))
project_svc = get_project_service(db)
slugs: list[str] = []
for pid in project_ids:
project = await project_svc.get(pid)
if project and project.slug:
slugs.append(project.slug)
if not slugs:
raise ValueError(f"product {product_id} resolves to no projects")
return slugs
def _resolve_intake_host_paths(self) -> dict[str, str | None]:
"""Host paths for the intake container's three mounts (claude/prompt/ws).
Mirrors ``_resolve_host_paths`` but only for what the driver needs
there is no settings.json, MCP config, or briefing for the intake agent.
"""
if PROJECT_HOST_PATH:
return {
"claude": CLAUDE_AUTH_HOST_PATH,
"prompt": (
f"{DATA_HOST_PATH}/prompts-generated/{INTAKE_AGENT_ID}-prompt.md"
),
"workspaces": f"{DATA_HOST_PATH}/workspaces",
}
return {
"claude": CLAUDE_AUTH_HOST_PATH,
"prompt": str(
Path(tempfile.gettempdir())
/ "roboco-prompts"
/ f"{INTAKE_AGENT_ID}-prompt.md"
),
"workspaces": str(Path(settings.workspaces_root)),
}
@staticmethod
def _build_intake_run_cmd(spec: _IntakeRunSpec) -> list[str]:
"""Compose the `docker run` argv for the persistent intake container.
No claude CLI args (the image ENTRYPOINT is the SDK driver), no
settings.json/hook mount (the driver owns port 9000), no MCP config.
The driver reads ``/app/system-prompt.md`` and the env below.
"""
cmd: list[str] = [
"docker",
"run",
"-d",
"--name",
spec.container_name,
"--network",
AGENT_NETWORK,
"-v",
f"{spec.hosts['claude']}:/home/agent/.claude",
]
AgentOrchestrator._append_claude_json_mount(cmd, spec.hosts)
cmd.extend(
[
"-v",
f"{spec.hosts['prompt']}:/app/system-prompt.md:ro",
"-v",
f"{spec.hosts['workspaces']}:/data/workspaces",
"-e",
f"ROBOCO_AGENT_ID={INTAKE_AGENT_ID}",
"-e",
f"ROBOCO_AGENT_ROLE={get_agent_role(INTAKE_AGENT_ID) or 'prompter'}",
"-e",
f"ROBOCO_API_URL={spec.api_url}",
"-e",
f"ROBOCO_PROMPTER_SESSION_ID={spec.session_id}",
"-e",
f"ROBOCO_WORKSPACE={spec.cwd}",
"-e",
f"CLAUDE_CODE_SUBAGENT_MODEL={spec.cli_model}",
]
)
# Non-Anthropic providers need explicit endpoint/token; the Anthropic
# default uses the mounted ~/.claude login (same as every agent).
if spec.provider_base_url:
cmd.extend(["-e", f"ANTHROPIC_BASE_URL={spec.provider_base_url}"])
if spec.provider_auth_token:
cmd.extend(["-e", f"ANTHROPIC_AUTH_TOKEN={spec.provider_auth_token}"])
cmd.append(spec.image)
return cmd
async def _run_container_cmd(self, cmd: list[str]) -> str:
"""Run a detached `docker run` and return the container id."""
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
if proc.returncode != 0:
raise RuntimeError(f"Failed to start intake container: {stderr.decode()}")
return stdout.decode().strip()
def _schedule_bg(self, coro: "Coroutine[Any, Any, None]") -> None:
"""Fire-and-forget a coroutine, strong-reffed so it isn't GC'd mid-flight.
Silently no-ops when there's no running loop (sync unit tests); the coro
is closed to avoid a "never awaited" warning.
"""
import contextlib as _ctx
try:
loop = asyncio.get_running_loop()
except RuntimeError:
with _ctx.suppress(Exception):
coro.close()
return
bg = loop.create_task(coro)
self._bg_tasks.add(bg)
bg.add_done_callback(self._bg_tasks.discard)
def _schedule_intake_first_message(self, session_id: str, text: str) -> None:
"""Fire-and-forget the opening message once the container is reachable."""
self._schedule_bg(self._deliver_when_ready(session_id, text))
async def _deliver_when_ready(
self,
session_id: str,
text: str,
*,
attempts: int = 30,
delay: float = 1.0,
) -> None:
"""Retry-deliver the first message until the container receiver is up."""
from roboco.services.prompter_live import get_live_registry
registry = get_live_registry()
for _ in range(attempts):
if await registry.deliver(session_id, text):
return
await asyncio.sleep(delay)
logger.warning(
"Intake first message never delivered (receiver never came up)",
session_id=session_id,
)
# =========================================================================
# AGENT STOPPING
# =========================================================================
@@ -2799,6 +3212,39 @@ Start by:
# same session.
await self._sweep_budget_exceeded()
@staticmethod
async def _fetch_budget_status(
client: httpx.AsyncClient, url: str, agent_id: str
) -> dict[str, Any] | None:
"""Read an agent's SDK budget status; None if unreachable/not-JSON.
The SDK being unreachable is benign (container not yet started, already
gone, or a transient blip) and the health loop covers genuine failures,
so the failure is swallowed but logged at debug so it is observable
rather than silent (the bare try/except/continue it replaced was not).
"""
try:
resp = await client.get(url)
except httpx.HTTPError as exc:
logger.debug(
"Budget status unreachable; skipping agent this sweep",
agent_id=agent_id,
error=str(exc),
)
return None
if resp.status_code != http_status.HTTP_200_OK:
return None
try:
data = resp.json()
except ValueError as exc:
logger.debug(
"Budget status not JSON; skipping agent this sweep",
agent_id=agent_id,
error=str(exc),
)
return None
return data if isinstance(data, dict) else None
async def _sweep_budget_exceeded(self) -> None:
"""Stop agents whose per-session SDK budget reports halt=true.
@@ -2818,16 +3264,8 @@ Start by:
):
continue
url = f"http://roboco-agent-{agent_id}:9000/budget/status"
try:
resp = await client.get(url)
if resp.status_code != http_status.HTTP_200_OK:
continue
data = resp.json()
except Exception:
# SDK unreachable / not yet started / container gone —
# either benign or covered by health loop.
continue
if not data.get("halt"):
data = await self._fetch_budget_status(client, url, agent_id)
if data is None or not data.get("halt"):
continue
logger.warning(
"Agent budget exceeded; terminating container",
@@ -2986,7 +3424,11 @@ Start by:
agent_id=agent_id,
)
return
from_agent = auditor.id if auditor else ceo.id # type: ignore[union-attr]
# recipients is non-empty (guarded above) and already holds the
# non-None ids in auditor-then-ceo order — its first entry is the
# same value as `auditor.id if auditor else ceo.id`, without the
# union-narrowing mypy can't prove.
from_agent = recipients[0]
notification = NotificationTable(
type=NotificationType.ALERT,
priority=NotificationPriority.HIGH,
+1
View File
@@ -107,6 +107,7 @@ _AGENT_PRESENTATION: dict[str, dict[str, Any]] = {
"product-owner": {"name": "Product Owner"},
"head-marketing": {"name": "Head of Marketing"},
"auditor": {"name": "Auditor"},
"intake-1": {"name": "Intake"},
}
+20
View File
@@ -113,6 +113,15 @@ _AUDITOR_FLOW = spec.intents_for_role(spec.Role.AUDITOR)
# no ack (silent observer — wouldn't ack notifications). channels for read map.
_AUDITOR_DO = ("note", "evidence", "notify_list", "notify_get", *_CHANNEL_DISCOVERY)
_PROMPTER_FLOW = spec.intents_for_role(
spec.Role.PROMPTER
) # none — not a lifecycle role
# Intake interviewer: human-only. It journals (note) and cites sources
# (evidence) but has NO outward agent comms — no say (channels), no dm/notify
# (agents), no channel discovery. Its conversation with the human runs over the
# live-session bridge, not these gateway tools.
_PROMPTER_DO = ("note", "evidence")
ROLE_CONFIGS: dict[str, RoleConfig] = {
"developer": RoleConfig(
@@ -179,6 +188,17 @@ ROLE_CONFIGS: dict[str, RoleConfig] = {
allows_subagent=False,
description="Silent observer; reads but never communicates outwardly.",
),
"prompter": RoleConfig(
role="prompter",
flow_tools=_PROMPTER_FLOW,
do_tools=_PROMPTER_DO,
allows_write=False,
allows_subagent=True,
description=(
"Intake interviewer; chats only with the human, reads the codebase, "
"and drafts a task. No outward agent comms; never writes or merges."
),
),
}
+536 -134
View File
@@ -14,9 +14,10 @@ from __future__ import annotations
import contextlib
import json
import re
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Literal
from uuid import UUID, uuid4
import httpx
@@ -30,7 +31,8 @@ from roboco.db.tables import (
TaskDraftTable,
TaskTable,
)
from roboco.models.base import Complexity, TaskNature, TaskType, Team
from roboco.foundation.identity import CELL_TEAMS
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType, Team
from roboco.models.task import TaskCreateRequest
from roboco.services.base import NotFoundError, ServiceError, ValidationError
@@ -53,6 +55,25 @@ class ConfirmOverrides:
product_id: UUID | None = None
assigned_to: str | None = None
extra: dict[str, Any] = field(default_factory=dict)
draft: dict[str, Any] | None = None
@dataclass
class ReadinessTag:
"""Parsed contents of an assistant turn's trailing roboco-meta block."""
covered: list[str] = field(default_factory=list)
ready: bool = False
scale: str | None = None
@dataclass
class TurnResult:
"""Outcome of a chat turn: the message list plus the readiness signal."""
messages: list[PrompterMessageTable]
draft_ready: bool = False
scale: str | None = None
# ---------------------------------------------------------------------------
@@ -60,58 +81,91 @@ class ConfirmOverrides:
# ---------------------------------------------------------------------------
_PROMPTER_SYSTEM_PROMPT = (
"You are the RoboCo Prompter — a conversational assistant that helps "
"users draft tasks for an AI agentic company.\n\n"
"Your job is to:\n"
"1. Ask clarifying questions to gather requirements.\n"
"2. Keep the conversation focused on producing a well-scoped task.\n"
"3. When you believe you have enough context, signal that a draft is "
"ready.\n"
"4. Never create the task yourself — only help the user articulate what "
"needs to be built.\n\n"
"Key rules:\n"
"- Be concise but thorough.\n"
"- Always ask for acceptance criteria if the user hasn't provided them.\n"
"- Suggest a team (backend, frontend, ux_ui) based on the work "
"described.\n"
"- Estimate complexity (low, medium, high) and task type (code, "
"documentation, research, planning, design, administrative).\n"
"- Determine nature (technical vs non_technical).\n"
"- If the user describes a bug, suggest a code task with technical "
"nature.\n"
"- If the user describes a feature, determine whether it's backend, "
"frontend, or UX/UI work.\n\n"
"When you have enough information to produce a complete draft, say so "
"explicitly with 'I have enough information to draft a task' or "
"'ready to draft'."
"You are the RoboCo Prompter — the intake interviewer for an AI agentic "
"software company. A human describes something they want built; you ask a "
"few sharp questions, then a launch-ready task spec is handed to the dev "
"teams.\n\n"
"How RoboCo is organized:\n"
"- A human CEO sits above a Board (Product Owner, Head of Marketing, "
"Auditor).\n"
"- The Main PM coordinates three delivery cells — Backend, Frontend, and "
"UX/UI. Each cell has developers, a QA, a PM, and a documenter.\n"
"- Small, single-domain work (a bug fix, one endpoint, one component) is "
"one task owned by one cell.\n"
"- A real feature is board-led: the Board sets requirements, the Main PM "
"delegates one subtask per participating cell, and the cells deliver in "
"parallel.\n\n"
"What a well-formed task looks like (the house standard):\n"
"- Objective — the outcome, not the implementation.\n"
"- What This Builds — the concrete artifacts.\n"
"- The Work — the per-cell breakdown (one cell for small work; Backend, "
"Frontend, UX/UI for a feature).\n"
"- Notes — constraints, what to reuse, anything to confirm with the human.\n"
"- Success Criteria — verifiable acceptance criteria.\n\n"
"Your interview discipline:\n"
"- Open by reflecting back, in one or two sentences, what you understand "
"they want, so they can correct course immediately.\n"
"- Then ask only the highest-leverage questions you are actually missing — "
"one or two per turn. Never dump a checklist.\n"
"- Before you can draft, cover: (1) the true objective, (2) scope "
"boundaries — what is explicitly out, (3) the surface — which page, "
"endpoint, or component, grounded in the projects/products you are shown, "
"(4) reuse vs build — what existing code or services to lean on, "
"(5) the audience, (6) what 'done' looks like.\n"
"- Stop as soon as objective, scope, surface, and acceptance are clear. "
"Aim for two to four turns total. Do not pad the conversation.\n"
"- Use the real project and product names you are given; prefer an "
"existing surface over inventing one.\n\n"
"Every reply ends with exactly one fenced control block the human never "
"sees, reporting coverage and readiness:\n"
"```roboco-meta\n"
'{"covered": ["objective", "scope", "surface", "acceptance"], '
'"ready": false, "scale": "single"}\n'
"```\n"
"- covered: which of objective / scope / surface / reuse / audience / "
"acceptance you have nailed down.\n"
"- ready: true only when you could write a complete task spec right now.\n"
"- scale: 'single' for one-cell work, 'multi' for a board-led feature "
"across cells.\n"
"Write nothing after that block."
)
_DRAFT_SYSTEM_PROMPT = (
"You are the RoboCo Prompter — an expert at converting conversations "
"into structured task drafts.\n\n"
"Given a conversation between a user and the Prompter assistant, "
"produce a JSON task draft that conforms to the RoboCo task schema.\n\n"
"You are the RoboCo Prompter's drafting engine. Given a finished "
"conversation, output a single JSON object — a structured task "
"draft. No markdown, no prose, no code fence.\n\n"
"Required fields:\n"
"- title: concise, actionable task title (max 200 chars)\n"
"- description: detailed description, min 20 chars, explaining what "
"needs to be done\n"
"- acceptance_criteria: list of strings, each a verifiable criterion "
"(min 1)\n"
"- team: one of backend, frontend, ux_ui\n"
"- title: concise, actionable (max 200 chars).\n"
"- objective: the outcome in one or two sentences.\n"
"- what_this_builds: array of concrete artifacts (strings).\n"
"- the_work: array of per-cell slices. Each item is "
'{"team": backend|frontend|ux_ui, "summary": one line, '
'"items": [deliverables]}. One entry for single-cell work; one entry per '
"participating cell for a board-led feature.\n"
"- acceptance_criteria: array of verifiable criteria (at least one) — "
"these become Success Criteria.\n"
"- notes: array of constraints, reuse pointers, things to confirm (may be "
"empty).\n"
"- team: the primary cell (backend|frontend|ux_ui). For a multi-cell "
"feature set the lead cell here; the backend routes it through the Main "
"PM.\n"
"- task_type: one of code, documentation, research, planning, design, "
"administrative\n"
"- nature: one of technical, non_technical\n"
"- estimated_complexity: one of low, medium, high\n"
"- priority: integer 0-3 (0=P0 highest, 3=P3 lowest)\n\n"
"Optional fields:\n"
"- project_id: UUID string if known from context\n"
"- product_id: UUID string if known from context (only one of "
"project_id/product_id should be set)\n"
"- assigned_to: agent slug or UUID if the user specified one\n"
"- target_date: ISO-8601 date string if mentioned\n\n"
'Always set source="prompter" and confirmed_by_human=false.\n\n'
"Return ONLY valid JSON matching the PrompterDraftTask schema. No "
"markdown, no preamble."
"administrative.\n"
"- nature: technical or non_technical.\n"
"- estimated_complexity: low, medium, high.\n"
"- priority: integer 0-3 (0 highest, 3 lowest).\n\n"
"Optional, only if unambiguous from context: project_id, product_id, "
"assigned_to, target_date.\n\n"
"Do NOT write a 'description' field — the backend composes it from your "
"structured fields.\n\n"
"Example shape (abbreviated):\n"
'{"title": "...", "objective": "...", "what_this_builds": ["..."], '
'"the_work": [{"team": "backend", "summary": "...", "items": ["..."]}, '
'{"team": "frontend", "summary": "...", "items": ["..."]}], '
'"acceptance_criteria": ["..."], "notes": ["..."], "team": "backend", '
'"task_type": "code", "nature": "technical", '
'"estimated_complexity": "high", "priority": 1}\n\n'
"Return ONLY the JSON object."
)
@@ -165,11 +219,7 @@ class PrompterService:
# Session-based interface
# -----------------------------------------------------------------------
async def create_session(
self,
agent_id: UUID,
context: dict[str, Any] | None = None, # noqa: ARG002
) -> PrompterSessionTable:
async def create_session(self, agent_id: UUID) -> PrompterSessionTable:
"""Create a new Prompter conversation session."""
session = PrompterSessionTable(
id=uuid4(),
@@ -188,10 +238,10 @@ class PrompterService:
agent_id: UUID,
content: str,
context: dict[str, Any] | None = None,
) -> list[PrompterMessageTable]:
) -> TurnResult:
"""
Append a user message, call the LLM for a reply, persist both,
and return all messages in the session.
Append a user message, call the LLM for a reply, persist both, and
return all messages plus the readiness signal for this turn.
"""
session = await self._get_session(session_id, agent_id)
@@ -210,13 +260,17 @@ class PrompterService:
history = await self._load_messages(session_id)
chat_messages = [{"role": m.role, "content": m.content} for m in history]
# Ground the interview in the real projects/products the human can target
live_context = await self._assemble_live_context()
# Call the LLM
llm_reply = await self._llm_chat(
messages=chat_messages,
context=context,
live_context=live_context,
)
# Persist the assistant reply
# Persist the assistant reply (control block already stripped)
assistant_msg = PrompterMessageTable(
id=uuid4(),
session_id=session_id,
@@ -237,8 +291,11 @@ class PrompterService:
draft_ready=llm_reply["draft_ready"],
)
# Return all messages in order
return await self._load_messages(session_id)
return TurnResult(
messages=await self._load_messages(session_id),
draft_ready=bool(llm_reply["draft_ready"]),
scale=llm_reply.get("scale"),
)
async def get_or_generate_draft(
self,
@@ -302,52 +359,21 @@ class PrompterService:
session_rec = await self._get_session(session_id, agent_id)
ov = confirm_overrides or ConfirmOverrides()
# Get or generate the draft, then merge confirm-time overrides
# Get or generate the draft. A human-edited structured draft, if passed,
# replaces the stored one before overrides and re-composition.
draft_record = await self.get_or_generate_draft(session_id, agent_id)
draft_data: dict[str, Any] = dict(draft_record.draft_data)
if ov.draft is not None:
draft_data: dict[str, Any] = dict(ov.draft)
draft_data["source"] = "prompter"
draft_data["confirmed_by_human"] = False
else:
draft_data = dict(draft_record.draft_data)
self._apply_overrides(draft_data, ov)
resolved_project_id = self._resolve_uuid_field(draft_data, "project_id")
resolved_product_id = self._resolve_uuid_field(draft_data, "product_id")
if resolved_project_id is None and resolved_product_id is None:
raise ValidationError(
message=(
"The draft must have either project_id or product_id set. "
"Pass one via the confirm request body."
),
field="project_id",
)
task = await self.create_task_from_draft(draft_data, agent_id)
team, task_type, nature, complexity = self._coerce_draft_enums(draft_data)
# Resolve assigned_to as UUID if possible
resolved_assigned_to: UUID | None = None
if draft_data.get("assigned_to"):
with contextlib.suppress(ValueError):
resolved_assigned_to = UUID(str(draft_data["assigned_to"]))
req = TaskCreateRequest(
title=draft_data["title"],
description=draft_data["description"],
acceptance_criteria=draft_data["acceptance_criteria"],
team=team,
created_by=agent_id,
task_type=task_type,
nature=nature,
estimated_complexity=complexity,
priority=int(draft_data.get("priority", 2)),
assigned_to=resolved_assigned_to,
project_id=resolved_project_id,
product_id=resolved_product_id,
source="prompter",
confirmed_by_human=True,
)
# Import TaskService lazily to avoid circular imports
from roboco.services.task import get_task_service
task_service = get_task_service(self._session)
task: TaskTable = await task_service.create(req)
# Persist the launched draft so the stored record reflects reality.
draft_record.draft_data = draft_data
# Mark draft as confirmed
now = datetime.now(UTC)
@@ -361,7 +387,139 @@ class PrompterService:
session_id=str(session_id),
task_id=str(task.id),
)
return task.id # type: ignore[return-value]
return UUID(str(task.id))
async def create_task_from_draft(
self,
draft_data: dict[str, Any],
agent_id: UUID,
*,
status: TaskStatus = TaskStatus.BACKLOG,
assigned_to: UUID | None = None,
) -> TaskTable:
"""Create a Task from a structured draft.
Shared by both prompter confirm paths (``confirm_draft`` and the
live-intake ``confirm_live_draft``): recomposes the description,
validates exactly-one target, coerces enums, routes the owning team
(product Main PM, project lead cell), and persists via
``TaskService.create``. Mutates ``draft_data['description']`` in place.
``confirmed_by_human=True`` the CEO confirmed it.
``status`` defaults to ``BACKLOG`` (legacy ``confirm_draft`` behaviour).
The live-intake buttons pass ``PENDING`` + an ``assigned_to`` (a board
agent for "Board review & Start", main-pm for "Approve & Start") so the
task starts immediately on the chosen review path. An explicit
``assigned_to`` wins over any assignee carried on the draft.
"""
# Recompose the description from the (possibly edited) structured fields —
# the task always carries a freshly-composed, consistent description.
draft_data["description"] = compose_description(draft_data)
resolved_project_id = self._resolve_uuid_field(draft_data, "project_id")
resolved_product_id = self._resolve_uuid_field(draft_data, "product_id")
if resolved_project_id is None and resolved_product_id is None:
raise ValidationError(
message=(
"The draft must target a project (single-cell) or a product "
"(board-led, multi-cell). Pick one in the confirm step."
),
field="project_id",
)
if resolved_project_id is not None and resolved_product_id is not None:
raise ValidationError(
message="Set exactly one of project_id or product_id, not both.",
field="product_id",
)
_lead, task_type, nature, complexity = self._coerce_draft_enums(draft_data)
# Adaptive routing: a product target is a board-led coordination root
# owned by the Main PM (who fans out per cell); a project target is a
# single-cell executable task owned by the cell doing the work.
if resolved_product_id is not None:
team = Team.MAIN_PM
else:
team = self._lead_cell_team(draft_data, default=_lead)
# Explicit assignment (from the confirm button) wins; else fall back to
# any assignee carried on the draft.
resolved_assigned_to: UUID | None = assigned_to
if resolved_assigned_to is None and draft_data.get("assigned_to"):
with contextlib.suppress(ValueError):
resolved_assigned_to = UUID(str(draft_data["assigned_to"]))
req = TaskCreateRequest(
title=draft_data["title"],
description=draft_data["description"],
acceptance_criteria=draft_data["acceptance_criteria"],
team=team,
created_by=agent_id,
task_type=task_type,
nature=nature,
estimated_complexity=complexity,
priority=self._coerce_priority(draft_data.get("priority")),
assigned_to=resolved_assigned_to,
project_id=resolved_project_id,
product_id=resolved_product_id,
status=status,
source="prompter",
confirmed_by_human=True,
)
# Import TaskService lazily to avoid circular imports
from roboco.services.task import get_task_service
task_service = get_task_service(self._session)
return await task_service.create(req)
async def confirm_live_draft(
self,
draft: dict[str, Any],
agent_id: UUID,
*,
project_id: UUID | None = None,
product_id: UUID | None = None,
route: Literal["board", "main_pm"] = "board",
) -> UUID:
"""Confirm a live-intake draft → create + start the task; return its id.
The human picked one of two start buttons (``route``):
- ``"board"`` ("Board review & Start") task at PENDING assigned to the
Product Owner, so the orchestrator dispatches the full Board review
(PO + Head of Marketing) before it reaches the Main PM.
- ``"main_pm"`` ("Approve & Start") task at PENDING assigned to the Main
PM, who delegates to the cells directly (Board review skipped).
Enum fields the dialog doesn't surface default to sane values so a
confirm never fails on a missing ``nature``.
"""
from roboco.seeds.initial_data import AGENT_UUIDS
draft_data: dict[str, Any] = dict(draft)
if project_id is not None:
draft_data["project_id"] = str(project_id)
if product_id is not None:
draft_data["product_id"] = str(product_id)
# Fields the confirm dialog doesn't expose — default rather than reject.
draft_data.setdefault("task_type", TaskType.CODE.value)
draft_data.setdefault("nature", TaskNature.TECHNICAL.value)
draft_data.setdefault("estimated_complexity", Complexity.MEDIUM.value)
draft_data.setdefault("priority", 2)
assignee_slug = "product-owner" if route == "board" else "main-pm"
assigned_to = UUID(AGENT_UUIDS[assignee_slug])
task = await self.create_task_from_draft(
draft_data, agent_id, status=TaskStatus.PENDING, assigned_to=assigned_to
)
self.log.info(
"Live intake draft confirmed — task started",
task_id=str(task.id),
route=route,
assigned_to=assignee_slug,
)
return UUID(str(task.id))
@staticmethod
def _apply_overrides(draft_data: dict[str, Any], ov: ConfirmOverrides) -> None:
@@ -389,23 +547,80 @@ class PrompterService:
field=key,
) from exc
@staticmethod
def _lead_cell_team(draft_data: dict[str, Any], default: Team) -> Team:
"""Owner of a single-cell task: first *valid* cell in the_work, else default.
Skips cell names that aren't valid ``Team`` values rather than raising —
the intake agent is an LLM and can emit an off-enum cell name.
"""
for raw in _cell_teams(draft_data.get("the_work") or []):
try:
return Team(raw)
except ValueError:
continue
return default
@staticmethod
def _coerce_draft_enums(
draft_data: dict[str, Any],
) -> tuple[Team, TaskType, TaskNature, Complexity]:
"""Coerce the draft's required enum fields, raising on missing/invalid."""
"""Coerce the draft's enum fields to valid values; default on invalid/missing.
The intake agent is an LLM and will occasionally emit an off-enum value
(e.g. ``task_type="feature"``, which is not a ``TaskType``). The
confirm/launch action must NEVER hard-fail on a cosmetic enum guess that
forces the agent to self-correct in-chat, which is unacceptable UX. Coerce
to a sane default instead; ``team`` falls back to the lead cell, then backend.
"""
try:
return (
Team(draft_data["team"]),
TaskType(draft_data["task_type"]),
TaskNature(draft_data["nature"]),
Complexity(draft_data["estimated_complexity"]),
)
except (KeyError, ValueError) as exc:
raise ValidationError(
message=f"Draft has invalid or missing required fields: {exc}",
field="draft",
) from exc
team = Team(draft_data["team"])
except (KeyError, ValueError, TypeError):
team = PrompterService._lead_cell_team(draft_data, Team.BACKEND)
try:
task_type = TaskType(draft_data["task_type"])
except (KeyError, ValueError, TypeError):
task_type = TaskType.CODE
try:
nature = TaskNature(draft_data["nature"])
except (KeyError, ValueError, TypeError):
nature = TaskNature.TECHNICAL
try:
complexity = Complexity(draft_data["estimated_complexity"])
except (KeyError, ValueError, TypeError):
complexity = Complexity.MEDIUM
return team, task_type, nature, complexity
@staticmethod
def _coerce_priority(value: Any) -> int:
"""Coerce the draft's priority to a valid int (0=urgent … 3=low).
priority is the one non-enum field the intake agent guesses, and it
guesses a word ("high") as often as a number. Map the words, clamp
numbers to 0-3, and default to 2 (medium) on anything unrecognized so the
launch never crashes on a priority guess (it did: ``int("high")``).
"""
words = {
"urgent": 0,
"critical": 0,
"high": 1,
"medium": 2,
"normal": 2,
"low": 3,
}
if isinstance(value, bool):
return 2
if isinstance(value, int):
return min(max(value, 0), 3)
if isinstance(value, str):
key = value.strip().lower()
if key in words:
return words[key]
try:
return min(max(int(key), 0), 3)
except ValueError:
return 2
return 2
# -----------------------------------------------------------------------
# Private helpers (session-based)
@@ -420,7 +635,7 @@ class PrompterService:
)
rec = result.scalar_one_or_none()
if rec is None:
raise NotFoundError(f"Prompter session {session_id} not found")
raise NotFoundError("Prompter session", str(session_id))
if rec.agent_id != agent_id:
raise ServiceError(
f"Session {session_id} does not belong to agent {agent_id}"
@@ -436,6 +651,48 @@ class PrompterService:
)
return list(result.scalars().all())
async def _assemble_live_context(self) -> str | None:
"""Build a compact 'Available projects / products' block for the interview.
Grounds the assistant in the real targets the human can launch against,
so it references existing surfaces and can resolve project/product
itself. Best-effort: a lookup failure degrades to no context rather than
breaking the chat. Returns None when nothing is registered.
"""
if self._db is None:
return None
from roboco.services.product import get_product_service
from roboco.services.project import get_project_service
lines: list[str] = []
try:
projects = await get_project_service(self._session).list_all(
active_only=True, limit=50
)
except Exception as exc:
self.log.warning("Live project list unavailable", error=str(exc))
projects = []
if projects:
lines.append("Available projects (single-cell tasks target one of these):")
lines.extend(f" - {p.name} (slug: {p.slug}, id: {p.id})" for p in projects)
try:
products = await get_product_service(self._session).list_all(limit=50)
except Exception as exc:
self.log.warning("Live product list unavailable", error=str(exc))
products = []
if products:
lines.append(
"Available products (board-led multi-cell features target one "
"of these):"
)
lines.extend(
f" - {pr.name} (slug: {pr.slug}, id: {pr.id})" for pr in products
)
return "\n".join(lines) if lines else None
# -----------------------------------------------------------------------
# Shared LLM helpers
# -----------------------------------------------------------------------
@@ -445,9 +702,14 @@ class PrompterService:
messages: list[dict[str, str]],
context: dict[str, Any] | None = None,
max_tokens: int = 2048,
live_context: str | None = None,
) -> dict[str, Any]:
"""Call the LLM for a chat response. Returns {message, draft_ready}."""
user_prompt = _build_chat_prompt(messages, context)
"""Call the LLM for a chat response.
Returns ``{message, draft_ready, scale}`` where ``message`` is the
user-visible reply with the trailing roboco-meta control block stripped.
"""
user_prompt = _build_chat_prompt(messages, context, live_context)
try:
content = await self._create_message(
messages=[
@@ -463,9 +725,14 @@ class PrompterService:
if not content:
raise ServiceError("LLM returned empty content")
clean, tag = parse_readiness(content)
# If the model omitted the control block, fall back to the clean text
# so the user still sees a reply rather than an empty bubble.
message = clean or content
return {
"message": content,
"draft_ready": _detect_draft_ready(content),
"message": message,
"draft_ready": bool(tag and tag.ready),
"scale": tag.scale if tag else None,
}
async def _llm_draft(
@@ -502,6 +769,9 @@ class PrompterService:
draft_data["source"] = "prompter"
draft_data["confirmed_by_human"] = False
# Compose the markdown description from the structured fields — the model
# never hand-formats it, so the description is always consistent.
draft_data["description"] = compose_description(draft_data)
return {
"draft": draft_data,
"reasoning": _build_reasoning(messages, draft_data),
@@ -546,8 +816,12 @@ class PrompterService:
def _build_chat_prompt(
messages: list[dict[str, str]],
context: dict[str, Any] | None,
live_context: str | None = None,
) -> str:
lines: list[str] = []
if live_context:
lines.append(live_context)
lines.append("")
if context:
lines.append("Context:")
for key, value in context.items():
@@ -560,9 +834,9 @@ def _build_chat_prompt(
lines.append(f"{role}: {content}")
lines.append("")
lines.append(
"Continue the conversation as the Prompter assistant. "
"If you have enough information to draft a complete task, "
"say so explicitly."
"Continue the conversation as the Prompter assistant. End with the "
"roboco-meta control block. If you can write a complete task spec now, "
"set ready to true."
)
return "\n".join(lines)
@@ -604,17 +878,145 @@ def _strip_code_fences(content: str) -> str:
return text.strip()
def _detect_draft_ready(content: str) -> bool:
signals = [
"i have enough information",
"ready to generate a draft",
"ready to draft",
"i can now draft",
"draft_ready=true",
"draft ready",
]
lower = content.lower()
return any(sig in lower for sig in signals)
_META_FENCE_RE = re.compile(r"```roboco-meta\s*(.*?)```", re.DOTALL)
# Mirror of PrompterDraftTask.description min_length — below this the composed
# body is too thin to be a valid task, so we fall back to any provided text.
_MIN_DESCRIPTION_LEN = 20
_TEAM_LABELS: dict[str, str] = {
"backend": "Backend",
"frontend": "Frontend",
"ux_ui": "UX/UI",
"main_pm": "Main PM",
"board": "Board",
}
def parse_readiness(content: str) -> tuple[str, ReadinessTag | None]:
"""Split an assistant reply into (clean_text, readiness_tag).
The interview prompt instructs the model to end each turn with a fenced
``roboco-meta`` JSON block. This extracts the last such block, strips it
from the user-visible text, and parses it. A missing or malformed block
yields ``None`` (treated as not-ready) so the conversation never breaks.
"""
matches = list(_META_FENCE_RE.finditer(content))
if not matches:
return content.strip(), None
# Strip every control block from the visible text (a well-behaved model
# emits one; remove any strays too), and read readiness from the last.
clean = _META_FENCE_RE.sub("", content).strip()
try:
data = json.loads(matches[-1].group(1).strip())
except (json.JSONDecodeError, ValueError):
return clean, None
if not isinstance(data, dict):
return clean, None
raw_scale = data.get("scale")
scale = str(raw_scale) if raw_scale in ("single", "multi") else None
covered = [str(c) for c in data.get("covered") or [] if isinstance(c, str)]
return clean, ReadinessTag(
covered=covered,
ready=bool(data.get("ready", False)),
scale=scale,
)
def _cell_teams(the_work: list[dict[str, Any]]) -> list[str]:
"""Distinct cell teams (backend/frontend/ux_ui) present in the_work, in order."""
cell_values = {t.value for t in CELL_TEAMS}
seen: list[str] = []
for entry in the_work:
team = str(entry.get("team", ""))
if team in cell_values and team not in seen:
seen.append(team)
return seen
def derive_scale(the_work: list[dict[str, Any]]) -> str:
"""'multi' when more than one cell participates, else 'single'."""
return "multi" if len(_cell_teams(the_work)) > 1 else "single"
def _clean_list(value: Any) -> list[str]:
"""Trimmed, non-empty string items from a possibly-missing list field."""
return [str(i).strip() for i in (value or []) if str(i).strip()]
def _text(value: Any) -> str:
"""Trimmed string from a possibly-missing scalar field."""
return str(value or "").strip()
def _bullets(items: list[str]) -> str:
"""Render a markdown bullet list."""
return "\n".join(f"- {i}" for i in items)
def _cell_label(team: str) -> str:
"""Display label for a team value."""
return _TEAM_LABELS.get(team) or team.replace("_", " ").title() or "Work"
def _render_work_entry(entry: dict[str, Any]) -> str:
"""Render one cell's slice: a bold heading and its deliverables."""
head = f"**{_cell_label(_text(entry.get('team')))}**"
summary = _text(entry.get("summary"))
if summary:
head = f"{head}{summary}"
items = _clean_list(entry.get("items"))
return f"{head}\n{_bullets(items)}" if items else head
def _render_the_work(the_work: list[dict[str, Any]]) -> str:
"""Render The Work section, with a board-led lead line when multi-cell."""
blocks = [_render_work_entry(e) for e in the_work]
if len(_cell_teams(the_work)) > 1:
blocks.insert(
0,
"Board-led: the Board sets requirements and the Main PM "
"delegates one subtask per cell.",
)
return "\n\n".join(blocks)
def _section(sections: list[str], heading: str, body: str) -> None:
"""Append a markdown section when its body is non-empty."""
if body:
sections.append(f"## {heading}\n\n{body}")
def compose_description(draft: dict[str, Any]) -> str:
"""Build the markdown description deterministically from structured fields.
Sections present only when their field has content. ``acceptance_criteria``
renders under Success Criteria. A multi-cell task gets a board-led lead
line. Falls back to any model-provided ``description`` if the structured
fields are too sparse to clear the schema's 20-char minimum.
"""
the_work = draft.get("the_work") or []
sections: list[str] = []
_section(sections, "Objective", _text(draft.get("objective")))
_section(
sections,
"What This Builds",
_bullets(_clean_list(draft.get("what_this_builds"))),
)
_section(sections, "The Work", _render_the_work(the_work) if the_work else "")
_section(sections, "Notes", _bullets(_clean_list(draft.get("notes"))))
_section(
sections,
"Success Criteria",
_bullets(_clean_list(draft.get("acceptance_criteria"))),
)
composed = "\n\n".join(sections).strip()
if len(composed) >= _MIN_DESCRIPTION_LEN:
return composed
return _text(draft.get("description")) or composed
def _build_reasoning(
+148
View File
@@ -0,0 +1,148 @@
"""Live intake-session relay — the orchestrator side of the chat bridge.
A live intake session is one spawned ``prompter`` container the CEO is chatting
with. This registry connects three flows for that session, all in-process (the
orchestrator is single-process and already holds container state in memory):
- **agent -> panel:** the container's driver POSTs each normalized
``StreamChunk`` to the relay endpoint, which ``push()``es it onto the
session's queue; the SSE endpoint ``stream()``s the queue to the browser.
- **panel -> agent:** the message endpoint ``deliver()``s the human's text to
the container's in-process receiver over HTTP.
- **lifecycle:** ``open`` on spawn, ``close`` on reap (draft confirmed / idle);
``close`` unblocks any open stream with a sentinel.
This module owns no SDK or Claude code it's pure plumbing, fully unit-tested.
"""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
import httpx
import structlog
if TYPE_CHECKING:
from collections.abc import AsyncIterator
logger = structlog.get_logger()
# The in-container receiver port (same ROBOCO_SDK_PORT every agent sidecar uses).
SDK_PORT = 9000
# Sentinel pushed onto a session's queue to end its SSE stream.
_CLOSE = object()
@dataclass
class LiveIntakeSession:
"""One live chat: a queue of outbound events + the container to deliver to."""
session_id: str
agent_id: str # container agent id, e.g. "intake-3f9c1a2b"
queue: asyncio.Queue[Any] = field(default_factory=asyncio.Queue)
closed: bool = False
class PrompterLiveRegistry:
"""Tracks live intake sessions and bridges panel <-> container."""
def __init__(self, *, http_client: httpx.AsyncClient | None = None) -> None:
self._sessions: dict[str, LiveIntakeSession] = {}
self._client = http_client
self.log = logger.bind(component="prompter_live")
# -- lifecycle ---------------------------------------------------------
def open(self, session_id: str, agent_id: str) -> LiveIntakeSession:
"""Register a live session (called when its container is spawned).
Idempotent: if a live (un-closed) session already exists for this id,
return it unchanged instead of replacing it with a fresh queue. A second
``open`` would otherwise orphan the SSE stream ``stream()`` captures the
session's queue once when the browser connects, so swapping in a new queue
strands the browser on the old one while the agent's events push to the
new one (the panel then shows nothing despite the agent replying).
"""
existing = self._sessions.get(session_id)
if existing is not None and not existing.closed:
return existing
session = LiveIntakeSession(session_id=session_id, agent_id=agent_id)
self._sessions[session_id] = session
self.log.info(
"Live intake session opened", session_id=session_id, agent_id=agent_id
)
return session
def get(self, session_id: str) -> LiveIntakeSession | None:
return self._sessions.get(session_id)
def close(self, session_id: str) -> None:
"""End a live session and unblock its stream (called on reap)."""
session = self._sessions.pop(session_id, None)
if session is None:
return
session.closed = True
session.queue.put_nowait(_CLOSE)
self.log.info("Live intake session closed", session_id=session_id)
# -- agent -> panel ----------------------------------------------------
def push(self, session_id: str, event: dict[str, Any]) -> bool:
"""Queue one agent event for the SSE stream. False if no such session."""
session = self._sessions.get(session_id)
if session is None or session.closed:
return False
session.queue.put_nowait(event)
return True
async def stream(self, session_id: str) -> AsyncIterator[dict[str, Any]]:
"""Yield queued agent events until the session is closed."""
session = self._sessions.get(session_id)
if session is None:
return
while True:
item = await session.queue.get()
if item is _CLOSE:
return
yield item
# -- panel -> agent ----------------------------------------------------
async def deliver(self, session_id: str, text: str) -> bool:
"""Deliver the human's message to the container's receiver. False if gone."""
session = self._sessions.get(session_id)
if session is None or session.closed:
return False
url = f"http://roboco-agent-{session.agent_id}:{SDK_PORT}/turn"
client = self._client or httpx.AsyncClient(timeout=10.0)
try:
resp = await client.post(url, json={"text": text})
resp.raise_for_status()
return True
except Exception as exc:
# Debug, not error: the opening-message delivery retries until the
# container's receiver is up, so transient failures here are expected
# and were spamming ERROR. Callers surface a real failure (the
# /messages route 404s; _deliver_when_ready warns once after N tries).
self.log.debug(
"Message delivery attempt failed", session_id=session_id, error=str(exc)
)
return False
finally:
if self._client is None:
await client.aclose()
# Process-wide singleton — the orchestrator owns one registry. Held on a class
# (mirrors events/stream_bus._StreamEventBusHolder) to avoid a `global`.
class _RegistryHolder:
instance: PrompterLiveRegistry | None = None
def get_live_registry() -> PrompterLiveRegistry:
"""Return the process-wide live-session registry."""
if _RegistryHolder.instance is None:
_RegistryHolder.instance = PrompterLiveRegistry()
return _RegistryHolder.instance