Read /Users/user_c042661f/Documents/Veas/docs/multi-agent-architecture.md and extract verbatim (or near-verbatim) the column/index definitions and conceptual descriptions for these sections, which I need to write a Sprint 1 migration plan:
§2 — artifact_topics join table column shape and partial indexes
§3 — schemas of these new tables: topics, bots, dyads, dyad_members, bot_bindings, channels, user_identities
§12.2 — user_identities backfill semantics including transport='legacy'
§16.1 — Sprint 1 verbatim (the plan brief already has it but confirm)
§16.8 — locked decisions
Focus on exact column types, constraints (especially the bot_bindings CHECK: (user_id IS NOT NULL) <> (dyad_id IS NOT NULL)), and index DDL. Return concise reproducible DDL fragments — not prose commentary. Output under ~600 lines.
Assistant
I'll read the document and extract the specific sections you need for your Sprint 1 migration plan.
Assistant
Let me read the file in sections to find the sections you need.
Assistant
Now let me search for the specific sections:
Assistant
Let me try a different pattern:
Assistant
Let me search for section headers differently:
Assistant
Perfect. Now let me read each section:
Assistant
Now let me get the sections on locked decisions (§16.8) and search for more detailed schema info:
Assistant
Perfect. Now let me get the remaining sections I need and compile them in a clean format. Let me also get tables from §3 more clearly and look for new tables schema:
Assistant
Let me search for the table definitions in the doc:
Assistant
Good. Now let me search for the topics, bots, and other table definitions that may be described in prose. Let me check around line 600-800 more carefully:
Assistant
Now let me check if there are explicit schema definitions for topics and bots tables anywhere, or if they're only referenced:
Assistant
Let me check what currently exists in migrations:
Assistant
Now let me search the document more carefully for table definitions that might be implicit in the narrative:
Assistant
Let me search for where user_bot_state schema is defined in the document:
Assistant
Let me search for the exact full definition of user_bot_state or if it's just mentioned without explicit DDL:
Assistant
Let me check if there's an explicit schema table for it:
Assistant
Now let me compile all the exact extractions. Based on what I've found, let me create a comprehensive summary. The document explicitly defines most schemas but leaves topics, bots somewhat implicit in the narrative (referenced but minimal DDL shown). Let me verify by reading §2 and 3 more carefully for any missing definitions:
Assistant
Let me read §5 which should have bots schema:
Assistant
Perfect. Now I have all the needed pieces. The document doesn't define topics and bots tables explicitly in DDL (they're referenced but the exact columns are determined by references and code). Let me compile the final extraction:
CREATE TABLE artifact_topics (
artifact_table text NOT NULL, -- 'memories' | 'observations' | …
artifact_id uuid NOT NULL,
topic_id uuid NOT NULL REFERENCES topics(id),
tagged_by_bot_id text NOT NULL REFERENCES bots(id),
reason text,
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','retired')),
created_at timestamptz NOT NULL DEFAULT now(),
retired_at timestamptz,
PRIMARY KEY (artifact_table, artifact_id, topic_id)
);
CREATE INDEX ON artifact_topics (topic_id, artifact_table) WHERE status='active';
CREATE INDEX ON artifact_topics (artifact_table, artifact_id) WHERE status='active';
Enforcement:
Join table, not array column — audit fidelity, per-topic lifecycle, authorization at write.
No FK to individual artifact tables (polymorphic via artifact_table); lint prevents orphans in S2a.
CREATE TABLE bot_bindings (
id uuid PRIMARY KEY,
bot_id text NOT NULL REFERENCES bots(id),
user_id uuid REFERENCES users(id), -- set for solo
dyad_id uuid REFERENCES dyads(id), -- set for dyad
created_at timestamptz NOT NULL DEFAULT now(),
CHECK ((user_id IS NOT NULL) <> (dyad_id IS NOT NULL))
);
channels
sql
CREATE TABLE channels (
id uuid PRIMARY KEY,
bot_id text NOT NULL REFERENCES bots(id),
transport text NOT NULL, -- 'discord' | 'whatsapp' | …
address text NOT NULL, -- bot account id, phone number, …
guild_id text, -- transport-specific
channel_id text,
config jsonb NOT NULL DEFAULT '{}'::jsonb,
UNIQUE (transport, address, guild_id, channel_id)
);
user_identities
sql
CREATE TABLE user_identities (
user_id uuid NOT NULL REFERENCES users(id),
transport text NOT NULL,
address text NOT NULL,
verified_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (transport, address)
);
Routing primitive:resolve_bot(inbound_event) -> bot_id via channels table lookup. No code path assumes 1:1.
CREATE TABLE topic_status (
id uuid PRIMARY KEY,
topic_id uuid NOT NULL REFERENCES topics(id),
dyad_id uuid REFERENCES dyads(id), -- set when pair-level
user_id uuid REFERENCES users(id), -- set when per-user
headline text NOT NULL,
body text NOT NULL,
last_updated_at timestamptz NOT NULL DEFAULT now(),
last_updated_by_bot_id text NOT NULL REFERENCES bots(id),
CHECK ((user_id IS NOT NULL) <> (dyad_id IS NOT NULL))
);
CREATE UNIQUE INDEX topic_status_user_key
ON topic_status (topic_id, user_id) WHERE user_id IS NOT NULL;
CREATE UNIQUE INDEX topic_status_dyad_key
ON topic_status (topic_id, dyad_id) WHERE dyad_id IS NOT NULL;
Constraint: Pair-level rows keyed by (topic_id, dyad_id) (not (topic_id, NULL)); prevents collision across multiple dyads.
Write rules:
Solo bot: per-user statuses only for bound user.
Dyadic bot: per-user statuses for either partner + pair-level status (dyad_id set, user_id NULL).
Tool:set_topic_status(scope, headline, body) where scope = "user:<id>" | "pair". Topic implicit from ctx.primary_topic_id.
Injection policy (§7.4): Gated by ctx.read_scopes.allow_cross_topic_status_injection:
peek or all: sees own topic's statuses + cross-topic statuses.
forbidden: sees only own topic's statuses.
user_bot_state (implicit schema from prose)
user_id uuid NOT NULL REFERENCES users(id)
bot_id text NOT NULL REFERENCES bots(id)
onboarding_state — migrated from users.onboarding_state for each (user, bot) pair
paused boolean — per-(user, bot) pause state (read path in S2a, write path deferred)
(Likely) PRIMARY KEY (user_id, bot_id)
Usage: Onboarding per bot (replaces global users.onboarding_state). Pause/resume per (user, bot) — additive to global system_state.is_paused kill switch.
§12.2 — User identity backfill semantics
sql
-- Backfill from users.phone to user_identities
INSERT INTO user_identities (user_id, transport, address, created_at)
SELECT id, 'legacy', phone, now()
FROM users
WHERE phone IS NOT NULL;
Rule: Existing users.phone → (transport='legacy', address=<phone>) rows in user_identities. The legacy transport signals pre-migration identity.
Audit requirement: If any row contains both a phone and a Discord id, both must become identity rows. Audit before backfill.
Future: Account-linking (verifying "this Discord id and that WhatsApp number are me") is a workflow to build later. Schema ready now. Until linking, two transport identities = two user_ids (duplicate-human risk).
§16.1 — Sprint 1 verbatim (Goal & Structure)
Goal: Land every additive table, backfill, and code skeletons (TurnContext fields, BotSpec carrier fields, channel/binding/identity resolution helpers) so subsequent sprints only flip switches.
Work items, ordered:
Migration 0020_topics_bots_bindings.sql: topics, bots, dyads, dyad_members, bot_bindings, channels, user_identities. Seed relationship topic, mediator bot, one dyads row, two dyad_members, one bot_bindings, channel rows for current Discord + WhatsApp. Backfill user_identities from users.phone.
Migration 0021_artifact_topics.sql: create the join table + partial indexes from §2. No FK to each artifact table (polymorphic via artifact_table column) — orphan prevention is application discipline; lint catches it in S2a.
Migration 0022_topic_status_user_bot_state.sql: topic_status (both partial indexes from §7), user_bot_state populated from users.onboarding_state for mediator.
Migration 0023_nullable_scope_columns.sql: nullable topic_id, bot_id on messages, bot_turns, scheduled_jobs, feedback, bridge_candidates; dyad_id on bridge_candidates; recorded_by_bot_id on artifact tables; audit columns on bot_turns (bot_spec_version, hot_context_builder_version, tool_schema_version).
Migration 0024_backfill.sql: Cursor-keyed INSERT INTO artifact_topics SELECT ... WHERE id > last_id ORDER BY id LIMIT 10000 loops with resumability per artifact table (not UPDATEs). Track progress in migration_progress(table, last_id) for restart. Validation queries committed to migrations/validation/.
OOB backfill rule: Existing out_of_bounds rows classified as relationship topic-scoped — get artifact_topics row pointing to relationship topic. "No artifact_topics rows = global OOB" is a future-only mode. Validation: SELECT count(*) FROM out_of_bounds WHERE NOT EXISTS (SELECT 1 FROM artifact_topics WHERE artifact_table='out_of_bounds' AND artifact_id=out_of_bounds.id) must be zero post-backfill.
All migrations live in prod. Backfill validated by OOB query + equivalent counts per artifact table.
Mediator behavior verified via frozen-fixture rendering equality: deterministic snapshot of DB + frozen now → render hot context pre- and post-migration → byte-equal.
TurnContext, BotSpec, routing.py shipped with new fields populated by default constructors. No call site references new fields yet.
All → relationship topic-scoped; "no rows = global OOB" is future-only
Soak duration before NOT NULL (S2a → S2b)
S2b
7 days minimum
Per-(user, bot) pause write-path scope
S4
Admin endpoint + tool, default off
decay.py per-topic vs global behavior
S3
Per-topic (coach's career observations shouldn't decay without mediator reinforcement)
Peek window length
S4
14 days
Status cap N
S4
5 most-recently-active topics per user
Solo bot identity, prompt, transport
S4/S5
Lock during S2a–S3; provisioning starts immediately
Solo crisis default
S4
Refer to dyadic bot + external resources
Cross-topic write ramp
S6
No bot at launch; mechanism only
Not cuttable:
S2b's CHECK ... NOT VALID → VALIDATE → NOT NULL pattern (rollback safety).
S3 (join cutover) before any second bot (no-op window).
S4 solo pre-flight track.
user_identities in S1 (duplicate-human risk).
consult_perspective clone helper in S4 (highest correctness defect).
Observability + eval baseline in S2a (regression detection).
app/services/turn_context.py
bot_id
bot_spec
binding_id
participants_shape
primary_topic_id
primary_topic_slug
channel_id
read_scopes
write_scopes
cross_topic_policy
all optional with defaults
partner: User | None
partner
Code: Extend app/bots/base.pyBotSpec with new fields as optional with mediator-shaped defaults. Add ReadScopes / WriteScopes dataclasses. No call-site changes.
Code: New module app/services/routing.py — resolve_bot(event), resolve_sender(transport, address), resolve_binding(bot_id, user_id). Not wired into inbound yet. Unit tests cover them.
Code: MEDIATOR_BOT carries new fields populated from DB at startup.