Files
roboco/roboco/seeds/initial_data.py
T
5fe1e6df58 feat: in-path PR-review gate — per-cell + main reviewers (#229)
* feat(lifecycle): add the in-path PR-review gate status + reviewer verbs

Insert awaiting_pr_review between the assembled-PR submit and the PM merge,
giving the merge level the rejection capability it structurally lacks — today
only qa_fail and ceo_reject ever reach needs_revision, so a PM review is a
merge button with no teeth.

- New Status awaiting_pr_review + submit_for_review / pr_pass / pr_fail actions
  (pr_pass -> awaiting_pm_review, pr_fail -> needs_revision, mirroring the QA gate).
- Reviewer verbs claim_gate_review / pr_pass / pr_fail, and a main-PM submit_root
  verb (the root analogue of the cell PM's submit_up; opens the root->master PR).
- Extend the self-review-symmetry validator to the new sign-off actions.
- Mirror the value into the ORM TaskStatus enum + the A2A state map, and add the
  postgres taskstatus enum value (migration 040, forward-only like 037).
- Regenerate the per-role verb tables; add gate spec tests.

Spec surface only; the gateway methods + dispatch are wired in follow-ups, so the
verbs are advertised but dormant (flow_server tolerates unregistered verbs).

* feat(identity): add the three cell PR-review-gate reviewers

The in-path gate needs a reviewer per cell so each cell's assembled cell->root
PR is reviewed by a stack-specialized agent, while pr-reviewer-1 serves the
root->master gate (and keeps doing inbound external PRs).

- be/fe/ux-pr-reviewer: PR_REVIEWER role, team-scoped (so dispatch routes each
  cell's gate to its own reviewer); seeded identities + ROLE_TEAM_RULES + names.
  AI agent count 22 -> 25.
- They reuse the existing roboco-agent-pr-reviewer image (AGENT_IMAGES maps the
  three slugs to it, as be-dev-1/-2 share one image) — no new image.
- Tracing table: pr_pass/pr_fail require a learning entry (parity with
  post_pr_review), submit_root mirrors submit_up, claim_gate_review is waived
  (its tracing applies on pr_pass/pr_fail) — completes the verb surface added
  in the prior commit.
- Update the roster-pinning identity tests.

* feat(gateway): wire the in-path PR-review gate end to end

Make the assembled-PR review gate operational across the choreographer, the
TaskService transitions, and the v1 flow surface.

- TaskService: submit_for_review (in_progress→awaiting_pr_review), pr_gate_claim
  (no-transition reviewer claim), pr_pass (→awaiting_pm_review), pr_fail
  (→needs_revision); mirror qa_pass/qa_fail (clear claim, actor-mismatch warn,
  issues appended for the PM's revision). VerbRunner gains the matching atomic
  handlers + a create_root_pr side effect.
- Repoint submit_up to compose submit_for_review (cell→root PR enters the gate),
  and add a main-PM submit_root verb (opens the root→master PR, enters the gate).
- Split main_pm_complete: a code root must pass the gate first (requires
  awaiting_pm_review; rejects an in_progress code root toward submit_root and no
  longer reopens the PR), while a branchless coordination root still walks
  straight through, ungated.
- PRGateMixin (claim_gate_review / pr_pass / pr_fail) composed onto the
  Choreographer; flow_server forwarders + v1 routes (pr_reviewer + main_pm) +
  request schemas.
- Tests: gate spec + the updated submit_up / main_pm_complete expectations + new
  real-DB integration tests driving submit_for_review→pr_gate_claim→pr_pass and
  pr_fail through the real enforcement layer.

* feat(orchestrator): dispatch the in-path PR-review gate

Make the gate live in the dispatch loop.

- _dispatch_pr_gate_work: route awaiting_pr_review tasks to reviewers by level —
  a cell→root task to its cell reviewer (be/fe/ux-pr-reviewer), the root→master
  task to pr-reviewer-1. The reviewer self-claims via claim_gate_review (no
  pre-claim, mirroring the external-PR dispatcher); registered in
  _dispatch_all_work. _select_agent_for_cell learns the pr_reviewer role.
- _build_pr_gate_prompt: anchors the reviewer to the parent objective + full
  acceptance criteria + the FE<->BE contract, then pr_pass / pr_fail.
- _readiness_check_role_for_status: awaiting_pr_review -> pr_reviewer.
- Fail routing: pr_fail reassigns the failed assembled task to its PM
  (_revision_pm_for_task: cell PM for a cell team, Main PM for the root), and the
  revision dispatcher is generalized from coordination-roots-only to any
  PM-owned needs_revision task so the gate-failed task is re-coordinated instead
  of deadlocking.

* docs: document the in-path PR-review gate + the cell reviewers (22→25)

Reflect the shipped gate across the canonical + RAG docs.

- CLAUDE.md: agent count 22→25, the cell reviewers in the org chart, an
  awaiting_pr_review state + the gate transitions + a gate note in the lifecycle
  section, and submit_root / claim_gate_review / pr_pass / pr_fail in the verb
  surface table.
- docs/rag/architecture: org-structure (count, cell-reviewer roster, cells
  table), agent-uuids (be/fe/ux-pr-reviewer rows), agent-model (role + team
  rows).
- docs/rag/roles/pr-reviewer: the in-path gate section + the gate verbs.
- Wrap reviewer.id with UUID(str(...)) in the gate DB tests for mypy.

* docs: finish the gate doc sweep across README + RAG + generated artifacts

Catch the remaining surfaces beyond the canonical docs.

- README + how-to: agent count 22→25, the 6-agent cells (+ PR Reviewer), the
  main reviewer's root→master gate role.
- RAG: permissions + tool-permissions + task-tools list the gate verbs
  (claim_gate_review / pr_pass / pr_fail) for pr_reviewer; regenerate the
  lifecycle artifacts (intent-verbs, status-transitions, the per-role
  lifecycle-*.md prompts, panel lifecycle.json) from the spec via
  build_lifecycle_artifacts.py so they carry the new status + verbs.

* fix(migration): shorten the 040 revision id to fit alembic_version VARCHAR(32)

The revision id '040_taskstatus_awaiting_pr_review' is 33 chars; alembic's
alembic_version.version_num column is VARCHAR(32), so recording the migration on
a real 'alembic upgrade head' failed with 'value too long for type character
varying(32)' (surfaced on the NAS deploy). The test suite missed it: the test DB
is built via Base.metadata.create_all and the parity test only renders SQL
offline, so nothing actually applied the migration chain.

- Rename to '040_awaiting_pr_review' (22 chars).
- Add a guard test asserting every revision id fits the VARCHAR(32) column.
- Verified by applying the full chain 001->040 against real Postgres: it now
  reaches head and records '040_awaiting_pr_review' without truncation.

* fix(migration): land the actual 040 revision-id shortening + guard test

The prior commit captured only the file rename (git add aborted on the deleted
old path), leaving the long revision id and missing the guard test. This commit
carries the real content: revision id '040_awaiting_pr_review' (22 chars) and the
revision-id length guard. Re-verified against real Postgres — the full chain
reaches head and records the short id without truncation.

* fix(product): flush cell deletes before inserts when re-mapping projects

Editing a product's cell->project map (PATCH /api/products/{id}) 409'd with
'duplicate key value violates unique constraint uq_product_projects_product_team'
whenever a team already had a mapping. _replace_cells clears the old rows and
appends the new ones, but within a single flush SQLAlchemy orders INSERTs before
DELETEs for the same table, so the new (product_id, team) rows collided with the
not-yet-deleted old ones. Flush the deletes first.

Pre-existing bug (unrelated to the PR-review gate); surfaced on the NAS. New
real-Postgres regression test re-maps all three cells to different projects —
it fails with the unique violation without the fix and passes with it. The
existing update test only changed WHICH team was mapped, so it never collided.

* fix(gateway): let main_pm submit_root past the shared submit-up guard

submit_root reused the cell PM's _submit_up_ownership_guard, which
hardcoded agent.role != cell_pm and rejected the Main PM with
"submit_up is reserved for cell_pm". A branch-bearing code root could
then never close: submit_root bounced to complete, while complete
required awaiting_pm_review (reachable only via submit_root) and bounced
back — a circular rejection.

Both callers already run the spec gate (can_invoke_intent), which
enforces submit_up→cell_pm and submit_root→main_pm, so the guard's role
re-check was redundant for submit_up and wrong for submit_root. Broaden
it to accept either PM role as a defense-in-depth non-PM reject.

Adds the first choreographer-level submit_root test (the gap that let
this ship).

* fix(gateway): proactively steer both PMs to their bubble-up verb

The submit_root deadlock had a sibling steering gap: nothing told a PM
which verb opens the gate. The delegate next-hint said only 'i_am_idle
when done', and complete's in_progress rejection named submit_root for
the Main PM but left the Cell PM with a bare 'not ready for completion'
— no submit_up pointer, the same guess-the-verb trap.

- delegate hint now names the role-correct verb (root → submit_root,
  cell parent → submit_up) proactively, before any rejection.
- cell_pm_complete's in_progress rejection now steers to submit_up,
  mirroring the Main PM's submit_root gate hint.

Tests cover both the cell-PM steer and the role-aware delegate hint.

* docs: correct who-merges-which-PR across the gate docs + complete description

Audit of the gate docs found the merge actors mis-stated in several
places — the exact ambiguity that risks 'the reviewer/PM merges the root
PR' confusion:

- complete IntentSpec description said 'Main PM merges root PR' — false;
  main_pm_complete escalates and the CEO merges root→master. Corrected
  (propagated to intent-verbs.md, lifecycle.json, generated role prompts
  via build_lifecycle_artifacts.py).
- task-tools.md: submit_up target was awaiting_pm_review (should be
  awaiting_pr_review); Main PM flow had no submit_root — added it.
- README.md: lifecycle diagram now shows the awaiting_pr_review gate.
- cell-pm.md / main-pm.md: dropped the stale 'submit_up hands work to the
  Main PM who merges your cell branch' model — the cell PM merges its own
  gated cell→root PR; the Main PM owns the root + submit_root; the CEO
  merges master. Added submit_root to the main-pm manifest.
- git-commits.md, pr-creation.md, tool-permissions.md, git-tools.md:
  stopped attributing root→master PR opening to complete (it's submit_root).

No behavior change; verb wiring + state machine verified gap-free this
session (the pr_fail→needs_revision→PM respawn loop closes correctly).

* fix(orchestrator): stop closure respawn waiting the reaper window

A PM that finished its subtasks and idled left its parent 'paused' with a
fresh last_heartbeat_at. _is_recently_paused gated closure respawn on
_claim_heartbeat_ttl — the REAPER window (stale_claim_reap_seconds: 600s
default, 1800s on the NAS) — so the parent sat untouched for up to 10-30
minutes before its PM was respawned to close it. The whole chain stalled
behind it.

The race that guard actually protects against (i_am_idle auto-pauses, then
the agent is marked IDLE + its container tears down) is seconds, and the
live-session case is already covered by _is_agent_active. Introduce a
dedicated short debounce (pm_closure_recently_paused_seconds, default 45s)
and gate closure on that instead.

The existing test fixture masked this by setting _claim_heartbeat_ttl to
claim_stale_seconds (180s), not the production reaper value. Fixture now
mirrors production; adds a regression test that a parent paused past the
debounce but within the reaper window respawns immediately.

* feat(gate): post the in-path review verdict on the assembled PR

The in-path gate previously left no trace on the PR it gated — pr_pass /
pr_fail were pure status transitions. Now each verdict is posted as a
GitHub review on the assembled PR itself (server-side, bot account), so
the decision is visible on the very PR the PM merges.

- pr_pass → APPROVE, pr_fail → REQUEST_CHANGES on a cell→root PR.
- The root→master PR ALWAYS gets a plain COMMENT, never APPROVE/REQUEST_
  CHANGES: only the CEO acts on master, so the gate must never leave an
  approval that could satisfy branch protection (letting someone else
  merge) nor a blocking review that could impede the CEO's merge.
- Best-effort and AFTER the DB transition — a GitHub failure is logged,
  never rolls back the gate decision. Reuses git.post_pr_review's existing
  self-review→COMMENT downgrade for the org's own PRs.

Adds _project_slug_for to the ChoreographerHelpers protocol (mypy) and a
unit suite covering event selection, the master-bound COMMENT rule, the
no-PR skip, and failure-swallowing. Docs updated (pr-reviewer, task-tools).

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-06-20 09:27:29 +02:00

332 lines
11 KiB
Python

"""
Initial Data Constants
Static seed data for bootstrapping the RoboCo system.
Separates data definitions from bootstrap logic.
"""
from typing import Any
from roboco.foundation import identity as _foundation
from roboco.foundation.policy import communications as _comms
# =============================================================================
# DEFAULT CHANNELS
#
# Channel topology (slug, description, type, membership) is canonicalized in
# `roboco.foundation.policy.communications.CHANNELS`. The DEFAULT_CHANNELS
# list and CHANNEL_MEMBERSHIPS dict below derive from that catalog at module
# load. The only seed-only field is `name` — a presentation string the
# foundation does not (and should not) own. It lives in
# `_CHANNEL_PRESENTATION` and is the only edit needed to rename a channel
# label.
# =============================================================================
# Per-channel display name. Slug, description, type, and membership are all
# sourced from foundation.CHANNELS; this dict only carries presentation.
_CHANNEL_PRESENTATION: dict[str, str] = {
"backend-cell": "Backend Cell",
"frontend-cell": "Frontend Cell",
"uxui-cell": "UX/UI Cell",
"dev-all": "All Developers",
"qa-all": "All QA",
"pm-all": "All PMs",
"doc-all": "All Documenters",
"main-pm-board": "Main PM & Board",
"board-private": "Board Private",
"announcements": "Announcements",
"all-hands": "All Hands",
}
def _build_default_channels() -> list[dict[str, Any]]:
"""Compose DEFAULT_CHANNELS rows from foundation specs + display names."""
return [
{
"slug": spec.slug,
"name": _CHANNEL_PRESENTATION[slug],
"description": spec.description,
# Legacy DB seeder keys this as `channel_type`; preserve the name
# so create_channels(session) keeps working unchanged.
"channel_type": spec.type.value,
}
for slug, spec in _comms.CHANNELS.items()
]
DEFAULT_CHANNELS: list[dict[str, Any]] = _build_default_channels()
# =============================================================================
# DEFAULT AGENTS
#
# All agents have static UUIDs for consistent mapping between:
# - Database records
# - Task assignments
# - Container orchestration
#
# UUID scheme (encoded in roboco/foundation/identity.py:AGENTS):
# - 0000-0000: System sentinel + CEO (human)
# - 0001-000X: Backend cell
# - 0002-000X: Frontend cell
# - 0003-000X: UX/UI cell
# - 0004-000X: Board/Management
#
# UUIDs, role, and team are all sourced from foundation.AGENTS so that
# adding/renaming an agent is a single-file edit. Per-agent presentation
# (display name) lives below in _AGENT_PRESENTATION because it is the
# only field foundation does not (and should not) own.
# =============================================================================
# Derived AGENT_UUIDS — string-keyed for backward compat with consumers
# that index by slug and read string-typed UUIDs.
AGENT_UUIDS: dict[str, str] = {
slug: str(row.uuid) for slug, row in _foundation.AGENTS.items()
}
# Per-agent display names. Anything role/team/uuid is sourced from
# foundation; this dict only carries presentation strings.
_AGENT_PRESENTATION: dict[str, dict[str, Any]] = {
"ceo": {"name": "Renzo"},
"be-dev-1": {"name": "Backend Developer 1"},
"be-dev-2": {"name": "Backend Developer 2"},
"be-qa": {"name": "Backend QA"},
"be-pm": {"name": "Backend PM"},
"be-doc": {"name": "Backend Documenter"},
"fe-dev-1": {"name": "Frontend Developer 1"},
"fe-dev-2": {"name": "Frontend Developer 2"},
"fe-qa": {"name": "Frontend QA"},
"fe-pm": {"name": "Frontend PM"},
"fe-doc": {"name": "Frontend Documenter"},
"ux-dev-1": {"name": "UX/UI Developer 1"},
"ux-dev-2": {"name": "UX/UI Developer 2"},
"ux-qa": {"name": "UX/UI QA"},
"ux-pm": {"name": "UX/UI PM"},
"ux-doc": {"name": "UX/UI Documenter"},
"main-pm": {"name": "Main PM"},
"product-owner": {"name": "Product Owner"},
"head-marketing": {"name": "Head of Marketing"},
"auditor": {"name": "Auditor"},
"intake-1": {"name": "Intake"},
"secretary-1": {"name": "Secretary"},
"pr-reviewer-1": {"name": "PR Reviewer"},
"be-pr-reviewer": {"name": "Backend PR Reviewer"},
"fe-pr-reviewer": {"name": "Frontend PR Reviewer"},
"ux-pr-reviewer": {"name": "UX/UI PR Reviewer"},
}
def _build_default_agents() -> list[dict[str, Any]]:
"""Compose DEFAULT_AGENTS rows from foundation + presentation metadata.
The system sentinel is appended as a literal because:
1. The postgres `team` enum does not include 'system' — only
'backend|frontend|ux_ui|board|main_pm|fullstack|marketing'.
Seeding with team='system' would fail at INSERT.
2. The system row is a from_agent FK target, never a participant.
"""
rows: list[dict[str, Any]] = []
for slug, row in _foundation.AGENTS.items():
if slug == "system":
continue
rows.append(
{
"id": str(row.uuid),
"slug": slug,
"role": row.role.value,
"team": row.team.value,
**_AGENT_PRESENTATION[slug],
}
)
# System sentinel — kept as a literal so we can pass team=None into the
# DB without colliding with the postgres `team` enum (which does not
# have a 'system' value).
rows.append(
{
"id": str(_foundation.AGENTS["system"].uuid),
"slug": "system",
"name": "System",
"role": _foundation.AGENTS["system"].role.value,
"team": None,
}
)
return rows
DEFAULT_AGENTS: list[dict[str, Any]] = _build_default_agents()
# =============================================================================
# CHANNEL MEMBERSHIP
#
# Populates the database channel.members / channel.writers / silent_observers
# fields at seed time. Membership is now derived from
# foundation.policy.communications.CHANNELS — adding/removing an agent from a
# channel is a single edit in the foundation catalog.
#
# NOTE: This is SEPARATE from roboco/agents_config.py CHANNEL_ACCESS which is
# the runtime permission source of truth. Both derive from the same
# foundation catalog. Privileged roles (CEO, Auditor, Main PM) still bypass
# membership at runtime via has_privileged_access() in services/permissions.py.
# =============================================================================
CEO_AGENT_ID = AGENT_UUIDS["ceo"]
# Cell-member roles subject to a channel's team_scope. Cross-cell roles
# (MAIN_PM, AUDITOR, CEO, board) are NOT filtered by team_scope. Mirrors the
# rule in agents_config._TEAM_SCOPED_ROLES; duplicated here to avoid a
# circular import (agents_config already imports AGENT_UUIDS from this
# module).
_TEAM_SCOPED_ROLES: frozenset[_foundation.Role] = frozenset(
{
_foundation.Role.DEVELOPER,
_foundation.Role.QA,
_foundation.Role.DOCUMENTER,
_foundation.Role.CELL_PM,
}
)
def _slugs_for_role_set(
role_set: frozenset[_foundation.Role],
team_scope: _foundation.Team | None,
) -> list[str]:
"""Expand a role-set to sorted agent slugs, honoring optional team_scope.
A slug qualifies when its role is in `role_set` AND, if its role is in
_TEAM_SCOPED_ROLES and team_scope is set, its team matches team_scope.
The system sentinel is always excluded.
"""
out: list[str] = []
for slug, row in _foundation.AGENTS.items():
if slug == "system":
continue
if row.role not in role_set:
continue
if (
team_scope is not None
and row.role in _TEAM_SCOPED_ROLES
and row.team != team_scope
):
continue
out.append(slug)
return sorted(out)
def _build_channel_memberships() -> dict[str, list[str]]:
"""Per-channel sorted member slugs derived from foundation.CHANNELS."""
return {
slug: _slugs_for_role_set(spec.read_roles, spec.team_scope)
for slug, spec in _comms.CHANNELS.items()
}
CHANNEL_MEMBERSHIPS: dict[str, list[str]] = _build_channel_memberships()
# Auditor silent-read channels — derived from CHANNELS where AUDITOR appears
# in silent_roles.
AUDITOR_SILENT_ACCESS: list[str] = sorted(
slug
for slug, spec in _comms.CHANNELS.items()
if _foundation.Role.AUDITOR in spec.silent_roles
)
# =============================================================================
# INITIAL CHANNEL MESSAGES
# =============================================================================
INITIAL_MESSAGES = {
"announcements": {
"agent_id": "main-pm",
"content": """Welcome to RoboCo!
This is the official announcements channel. Company-wide updates will be posted here.
**Key Channels:**
- `#backend-cell`, `#frontend-cell`, `#uxui-cell` - Team communication
- `#dev-all`, `#qa-all`, `#pm-all`, `#doc-all` - Cross-cell role channels
- `#all-hands` - Company-wide open discussion
**Workflow:**
1. Call `give_me_work()` to receive your next assignment
2. Claim tasks in your team
3. Follow the lifecycle: CLAIM -> IN_PROGRESS -> VERIFY -> QA -> DOCS -> COMPLETE
4. Use your journal to track learning and decisions
Let's build something great together!
""",
},
"all-hands": {
"agent_id": "main-pm",
"content": """This is the all-hands channel for company-wide discussions.
Feel free to:
- Ask questions that span multiple teams
- Share interesting findings
- Discuss architecture decisions that affect everyone
- Celebrate wins and completed tasks
Please keep cell-specific discussions in your respective cell channels.
""",
},
"backend-cell": {
"agent_id": "be-pm",
"content": """Welcome to the Backend Cell channel!
**Team:**
- be-dev-1, be-dev-2: Backend Developers
- be-qa: Backend QA
- be-pm: Backend PM (me)
- be-doc: Backend Documenter
**Our Focus:**
- API development
- Database design
- Service architecture
- Performance optimization
Call `give_me_work()` to receive your next backend task.
""",
},
"frontend-cell": {
"agent_id": "fe-pm",
"content": """Welcome to the Frontend Cell channel!
**Team:**
- fe-dev-1, fe-dev-2: Frontend Developers
- fe-qa: Frontend QA
- fe-pm: Frontend PM (me)
- fe-doc: Frontend Documenter
**Our Focus:**
- UI development
- User experience
- Component architecture
- State management
Call `give_me_work()` to receive your next frontend task.
""",
},
"uxui-cell": {
"agent_id": "ux-pm",
"content": """Welcome to the UX/UI Cell channel!
**Team:**
- ux-dev-1, ux-dev-2: UX/UI Developers
- ux-qa: UX/UI QA
- ux-pm: UX/UI PM (me)
- ux-doc: UX/UI Documenter
**Our Focus:**
- Design systems
- User research
- Prototyping
- Accessibility
Call `give_me_work()` to receive your next UX/UI task.
""",
},
}