import { ComponentType, ReactNode } from 'react'; import { SupabaseLike } from '@ai-matrx/data/db'; /** * EVERY registered entity token (the FK-valid set). Use this for any * `source_type` / `target_type` argument so an invalid token is a COMPILE error. */ type EntityTypeToken = "access_delta_probe" | "access_delta_run" | "access_request" | "access_shadow_log" | "access_version" | "access_version_event" | "account_addon" | "account_closure" | "account_facts" | "acquisition_block" | "activity" | "admin_audit_log" | "admin_email_log" | "admin_markdown_sample" | "admin_user" | "admin_user_owned_resources_cache" | "admission_config" | "agent" | "agent_card" | "agent_definition_version" | "agent_drift_alert" | "agent_exemplar" | "agent_mandate_note" | "agent_prompt_block" | "agent_prompt_block_variant" | "agent_prompt_remediation" | "agent_required_flag_change" | "agent_run" | "agent_run_stage" | "agent_schedule" | "agent_schedule_claim" | "agent_shortcut" | "agent_surface_binding" | "agent_template" | "agent_term_list" | "agent_test_result" | "agent_test_run" | "agent_usage" | "ai_api" | "ai_calls" | "ai_device_model_file" | "ai_device_model_root" | "ai_endpoint" | "ai_media_generation_cache" | "ai_model" | "ai_model_alias" | "ai_model_artifact" | "ai_model_candidate" | "ai_model_presentation" | "ai_model_upstream" | "ai_model_variant" | "ai_model_verification_run" | "ai_model_want" | "ai_offering" | "ai_person_model_want" | "ai_provider" | "ai_request_latency" | "ai_runtime" | "ai_runtime_build" | "ai_runtime_compat" | "ai_setting" | "ai_setting_profile" | "ai_translation_cell" | "ai_usage_execution_facts" | "ai_usage_executions" | "ai_usage_hourly" | "ai_usage_hourly_watermark" | "analysis_result" | "anon_form" | "anon_form_password" | "anon_form_visit" | "anon_function_birth_grandfather" | "anon_hit" | "anon_inbound" | "anon_replay" | "anon_submission" | "anon_token" | "api_field_warning" | "api_request_log" | "app" | "app_config" | "app_config_history" | "app_definition_version" | "app_error" | "app_execution" | "app_instance" | "app_log" | "app_log_hourly" | "app_log_hourly_watermark" | "app_log_lines" | "app_log_muted_pattern" | "app_log_norm_exception" | "app_log_requests_hourly" | "app_rate_limit" | "app_setting" | "app_sync_status" | "applet_visitor_binding" | "approach" | "artifact" | "assessment" | "assessment_item" | "assessment_result" | "assignment_session" | "assist" | "assist_producer_policy" | "assist_producer_policy_history" | "association_type" | "assurance_level" | "attempt" | "attention_audience_rule" | "attention_audit" | "attention_item_state" | "attention_showing" | "audit_broken_functions" | "audit_canonical_findings" | "audit_exemption" | "audit_function_deps" | "audit_function_runtime_probe" | "audit_m2m_candidates" | "audit_refresh_log" | "audit_stale_registry" | "audit_unregistered_candidates" | "automation_delivery" | "automation_fired" | "base_entity_template" | "batch_cost_event" | "batch_provider_batch" | "batch_work_item" | "billing_capability" | "billing_capability_limit" | "billing_ci_package_build" | "billing_connect_account" | "billing_coupon" | "billing_coupon_redemption" | "billing_customer" | "billing_external_call_vendor" | "billing_free_network_counter" | "billing_free_period_grant" | "billing_free_use_counter" | "billing_hard_cost_reconciliation" | "billing_held_run" | "billing_org_payment_account" | "billing_payment" | "billing_payment_ask" | "billing_plan" | "billing_plan_limit" | "billing_price" | "billing_product" | "billing_provider_balance_snapshot" | "billing_spend_alarm" | "billing_spend_alarm_occurrence" | "billing_spend_approval" | "billing_spend_guardrail" | "billing_spend_hold" | "billing_stripe_event" | "billing_subscription" | "billing_usage_ledger" | "billing_usage_reset" | "billing_user_plan" | "block_state" | "board" | "browser_account_binding" | "browser_action_event" | "browser_authenticator_window" | "browser_capture" | "browser_control_request" | "browser_handoff" | "browser_login_attempt" | "browser_login_recipe" | "browser_profile" | "browser_profile_checkpoint" | "browser_run" | "browser_site_observation" | "browser_site_policy" | "browser_stream_ticket" | "build_lock" | "calendar_event" | "campaign_watch_ramp_gate_run" | "campaign_watch_switch_outbox" | "campaign_watch_switch_window" | "canvas_comment" | "canvas_comment_like" | "canvas_item" | "canvas_item_state" | "canvas_like" | "canvas_score" | "canvas_view" | "capture_window" | "carrying_rule" | "catalog_entries_history" | "catalog_entry" | "category" | "change_item" | "change_job" | "change_job_row" | "change_plan" | "change_type_default" | "change_work" | "chat_user_usage_summary" | "citations" | "class_purchase" | "classifier_revision_ledger" | "client_callable_door" | "client_callable_door_retirement" | "client_excluded_column_unregistered" | "cmp_entry" | "cmp_feedback" | "code_file" | "code_folder" | "code_repository" | "coding_session" | "coding_session_entry" | "collab_checkpoint" | "collab_op" | "collab_room" | "comment" | "commerce_asset_allocation" | "commerce_asset_grading" | "commerce_asset_identifier" | "commerce_asset_lot_event" | "commerce_asset_mandate_result" | "commerce_asset_price_factor" | "commerce_asset_reshoot_request" | "commerce_asset_review" | "commerce_asset_unknown" | "commerce_certified_printer" | "commerce_cloud_sync_connection" | "commerce_ebay_business_policy" | "commerce_ebay_category" | "commerce_ebay_category_aspect" | "commerce_ebay_category_tree" | "commerce_ebay_custom_policy" | "commerce_ebay_inventory_item" | "commerce_ebay_inventory_item_group" | "commerce_ebay_inventory_item_group_member" | "commerce_ebay_inventory_location" | "commerce_ebay_listing" | "commerce_ebay_marketplace_policy" | "commerce_ebay_media_asset" | "commerce_ebay_notification_destination" | "commerce_ebay_notification_event" | "commerce_ebay_notification_subscription" | "commerce_ebay_notification_topic" | "commerce_ebay_offer" | "commerce_ebay_order" | "commerce_ebay_order_line_item" | "commerce_ebay_shipping_fulfillment" | "commerce_ebay_store_category" | "commerce_human_correction" | "commerce_intake_artifact" | "commerce_intake_asset" | "commerce_intake_batch" | "commerce_label_batch" | "commerce_label_code" | "commerce_marketplace_account" | "commerce_marketplace_account_deletion_audit" | "commerce_marketplace_api_call" | "commerce_marketplace_rate_budget" | "commerce_marketplace_site" | "commerce_marketplace_sync_run" | "commerce_prediction_outcome" | "commerce_print_order" | "commerce_product" | "commerce_product_channel_ref" | "commerce_product_media" | "commerce_product_variant" | "commerce_recall_audit" | "communication_calendar_selected_snapshot_state" | "communication_channel_readiness" | "comparison_set" | "computed_org_mark" | "computed_reader_cols" | "computed_reader_judgement" | "config_manifest" | "config_read_bucket" | "contact_medium" | "contact_submission" | "content_certification" | "content_ir_converter_definition" | "content_ir_converter_run" | "content_ir_kind" | "content_ir_kind_component" | "content_ir_kind_component_incident" | "content_ir_kind_component_layer" | "content_ir_kind_conformance" | "content_ir_kind_edge" | "content_ir_kind_example" | "content_ir_kind_instance" | "content_ir_kind_surface" | "content_ir_render_inspection" | "content_lane" | "context_access_log" | "context_item" | "context_item_suggestion" | "conversation" | "conversation_value" | "courts" | "credential_attachment" | "credential_item" | "credential_mutation_receipt" | "crm_address" | "crm_affiliation" | "crm_blocklist_entry" | "crm_contact_candidate" | "crm_deal" | "crm_deal_stage_event" | "crm_enrichment_call" | "crm_interaction" | "crm_merge_candidate" | "crm_outreach_list" | "crm_outreach_list_member" | "crm_party_merge" | "crm_party_research" | "crm_registry_ingest_run" | "crm_registry_source" | "crm_sending_claim" | "crm_sending_event" | "crm_sending_identity" | "crm_sending_identity_check" | "crm_sending_policy" | "custom_agent_table_origin" | "custom_agent_table_trust" | "custom_agg_digest_checked" | "custom_anon_form_draft" | "custom_base" | "custom_base_snapshot" | "custom_field_definition" | "custom_field_target" | "custom_inbox_item_state" | "custom_io_outbox_consumer" | "custom_io_outbox_consumption" | "custom_portal" | "custom_portal_principal" | "custom_portal_table" | "custom_share_tails_mine_repair" | "custom_synced_source" | "custom_template" | "custom_template_install" | "custom_whole_value_parked" | "cx_agent_memory" | "cx_agent_plan" | "cx_agent_task" | "cx_code_edit" | "cx_code_message_file" | "cx_media" | "cx_observational_memory" | "cx_observational_memory_event" | "cx_pending_injection" | "cx_request" | "cx_request_snapshot" | "cx_request_values" | "cx_tool_trace" | "cx_user_request" | "cx_user_todo" | "data_rights_event" | "data_store" | "data_store_members" | "ddl_guard_log" | "deck_suggestion" | "definer_class_exemption" | "definer_client_grant_grandfather" | "definer_grant_baseline" | "deprecated_relation" | "derive_run" | "desktop_app_account" | "desktop_app_instance" | "desktop_app_profile" | "dev_login_audit" | "device_handoff" | "dict_entry" | "dict_provider_publication" | "dict_setting" | "dm_conversation" | "dm_message" | "dm_participant" | "dm_session_member" | "doc_render" | "doc_signature" | "dockets" | "document" | "document_version" | "domain_classification" | "edge_payload_kind" | "egress_device" | "egress_pairing" | "egress_ticket" | "emails" | "embedding_cache" | "embeddings_google_gemini_2_1536" | "embeddings_oai_3_small_1536" | "embeddings_voyage_4_large_1024" | "embeddings_voyage_code_3_1024" | "endpoint_family_sweep_state" | "engine_owner_task" | "entity_grant" | "entity_protected_value" | "entity_protected_value_version" | "entity_relationship" | "entity_type" | "esign_campaign" | "esign_campaign_member" | "esign_consent_disclosure" | "esign_envelope" | "esign_envelope_certificate" | "esign_envelope_document" | "esign_envelope_draft" | "esign_envelope_event" | "esign_envelope_external_ref" | "esign_envelope_signer" | "esign_provider" | "esign_provider_binding" | "esign_saved_signature" | "esign_signing_key" | "esign_template" | "execution_event_cursor" | "extension_auth_code" | "external_api_reservation" | "external_conversation" | "external_delivery_event" | "external_inbox" | "external_link" | "external_message" | "external_provider_receipt" | "external_source" | "extract_sweep_state" | "fc_card" | "fc_detail" | "fc_set" | "feature_doc" | "feature_knob" | "feedback_comments" | "feedback_user_messages" | "file" | "file_analysis" | "file_entities" | "file_overrides" | "file_page_annotations" | "file_pages" | "file_rag_job" | "file_template" | "file_version" | "files_account_tier" | "files_machine_written_prefix" | "files_sync_mapping" | "files_user_account" | "folder" | "function_contract" | "game_badge" | "game_result" | "game_room" | "global_execution" | "global_execution_checkpoint" | "global_execution_control" | "global_execution_event" | "global_meter_entry" | "global_origin" | "global_request" | "google_document" | "growth_loop_event" | "growth_loop_run" | "growth_loop_stage_run" | "guardian_link" | "guest_conversion_audit" | "guest_execution_log" | "guest_executions" | "guided_checklist_run" | "heatmap_save" | "hindsight_enrollment" | "hindsight_finding" | "hindsight_regression_case" | "hindsight_replay" | "hindsight_replay_step" | "hindsight_review" | "hr_access_audit" | "hr_access_role" | "hr_accommodation_request" | "hr_ai_evidence" | "hr_alert_routing_rule" | "hr_application" | "hr_approval_authority" | "hr_approval_delegation" | "hr_asset" | "hr_asset_assignment" | "hr_attendance_exception" | "hr_auto_close_rule" | "hr_availability" | "hr_background_check" | "hr_benefits_event" | "hr_calculation_snapshot" | "hr_candidate" | "hr_candidate_conversion" | "hr_candidate_message" | "hr_careers_portal" | "hr_checklist_item" | "hr_checklist_run" | "hr_checklist_template" | "hr_checklist_template_item" | "hr_compensation" | "hr_corrective_action" | "hr_course" | "hr_course_version" | "hr_credential" | "hr_crew" | "hr_deduction_code" | "hr_department" | "hr_derived_grant" | "hr_disposition_event" | "hr_earning_code" | "hr_eeo_response" | "hr_emergency_contact" | "hr_employee" | "hr_employee_private" | "hr_employer_profile" | "hr_employment" | "hr_employment_pin" | "hr_engagement" | "hr_establishment" | "hr_external_identity" | "hr_field_policy" | "hr_goal" | "hr_holiday" | "hr_holiday_calendar" | "hr_i9" | "hr_i9_document" | "hr_incident" | "hr_incident_party" | "hr_interview" | "hr_interview_kit" | "hr_job_title" | "hr_jurisdiction" | "hr_jurisdiction_rule" | "hr_jurisdiction_rule_class" | "hr_jurisdiction_rule_org_decision" | "hr_jurisdiction_rule_test" | "hr_kiosk_device" | "hr_kiosk_session" | "hr_labor_target" | "hr_leave_case" | "hr_leave_enrollment" | "hr_leave_ledger" | "hr_leave_policy" | "hr_leave_request" | "hr_legal_hold" | "hr_legal_hold_item" | "hr_location" | "hr_new_hire_report" | "hr_offer" | "hr_opening" | "hr_overtime_alert" | "hr_overtime_alert_rule" | "hr_overtime_preapproval" | "hr_pay_group" | "hr_pay_period" | "hr_pay_period_employment" | "hr_payroll_export" | "hr_payroll_export_line" | "hr_position_assignment" | "hr_posting" | "hr_posting_publication" | "hr_provider_binding" | "hr_provider_event" | "hr_provisioning_result" | "hr_punch" | "hr_recalculation_batch" | "hr_record_class" | "hr_records_request" | "hr_reference_check" | "hr_reporting_line" | "hr_requisition" | "hr_restricted_note" | "hr_retention_rule" | "hr_review" | "hr_review_cycle" | "hr_review_peer_nomination" | "hr_review_response" | "hr_review_template" | "hr_role_assignment" | "hr_schedule" | "hr_schedule_change" | "hr_schedule_guidance" | "hr_schedule_template" | "hr_schedule_template_shift" | "hr_scorecard" | "hr_separation" | "hr_shift" | "hr_shift_claim" | "hr_staffing_requirement" | "hr_survey" | "hr_survey_invitation" | "hr_survey_question" | "hr_survey_response" | "hr_tax_registration" | "hr_tax_withholding" | "hr_time_adjustment" | "hr_training_assignment" | "hr_training_attempt" | "hr_transcript_entry" | "hr_verification_letter_request" | "hr_work_interval" | "hr_workflow_binding" | "hr_workflow_decision" | "hr_workflow_definition" | "hr_workflow_event" | "hr_workflow_failure" | "hr_workflow_flow_type" | "hr_workflow_instance" | "hr_workflow_step" | "hr_workflow_step_definition" | "hr_workweek" | "html_extraction" | "iam_access_audit" | "iam_access_setup" | "iam_api_key" | "iam_emergency_door_request" | "iam_oauth_app" | "iam_org_availability_key" | "iam_org_domain" | "iam_org_domain_route" | "iam_publish_binding" | "iam_publisher_verification" | "iam_read_lane_v2_rollout" | "iam_record_seat_change" | "iam_sign_in_event" | "iam_world_namespace" | "iam_world_publish_admission" | "idempotency" | "industry" | "industry_curator" | "infra_status" | "ingest_runs" | "integration_connection" | "integration_connection_resource" | "interview_decision_interview" | "interview_decision_question" | "interview_document_revision" | "interview_hole" | "interview_question" | "interview_session" | "interview_turn" | "invitation" | "invitation_code" | "invitation_request" | "io_comment" | "io_contract" | "io_import" | "io_outbox" | "item" | "item_mastery" | "judge_verdict" | "jurisdiction_policy" | "keyword_classification_queue" | "kg_alert" | "kg_chunk_entities" | "kg_chunks" | "kg_clusters" | "kg_edges" | "kg_entities" | "kg_entity_aliases" | "kg_suggestion_ack" | "kg_sweep_queue" | "kg_sweep_run" | "kg_sweep_state" | "kg_value_match" | "knob_override" | "knob_override_audit" | "knob_rung_lock" | "knob_scope_kind" | "knob_write_door" | "league_membership" | "learn_doc" | "library_doc" | "lifecycle_archive" | "lifecycle_archive_row" | "lifecycle_audit" | "lifecycle_entity_plan" | "lifecycle_map_build" | "lifecycle_reference_map" | "lifecycle_run" | "lifecycle_tier_ledger" | "location" | "mandate" | "mandate_advance_batch_row" | "mandate_binding" | "mandate_candidate" | "mandate_candidate_run" | "mandate_candidate_run_payload" | "mandate_goal_clauses" | "mandate_observation" | "mandate_proposal" | "mandate_readiness_verdict" | "mandate_reference" | "mandate_scan" | "mandate_treatment" | "marketing_initiative" | "masterwork_corpus_item" | "masterwork_run" | "masterwork_run_kind" | "masterwork_source" | "math_course_structure" | "math_problem" | "matrx_action_ledger" | "mcp_config" | "mcp_server" | "mcp_user_conn" | "media_capture_handoff" | "media_catalog_setting" | "media_library_item" | "media_selection_item" | "media_selection_job" | "media_source_library" | "meet_call_invite" | "meet_chat_message" | "meet_connection" | "meet_invitee" | "meet_meeting" | "meet_note" | "meet_occurrence_override" | "meet_participant" | "meet_recording" | "meet_session" | "meet_transcript_segment" | "membership" | "membership_grant" | "memory_trial" | "memory_trial_step" | "merge_field_provenance" | "message" | "message_template" | "message_template_detail" | "meta_excluded_schema" | "meta_table_stats_history" | "metadata_reserved_keys" | "migration_log" | "mtx_media_heal_queue" | "mtx_public_url_guard" | "ner_shadow" | "note" | "notification" | "notification_channel_preference" | "notification_event_override" | "notification_event_type" | "notification_preference" | "notification_submission" | "notify_outsider_door_baseline" | "oauth_handoff_claim" | "opinion_clusters" | "opinions" | "ops_auth_lock_watchdog_log" | "ops_check_item" | "ops_check_run" | "ops_db_host_sample" | "ops_issue_class" | "ops_issue_event" | "ops_perf_client_event" | "ops_perf_sample" | "ops_perf_statement_snapshot" | "ops_proof_check" | "ops_proof_run" | "ops_proof_scenario" | "ops_source_read_cache" | "ops_test_replay_cache" | "org_admin_audit" | "org_change_policy" | "org_chart_publication" | "org_context_ledger" | "org_industries" | "org_member_control" | "org_module_config" | "org_move_txn" | "org_plan" | "org_sweep_list" | "organization" | "organization_preferences" | "organization_visibility_version" | "output_feedback" | "outreach_acceptance" | "page_extraction_job" | "page_extraction_page_run" | "page_extraction_results" | "page_extraction_runs" | "page_intent_queue" | "page_mapping_queue" | "page_vitals" | "part_config" | "part_config_sub" | "party" | "party_contact_point" | "passkey_credential" | "pc_article" | "pc_episode" | "pc_show" | "pc_studio_run" | "pc_studio_run_asset" | "pdf_consolidation_log" | "pdf_redaction_audit" | "pdf_redaction_key_escrow" | "permission_grant" | "personal_data_column" | "plan_cms_fill_item" | "plan_cms_fill_job" | "plan_entity" | "plan_node" | "plan_node_artifact" | "plan_node_step" | "plan_profile" | "platform_action_request" | "platform_actor_session" | "platform_actor_token" | "platform_actor_token_event" | "platform_class_approval_by_arman" | "platform_class_approval_by_org_admin" | "platform_continued_access" | "platform_cutover_census_run" | "platform_cutover_evaluation_replaced" | "platform_cutover_evaluation_write" | "platform_cutover_seam" | "platform_cutover_seam_measure" | "platform_cutover_seam_press" | "platform_dated_change" | "platform_doors_only_pending_cutover" | "platform_google_calendar_event_create_intent" | "platform_google_task_create_intent" | "platform_hidden_item" | "platform_kernel_fingerprint_record" | "platform_outcome_event" | "platform_outsider_consumer" | "platform_provision_base_contract_pending" | "platform_reachability" | "platform_reachability_rebuild_pending" | "platform_realtime_topic_prefix" | "platform_reference_category" | "platform_reference_declaration" | "platform_repo" | "platform_saved_view" | "platform_schema" | "platform_secure_delivery" | "platform_share_link" | "platform_strict_class_probe" | "podcast_race" | "position" | "presentation" | "processed_document" | "processed_document_page" | "product_capture_file" | "product_capture_item" | "product_capture_payload" | "product_capture_product" | "product_capture_question" | "project" | "provider_account" | "provider_account_credential" | "provision" | "provision_generate_target" | "provision_grant" | "provision_marker" | "provision_rule_message" | "provision_schema" | "provision_shape_debt" | "provision_snapshot" | "provision_spec" | "provision_spec_grandfather" | "provision_vocabulary" | "public_compat_wrapper" | "public_placement_baseline" | "public_placement_census" | "public_placement_domain" | "public_restore_permit" | "purpose" | "quiz_session" | "rag_ingest_run" | "rag_library_audit_log" | "rate_limit_buckets" | "reachability_pending" | "read_mask_kept" | "recompute_queue" | "record" | "record_alias" | "record_computed" | "record_follow" | "redaction_mapping" | "relationship_rule" | "research_analysis" | "research_content" | "research_context_bundle" | "research_document" | "research_intent" | "research_keyword" | "research_media" | "research_source" | "research_synthesis" | "research_tag" | "research_template" | "research_topic" | "retention_policy" | "retrieval_audit" | "review_queue" | "route_manifest_entry" | "row_version" | "rulebook" | "run_approval" | "run_approval_event" | "runtime_operation_stream" | "runtime_operation_stream_batch" | "sandbox_instance" | "sch_agent_task" | "sch_run" | "sch_task" | "sch_trigger" | "scheduler_automation_run_subject" | "schema_client_exposure" | "schema_migration_ledger" | "schema_migration_legacy" | "schema_migration_slot_grandfather" | "schema_templates" | "scope" | "scope_association_suggestion" | "scope_door_registry" | "scope_item_value_suggestion" | "scope_suggestion" | "scope_type" | "scrape_domain" | "scrape_domain_settings" | "scrape_failure_log" | "scrape_parsed_page" | "scrape_path_override" | "scrape_path_pattern" | "scrape_retry_queue" | "scraper_comparison_run" | "scraper_data_fetch_job" | "scraper_data_fetch_job_row" | "scraper_data_source" | "search_item" | "seo_ai_capability" | "seo_ai_visibility_brand_check" | "seo_ai_visibility_citation" | "seo_ai_visibility_claim" | "seo_ai_visibility_design_artifact" | "seo_ai_visibility_panel" | "seo_ai_visibility_panel_version" | "seo_ai_visibility_response" | "seo_ai_visibility_signal" | "seo_backlink" | "seo_backlink_change_event" | "seo_backlink_dimension_snapshot" | "seo_backlink_observation" | "seo_backlink_snapshot" | "seo_change_assessment" | "seo_change_event" | "seo_change_item" | "seo_change_metric" | "seo_change_set" | "seo_change_theory" | "seo_collection_run" | "seo_competitor" | "seo_competitor_observation" | "seo_competitor_opportunity" | "seo_coverage_mention" | "seo_coverage_tracker" | "seo_dimension_value_matcher" | "seo_engine_schedule" | "seo_geo_place" | "seo_gsc_dig_rule" | "seo_keyword" | "seo_keyword_class_rule" | "seo_keyword_edge" | "seo_keyword_facet" | "seo_keyword_market" | "seo_keyword_market_observation" | "seo_keyword_place" | "seo_keyword_saved_view" | "seo_keyword_topic" | "seo_landscape_brief" | "seo_link_gap_domain" | "seo_link_gap_match" | "seo_map_facet" | "seo_map_facet_value" | "seo_map_topic" | "seo_page_measurement_health" | "seo_page_performance" | "seo_pr_moment" | "seo_provider_call" | "seo_provider_task" | "seo_rank_observation" | "seo_rank_target" | "seo_raw_payload" | "seo_referring_domain_profile" | "seo_reputation_case" | "seo_search_performance_daily" | "seo_serp_mention" | "seo_serp_opportunity" | "seo_serp_result" | "seo_serp_snapshot" | "seo_site_geo_area" | "seo_site_keyword_offering" | "seo_site_keyword_value" | "seo_site_offering_value" | "seo_site_topic_value" | "seo_site_value_combo" | "seo_site_value_worth" | "seo_site_vocabulary" | "seo_source_request" | "seo_starter_pack" | "seo_starter_pack_item" | "seo_story_angle" | "seo_topic" | "seo_topical_map" | "seo_tracker_story" | "seo_web_analytics_daily" | "share_link_password" | "shareable_resource_registry" | "shared_canvas_item" | "short_link" | "sign_in_fk_legacy" | "skill" | "skill_detail" | "sms_consent" | "sms_conversation" | "sms_message" | "sms_message_media" | "sms_notification" | "sms_notification_preference" | "sms_phone_number" | "sms_rate_limits" | "sms_webhook_logs" | "social_account_insight_daily" | "social_ad" | "social_captured_post" | "social_kpi_goal" | "social_own_post_metric" | "social_post" | "social_post_analysis" | "social_post_comment" | "social_post_metric_snapshot" | "social_post_stat" | "social_post_transcript" | "social_profile" | "social_profile_snapshot" | "social_remix_output" | "social_swipe_collection" | "social_tracked_account" | "social_video_composition_version" | "social_video_project" | "social_video_variant" | "social_watchlist_hit" | "soft_delete_cascade_job" | "soft_delete_edge" | "source_authority" | "space_payload" | "stage_ref_kind" | "stamped_write_table" | "structure" | "studio_cleaned_segments" | "studio_concept_items" | "studio_documents" | "studio_module_segments" | "studio_raw_segments" | "studio_recording_chunks" | "studio_recording_segments" | "studio_run" | "studio_session" | "studio_session_settings" | "study_attempt" | "study_goal" | "study_media" | "study_plan" | "study_plan_block" | "study_plan_day" | "study_reminder_context" | "study_reminder_delivery" | "study_session" | "study_source_chunk" | "study_streak" | "study_structured_section" | "superseded_policy" | "support_session" | "support_session_event" | "surface" | "system_announcement" | "system_context_item" | "system_context_item_org_value" | "system_error" | "system_orgs" | "system_write_failure" | "t13_backfill_ledger" | "t13_default_ledger" | "t13_row_column_events" | "tag" | "task" | "task_user_state" | "taxonomy_node" | "team" | "template_context_items" | "template_scope_types" | "templates" | "test_handset_inbox" | "test_handset_verification" | "thread" | "tool" | "tool_battle" | "tool_battle_cell" | "tool_binding" | "tool_bundle" | "tool_call" | "tool_call_facts" | "tool_canary_run" | "tool_catalog_cache" | "tool_catalog_call" | "tool_catalog_call_attempt" | "tool_catalog_call_detail" | "tool_catalog_endpoint" | "tool_catalog_entry" | "tool_catalog_provider" | "tool_definition_version" | "tool_executor" | "tool_feature_scorecard" | "tool_surface_defaults" | "tool_test_sample" | "tool_ui" | "tool_ui_incident" | "tool_ui_version" | "topic_placement_queue" | "transcript" | "trigger_event" | "udt_document" | "udt_document_snapshot" | "udt_workbook_snapshot" | "ui_client" | "ui_decision_pick" | "ui_surface_action" | "ui_surface_agent_pref" | "ui_surface_agent_role" | "ui_surface_client_tool" | "ui_surface_config" | "ui_surface_item_type" | "ui_surface_value" | "ui_surface_write_target" | "univer_payload" | "unsubscribe_token" | "uploads_inflight" | "user" | "user_achievement" | "user_acquisition_facts" | "user_acquisition_facts_stored" | "user_acquisition_facts_stored_watermark" | "user_active_context" | "user_analysis_preference" | "user_email_preference" | "user_entity_state" | "user_feedback" | "user_follows" | "user_form_profile" | "user_markdown_sample" | "user_memory" | "user_preference" | "user_profile" | "user_secret" | "user_secret_audit" | "user_secret_grant" | "user_stat" | "user_storage_usage" | "user_surface_state" | "users_calendar_feed" | "vault_fill_approvals" | "vault_fill_devices" | "vault_fill_nonces" | "visibility_cache" | "visibility_epoch" | "voice" | "war_room" | "wbx_demo" | "wbx_guidance" | "wbx_highlight" | "wbx_pattern" | "wbx_recipe" | "wbx_screenshot" | "wbx_seo_audit" | "wc_claim" | "wc_impairment_definition" | "wc_injury" | "wc_report" | "web_analysis_item" | "web_brand" | "web_brand_asset" | "web_brand_choice" | "web_brand_exclusion" | "web_brand_offering" | "web_brand_persona" | "web_brand_relation_kind" | "web_brand_review" | "web_brand_testimony" | "web_business_fact" | "web_business_location" | "web_channel_analytics_daily" | "web_crawl_event" | "web_crawl_preset" | "web_crawl_schedule" | "web_crawl_session" | "web_crawl_url" | "web_discovered_item" | "web_domain_category" | "web_domain_category_observation" | "web_finding" | "web_gsc_page_stat" | "web_link_edge" | "web_listing_publisher" | "web_location_listing" | "web_news_item" | "web_offering_template" | "web_page" | "web_page_content" | "web_page_evidence" | "web_page_sitemap" | "web_property" | "web_provider" | "web_result" | "web_screenshot" | "web_search_review" | "web_site" | "web_site_endpoint_rule" | "web_site_item_config" | "web_site_offering" | "web_sitemap" | "web_snapshot" | "web_tag_manager_snapshot" | "web_temp_brand_firmographic" | "web_temp_brand_presence" | "web_temp_brand_recognition" | "web_voice_fingerprint" | "web_youtube_video" | "webhook_deliveries" | "webhook_dispatch_state" | "webhook_test_receipt" | "webhooks" | "wf_node_data_slot" | "work_claim" | "work_item" | "workbook" | "worker_heartbeat" | "workflow" | "workflow_card" | "workflow_checkpoint" | "workflow_checkpoint_value" | "workflow_comparison" | "workflow_definition_overview" | "workflow_definition_version" | "workflow_idempotency" | "workflow_job" | "workflow_node_events" | "workflow_node_outcome" | "workflow_plan" | "workflow_plan_event" | "workflow_plan_sample" | "workflow_recovery_audit" | "workflow_review_issue" | "workflow_run" | "workflow_run_cost" | "workflow_run_facts" | "workflow_run_log" | "workflow_runtime_surface" | "workflow_step_facts" | "workflow_step_result" | "workflow_template" | "workflow_trigger" | "workflow_trigger_fire" | "workflow_work_item" | "write_guard_key" | "youtube_quota_day" | "youtube_search" | "youtube_video"; /** * The data seam β€” a structural subset of `SupabaseClient`: any * client that can answer the demanded RPC families (README Β§ The demanded * schema). The package IS data operations; there is no degraded mode without * one. `PromiseLike` because supabase-js returns a thenable builder, not a * `Promise`. * * 🚨 SINCE 0.14.0 THE PORT IS THE HOST'S SUPABASE CLIENT ITSELF (`@ai-matrx/data`'s structural * `SupabaseLike`: `schema(name).rpc(...)`). Every call goes through data's generated * function doors (`src/db/public.ts`); the four edge lists are read COMPLETE (paged by * the package β€” a host no longer pages them). Pass `supabase`, not an `{ rpc }` wrapper. * * 🚨 RPC AND NOTHING ELSE (DOORS-ONLY-4, 2026-09-21). This port used to carry * OPTIONAL `from`/`schema` table surfaces, used by exactly one service β€” * entity-row create/rename, which wrote the registered entity's backing table * directly. The doors-only ruling (`platform` and `iam` are not client-writable; * every write goes through a named SECURITY DEFINER door) made that path answer * `42501` on every closed table, so it now calls `entity_row_create` / * `entity_row_rename` like every other operation. With its one reader gone the * two optional members were a port nobody reads β€” removed rather than left as a * seam a future write could quietly reach for. */ type AssociationsDataSource = SupabaseLike; /** * An `{ rpc }`-only client (a host bridge that forwards public-schema function calls, the shape * every host passed before 0.14.0). ACCEPTED AGAIN since 0.14.5: 0.14.0 refused it at * construction and every agent-catalog host with a bridge crashed ("the REQUIRED dataSource port * is missing"). The store adapts it β€” `schema("public").rpc` is its `rpc` β€” so a caller cannot hit * that crash. Every function this package calls is a `public` one (`src/db/public.ts`); any other * schema, or a table read, is refused ALOUD by the adapter, never answered silently. */ interface AssociationsRpcOnlyDataSource { rpc(fn: string, args?: Record, opts?: { count?: "exact" | "planned" | "estimated"; }): PromiseLike; } /** * The identity seam β€” today a store-singleton read (`requireUserId`) plus the * org resolver `CategoryTagPicker` uses for created rows. `requireUserId` * failures stay LOUD (`Not authenticated`) β€” never silently anonymous. */ interface AssociationsIdentity { requireUserId(): string; /** Org for created rows/edges (the CategoryTagPicker create path). */ ensureOrgId?(): Promise; /** * Whether the client's database session is attached right now. A 42501 * "permission denied for function" from a demanded door means the request * went out anonymous (an ended or expired session) β€” UNLESS the session is * attached, when it is a real grant gap. Absent β†’ treated as not attached. */ sessionAttached?(): boolean; } /** * The scream seam. Every degraded path, every `demanded_schema_violation`, * every create-then-attach partial failure reports here regardless of * notifier availability. * * DEFAULT (0.6.0, C23): absent β†’ `createDefaultErrorSink()` β€” a tagged * `console.error` per event that announces ONCE that no sink is bound and * names the remedy. A host with a diagnostics surface binds its own. */ type ErrorSink = (event: { code: string; message: string; context?: object; }) => void; /** * Per-token host overlay β€” the code-native values the DB registry cannot * carry (today: the 804-line ENTITY_OVERLAY literal in matrx-frontend's * entityRegistry). EVERY field optional; absence degrades per field: * convention columns, default icon, `${label}s`, no door, generic * titleColumn candidate read. A `reference_pickable` token with no title * column and no override is screamed to the errorSink, never shown broken. */ interface EntityOverlayEntry { /** Icon component (host-supplied; packages never depend on an icon library). */ /** A component, never a bare ElementType: the app compiling this source may carry global JSX elements (react-three-fiber) that make a bare ElementType's props `never` (2026-10-22). */ Icon?: ComponentType<{ className?: string; }>; /** Plural label; default `${label}s`. */ labelPlural?: string; /** Owner column override; default the "created_by" convention. */ ownerColumn?: string | null; /** Org column override; default the "organization_id" convention. */ orgColumn?: string | null; /** Route for this token's rows; absent β†’ no open door (label renders plain). */ hrefFor?: (id: string) => string; /** * Candidate-list override for tokens whose backing table can't be read * client-side (e.g. `data_store` β€” rag.* is not PostgREST-exposed); * absent β†’ the generic `reference_search_candidates` titleColumn read. */ listCandidates?: (args: { search?: string; limit?: number; }) => Promise<{ ok: true; data: { id: string; title: string; }[]; } | { ok: false; error: string; }>; } /** The overlay registration map β€” bound per host, merged over the generated registry. */ type EntityOverlayMap = Partial>; /** * The user-notification seam (today: `@/lib/toast` in 6 components). * Optional β€” /react warns once when absent. Every user-facing failure ALSO * routes to the errorSink + the component's inline error state, so the * create-then-associate loud-outcome law is satisfied structurally, not by * toast availability. */ interface AssociationsNotifier { success(msg: string): void; error(msg: string, opts?: { description?: string; action?: { label: string; onClick(): void; }; }): void; } /** * The window seam. * * DEFAULT (0.6.0, C23): absent β†’ `DefaultWindowShell`, the package's OWN * window β€” draggable, resizable, maximizable, viewport-clamped, portalled, * non-modal, mobile bottom-card. Not a degradation; the shipped default. * A host binds this port only when its own window MANAGER (tray docking, * workspace persistence, cross-window z-order) must own the surface. */ interface WindowShellPort { Window: ComponentType<{ id: string; title: string; onClose(): void; children: ReactNode; }>; } /** Options for {@link CapturePort.requestUpload} (measured: uploadGuardOpeners). */ interface CaptureUploadOpts { files: File[]; /** Logical cloud-files folder new uploads land in (auto-created). */ folderPath: string; /** Publish the uploads to the web (the only anonymous lane; access ladder T-13). */ publishedToWeb?: boolean; /** The "Shown to" list filter stamped on uploads (`only_me` Β· `my_team` Β· `everyone` Β· `everyone_on_ai_matrx`). */ shownTo?: CaptureShownTo; /** The retiring level word, derived from the two words above for hosts not yet on them. */ visibility?: string; } /** `platform.shown_to`: a list filter, never row security. */ type CaptureShownTo = "only_me" | "my_team" | "everyone" | "everyone_on_ai_matrx"; /** Honest outcome of a host upload β€” created-but-unlinked must be reportable. */ interface CaptureUploadResult { cancelled?: boolean; uploaded: string[]; aliased: { existingFileId: string; }[]; failed: { name: string; error: string; }[]; } /** Options for {@link CapturePort.openFilePicker} (measured: cloudFilesPickerOpeners). */ interface CapturePickOpts { multi?: boolean; title?: string; description?: string; } /** * The capture-toolbar seam. PER-HANDLER optional: the toolbar renders only * the chips it can actually honor; a chip with no path behind it is never * rendered dead. NEVER dead buttons. * * THE UPLOAD DEFAULT (0.6.0, C23): a host does NOT have to build an upload * flow. Bind the one-file primitive `uploadFile` and the package ships the * WHOLE flow over it β€” the file input, whole-body drag-and-drop, sequential * uploads, the stall watchdog, per-file outcomes, and the loud * created-but-unattached report. `requestUpload` stays for a host that owns * a richer pipeline (duplicate-alias dialogs, progress UI); when both are * bound `requestUpload` wins. */ interface CapturePort { /** * The MINIMAL upload primitive: persist ONE file, answer with its id (or * an honest error). Everything else β€” batching, drag-and-drop, progress * state, failure copy β€” is the package's job. */ uploadFile?(file: File, opts: Omit): Promise<{ ok: true; id: string; } | { ok: false; error: string; }>; /** The full host upload pipeline. Wins over `uploadFile` when bound. */ requestUpload?(opts: CaptureUploadOpts): Promise; /** Resolves with picked file ids, or null/empty on cancel. */ openFilePicker?(opts: CapturePickOpts): Promise; /** Creates a document in the authoritative organization of this container. */ createDataTable?(opts: { name: string; organizationId: string; }): Promise<{ id: string; } | null>; } /** * Props of the generic association picker face β€” ALSO the contract a * per-token override component must implement (today: the hardcoded * `token === "file"` β†’ FilePickerWindow branch in AssociationPicker becomes a * `registerPickerOverride("file", …)` host binding). Ported verbatim from the * measured component. */ interface AssociationPickerProps { open: boolean; onOpenChange: (open: boolean) => void; token: EntityTypeToken; /** Container display label, for the header ("…to Titanium Marketing"). */ containerLabel?: string; /** Org stamped onto rows created by the "+ New" footer. */ orgId?: string | null; /** Resource ids already attached to the container. */ attachedIds: Set; /** Attach a resource (returns ok/err so the row can surface failures). */ onAttach: (resourceId: string, title: string) => Promise<{ ok: boolean; error?: string; }>; /** Detach a resource. */ onDetach: (resourceId: string) => Promise<{ ok: boolean; error?: string; }>; /** * Filed-under mode: the primary is being FILED UNDER the picked items * (`primary β†’ item`), so the header says "File … under" not "Attach to". */ filing?: boolean; } /** Per-token picker override map β€” absent tokens use the generic picker sheet. */ type PickerOverrideMap = Partial>>; /** * Props the entity-doors port's `EntityRef` receives (the measured subset the * association faces pass today). */ interface EntityRefProps { token: string; id: string; name?: string | null; showIcon?: boolean; openInNewTab?: boolean; alwaysShowActions?: boolean; className?: string; } /** Props the entity-doors port's `DoorControls` receives. */ interface EntityDoorProps { token: string; id: string; name?: string | null; className?: string; } /** What the authorDisplay port receives β€” one comment's denormalized author. */ interface AuthorDisplayInput { /** The auth user id (`created_by`), or null on an authorless legacy row. */ userId: string | null; email: string | null; displayName: string | null; avatarUrl: string | null; } /** * The author-display seam (W6 comments UI). The package cannot resolve user * profiles itself β€” `cmt_list` denormalizes email/displayName/avatarUrl per * row, and a host with a richer profile store (presence, current names, * signed avatar URLs) overrides them here. Return `null` (or omit a field) * to keep the denormalized value. * * DEGRADATION (absent port): the RPC's denormalized fields render as-is; * a row with neither displayName nor email shows the package's * "Unknown user" label with the default initial avatar. Never blank, never * a crash. */ type AuthorDisplayPort = (author: AuthorDisplayInput) => { displayName?: string | null; avatarUrl?: string | null; } | null; /** * The entity-doors seam (today: `EntityRef` / `EntityDoorControls` / * access-gate `UnresolvedEntityRef`). Absent β†’ title text plus the overlay's * `hrefFor` link when present; unresolved rows render the package's plain * "unavailable" chip. */ interface EntityDoorsPort { EntityRef?: ComponentType; DoorControls?: ComponentType; UnresolvedRef?: ComponentType<{ token: string; id: string; }>; } /** * Everything a host binds, once. `createAssociationsStore(cfg)` (/core) * throws when `dataSource` or `identity` is missing β€” those two ARE the * host's app identity and cannot be defaulted. Every other port ships a * working default (C23) or degrades per its own documented contract, never * silently. */ interface AssociationsConfig { dataSource: AssociationsDataSource | AssociationsRpcOnlyDataSource; identity: AssociationsIdentity; errorSink?: ErrorSink; entityOverlay?: EntityOverlayMap; notifier?: AssociationsNotifier; windowShell?: WindowShellPort; capture?: CapturePort; pickerOverrides?: PickerOverrideMap; entityDoors?: EntityDoorsPort; authorDisplay?: AuthorDisplayPort; } declare const ASSOCIATION_TARGET_TYPES: readonly ["organization", "scope", "tag", "scope_type", "project", "task", "context_item", "thread", "war_room", "category", "conversation", "fc_set", "fc_card", "study_media", "assessment", "note", "file", "processed_document", "quiz_session", "agent", "agent_term_list", "research_tag", "skill", "surface", "plan_entity", "plan_node", "web_site", "seo_topic", "seo_keyword", "web_page", "web_screenshot", "party", "crm_outreach_list", "crm_deal", "rulebook", "research_topic", "media_source_library", "membership", "team", "position", "workflow", "board", "web_brand", "record", "transcript"]; type AssociationTargetType = (typeof ASSOCIATION_TARGET_TYPES)[number]; interface AssociationEdge { id: string; direction: "outgoing" | "incoming"; otherType: string; otherId: string; role: string | null; label: string | null; position: number | null; metadata: unknown; orgId: string | null; createdAt: string; } interface AssociationTargetEdge { id: string; targetId: string; sourceType: string; sourceId: string; role: string | null; label: string | null; position: number | null; metadata: unknown; orgId: string | null; createdAt: string; } interface AssociationSourceEdge { id: string; sourceId: string; targetType: string; targetId: string; role: string | null; label: string | null; position: number | null; metadata: unknown; orgId: string | null; createdAt: string; } interface AssociationsEntry { status: "idle" | "loading" | "ready" | "error"; edges: AssociationEdge[]; fetchedAt: number | null; error: string | null; } interface UserEntityState { entityType: string; entityId: string; isFavorite: boolean; isPinned: boolean; isHidden: boolean; lastViewedAt: string | null; } /** The three boolean dimensions of per-user state, as accepted by `ues_list`. */ type UserStateKind = "favorite" | "pinned" | "hidden"; /** * The facet a category belongs to. Open vocabulary (new dimensions need no * migration β€” `dimension` is free text in the DB); hosts enumerate their * known dimensions as constants. */ type CategoryDimension = string; /** One `platform.categories` row, camelCased (mirrors `cat_list`'s return). */ interface PlatformCategory { id: string; /** Owning organization; system/global rows use the Matrx System org. */ orgId: string | null; dimension: CategoryDimension; name: string; slug: string | null; parentId: string | null; isSystem: boolean; color: string | null; icon: string | null; position: number | null; /** * The row's jsonb metadata β€” category rows CARRY semantics: e.g. a * `deal_pipeline` stage stores `{outcome: "won"|"lost", probability: 0..100}` * here. Null when empty or when hydrated from an older cache entry. */ metadata: Record | null; } /** Cache entry for one `dimension` β€” mirrors `AssociationsEntry`. */ interface CategoriesEntry { status: "idle" | "loading" | "ready" | "error"; categories: PlatformCategory[]; fetchedAt: number | null; error: string | null; } /** The author of a comment, denormalized by `cmt_list` from the auth user. */ interface CommentAuthor { email: string | null; displayName: string | null; avatarUrl: string | null; } /** * One `platform.comments` row, camelCased (mirrors `cmt_list`'s return). * Threading is by `parentId`: a top-level comment has `parentId === null`; * a reply points at its parent. `cmt_list` returns rows oldestβ†’newest so * callers can build the thread in one pass. */ interface PlatformComment { id: string; orgId: string | null; entityType: string; entityId: string; parentId: string | null; body: string; createdAt: string; updatedAt: string; createdBy: string | null; author: CommentAuthor; /** * The platform agent that wrote this comment (a reply the agent made in the * thread), or null when a person did. `createdBy` stays the person whose * authority it ran under β€” an agent's comment is never "mine" and has no Edit. */ authorAgent: CommentAgentAuthor | null; /** * The platform itself wrote this comment (`created_by_tier = 'system'`, e.g. the opener of * an edit remark's thread): credited to the system, never to `createdBy`, never editable. */ authorSystem?: boolean; /** The comment's anchor (`text_anchor` passage, `part_anchor` part, ...), or null for the whole record. */ anchor: CommentAnchor | null; } /** The agent behind a comment (`cmt_list`'s author_agent_id/name). */ interface CommentAgentAuthor { id: string; name: string | null; } /** A comment's anchor as stored: a `__kind`-marked object (`platform.comments.anchor`). */ type CommentAnchor = { __kind: string; } & Record; /** * One cached comment thread (per `${entityType}:${entityId}` endpoint) β€” the * same lifecycle shape as `AssociationsEntry`/`CategoriesEntry`: pending * keeps previous comments AND the visible error; `fetchedAt` is the last * successful load. */ interface CommentsEntry { status: "idle" | "loading" | "ready" | "error"; comments: readonly PlatformComment[]; fetchedAt: number | null; error: string | null; } type ContentRole = "utility" | "source" | "destination" | "hybrid" | "container"; /** * Fully-resolved entity descriptor β€” generated metadata + host overlay, with * safe fallbacks so an un-overlaid token still renders (derived plural, no * door, `Icon: null` β†’ the consumer's default) even if it can't be queried * for candidates yet. */ interface EntityInfo { token: EntityTypeToken; label: string; labelPlural: string; /** Postgres schema of the backing table (from the generated registry). */ schema: string; /** Backing table name (from the generated registry). */ table: string; /** Title column for the picker, or null when none is registered. */ titleColumn: string | null; /** Ownership column to scope candidate reads to the current user. */ ownerColumn: string; /** Org-scoping column. */ orgColumn: string; /** Host-supplied icon component, or null (consumer renders its default). */ Icon: EntityOverlayEntry["Icon"] | null; hrefFor: ((id: string) => string) | null; scopeable: boolean; category: string | null; /** Knowledge-model grouping bucket (resource surfaces group by this). */ contentRole: ContentRole; /** Candidate-source override (rag-backed tokens etc.); null = generic read. */ listCandidates: EntityOverlayEntry["listCandidates"] | null; /** True when a picker can list real candidates (title column OR override). */ canListCandidates: boolean; } interface EntityRegistry { /** Merge more overlay entries in (host binding, W4 pickers, tests). */ registerEntityOverlay(overlay: EntityOverlayMap): void; /** Resolve a KNOWN token to its full descriptor. */ getEntityInfo(token: EntityTypeToken): EntityInfo; /** Safe variant for raw strings (e.g. an edge's `otherType`). */ tryGetEntityInfo(token: string): EntityInfo | null; /** Resolve from a live `(schema, table)` pair, or null. */ tryGetEntityInfoByTable(schema: string, table: string): EntityInfo | null; /** Resolve a raw table name only when it maps to exactly one entity. */ tryGetEntityInfoByUniqueTableName(table: string): EntityInfo | null; /** * Tokens the DB classifies as knowledge resources via a valid * `content_role` AND that can list candidates. The default set for card * grids, resource sections, and attach pickers. */ curatedTokens(): EntityTypeToken[]; /** * Tokens offered as reference "Allowed types" β€” DB-driven via * `platform.entity_types.reference_pickable`. A pickable token with no * title column and no candidate override is a config defect: excluded and * screamed to the errorSink, never silently shown broken. */ listableTokens(): EntityTypeToken[]; } type AssociationsRpcErrorCode = "unauthorized" | "forbidden_org" | "forbidden_role" | "not_found" | "conflict_in_use" | "invalid_argument" | "version_conflict" | "quota_exceeded" /** * THE DEMANDED-SCHEMA SCREAM. A PostgREST missing-function error (PGRST202) * on any demanded RPC maps to this code: the database this client is * pointed at does not run the schema this package demands (README front * door). It always reaches the errorSink β€” one unambiguous scream, never a * mystery toast β€” PGRST202 arrives as `demanded_schema_violation`. */ | "demanded_schema_violation" | "internal"; interface AssociationsRpcError { code: AssociationsRpcErrorCode; message: string; hint?: string; detail?: unknown; } type AssociationsRpcResult = { ok: true; data: T; } | { ok: false; error: AssociationsRpcError; }; interface ConversationFileLink { fileId: string; label: string | null; metadata: unknown; createdAt: string; } interface AddAssociationArgs { sourceType: string; sourceId: string; targetType: AssociationTargetType; targetId: string; orgId?: string; label?: string; metadata?: unknown; /** * Exact file β†’ conversation updates preserve existing metadata unless the * caller explicitly opts into replacement. Invalid for every other pair. */ replaceMetadata?: boolean; role?: string; position?: number; /** * Typed edge payload (Edge Payload System). `payloadKind` must be a * registered `platform.edge_payload_kind`; the DB trigger validates * `payload` against its JSON Schema and hard-fails on any mismatch. Real * logic an edge carries goes HERE β€” `metadata` is for loose annotations. */ payloadKind?: string; payload?: unknown; } interface AssociationsServiceApi { listForEntity(rawType: string, id: string): Promise>; listConversationFiles(conversationId: string): Promise>; listForTargets(rawTargetType: string, targetIds: string[]): Promise>; listForTargetsVisible(rawTargetType: string, targetIds: string[]): Promise>; listForSources(rawSourceType: string, sourceIds: string[], rawTargetType?: string): Promise>; add(args: AddAssociationArgs): Promise>; /** * Attach MANY edges in ONE database transaction (`platform.assoc_add_many`): every edge is * applied exactly as {@link add} applies it, the ids come back in input order, and if ANY edge * is refused the whole call fails and NOTHING is applied. Keep a call under * {@link ASSOC_ADD_MANY_CHUNK} edges (the helpers' `linkEdges` chunks for you). The * file β†’ conversation pair is not batchable (it has its own stricter door): use {@link add}. */ addMany(args: AddAssociationArgs[]): Promise>; remove(args: { sourceType: string; sourceId: string; targetType: string; targetId: string; role?: string; }): Promise>; setTargets(args: { sourceType: string; sourceId: string; targetType: AssociationTargetType; targetIds: string[]; orgId?: string; role?: string; }): Promise>; addAgentResource(args: { agentId: string; sourceType: string; sourceId: string; label?: string; metadata?: unknown; }): Promise>; removeAgentResource(args: { agentId: string; sourceType: string; sourceId: string; }): Promise>; removeForEntity(rawType: string, id: string): Promise>; } interface CategoriesServiceApi { list(dimension?: CategoryDimension): Promise>; create(args: { dimension: CategoryDimension; name: string; orgId: string; parentId?: string | null; color?: string | null; icon?: string | null; slug?: string | null; }): Promise>; update(args: { id: string; name: string; slug: string | null; color: string | null; icon: string | null; position: number | null; }): Promise>; reparent(args: { id: string; parentId: string | null; }): Promise>; delete(id: string): Promise>; } interface FavoritesServiceApi { setState(args: { entityType: string; entityId: string; isFavorite?: boolean; isPinned?: boolean; isHidden?: boolean; }): Promise>; setFavorite(entityType: string, entityId: string, isFavorite: boolean): Promise>; setPinned(entityType: string, entityId: string, isPinned: boolean): Promise>; setHidden(entityType: string, entityId: string, isHidden: boolean): Promise>; list(kind?: UserStateKind): Promise>; getBulk(entityType: string, entityIds: string[]): Promise>; touch(entityType: string, entityId: string): Promise>; } interface CandidateRecord { id: string; title: string; } interface ListCandidatesArgs { token: EntityTypeToken; /** Case-insensitive title filter. */ search?: string; limit?: number; } type CandidatesResult = { ok: true; data: CandidateRecord[]; } | { ok: false; error: string; }; interface UniversalCandidate extends CandidateRecord { token: EntityTypeToken; } interface SearchAcrossTokensArgs { /** Tokens to search. Defaults to every curated token in the registry. */ tokens?: EntityTypeToken[]; search: string; /** Cap per token β€” a universal search shows a few of everything. */ perTokenLimit?: number; /** Max in-flight token queries. */ concurrency?: number; } /** One token whose candidate read failed during a cross-token search. */ interface TokenSearchFailure { token: EntityTypeToken; error: string; } /** * A cross-token search's honest answer: what could be read, AND what could * not. An empty `results` with non-empty `failures` is "we couldn't look", * never "there is nothing". */ interface SearchAcrossTokensResult { results: UniversalCandidate[]; failures: TokenSearchFailure[]; } interface ReferenceSearchCandidatesFn { (args: { p_token: string; p_search?: string; p_limit?: number; p_ids?: string[]; }): Promise<{ data: Array<{ id: string; title: string | null; }>; error: null; } | { data: null; error: { message: string; }; }>; } interface CandidatesServiceApi { /** * The universal candidate reader RPC (`platform.reference_search_candidates`) * β€” shared by candidate search here and title resolution in titles.ts. */ callReferenceSearchCandidates: ReferenceSearchCandidatesFn; listAssociationCandidates(args: ListCandidatesArgs): Promise; /** * ONE search over EVERY listable entity type β€” the "attach anything from * anywhere" primitive. Registry-driven client fan-out, capped and * concurrency-limited. One broken table never blanks the search: a failed * token is screamed (errorSink) AND reported in `failures` (registry * order), so a face can say what it could not search instead of showing * "no results". */ searchCandidatesAcrossTokens(args: SearchAcrossTokensArgs): Promise; } interface TitlesServiceApi { /** Read the cache synchronously (for render paths after a fetch settled). */ get(token: string, id: string): string | null; /** * Push a known-fresh title into the cache (after a rename or a create), so * surfaces that resolve through this service never show a stale name. */ prime(token: string, id: string, title: string): void; /** Display fallback when no label and no fetched title exist. */ fallback(token: string): string; /** * Resolve titles for `ids` of one token. Returns ONLY the resolved entries * (cache + fresh reads); missing rows (deleted, no access) stay absent. */ fetch(token: string, ids: string[]): Promise>; } type EntityRowResult = { ok: true; data: { id: string; title: string; }; } | { ok: false; error: string; }; interface CreateEntityRowArgs { /** The new row's human name β€” written to the registry `titleColumn`. */ title: string; /** * The organization the new row belongs to. REQUIRED by * `platform.entity_row_create`: every creatable token's table carries * `organization_id`, and the door refuses a row with nobody owning it. */ orgId?: string | null; /** * 🚨 NO LONGER WRITABLE THROUGH THIS SERVICE (DOORS-ONLY-4). The door writes the * name, the owner and the organization and nothing else, so a non-empty value here * is REFUSED with the columns named rather than dropped on the floor. A token whose * table needs more than a name is created by its own feature's create service; this * generic path then only renames it. */ extraColumns?: Record; } interface EntityRowsServiceApi { createEntityRow(token: EntityTypeToken, args: CreateEntityRowArgs): Promise; renameEntityRow(token: EntityTypeToken, id: string, title: string): Promise<{ ok: true; } | { ok: false; error: string; }>; } /** A typed reference to a single row β€” `{ type, id }`. */ interface EntityRef { type: EntityTypeToken; id: string; } /** A container reference β€” the deliberate set an edge may point at. */ interface ContainerRef { type: AssociationTargetType; id: string; } /** Per-edge attributes shared by the link helpers. */ interface EdgeAttrs { orgId?: string; label?: string; metadata?: unknown; role?: string; position?: number; } /** One fully-specified edge for {@link AssociationHelpersApi.linkEdges}. */ interface EdgeSpec extends EdgeAttrs { source: EntityRef; target: ContainerRef; } interface AssociationHelpersApi { /** * Add an arbitrary batch of edges in one call (idempotent per edge). * Written through the batch door (`platform.assoc_add_many`) in sequential chunks of * {@link ASSOC_ADD_MANY_CHUNK}; each chunk is ONE transaction (all or nothing). The result * is `ok` with the ids in input order only when ALL succeed, otherwise `err` whose * `detail` lists a failure for every edge that was not written (chunks that DID succeed * remain applied β€” re-running is safe via ON CONFLICT). */ linkEdges(edges: EdgeSpec[]): Promise>; /** Attach ONE source to MANY containers in a single shot. */ linkOneToMany(args: { source: EntityRef; targets: ContainerRef[]; attrs?: EdgeAttrs; }): Promise>; /** Attach MANY sources to ONE container in a single shot. */ linkManyToOne(args: { sources: EntityRef[]; target: ContainerRef; attrs?: EdgeAttrs; }): Promise>; /** * REPLACE the full set of a source's edges of one container type (adds * missing, removes extras) in one DB transaction β€” the set-semantics * one-shot. Thin, named pass-through to `assoc_set_targets`. */ replaceTargets(args: { source: EntityRef; targetType: AssociationTargetType; targetIds: string[]; orgId?: string; role?: string; }): Promise>; /** * Wire edges onto a JUST-CREATED entity. The caller inserts its own row * (entity tables are feature-owned), then passes the new id here to attach * it to any number of containers (orphan-on-partial-fail is harmless and * re-runnable). `created` is the new entity; it becomes the edges' SOURCE. */ linkCreated(args: { created: EntityRef; targets: ContainerRef[]; attrs?: EdgeAttrs; }): Promise>; /** Remove an arbitrary batch of edges (best-effort; no-op per missing edge). */ unlinkEdges(edges: { source: EntityRef; target: ContainerRef; role?: string; }[]): Promise>; } interface AddCommentArgs { /** Registered entity-type token the comment hangs on (writes-strict, C18). */ entityType: string; entityId: string; body: string; /** Reply target β€” an existing comment's id. Top-level when omitted. */ parentId?: string | null; /** Org override; the RPC resolves task-org/personal-org when omitted. */ orgId?: string | null; /** Where on the record the comment points (a `part_anchor`, a `text_anchor`); whole record when omitted. */ anchor?: CommentAnchor | null; } interface CommentsServiceApi { listForEntity(entityType: string, entityId: string): Promise>; add(args: AddCommentArgs): Promise>; edit(id: string, body: string): Promise>; remove(id: string): Promise>; } interface AssociationWriteResult { ok: boolean; /** Set on a successful single-edge `add`. */ id?: string; error?: string; } interface CategoryMutationResult { ok: boolean; /** Set on a successful mutation. */ id?: string; error?: string; } interface CommentMutationResult { ok: boolean; /** Set on a successful `addComment`. */ id?: string; error?: string; } interface AssociationsStore { /** Stable, sync read of one endpoint's entry (idle default when uncached). */ getEdges(type: string, id: string): AssociationsEntry; /** * Lazy load of every edge touching `${type}:${id}` (both directions). * Deduped per key; `status === "ready"` short-circuits unless `force`. */ load(type: string, id: string, opts?: { force?: boolean; }): Promise; /** External-store contract: notified whenever the key's entry changes. */ subscribe(key: string, cb: () => void): () => void; /** Attach source β†’ target; on success reloads BOTH endpoints. */ add(args: { sourceType: string; sourceId: string; targetType: AssociationTargetType; targetId: string; orgId?: string; label?: string; role?: string; metadata?: unknown; replaceMetadata?: boolean; }): Promise; /** Detach source β†’ target; on success reloads BOTH endpoints. */ remove(args: { sourceType: string; sourceId: string; targetType: string; targetId: string; role?: string; }): Promise; /** Replace the source's `targetType` edge set; reloads the SOURCE. */ setTargets(args: { sourceType: string; sourceId: string; targetType: AssociationTargetType; targetIds: string[]; orgId?: string; role?: string; }): Promise; /** Reset one endpoint to idle and notify its subscribers. */ invalidate(type: string, id: string): void; /** Reset every association endpoint, category facet, and comment thread. */ invalidateAll(): void; getCategories(dimension: CategoryDimension): CategoriesEntry; loadCategories(dimension: CategoryDimension, opts?: { force?: boolean; }): Promise; subscribeCategories(dimension: CategoryDimension, cb: () => void): () => void; /** Create + echo-insert + authoritative force reload. Returns the new id. */ createCategory(args: { dimension: CategoryDimension; name: string; orgId: string; parentId?: string | null; color?: string | null; icon?: string | null; slug?: string | null; }): Promise; updateCategory(args: { dimension: CategoryDimension; id: string; name: string; slug: string | null; color: string | null; icon: string | null; position: number | null; }): Promise; reparentCategory(args: { dimension: CategoryDimension; id: string; parentId: string | null; }): Promise; deleteCategory(args: { dimension: CategoryDimension; id: string; }): Promise; /** Stable, sync read of one entity's comment thread (idle when uncached). */ getComments(type: string, id: string): CommentsEntry; /** * Lazy load of every comment on `${type}:${id}` (oldestβ†’newest; thread by * `parentId`). Deduped per key; `status === "ready"` short-circuits unless * `force`. */ loadComments(type: string, id: string, opts?: { force?: boolean; }): Promise; /** External-store contract for one entity's comment thread. */ subscribeComments(key: string, cb: () => void): () => void; /** Post a comment (or a reply); on success force-reloads the thread. */ addComment(args: { entityType: string; entityId: string; body: string; parentId?: string | null; orgId?: string | null; anchor?: CommentAnchor | null; }): Promise; /** Edit a comment body (author-only in the RPC); reloads the thread. */ editComment(args: { entityType: string; entityId: string; id: string; body: string; }): Promise; /** Soft-delete a comment (author/org member in the RPC); reloads the thread. */ deleteComment(args: { entityType: string; entityId: string; id: string; }): Promise; /** Reset one entity's comment thread to idle and notify its subscribers. */ invalidateComments(type: string, id: string): void; /** Batched title resolution + the session cache + prime. */ titles: TitlesServiceApi; /** Per-user favorite/pinned/hidden state (`ues_*`). */ favorites: FavoritesServiceApi; /** Candidate reads for the pickers. */ candidates: CandidatesServiceApi; /** Generic registry-convention row create/rename. */ entityRows: EntityRowsServiceApi; /** Composite link helpers over the chokepoint. */ helpers: AssociationHelpersApi; /** The registry merge engine (generated metadata + host overlay). */ registry: EntityRegistry; /** * The raw chokepoint services β€” every RPC family, results-enveloped. * `associations` writes here do NOT touch the cache; use the store-level * `add`/`remove`/`setTargets` when a cached surface must stay fresh. */ services: { associations: AssociationsServiceApi; categories: CategoriesServiceApi; comments: CommentsServiceApi; }; /** Merge more host overlay entries in (icons/routes/candidate loaders). */ registerEntityOverlay: EntityRegistry["registerEntityOverlay"]; /** * The bound scream seam (W3, additive): /react surfaces route their loud * recoveries here (the originals' console.error sites) without a second * sink binding. Same function the host passed at construction. */ errorSink: ErrorSink; /** * The bound data seam (0.6.0, additive): the provider's demanded-schema * boot probe reads it so hosts stop re-exporting their dataSource just to * run a check the package owns. */ dataSource: AssociationsDataSource; /** * The bound identity port (W3, additive): /react hooks that FILTER by the * current user (candidate owner scoping) read it leniently; write paths * keep going through the services, where `requireUserId` failures stay * loud. Same object the host passed at construction. */ identity: AssociationsConfig["identity"]; } export type { AssociationPickerProps as A, CategoryMutationResult as C, EntityTypeToken as E, PlatformCategory as P, UniversalCandidate as U, WindowShellPort as W, CategoryDimension as a, CategoriesEntry as b, CandidateRecord as c, PlatformComment as d, CommentsEntry as e, CommentAnchor as f, CommentMutationResult as g, EntityDoorProps as h, EntityRefProps as i, ContentRole as j, AssociationWriteResult as k, AssociationEdge as l, AssociationsEntry as m, AssociationTargetType as n, CaptureShownTo as o, AssociationsNotifier as p, CapturePort as q, PickerOverrideMap as r, EntityDoorsPort as s, AuthorDisplayPort as t, AssociationsStore as u };