Commit e6070777
e60707779215Merged
Scott Nixon <[email protected]> ยท 7 months ago ยท 1 file ยท ~1 modified
Description
fix(pipeline): restore corrupted phase-1-spec.dot with valid DOT
The file contained a markdown conversation dump from a failed LLM generation instead of actual DOT content. Restored from the working SMB project copy and fixed dialect issues:
- Bare booleans for goal_gate/loop_restart (not quoted strings)
- Bare durations for timeout (not quoted strings)
- Added condition attrs to all FAIL edges
- Removed unsupported rankdir attribute
Details
- Commit
- e60707779215
- Parent
- d696a25aa0e3
pipelines/phase-1-spec.dotmodifiedView file
@@ -1,27 +1,147 @@
1-
The file keeps getting denied. Let me output the DOT content directly so you can save it yourself.1+
digraph phase1_eleanor_schema {2+
label="Phase 1: Eleanor Workflow Schema + Domain Model"3+
goal="Create 7 canonical workflow tables, TypeScript types, migration SQL, and seed data for the Eleanor AI workflow engine"4+
model="sonnet"5+
6+
7+
start [8+
label="Start"9+
shape="Mdiamond"10+
prompt="Begin Phase 1 of the Eleanor Workflow Engine: Schema + Domain Model. This phase replaces 15+ legacy scattered workflow tables with 7 canonical tables. No prior phase dependencies."11+
]12+
13+
write_types [14+
label="Write types.ts"15+
shape="box"16+
timeout=20m17+
allowed_tools="Read,Write,Glob,Bash"18+
prompt="Create the file apps/api/src/workflow/types.ts from scratch with all TypeScript enums, const arrays, union types, and row interfaces for the Eleanor workflow engine. The file must export the following sections in order: (1) ID generation: import nanoid; export const genId = (prefix: string) => prefix + nanoid(). Prefixes: rel_, wfi_, wft_, wfe_, art_, sup_, vrf_. (2) RELATIONSHIP_STAGES as const array: target, attempting_contact, conversation_active, nurturing, qualified_opportunity, account_open, implementing, improving, dormant_customer, closed_won, closed_lost, do_not_pursue. Export type RelationshipStage and TERMINAL_RELATIONSHIP_STAGES readonly array (closed_won, closed_lost, do_not_pursue). (3) WORKFLOW_TYPES as const: cold_outreach, follow_up, nurture, qualification, post_account, implementation, improvement. Export WorkflowType. (4) WORKFLOW_STATES as const: not_started, ready, in_progress, waiting_on_prospect, waiting_on_rosco, scheduled, blocked, completed, stopped. Export WorkflowState and TERMINAL_WORKFLOW_STATES (completed, stopped). (5) Substate const arrays and types: COLD_OUTREACH_SUBSTATES (target_selected, research_ready, contact_verification_needed, draft_needed, draft_in_review, approved_for_send, send_scheduled, sent_waiting_reply, reply_triage_needed, sequence_exhausted), FOLLOW_UP_SUBSTATES (waiting_followup_window, insight_needed, draft_needed, scheduled, sent_waiting_reply, reply_triage_needed, exhausted), NURTURE_SUBSTATES (parked_until_signal, nurture_due, evidence_collection, draft_needed, scheduled, waiting_response, paused_by_policy), QUALIFICATION_SUBSTATES (inbound_reply_open, discovery_needed, discovery_scheduled, proposal_requested, proposal_pending, decision_pending, stalled), IMPLEMENTATION_SUBSTATES (kickoff_needed, access_needed, baseline_pending, setup_in_progress, deliverable_pending, handoff_pending, baseline_complete), IMPROVEMENT_SUBSTATES (review_due, analysis_in_progress, recommendation_pending, waiting_customer, expansion_opportunity, paused_low_engagement). Export each substate type and export union type WorkflowSubstate covering all six. (6) TASK_TYPES as const: research_company, verify_contact, generate_draft, review_draft, dispatch_message, triage_reply, schedule_call, prepare_onboarding, deliver_baseline_report, deliver_audit, close_verification_gap, generate_nurture_content, collect_evidence, send_followup. Export TaskType. (7) TASK_STATUSES as const: pending, ready, in_progress, waiting, blocked, completed, cancelled. Export TaskStatus. (8) EVENT_TYPES as const: relationship_created, relationship_stage_changed, workflow_started, workflow_state_changed, workflow_completed, workflow_stopped, task_created, task_started, task_completed, task_cancelled, message_drafted, message_sent, reply_received, suppression_applied, suppression_revoked, timer_fired, verification_failed, verification_recovered. Export EventType. (9) ACTOR_TYPES as const: system, user, worker, mailbox, webhook. Export ActorType. (10) TRIGGER_TYPES as const (human): operator_started_workflow, operator_approved_draft, operator_completed_task, operator_applied_suppression, operator_closed_workflow; (system): scheduler_fired, retry_due, nurture_window_opened, verification_job_flagged_issue, deadline_reached; (external): reply_received, bounce_received, unsubscribe_received, meeting_booked, payment_or_account_created, onboarding_form_submitted; (derived): sequence_exhausted, qualification_threshold_met, implementation_success_criteria_met, customer_became_dormant. Export TriggerType. (11) WAITING_ON_VALUES as const: prospect, rosco, system, none. Export WaitingOn. (12) SUPPRESSION_TYPES as const: do_not_contact, invalid_contact, explicit_opt_out, legal_hold, paused_until, customer_pause. Export SuppressionType. SUPPRESSION_SCOPES: relationship, contact, channel, workflow. Export SuppressionScope. SUPPRESSION_STATUSES: active, expiring, revoked. Export SuppressionStatus. (13) ARTIFACT_TYPES as const: draft, outbound_message, delivery_attempt, inbox_message, reply_classification, meeting_note, proposal, report, implementation_note. Export ArtifactType. ARTIFACT_DIRECTIONS: outbound, inbound, internal. Export ArtifactDirection. (14) FINDING_TYPES as const: missing_next_action, duplicate_active_workflow, illegal_transition_attempt, task_without_owner, overdue_waiting_state, queue_mismatch, artifact_without_workflow, stuck_blocked, orphaned_artifact. Export FindingType. FINDING_SEVERITIES: info, warning, error. FindingSeverity. FINDING_STATUSES: open, acknowledged, resolved, suppressed. FindingStatus. (15) Row interfaces matching SQL schema exactly โ all IDs are string, all timestamps are Date, nullable fields are T | null (not optional), jsonb fields are Record<string, unknown>, artifact_refs is string[]: export interface Relationship { id: string; company_id: string; company_name: string; primary_contact_email: string | null; primary_contact_name: string | null; domain: string | null; city: string | null; niche: string | null; relationship_stage: RelationshipStage; active_workflow_instance_id: string | null; owner_user_id: string | null; next_action: string | null; next_action_at: Date | null; waiting_on: WaitingOn | null; blocking_reason: string | null; memory_summary: string | null; context: Record<string, unknown>; last_meaningful_event_at: Date | null; closed_reason: string | null; version: number; created_at: Date; updated_at: Date; }. export interface WorkflowInstance { id: string; relationship_id: string; workflow_type: WorkflowType; workflow_version: number; state: WorkflowState; substate: string | null; owner_user_id: string | null; next_action: string | null; next_action_at: Date | null; due_at: Date | null; waiting_on: WaitingOn | null; blocking_reason: string | null; context: Record<string, unknown>; started_at: Date; entered_state_at: Date; completed_at: Date | null; stopped_at: Date | null; exit_reason: string | null; is_active: boolean; version: number; created_at: Date; updated_at: Date; }. export interface WorkflowTask { id: string; workflow_instance_id: string; task_type: TaskType; status: TaskStatus; assignee_user_id: string | null; priority: number; due_at: Date | null; started_at: Date | null; completed_at: Date | null; blocked_reason: string | null; payload: Record<string, unknown>; artifact_refs: string[]; created_at: Date; updated_at: Date; }. export interface WorkflowEvent { id: string; relationship_id: string; workflow_instance_id: string | null; workflow_task_id: string | null; event_type: EventType; from_state: string | null; to_state: string | null; actor_type: ActorType; actor_id: string | null; reason_code: string | null; correlation_id: string | null; metadata: Record<string, unknown>; occurred_at: Date; created_row_at: Date; }. export interface CommunicationArtifact { id: string; relationship_id: string; workflow_instance_id: string | null; workflow_task_id: string | null; artifact_type: ArtifactType; provider: string | null; provider_id: string | null; thread_id: string | null; direction: ArtifactDirection | null; status: string | null; summary: string | null; payload: Record<string, unknown>; occurred_at: Date | null; created_at: Date; updated_at: Date; }. export interface Suppression { id: string; relationship_id: string; scope: SuppressionScope; suppression_type: SuppressionType; status: SuppressionStatus; starts_at: Date; ends_at: Date | null; reason: string | null; metadata: Record<string, unknown>; created_at: Date; updated_at: Date; }. export interface VerificationFinding { id: string; relationship_id: string | null; workflow_instance_id: string | null; workflow_task_id: string | null; finding_type: FindingType; severity: FindingSeverity; status: FindingStatus; summary: string; details: Record<string, unknown>; detected_at: Date; resolved_at: Date | null; created_at: Date; updated_at: Date; }."19+
]20+
21+
verify_types [22+
label="Types compile?"23+
shape="diamond"24+
timeout=10m25+
node_type="conditional"26+
allowed_tools="Read,Bash"27+
goal_gate=true28+
prompt="Verify that apps/api/src/workflow/types.ts compiles with no TypeScript errors. Run tsc --noEmit using the project tsconfig (try: cd apps/api && npx tsc --noEmit, or check for a tsconfig.json and run accordingly). Check for: (1) All const arrays declared with 'as const' so derived types are literal string unions not widened to string. (2) All row interfaces use T | null for nullable fields, never optional ?:. (3) WorkflowSubstate union type covers all six substate union members. (4) genId function properly typed โ takes string prefix, returns string. (5) No missing imports (nanoid must be imported). (6) No duplicate identifiers. (7) All exported interfaces have every field from the spec. Emit PASS if tsc exits with code 0 and no errors are printed. Emit FAIL if any type errors, missing exports, or import failures are found โ include the error messages in your output."29+
]30+
31+
fix_types [32+
label="Fix type errors"33+
shape="box"34+
timeout=15m35+
allowed_tools="Read,Write,Bash"36+
prompt="Fix all TypeScript compilation errors in apps/api/src/workflow/types.ts. Read the current file content and the tsc error output. Apply targeted fixes: (1) If arrays lack 'as const' โ add it so (typeof ARRAY)[number] produces a union of literals not string. (2) If nullable fields use optional syntax ?: โ change to T | null. (3) If nanoid import fails โ check the project's package.json for the correct import path (may be 'nanoid' as ESM or require a specific import style). (4) If an interface is missing fields โ add them. (5) If union types are missing members โ add them. Do not rewrite working sections. After fixing, re-read the file to confirm the fix looks correct before finishing."37+
]38+
39+
write_migration [40+
label="Write migration SQL"41+
shape="box"42+
timeout=20m43+
allowed_tools="Read,Write,Glob,Bash"44+
prompt="Create the file sql/migrations/0007_eleanor_workflow_schema.sql. The entire file must be wrapped in BEGIN; ... COMMIT;. Structure it in three sections: DROPS, CREATES, and ALTER for the circular FK. SECTION 1 โ DROP legacy tables (all with IF EXISTS ... CASCADE, in dependency order): DROP TABLE IF EXISTS outreach_engagement_events CASCADE; DROP TABLE IF EXISTS outreach_delivery_attempts CASCADE; DROP TABLE IF EXISTS outreach_messages CASCADE; DROP TABLE IF EXISTS inbox_messages CASCADE; DROP TABLE IF EXISTS outreach_item_events CASCADE; DROP TABLE IF EXISTS outreach_items CASCADE; DROP TABLE IF EXISTS outreach_drafts CASCADE; DROP TABLE IF EXISTS outreach_logs CASCADE; DROP TABLE IF EXISTS outreach_experiments CASCADE; DROP TABLE IF EXISTS outreach_suppression_list CASCADE; DROP TABLE IF EXISTS audit_requests CASCADE; DROP TABLE IF EXISTS lead_events CASCADE; DROP TABLE IF EXISTS lead_competitors CASCADE; DROP TABLE IF EXISTS leads CASCADE; DROP TABLE IF EXISTS free_report_confirmations CASCADE; DROP TABLE IF EXISTS app_state_snapshots CASCADE; SECTION 2 โ CREATE the 7 new tables in dependency order: TABLE 1 relationships โ id text PRIMARY KEY, company_id text NOT NULL, company_name text NOT NULL, primary_contact_email text, primary_contact_name text, domain text, city text, niche text, relationship_stage text NOT NULL DEFAULT 'target', active_workflow_instance_id text (no FK yet โ circular dependency resolved in section 3), owner_user_id text, next_action text, next_action_at timestamptz, waiting_on text, blocking_reason text, memory_summary text, context jsonb NOT NULL DEFAULT '{}'::jsonb, last_meaningful_event_at timestamptz, closed_reason text, version integer NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_relationships_stage_action ON relationships (relationship_stage, next_action_at); CREATE INDEX idx_relationships_owner_action ON relationships (owner_user_id, next_action_at) WHERE owner_user_id IS NOT NULL; CREATE INDEX idx_relationships_active_workflow ON relationships (active_workflow_instance_id) WHERE active_workflow_instance_id IS NOT NULL; CREATE UNIQUE INDEX idx_relationships_company_id ON relationships (company_id); CREATE INDEX idx_relationships_domain ON relationships (lower(domain)) WHERE domain IS NOT NULL; CREATE INDEX idx_relationships_email ON relationships (lower(primary_contact_email)) WHERE primary_contact_email IS NOT NULL. TABLE 2 workflow_instances โ id text PRIMARY KEY, relationship_id text NOT NULL REFERENCES relationships(id), workflow_type text NOT NULL, workflow_version integer NOT NULL DEFAULT 1, state text NOT NULL DEFAULT 'not_started', substate text, owner_user_id text, next_action text, next_action_at timestamptz, due_at timestamptz, waiting_on text, blocking_reason text, context jsonb NOT NULL DEFAULT '{}'::jsonb, started_at timestamptz NOT NULL DEFAULT now(), entered_state_at timestamptz NOT NULL DEFAULT now(), completed_at timestamptz, stopped_at timestamptz, exit_reason text, is_active boolean NOT NULL DEFAULT true, version integer NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE UNIQUE INDEX idx_workflow_instances_one_active ON workflow_instances (relationship_id) WHERE is_active = true; CREATE INDEX idx_workflow_instances_type_state ON workflow_instances (workflow_type, state, next_action_at); CREATE INDEX idx_workflow_instances_owner ON workflow_instances (owner_user_id, state, due_at) WHERE owner_user_id IS NOT NULL; CREATE INDEX idx_workflow_instances_relationship ON workflow_instances (relationship_id, is_active). TABLE 3 workflow_tasks โ id text PRIMARY KEY, workflow_instance_id text NOT NULL REFERENCES workflow_instances(id), task_type text NOT NULL, status text NOT NULL DEFAULT 'pending', assignee_user_id text, priority integer NOT NULL DEFAULT 100, due_at timestamptz, started_at timestamptz, completed_at timestamptz, blocked_reason text, payload jsonb NOT NULL DEFAULT '{}'::jsonb, artifact_refs jsonb NOT NULL DEFAULT '[]'::jsonb, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_workflow_tasks_instance_status ON workflow_tasks (workflow_instance_id, status, due_at); CREATE INDEX idx_workflow_tasks_assignee ON workflow_tasks (assignee_user_id, status, due_at) WHERE assignee_user_id IS NOT NULL; CREATE INDEX idx_workflow_tasks_type_status ON workflow_tasks (task_type, status). TABLE 4 workflow_events โ id text PRIMARY KEY, relationship_id text NOT NULL REFERENCES relationships(id), workflow_instance_id text REFERENCES workflow_instances(id), workflow_task_id text REFERENCES workflow_tasks(id), event_type text NOT NULL, from_state text, to_state text, actor_type text NOT NULL, actor_id text, reason_code text, correlation_id text, metadata jsonb NOT NULL DEFAULT '{}'::jsonb, occurred_at timestamptz NOT NULL DEFAULT now(), created_row_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_workflow_events_relationship ON workflow_events (relationship_id, occurred_at DESC); CREATE INDEX idx_workflow_events_instance ON workflow_events (workflow_instance_id, occurred_at DESC) WHERE workflow_instance_id IS NOT NULL; CREATE INDEX idx_workflow_events_type ON workflow_events (event_type, occurred_at DESC); CREATE INDEX idx_workflow_events_correlation ON workflow_events (correlation_id) WHERE correlation_id IS NOT NULL. TABLE 5 communication_artifacts โ id text PRIMARY KEY, relationship_id text NOT NULL REFERENCES relationships(id), workflow_instance_id text REFERENCES workflow_instances(id), workflow_task_id text REFERENCES workflow_tasks(id), artifact_type text NOT NULL, provider text, provider_id text, thread_id text, direction text, status text, summary text, payload jsonb NOT NULL DEFAULT '{}'::jsonb, occurred_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_artifacts_relationship ON communication_artifacts (relationship_id, artifact_type, created_at DESC); CREATE INDEX idx_artifacts_workflow ON communication_artifacts (workflow_instance_id, artifact_type) WHERE workflow_instance_id IS NOT NULL; CREATE INDEX idx_artifacts_thread ON communication_artifacts (thread_id) WHERE thread_id IS NOT NULL; CREATE INDEX idx_artifacts_provider ON communication_artifacts (provider, provider_id) WHERE provider_id IS NOT NULL. TABLE 6 suppressions โ id text PRIMARY KEY, relationship_id text NOT NULL REFERENCES relationships(id), scope text NOT NULL, suppression_type text NOT NULL, status text NOT NULL DEFAULT 'active', starts_at timestamptz NOT NULL DEFAULT now(), ends_at timestamptz, reason text, metadata jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_suppressions_relationship ON suppressions (relationship_id, status); CREATE INDEX idx_suppressions_active ON suppressions (status, suppression_type) WHERE status = 'active'; CREATE INDEX idx_suppressions_expiring ON suppressions (ends_at) WHERE ends_at IS NOT NULL AND status = 'active'. TABLE 7 verification_findings โ id text PRIMARY KEY, relationship_id text REFERENCES relationships(id), workflow_instance_id text REFERENCES workflow_instances(id), workflow_task_id text REFERENCES workflow_tasks(id), finding_type text NOT NULL, severity text NOT NULL, status text NOT NULL DEFAULT 'open', summary text NOT NULL, details jsonb NOT NULL DEFAULT '{}'::jsonb, detected_at timestamptz NOT NULL DEFAULT now(), resolved_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(). Indexes: CREATE INDEX idx_findings_status ON verification_findings (status, severity); CREATE INDEX idx_findings_relationship ON verification_findings (relationship_id) WHERE relationship_id IS NOT NULL; CREATE INDEX idx_findings_type ON verification_findings (finding_type, status). SECTION 3 โ Add circular FK: ALTER TABLE relationships ADD CONSTRAINT fk_relationships_active_workflow FOREIGN KEY (active_workflow_instance_id) REFERENCES workflow_instances(id);"45+
]46+
47+
verify_migration [48+
label="Migration runs clean?"49+
shape="diamond"50+
timeout=10m51+
node_type="conditional"52+
allowed_tools="Read,Bash"53+
goal_gate=true54+
prompt="Verify that sql/migrations/0007_eleanor_workflow_schema.sql executes without errors. Steps: (1) Check the DATABASE_URL environment variable is set. (2) Run the migration: psql $DATABASE_URL -f sql/migrations/0007_eleanor_workflow_schema.sql. Capture the exit code and output. (3) If successful, verify the 7 new tables exist by running: psql $DATABASE_URL -c \"SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name;\" and confirm relationships, workflow_instances, workflow_tasks, workflow_events, communication_artifacts, suppressions, verification_findings are all present. (4) Verify legacy tables are gone: leads, outreach_items, outreach_drafts, outreach_messages, inbox_messages, outreach_delivery_attempts, outreach_engagement_events, outreach_item_events, outreach_logs, outreach_experiments, outreach_suppression_list, audit_requests, lead_events, lead_competitors, app_state_snapshots should NOT appear in the table list. (5) Verify non-workflow tables are intact: brands, prompts, scan_runs, report_runs, org_subscriptions should still be present. (6) Verify the unique partial index on workflow_instances exists: psql $DATABASE_URL -c \"SELECT indexname FROM pg_indexes WHERE tablename='workflow_instances' AND indexname='idx_workflow_instances_one_active';\" (7) Verify the circular FK was added: psql $DATABASE_URL -c \"SELECT constraint_name FROM information_schema.table_constraints WHERE table_name='relationships' AND constraint_type='FOREIGN KEY';\" and confirm fk_relationships_active_workflow is present. Emit PASS if migration exits 0, all 7 tables exist, all legacy tables are gone, and non-workflow tables are intact. Emit FAIL with specific error details otherwise."55+
]56+
57+
fix_migration [58+
label="Fix migration errors"59+
shape="box"60+
timeout=15m61+
allowed_tools="Read,Write,Bash"62+
prompt="Fix errors in sql/migrations/0007_eleanor_workflow_schema.sql based on the psql error output. Common issues: (1) FK creation order error โ relationships must be created BEFORE workflow_instances but WITHOUT the active_workflow_instance_id FK (which creates the circular dependency). The FK must be added via ALTER TABLE after both tables exist. Check that the DROP and CREATE order is correct. (2) 'table does not exist' on DROP โ ensure all DROP statements use IF EXISTS. (3) jsonb default syntax โ must be '{}'::jsonb and '[]'::jsonb with explicit cast. (4) Partial index WHERE clause syntax โ must be a simple column condition e.g. WHERE is_active = true, WHERE owner_user_id IS NOT NULL. (5) Constraint name conflicts from a previous failed run โ add DROP CONSTRAINT IF EXISTS before adding constraints, or wrap in a DO $$ block. (6) Transaction aborted mid-way โ fix the error that caused the abort, then the whole BEGIN/COMMIT block will retry clean. Do not remove the BEGIN/COMMIT wrapper."63+
]64+
65+
write_seed [66+
label="Write seed.ts"67+
shape="box"68+
timeout=20m69+
allowed_tools="Read,Write,Glob,Bash"70+
prompt="Create the file apps/api/src/workflow/seed.ts. First, read existing database client files to find how the project connects to PostgreSQL (check apps/api/src/db.ts, apps/api/src/database.ts, or similar). Also read apps/api/src/workflow/types.ts to confirm the genId import path. The seed script must export an async function seedWorkflow() and include a main guard (if require.main === module or if import.meta.url === ...) to call it. The function must insert 3 relationships, 3 workflow instances, 3 workflow tasks, and 6 workflow events in the following order to avoid FK violations: STEP 1 โ Insert 3 relationships with active_workflow_instance_id = NULL: (a) Acme Corp: id=genId('rel_'), company_id='company_acme', company_name='Acme Corp', domain='acmecorp.com', relationship_stage='attempting_contact', version=1. (b) Widget Inc: id=genId('rel_'), company_id='company_widget', company_name='Widget Inc', domain='widgetinc.com', relationship_stage='nurturing', version=1. (c) TechStart LLC: id=genId('rel_'), company_id='company_techstart', company_name='TechStart LLC', domain='techstart.io', relationship_stage='implementing', version=1. STEP 2 โ Insert 3 workflow instances: (a) Acme cold_outreach: id=genId('wfi_'), relationship_id=acme.id, workflow_type='cold_outreach', workflow_version=1, state='in_progress', substate='draft_needed', is_active=true, version=1. (b) Widget nurture: id=genId('wfi_'), relationship_id=widget.id, workflow_type='nurture', workflow_version=1, state='scheduled', substate='parked_until_signal', is_active=true, next_action_at=30 days from now, version=1. (c) TechStart implementation: id=genId('wfi_'), relationship_id=techstart.id, workflow_type='implementation', workflow_version=1, state='in_progress', substate='setup_in_progress', is_active=true, version=1. STEP 3 โ Insert 3 workflow tasks: (a) Acme task: id=genId('wft_'), workflow_instance_id=acmeWfi.id, task_type='generate_draft', status='ready', priority=100. (b) Widget task: id=genId('wft_'), workflow_instance_id=widgetWfi.id, task_type='generate_nurture_content', status='pending', priority=100, due_at=30 days from now. (c) TechStart task: id=genId('wft_'), workflow_instance_id=techstartWfi.id, task_type='deliver_baseline_report', status='in_progress', priority=100, started_at=now. STEP 4 โ Insert 6 workflow events (relationship_created and workflow_started for each): For each relationship emit a relationship_created event (actor_type='system', event_type='relationship_created'), and for each workflow instance emit a workflow_started event (actor_type='system', event_type='workflow_started', from_state=null, to_state='in_progress' or 'scheduled' as appropriate). All event IDs use genId('wfe_'). STEP 5 โ UPDATE relationships to set active_workflow_instance_id: UPDATE relationships SET active_workflow_instance_id=acmeWfi.id WHERE id=acme.id; same for widget and techstart. Use the project's db client to run all inserts. If the project uses a query builder (Drizzle, Kysely) use it; if raw SQL use parameterized queries. Log 'Seed complete' on success. Handle errors by logging and re-throwing."71+
]72+
73+
verify_seed [74+
label="Seed + canonical queries pass?"75+
shape="diamond"76+
timeout=10m77+
node_type="conditional"78+
allowed_tools="Read,Bash"79+
goal_gate=true80+
prompt="Verify the seed script runs and the five canonical queries return correct results. (1) Run the seed script: cd apps/api && npx tsx src/workflow/seed.ts (or ts-node, whichever the project uses). Verify it exits 0. (2) Verify row counts: psql $DATABASE_URL -c 'SELECT COUNT(*) FROM relationships;' โ expect 3. psql $DATABASE_URL -c 'SELECT COUNT(*) FROM workflow_instances;' โ expect 3. psql $DATABASE_URL -c 'SELECT COUNT(*) FROM workflow_tasks;' โ expect 3. psql $DATABASE_URL -c 'SELECT COUNT(*) FROM workflow_events;' โ expect 6. (3) Run the five canonical queries for Acme Corp: Q1 (stage): SELECT relationship_stage FROM relationships WHERE company_name='Acme Corp' โ expect 'attempting_contact'. Q2 (active workflow): SELECT workflow_type, state FROM workflow_instances WHERE relationship_id=(SELECT id FROM relationships WHERE company_name='Acme Corp') AND is_active=true โ expect cold_outreach / in_progress. Q3 (next action): SELECT task_type, status FROM workflow_tasks WHERE workflow_instance_id=(SELECT id FROM workflow_instances WHERE relationship_id=(SELECT id FROM relationships WHERE company_name='Acme Corp') AND is_active=true) AND status IN ('pending','ready') โ expect generate_draft / ready. Q4 (owner): SELECT owner_user_id FROM workflow_instances WHERE relationship_id=(SELECT id FROM relationships WHERE company_name='Acme Corp') AND is_active=true โ may be null, that is acceptable. Q5 (due): SELECT next_action_at FROM workflow_instances WHERE relationship_id=(SELECT id FROM relationships WHERE company_name='Acme Corp') AND is_active=true โ return value noted. (4) Verify active_workflow_instance_id back-pointer is set: SELECT active_workflow_instance_id FROM relationships WHERE company_name='Acme Corp' โ must NOT be null. Emit PASS if seed exits 0, row counts are correct, Q1-Q3 return expected values, and back-pointers are set. Emit FAIL with specific details otherwise."81+
]82+
83+
fix_seed [84+
label="Fix seed errors"85+
shape="box"86+
timeout=15m87+
allowed_tools="Read,Write,Bash,Glob"88+
prompt="Fix errors in apps/api/src/workflow/seed.ts based on the error output from running tsx or ts-node. Common issues: (1) FK violation on relationships insert โ active_workflow_instance_id must be NULL on initial insert, then UPDATEd after workflow_instances are created. Confirm STEP 5 UPDATE is present and runs after all inserts. (2) Wrong db client import โ re-read existing service files (apps/api/src/) to find the correct import. (3) genId import path wrong โ re-check apps/api/src/workflow/types.ts export. (4) Canonical query Q1 returns wrong stage โ check that relationship_stage is being set correctly in the INSERT. (5) Canonical query Q2 returns no rows โ check that is_active=true is being set on workflow instance inserts. (6) Row count wrong โ check for duplicate inserts if seed was run twice; add a cleanup block at the start: DELETE FROM workflow_events WHERE relationship_id IN (SELECT id FROM relationships WHERE company_name IN ('Acme Corp','Widget Inc','TechStart LLC')); and similarly for other tables, in reverse FK order, then re-insert. Make targeted fixes and do not break working inserts."89+
]90+
91+
verify_non_workflow [92+
label="Non-workflow tables intact?"93+
shape="diamond"94+
timeout=10m95+
node_type="conditional"96+
allowed_tools="Bash,Read"97+
goal_gate=true98+
prompt="Verify that all non-workflow tables are intact and queryable after the migration. Run: psql $DATABASE_URL -c \"SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name;\" and check that each of the following tables appears in the output: brands, brand_competitors, prompts, configured_models, scan_runs, scan_entries, scan_entry_mentions, report_runs, report_details, report_artifacts, report_events, optimization_actions, optimization_action_events, optimization_kpi_snapshots, cta_funnel_events, org_subscriptions, model_config_snapshots, contact_verification_cache. Also spot-check data integrity: run SELECT COUNT(*) FROM brands; and SELECT COUNT(*) FROM scan_runs; โ if either returns an error or unexpectedly zero rows (and the project is not brand new), flag it. Run SELECT COUNT(*) FROM configured_models; โ should return without error. Also verify Better Auth tables exist: user, session, account, organization. Emit PASS if all non-workflow tables are present and SELECT COUNT(*) runs without error on brands, scan_runs, and configured_models. Emit FAIL if any table is missing with the specific table names that are absent."99+
]100+
101+
fix_collateral [102+
label="Fix collateral damage"103+
shape="box"104+
timeout=15m105+
allowed_tools="Read,Write,Bash"106+
prompt="Fix any non-workflow tables that were accidentally dropped or damaged by the migration in sql/migrations/0007_eleanor_workflow_schema.sql. First, identify which tables are missing by diffing the expected table list against psql output. Then: (1) If the migration has an overly broad DROP statement that matched a non-workflow table โ edit the migration file to be more specific and add IF EXISTS guards. (2) If a non-workflow table is missing and a pg_dump backup exists โ restore it with: pg_restore -d $DATABASE_URL --table=<table_name> --data-only backup_YYYYMMDD.dump. (3) If no backup exists and the table structure is known from the codebase โ reconstruct the CREATE TABLE statement from ORM schema files or migration history and re-create it. Document what was lost and what was fixed. After fixing, note that the migration file must be edited so the issue does not recur."107+
]108+
109+
commit_changes [110+
label="Commit changes"111+
shape="box"112+
timeout=10m113+
allowed_tools="Bash"114+
prompt="Commit all Phase 1 changes to git. Run: git add apps/api/src/workflow/types.ts sql/migrations/0007_eleanor_workflow_schema.sql apps/api/src/workflow/seed.ts && git commit -m 'feat(eleanor): Phase 1 โ schema, types, migration, and seed data\n\nCreate 7 canonical workflow tables replacing 15+ legacy tables.\nAdd TypeScript types, enums, and row interfaces.\nAdd seed script with 3 sample relationships.\nAll canonical queries verified against seed data.'"115+
]116+
117+
done [118+
label="Done"119+
shape="Msquare"120+
prompt="Phase 1 complete. Deliverables produced: (1) apps/api/src/workflow/types.ts โ all TypeScript enums, const arrays, union types, row interfaces, and genId helper, compiling with no errors. (2) sql/migrations/0007_eleanor_workflow_schema.sql โ migration that drops 15 legacy tables and creates 7 canonical tables (relationships, workflow_instances, workflow_tasks, workflow_events, communication_artifacts, suppressions, verification_findings) with all indexes and the circular FK between relationships and workflow_instances. (3) apps/api/src/workflow/seed.ts โ seed script creating 3 sample relationships in different stages with active workflows and tasks. All five canonical queries verified against seed data. Non-workflow tables (brands, scans, reports, auth, billing) are unaffected."121+
]2122
3-
Written to `pipelines/eleanor-phase1-schema.dot`. Pipeline structure:123+
start -> write_types124+
125+
write_types -> verify_types4126
5-
```6-
start7-
โ create_types โ verify_types โฒ fix_types8-
โ create_migration โ verify_migration โฒ fix_migration9-
โ create_seed โ verify_seed โฒ fix_seed10-
โ final_verify โฒ fix_integration11-
โ done12-
```127+
verify_types -> write_migration [label="PASS" condition="preferred_label=PASS"]128+
verify_types -> fix_types [label="FAIL", condition="preferred_label=FAIL"]129+
fix_types -> verify_types [loop_restart=true]13130
14-
**4 work phases, each with verify/fix loops:**131+
write_migration -> verify_migration15132
16-
| Phase | Work Node | Verify Node | Fix Node | Output |17-
|-------|-----------|-------------|----------|--------|18-
| 1 | Create TypeScript Types | Verify Types | Fix Types | `apps/api/src/workflow/types.ts` |19-
| 2 | Create SQL Migration | Verify Migration | Fix Migration | `sql/migrations/0007_eleanor_workflow_schema.sql` |20-
| 3 | Create Seed Data | Verify Seed Data | Fix Seed Data | `apps/api/src/workflow/seed.ts` |21-
| 4 | โ | Final Integration Check | Fix Integration | Cross-file consistency |133+
verify_migration -> write_seed [label="PASS" condition="preferred_label=PASS"]134+
verify_migration -> fix_migration [label="FAIL", condition="preferred_label=FAIL"]135+
fix_migration -> verify_migration [loop_restart=true]22136
23-
**11 nodes total:** 1 start, 1 done, 3 work boxes, 4 conditional diamonds (verify/check), 3 fix boxes. Each verify node outputs PASS/FAIL. FAIL loops back through the fix node with `loop_restart=true`. The final integration check has `goal_gate="true"` and validates cross-file consistency plus the 5 canonical SQL queries.137+
write_seed -> verify_seed24138
25-
All prompts are self-contained with the full spec context โ no external references to ticket systems or issue IDs.139+
verify_seed -> verify_non_workflow [label="PASS" condition="preferred_label=PASS"]140+
verify_seed -> fix_seed [label="FAIL", condition="preferred_label=FAIL"]141+
fix_seed -> verify_seed [loop_restart=true]26142
27-
Want me to try writing the file again, or would you prefer to copy the content from above?143+
verify_non_workflow -> commit_changes [label="PASS" condition="preferred_label=PASS"]144+
commit_changes -> done145+
verify_non_workflow -> fix_collateral [label="FAIL", condition="preferred_label=FAIL"]146+
fix_collateral -> verify_non_workflow [loop_restart=true]147+
}