Skip to content

Lifecycle registry

Every lifecycle in Rose: a thing that moves through states (a booking, an ingestion operation, a HubSpot event, the widget's display). Read this page before you add or change a status, state, phase or step value, a flag or nullable timestamp that marks progress, or code that branches on one. Find the row, go to its owner, change it there.

A lifecycle is implicit when its states and transitions exist but are declared nowhere: a status string written from several functions, booleans that together encode a state, a timestamp whose NULL means "not yet". Implicit lifecycles are where stuck states and duplicate side effects come from. The inventory below was built by a repository-wide audit (IX-6217, November 2026).

How to declare a lifecycle

Rose does not use a state-machine library. Each layer already has a pattern that works; new lifecycles follow it, and existing ones move towards it when they are touched.

Layer Pattern Reference implementation
Postgres Value set as an enum or CHECK. Status and its timestamps tied by one CHECK. Every transition in a function that locks the row and checks the current state. A partial unique index for "at most one active". knowledge.ingestion_* tables and their RPCs; the status and timestamp CHECK on knowledge.website_rescan_reviews
Python A StrEnum that mirrors the database set. A pure function that decides the next state, and a table that maps it to an effect. Writes are compare-and-set: filter on the state you read. determine_next_action and NEXT_ACTION_TO_ROUTE in ixchat/nodes/intent_router.py; ixknowledge/content_transitions.py; update_registration in ixadmin_api/routes/agent_auth.py
LangGraph state State is checkpointed: a key keeps last turn's value unless this turn writes it. A value that belongs to one turn is reset at turn start (_prepare_query_state in ixchat/chatbot.py). A node with no result writes an explicit empty value, never {}. The turn-local block in _prepare_query_state; intent_classifier_node on failure
TypeScript A discriminated union whose variants carry their own data. One reducer or hook owns it and guards each action on the current state. Status to label or color maps are Record<Union, …> so a new value fails the type check. shared/src/utils/widget/conversationFlowReducer.ts; configReducer in shared/src/config/unified/ConfigProvider.tsx; client-backoffice/src/services/documentUploadQueue.ts
Timers and observers One handle per lifecycle, cleared when the lifecycle restarts and on cleanup. stopPolling in DomObserverStrategy.ts

Three rules follow from the defects found:

  • One owner writes. Anything else that needs the state reads it or calls the owner. A second store that mirrors the state is a bug waiting for a missed write.
  • Name the state once. If two places test "is active" with different expressions, they will disagree. Export the predicate from the owner.
  • A terminal write checks the state it leaves. UPDATE … WHERE id = … lets a late worker overwrite a newer result; add AND status = <expected>.

When you add a lifecycle, add its row here. When you fix a hazard, remove it from Open hazards.

Inventory

Level: explicit (declared and enforced in one place), partial (typed, but transitions are spread out), implicit (flag or string combinations only).

Paths are relative to backend/packages, backend/apps or frontend as the name shows. SQL functions live in supabase/migrations; the baseline holds most of them.

Knowledge and ingestion

Lifecycle States Stored in Transitions owned by Level
Ingestion operation queued, running, succeeded, partial_failed, failed, cancelling, cancelled knowledge.ingestion_operations.status SQL RPCs; refresh_ingestion_operation derives it from work items explicit
Work item and attempt item: pending, dispatched, running, retry_wait, succeeded, skipped, failed, cancelled; attempt adds dispatching, expired knowledge.ingestion_work_items, ingestion_work_item_attempts SQL RPCs with lease tokens (claim_, complete_, fail_, recover_…) explicit, with the failure-settlement block copied in five functions
Content stage DAG map → triage → finalize_discovery → sample → decide_section → scrape → clean ingestion_work_items.stage ContentTransitions.complete_content_work_item in ixknowledge/content_transitions.py explicit
Website re-scan review scanning, ready, approved, dismissed, stale, plus a free-text resolution knowledge.website_rescan_reviews SQL RPCs (start_, apply_, dismiss_website_rescan_review) explicit in SQL; the "review blocks this action" test is written four times
Preparation run uploading, running, awaiting_review, paused, failed, cancelled, published, completed × checkpoint × target knowledge.preparation_runs (text + CHECK) Ten SQL functions implicit
Document discovered, active, stale, failed (blocked, superseded never written) × is_deleted × scrape_policy × snapshot present knowledge.documents SQL RPCs and direct writes from ixscraping/stores/supabase_store.py and ixrag/document_pipeline/knowledge_document_store.py implicit
Crawl run queued, mapping, mapped, failed knowledge.crawl_runs.status SQL (projection of the operation) and the legacy ixscraping store partial, two writers
Corpus status absent, indexing, ready, failed public.workspaces.corpus_status Triggers sync_site_corpus_lifecycle and invalidate_site_corpus_on_root_change explicit; see corpus status transitions
Re-ingest run running, succeeded, failed knowledge.reingest_runs The document-loader process that created the row partial
Legacy to new knowledge migration Derived on each run from a hold row, pending Drive documents, review status and two config booleans knowledge.corpus_migration_holds, system.website_migrated, system.documents_migrated cli/commands/unified/migration_run.py implicit

Corpus status transitions

The glossary's absent → indexing → ready | failed is the main path. The triggers also do:

  • failed → indexing and absent → indexing when a new operation starts (a ready corpus is not rebound and keeps serving);
  • indexing → absent when the operation succeeds with nothing to serve;
  • indexing → indexing when the operation succeeds but newer source revisions are not loaded yet;
  • any state → absent when the workspace's roots change.

Chat graph (ixchat)

Lifecycle States Stored in Transitions owned by Level
Booking flow none, first entry, collecting, paused, redirected, exited, max attempts, completed: all flag combinations RoseChatState.booking_state (BookingState), merged by merge_booking_states chatbot._prepare_query_state, intent_router, booking_handler implicit
Turn-local values "this turn" versus "this session" Every key is checkpointed; resets in _prepare_query_state, TRANSIENT_FIELDS in nodes/response.py, and service.py Convention partial
Demo proposal Interest score, proposed last turn, ever proposed, judge verdict, judge hold interest_signals_state, dialog_supervision_state, demo_readiness_verdict, demo_gate_judge_hold interest_signals_detector, intent_router, skill_applier_rules (the suppression ladder appears in all three) implicit
Profiling and post-conversion questionnaire Collected, pending, asked, complete, finalized ProfilingState; metadata.post_conversion_completion_finalized profile_extractor, post_conversion_answer, booking_handler implicit; is_complete has four meanings
Email capture "Email known", stored five ways visitor_profile.email, dialog_supervision_state.email_captured, collected_values["email"], content_gating_captured, conversations.email_captured booking_handler, visitor_profiler, dialog_state_extractor; storage uses EmailCaptureTransition implicit above storage
Conversation mode default, qualifying, booking, form_assistant, post_conversion RoseChatState.conversation_mode utils/conversation_mode.py (pure) explicit type, but routing still reads the older flags
Intent to route VisitorIntent → NextAction → route intent_classification_state, intent_router_state, next_route determine_next_action, NEXT_ACTION_TO_ROUTE explicit
Background tasks started, awaited, cancelled; TaskOutcome Process-local stores Starter and awaiter nodes partial: only retrieval is cancelled on the redirect and booking paths

Integrations and admin API

Lifecycle States Stored in Transitions owned by Level
HubSpot inbox events (webhooks, email captures) pending, processing, processed, ignored, failed, plus a 15-minute claim hubspot.crm_hubspot_webhook_events, crm_hubspot_email_capture_events Claim: SQL RPC. The rest: ixhubspot/hubspot_store.py and two near-identical processors partial
HubSpot note and association reservations creating, created, failed Three hubspot.crm_hubspot_* tables Reserve: SQL RPC. Mark: direct updates in hubspot_store.py partial; the three reserve functions disagree
HubSpot connection connected, disconnected, error hubspot.crm_hubspot_connections.status OAuth routes; the contacts-sync job partial
HubSpot sync run queued, running, success, failed, mirrored in connections.last_sync_status hubspot.crm_hubspot_sync_runs API routes and jobs/hubspot_contacts_sync partial, two sources of truth
Agent registration unclaimed, code live, locked, claimed, delivered, revoked: all from nullable timestamps integrations.agent_registrations ixadmin_api/routes/agent_auth.py implicit
Job run rows queued, running, succeeded, failed geo.runs, integrations.r4a_surface_checks ixgeo/runs.py; jobs/r4a_surfaces_check explicit, except terminal writes
GEO FAQ proposal pending, accepted, rejected, superseded, unchanged geo.faq_proposals.status ixgeo/proposals.py, ixadmin_api/routes/geo.py partial; Python types only two of the five
GEO FAQ entry live, retired, legacy-disabled, human-edited geo.faqs booleans and timestamps ixadmin_api/routes/geo.py, ixgeo/translation.py implicit
GEO custom hostname Ten Stage values, derived Not stored _derive in ixgeo/custom_hostname.py explicit
MCP preview and apply A signed change token with an expiry and an expected updated_at The token ixrose_client/changes.py explicit
Identification webhooks pending, or one of claimed, sent, failed, retired Three *_webhook_sent_at timestamps on public.visitors ixdata/clients/identity_dispatch.py partial
Snitcher lookup pending, matched, no_match, expired integrations.snitcher_pending_lookups jobs/identity_sweep partial
Stripe subscription mirror Stripe's status, free text billing.client_billing.status config.apply_stripe_subscription; read through billing.client_is_stopped explicit owner, free-text values by design

Accounts and configuration

Lifecycle States Stored in Transitions owned by Level
Client type Eight enum values; former, enabled = false and client_is_stopped all mean "stopped" public.clients Direct writes from the backoffice and the CLI implicit
Domain status enabled, disabled, hidden. Display only: disabled and hidden hide the widget but still count conversions (tracking_only, IX-6285); chat, routing and the agent catalogue still treat them as off public.domains.status Direct writes from the backoffice (Edit clients › Domains); read by get_widget_config, resolve_site_route implicit
Workspace status draft, live, disabled public.sites.status Nothing: only live is ever written dead states
Experiment draft, running, completed experiments.experiments.status Start: public.start_experiment. Stop: a direct update from the backoffice partial
Day-1 setup progress Six booleans config.client_configs, slug onboarding useSetupProgress (frontend); merged server-side partial
Dataset run running, completed, cancelled, failed backoffice.dataset_runs The browser tab (client-backoffice/src/lib/datasetRunner.ts) partial

Widget (frontend/shared, frontend/widget)

Lifecycle States Stored in Transitions owned by Level
Display collapsed, expanded, minimized Three stores: widgetReducer, useServiceInitialization state (the one that renders), sessionStorage About twenty call sites in RoseWidget.tsx implicit
Send and stream idle, sending, thinking, streaming, failed widgetState.isLoading, streamingMessage, the last pair's answer, several refs RoseWidget.tsx, useStreamingMessage.ts, services/inboundx.ts implicit
Conversation and booking flow ANSWERING, BOOKING (with sub-states) conversationFlowReducer The reducer; orchestration in ExpandedChatView.tsx explicit reducer, implicit orchestration
Post-conversion not started, auto-opened, dismissed, complete sessionStorage and localStorage flags, a ref, the first pair's marker Effects in RoseWidget.tsx, DisplayController.tsx implicit
Display decision allowed, form factor, form assistant, post-conversion displayDecision in DisplayController.tsx Three writers with different rules partial
Boot idle, loading, ready, error for config; then analytics, then service configReducer; AnalyticsContext; useServiceInitialization The config stage is a reducer; the chain is effects partial
Readiness signal ready or not window.__InboundXWidgetReady, written by the widget manager and by RoseWidget Two owners implicit
Form detection (pending submission) idle, pending, detected, timed out Fields of DomObserverStrategy, NetworkObserverStrategy Each strategy class partial
Loader and self-heal not loaded, loaded, reloaded once Class fields and sessionStorage guards in widget/src/loader.ts, widget/src/main.tsx The loader and widget manager implicit
Consent mode pending, full, cookieless shared/src/services/consentMode.ts One setter, read through useSyncExternalStore explicit

Backoffice (frontend/client-backoffice)

Lifecycle States Stored in Transitions owned by Level
Knowledge training progress The seven operation statuses, a "starting" entry with no operation yet, legacy runs, and the bar face pending, running, idle, failed KnowledgeOperationProgressContext, RetrainProgressContext, useKnowledgeRetrain, module-level sets, localStorage Four layers of derivation; the "is active" test is re-derived in five more places implicit
Re-scan review screen Review status × scan operation status × apply operation status, plus local flags react-query cache and 17 useState in pages/WebsiteSyncingPage.tsx Handlers and a nine-arm notice ternary implicit
Sign-up, claim, welcome Seven gate screens; claiming, personalizing, activating, failed AuthGuard.tsx, WelcomeLoader.tsx, sessionStorage rose_welcome, router state Early returns and effects implicit
Config form clean, dirty, saving useEnhancedConfig ({current, saved, seed}); ConfigSection.tsx (refs and state) The hook is explicit; ConfigSection is not two engines
GEO hostname save Config saved, pointer synced Mutation callbacks in components/geo/GeoPublishCard.tsx Per-call onSuccess chain implicit
Workspace switch overlay switching or not WorkspaceContext.tsx (state, ref, global fetch count) One effect implicit
Document upload queue waiting, uploading, processing, added, failed services/documentUploadQueue.ts The queue explicit

Open hazards

Ranked by who is affected. Evidence: confirmed means the code path was read twice, by the audit and again when this page was written; audit means read once, so re-read before acting. None of these was reproduced against a running system.

Visitors and client CRMs

Lifecycle Hazard Evidence What a fix needs
Widget send The double-submit guard compares only the text, so a second identical message ("Yes", then "Yes") is dropped silently. isBusy already blocks real double sends. confirmed A widget change with mobile and desktop checks
Widget send A stream that has started is not cancelled by "New conversation": the read loop does not check the abort signal, and its last chunk puts the old session id back in memory. confirmed (code path) Abort wiring in services/inboundx.ts, with a stream test
Widget post-conversion On a post-conversion page, a conversation whose first question is not the welcome marker is wiped on every change. A visitor whose qualification is already complete cannot chat there. confirmed (code path) One explicit phase value; product decision on what a completed visitor sees
Widget display The public collapse / expand / minimize methods update the reducer and storage but not the store that renders. confirmed One owner for the two flags; see widget display state
Widget booking The reducer's isFormAssistant is fixed at mount while the prop follows SPA navigation; a booking can start on the backend and never on the frontend. "New conversation" does not reset the flow. audit Guards in conversationFlowReducer behind its tests
Booking flow Retry counters merge with max and booking_completed is sticky, so a second CTA click in the same session inherits both. The click handler's comment says "fresh". confirmed A product decision: should a second click start clean?
Booking flow "In booking" is is_booking_flow for some readers and is_booking_flow and pending_booking_fields for others; the redirected state never exits. audit One exported predicate; the widget already works around the stale state
Email capture The lead webhook is sent from a detached task on every turn; on redirect and post-conversion turns its result never reaches state, so the same email can be sent again. audit Compare-and-set on the stored capture, as EmailCaptureTransition does
HubSpot email captures If the task enqueue fails after the event row is inserted, the retry finds a duplicate and returns 202 without enqueueing. The row stays pending; nothing sweeps it. confirmed Enqueue on duplicate when no task was recorded, or a sweeper
HubSpot notes A note left in creating is never reserved again (only failed is), and readers treat it as done. confirmed A migration aligning the three reserve functions
HubSpot connection error has no repair path: reauthorize requires connected, webhooks are dropped, the job skips it. confirmed Let reauthorize accept error

Staff and backoffice users

Lifecycle Hazard Evidence What a fix needs
Config form (ConfigSection) The form resets whenever the resolved value changes identity, with no dirty check, so a background refetch discards unsaved edits. useEnhancedConfig has the rule that prevents it. confirmed Port the {current, saved, seed} rule; UI evidence
Knowledge training progress A tracked entry whose operation never loads stays "active" and is polled forever, which keeps every retrain button disabled until reload. confirmed (code path) A failure budget on the poll loop
Knowledge training progress Terminal side effects are split between the provider and a hook mounted on one page; a retrain that ends elsewhere leaves lists stale. audit One owner for the terminal transition
Re-scan review screen stale is never rendered; after a reload a stale review shows no card and no notice. audit A pure reviewPhase() function behind the page's 45 tests
Sign-up and claim A reload during the claim may submit it twice (router state survives reload). audit, not confirmed Tests for the gate first
GEO hostname save If the routing pointer fails after the config save, Save is disabled and nothing retries. audit One mutation with a retry button
Preparation run Cancel has no precondition: a completed or published run can be relabelled cancelled. Test environment only. confirmed A migration adding the status guard
Re-scan review Two of the four "blocking review" tests ignore an approved review whose apply failed, although the guide says it blocks source changes. audit One SQL helper
Client type Nothing in the database stops a retype to video, and delete_video_client cascades. Only a UI list prevents it. audit A trigger refusing the retype
Experiment running → completed is a direct browser update; for non-behavior experiments nothing forbids completed → running. audit An RPC for stop
Job run rows Terminal writes filter on the id only, so a run expired as stale can later flip failed → succeeded. confirmed AND status = 'running' on the terminal write
Agent registration The wrong-code counter is read-modify-write; parallel guesses under-count. The caller must be signed in as the matching email. confirmed An atomic increment (SQL function)
MCP apply Creating a document does not pass the change id, so a retried apply creates a duplicate. confirmed An id or idempotency key on the admin document create route
Dataset run Closing the tab leaves the row running forever. audit A stale sweep

Dead states and drift

Never written by any code: sites.status values draft and disabled; document_status values blocked and superseded; documents.kb_indexed and blocked_reason; crawl_run_mode value reprocess_from_snapshot; config.api_keys.revoked_at; the whole scraping schema; the RPC mark_crm_hubspot_note_deal_association; the flow states FORM_COLLECTING and REDIRECTING in conversationFlowReducer; ConversationMode values form_assistant and post_conversion (declared, no reader). Job runs say success in HubSpot and succeeded everywhere else.

Fixed

Ticket Lifecycle What changed
IX-6217 Intent to route A failed or skipped classification now writes an empty state. Before, the checkpoint supplied last turn's intent, which the router routed and counted again (a repeated hack count, a repeated redirect).
IX-6217 Post-conversion questionnaire Completion is delivered once per session (summary, HubSpot event, customer webhooks), and again only when a later message adds a value.
IX-6217 Form detection A second click on a submit button no longer leaves an orphan poll that cancels every later one (dom_observer), nor an expiry timer that closes the second click's window (network_observer).