@codemem/core 0.30.0-alpha.3 → 0.30.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -616,6 +616,7 @@ var V = class {
616
616
  P("idx_memory_items_active_created").on(e.active, e.created_at),
617
617
  P("idx_memory_items_session").on(e.session_id),
618
618
  P("idx_memory_items_scope_visibility_created").on(e.scope_id, e.visibility, e.created_at),
619
+ P("idx_memory_items_scope_backfill_pending").on(e.id).where(M`scope_id IS NULL OR scope_id = ''`),
619
620
  P("idx_memory_items_dedup_key_active_created").on(e.dedup_key, e.active, e.created_at),
620
621
  xe("idx_memory_items_same_session_dedup_unique").on(e.session_id, e.kind, e.visibility, e.workspace_id, e.dedup_key).where(M`active = 1 AND dedup_key IS NOT NULL`)
621
622
  ]), tt = I("memory_file_refs", {
@@ -1339,7 +1340,7 @@ function ln(e, t) {
1339
1340
  }
1340
1341
  //#endregion
1341
1342
  //#region src/test-schema.generated.ts
1342
- var un = "CREATE TABLE IF NOT EXISTS `sessions` (\n `id` integer PRIMARY KEY NOT NULL,\n `started_at` text NOT NULL,\n `ended_at` text,\n `cwd` text,\n `project` text,\n `git_remote` text,\n `git_branch` text,\n `user` text,\n `tool_version` text,\n `metadata_json` text,\n `import_key` text\n);\n\nCREATE TABLE IF NOT EXISTS `replication_scopes` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `label` text NOT NULL,\n `kind` text DEFAULT 'user' NOT NULL,\n `authority_type` text DEFAULT 'local' NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `manifest_hash` text,\n `status` text DEFAULT 'active' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_status` ON `replication_scopes` (`status`);\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_authority_group` ON `replication_scopes` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `project_scope_mappings` (\n `id` integer PRIMARY KEY NOT NULL,\n `workspace_identity` text,\n `project_pattern` text NOT NULL,\n `scope_id` text NOT NULL,\n `priority` integer DEFAULT 0 NOT NULL,\n `source` text DEFAULT 'user' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_workspace_priority` ON `project_scope_mappings` (`workspace_identity`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_pattern_priority` ON `project_scope_mappings` (`project_pattern`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_scope` ON `project_scope_mappings` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `scope_memberships` (\n `scope_id` text NOT NULL,\n `device_id` text NOT NULL,\n `role` text DEFAULT 'member' NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `manifest_hash` text,\n `signed_manifest_json` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`scope_id`, `device_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_device_status` ON `scope_memberships` (`device_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_scope_status` ON `scope_memberships` (`scope_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_authority_group` ON `scope_memberships` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `artifacts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\n `kind` text NOT NULL,\n `path` text,\n `content_text` text,\n `content_hash` text,\n `created_at` text NOT NULL,\n `metadata_json` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_artifacts_session_kind` ON `artifacts` (`session_id`,`kind`);\nCREATE TABLE IF NOT EXISTS `memory_items` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\n `kind` text NOT NULL,\n `title` text NOT NULL,\n `subtitle` text,\n `body_text` text NOT NULL,\n `confidence` real DEFAULT 0.5,\n `tags_text` text DEFAULT '',\n `active` integer DEFAULT 1,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n `metadata_json` text,\n `actor_id` text,\n `actor_display_name` text,\n `visibility` text,\n `workspace_id` text,\n `workspace_kind` text,\n `origin_device_id` text,\n `origin_source` text,\n `trust_state` text,\n `facts` text,\n `narrative` text,\n `concepts` text,\n `files_read` text,\n `files_modified` text,\n `user_prompt_id` integer,\n `prompt_number` integer,\n `deleted_at` text,\n `rev` integer DEFAULT 0,\n `dedup_key` text,\n `import_key` text,\n `scope_id` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_items_active_created` ON `memory_items` (`active`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_session` ON `memory_items` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_visibility_created` ON `memory_items` (`scope_id`,`visibility`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_dedup_key_active_created` ON `memory_items` (`dedup_key`,`active`,`created_at`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_memory_items_same_session_dedup_unique` ON `memory_items` (`session_id`,`kind`,`visibility`,`workspace_id`,`dedup_key`) WHERE active = 1 AND dedup_key IS NOT NULL;\nCREATE TABLE IF NOT EXISTS `memory_file_refs` (\n `memory_id` integer NOT NULL,\n `file_path` text NOT NULL,\n `relation` text NOT NULL,\n PRIMARY KEY(`memory_id`, `file_path`, `relation`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_file_refs_path` ON `memory_file_refs` (`file_path`);\nCREATE TABLE IF NOT EXISTS `memory_concept_refs` (\n `memory_id` integer NOT NULL,\n `concept` text NOT NULL,\n PRIMARY KEY(`memory_id`, `concept`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_concept_refs_concept` ON `memory_concept_refs` (`concept`);\nCREATE TABLE IF NOT EXISTS `usage_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `event` text NOT NULL,\n `tokens_read` integer DEFAULT 0,\n `tokens_written` integer DEFAULT 0,\n `tokens_saved` integer DEFAULT 0,\n `created_at` text NOT NULL,\n `metadata_json` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null\n);\n\nCREATE INDEX IF NOT EXISTS `idx_usage_events_event_created` ON `usage_events` (`event`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_usage_events_session` ON `usage_events` (`session_id`);\nCREATE TABLE IF NOT EXISTS `raw_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `event_id` text,\n `event_seq` integer NOT NULL,\n `event_type` text NOT NULL,\n `ts_wall_ms` integer,\n `ts_mono_ms` real,\n `payload_json` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_seq` ON `raw_events` (`source`,`stream_id`,`event_seq`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_event_id` ON `raw_events` (`source`,`stream_id`,`event_id`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_session_seq` ON `raw_events` (`opencode_session_id`,`event_seq`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_created` ON `raw_events` (`created_at`);\nCREATE TABLE IF NOT EXISTS `raw_event_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `cwd` text,\n `project` text,\n `started_at` text,\n `last_seen_ts_wall_ms` integer,\n `last_received_event_seq` integer DEFAULT -1 NOT NULL,\n `last_flushed_event_seq` integer DEFAULT -1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`)\n);\n\nCREATE TABLE IF NOT EXISTS `opencode_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `session_id` integer,\n `created_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`),\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_opencode_sessions_session` ON `opencode_sessions` (`session_id`);\nCREATE TABLE IF NOT EXISTS `raw_event_flush_batches` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `start_event_seq` integer NOT NULL,\n `end_event_seq` integer NOT NULL,\n `extractor_version` text NOT NULL,\n `status` text NOT NULL,\n `error_message` text,\n `error_type` text,\n `observer_provider` text,\n `observer_model` text,\n `observer_runtime` text,\n `observer_auth_source` text,\n `observer_auth_type` text,\n `observer_error_code` text,\n `observer_error_message` text,\n `attempt_count` integer DEFAULT 0 NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_flush_batches_source_stream_seq_ver` ON `raw_event_flush_batches` (`source`,`stream_id`,`start_event_seq`,`end_event_seq`,`extractor_version`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_session_created` ON `raw_event_flush_batches` (`opencode_session_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`);\nCREATE TABLE IF NOT EXISTS `user_prompts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `project` text,\n `prompt_text` text NOT NULL,\n `prompt_number` integer,\n `created_at` text NOT NULL,\n `created_at_epoch` integer NOT NULL,\n `metadata_json` text,\n `import_key` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_session` ON `user_prompts` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_project` ON `user_prompts` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_epoch` ON `user_prompts` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `session_summaries` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `project` text,\n `request` text,\n `investigated` text,\n `learned` text,\n `completed` text,\n `next_steps` text,\n `notes` text,\n `files_read` text,\n `files_edited` text,\n `prompt_number` integer,\n `created_at` text NOT NULL,\n `created_at_epoch` integer NOT NULL,\n `metadata_json` text,\n `import_key` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_session` ON `session_summaries` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_project` ON `session_summaries` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_epoch` ON `session_summaries` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `replication_ops` (\n `op_id` text PRIMARY KEY NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `op_type` text NOT NULL,\n `payload_json` text,\n `clock_rev` integer NOT NULL,\n `clock_updated_at` text NOT NULL,\n `clock_device_id` text NOT NULL,\n `device_id` text NOT NULL,\n `created_at` text NOT NULL,\n `scope_id` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_created` ON `replication_ops` (`created_at`,`op_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_entity` ON `replication_ops` (`entity_type`,`entity_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_scope_created` ON `replication_ops` (`scope_id`,`created_at`,`op_id`);\nCREATE TABLE IF NOT EXISTS `replication_cursors` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `replication_cursors_v2` (\n `peer_device_id` text NOT NULL,\n `scope_id` text NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`peer_device_id`, `scope_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_cursors_v2_scope` ON `replication_cursors_v2` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `sync_peers` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `name` text,\n `pinned_fingerprint` text,\n `public_key` text,\n `addresses_json` text,\n `claimed_local_actor` integer DEFAULT 0 NOT NULL,\n `actor_id` text,\n `projects_include_json` text,\n `projects_exclude_json` text,\n `created_at` text NOT NULL,\n `last_seen_at` text,\n `last_sync_at` text,\n `last_error` text,\n `discovered_via_coordinator_id` text,\n `discovered_via_group_id` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_nonces` (\n `nonce` text PRIMARY KEY NOT NULL,\n `device_id` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_device` (\n `device_id` text PRIMARY KEY NOT NULL,\n `public_key` text NOT NULL,\n `fingerprint` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_attempts` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `peer_device_id` text NOT NULL,\n `started_at` text NOT NULL,\n `finished_at` text,\n `ok` integer NOT NULL,\n `ops_in` integer NOT NULL,\n `ops_out` integer NOT NULL,\n `error` text,\n `local_sync_capability` text,\n `peer_sync_capability` text,\n `negotiated_sync_capability` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_peer_started` ON `sync_attempts` (`peer_device_id`,`started_at`);\nCREATE TABLE IF NOT EXISTS `sync_scope_rejections` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `peer_device_id` text,\n `op_id` text NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `scope_id` text,\n `reason` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_peer_created` ON `sync_scope_rejections` (`peer_device_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_scope_created` ON `sync_scope_rejections` (`scope_id`,`created_at`);\nCREATE TABLE IF NOT EXISTS `sync_daemon_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `last_error` text,\n `last_traceback` text,\n `last_error_at` text,\n `last_ok_at` text,\n `phase` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_retention_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `last_run_at` text,\n `last_duration_ms` integer,\n `last_deleted_ops` integer DEFAULT 0 NOT NULL,\n `last_estimated_bytes_before` integer,\n `last_estimated_bytes_after` integer,\n `retained_floor_cursor` text,\n `last_error` text,\n `last_error_at` text\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_samples` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `created_at` text NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_stats` (\n `id` integer PRIMARY KEY NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `coordinator_group_preferences` (\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `projects_include_json` text,\n `projects_exclude_json` text,\n `auto_seed_scope` integer DEFAULT 1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`coordinator_id`, `group_id`)\n);\n\nCREATE TABLE IF NOT EXISTS `actors` (\n `actor_id` text PRIMARY KEY NOT NULL,\n `display_name` text NOT NULL,\n `is_local` integer DEFAULT 0 NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `merged_into_actor_id` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_actors_is_local` ON `actors` (`is_local`);\nCREATE INDEX IF NOT EXISTS `idx_actors_status` ON `actors` (`status`);", dn = "\nCREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n\nCREATE TABLE IF NOT EXISTS sync_retention_state (\n id INTEGER PRIMARY KEY,\n last_run_at TEXT,\n last_duration_ms INTEGER,\n last_deleted_ops INTEGER NOT NULL DEFAULT 0,\n last_estimated_bytes_before INTEGER,\n last_estimated_bytes_after INTEGER,\n retained_floor_cursor TEXT,\n last_error TEXT,\n last_error_at TEXT\n);\n\nCREATE TABLE IF NOT EXISTS maintenance_jobs (\n kind TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n status TEXT NOT NULL,\n message TEXT,\n progress_current INTEGER NOT NULL DEFAULT 0,\n progress_total INTEGER,\n progress_unit TEXT NOT NULL DEFAULT 'items',\n metadata_json TEXT,\n started_at TEXT,\n updated_at TEXT NOT NULL,\n finished_at TEXT,\n error TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n ON maintenance_jobs(status, updated_at);\n\nCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n peer_device_id TEXT,\n op_id TEXT NOT NULL,\n entity_type TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n scope_id TEXT,\n reason TEXT NOT NULL,\n created_at TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n ON sync_scope_rejections(peer_device_id, created_at);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n ON sync_scope_rejections(scope_id, created_at);\n\n-- import_key is the primary lookup key from replication_ops.entity_id back to\n-- the source memory. The scope-backfill runner's selectReplicationOpScopeCandidates\n-- query joins on it for every unstamped op; without this index a Pi 4 with\n-- ~17k memories and ~35k ops scans the full memory_items table on every batch\n-- tick. The partial WHERE clause keeps the index small (most rows have\n-- import_key set; the few that don't aren't searchable anyway).\nCREATE INDEX IF NOT EXISTS idx_memory_items_import_key\n ON memory_items(import_key)\n WHERE import_key IS NOT NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n title, body_text, tags_text,\n content='memory_items',\n content_rowid='id'\n);\n\nCREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_au;\nCREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_ad;\nCREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\nEND;\n\nCREATE TABLE IF NOT EXISTS memory_file_refs (\n memory_id INTEGER NOT NULL,\n file_path TEXT NOT NULL,\n relation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n PRIMARY KEY (memory_id, file_path, relation),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path\n ON memory_file_refs(file_path);\n\nCREATE TABLE IF NOT EXISTS memory_concept_refs (\n memory_id INTEGER NOT NULL,\n concept TEXT NOT NULL,\n PRIMARY KEY (memory_id, concept),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept\n ON memory_concept_refs(concept);\n\nCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n projects_include_json TEXT,\n projects_exclude_json TEXT,\n auto_seed_scope INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id)\n);\n\nCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n last_refresh_at TEXT NOT NULL,\n last_success_at TEXT,\n last_error TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id)\n);\n", fn = "\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_vectors USING vec0(\n embedding float[384],\n memory_id INTEGER,\n chunk_index INTEGER,\n content_hash TEXT,\n model TEXT\n);\n";
1343
+ var un = "CREATE TABLE IF NOT EXISTS `sessions` (\n `id` integer PRIMARY KEY NOT NULL,\n `started_at` text NOT NULL,\n `ended_at` text,\n `cwd` text,\n `project` text,\n `git_remote` text,\n `git_branch` text,\n `user` text,\n `tool_version` text,\n `metadata_json` text,\n `import_key` text\n);\n\nCREATE TABLE IF NOT EXISTS `replication_scopes` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `label` text NOT NULL,\n `kind` text DEFAULT 'user' NOT NULL,\n `authority_type` text DEFAULT 'local' NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `manifest_hash` text,\n `status` text DEFAULT 'active' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_status` ON `replication_scopes` (`status`);\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_authority_group` ON `replication_scopes` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `project_scope_mappings` (\n `id` integer PRIMARY KEY NOT NULL,\n `workspace_identity` text,\n `project_pattern` text NOT NULL,\n `scope_id` text NOT NULL,\n `priority` integer DEFAULT 0 NOT NULL,\n `source` text DEFAULT 'user' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_workspace_priority` ON `project_scope_mappings` (`workspace_identity`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_pattern_priority` ON `project_scope_mappings` (`project_pattern`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_scope` ON `project_scope_mappings` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `scope_memberships` (\n `scope_id` text NOT NULL,\n `device_id` text NOT NULL,\n `role` text DEFAULT 'member' NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `manifest_hash` text,\n `signed_manifest_json` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`scope_id`, `device_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_device_status` ON `scope_memberships` (`device_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_scope_status` ON `scope_memberships` (`scope_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_authority_group` ON `scope_memberships` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `artifacts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\n `kind` text NOT NULL,\n `path` text,\n `content_text` text,\n `content_hash` text,\n `created_at` text NOT NULL,\n `metadata_json` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_artifacts_session_kind` ON `artifacts` (`session_id`,`kind`);\nCREATE TABLE IF NOT EXISTS `memory_items` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\n `kind` text NOT NULL,\n `title` text NOT NULL,\n `subtitle` text,\n `body_text` text NOT NULL,\n `confidence` real DEFAULT 0.5,\n `tags_text` text DEFAULT '',\n `active` integer DEFAULT 1,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n `metadata_json` text,\n `actor_id` text,\n `actor_display_name` text,\n `visibility` text,\n `workspace_id` text,\n `workspace_kind` text,\n `origin_device_id` text,\n `origin_source` text,\n `trust_state` text,\n `facts` text,\n `narrative` text,\n `concepts` text,\n `files_read` text,\n `files_modified` text,\n `user_prompt_id` integer,\n `prompt_number` integer,\n `deleted_at` text,\n `rev` integer DEFAULT 0,\n `dedup_key` text,\n `import_key` text,\n `scope_id` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_items_active_created` ON `memory_items` (`active`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_session` ON `memory_items` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_visibility_created` ON `memory_items` (`scope_id`,`visibility`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_backfill_pending` ON `memory_items` (`id`) WHERE scope_id IS NULL OR scope_id = '';\nCREATE INDEX IF NOT EXISTS `idx_memory_items_dedup_key_active_created` ON `memory_items` (`dedup_key`,`active`,`created_at`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_memory_items_same_session_dedup_unique` ON `memory_items` (`session_id`,`kind`,`visibility`,`workspace_id`,`dedup_key`) WHERE active = 1 AND dedup_key IS NOT NULL;\nCREATE TABLE IF NOT EXISTS `memory_file_refs` (\n `memory_id` integer NOT NULL,\n `file_path` text NOT NULL,\n `relation` text NOT NULL,\n PRIMARY KEY(`memory_id`, `file_path`, `relation`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_file_refs_path` ON `memory_file_refs` (`file_path`);\nCREATE TABLE IF NOT EXISTS `memory_concept_refs` (\n `memory_id` integer NOT NULL,\n `concept` text NOT NULL,\n PRIMARY KEY(`memory_id`, `concept`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_concept_refs_concept` ON `memory_concept_refs` (`concept`);\nCREATE TABLE IF NOT EXISTS `usage_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `event` text NOT NULL,\n `tokens_read` integer DEFAULT 0,\n `tokens_written` integer DEFAULT 0,\n `tokens_saved` integer DEFAULT 0,\n `created_at` text NOT NULL,\n `metadata_json` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null\n);\n\nCREATE INDEX IF NOT EXISTS `idx_usage_events_event_created` ON `usage_events` (`event`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_usage_events_session` ON `usage_events` (`session_id`);\nCREATE TABLE IF NOT EXISTS `raw_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `event_id` text,\n `event_seq` integer NOT NULL,\n `event_type` text NOT NULL,\n `ts_wall_ms` integer,\n `ts_mono_ms` real,\n `payload_json` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_seq` ON `raw_events` (`source`,`stream_id`,`event_seq`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_event_id` ON `raw_events` (`source`,`stream_id`,`event_id`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_session_seq` ON `raw_events` (`opencode_session_id`,`event_seq`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_created` ON `raw_events` (`created_at`);\nCREATE TABLE IF NOT EXISTS `raw_event_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `cwd` text,\n `project` text,\n `started_at` text,\n `last_seen_ts_wall_ms` integer,\n `last_received_event_seq` integer DEFAULT -1 NOT NULL,\n `last_flushed_event_seq` integer DEFAULT -1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`)\n);\n\nCREATE TABLE IF NOT EXISTS `opencode_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `session_id` integer,\n `created_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`),\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_opencode_sessions_session` ON `opencode_sessions` (`session_id`);\nCREATE TABLE IF NOT EXISTS `raw_event_flush_batches` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `start_event_seq` integer NOT NULL,\n `end_event_seq` integer NOT NULL,\n `extractor_version` text NOT NULL,\n `status` text NOT NULL,\n `error_message` text,\n `error_type` text,\n `observer_provider` text,\n `observer_model` text,\n `observer_runtime` text,\n `observer_auth_source` text,\n `observer_auth_type` text,\n `observer_error_code` text,\n `observer_error_message` text,\n `attempt_count` integer DEFAULT 0 NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_flush_batches_source_stream_seq_ver` ON `raw_event_flush_batches` (`source`,`stream_id`,`start_event_seq`,`end_event_seq`,`extractor_version`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_session_created` ON `raw_event_flush_batches` (`opencode_session_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`);\nCREATE TABLE IF NOT EXISTS `user_prompts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `project` text,\n `prompt_text` text NOT NULL,\n `prompt_number` integer,\n `created_at` text NOT NULL,\n `created_at_epoch` integer NOT NULL,\n `metadata_json` text,\n `import_key` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_session` ON `user_prompts` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_project` ON `user_prompts` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_epoch` ON `user_prompts` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `session_summaries` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\n `project` text,\n `request` text,\n `investigated` text,\n `learned` text,\n `completed` text,\n `next_steps` text,\n `notes` text,\n `files_read` text,\n `files_edited` text,\n `prompt_number` integer,\n `created_at` text NOT NULL,\n `created_at_epoch` integer NOT NULL,\n `metadata_json` text,\n `import_key` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_session` ON `session_summaries` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_project` ON `session_summaries` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_epoch` ON `session_summaries` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `replication_ops` (\n `op_id` text PRIMARY KEY NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `op_type` text NOT NULL,\n `payload_json` text,\n `clock_rev` integer NOT NULL,\n `clock_updated_at` text NOT NULL,\n `clock_device_id` text NOT NULL,\n `device_id` text NOT NULL,\n `created_at` text NOT NULL,\n `scope_id` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_created` ON `replication_ops` (`created_at`,`op_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_entity` ON `replication_ops` (`entity_type`,`entity_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_scope_created` ON `replication_ops` (`scope_id`,`created_at`,`op_id`);\nCREATE TABLE IF NOT EXISTS `replication_cursors` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `replication_cursors_v2` (\n `peer_device_id` text NOT NULL,\n `scope_id` text NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`peer_device_id`, `scope_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_cursors_v2_scope` ON `replication_cursors_v2` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `sync_peers` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `name` text,\n `pinned_fingerprint` text,\n `public_key` text,\n `addresses_json` text,\n `claimed_local_actor` integer DEFAULT 0 NOT NULL,\n `actor_id` text,\n `projects_include_json` text,\n `projects_exclude_json` text,\n `created_at` text NOT NULL,\n `last_seen_at` text,\n `last_sync_at` text,\n `last_error` text,\n `discovered_via_coordinator_id` text,\n `discovered_via_group_id` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_nonces` (\n `nonce` text PRIMARY KEY NOT NULL,\n `device_id` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_device` (\n `device_id` text PRIMARY KEY NOT NULL,\n `public_key` text NOT NULL,\n `fingerprint` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_attempts` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `peer_device_id` text NOT NULL,\n `started_at` text NOT NULL,\n `finished_at` text,\n `ok` integer NOT NULL,\n `ops_in` integer NOT NULL,\n `ops_out` integer NOT NULL,\n `error` text,\n `local_sync_capability` text,\n `peer_sync_capability` text,\n `negotiated_sync_capability` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_peer_started` ON `sync_attempts` (`peer_device_id`,`started_at`);\nCREATE TABLE IF NOT EXISTS `sync_scope_rejections` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `peer_device_id` text,\n `op_id` text NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `scope_id` text,\n `reason` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_peer_created` ON `sync_scope_rejections` (`peer_device_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_scope_created` ON `sync_scope_rejections` (`scope_id`,`created_at`);\nCREATE TABLE IF NOT EXISTS `sync_daemon_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `last_error` text,\n `last_traceback` text,\n `last_error_at` text,\n `last_ok_at` text,\n `phase` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_retention_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `last_run_at` text,\n `last_duration_ms` integer,\n `last_deleted_ops` integer DEFAULT 0 NOT NULL,\n `last_estimated_bytes_before` integer,\n `last_estimated_bytes_after` integer,\n `retained_floor_cursor` text,\n `last_error` text,\n `last_error_at` text\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_samples` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `created_at` text NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_stats` (\n `id` integer PRIMARY KEY NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `coordinator_group_preferences` (\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `projects_include_json` text,\n `projects_exclude_json` text,\n `auto_seed_scope` integer DEFAULT 1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`coordinator_id`, `group_id`)\n);\n\nCREATE TABLE IF NOT EXISTS `actors` (\n `actor_id` text PRIMARY KEY NOT NULL,\n `display_name` text NOT NULL,\n `is_local` integer DEFAULT 0 NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `merged_into_actor_id` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_actors_is_local` ON `actors` (`is_local`);\nCREATE INDEX IF NOT EXISTS `idx_actors_status` ON `actors` (`status`);", dn = "\nCREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n\nCREATE TABLE IF NOT EXISTS sync_retention_state (\n id INTEGER PRIMARY KEY,\n last_run_at TEXT,\n last_duration_ms INTEGER,\n last_deleted_ops INTEGER NOT NULL DEFAULT 0,\n last_estimated_bytes_before INTEGER,\n last_estimated_bytes_after INTEGER,\n retained_floor_cursor TEXT,\n last_error TEXT,\n last_error_at TEXT\n);\n\nCREATE TABLE IF NOT EXISTS maintenance_jobs (\n kind TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n status TEXT NOT NULL,\n message TEXT,\n progress_current INTEGER NOT NULL DEFAULT 0,\n progress_total INTEGER,\n progress_unit TEXT NOT NULL DEFAULT 'items',\n metadata_json TEXT,\n started_at TEXT,\n updated_at TEXT NOT NULL,\n finished_at TEXT,\n error TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated\n ON maintenance_jobs(status, updated_at);\n\nCREATE TABLE IF NOT EXISTS sync_scope_rejections (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n peer_device_id TEXT,\n op_id TEXT NOT NULL,\n entity_type TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n scope_id TEXT,\n reason TEXT NOT NULL,\n created_at TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n ON sync_scope_rejections(peer_device_id, created_at);\n\nCREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n ON sync_scope_rejections(scope_id, created_at);\n\n-- import_key is the primary lookup key from replication_ops.entity_id back to\n-- the source memory. The scope-backfill runner's selectReplicationOpScopeCandidates\n-- query joins on it for every unstamped op; without this index a Pi 4 with\n-- ~17k memories and ~35k ops scans the full memory_items table on every batch\n-- tick. The partial WHERE clause keeps the index small (most rows have\n-- import_key set; the few that don't aren't searchable anyway).\nCREATE INDEX IF NOT EXISTS idx_memory_items_import_key\n ON memory_items(import_key)\n WHERE import_key IS NOT NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n title, body_text, tags_text,\n content='memory_items',\n content_rowid='id'\n);\n\nCREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_au;\nCREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\nEND;\n\nDROP TRIGGER IF EXISTS memory_items_ad;\nCREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\nEND;\n\nCREATE TABLE IF NOT EXISTS memory_file_refs (\n memory_id INTEGER NOT NULL,\n file_path TEXT NOT NULL,\n relation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n PRIMARY KEY (memory_id, file_path, relation),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_file_refs_path\n ON memory_file_refs(file_path);\n\nCREATE TABLE IF NOT EXISTS memory_concept_refs (\n memory_id INTEGER NOT NULL,\n concept TEXT NOT NULL,\n PRIMARY KEY (memory_id, concept),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept\n ON memory_concept_refs(concept);\n\nCREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n projects_include_json TEXT,\n projects_exclude_json TEXT,\n auto_seed_scope INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id)\n);\n\nCREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n last_refresh_at TEXT NOT NULL,\n last_success_at TEXT,\n last_error TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id)\n);\n", fn = "\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_vectors USING vec0(\n embedding float[384],\n memory_id INTEGER,\n chunk_index INTEGER,\n content_hash TEXT,\n model TEXT\n);\n";
1343
1344
  function pn(e) {
1344
1345
  if (!Ln()) try {
1345
1346
  mn(e) || In(e), e.exec(fn);
@@ -1519,6 +1520,9 @@ function Hn(e) {
1519
1520
  try {
1520
1521
  e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_scope_visibility_created ON memory_items(scope_id, visibility, created_at)");
1521
1522
  } catch {}
1523
+ try {
1524
+ e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_scope_backfill_pending ON memory_items(id) WHERE scope_id IS NULL OR scope_id = ''");
1525
+ } catch {}
1522
1526
  }
1523
1527
  if (X(e, "replication_ops")) {
1524
1528
  Vn(e, "replication_ops", "scope_id", "TEXT");
@@ -14828,40 +14832,37 @@ function Tv(e, t = (/* @__PURE__ */ new Date()).toISOString()) {
14828
14832
  })();
14829
14833
  }
14830
14834
  function Ev(e) {
14831
- let t = e.prepare("SELECT COUNT(*) AS n\n FROM memory_items\n WHERE scope_id IS NULL OR TRIM(scope_id) = ''").get();
14835
+ let t = e.prepare("SELECT COUNT(*) AS n\n FROM memory_items\n WHERE scope_id IS NULL OR scope_id = ''").get();
14832
14836
  return Number(t?.n ?? 0);
14833
14837
  }
14834
14838
  function Dv(e) {
14835
- let t = e.prepare("SELECT MAX(id) AS max_id\n FROM memory_items\n WHERE scope_id IS NOT NULL AND TRIM(scope_id) <> ''").get();
14839
+ let t = e.prepare("SELECT MAX(id) AS max_id\n FROM memory_items\n WHERE scope_id IS NOT NULL AND scope_id <> ''").get();
14836
14840
  return Number(t?.max_id ?? 0);
14837
14841
  }
14838
14842
  function Ov(e) {
14839
- let t = e.prepare("SELECT COUNT(*) AS n\n FROM replication_ops\n WHERE entity_type = 'memory_item'\n AND (scope_id IS NULL OR TRIM(scope_id) = '')").get();
14843
+ let t = e.prepare("SELECT COUNT(*) AS n\n FROM replication_ops\n WHERE entity_type = 'memory_item'\n AND (scope_id IS NULL OR scope_id = '')").get();
14840
14844
  return Number(t?.n ?? 0);
14841
14845
  }
14842
14846
  function kv(e) {
14843
- if (e.prepare("SELECT 1\n FROM (SELECT ? AS scope_id UNION ALL SELECT ? AS scope_id) required\n WHERE NOT EXISTS (\n SELECT 1 FROM replication_scopes rs WHERE rs.scope_id = required.scope_id\n )\n LIMIT 1").get("local-default", "legacy-shared-review") || e.prepare("SELECT 1\n FROM memory_items\n WHERE scope_id IS NULL OR TRIM(scope_id) = ''\n LIMIT 1").get()) return !0;
14844
- let t = Ov(e);
14847
+ if (e.prepare("SELECT 1\n FROM (SELECT ? AS scope_id UNION ALL SELECT ? AS scope_id) required\n WHERE NOT EXISTS (\n SELECT 1 FROM replication_scopes rs WHERE rs.scope_id = required.scope_id\n )\n LIMIT 1").get("local-default", "legacy-shared-review") || e.prepare("SELECT 1\n FROM memory_items\n WHERE scope_id IS NULL OR scope_id = ''\n LIMIT 1").get()) return !0;
14848
+ let t = Ov(e), n = Q(e, bv);
14849
+ if (n?.status === "running") return !0;
14845
14850
  if (t === 0) return !1;
14846
- let n = Q(e, bv);
14847
14851
  if (!n || n.status !== "completed") return !0;
14848
14852
  let r = n.metadata ?? {}, i = r.unstamped_replication_ops_at_completion;
14849
14853
  if (typeof i != "number" || t > i) return !0;
14850
14854
  let a = r.max_stamped_memory_id_at_completion;
14851
- return typeof a == "number" ? !!e.prepare("SELECT 1\n FROM memory_items\n WHERE id > ?\n AND scope_id IS NOT NULL AND TRIM(scope_id) <> ''\n LIMIT 1").get(a) : !0;
14855
+ return typeof a == "number" ? !!e.prepare("SELECT 1\n FROM memory_items\n WHERE id > ?\n AND scope_id IS NOT NULL AND scope_id <> ''\n LIMIT 1").get(a) : !0;
14852
14856
  }
14853
14857
  function Av(e, t) {
14854
- return e.prepare("SELECT\n mi.id,\n mi.visibility,\n mi.workspace_id,\n mi.workspace_kind,\n s.project,\n s.cwd,\n s.git_remote\n FROM memory_items mi\n LEFT JOIN sessions s ON s.id = mi.session_id\n WHERE mi.scope_id IS NULL OR TRIM(mi.scope_id) = ''\n ORDER BY mi.id ASC\n LIMIT ?").all(t);
14858
+ return e.prepare("SELECT\n mi.id,\n mi.visibility,\n mi.workspace_id,\n mi.workspace_kind,\n s.project,\n s.cwd,\n s.git_remote\n FROM memory_items AS mi INDEXED BY idx_memory_items_scope_backfill_pending\n LEFT JOIN sessions s ON s.id = mi.session_id\n WHERE mi.scope_id IS NULL OR mi.scope_id = ''\n ORDER BY mi.id ASC\n LIMIT ?").all(t);
14855
14859
  }
14856
14860
  function jv(e, t) {
14857
- return e.prepare("SELECT op_id, entity_id, created_at\n FROM (\n SELECT ro.op_id, ro.entity_id, ro.created_at\n FROM replication_ops ro\n INNER JOIN memory_items mi ON mi.import_key = ro.entity_id\n WHERE ro.entity_type = 'memory_item'\n AND (ro.scope_id IS NULL OR TRIM(ro.scope_id) = '')\n AND mi.scope_id IS NOT NULL\n AND TRIM(mi.scope_id) != ''\n UNION\n SELECT ro.op_id, ro.entity_id, ro.created_at\n FROM replication_ops ro\n INNER JOIN memory_items mi ON mi.id = CAST(ro.entity_id AS INTEGER)\n WHERE ro.entity_type = 'memory_item'\n AND (ro.scope_id IS NULL OR TRIM(ro.scope_id) = '')\n AND mi.scope_id IS NOT NULL\n AND TRIM(mi.scope_id) != ''\n AND CAST(mi.id AS TEXT) = ro.entity_id\n )\n ORDER BY created_at ASC, op_id ASC\n LIMIT ?").all(t);
14861
+ return e.prepare("SELECT op_id, entity_id, scope_id, created_at\n FROM (\n SELECT ro.op_id, ro.entity_id, mi.scope_id, ro.created_at\n FROM replication_ops ro\n INNER JOIN memory_items mi ON mi.import_key = ro.entity_id\n WHERE ro.entity_type = 'memory_item'\n AND (ro.scope_id IS NULL OR ro.scope_id = '')\n AND mi.scope_id IS NOT NULL\n AND mi.scope_id != ''\n UNION ALL\n SELECT ro.op_id, ro.entity_id, mi.scope_id, ro.created_at\n FROM replication_ops ro\n INNER JOIN memory_items mi ON mi.id = CAST(ro.entity_id AS INTEGER)\n WHERE ro.entity_type = 'memory_item'\n AND (ro.scope_id IS NULL OR ro.scope_id = '')\n AND mi.scope_id IS NOT NULL\n AND mi.scope_id != ''\n AND CAST(mi.id AS TEXT) = ro.entity_id\n AND NOT EXISTS (\n SELECT 1\n FROM memory_items import_match\n WHERE import_match.import_key = ro.entity_id\n AND import_match.scope_id IS NOT NULL\n AND import_match.scope_id != ''\n LIMIT 1\n )\n )\n ORDER BY created_at ASC, op_id ASC\n LIMIT ?").all(t);
14858
14862
  }
14859
- function Mv(e, t) {
14860
- return xv(e.prepare("SELECT scope_id\n FROM memory_items\n WHERE (import_key = ? OR CAST(id AS TEXT) = ?)\n AND scope_id IS NOT NULL\n AND TRIM(scope_id) != ''\n ORDER BY CASE WHEN import_key = ? THEN 0 ELSE 1 END, id ASC\n LIMIT 1").get(t, t, t)?.scope_id);
14861
- }
14862
- function Nv(e, t = {}) {
14863
- let n = Math.max(1, t.memoryLimit ?? 250), r = Math.max(1, t.replicationOpLimit ?? n), i = Tv(e, t.now), a = Av(e, n), o = e.prepare("UPDATE memory_items\n SET scope_id = ?\n WHERE id = ?\n AND (scope_id IS NULL OR TRIM(scope_id) = '')"), s = e.prepare("UPDATE replication_ops\n SET scope_id = ?\n WHERE op_id = ?\n AND (scope_id IS NULL OR TRIM(scope_id) = '')"), c = e.transaction(() => {
14864
- let t = 0, n = 0, i = 0;
14863
+ function Mv(e, t = {}) {
14864
+ let n = Math.max(1, t.memoryLimit ?? 250), r = Math.max(1, t.replicationOpLimit ?? n), i = Tv(e, t.now), a = Av(e, n), o = e.prepare("UPDATE memory_items\n SET scope_id = ?\n WHERE id = ?\n AND (scope_id IS NULL OR scope_id = '')"), s = e.prepare("UPDATE replication_ops\n SET scope_id = ?\n WHERE op_id = ?\n AND (scope_id IS NULL OR scope_id = '')"), c = e.transaction(() => {
14865
+ let t = 0, i = 0, c = 0;
14865
14866
  for (let e of a) {
14866
14867
  let n = Cv({
14867
14868
  visibility: e.visibility,
@@ -14873,20 +14874,20 @@ function Nv(e, t = {}) {
14873
14874
  });
14874
14875
  t += Number(o.run(n.scopeId, e.id).changes ?? 0);
14875
14876
  }
14876
- let c = jv(e, r);
14877
- for (let t of c) {
14878
- let r = Mv(e, t.entity_id);
14879
- if (!r) {
14880
- i += 1;
14877
+ let l = a.length >= n ? [] : jv(e, r);
14878
+ for (let e of l) {
14879
+ let t = xv(e.scope_id);
14880
+ if (!t) {
14881
+ c += 1;
14881
14882
  continue;
14882
14883
  }
14883
- n += Number(s.run(r, t.op_id).changes ?? 0);
14884
+ i += Number(s.run(t, e.op_id).changes ?? 0);
14884
14885
  }
14885
14886
  return {
14886
- checkedReplicationOps: c.length,
14887
+ checkedReplicationOps: l.length,
14887
14888
  updatedMemoryItems: t,
14888
- updatedReplicationOps: n,
14889
- skippedReplicationOps: i
14889
+ updatedReplicationOps: i,
14890
+ skippedReplicationOps: c
14890
14891
  };
14891
14892
  })();
14892
14893
  return {
@@ -14900,40 +14901,47 @@ function Nv(e, t = {}) {
14900
14901
  remainingReplicationOps: Ov(e)
14901
14902
  };
14902
14903
  }
14903
- function Pv(e) {
14904
+ function Nv(e) {
14904
14905
  return Q(e, "scope_id_backfill")?.metadata ?? {};
14905
14906
  }
14907
+ function Pv(e) {
14908
+ return Number(e.seeded_scopes ?? 0) + Number(e.processed_memories ?? 0) + Number(e.processed_replication_ops ?? 0);
14909
+ }
14906
14910
  async function Fv(e, t = {}) {
14907
- let n = Math.max(1, t.batchSize ?? 250), r = Q(e, bv), i = Pv(e), a = !r || r.status === "completed" || r.status === "failed", o = Ev(e), s = Ov(e), c = wv(e), l = o + s + c;
14911
+ let n = Math.max(1, t.batchSize ?? 250), r = Q(e, bv), i = Nv(e), a = !r || r.status === "completed" || r.status === "failed", o = Ev(e), s = Ov(e), c = wv(e), l = o + s + c;
14908
14912
  if (l <= 0) {
14909
14913
  let t = !!i.exhausted_in_previous_pass;
14910
- return r && r.status !== "completed" ? t ? (Yr(e, bv, {
14911
- message: "Scope backfill complete",
14912
- progressCurrent: Number(i.processed_memories ?? 0),
14913
- progressTotal: Number(i.processed_memories ?? 0),
14914
- metadata: {
14915
- ...i,
14916
- remaining_memories: 0,
14917
- remaining_replication_ops: 0,
14918
- unstamped_replication_ops_at_completion: Ov(e),
14919
- max_stamped_memory_id_at_completion: Dv(e)
14920
- }
14921
- }), !1) : (Jr(e, bv, {
14922
- message: "Scope backfill quiescent — confirming on next tick",
14923
- progressCurrent: Number(i.processed_memories ?? 0),
14924
- progressTotal: Number(i.processed_memories ?? 0),
14925
- metadata: {
14926
- ...i,
14927
- remaining_memories: 0,
14928
- remaining_replication_ops: 0,
14929
- exhausted_in_previous_pass: !0
14930
- }
14931
- }), !0) : !1;
14914
+ if (r && r.status !== "completed") {
14915
+ let n = Pv(i);
14916
+ return t ? (Yr(e, bv, {
14917
+ message: "Sharing-domain backfill complete; future startup should be quieter",
14918
+ progressCurrent: n,
14919
+ progressTotal: n,
14920
+ metadata: {
14921
+ ...i,
14922
+ remaining_memories: 0,
14923
+ remaining_replication_ops: 0,
14924
+ unstamped_replication_ops_at_completion: Ov(e),
14925
+ max_stamped_memory_id_at_completion: Dv(e)
14926
+ }
14927
+ }), !1) : (Jr(e, bv, {
14928
+ message: "Sharing-domain backfill quiescent — confirming on next tick",
14929
+ progressCurrent: n,
14930
+ progressTotal: n + 1,
14931
+ metadata: {
14932
+ ...i,
14933
+ remaining_memories: 0,
14934
+ remaining_replication_ops: 0,
14935
+ exhausted_in_previous_pass: !0
14936
+ }
14937
+ }), !0);
14938
+ }
14939
+ return !1;
14932
14940
  }
14933
14941
  a && qr(e, {
14934
14942
  kind: bv,
14935
- title: "Backfilling sharing domains",
14936
- message: `Backfilling ${l} legacy scope item(s)`,
14943
+ title: "Backfilling Sharing domains",
14944
+ message: `Backfilling ${l} legacy Sharing-domain item(s), including memories and replication ops`,
14937
14945
  progressTotal: l,
14938
14946
  metadata: {
14939
14947
  seeded_scopes: 0,
@@ -14946,10 +14954,10 @@ async function Fv(e, t = {}) {
14946
14954
  remaining_replication_ops: s
14947
14955
  }
14948
14956
  });
14949
- let u = Nv(e, {
14957
+ let u = Mv(e, {
14950
14958
  memoryLimit: n,
14951
14959
  replicationOpLimit: n
14952
- }), d = a ? {} : i, f = Number(d.seeded_scopes ?? 0) + u.seededScopes, p = Number(d.processed_memories ?? 0) + u.checkedMemoryItems, m = Number(d.updated_memories ?? 0) + u.updatedMemoryItems, h = Number(d.processed_replication_ops ?? 0) + u.checkedReplicationOps, g = Number(d.updated_replication_ops ?? 0) + u.updatedReplicationOps, _ = Number(d.skipped_replication_ops ?? 0) + u.skippedReplicationOps, v = u.remainingMemoryItems, y = u.checkedReplicationOps === 0, b = wv(e), x = v === 0 && y && b === 0, S = !!d.exhausted_in_previous_pass, C = x && S, w = Math.max(l - (v + b + +!y), 0), ee = {
14960
+ }), d = a ? {} : i, f = Number(d.seeded_scopes ?? 0) + u.seededScopes, p = Number(d.processed_memories ?? 0) + u.checkedMemoryItems, m = Number(d.updated_memories ?? 0) + u.updatedMemoryItems, h = Number(d.processed_replication_ops ?? 0) + u.checkedReplicationOps, g = Number(d.updated_replication_ops ?? 0) + u.updatedReplicationOps, _ = Number(d.skipped_replication_ops ?? 0) + u.skippedReplicationOps, v = u.remainingMemoryItems, y = u.checkedReplicationOps === 0, b = wv(e), x = v === 0 && y && b === 0, S = !!d.exhausted_in_previous_pass, C = x && S, w = f + p + h, ee = !C && v === 0 && u.remainingReplicationOps === 0 && b === 0, T = Math.max(w + v + u.remainingReplicationOps + b + +!!ee, w), te = {
14953
14961
  seeded_scopes: f,
14954
14962
  processed_memories: p,
14955
14963
  updated_memories: m,
@@ -14961,19 +14969,19 @@ async function Fv(e, t = {}) {
14961
14969
  exhausted_in_previous_pass: x
14962
14970
  };
14963
14971
  return C ? (Yr(e, bv, {
14964
- message: "Scope backfill complete",
14965
- progressCurrent: l,
14966
- progressTotal: l,
14972
+ message: "Sharing-domain backfill complete; future startup should be quieter",
14973
+ progressCurrent: T,
14974
+ progressTotal: T,
14967
14975
  metadata: {
14968
- ...ee,
14976
+ ...te,
14969
14977
  unstamped_replication_ops_at_completion: Ov(e),
14970
14978
  max_stamped_memory_id_at_completion: Dv(e)
14971
14979
  }
14972
14980
  }), !1) : (Jr(e, bv, {
14973
- message: `Backfilled sharing domains for ${w} of ${l} item(s)`,
14981
+ message: `Backfilled Sharing domains for ${w} of ${T} item(s), including memories and replication ops`,
14974
14982
  progressCurrent: w,
14975
- progressTotal: l,
14976
- metadata: ee
14983
+ progressTotal: T,
14984
+ metadata: te
14977
14985
  }), !0);
14978
14986
  }
14979
14987
  var Iv = class {
@@ -14991,7 +14999,7 @@ var Iv = class {
14991
14999
  this.active || (this.active = !0, this.schedule(100));
14992
15000
  }
14993
15001
  async stop() {
14994
- this.active = !1, this.timer &&= (clearTimeout(this.timer), null), this.currentRun && await this.currentRun;
15002
+ this.active = !1, this.timer &&= (clearTimeout(this.timer), null), !this.signal?.aborted && this.currentRun && await this.currentRun;
14995
15003
  }
14996
15004
  schedule(e) {
14997
15005
  !this.active || this.signal?.aborted || (this.timer = setTimeout(() => {
@@ -15008,42 +15016,52 @@ var Iv = class {
15008
15016
  try {
15009
15017
  e = Mn(this.dbPath), await Fv(e, { batchSize: this.batchSize }) || (this.active = !1);
15010
15018
  } catch (t) {
15019
+ if (Lv(t)) {
15020
+ console.warn("Scope backfill runner deferred because the database is busy", t);
15021
+ return;
15022
+ }
15011
15023
  e && Xr(e, bv, t instanceof Error ? t.message : String(t)), console.warn("Scope backfill runner failed", t);
15012
15024
  } finally {
15013
15025
  e?.close();
15014
15026
  }
15015
15027
  }
15016
15028
  };
15029
+ function Lv(e) {
15030
+ let t = typeof e == "object" && e ? String(e.code ?? "") : "";
15031
+ if (t === "SQLITE_BUSY" || t === "SQLITE_LOCKED") return !0;
15032
+ let n = e instanceof Error ? e.message : String(e);
15033
+ return /database is (?:locked|busy)/i.test(n);
15034
+ }
15017
15035
  //#endregion
15018
15036
  //#region src/project-scope-settings.ts
15019
- function Lv(e) {
15037
+ function Rv(e) {
15020
15038
  return e?.trim() || null;
15021
15039
  }
15022
- function Rv(e) {
15023
- let t = Lv(e);
15040
+ function zv(e) {
15041
+ let t = Rv(e);
15024
15042
  return t ? t.replaceAll("\\", "/").replace(/\/+$/, "") || t : null;
15025
15043
  }
15026
- function zv(e, t) {
15044
+ function Bv(e, t) {
15027
15045
  return e?.label || t;
15028
15046
  }
15029
- function Bv(e) {
15047
+ function Vv(e) {
15030
15048
  return new Map(e.map((e) => [e.scope_id, e]));
15031
15049
  }
15032
- function Vv(e) {
15050
+ function Hv(e) {
15033
15051
  return !e || e.scope_id === "local-default" ? !1 : e.authority_type === "local" ? e.kind === "team" || e.kind === "org" || e.kind === "client" : !0;
15034
15052
  }
15035
- function Hv(e) {
15053
+ function Uv(e) {
15036
15054
  return /[*?]/.test(e);
15037
15055
  }
15038
- function Uv(e) {
15056
+ function Wv(e) {
15039
15057
  let t = e.search(/[*?]/);
15040
15058
  return (t >= 0 ? e.slice(0, t) : e).replace(/\/+$/, "");
15041
15059
  }
15042
- function Wv(e) {
15043
- let t = Uv(e.replaceAll("\\", "/"));
15060
+ function Gv(e) {
15061
+ let t = Wv(e.replaceAll("\\", "/"));
15044
15062
  return t === "~" || /^\/Users\/[^/]+$/i.test(t) || /^\/home\/[^/]+$/i.test(t) || /^\/var\/home\/[^/]+$/i.test(t) || /^[A-Z]:\/Users\/[^/]+$/i.test(t);
15045
15063
  }
15046
- function Gv(e) {
15064
+ function Kv(e) {
15047
15065
  let t = JSON.stringify({
15048
15066
  code: e.code,
15049
15067
  mapping_id: e.mapping_id ?? null,
@@ -15055,18 +15073,18 @@ function Gv(e) {
15055
15073
  });
15056
15074
  return `psg_${u("sha256").update(t).digest("hex").slice(0, 32)}`;
15057
15075
  }
15058
- function Kv(e) {
15076
+ function qv(e) {
15059
15077
  return e.requires_confirmation ? {
15060
15078
  ...e,
15061
- confirmation_token: Gv(e)
15079
+ confirmation_token: Kv(e)
15062
15080
  } : e;
15063
15081
  }
15064
- function qv(e, t) {
15082
+ function Jv(e, t) {
15065
15083
  if (e.workspace_identity) return [];
15066
- let n = Rv(e.project_pattern) ?? e.project_pattern, r = t.get(e.scope_id);
15067
- if (!Vv(r)) return [];
15068
- let i = zv(r, e.scope_id), a = [];
15069
- return Hv(n) && a.push({
15084
+ let n = zv(e.project_pattern) ?? e.project_pattern, r = t.get(e.scope_id);
15085
+ if (!Hv(r)) return [];
15086
+ let i = Bv(r, e.scope_id), a = [];
15087
+ return Uv(n) && a.push({
15070
15088
  code: "broad_org_domain_pattern",
15071
15089
  severity: "warning",
15072
15090
  message: `Wildcard project pattern ${n} can catch multiple projects. Review before attaching it to ${i}.`,
@@ -15074,7 +15092,7 @@ function qv(e, t) {
15074
15092
  scope_id: e.scope_id,
15075
15093
  mapping_id: e.id ?? null,
15076
15094
  project_pattern: e.project_pattern
15077
- }), Wv(n) && a.push({
15095
+ }), Gv(n) && a.push({
15078
15096
  code: "home_directory_org_domain_pattern",
15079
15097
  severity: "warning",
15080
15098
  message: `Home-directory project pattern ${n} can mix personal and work projects. Review before attaching it to ${i}.`,
@@ -15082,20 +15100,20 @@ function qv(e, t) {
15082
15100
  scope_id: e.scope_id,
15083
15101
  mapping_id: e.id ?? null,
15084
15102
  project_pattern: e.project_pattern
15085
- }), a.map(Kv);
15086
- }
15087
- function Jv(e) {
15088
- return (Lv(e.project) ?? Lv(e.display_project) ?? e.workspace_identity).toLowerCase();
15103
+ }), a.map(qv);
15089
15104
  }
15090
15105
  function Yv(e) {
15106
+ return (Rv(e.project) ?? Rv(e.display_project) ?? e.workspace_identity).toLowerCase();
15107
+ }
15108
+ function Xv(e) {
15091
15109
  let t = /* @__PURE__ */ new Map();
15092
15110
  for (let n of e) {
15093
- let e = Jv(n);
15111
+ let e = Yv(n);
15094
15112
  t.set(e, [...t.get(e) ?? [], n]);
15095
15113
  }
15096
15114
  return t;
15097
15115
  }
15098
- function Xv(e, t) {
15116
+ function Zv(e, t) {
15099
15117
  let n = [];
15100
15118
  e.resolution_reason === "local_default" && n.push({
15101
15119
  code: "unknown_project_local_only",
@@ -15105,7 +15123,7 @@ function Xv(e, t) {
15105
15123
  workspace_identity: e.workspace_identity,
15106
15124
  scope_id: Ti
15107
15125
  });
15108
- let r = (t.get(Jv(e)) ?? []).filter((t) => t.workspace_identity !== e.workspace_identity);
15126
+ let r = (t.get(Yv(e)) ?? []).filter((t) => t.workspace_identity !== e.workspace_identity);
15109
15127
  return r.length > 0 && n.push({
15110
15128
  code: "basename_collision_review",
15111
15129
  severity: "warning",
@@ -15114,16 +15132,16 @@ function Xv(e, t) {
15114
15132
  workspace_identity: e.workspace_identity,
15115
15133
  related_workspace_identities: r.map((e) => e.workspace_identity),
15116
15134
  related_projects: r.map((e) => e.display_project)
15117
- }), n.map(Kv);
15135
+ }), n.map(qv);
15118
15136
  }
15119
- function Zv(e) {
15120
- let t = Yv(e);
15137
+ function Qv(e) {
15138
+ let t = Xv(e);
15121
15139
  return e.map((e) => ({
15122
15140
  ...e,
15123
- guardrail_warnings: Xv(e, t)
15141
+ guardrail_warnings: Zv(e, t)
15124
15142
  }));
15125
15143
  }
15126
- function Qv(e) {
15144
+ function $v(e) {
15127
15145
  let t = /* @__PURE__ */ new Set();
15128
15146
  return e.filter((e) => {
15129
15147
  let n = [
@@ -15134,28 +15152,28 @@ function Qv(e) {
15134
15152
  e.related_workspace_identities?.join("|") ?? ""
15135
15153
  ].join("\0");
15136
15154
  return t.has(n) ? !1 : (t.add(n), !0);
15137
- }).map(Kv);
15155
+ }).map(qv);
15138
15156
  }
15139
- function $v(e, t) {
15157
+ function ey(e, t) {
15140
15158
  if (!e && !/[\\/:]/.test(t) && !(/[*?]/.test(t) && /[\\/:]/.test(t.replace(/[*?]/g, "")))) throw Error("project_pattern must use a canonical path, remote, or workspace pattern");
15141
15159
  }
15142
- function ey(e) {
15160
+ function ty(e) {
15143
15161
  return {
15144
15162
  scope_id: String(e.scope_id ?? ""),
15145
15163
  label: String(e.label ?? ""),
15146
15164
  kind: String(e.kind ?? "user"),
15147
15165
  authority_type: String(e.authority_type ?? "local"),
15148
- coordinator_id: Lv(e.coordinator_id),
15149
- group_id: Lv(e.group_id),
15166
+ coordinator_id: Rv(e.coordinator_id),
15167
+ group_id: Rv(e.group_id),
15150
15168
  membership_epoch: Number(e.membership_epoch ?? 0),
15151
15169
  status: String(e.status ?? "active"),
15152
15170
  updated_at: String(e.updated_at ?? "")
15153
15171
  };
15154
15172
  }
15155
- function ty(e) {
15173
+ function ny(e) {
15156
15174
  return {
15157
15175
  id: Number(e.id ?? 0),
15158
- workspace_identity: Rv(e.workspace_identity),
15176
+ workspace_identity: zv(e.workspace_identity),
15159
15177
  project_pattern: String(e.project_pattern ?? ""),
15160
15178
  scope_id: String(e.scope_id ?? ""),
15161
15179
  priority: Number(e.priority ?? 0),
@@ -15165,54 +15183,54 @@ function ty(e) {
15165
15183
  guardrail_warnings: []
15166
15184
  };
15167
15185
  }
15168
- function ny(e) {
15169
- return Tv(e), e.prepare("SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n membership_epoch, status, updated_at\n FROM replication_scopes\n WHERE status = 'active'\n ORDER BY CASE WHEN scope_id = ? THEN 0 ELSE 1 END, label COLLATE NOCASE, scope_id").all(Ti).map((e) => ey(e));
15170
- }
15171
15186
  function ry(e) {
15187
+ return Tv(e), e.prepare("SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n membership_epoch, status, updated_at\n FROM replication_scopes\n WHERE status = 'active'\n ORDER BY CASE WHEN scope_id = ? THEN 0 ELSE 1 END, label COLLATE NOCASE, scope_id").all(Ti).map((e) => ty(e));
15188
+ }
15189
+ function iy(e) {
15172
15190
  Tv(e);
15173
- let t = Bv(ny(e));
15191
+ let t = Vv(ry(e));
15174
15192
  return e.prepare("SELECT id, workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at\n FROM project_scope_mappings\n ORDER BY priority DESC, updated_at DESC, id DESC").all().map((e) => {
15175
- let n = ty(e);
15193
+ let n = ny(e);
15176
15194
  return {
15177
15195
  ...n,
15178
- guardrail_warnings: qv(n, t)
15196
+ guardrail_warnings: Jv(n, t)
15179
15197
  };
15180
15198
  });
15181
15199
  }
15182
- function iy(e, t) {
15200
+ function ay(e, t) {
15183
15201
  let n = e.prepare("SELECT id, workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at\n FROM project_scope_mappings\n WHERE id = ?\n LIMIT 1").get(t);
15184
- return n ? ty(n) : null;
15202
+ return n ? ny(n) : null;
15185
15203
  }
15186
- function ay(e, t) {
15204
+ function oy(e, t) {
15187
15205
  let n = e.prepare("SELECT id, workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at\n FROM project_scope_mappings\n WHERE workspace_identity = ?\n ORDER BY priority DESC, updated_at DESC, id DESC\n LIMIT 1").get(t);
15188
- return n ? ty(n) : null;
15206
+ return n ? ny(n) : null;
15189
15207
  }
15190
- function oy(e, t) {
15208
+ function sy(e, t) {
15191
15209
  if (!e.prepare("SELECT 1 FROM replication_scopes WHERE scope_id = ? AND status = 'active' LIMIT 1").get(t)) throw Error(`scope_id ${t} is not an active Sharing domain`);
15192
15210
  }
15193
- function sy(e, t) {
15194
- let n = t.id == null ? null : Number(t.id), r = n && Number.isInteger(n) ? iy(e, n) : null, i = Rv(t.workspace_identity) ?? r?.workspace_identity ?? null, a = i ? ay(e, i) : null, o = r ?? a, s = Lv(t.project_pattern) ?? o?.project_pattern ?? i, c = t.priority == null ? o?.priority ?? 0 : Number(t.priority);
15211
+ function cy(e, t) {
15212
+ let n = t.id == null ? null : Number(t.id), r = n && Number.isInteger(n) ? ay(e, n) : null, i = zv(t.workspace_identity) ?? r?.workspace_identity ?? null, a = i ? oy(e, i) : null, o = r ?? a, s = Rv(t.project_pattern) ?? o?.project_pattern ?? i, c = t.priority == null ? o?.priority ?? 0 : Number(t.priority);
15195
15213
  return {
15196
15214
  existing: o,
15197
15215
  workspaceIdentity: i,
15198
15216
  projectPattern: s,
15199
- scopeId: Lv(t.scope_id) ?? "",
15217
+ scopeId: Rv(t.scope_id) ?? "",
15200
15218
  priority: c,
15201
- source: Lv(t.source) ?? "user"
15219
+ source: Rv(t.source) ?? "user"
15202
15220
  };
15203
15221
  }
15204
- function cy(e, t) {
15222
+ function ly(e, t) {
15205
15223
  Tv(e);
15206
- let n = sy(e, t), r = Bv(ny(e)), i = [];
15207
- n.projectPattern && n.scopeId && i.push(...qv({
15224
+ let n = cy(e, t), r = Vv(ry(e)), i = [];
15225
+ n.projectPattern && n.scopeId && i.push(...Jv({
15208
15226
  id: n.existing?.id ?? 0,
15209
15227
  workspace_identity: n.workspaceIdentity,
15210
15228
  project_pattern: n.projectPattern,
15211
15229
  scope_id: n.scopeId
15212
15230
  }, r));
15213
- let a = n.workspaceIdentity ? ly(e).find((e) => e.workspace_identity === n.workspaceIdentity) : null, o = r.get(n.scopeId);
15214
- if (a && i.push(...a.guardrail_warnings.filter((e) => e.code !== "basename_collision_review" || Vv(o))), n.scopeId && n.existing && n.existing.scope_id !== n.scopeId) {
15215
- let e = zv(r.get(n.existing.scope_id), n.existing.scope_id), t = zv(r.get(n.scopeId), n.scopeId);
15231
+ let a = n.workspaceIdentity ? uy(e).find((e) => e.workspace_identity === n.workspaceIdentity) : null, o = r.get(n.scopeId);
15232
+ if (a && i.push(...a.guardrail_warnings.filter((e) => e.code !== "basename_collision_review" || Hv(o))), n.scopeId && n.existing && n.existing.scope_id !== n.scopeId) {
15233
+ let e = Bv(r.get(n.existing.scope_id), n.existing.scope_id), t = Bv(r.get(n.scopeId), n.scopeId);
15216
15234
  i.push({
15217
15235
  code: "scope_reassignment_old_copies",
15218
15236
  severity: "warning",
@@ -15230,12 +15248,12 @@ function cy(e, t) {
15230
15248
  requested_scope_id: n.scopeId,
15231
15249
  requested_workspace_identity: n.workspaceIdentity,
15232
15250
  requested_project_pattern: n.projectPattern,
15233
- warnings: Qv(i)
15251
+ warnings: $v(i)
15234
15252
  };
15235
15253
  }
15236
- function ly(e, t = {}) {
15254
+ function uy(e, t = {}) {
15237
15255
  Tv(e);
15238
- let n = Math.max(1, Math.min(t.limit ?? 250, 1e3)), r = ry(e), i = e.prepare("SELECT\n s.id,\n s.started_at,\n s.cwd,\n s.project,\n s.git_remote,\n s.git_branch,\n (\n SELECT mi.workspace_id\n FROM memory_items mi\n WHERE mi.session_id = s.id\n AND mi.workspace_id IS NOT NULL\n AND TRIM(mi.workspace_id) <> ''\n ORDER BY mi.id DESC\n LIMIT 1\n ) AS workspace_id\n FROM sessions s\n WHERE COALESCE(TRIM(s.git_remote), TRIM(s.cwd), TRIM(s.project), '') <> ''\n OR EXISTS (SELECT 1 FROM memory_items mi_candidate WHERE mi_candidate.session_id = s.id)\n ORDER BY s.started_at DESC, s.id DESC\n LIMIT ?").all(n), a = /* @__PURE__ */ new Set(), o = [];
15256
+ let n = Math.max(1, Math.min(t.limit ?? 250, 1e3)), r = iy(e), i = e.prepare("SELECT\n s.id,\n s.started_at,\n s.cwd,\n s.project,\n s.git_remote,\n s.git_branch,\n (\n SELECT mi.workspace_id\n FROM memory_items mi\n WHERE mi.session_id = s.id\n AND mi.workspace_id IS NOT NULL\n AND TRIM(mi.workspace_id) <> ''\n ORDER BY mi.id DESC\n LIMIT 1\n ) AS workspace_id\n FROM sessions s\n WHERE COALESCE(TRIM(s.git_remote), TRIM(s.cwd), TRIM(s.project), '') <> ''\n OR EXISTS (SELECT 1 FROM memory_items mi_candidate WHERE mi_candidate.session_id = s.id)\n ORDER BY s.started_at DESC, s.id DESC\n LIMIT ?").all(n), a = /* @__PURE__ */ new Set(), o = [];
15239
15257
  for (let e of i) {
15240
15258
  let t = ji({
15241
15259
  gitRemote: e.git_remote,
@@ -15257,11 +15275,11 @@ function ly(e, t = {}) {
15257
15275
  o.push({
15258
15276
  workspace_identity: t.value,
15259
15277
  identity_source: t.source,
15260
- display_project: t.displayProject ?? Lv(e.project) ?? Lv(e.cwd) ?? t.value,
15261
- project: Lv(e.project),
15262
- cwd: Lv(e.cwd),
15263
- git_remote: Lv(e.git_remote),
15264
- git_branch: Lv(e.git_branch),
15278
+ display_project: t.displayProject ?? Rv(e.project) ?? Rv(e.cwd) ?? t.value,
15279
+ project: Rv(e.project),
15280
+ cwd: Rv(e.cwd),
15281
+ git_remote: Rv(e.git_remote),
15282
+ git_branch: Rv(e.git_branch),
15265
15283
  latest_session_at: e.started_at,
15266
15284
  resolved_scope_id: n.scopeId,
15267
15285
  resolution_reason: n.reason,
@@ -15270,48 +15288,48 @@ function ly(e, t = {}) {
15270
15288
  guardrail_warnings: []
15271
15289
  });
15272
15290
  }
15273
- return Zv(o.toSorted((e, t) => e.display_project.localeCompare(t.display_project) || e.workspace_identity.localeCompare(t.workspace_identity)));
15291
+ return Qv(o.toSorted((e, t) => e.display_project.localeCompare(t.display_project) || e.workspace_identity.localeCompare(t.workspace_identity)));
15274
15292
  }
15275
- function uy(e, t) {
15293
+ function dy(e, t) {
15276
15294
  Tv(e);
15277
- let n = sy(e, t), r = n.scopeId;
15295
+ let n = cy(e, t), r = n.scopeId;
15278
15296
  if (!r) throw Error("scope_id must be a non-empty string");
15279
- oy(e, r);
15297
+ sy(e, r);
15280
15298
  let { existing: i, workspaceIdentity: a } = n, o = n.projectPattern;
15281
15299
  if (!o) throw Error("project_pattern or workspace_identity is required");
15282
- $v(a, o);
15300
+ ey(a, o);
15283
15301
  let s = n.priority;
15284
15302
  if (!Number.isFinite(s) || !Number.isInteger(s)) throw Error("priority must be an integer");
15285
15303
  let c = n.source, l = (/* @__PURE__ */ new Date()).toISOString();
15286
15304
  if (i) {
15287
15305
  e.prepare("UPDATE project_scope_mappings\n SET workspace_identity = ?, project_pattern = ?, scope_id = ?, priority = ?, source = ?, updated_at = ?\n WHERE id = ?").run(a, o, r, s, c, l, i.id);
15288
- let t = iy(e, i.id);
15306
+ let t = ay(e, i.id);
15289
15307
  if (!t) throw Error("project_scope_mapping update returned no row");
15290
15308
  return t;
15291
15309
  }
15292
- let u = e.prepare("INSERT INTO project_scope_mappings(\n workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)").run(a, o, r, s, c, l, l), d = iy(e, Number(u.lastInsertRowid));
15310
+ let u = e.prepare("INSERT INTO project_scope_mappings(\n workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)").run(a, o, r, s, c, l, l), d = ay(e, Number(u.lastInsertRowid));
15293
15311
  if (!d) throw Error("project_scope_mapping insert returned no row");
15294
15312
  return d;
15295
15313
  }
15296
- function dy(e, t) {
15314
+ function fy(e, t) {
15297
15315
  if (!Number.isInteger(t) || t <= 0) throw Error("id must be a positive integer");
15298
15316
  let n = e.prepare("DELETE FROM project_scope_mappings WHERE id = ?").run(t);
15299
15317
  return Number(n.changes ?? 0) > 0;
15300
15318
  }
15301
15319
  //#endregion
15302
15320
  //#region src/raw-event-sweeper.ts
15303
- var fy = 60;
15304
- function py(e, t) {
15321
+ var py = 60;
15322
+ function my(e, t) {
15305
15323
  let n = process.env[e];
15306
15324
  if (n == null) return t;
15307
15325
  let r = Number.parseInt(n, 10);
15308
15326
  return Number.isFinite(r) ? r : t;
15309
15327
  }
15310
- function my(e) {
15328
+ function hy(e) {
15311
15329
  let t = (process.env[e] ?? "1").trim().toLowerCase();
15312
15330
  return t === "0" || t === "false" || t === "off";
15313
15331
  }
15314
- var hy = class {
15332
+ var gy = class {
15315
15333
  store;
15316
15334
  ingestOpts;
15317
15335
  active = !1;
@@ -15329,7 +15347,7 @@ var hy = class {
15329
15347
  this.store = e, this.ingestOpts = t;
15330
15348
  }
15331
15349
  enabled() {
15332
- return !my("CODEMEM_RAW_EVENTS_SWEEPER");
15350
+ return !hy("CODEMEM_RAW_EVENTS_SWEEPER");
15333
15351
  }
15334
15352
  intervalMs() {
15335
15353
  let e = process.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS;
@@ -15341,31 +15359,31 @@ var hy = class {
15341
15359
  return Number.isFinite(n) && n > 0 ? Math.max(1e3, n * 1e3) : 3e4;
15342
15360
  }
15343
15361
  idleMs() {
15344
- return py("CODEMEM_RAW_EVENTS_SWEEPER_IDLE_MS", 12e4);
15362
+ return my("CODEMEM_RAW_EVENTS_SWEEPER_IDLE_MS", 12e4);
15345
15363
  }
15346
15364
  limit() {
15347
- return py("CODEMEM_RAW_EVENTS_SWEEPER_LIMIT", 25);
15365
+ return my("CODEMEM_RAW_EVENTS_SWEEPER_LIMIT", 25);
15348
15366
  }
15349
15367
  workerMaxEvents() {
15350
- let e = py("CODEMEM_RAW_EVENTS_WORKER_MAX_EVENTS", 100);
15368
+ let e = my("CODEMEM_RAW_EVENTS_WORKER_MAX_EVENTS", 100);
15351
15369
  return e <= 0 ? null : e;
15352
15370
  }
15353
15371
  retentionMs() {
15354
- return py("CODEMEM_RAW_EVENTS_RETENTION_MS", 0);
15372
+ return my("CODEMEM_RAW_EVENTS_RETENTION_MS", 0);
15355
15373
  }
15356
15374
  autoFlushEnabled() {
15357
15375
  return (process.env.CODEMEM_RAW_EVENTS_AUTO_FLUSH ?? "").trim() === "1";
15358
15376
  }
15359
15377
  debounceMs() {
15360
- return py("CODEMEM_RAW_EVENTS_DEBOUNCE_MS", 6e4);
15378
+ return my("CODEMEM_RAW_EVENTS_DEBOUNCE_MS", 6e4);
15361
15379
  }
15362
15380
  stuckBatchMs() {
15363
- return py("CODEMEM_RAW_EVENTS_STUCK_BATCH_MS", 3e5);
15381
+ return my("CODEMEM_RAW_EVENTS_STUCK_BATCH_MS", 3e5);
15364
15382
  }
15365
15383
  handleAuthError(e) {
15366
- if (this.authBackoffUntil = Date.now() / 1e3 + fy, !this.authErrorLogged) {
15384
+ if (this.authBackoffUntil = Date.now() / 1e3 + py, !this.authErrorLogged) {
15367
15385
  this.authErrorLogged = !0;
15368
- let t = `codemem: observer auth error — backing off for ${fy}s. Refresh your provider credentials or update observer_provider in settings. (${e.message})`;
15386
+ let t = `codemem: observer auth error — backing off for ${py}s. Refresh your provider credentials or update observer_provider in settings. (${e.message})`;
15369
15387
  console.error(t);
15370
15388
  }
15371
15389
  }
@@ -15549,16 +15567,16 @@ var hy = class {
15549
15567
  }
15550
15568
  }
15551
15569
  }
15552
- }, gy = "memory_ref_backfill", _y = "mi.active = 1\n AND (\n (\n (\n (json_valid(mi.files_read) AND json_type(mi.files_read) = 'array' AND json_array_length(mi.files_read) > 0)\n OR\n (json_valid(mi.files_modified) AND json_type(mi.files_modified) = 'array' AND json_array_length(mi.files_modified) > 0)\n )\n AND NOT EXISTS (\n SELECT 1 FROM memory_file_refs mfr WHERE mfr.memory_id = mi.id\n )\n )\n OR\n (\n json_valid(mi.concepts)\n AND json_type(mi.concepts) = 'array'\n AND json_array_length(mi.concepts) > 0\n AND NOT EXISTS (\n SELECT 1 FROM memory_concept_refs mcr WHERE mcr.memory_id = mi.id\n )\n )\n )";
15553
- function vy(e) {
15570
+ }, _y = "memory_ref_backfill", vy = "mi.active = 1\n AND (\n (\n (\n (json_valid(mi.files_read) AND json_type(mi.files_read) = 'array' AND json_array_length(mi.files_read) > 0)\n OR\n (json_valid(mi.files_modified) AND json_type(mi.files_modified) = 'array' AND json_array_length(mi.files_modified) > 0)\n )\n AND NOT EXISTS (\n SELECT 1 FROM memory_file_refs mfr WHERE mfr.memory_id = mi.id\n )\n )\n OR\n (\n json_valid(mi.concepts)\n AND json_type(mi.concepts) = 'array'\n AND json_array_length(mi.concepts) > 0\n AND NOT EXISTS (\n SELECT 1 FROM memory_concept_refs mcr WHERE mcr.memory_id = mi.id\n )\n )\n )";
15571
+ function yy(e) {
15554
15572
  return e.prepare(`SELECT 1 FROM memory_items mi
15555
- WHERE ${_y}
15573
+ WHERE ${vy}
15556
15574
  LIMIT 1`).get() != null;
15557
15575
  }
15558
- function yy(e) {
15576
+ function by(e) {
15559
15577
  return Q(e, "memory_ref_backfill")?.metadata ?? {};
15560
15578
  }
15561
- function by(e) {
15579
+ function xy(e) {
15562
15580
  if (!e) return null;
15563
15581
  try {
15564
15582
  let t = JSON.parse(e);
@@ -15566,17 +15584,17 @@ function by(e) {
15566
15584
  } catch {}
15567
15585
  return null;
15568
15586
  }
15569
- async function xy(e, t = {}) {
15570
- let n = Q(e, gy), r = yy(e), i = Math.max(1, t.batchSize ?? 50), a = Number(r.last_cursor_id ?? 0), o = e.prepare(`SELECT mi.id, mi.files_read, mi.files_modified, mi.concepts
15587
+ async function Sy(e, t = {}) {
15588
+ let n = Q(e, _y), r = by(e), i = Math.max(1, t.batchSize ?? 50), a = Number(r.last_cursor_id ?? 0), o = e.prepare(`SELECT mi.id, mi.files_read, mi.files_modified, mi.concepts
15571
15589
  FROM memory_items mi
15572
15590
  WHERE mi.id > ?
15573
- AND ${_y}
15591
+ AND ${vy}
15574
15592
  ORDER BY mi.id ASC
15575
15593
  LIMIT ?`).all(a, i);
15576
15594
  if (o.length === 0) {
15577
15595
  if (n && n.status !== "completed") {
15578
15596
  let t = Number(r.processed ?? 0);
15579
- Yr(e, gy, {
15597
+ Yr(e, _y, {
15580
15598
  message: "Ref backfill complete",
15581
15599
  progressCurrent: t,
15582
15600
  progressTotal: Number(r.total_backfillable ?? t),
@@ -15592,9 +15610,9 @@ async function xy(e, t = {}) {
15592
15610
  let s = Number(r.processed ?? 0), c = Number(r.total_backfillable ?? 0);
15593
15611
  if (!n || n.status === "completed" || n.status === "failed") {
15594
15612
  let t = e.prepare(`SELECT COUNT(*) AS cnt FROM memory_items mi
15595
- WHERE ${_y}`).get().cnt;
15613
+ WHERE ${vy}`).get().cnt;
15596
15614
  qr(e, {
15597
- kind: gy,
15615
+ kind: _y,
15598
15616
  title: "Backfilling memory file/concept refs",
15599
15617
  message: `Backfilling refs for ${t} memories`,
15600
15618
  progressTotal: t,
@@ -15607,7 +15625,7 @@ async function xy(e, t = {}) {
15607
15625
  }), c = t;
15608
15626
  }
15609
15627
  let l = e.prepare("INSERT OR IGNORE INTO memory_file_refs (memory_id, file_path, relation) VALUES (?, ?, ?)"), u = e.prepare("INSERT OR IGNORE INTO memory_concept_refs (memory_id, concept) VALUES (?, ?)"), d = e.transaction((e) => {
15610
- let t = by(e.files_read), n = by(e.files_modified), r = by(e.concepts);
15628
+ let t = xy(e.files_read), n = xy(e.files_modified), r = xy(e.concepts);
15611
15629
  if (t) for (let n of t) n && l.run(e.id, n, "read");
15612
15630
  if (n) for (let t of n) t && l.run(e.id, t, "modified");
15613
15631
  if (r) for (let t of r) {
@@ -15618,8 +15636,8 @@ async function xy(e, t = {}) {
15618
15636
  for (let e of o) d(e);
15619
15637
  let f = s + o.length, p = o.length < i, m = o[o.length - 1].id;
15620
15638
  if (p) {
15621
- let t = Number(yy(e).total_backfillable ?? c ?? f);
15622
- return Yr(e, gy, {
15639
+ let t = Number(by(e).total_backfillable ?? c ?? f);
15640
+ return Yr(e, _y, {
15623
15641
  message: "Ref backfill complete",
15624
15642
  progressCurrent: f,
15625
15643
  progressTotal: t,
@@ -15631,7 +15649,7 @@ async function xy(e, t = {}) {
15631
15649
  }
15632
15650
  }), !1;
15633
15651
  }
15634
- return Jr(e, gy, {
15652
+ return Jr(e, _y, {
15635
15653
  message: `Backfilled refs for ${f} of ${c} memories`,
15636
15654
  progressCurrent: f,
15637
15655
  progressTotal: c,
@@ -15643,7 +15661,7 @@ async function xy(e, t = {}) {
15643
15661
  }
15644
15662
  }), !0;
15645
15663
  }
15646
- var Sy = class {
15664
+ var Cy = class {
15647
15665
  dbPath;
15648
15666
  signal;
15649
15667
  batchSize;
@@ -15673,14 +15691,14 @@ var Sy = class {
15673
15691
  if (!this.active || this.signal?.aborted) return;
15674
15692
  let e = null;
15675
15693
  try {
15676
- e = Mn(this.dbPath), await xy(e, { batchSize: this.batchSize }) || (this.active = !1);
15694
+ e = Mn(this.dbPath), await Sy(e, { batchSize: this.batchSize }) || (this.active = !1);
15677
15695
  } catch (t) {
15678
- e && Xr(e, gy, t instanceof Error ? t.message : String(t)), console.warn("Ref backfill runner failed", t);
15696
+ e && Xr(e, _y, t instanceof Error ? t.message : String(t)), console.warn("Ref backfill runner failed", t);
15679
15697
  } finally {
15680
15698
  e?.close();
15681
15699
  }
15682
15700
  }
15683
- }, Cy = "session_context_backfill", wy = [
15701
+ }, wy = "session_context_backfill", Ty = [
15684
15702
  "firstPrompt",
15685
15703
  "promptCount",
15686
15704
  "toolCount",
@@ -15688,20 +15706,20 @@ var Sy = class {
15688
15706
  "filesModified",
15689
15707
  "filesRead"
15690
15708
  ];
15691
- function Ty(e) {
15709
+ function Ey(e) {
15692
15710
  let t = e.prepare("SELECT COUNT(*) AS c FROM sessions\n WHERE json_extract(metadata_json, '$.session_context.flusher') = 'raw_events'").get();
15693
15711
  return Number(t?.c ?? 0);
15694
15712
  }
15695
- function Ey(e, t, n) {
15713
+ function Dy(e, t, n) {
15696
15714
  return e.prepare("SELECT\n s.id AS id,\n s.metadata_json AS metadata_json,\n os.source AS source,\n os.stream_id AS stream_id\n FROM sessions s\n LEFT JOIN (\n SELECT session_id, source, stream_id\n FROM opencode_sessions\n GROUP BY session_id\n ) os ON os.session_id = s.id\n WHERE s.id > ?\n AND json_extract(s.metadata_json, '$.session_context.flusher') = 'raw_events'\n ORDER BY s.id ASC\n LIMIT ?").all(t, n);
15697
15715
  }
15698
- function Dy(e, t, n) {
15716
+ function Oy(e, t, n) {
15699
15717
  return e.prepare("SELECT event_seq, event_type, ts_wall_ms, ts_mono_ms, payload_json, event_id\n FROM raw_events\n WHERE source = ? AND stream_id = ?\n ORDER BY event_seq ASC").all(t, n).map((e) => {
15700
15718
  let t = JSON.parse(e.payload_json);
15701
15719
  return t.type = t.type || e.event_type, t.timestamp_wall_ms = e.ts_wall_ms, t.timestamp_mono_ms = e.ts_mono_ms, t.event_seq = e.event_seq, t.event_id = e.event_id, t;
15702
15720
  });
15703
15721
  }
15704
- function Oy(e) {
15722
+ function ky(e) {
15705
15723
  if (!e) return {};
15706
15724
  try {
15707
15725
  let t = JSON.parse(e);
@@ -15709,42 +15727,42 @@ function Oy(e) {
15709
15727
  } catch {}
15710
15728
  return {};
15711
15729
  }
15712
- function ky(e) {
15730
+ function Ay(e) {
15713
15731
  return Array.isArray(e) ? [...e].sort() : e ?? null;
15714
15732
  }
15715
- function Ay(e, t) {
15716
- for (let n of wy) {
15717
- let r = ky(e[n]), i = ky(t[n]);
15733
+ function jy(e, t) {
15734
+ for (let n of Ty) {
15735
+ let r = Ay(e[n]), i = Ay(t[n]);
15718
15736
  if (JSON.stringify(r) !== JSON.stringify(i)) return !0;
15719
15737
  }
15720
15738
  return !1;
15721
15739
  }
15722
- function jy(e, t) {
15740
+ function My(e, t) {
15723
15741
  let n = { ...e };
15724
- for (let e of wy) {
15742
+ for (let e of Ty) {
15725
15743
  let r = t[e];
15726
15744
  r === void 0 ? delete n[e] : n[e] = r;
15727
15745
  }
15728
15746
  return n;
15729
15747
  }
15730
- function My(e, t, n) {
15748
+ function Ny(e, t, n) {
15731
15749
  let r = 0, i = 0, a = 0, o = 0, s = t.at(-1)?.id ?? 0, c = e.prepare("UPDATE sessions SET metadata_json = ? WHERE id = ?");
15732
15750
  for (let n of t) {
15733
15751
  if (s = n.id, !n.source || !n.stream_id) {
15734
15752
  a += 1;
15735
15753
  continue;
15736
15754
  }
15737
- let t = Dy(e, n.source, n.stream_id);
15755
+ let t = Oy(e, n.source, n.stream_id);
15738
15756
  if (t.length === 0) {
15739
15757
  i += 1;
15740
15758
  continue;
15741
15759
  }
15742
- let l = tv(S_(t)), u = Oy(n.metadata_json), d = u.session_context, f = d && typeof d == "object" ? d : {};
15743
- if (!Ay(f, l)) {
15760
+ let l = tv(S_(t)), u = ky(n.metadata_json), d = u.session_context, f = d && typeof d == "object" ? d : {};
15761
+ if (!jy(f, l)) {
15744
15762
  o += 1;
15745
15763
  continue;
15746
15764
  }
15747
- let p = jy(f, l), m = {
15765
+ let p = My(f, l), m = {
15748
15766
  ...u,
15749
15767
  session_context: p
15750
15768
  };
@@ -15760,14 +15778,14 @@ function My(e, t, n) {
15760
15778
  exhausted: t.length < n
15761
15779
  };
15762
15780
  }
15763
- function Ny(e) {
15764
- return Q(e, "session_context_backfill")?.status === "completed" ? !1 : Ty(e) > 0;
15781
+ function Py(e) {
15782
+ return Q(e, "session_context_backfill")?.status === "completed" ? !1 : Ey(e) > 0;
15765
15783
  }
15766
- async function Py(e, t = {}) {
15767
- let n = Math.max(1, t.batchSize ?? 100), r = Q(e, Cy), i = r?.metadata ?? {}, a = !r || r.status === "completed" || r.status === "failed", o = a ? 0 : Number(i.last_cursor_id ?? 0), s = a ? Ty(e) : Number(i.total_candidates ?? Ty(e));
15784
+ async function Fy(e, t = {}) {
15785
+ let n = Math.max(1, t.batchSize ?? 100), r = Q(e, wy), i = r?.metadata ?? {}, a = !r || r.status === "completed" || r.status === "failed", o = a ? 0 : Number(i.last_cursor_id ?? 0), s = a ? Ey(e) : Number(i.total_candidates ?? Ey(e));
15768
15786
  if (a && s <= 0) return !1;
15769
15787
  a && qr(e, {
15770
- kind: Cy,
15788
+ kind: wy,
15771
15789
  title: "Backfilling session context",
15772
15790
  message: `Rebuilding session_context for ${s} raw-event sessions`,
15773
15791
  progressTotal: s,
@@ -15781,11 +15799,11 @@ async function Py(e, t = {}) {
15781
15799
  unchanged_sessions: 0
15782
15800
  }
15783
15801
  });
15784
- let c = Ey(e, o, n);
15802
+ let c = Dy(e, o, n);
15785
15803
  if (c.length === 0) {
15786
15804
  let t = Q(e, "session_context_backfill")?.metadata ?? {};
15787
- return Yr(e, Cy, {
15788
- message: Fy(t),
15805
+ return Yr(e, wy, {
15806
+ message: Iy(t),
15789
15807
  progressCurrent: Number(t.processed_sessions ?? 0),
15790
15808
  progressTotal: Number(t.total_candidates ?? t.processed_sessions ?? 0),
15791
15809
  metadata: {
@@ -15794,7 +15812,7 @@ async function Py(e, t = {}) {
15794
15812
  }
15795
15813
  }), !1;
15796
15814
  }
15797
- let l = My(e, c, n), u = Q(e, "session_context_backfill")?.metadata ?? {}, d = Number(u.processed_sessions ?? 0) + l.processed, f = Number(u.rewritten_sessions ?? 0) + l.rewritten, p = Number(u.skipped_no_events ?? 0) + l.skippedNoEvents, m = Number(u.skipped_no_bridge ?? 0) + l.skippedNoBridge, h = Number(u.unchanged_sessions ?? 0) + l.unchanged, g = {
15815
+ let l = Ny(e, c, n), u = Q(e, "session_context_backfill")?.metadata ?? {}, d = Number(u.processed_sessions ?? 0) + l.processed, f = Number(u.rewritten_sessions ?? 0) + l.rewritten, p = Number(u.skipped_no_events ?? 0) + l.skippedNoEvents, m = Number(u.skipped_no_bridge ?? 0) + l.skippedNoBridge, h = Number(u.unchanged_sessions ?? 0) + l.unchanged, g = {
15798
15816
  last_cursor_id: l.lastCursorId,
15799
15817
  total_candidates: Number(u.total_candidates ?? s),
15800
15818
  processed_sessions: d,
@@ -15803,12 +15821,12 @@ async function Py(e, t = {}) {
15803
15821
  skipped_no_bridge: m,
15804
15822
  unchanged_sessions: h
15805
15823
  };
15806
- return l.exhausted ? (Yr(e, Cy, {
15807
- message: Fy(g),
15824
+ return l.exhausted ? (Yr(e, wy, {
15825
+ message: Iy(g),
15808
15826
  progressCurrent: d,
15809
15827
  progressTotal: Number(g.total_candidates ?? d),
15810
15828
  metadata: g
15811
- }), !1) : (Jr(e, Cy, {
15829
+ }), !1) : (Jr(e, wy, {
15812
15830
  status: "running",
15813
15831
  message: `Rebuilt session_context for ${f} of ${d} scanned sessions`,
15814
15832
  progressCurrent: d,
@@ -15816,11 +15834,11 @@ async function Py(e, t = {}) {
15816
15834
  metadata: g
15817
15835
  }), !0);
15818
15836
  }
15819
- function Fy(e) {
15837
+ function Iy(e) {
15820
15838
  let t = Number(e.rewritten_sessions ?? 0), n = Number(e.processed_sessions ?? 0), r = Number(e.skipped_no_events ?? 0) + Number(e.skipped_no_bridge ?? 0);
15821
15839
  return n === 0 ? "No raw-event sessions required session_context backfill" : t === 0 ? `Scanned ${n} sessions, no session_context rewrite required` : `Rebuilt session_context for ${t} of ${n} sessions${r > 0 ? ` (${r} skipped)` : ""}`;
15822
15840
  }
15823
- var Iy = class {
15841
+ var Ly = class {
15824
15842
  dbPath;
15825
15843
  signal;
15826
15844
  batchSize;
@@ -15850,25 +15868,25 @@ var Iy = class {
15850
15868
  if (!this.active || this.signal?.aborted) return;
15851
15869
  let e = null;
15852
15870
  try {
15853
- e = Mn(this.dbPath), await Py(e, { batchSize: this.batchSize }) || (this.active = !1);
15871
+ e = Mn(this.dbPath), await Fy(e, { batchSize: this.batchSize }) || (this.active = !1);
15854
15872
  } catch (t) {
15855
- e && Xr(e, Cy, t instanceof Error ? t.message : String(t)), console.warn("Session-context backfill runner failed", t);
15873
+ e && Xr(e, wy, t instanceof Error ? t.message : String(t)), console.warn("Session-context backfill runner failed", t);
15856
15874
  } finally {
15857
15875
  e?.close();
15858
15876
  }
15859
15877
  }
15860
- }, Ly = "session_summary_dedup_backfill";
15861
- function Ry(e) {
15878
+ }, Ry = "session_summary_dedup_backfill";
15879
+ function zy(e) {
15862
15880
  let t = e.prepare("SELECT COUNT(*) AS n FROM (\n SELECT session_id\n FROM memory_items\n WHERE active = 1\n AND kind = 'session_summary'\n AND json_extract(metadata_json, '$.source') = 'observer_summary'\n GROUP BY session_id\n HAVING COUNT(*) > 1\n )").get();
15863
15881
  return Number(t?.n ?? 0);
15864
15882
  }
15865
- function zy(e) {
15866
- return Ry(e) > 0;
15867
- }
15868
15883
  function By(e) {
15884
+ return zy(e) > 0;
15885
+ }
15886
+ function Vy(e) {
15869
15887
  return Q(e, "session_summary_dedup_backfill")?.metadata ?? {};
15870
15888
  }
15871
- function Vy(e, t, n) {
15889
+ function Hy(e, t, n) {
15872
15890
  let r = e.prepare("SELECT session_id\n FROM memory_items\n WHERE active = 1\n AND kind = 'session_summary'\n AND json_extract(metadata_json, '$.source') = 'observer_summary'\n AND session_id > ?\n GROUP BY session_id\n HAVING COUNT(*) > 1\n ORDER BY session_id ASC\n LIMIT ?").all(t, n);
15873
15891
  if (r.length === 0) return [];
15874
15892
  let i = e.prepare("SELECT id, rev, metadata_json, created_at\n FROM memory_items\n WHERE session_id = ?\n AND active = 1\n AND kind = 'session_summary'\n AND json_extract(metadata_json, '$.source') = 'observer_summary'\n ORDER BY created_at DESC, id DESC"), a = [];
@@ -15884,7 +15902,7 @@ function Vy(e, t, n) {
15884
15902
  }
15885
15903
  return a;
15886
15904
  }
15887
- function Hy(e, t, n) {
15905
+ function Uy(e, t, n) {
15888
15906
  let r = (/* @__PURE__ */ new Date()).toISOString(), i = e.prepare("UPDATE memory_items\n SET active = 0,\n deleted_at = ?,\n updated_at = ?,\n metadata_json = ?,\n rev = ?\n WHERE id = ?"), a = 0;
15889
15907
  for (let o of t.superseded) {
15890
15908
  let s = Un(o.metadata_json);
@@ -15900,9 +15918,9 @@ function Hy(e, t, n) {
15900
15918
  }
15901
15919
  return a;
15902
15920
  }
15903
- async function Uy(e, t = {}) {
15904
- let n = Math.max(1, t.batchSize ?? 50), r = t.deviceId ?? "local", i = Q(e, Ly), a = By(e), o = !i || i.status === "completed" || i.status === "failed", s = o ? 0 : Number(a.last_session_id ?? 0), c = Vy(e, s, n), l = o ? 0 : Number(a.processed_sessions ?? 0), u = o ? 0 : Number(a.superseded_rows ?? 0);
15905
- if (c.length === 0) return i && i.status !== "completed" && Yr(e, Ly, {
15921
+ async function Wy(e, t = {}) {
15922
+ let n = Math.max(1, t.batchSize ?? 50), r = t.deviceId ?? "local", i = Q(e, Ry), a = Vy(e), o = !i || i.status === "completed" || i.status === "failed", s = o ? 0 : Number(a.last_session_id ?? 0), c = Hy(e, s, n), l = o ? 0 : Number(a.processed_sessions ?? 0), u = o ? 0 : Number(a.superseded_rows ?? 0);
15923
+ if (c.length === 0) return i && i.status !== "completed" && Yr(e, Ry, {
15906
15924
  message: u > 0 ? `Session-summary dedup complete (${u} rows superseded)` : "Session-summary dedup complete",
15907
15925
  progressCurrent: l,
15908
15926
  progressTotal: Number(a.total_sessions ?? l),
@@ -15912,9 +15930,9 @@ async function Uy(e, t = {}) {
15912
15930
  }
15913
15931
  }), !1;
15914
15932
  if (!i || i.status === "completed" || i.status === "failed") {
15915
- let t = Ry(e);
15933
+ let t = zy(e);
15916
15934
  qr(e, {
15917
- kind: Ly,
15935
+ kind: Ry,
15918
15936
  title: "Deduplicating historical session summaries",
15919
15937
  message: `Cleaning up ${t} sessions with duplicate observer summaries`,
15920
15938
  progressTotal: t,
@@ -15929,10 +15947,10 @@ async function Uy(e, t = {}) {
15929
15947
  }
15930
15948
  let d = 0, f = s;
15931
15949
  e.transaction(() => {
15932
- for (let t of c) d += Hy(e, t, r), t.session_id > f && (f = t.session_id);
15950
+ for (let t of c) d += Uy(e, t, r), t.session_id > f && (f = t.session_id);
15933
15951
  })();
15934
- let p = l + c.length, m = u + d, h = Ry(e), g = Math.max(Number(a.total_sessions ?? p), p + h);
15935
- return h === 0 ? (Yr(e, Ly, {
15952
+ let p = l + c.length, m = u + d, h = zy(e), g = Math.max(Number(a.total_sessions ?? p), p + h);
15953
+ return h === 0 ? (Yr(e, Ry, {
15936
15954
  message: `Session-summary dedup complete (${m} rows superseded across ${p} sessions)`,
15937
15955
  progressCurrent: p,
15938
15956
  progressTotal: g,
@@ -15942,7 +15960,7 @@ async function Uy(e, t = {}) {
15942
15960
  superseded_rows: m,
15943
15961
  last_session_id: f
15944
15962
  }
15945
- }), !1) : (Jr(e, Ly, {
15963
+ }), !1) : (Jr(e, Ry, {
15946
15964
  message: `Deduplicated ${p} of ${g} sessions (${m} rows superseded)`,
15947
15965
  progressCurrent: p,
15948
15966
  progressTotal: g,
@@ -15954,7 +15972,7 @@ async function Uy(e, t = {}) {
15954
15972
  }
15955
15973
  }), !0);
15956
15974
  }
15957
- var Wy = class {
15975
+ var Gy = class {
15958
15976
  dbPath;
15959
15977
  signal;
15960
15978
  batchSize;
@@ -15985,97 +16003,97 @@ var Wy = class {
15985
16003
  if (!this.active || this.signal?.aborted) return;
15986
16004
  let e = null;
15987
16005
  try {
15988
- e = Mn(this.dbPath), await Uy(e, {
16006
+ e = Mn(this.dbPath), await Wy(e, {
15989
16007
  batchSize: this.batchSize,
15990
16008
  deviceId: this.deviceId
15991
16009
  }) || (this.active = !1);
15992
16010
  } catch (t) {
15993
- e && Xr(e, Ly, t instanceof Error ? t.message : String(t)), console.warn("Summary-dedup backfill runner failed", t);
16011
+ e && Xr(e, Ry, t instanceof Error ? t.message : String(t)), console.warn("Summary-dedup backfill runner failed", t);
15994
16012
  } finally {
15995
16013
  e?.close();
15996
16014
  }
15997
16015
  }
15998
- }, Gy = [
16016
+ }, Ky = [
15999
16017
  "unsupported",
16000
16018
  "aware",
16001
16019
  "enforcing"
16002
- ], Ky = "X-Codemem-Sync-Capability", qy = "aware", Jy = {
16020
+ ], qy = "X-Codemem-Sync-Capability", Jy = "aware", Yy = {
16003
16021
  unsupported: 0,
16004
16022
  aware: 1,
16005
16023
  enforcing: 2
16006
16024
  };
16007
- function Yy(e) {
16025
+ function Xy(e) {
16008
16026
  if (typeof e != "string") return "unsupported";
16009
16027
  let t = e.trim().toLowerCase();
16010
- return Gy.includes(t) ? t : "unsupported";
16028
+ return Ky.includes(t) ? t : "unsupported";
16011
16029
  }
16012
- function Xy(e, t) {
16013
- let n = Yy(e), r = Yy(t);
16014
- return Jy[n] <= Jy[r] ? n : r;
16030
+ function Zy(e, t) {
16031
+ let n = Xy(e), r = Xy(t);
16032
+ return Yy[n] <= Yy[r] ? n : r;
16015
16033
  }
16016
16034
  //#endregion
16017
16035
  //#region src/vector-migration.ts
16018
- var Zy = "vector_model_migration", Qy = "sync_bootstrap", $y = "sync_incremental", eb = 6e4, tb = null;
16019
- function nb(e) {
16036
+ var Qy = "vector_model_migration", $y = "sync_bootstrap", eb = "sync_incremental", tb = 6e4, nb = null;
16037
+ function rb(e) {
16020
16038
  return [...new Set(e.filter((e) => Number.isInteger(e) && e > 0))].sort((e, t) => e - t);
16021
16039
  }
16022
- function rb(e) {
16023
- return Array.isArray(e) ? nb(e.filter((e) => typeof e == "number")) : [];
16040
+ function ib(e) {
16041
+ return Array.isArray(e) ? rb(e.filter((e) => typeof e == "number")) : [];
16024
16042
  }
16025
- function ib(e, t) {
16026
- let n = new Set(rb(e.pending_upsert_memory_ids)), r = new Set(rb(e.pending_delete_memory_ids));
16027
- for (let e of nb(t.deleteMemoryIds)) n.delete(e), r.add(e);
16028
- for (let e of nb(t.upsertMemoryIds)) r.delete(e), n.add(e);
16043
+ function ab(e, t) {
16044
+ let n = new Set(ib(e.pending_upsert_memory_ids)), r = new Set(ib(e.pending_delete_memory_ids));
16045
+ for (let e of rb(t.deleteMemoryIds)) n.delete(e), r.add(e);
16046
+ for (let e of rb(t.upsertMemoryIds)) r.delete(e), n.add(e);
16029
16047
  return {
16030
16048
  pending_upsert_memory_ids: [...n],
16031
16049
  pending_delete_memory_ids: [...r]
16032
16050
  };
16033
16051
  }
16034
- function ab(e, t) {
16052
+ function ob(e, t) {
16035
16053
  if (t.length === 0) return;
16036
16054
  let n = t.map(() => "?").join(", ");
16037
16055
  e.prepare(`DELETE FROM memory_vectors WHERE memory_id IN (${n})`).run(...t);
16038
16056
  }
16039
- function ob(e, t) {
16040
- return JSON.stringify(rb(e.pending_upsert_memory_ids)) === JSON.stringify(rb(t.pending_upsert_memory_ids)) && JSON.stringify(rb(e.pending_delete_memory_ids)) === JSON.stringify(rb(t.pending_delete_memory_ids));
16057
+ function sb(e, t) {
16058
+ return JSON.stringify(ib(e.pending_upsert_memory_ids)) === JSON.stringify(ib(t.pending_upsert_memory_ids)) && JSON.stringify(ib(e.pending_delete_memory_ids)) === JSON.stringify(ib(t.pending_delete_memory_ids));
16041
16059
  }
16042
- function sb() {
16043
- tb?.wake();
16060
+ function cb() {
16061
+ nb?.wake();
16044
16062
  }
16045
- function cb(e, t) {
16046
- let n = ib({}, t);
16063
+ function lb(e, t) {
16064
+ let n = ab({}, t);
16047
16065
  if ((n.pending_upsert_memory_ids?.length ?? 0) === 0 && (n.pending_delete_memory_ids?.length ?? 0) === 0) return;
16048
- let r = Q(e, Zy), i = r && r.status !== "completed" && r.status !== "cancelled" ? r.metadata ?? {} : {}, a = {
16066
+ let r = Q(e, Qy), i = r && r.status !== "completed" && r.status !== "cancelled" ? r.metadata ?? {} : {}, a = {
16049
16067
  ...i,
16050
- ...ib(i, t),
16051
- trigger: i.trigger ?? $y
16052
- }, o = rb(a.pending_upsert_memory_ids).length + rb(a.pending_delete_memory_ids).length;
16068
+ ...ab(i, t),
16069
+ trigger: i.trigger ?? eb
16070
+ }, o = ib(a.pending_upsert_memory_ids).length + ib(a.pending_delete_memory_ids).length;
16053
16071
  if (!r || r.status === "completed" || r.status === "cancelled") {
16054
16072
  qr(e, {
16055
- kind: Zy,
16073
+ kind: Qy,
16056
16074
  title: "Re-indexing memories",
16057
16075
  status: "pending",
16058
16076
  message: "Queued vector catch-up for incremental sync data",
16059
16077
  progressTotal: null,
16060
16078
  metadata: a
16061
- }), sb();
16079
+ }), cb();
16062
16080
  return;
16063
16081
  }
16064
- Jr(e, Zy, {
16082
+ Jr(e, Qy, {
16065
16083
  status: "pending",
16066
16084
  message: "Queued vector catch-up for incremental sync data",
16067
16085
  progressCurrent: r.status === "failed" ? 0 : Math.min(r.progress.current, o),
16068
16086
  progressTotal: r.progress.total,
16069
16087
  metadata: a
16070
- }), sb();
16088
+ }), cb();
16071
16089
  }
16072
- async function lb(e, t, n, r, i) {
16073
- let a = t.metadata ?? {}, o = rb(a.pending_delete_memory_ids), s = rb(a.pending_upsert_memory_ids);
16090
+ async function ub(e, t, n, r, i) {
16091
+ let a = t.metadata ?? {}, o = ib(a.pending_delete_memory_ids), s = ib(a.pending_upsert_memory_ids);
16074
16092
  if (o.length === 0 && s.length === 0) return {
16075
16093
  completed: !1,
16076
16094
  metadata: a
16077
16095
  };
16078
- o.length > 0 && ab(e, o);
16096
+ o.length > 0 && ob(e, o);
16079
16097
  let c = s.slice(0, r);
16080
16098
  if (c.length > 0) {
16081
16099
  if (await ks(e, {
@@ -16091,14 +16109,14 @@ async function lb(e, t, n, r, i) {
16091
16109
  ...a,
16092
16110
  pending_delete_memory_ids: [],
16093
16111
  pending_upsert_memory_ids: s.slice(c.length)
16094
- }, u = Q(e, "vector_model_migration")?.metadata ?? {}, d = ob(u, a) ? l : {
16112
+ }, u = Q(e, "vector_model_migration")?.metadata ?? {}, d = sb(u, a) ? l : {
16095
16113
  ...u,
16096
- ...ib(u, {
16097
- upsertMemoryIds: rb(l.pending_upsert_memory_ids),
16098
- deleteMemoryIds: rb(l.pending_delete_memory_ids)
16114
+ ...ab(u, {
16115
+ upsertMemoryIds: ib(l.pending_upsert_memory_ids),
16116
+ deleteMemoryIds: ib(l.pending_delete_memory_ids)
16099
16117
  })
16100
- }, f = rb(d.pending_delete_memory_ids).length + rb(d.pending_upsert_memory_ids).length, p = (a.trigger ?? $y) === $y && !a.source_model && !a.last_cursor_id && a.embeddable_total == null;
16101
- return f === 0 && p ? (Yr(e, Zy, {
16118
+ }, f = ib(d.pending_delete_memory_ids).length + ib(d.pending_upsert_memory_ids).length, p = (a.trigger ?? eb) === eb && !a.source_model && !a.last_cursor_id && a.embeddable_total == null;
16119
+ return f === 0 && p ? (Yr(e, Qy, {
16102
16120
  message: "Finished vector catch-up for incremental sync data",
16103
16121
  progressCurrent: 0,
16104
16122
  progressTotal: null,
@@ -16106,7 +16124,7 @@ async function lb(e, t, n, r, i) {
16106
16124
  }), {
16107
16125
  completed: !0,
16108
16126
  metadata: d
16109
- }) : (Jr(e, Zy, {
16127
+ }) : (Jr(e, Qy, {
16110
16128
  status: f > 0 ? "running" : t.status,
16111
16129
  message: f > 0 ? `Queued vector catch-up has ${f} memory change(s) remaining` : t.message,
16112
16130
  progressCurrent: 0,
@@ -16117,36 +16135,36 @@ async function lb(e, t, n, r, i) {
16117
16135
  metadata: d
16118
16136
  });
16119
16137
  }
16120
- function ub(e, t = {}) {
16138
+ function db(e, t = {}) {
16121
16139
  let n = typeof t.embeddableTotal == "number" && t.embeddableTotal >= 0 ? t.embeddableTotal : null, r = {
16122
16140
  last_cursor_id: 0,
16123
16141
  processed_embeddable: 0,
16124
- trigger: Qy
16142
+ trigger: $y
16125
16143
  };
16126
16144
  n != null && (r.embeddable_total = n), qr(e, {
16127
- kind: Zy,
16145
+ kind: Qy,
16128
16146
  title: "Re-indexing memories",
16129
16147
  status: "pending",
16130
16148
  message: "Queued vector catch-up for synced bootstrap data",
16131
16149
  progressTotal: n,
16132
16150
  metadata: r
16133
- }), sb();
16151
+ }), cb();
16134
16152
  }
16135
- function db(e) {
16153
+ function fb(e) {
16136
16154
  return e.prepare("SELECT model, COUNT(*) AS rows FROM memory_vectors GROUP BY model ORDER BY rows DESC, model ASC").all();
16137
16155
  }
16138
- function fb(e) {
16156
+ function pb(e) {
16139
16157
  let t = e.prepare("SELECT COUNT(*) AS c FROM memory_items\n WHERE active = 1\n AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''").get();
16140
16158
  return Number(t?.c ?? 0);
16141
16159
  }
16142
- function pb(e, t, n) {
16160
+ function mb(e, t, n) {
16143
16161
  return e.prepare("SELECT id, title, body_text\n FROM memory_items\n WHERE active = 1 AND id > ?\n ORDER BY id ASC\n LIMIT ?").all(t, n);
16144
16162
  }
16145
- function mb(e) {
16163
+ function hb(e) {
16146
16164
  return `${e.title ?? ""}
16147
16165
  ${e.body_text ?? ""}`.trim().length > 0;
16148
16166
  }
16149
- function hb(e, t, n, r) {
16167
+ function gb(e, t, n, r) {
16150
16168
  let i = e?.metadata ?? {};
16151
16169
  return {
16152
16170
  source_model: t ?? i.source_model ?? null,
@@ -16156,39 +16174,39 @@ function hb(e, t, n, r) {
16156
16174
  embeddable_total: Number(i.embeddable_total ?? r)
16157
16175
  };
16158
16176
  }
16159
- function gb(e, t) {
16177
+ function _b(e, t) {
16160
16178
  let n = e.prepare("SELECT COUNT(*) AS c FROM memory_vectors WHERE model != ?").get(t), r = Number(n?.c ?? 0);
16161
16179
  return r > 0 && e.prepare("DELETE FROM memory_vectors WHERE model != ?").run(t), r;
16162
16180
  }
16163
- function _b(e, t) {
16164
- return db(e).filter((e) => e.model !== t)[0]?.model ?? null;
16181
+ function vb(e, t) {
16182
+ return fb(e).filter((e) => e.model !== t)[0]?.model ?? null;
16165
16183
  }
16166
- async function vb(e, t = {}) {
16167
- let n = Q(e, Zy), r = n?.status === "running" || n?.status === "pending";
16184
+ async function yb(e, t = {}) {
16185
+ let n = Q(e, Qy), r = n?.status === "running" || n?.status === "pending";
16168
16186
  if (Ln()) {
16169
- r && Xr(e, Zy, "Embeddings are disabled", { message: "Vector re-indexing is waiting for embeddings to be enabled" });
16187
+ r && Xr(e, Qy, "Embeddings are disabled", { message: "Vector re-indexing is waiting for embeddings to be enabled" });
16170
16188
  return;
16171
16189
  }
16172
16190
  let i = await es();
16173
16191
  if (!i) {
16174
- r && Xr(e, Zy, "Embedding client unavailable", { message: "Vector re-indexing is waiting for the embedding client" });
16192
+ r && Xr(e, Qy, "Embedding client unavailable", { message: "Vector re-indexing is waiting for the embedding client" });
16175
16193
  return;
16176
16194
  }
16177
- let a = i.model, o = Math.max(1, t.batchSize ?? 50), s = n?.metadata ?? {}, c = rb(s.pending_upsert_memory_ids).length + rb(s.pending_delete_memory_ids).length;
16195
+ let a = i.model, o = Math.max(1, t.batchSize ?? 50), s = n?.metadata ?? {}, c = ib(s.pending_upsert_memory_ids).length + ib(s.pending_delete_memory_ids).length;
16178
16196
  if (n?.status === "completed" && s.target_model === a && c === 0) return;
16179
16197
  if (n) {
16180
- let r = await lb(e, n, a, o, t.signal);
16198
+ let r = await ub(e, n, a, o, t.signal);
16181
16199
  if (r.completed) return;
16182
- let i = rb(r.metadata.pending_delete_memory_ids).length + rb(r.metadata.pending_upsert_memory_ids).length;
16183
- if ((r.metadata.trigger ?? $y) === $y && i > 0) return;
16184
- n = Q(e, Zy);
16200
+ let i = ib(r.metadata.pending_delete_memory_ids).length + ib(r.metadata.pending_upsert_memory_ids).length;
16201
+ if ((r.metadata.trigger ?? eb) === eb && i > 0) return;
16202
+ n = Q(e, Qy);
16185
16203
  }
16186
- let l = _b(e, a), u = n?.status === "running" || n?.status === "pending" || n?.status === "failed", d = n?.metadata?.trigger;
16187
- if (!l && (d === $y || d === Qy) && u) {
16204
+ let l = vb(e, a), u = n?.status === "running" || n?.status === "pending" || n?.status === "failed", d = n?.metadata?.trigger;
16205
+ if (!l && (d === eb || d === $y) && u) {
16188
16206
  let t = e.prepare("SELECT COUNT(*) AS c FROM memory_items\n WHERE active = 1\n AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)").get(a);
16189
16207
  if (Number(t?.c ?? 0) <= 0) {
16190
- let t = n?.metadata ?? {}, r = fb(e);
16191
- Yr(e, Zy, {
16208
+ let t = n?.metadata ?? {}, r = pb(e);
16209
+ Yr(e, Qy, {
16192
16210
  message: "Finished re-indexing memories",
16193
16211
  progressCurrent: r,
16194
16212
  progressTotal: r,
@@ -16203,9 +16221,9 @@ async function vb(e, t = {}) {
16203
16221
  return;
16204
16222
  }
16205
16223
  }
16206
- let f = n?.metadata ?? {}, p = (n?.status === "running" || n?.status === "pending") && f.embeddable_total ? Number(f.embeddable_total) : fb(e);
16224
+ let f = n?.metadata ?? {}, p = (n?.status === "running" || n?.status === "pending") && f.embeddable_total ? Number(f.embeddable_total) : pb(e);
16207
16225
  if (p <= 0 && u && !l) {
16208
- Yr(e, Zy, {
16226
+ Yr(e, Qy, {
16209
16227
  message: "No embeddable memories to re-index",
16210
16228
  progressCurrent: 0,
16211
16229
  progressTotal: 0,
@@ -16219,9 +16237,9 @@ async function vb(e, t = {}) {
16219
16237
  return;
16220
16238
  }
16221
16239
  if (l && p <= 0) {
16222
- let t = gb(e, a);
16240
+ let t = _b(e, a);
16223
16241
  qr(e, {
16224
- kind: Zy,
16242
+ kind: Qy,
16225
16243
  title: "Re-indexing memories",
16226
16244
  message: t > 0 ? `Removed ${t} stale vector rows` : "No embeddable memories to re-index",
16227
16245
  progressTotal: 0,
@@ -16230,7 +16248,7 @@ async function vb(e, t = {}) {
16230
16248
  target_model: a,
16231
16249
  removed_stale_rows: t
16232
16250
  }
16233
- }), Yr(e, Zy, {
16251
+ }), Yr(e, Qy, {
16234
16252
  progressCurrent: 0,
16235
16253
  progressTotal: 0,
16236
16254
  metadata: {
@@ -16241,15 +16259,15 @@ async function vb(e, t = {}) {
16241
16259
  });
16242
16260
  return;
16243
16261
  }
16244
- let m = n, h = hb(m, l, a, p);
16262
+ let m = n, h = gb(m, l, a, p);
16245
16263
  (!m || m.status === "completed" || m.status === "failed") && qr(e, {
16246
- kind: Zy,
16264
+ kind: Qy,
16247
16265
  title: "Re-indexing memories",
16248
16266
  message: l ? `Building ${a} vectors while semantic search falls back to FTS-only` : `Building ${a} vectors`,
16249
16267
  progressTotal: p,
16250
16268
  metadata: h
16251
16269
  });
16252
- let g = pb(e, h.last_cursor_id ?? 0, o), _ = g.map((e) => e.id), v = g.filter(mb).length, y = g.at(-1)?.id ?? h.last_cursor_id ?? 0, b = Math.min(p, (h.processed_embeddable ?? 0) + v);
16270
+ let g = mb(e, h.last_cursor_id ?? 0, o), _ = g.map((e) => e.id), v = g.filter(hb).length, y = g.at(-1)?.id ?? h.last_cursor_id ?? 0, b = Math.min(p, (h.processed_embeddable ?? 0) + v);
16253
16271
  if (_.length > 0) {
16254
16272
  if (await ks(e, {
16255
16273
  memoryIds: _,
@@ -16257,8 +16275,8 @@ async function vb(e, t = {}) {
16257
16275
  }), t.signal?.aborted) return;
16258
16276
  if (g.length < o) {
16259
16277
  e.transaction(() => {
16260
- let t = gb(e, a);
16261
- Yr(e, Zy, {
16278
+ let t = _b(e, a);
16279
+ Yr(e, Qy, {
16262
16280
  message: t > 0 ? `Finished re-indexing and removed ${t} stale vector rows` : "Finished re-indexing memories",
16263
16281
  progressCurrent: b,
16264
16282
  progressTotal: p,
@@ -16273,7 +16291,7 @@ async function vb(e, t = {}) {
16273
16291
  })();
16274
16292
  return;
16275
16293
  }
16276
- Jr(e, Zy, {
16294
+ Jr(e, Qy, {
16277
16295
  message: `Re-indexed ${b} of ${p} memories`,
16278
16296
  progressCurrent: b,
16279
16297
  progressTotal: p,
@@ -16287,8 +16305,8 @@ async function vb(e, t = {}) {
16287
16305
  return;
16288
16306
  }
16289
16307
  h.last_cursor_id && h.last_cursor_id > 0 && e.transaction(() => {
16290
- let t = gb(e, a);
16291
- Yr(e, Zy, {
16308
+ let t = _b(e, a);
16309
+ Yr(e, Qy, {
16292
16310
  message: t > 0 ? `Finished re-indexing and removed ${t} stale vector rows` : "Finished re-indexing memories",
16293
16311
  progressCurrent: p,
16294
16312
  progressTotal: p,
@@ -16301,23 +16319,24 @@ async function vb(e, t = {}) {
16301
16319
  });
16302
16320
  })();
16303
16321
  }
16304
- var yb = class {
16322
+ var bb = class {
16305
16323
  dbPath;
16306
16324
  signal;
16307
16325
  batchSize;
16308
16326
  intervalMs;
16327
+ idleIntervalMs;
16309
16328
  active = !1;
16310
16329
  timer = null;
16311
16330
  currentRun = null;
16312
16331
  lastTickWasIdle = !1;
16313
16332
  constructor(e = {}) {
16314
- this.dbPath = Dn(e.dbPath), this.signal = e.signal, this.batchSize = Math.max(1, e.batchSize ?? 50), this.intervalMs = Math.max(1e3, e.intervalMs ?? 5e3);
16333
+ this.dbPath = Dn(e.dbPath), this.signal = e.signal, this.batchSize = Math.max(1, e.batchSize ?? 50), this.intervalMs = Math.max(1e3, e.intervalMs ?? 5e3), this.idleIntervalMs = Math.max(1e3, e.idleIntervalMs ?? tb);
16315
16334
  }
16316
16335
  start() {
16317
- this.active || (this.active = !0, this.lastTickWasIdle = !1, tb = this, this.schedule(100));
16336
+ this.active || (this.active = !0, this.lastTickWasIdle = !1, nb = this, this.schedule(100));
16318
16337
  }
16319
16338
  async stop() {
16320
- this.active = !1, tb === this && (tb = null), this.timer &&= (clearTimeout(this.timer), null), this.currentRun && await this.currentRun;
16339
+ this.active = !1, nb === this && (nb = null), this.timer &&= (clearTimeout(this.timer), null), this.currentRun && await this.currentRun;
16321
16340
  }
16322
16341
  wake() {
16323
16342
  this.active && (this.lastTickWasIdle = !1, this.timer && (clearTimeout(this.timer), this.timer = null, this.schedule(100)));
@@ -16328,7 +16347,7 @@ var yb = class {
16328
16347
  console.error("Vector migration runner tick failed:", e);
16329
16348
  }).finally(() => {
16330
16349
  this.currentRun = null;
16331
- let e = this.lastTickWasIdle ? eb : this.intervalMs;
16350
+ let e = this.lastTickWasIdle ? this.idleIntervalMs : this.intervalMs;
16332
16351
  this.schedule(e);
16333
16352
  });
16334
16353
  }, e), typeof this.timer == "object" && "unref" in this.timer && this.timer.unref());
@@ -16337,28 +16356,28 @@ var yb = class {
16337
16356
  if (!this.active || this.signal?.aborted) return;
16338
16357
  let e = null;
16339
16358
  try {
16340
- e = Mn(this.dbPath), In(e), await vb(e, {
16359
+ e = Mn(this.dbPath), In(e), await yb(e, {
16341
16360
  batchSize: this.batchSize,
16342
16361
  signal: this.signal
16343
16362
  }), this.lastTickWasIdle = this.computeIdle(e);
16344
16363
  } catch (t) {
16345
- e && Xr(e, Zy, t instanceof Error ? t.message : String(t)), this.lastTickWasIdle = !0, console.warn("Vector migration runner failed", t);
16364
+ e && Xr(e, Qy, t instanceof Error ? t.message : String(t)), this.lastTickWasIdle = !0, console.warn("Vector migration runner failed", t);
16346
16365
  } finally {
16347
16366
  e?.close();
16348
16367
  }
16349
16368
  }
16350
16369
  computeIdle(e) {
16351
16370
  if (Ln()) return !0;
16352
- let t = Q(e, Zy);
16371
+ let t = Q(e, Qy);
16353
16372
  if (t) {
16354
16373
  if (t.status === "running" || t.status === "pending") return !1;
16355
16374
  let e = t.metadata ?? {};
16356
- return !(rb(e.pending_upsert_memory_ids).length + rb(e.pending_delete_memory_ids).length > 0);
16375
+ return !(ib(e.pending_upsert_memory_ids).length + ib(e.pending_delete_memory_ids).length > 0);
16357
16376
  }
16358
16377
  let n = $o();
16359
16378
  try {
16360
16379
  let t = e.prepare("SELECT COUNT(*) AS c FROM memory_items\n WHERE active = 1\n AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''\n AND id NOT IN (SELECT DISTINCT memory_id FROM memory_vectors WHERE model = ?)").get(n);
16361
- return Number(t?.c ?? 0) > 0 ? !1 : _b(e, n) === null;
16380
+ return Number(t?.c ?? 0) > 0 ? !1 : vb(e, n) === null;
16362
16381
  } catch (e) {
16363
16382
  return console.warn("Vector migration runner idle peek failed", e), !1;
16364
16383
  }
@@ -16366,7 +16385,7 @@ var yb = class {
16366
16385
  };
16367
16386
  //#endregion
16368
16387
  //#region src/sync-bootstrap.ts
16369
- async function bb(e, t, n, r) {
16388
+ async function xb(e, t, n, r) {
16370
16389
  let i = r?.pageSize ?? 200, a = r?.timeoutS ?? 10, o = r?.keysDir, s = r?.bootstrapGrantId?.trim() || void 0, c = r?.maxItems ?? 1e5, l = [], u = null, d = null;
16371
16390
  for (;;) {
16372
16391
  let r = new URLSearchParams({
@@ -16385,7 +16404,7 @@ async function bb(e, t, n, r) {
16385
16404
  bootstrapGrantId: s,
16386
16405
  keysDir: o
16387
16406
  }),
16388
- [Ky]: qy
16407
+ [qy]: Jy
16389
16408
  },
16390
16409
  timeoutS: a
16391
16410
  });
@@ -16409,7 +16428,7 @@ async function bb(e, t, n, r) {
16409
16428
  ...d
16410
16429
  };
16411
16430
  }
16412
- function xb(e) {
16431
+ function Sb(e) {
16413
16432
  if (!e.payload_json) return null;
16414
16433
  try {
16415
16434
  let t = JSON.parse(e.payload_json);
@@ -16418,23 +16437,23 @@ function xb(e) {
16418
16437
  return null;
16419
16438
  }
16420
16439
  }
16421
- function Sb(e) {
16440
+ function Cb(e) {
16422
16441
  return `${typeof e.title == "string" ? e.title : ""}\n${typeof e.body_text == "string" ? e.body_text : ""}`.trim().length > 0;
16423
16442
  }
16424
- function Cb(e) {
16443
+ function wb(e) {
16425
16444
  if (typeof e != "string") return null;
16426
16445
  let t = e.trim();
16427
16446
  return t.length > 0 ? t : null;
16428
16447
  }
16429
- function wb(e, t) {
16430
- return t || Cb(e.scope_id);
16448
+ function Tb(e, t) {
16449
+ return t || wb(e.scope_id);
16431
16450
  }
16432
- var Tb = /* @__PURE__ */ new Map();
16433
- function Eb(e, t, n) {
16434
- let r = n ?? "__none__", i = Tb.get(r);
16451
+ var Eb = /* @__PURE__ */ new Map();
16452
+ function Db(e, t, n) {
16453
+ let r = n ?? "__none__", i = Eb.get(r);
16435
16454
  if (i != null) return i;
16436
16455
  let a = n ? `__sync_bootstrap__:${n}` : "__sync_bootstrap__", o = e.select({ id: U.id }).from(U).where(k(U.cwd, a)).limit(1).get();
16437
- if (o) return Tb.set(r, o.id), o.id;
16456
+ if (o) return Eb.set(r, o.id), o.id;
16438
16457
  let s = e.insert(U).values({
16439
16458
  started_at: t,
16440
16459
  cwd: a,
@@ -16442,25 +16461,25 @@ function Eb(e, t, n) {
16442
16461
  user: "sync",
16443
16462
  tool_version: "bootstrap"
16444
16463
  }).returning({ id: U.id }).all()[0]?.id ?? 0;
16445
- return Tb.set(r, s), s;
16464
+ return Eb.set(r, s), s;
16446
16465
  }
16447
- function Db(e, t, n, r, i) {
16466
+ function Ob(e, t, n, r, i) {
16448
16467
  let a = {
16449
16468
  ok: !1,
16450
16469
  applied: 0,
16451
16470
  deleted: 0
16452
- }, o = i ?? new dl(), s = Cb(r.scope_id), c = s ? k(W.scope_id, s) : ve(pe(W.scope_id), k(W.scope_id, Su));
16471
+ }, o = i ?? new dl(), s = wb(r.scope_id), c = s ? k(W.scope_id, s) : ve(pe(W.scope_id), k(W.scope_id, Su));
16453
16472
  return e.transaction(() => {
16454
16473
  let i = N(e, { schema: H }), l = 0;
16455
- a.deleted = i.delete(W).where(O(fe(W.import_key), c, _e(M`COALESCE(${W.visibility}, '')`, "private"))).run().changes, Tb.clear();
16474
+ a.deleted = i.delete(W).where(O(fe(W.import_key), c, _e(M`COALESCE(${W.visibility}, '')`, "private"))).run().changes, Eb.clear();
16456
16475
  for (let e of n) {
16457
- let t = xb(e);
16476
+ let t = Sb(e);
16458
16477
  if (!t) continue;
16459
16478
  gl(t, o);
16460
- let n = wb(t, s), r = typeof t.project == "string" && t.project.trim() ? t.project.trim() : null, c = Eb(i, (/* @__PURE__ */ new Date()).toISOString(), r), u = t.metadata_json, d = u && typeof u == "object" && !Array.isArray(u) ? u : {};
16479
+ let n = Tb(t, s), r = typeof t.project == "string" && t.project.trim() ? t.project.trim() : null, c = Db(i, (/* @__PURE__ */ new Date()).toISOString(), r), u = t.metadata_json, d = u && typeof u == "object" && !Array.isArray(u) ? u : {};
16461
16480
  d.clock_device_id = e.clock_device_id;
16462
16481
  let f = e.op_type === "delete";
16463
- !f && Sb(t) && l++, i.insert(W).values({
16482
+ !f && Cb(t) && l++, i.insert(W).values({
16464
16483
  session_id: c,
16465
16484
  kind: typeof t.kind == "string" ? t.kind : "discovery",
16466
16485
  title: typeof t.title == "string" ? t.title : "",
@@ -16497,16 +16516,16 @@ function Db(e, t, n, r, i) {
16497
16516
  generation: r.generation,
16498
16517
  snapshot_id: r.snapshot_id,
16499
16518
  baseline_cursor: r.baseline_cursor
16500
- }, r.scope_id), ub(e, { embeddableTotal: l }), a.ok = !0;
16519
+ }, r.scope_id), db(e, { embeddableTotal: l }), a.ok = !0;
16501
16520
  }).immediate(), a;
16502
16521
  }
16503
16522
  //#endregion
16504
16523
  //#region src/sync-discovery.ts
16505
- var Ob = Ee(import.meta.url), kb = "_codemem._tcp.local.";
16506
- function Ab(e) {
16524
+ var kb = Ee(import.meta.url), Ab = "_codemem._tcp.local.";
16525
+ function jb(e) {
16507
16526
  return e.mdns.length === 0 ? yl(e.stored, []) : yl(e.mdns, e.stored);
16508
16527
  }
16509
- function jb(e, t) {
16528
+ function Mb(e, t) {
16510
16529
  let n = N(e, { schema: H }).select({ addresses_json: Y.addresses_json }).from(Y).where(k(Y.peer_device_id, t)).get();
16511
16530
  if (!n?.addresses_json) return [];
16512
16531
  try {
@@ -16516,8 +16535,8 @@ function jb(e, t) {
16516
16535
  return [];
16517
16536
  }
16518
16537
  }
16519
- function Mb(e, t, n, r) {
16520
- let i = yl(jb(e, t), n), a = (/* @__PURE__ */ new Date()).toISOString(), o = JSON.stringify(i);
16538
+ function Nb(e, t, n, r) {
16539
+ let i = yl(Mb(e, t), n), a = (/* @__PURE__ */ new Date()).toISOString(), o = JSON.stringify(i);
16521
16540
  return N(e, { schema: H }).insert(Y).values({
16522
16541
  peer_device_id: t,
16523
16542
  name: r?.name ?? null,
@@ -16537,7 +16556,7 @@ function Mb(e, t, n, r) {
16537
16556
  }
16538
16557
  }).run(), i;
16539
16558
  }
16540
- function Nb(e, t, n) {
16559
+ function Pb(e, t, n) {
16541
16560
  let r = N(e, { schema: H }), i = (/* @__PURE__ */ new Date()).toISOString();
16542
16561
  r.insert(ft).values({
16543
16562
  peer_device_id: t,
@@ -16552,10 +16571,10 @@ function Nb(e, t, n) {
16552
16571
  last_error: null
16553
16572
  }).where(k(Y.peer_device_id, t)).run() : r.update(Y).set({ last_error: n.error ?? null }).where(k(Y.peer_device_id, t)).run();
16554
16573
  }
16555
- function Pb(e, t, n) {
16574
+ function Fb(e, t, n) {
16556
16575
  let r = _l(n ?? ""), i = (/* @__PURE__ */ new Date()).toISOString();
16557
16576
  return e.transaction((t, n, r) => {
16558
- let i = jb(e, t), a = n ? i.filter((e) => _l(e) !== n) : i, o = n ? [n, ...a] : i;
16577
+ let i = Mb(e, t), a = n ? i.filter((e) => _l(e) !== n) : i, o = n ? [n, ...a] : i;
16559
16578
  return N(e, { schema: H }).update(Y).set({
16560
16579
  addresses_json: JSON.stringify(o),
16561
16580
  last_sync_at: r,
@@ -16564,18 +16583,18 @@ function Pb(e, t, n) {
16564
16583
  }).where(k(Y.peer_device_id, t)).run(), o;
16565
16584
  }).immediate(t, r, i);
16566
16585
  }
16567
- function Fb(e, t, n) {
16586
+ function Ib(e, t, n) {
16568
16587
  let r = n.include === null ? null : JSON.stringify(n.include), i = n.exclude === null ? null : JSON.stringify(n.exclude);
16569
16588
  N(e, { schema: H }).update(Y).set({
16570
16589
  projects_include_json: r,
16571
16590
  projects_exclude_json: i
16572
16591
  }).where(k(Y.peer_device_id, t)).run();
16573
16592
  }
16574
- function Ib(e, t, n) {
16593
+ function Lb(e, t, n) {
16575
16594
  N(e, { schema: H }).update(Y).set({ claimed_local_actor: +!!n }).where(k(Y.peer_device_id, t)).run();
16576
16595
  }
16577
- var Lb = "codemem";
16578
- function Rb() {
16596
+ var Rb = "codemem";
16597
+ function zb() {
16579
16598
  let e = process.env.CODEMEM_SYNC_MDNS;
16580
16599
  if (e) return e === "1" || e.toLowerCase() === "true";
16581
16600
  try {
@@ -16584,9 +16603,9 @@ function Rb() {
16584
16603
  return !1;
16585
16604
  }
16586
16605
  }
16587
- function zb() {
16606
+ function Bb() {
16588
16607
  try {
16589
- let e = Ob("bonjour-service"), t = e.Bonjour ?? e.default;
16608
+ let e = kb("bonjour-service"), t = e.Bonjour ?? e.default;
16590
16609
  return t ? new t(void 0, (e) => {
16591
16610
  console.warn("[codemem] mDNS runtime error (non-fatal):", e?.message ?? e);
16592
16611
  }) : null;
@@ -16594,40 +16613,40 @@ function zb() {
16594
16613
  return null;
16595
16614
  }
16596
16615
  }
16597
- var Bb = null, Vb = 0;
16598
- function Hb() {
16599
- if (Bb) return Vb += 1, Bb;
16600
- let e = zb();
16601
- return e ? (Bb = e, Vb = 1, Bb) : null;
16602
- }
16616
+ var Vb = null, Hb = 0;
16603
16617
  function Ub() {
16604
- if (!Bb || (Vb = Math.max(0, Vb - 1), Vb > 0)) return;
16605
- let e = Bb;
16606
- Bb = null;
16618
+ if (Vb) return Hb += 1, Vb;
16619
+ let e = Bb();
16620
+ return e ? (Vb = e, Hb = 1, Vb) : null;
16621
+ }
16622
+ function Wb() {
16623
+ if (!Vb || (Hb = Math.max(0, Hb - 1), Hb > 0)) return;
16624
+ let e = Vb;
16625
+ Vb = null;
16607
16626
  try {
16608
16627
  e.destroy();
16609
16628
  } catch {}
16610
16629
  }
16611
- function Wb(e, t) {
16612
- if (!Rb() || !e || !t || !Number.isFinite(t)) return { close() {} };
16613
- let n = Hb();
16630
+ function Gb(e, t) {
16631
+ if (!zb() || !e || !t || !Number.isFinite(t)) return { close() {} };
16632
+ let n = Ub();
16614
16633
  if (!n) return { close() {} };
16615
16634
  let r = null;
16616
16635
  try {
16617
16636
  r = n.publish({
16618
16637
  name: `codemem-${e.slice(0, 12)}`,
16619
- type: Lb,
16638
+ type: Rb,
16620
16639
  port: t,
16621
16640
  txt: { device_id: e }
16622
16641
  });
16623
16642
  } catch {
16624
- return Ub(), { close() {} };
16643
+ return Wb(), { close() {} };
16625
16644
  }
16626
16645
  let i = !1;
16627
16646
  return { close() {
16628
16647
  if (i) return;
16629
16648
  i = !0;
16630
- let e = () => Ub();
16649
+ let e = () => Wb();
16631
16650
  try {
16632
16651
  r?.stop(() => e());
16633
16652
  } catch {
@@ -16635,13 +16654,13 @@ function Wb(e, t) {
16635
16654
  }
16636
16655
  } };
16637
16656
  }
16638
- async function Gb(e = 1500) {
16639
- if (!Rb()) return [];
16640
- let t = Hb();
16657
+ async function Kb(e = 1500) {
16658
+ if (!zb()) return [];
16659
+ let t = Ub();
16641
16660
  if (!t) return [];
16642
16661
  let n = [], r = /* @__PURE__ */ new Set(), i = !0, a = null;
16643
16662
  try {
16644
- a = t.find({ type: Lb }, (e) => {
16663
+ a = t.find({ type: Rb }, (e) => {
16645
16664
  if (!i) return;
16646
16665
  let t = `${e.name}|${e.host ?? e.fqdn ?? ""}|${e.port}`;
16647
16666
  if (r.has(t)) return;
@@ -16661,11 +16680,11 @@ async function Gb(e = 1500) {
16661
16680
  try {
16662
16681
  a?.stop();
16663
16682
  } catch {}
16664
- Ub();
16683
+ Wb();
16665
16684
  }
16666
16685
  return n;
16667
16686
  }
16668
- function Kb(e, t) {
16687
+ function qb(e, t) {
16669
16688
  let n = [];
16670
16689
  for (let r of t) {
16671
16690
  let t = r.properties ?? {}, i = t.device_id ?? t.device_id;
@@ -16679,56 +16698,56 @@ function Kb(e, t) {
16679
16698
  }
16680
16699
  //#endregion
16681
16700
  //#region src/sync-pass.ts
16682
- var qb = 1048576, Jb = !1, Yb = 500, Xb = 2e3, Zb = "2";
16683
- function Qb(e, t) {
16701
+ var Jb = 1048576, Yb = !1, Xb = 500, Zb = 2e3, Qb = "2";
16702
+ function $b(e, t) {
16684
16703
  return !t || !t.includes("|") ? !1 : e ? t > e : !0;
16685
16704
  }
16686
- function $b(e) {
16705
+ function ex(e) {
16687
16706
  if (!e) return null;
16688
16707
  let t = e.error, n = e.reason;
16689
16708
  return typeof t == "string" && typeof n == "string" ? `${t}:${n}` : typeof t == "string" ? t : null;
16690
16709
  }
16691
- function ex(e) {
16710
+ function tx(e) {
16692
16711
  return e.length === 0 ? null : `all addresses failed | ${e.map((e) => `${e.address}: ${e.error}`).join(" || ")}`;
16693
16712
  }
16694
- function tx(e) {
16713
+ function nx(e) {
16695
16714
  if (typeof e != "string") return null;
16696
16715
  let t = e.trim();
16697
16716
  return t.length > 0 ? t : null;
16698
16717
  }
16699
- function nx(e) {
16718
+ function rx(e) {
16700
16719
  let t = e?.sync_reset;
16701
16720
  if (!t || typeof t != "object" || Array.isArray(t)) return null;
16702
16721
  let n = t;
16703
16722
  if (!Number.isFinite(n.generation) || typeof n.snapshot_id != "string" || n.snapshot_id.trim().length === 0) return null;
16704
- let r = tx(n.baseline_cursor);
16723
+ let r = nx(n.baseline_cursor);
16705
16724
  return {
16706
- scope_id: tx(n.scope_id),
16725
+ scope_id: nx(n.scope_id),
16707
16726
  generation: Number(n.generation),
16708
16727
  snapshot_id: n.snapshot_id.trim(),
16709
16728
  baseline_cursor: r,
16710
- retained_floor_cursor: tx(n.retained_floor_cursor)
16729
+ retained_floor_cursor: nx(n.retained_floor_cursor)
16711
16730
  };
16712
16731
  }
16713
- function rx(e) {
16732
+ function ix(e) {
16714
16733
  return !(!e || e.reset_required !== !1 || !Number.isFinite(e.generation) || typeof e.snapshot_id != "string" || e.snapshot_id.trim().length === 0 || !(e.baseline_cursor == null || typeof e.baseline_cursor == "string") || !(e.retained_floor_cursor == null || typeof e.retained_floor_cursor == "string") || !Array.isArray(e.ops) || !(e.next_cursor == null || typeof e.next_cursor == "string") || !Number.isFinite(e.skipped));
16715
16734
  }
16716
- function ix(e) {
16717
- let t = Yy(e);
16735
+ function ax(e) {
16736
+ let t = Xy(e);
16718
16737
  return {
16719
- local: qy,
16738
+ local: Jy,
16720
16739
  peer: t,
16721
- negotiated: Xy(qy, t)
16740
+ negotiated: Zy(Jy, t)
16722
16741
  };
16723
16742
  }
16724
- function ax() {
16725
- return { [Ky]: qy };
16726
- }
16727
16743
  function ox() {
16728
- return ix("unsupported");
16744
+ return { [qy]: Jy };
16729
16745
  }
16730
- function sx(e, t, n) {
16731
- let r = N(e, { schema: H }), i = (/* @__PURE__ */ new Date()).toISOString(), a = n.capabilities ?? ox();
16746
+ function sx() {
16747
+ return ax("unsupported");
16748
+ }
16749
+ function cx(e, t, n) {
16750
+ let r = N(e, { schema: H }), i = (/* @__PURE__ */ new Date()).toISOString(), a = n.capabilities ?? sx();
16732
16751
  r.insert(ft).values({
16733
16752
  peer_device_id: t,
16734
16753
  started_at: i,
@@ -16742,7 +16761,7 @@ function sx(e, t, n) {
16742
16761
  negotiated_sync_capability: a.negotiated
16743
16762
  }).run();
16744
16763
  }
16745
- function cx(e, t, n, r) {
16764
+ function lx(e, t, n, r) {
16746
16765
  let i = N(e, { schema: H }), { replicationOps: a } = H, o;
16747
16766
  if (t) {
16748
16767
  let e = t.indexOf("|"), s = e >= 0 ? t.slice(0, e) : t, c = e >= 0 ? t.slice(e + 1) : "";
@@ -16754,12 +16773,12 @@ function cx(e, t, n, r) {
16754
16773
  let c = `${s.created_at}|${s.op_id}`;
16755
16774
  return [o, c];
16756
16775
  }
16757
- var lx = 8;
16758
- async function ux(e, t, n, r, i = 0) {
16776
+ var ux = 8;
16777
+ async function dx(e, t, n, r, i = 0) {
16759
16778
  if (n.length === 0) return;
16760
16779
  let a = {
16761
16780
  ops: n,
16762
- sync_capability: qy
16781
+ sync_capability: Jy
16763
16782
  }, o = Buffer.from(JSON.stringify(a), "utf-8"), [s, c] = await xl("POST", e, {
16764
16783
  headers: {
16765
16784
  ..._r({
@@ -16769,28 +16788,28 @@ async function ux(e, t, n, r, i = 0) {
16769
16788
  bodyBytes: o,
16770
16789
  keysDir: r
16771
16790
  }),
16772
- ...ax()
16791
+ ...ox()
16773
16792
  },
16774
16793
  body: a,
16775
16794
  bodyBytes: o
16776
16795
  });
16777
16796
  if (s === 200 && c != null) return;
16778
- let l = $b(c);
16779
- if (s === 413 && n.length > 1 && i < lx && (l === "payload_too_large" || l === "too_many_ops")) {
16797
+ let l = ex(c);
16798
+ if (s === 413 && n.length > 1 && i < ux && (l === "payload_too_large" || l === "too_many_ops")) {
16780
16799
  let a = Math.floor(n.length / 2);
16781
- await ux(e, t, n.slice(0, a), r, i + 1), await ux(e, t, n.slice(a), r, i + 1);
16800
+ await dx(e, t, n.slice(0, a), r, i + 1), await dx(e, t, n.slice(a), r, i + 1);
16782
16801
  return;
16783
16802
  }
16784
16803
  let u = l ? ` (${s}: ${l})` : ` (${s})`;
16785
16804
  throw Error(`peer ops push failed${u}`);
16786
16805
  }
16787
- function dx(e) {
16806
+ function fx(e) {
16788
16807
  Hn(e), qd(e, 2e3), Jd(e, 200);
16789
16808
  }
16790
- async function fx(e, t, n, r) {
16809
+ async function px(e, t, n, r) {
16791
16810
  Hn(e);
16792
- let i = r?.limit ?? Yb, a = r?.keysDir, o = r?.scanner;
16793
- !o && !Jb && (Jb = !0, process.stderr.write("[codemem] sync apply running without explicit scanner — workspace-level secret rules will not apply to inbound peer content\n"));
16811
+ let i = r?.limit ?? Xb, a = r?.keysDir, o = r?.scanner;
16812
+ !o && !Yb && (Yb = !0, process.stderr.write("[codemem] sync apply running without explicit scanner — workspace-level secret rules will not apply to inbound peer content\n"));
16794
16813
  let s = N(e, { schema: H }).select({ pinned_fingerprint: Y.pinned_fingerprint }).from(Y).where(k(Y.peer_device_id, t)).get()?.pinned_fingerprint ?? "";
16795
16814
  if (!s) return {
16796
16815
  ok: !1,
@@ -16804,7 +16823,7 @@ async function fx(e, t, n, r) {
16804
16823
  [u] = dr(e, { keysDir: a });
16805
16824
  } catch (n) {
16806
16825
  let r = `device identity unavailable: ${n instanceof Error ? n.message.trim() || n.constructor.name : "unknown"}`;
16807
- return sx(e, t, {
16826
+ return cx(e, t, {
16808
16827
  ok: !1,
16809
16828
  error: r
16810
16829
  }), {
@@ -16829,15 +16848,15 @@ async function fx(e, t, n, r) {
16829
16848
  bodyBytes: Buffer.alloc(0),
16830
16849
  keysDir: a
16831
16850
  }),
16832
- ...ax()
16851
+ ...ox()
16833
16852
  } });
16834
16853
  if (d !== 200 || !f) {
16835
- let e = $b(f), t = e ? ` (${d}: ${e})` : ` (${d})`;
16854
+ let e = ex(f), t = e ? ` (${d}: ${e})` : ` (${d})`;
16836
16855
  throw Error(`peer status failed${t}`);
16837
16856
  }
16838
16857
  if (f.fingerprint !== s) throw Error("peer fingerprint mismatch");
16839
- if (p = ix(f.sync_capability), String(f.protocol_version ?? "") !== Zb) throw Error(`peer protocol mismatch (expected ${Zb}, got ${String(f.protocol_version ?? "missing")})`);
16840
- let m = nx(f);
16858
+ if (p = ax(f.sync_capability), String(f.protocol_version ?? "") !== Qb) throw Error(`peer protocol mismatch (expected ${Qb}, got ${String(f.protocol_version ?? "missing")})`);
16859
+ let m = rx(f);
16841
16860
  if (!m) throw Error("peer status missing sync_reset boundary");
16842
16861
  if (c === null && l === null && Number(e.prepare("SELECT count(*) as n FROM memory_items WHERE import_key IS NOT NULL").get()?.n ?? 0) === 0) try {
16843
16862
  let r = {
@@ -16848,11 +16867,11 @@ async function fx(e, t, n, r) {
16848
16867
  retained_floor_cursor: m.retained_floor_cursor ?? null,
16849
16868
  reset_required: !0,
16850
16869
  reason: "initial_bootstrap"
16851
- }, { items: i } = await bb(n, r, u, {
16870
+ }, { items: i } = await xb(n, r, u, {
16852
16871
  keysDir: a,
16853
- pageSize: Xb
16872
+ pageSize: Zb
16854
16873
  }), s = Number(e.prepare("SELECT count(*) as n FROM memory_items WHERE import_key IS NOT NULL").get()?.n ?? 0);
16855
- if (s > 0) return sx(e, t, {
16874
+ if (s > 0) return cx(e, t, {
16856
16875
  ok: !1,
16857
16876
  error: "needs_attention:shared_memories_appeared_during_bootstrap",
16858
16877
  capabilities: p
@@ -16864,9 +16883,9 @@ async function fx(e, t, n, r) {
16864
16883
  opsOut: 0,
16865
16884
  addressErrors: []
16866
16885
  };
16867
- let c = Db(e, t, i, r, o);
16886
+ let c = Ob(e, t, i, r, o);
16868
16887
  if (!c.ok) throw Error("initial bootstrap apply failed");
16869
- return Pb(e, t, n), sx(e, t, {
16888
+ return Fb(e, t, n), cx(e, t, {
16870
16889
  ok: !0,
16871
16890
  opsIn: c.applied,
16872
16891
  opsOut: 0,
@@ -16897,7 +16916,7 @@ async function fx(e, t, n, r) {
16897
16916
  bodyBytes: Buffer.alloc(0),
16898
16917
  keysDir: a
16899
16918
  }),
16900
- ...ax()
16919
+ ...ox()
16901
16920
  } });
16902
16921
  if (_ === 409 && v?.reset_required === !0) {
16903
16922
  let r = ad(e), i = {
@@ -16909,7 +16928,7 @@ async function fx(e, t, n, r) {
16909
16928
  baseline_cursor: typeof v.baseline_cursor == "string" && v.baseline_cursor.trim() ? v.baseline_cursor.trim() : null,
16910
16929
  retained_floor_cursor: typeof v.retained_floor_cursor == "string" && v.retained_floor_cursor.trim() ? v.retained_floor_cursor.trim() : null
16911
16930
  };
16912
- if (r.dirty) return sx(e, t, {
16931
+ if (r.dirty) return cx(e, t, {
16913
16932
  ok: !1,
16914
16933
  error: `needs_attention:local_unsynced_shared_memory:${r.count}`,
16915
16934
  capabilities: p
@@ -16923,8 +16942,8 @@ async function fx(e, t, n, r) {
16923
16942
  resetRequired: i
16924
16943
  };
16925
16944
  try {
16926
- let { items: r } = await bb(n, i, u, { keysDir: a }), s = ad(e);
16927
- if (s.dirty) return sx(e, t, {
16945
+ let { items: r } = await xb(n, i, u, { keysDir: a }), s = ad(e);
16946
+ if (s.dirty) return cx(e, t, {
16928
16947
  ok: !1,
16929
16948
  error: `needs_attention:local_unsynced_shared_memory:${s.count}`,
16930
16949
  capabilities: p
@@ -16937,9 +16956,9 @@ async function fx(e, t, n, r) {
16937
16956
  addressErrors: [],
16938
16957
  resetRequired: i
16939
16958
  };
16940
- let c = Db(e, t, r, i, o);
16959
+ let c = Ob(e, t, r, i, o);
16941
16960
  if (!c.ok) throw Error("bootstrap apply failed");
16942
- return Pb(e, t, n), sx(e, t, {
16961
+ return Fb(e, t, n), cx(e, t, {
16943
16962
  ok: !0,
16944
16963
  opsIn: c.applied,
16945
16964
  opsOut: 0,
@@ -16953,7 +16972,7 @@ async function fx(e, t, n, r) {
16953
16972
  };
16954
16973
  } catch (r) {
16955
16974
  let a = r instanceof Error ? r.message : String(r);
16956
- return sx(e, t, {
16975
+ return cx(e, t, {
16957
16976
  ok: !1,
16958
16977
  error: `bootstrap_failed:${a}`,
16959
16978
  capabilities: p
@@ -16969,10 +16988,10 @@ async function fx(e, t, n, r) {
16969
16988
  }
16970
16989
  }
16971
16990
  if (_ !== 200 || v == null) {
16972
- let e = $b(v), t = e ? ` (${_}: ${e})` : ` (${_})`;
16991
+ let e = ex(v), t = e ? ` (${_}: ${e})` : ` (${_})`;
16973
16992
  throw Error(`peer ops fetch failed${t}`);
16974
16993
  }
16975
- if (!rx(v)) throw Error("invalid ops response");
16994
+ if (!ix(v)) throw Error("invalid ops response");
16976
16995
  let y = Xu(v), b = y.find((e) => e.device_id !== t || e.clock_device_id !== t);
16977
16996
  if (b) throw Error(`inbound op device mismatch:${b.op_id}`);
16978
16997
  let x = p?.negotiated === "unsupported" ? {
@@ -16984,7 +17003,7 @@ async function fx(e, t, n, r) {
16984
17003
  throw Error(`inbound scope rejected:${e}`);
16985
17004
  }
16986
17005
  try {
16987
- cb(e, S.vectorWork);
17006
+ lb(e, S.vectorWork);
16988
17007
  } catch (t) {
16989
17008
  let n = await Ds(e, S.vectorWork);
16990
17009
  if (n.errors.length > 0) {
@@ -16992,15 +17011,15 @@ async function fx(e, t, n, r) {
16992
17011
  throw Error(`vector catch-up queue failed: ${t instanceof Error ? t.message : String(t)}; fallback failed: ${e}`);
16993
17012
  }
16994
17013
  }
16995
- let C = tx(v.next_cursor);
16996
- Qb(c, C) && (Ju(e, t, { lastApplied: C }), c = C);
16997
- let [w, ee] = cx(e, l, u, i), [T, te, ne] = Ad(e, w, t, { localDeviceId: u }), re = ne?.skipped_count ?? 0, ie = `${n}/v1/ops`;
17014
+ let C = nx(v.next_cursor);
17015
+ $b(c, C) && (Ju(e, t, { lastApplied: C }), c = C);
17016
+ let [w, ee] = lx(e, l, u, i), [T, te, ne] = Ad(e, w, t, { localDeviceId: u }), re = ne?.skipped_count ?? 0, ie = `${n}/v1/ops`;
16998
17017
  if (T.length > 0) {
16999
- let e = Uu(T, qb);
17000
- for (let t of e) await ux(ie, u, t, a);
17018
+ let e = Uu(T, Jb);
17019
+ for (let t of e) await dx(ie, u, t, a);
17001
17020
  }
17002
17021
  let ae = te ?? ee;
17003
- return ae && Qb(l, ae) && (Ju(e, t, { lastAcked: ae }), l = ae), Pb(e, t, n), sx(e, t, {
17022
+ return ae && $b(l, ae) && (Ju(e, t, { lastAcked: ae }), l = ae), Fb(e, t, n), cx(e, t, {
17004
17023
  ok: !0,
17005
17024
  opsIn: S.applied,
17006
17025
  opsOut: T.length,
@@ -17023,8 +17042,8 @@ async function fx(e, t, n, r) {
17023
17042
  }
17024
17043
  }
17025
17044
  }
17026
- let m = ex(d);
17027
- return f || (m = "no dialable peer addresses"), m ||= "sync failed without diagnostic detail", sx(e, t, {
17045
+ let m = tx(d);
17046
+ return f || (m = "no dialable peer addresses"), m ||= "sync failed without diagnostic detail", cx(e, t, {
17028
17047
  ok: !1,
17029
17048
  error: m,
17030
17049
  capabilities: p
@@ -17036,15 +17055,15 @@ async function fx(e, t, n, r) {
17036
17055
  addressErrors: d
17037
17056
  };
17038
17057
  }
17039
- async function px(e, t, n) {
17058
+ async function mx(e, t, n) {
17040
17059
  let r = N(e, { schema: H }).select({ addresses_json: Y.addresses_json }).from(Y).where(k(Y.peer_device_id, t)).get(), i = [];
17041
17060
  if (r?.addresses_json) try {
17042
17061
  let e = JSON.parse(r.addresses_json);
17043
17062
  Array.isArray(e) && (i = e.filter((e) => typeof e == "string"));
17044
17063
  } catch {}
17045
- return fx(e, t, i, n);
17064
+ return px(e, t, i, n);
17046
17065
  }
17047
- var mx = [
17066
+ var hx = [
17048
17067
  "no route to host",
17049
17068
  "connection refused",
17050
17069
  "network is unreachable",
@@ -17055,33 +17074,33 @@ var mx = [
17055
17074
  "errno 61",
17056
17075
  "errno 60",
17057
17076
  "errno 111"
17058
- ], hx = 120, gx = 1800;
17059
- function _x(e) {
17077
+ ], gx = 120, _x = 1800;
17078
+ function vx(e) {
17060
17079
  if (!e) return !1;
17061
17080
  let t = e.toLowerCase();
17062
- return mx.some((e) => t.includes(e));
17081
+ return hx.some((e) => t.includes(e));
17063
17082
  }
17064
- function vx(e, t, n = 10) {
17083
+ function yx(e, t, n = 10) {
17065
17084
  let r = N(e, { schema: H }).select({
17066
17085
  ok: ft.ok,
17067
17086
  error: ft.error
17068
17087
  }).from(ft).where(k(ft.peer_device_id, t)).orderBy(ue(ft.started_at)).limit(n).all(), i = 0;
17069
17088
  for (let e of r) {
17070
17089
  if (e.ok) break;
17071
- if (_x(e.error)) i++;
17090
+ if (vx(e.error)) i++;
17072
17091
  else break;
17073
17092
  }
17074
17093
  return i;
17075
17094
  }
17076
- function yx(e) {
17095
+ function bx(e) {
17077
17096
  if (e <= 1) return 0;
17078
17097
  let t = Math.min(e - 1, 8);
17079
- return Math.min(hx * 2 ** (t - 1), gx) * (.5 + Math.random() * .5);
17098
+ return Math.min(gx * 2 ** (t - 1), _x) * (.5 + Math.random() * .5);
17080
17099
  }
17081
- function bx(e, t) {
17082
- let n = vx(e, t);
17100
+ function xx(e, t) {
17101
+ let n = yx(e, t);
17083
17102
  if (n < 2) return !1;
17084
- let r = yx(n);
17103
+ let r = bx(n);
17085
17104
  if (r <= 0) return !1;
17086
17105
  let i = N(e, { schema: H }).select({ started_at: ft.started_at }).from(ft).where(k(ft.peer_device_id, t)).orderBy(ue(ft.started_at)).limit(1).get();
17087
17106
  if (!i?.started_at) return !1;
@@ -17094,7 +17113,7 @@ function bx(e, t) {
17094
17113
  }
17095
17114
  //#endregion
17096
17115
  //#region src/sync-daemon.ts
17097
- function xx(e) {
17116
+ function Sx(e) {
17098
17117
  let t = N(e, { schema: H }), n = (/* @__PURE__ */ new Date()).toISOString();
17099
17118
  t.insert(mt).values({
17100
17119
  id: 1,
@@ -17108,7 +17127,7 @@ function xx(e) {
17108
17127
  }
17109
17128
  }).run();
17110
17129
  }
17111
- function Sx(e, t, n) {
17130
+ function Cx(e, t, n) {
17112
17131
  let r = N(e, { schema: H }), i = (/* @__PURE__ */ new Date()).toISOString();
17113
17132
  r.insert(mt).values({
17114
17133
  id: 1,
@@ -17124,11 +17143,11 @@ function Sx(e, t, n) {
17124
17143
  }
17125
17144
  }).run();
17126
17145
  }
17127
- function Cx(e) {
17146
+ function wx(e) {
17128
17147
  let t = N(e, { schema: H }).select({ phase: mt.phase }).from(mt).where(k(mt.id, 1)).get()?.phase;
17129
17148
  return t === "needs_attention" ? t : null;
17130
17149
  }
17131
- function wx(e, t) {
17150
+ function Tx(e, t) {
17132
17151
  N(e, { schema: H }).insert(mt).values({
17133
17152
  id: 1,
17134
17153
  phase: t
@@ -17137,18 +17156,18 @@ function wx(e, t) {
17137
17156
  set: { phase: t }
17138
17157
  }).run();
17139
17158
  }
17140
- async function Tx(e, t, n) {
17159
+ async function Ex(e, t, n) {
17141
17160
  let r = Al();
17142
17161
  return jl(r) ? (await Nl({
17143
17162
  db: e,
17144
17163
  dbPath: t
17145
17164
  }, r, { keysDir: n }), await hu(e, r), !0) : !1;
17146
17165
  }
17147
- async function Ex(e, t, n, r) {
17166
+ async function Dx(e, t, n, r) {
17148
17167
  let i = N(e, { schema: H }).select({ peer_device_id: Y.peer_device_id }).from(Y).all();
17149
17168
  if (i.length === 0) return [];
17150
17169
  let a = Al().syncOpsLimit;
17151
- dx(e);
17170
+ fx(e);
17152
17171
  let o = [];
17153
17172
  for (let s of i) {
17154
17173
  let i = s.peer_device_id;
@@ -17160,7 +17179,7 @@ async function Ex(e, t, n, r) {
17160
17179
  });
17161
17180
  continue;
17162
17181
  }
17163
- if (bx(e, i)) {
17182
+ if (xx(e, i)) {
17164
17183
  o.push({
17165
17184
  ok: !1,
17166
17185
  skipped: !0,
@@ -17168,7 +17187,7 @@ async function Ex(e, t, n, r) {
17168
17187
  });
17169
17188
  continue;
17170
17189
  }
17171
- let c = await px(e, i, {
17190
+ let c = await mx(e, i, {
17172
17191
  keysDir: t,
17173
17192
  limit: a,
17174
17193
  scanner: r
@@ -17182,13 +17201,13 @@ async function Ex(e, t, n, r) {
17182
17201
  }
17183
17202
  return o;
17184
17203
  }
17185
- async function Dx(e) {
17204
+ async function Ox(e) {
17186
17205
  let t = e?.intervalS ?? 120, n = Dn(e?.dbPath), r = e?.keysDir, i = e?.signal, a = e?.onPhaseChange, o = e?.scanner;
17187
17206
  a?.("starting");
17188
17207
  let s = Mn(n), c = null;
17189
17208
  try {
17190
17209
  let [t] = dr(s, { keysDir: r });
17191
- Rb() && e?.port && (c = Wb(t, e.port));
17210
+ zb() && e?.port && (c = Gb(t, e.port));
17192
17211
  } finally {
17193
17212
  s.close();
17194
17213
  }
@@ -17198,7 +17217,7 @@ async function Dx(e) {
17198
17217
  }
17199
17218
  return new Promise((e) => {
17200
17219
  let s = !1, l = !1, u = () => {
17201
- s || (s = !0, Ox(n, r, o).finally(() => {
17220
+ s || (s = !0, kx(n, r, o).finally(() => {
17202
17221
  s = !1, l || (l = !0, a?.("running"));
17203
17222
  }));
17204
17223
  }, d = setInterval(u, t * 1e3);
@@ -17215,38 +17234,38 @@ async function Dx(e) {
17215
17234
  }
17216
17235
  });
17217
17236
  }
17218
- async function Ox(e, t, n) {
17237
+ async function kx(e, t, n) {
17219
17238
  let r = Mn(e);
17220
17239
  try {
17221
17240
  Hn(r);
17222
17241
  try {
17223
- await Tx(r, e, t);
17242
+ await Ex(r, e, t);
17224
17243
  } catch {}
17225
- (await Ex(r, t, await Rl(r, e, t), n)).some((e) => !e.ok && e.error?.includes("needs_attention")) ? wx(r, "needs_attention") : xx(r);
17244
+ (await Dx(r, t, await Rl(r, e, t), n)).some((e) => !e.ok && e.error?.includes("needs_attention")) ? Tx(r, "needs_attention") : Sx(r);
17226
17245
  } catch (e) {
17227
- Sx(r, e instanceof Error ? e.message : String(e), e instanceof Error ? e.stack ?? "" : "");
17246
+ Cx(r, e instanceof Error ? e.message : String(e), e instanceof Error ? e.stack ?? "" : "");
17228
17247
  } finally {
17229
17248
  r.close();
17230
17249
  }
17231
17250
  }
17232
17251
  //#endregion
17233
17252
  //#region src/sync-retention-runner.ts
17234
- function kx(e) {
17253
+ function Ax(e) {
17235
17254
  let t = String(e ?? "").trim();
17236
17255
  return t.length > 0 ? t : Su;
17237
17256
  }
17238
- function Ax(e) {
17257
+ function jx(e) {
17239
17258
  e.exec("\n CREATE TABLE IF NOT EXISTS sync_retention_state (\n id INTEGER PRIMARY KEY,\n last_run_at TEXT,\n last_duration_ms INTEGER,\n last_deleted_ops INTEGER NOT NULL DEFAULT 0,\n last_estimated_bytes_before INTEGER,\n last_estimated_bytes_after INTEGER,\n retained_floor_cursor TEXT,\n last_error TEXT,\n last_error_at TEXT\n );\n CREATE TABLE IF NOT EXISTS sync_retention_state_v2 (\n scope_id TEXT PRIMARY KEY NOT NULL,\n last_run_at TEXT,\n last_duration_ms INTEGER,\n last_deleted_ops INTEGER NOT NULL DEFAULT 0,\n last_estimated_bytes_before INTEGER,\n last_estimated_bytes_after INTEGER,\n retained_floor_cursor TEXT,\n last_error TEXT,\n last_error_at TEXT\n )\n ");
17240
17259
  }
17241
- function jx(e) {
17260
+ function Mx(e) {
17242
17261
  let t = e.prepare("SELECT scope_id FROM (\n SELECT COALESCE(NULLIF(TRIM(scope_id), ''), ?) AS scope_id FROM replication_ops\n UNION\n SELECT COALESCE(NULLIF(TRIM(scope_id), ''), ?) AS scope_id FROM sync_reset_state_v2\n UNION\n SELECT COALESCE(NULLIF(TRIM(scope_id), ''), ?) AS scope_id FROM sync_retention_state_v2\n )\n ORDER BY CASE WHEN scope_id = ? THEN 0 ELSE 1 END, scope_id").all(Su, Su, Su, Su), n = new Set([Su]);
17243
17262
  for (let e of t) {
17244
- let t = kx(e.scope_id);
17263
+ let t = Ax(e.scope_id);
17245
17264
  n.add(t);
17246
17265
  }
17247
17266
  return Array.from(n);
17248
17267
  }
17249
- function Mx(e, t, n, r) {
17268
+ function Nx(e, t, n, r) {
17250
17269
  e.insert(vt).values({
17251
17270
  scope_id: t,
17252
17271
  ...n
@@ -17261,7 +17280,7 @@ function Mx(e, t, n, r) {
17261
17280
  set: n
17262
17281
  }).run();
17263
17282
  }
17264
- function Nx(e, t, n, r, i) {
17283
+ function Px(e, t, n, r, i) {
17265
17284
  let a = i === Su;
17266
17285
  try {
17267
17286
  let o = dd(e, i), s = sd(e, {
@@ -17273,7 +17292,7 @@ function Nx(e, t, n, r, i) {
17273
17292
  maxPasses: n.maxCatchUpPasses,
17274
17293
  signal: n.signal
17275
17294
  });
17276
- Mx(t, i, {
17295
+ Nx(t, i, {
17277
17296
  last_run_at: r,
17278
17297
  last_duration_ms: Date.now() - Date.parse(r),
17279
17298
  last_deleted_ops: s.totalDeleted,
@@ -17284,7 +17303,7 @@ function Nx(e, t, n, r, i) {
17284
17303
  last_error_at: null
17285
17304
  }, a);
17286
17305
  } catch (e) {
17287
- Mx(t, i, {
17306
+ Nx(t, i, {
17288
17307
  last_run_at: r,
17289
17308
  last_duration_ms: Date.now() - Date.parse(r),
17290
17309
  last_deleted_ops: 0,
@@ -17296,13 +17315,13 @@ function Nx(e, t, n, r, i) {
17296
17315
  }, a);
17297
17316
  }
17298
17317
  }
17299
- async function Px(e, t) {
17318
+ async function Fx(e, t) {
17300
17319
  if (!t.syncRetentionEnabled) return;
17301
- Ax(e);
17302
- let n = N(e, { schema: H }), r = (/* @__PURE__ */ new Date()).toISOString(), i = t.scopeId === void 0 ? jx(e) : [kx(t.scopeId)];
17303
- for (let a of i) Nx(e, n, t, r, a);
17320
+ jx(e);
17321
+ let n = N(e, { schema: H }), r = (/* @__PURE__ */ new Date()).toISOString(), i = t.scopeId === void 0 ? Mx(e) : [Ax(t.scopeId)];
17322
+ for (let a of i) Px(e, n, t, r, a);
17304
17323
  }
17305
- var Fx = class {
17324
+ var Ix = class {
17306
17325
  dbPath;
17307
17326
  signal;
17308
17327
  active = !1;
@@ -17330,7 +17349,7 @@ var Fx = class {
17330
17349
  if (!this.active || this.signal?.aborted) return;
17331
17350
  let e = Al(Rt()), t = Mn(this.dbPath);
17332
17351
  try {
17333
- await Px(t, {
17352
+ await Fx(t, {
17334
17353
  ...e,
17335
17354
  signal: this.signal
17336
17355
  });
@@ -17338,8 +17357,8 @@ var Fx = class {
17338
17357
  t.close();
17339
17358
  }
17340
17359
  }
17341
- }, Ix = "scope_id";
17342
- function Lx(e, t) {
17360
+ }, Lx = "scope_id";
17361
+ function Rx(e, t) {
17343
17362
  return t ? typeof e == "string" && e.trim() ? {
17344
17363
  ok: !1,
17345
17364
  reason: "unsupported_scope"
@@ -17352,31 +17371,31 @@ function Lx(e, t) {
17352
17371
  scope_id: null
17353
17372
  };
17354
17373
  }
17355
- function Rx(e, t) {
17374
+ function zx(e, t) {
17356
17375
  return {
17357
17376
  ...e,
17358
17377
  scope_id: t
17359
17378
  };
17360
17379
  }
17361
- function zx(e, t, n) {
17380
+ function Bx(e, t, n) {
17362
17381
  return {
17363
17382
  error: "reset_required",
17364
17383
  reset_required: !0,
17365
17384
  sync_capability: n,
17366
17385
  reason: t,
17367
- ...Rx(e, null)
17386
+ ...zx(e, null)
17368
17387
  };
17369
17388
  }
17370
17389
  //#endregion
17371
17390
  //#region src/test-utils.ts
17372
- function Bx(e) {
17391
+ function Vx(e) {
17373
17392
  hn(e);
17374
17393
  }
17375
- function Vx(e) {
17394
+ function Hx(e) {
17376
17395
  let t = (/* @__PURE__ */ new Date()).toISOString(), n = e.prepare("INSERT INTO sessions(started_at, cwd, project, user, tool_version) VALUES (?, ?, ?, ?, ?)").run(t, "/tmp/test", "test-project", "test-user", "test");
17377
17396
  return Number(n.lastInsertRowid);
17378
17397
  }
17379
- function Hx(e, t = "local") {
17398
+ function Ux(e, t = "local") {
17380
17399
  let n = "2026-04-01T00:00:00.000Z", r = "fixture-work-authorized", i = "fixture-oss-hidden", a = "mixedscopeleak";
17381
17400
  e.prepare("INSERT OR IGNORE INTO sync_device(device_id, public_key, fingerprint, created_at) VALUES (?, ?, ?, ?)").run(t, "fixture-public-key", "fixture-fingerprint", n), e.prepare("INSERT OR REPLACE INTO replication_scopes(\n scope_id, label, kind, authority_type, coordinator_id, group_id,\n membership_epoch, status, created_at, updated_at\n ) VALUES (?, ?, 'team', 'coordinator', 'fixture-coordinator', 'fixture-group', 0, 'active', ?, ?)").run(r, "Authorized work fixture", n, n), e.prepare("INSERT OR REPLACE INTO replication_scopes(\n scope_id, label, kind, authority_type, coordinator_id, group_id,\n membership_epoch, status, created_at, updated_at\n ) VALUES (?, ?, 'team', 'coordinator', 'fixture-coordinator', 'fixture-group', 0, 'active', ?, ?)").run(i, "Hidden OSS fixture", n, n), e.prepare("INSERT OR REPLACE INTO scope_memberships(\n scope_id, device_id, role, status, membership_epoch,\n coordinator_id, group_id, updated_at\n ) VALUES (?, ?, 'member', 'active', 0, 'fixture-coordinator', 'fixture-group', ?)").run(r, t, n);
17382
17401
  let o = e.prepare("INSERT INTO sessions(started_at, cwd, project, user, tool_version, metadata_json, import_key)\n VALUES (?, '/tmp/mixed-domain-fixture', 'mixed-domain-fixture', 'test-user', 'test', '{}', 'fixture-session')").run(n), s = Number(o.lastInsertRowid), c = (t) => {
@@ -17425,8 +17444,8 @@ function Hx(e, t = "local") {
17425
17444
  }
17426
17445
  //#endregion
17427
17446
  //#region src/index.ts
17428
- var Ux = "0.30.0-alpha.3";
17447
+ var Wx = "0.30.0-alpha.5";
17429
17448
  //#endregion
17430
- export { ke as Api, V as BetterSqliteCoordinatorStore, Ft as CODEMEM_CONFIG_ENV_OVERRIDES, xh as DEDUP_KEY_BACKFILL_JOB, R as DEFAULT_COORDINATOR_DB_PATH, En as DEFAULT_DB_PATH, Wl as DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS, kb as DEFAULT_SERVICE_TYPE, Su as DEFAULT_SYNC_SCOPE_ID, o as DEFAULT_TIME_WINDOW_S, Th as DedupKeyBackfillRunner, si as INJECTION_EVAL_SCENARIO_PACKS, yv as LEGACY_SHARED_REVIEW_SCOPE_ID, Ti as LOCAL_DEFAULT_SCOPE_ID, qy as LOCAL_SYNC_CAPABILITY, zg as LOW_SIGNAL_TOOLS, Sr as MAPPABLE_CLAUDE_HOOK_EVENTS, Cn as MIN_COMPATIBLE_SCHEMA, Ae as MUTATING_TOOL_NAMES, bf as MemoryStore, yp as ObserverAuthAdapter, Hp as ObserverAuthError, pm as ObserverClient, gy as REF_BACKFILL_JOB, mg as RICH_TIER_DEFAULTS, hy as RawEventSweeper, Sy as RefBackfillRunner, Sn as SCHEMA_VERSION, bv as SCOPE_BACKFILL_JOB, n as SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, Cy as SESSION_CONTEXT_BACKFILL_JOB, fr as SIGNATURE_VERSION, pg as SIMPLE_TIER_DEFAULTS, Ly as SUMMARY_DEDUP_BACKFILL_JOB, Gy as SYNC_CAPABILITIES, Ky as SYNC_CAPABILITY_HEADER, Ix as SYNC_SCOPE_QUERY_PARAM, Iv as ScopeBackfillRunner, Iy as SessionContextBackfillRunner, Wy as SummaryDedupBackfillRunner, Fx as SyncRetentionRunner, p_ as TRIVIAL_REQUESTS, Zy as VECTOR_MODEL_MIGRATION_JOB, Ux as VERSION, yb as VectorModelMigrationRunner, Qo as _resetEmbeddingClient, Rx as addSyncScopeToBoundary, vl as addressDedupeKey, Wb as advertiseMdns, Om as aiBackfillStructuredContent, cy as analyzeProjectScopeMappingChangeGuardrails, Db as applyBootstrapSnapshot, Zd as applyReplicationOps, zn as assertSchemaReady, ep as backfillMemoryDedupKeys, Yf as backfillNarrativeFromBody, Jd as backfillReplicationOps, Nv as backfillScopeIds, zf as backfillTagsText, ks as backfillVectors, hn as bootstrapSchema, Zg as budgetToolEvents, _r as buildAuthHeaders, bl as buildBaseUrl, pr as buildCanonicalRequest, mp as buildCodexHeaders, Ji as buildFilterClauses, Yi as buildFilterClausesWithContext, Ih as buildImportKey, zr as buildIngestPayloadFromHook, qc as buildMemoryPack, Yc as buildMemoryPackAsync, Jc as buildMemoryPackTrace, Xc as buildMemoryPackTraceAsync, d_ as buildObserverPrompt, Rr as buildRawEventEnvelopeFromHook, tv as buildSessionContext, v_ as buildTranscript, cd as bulkPruneReplicationOpsByAgeCutoff, mi as canonicalMemoryKind, ji as canonicalWorkspaceIdentity, Uu as chunkOpsBySize, Xo as chunkText, Cv as classifyLegacyMemoryScope, J_ as cleanOrphanSessions, yr as cleanupNonces, ha as clearMemoryRefs, Zu as clockTuple, Af as compareMemoryRoleReports, Yr as completeMaintenanceJob, Mn as connect, Xe as connectCoordinator, vx as consecutiveConnectivityFailures, qm as coordinatorArchiveGroupAction, Gm as coordinatorCreateGroupAction, ch as coordinatorCreateInviteAction, Zm as coordinatorCreateScopeAction, ah as coordinatorDisableDeviceAction, oh as coordinatorEnableDeviceAction, jl as coordinatorEnabled, nh as coordinatorEnrollDeviceAction, eh as coordinatorGrantScopeMembershipAction, lh as coordinatorImportInviteAction, fh as coordinatorListBootstrapGrantsAction, rh as coordinatorListDevicesAction, Ym as coordinatorListGroupsAction, uh as coordinatorListJoinRequestsAction, $m as coordinatorListScopeMembershipsAction, Xm as coordinatorListScopesAction, sh as coordinatorRemoveDeviceAction, ih as coordinatorRenameDeviceAction, Km as coordinatorRenameGroupAction, dh as coordinatorReviewJoinRequestAction, ph as coordinatorRevokeBootstrapGrantAction, th as coordinatorRevokeScopeMembershipAction, Hl as coordinatorStatusSnapshot, Jm as coordinatorUnarchiveGroupAction, Qm as coordinatorUpdateScopeAction, br as createBetterSqliteCoordinatorApp, c as createCoordinatorApp, Bl as createCoordinatorReciprocalApproval, Qb as cursorAdvances, Kf as deactivateLowSignalMemories, Gf as deactivateLowSignalObservations, Tg as decideExtractionReplayTier, s as decodeInvitePayload, qf as dedupNearDuplicateMemories, Wo as dedupeOrderedIds, bh as deleteCoordinatorGroupPreference, dy as deleteProjectScopeSettingsMapping, __ as deriveRequest, xu as deriveTags, Gb as discoverPeersViaMdns, ts as embedTexts, t as encodeInvitePayload, dr as ensureDeviceIdentity, Zr as ensureMaintenanceJobsSchema, yn as ensureSchemaBootstrapped, Tv as ensureScopeBackfillScopes, Xl as ensureScopeMembershipCacheStateTable, Bs as estimateTokens, dg as evaluateSessionExtractionItems, Wg as eventToToolEvent, Ga as expandQuery, Jo as explain, e as explainScopeMembershipRevocation, Gh as exportMemories, Kg as extractAdapterEvent, je as extractApplyPatchPaths, y_ as extractAssistantMessages, b_ as extractAssistantUsage, r as extractInvitePayload, Jf as extractNarrativeFromBody, lp as extractOAuthAccess, fp as extractOAuthAccountId, pp as extractOAuthExpires, x_ as extractPrompts, up as extractProviderApiKey, Xu as extractReplicationOps, Gg as extractToolEvents, Xr as failMaintenanceJob, bb as fetchAllSnapshotPages, Rl as fetchCoordinatorStalePeers, bu as fileTags, jd as filterReplicationOpsForSync, Ad as filterReplicationOpsForSyncWithStatus, va as findByConcept, _a as findByFile, i as fingerprintPublicKey, g_ as firstSentence, rv as flushRawEvents, Un as fromJson, Wn as fromJsonStrict, sr as generateKeypair, _u as getCachedScopeAuthorization, Lt as getCodememConfigPath, Ht as getCodememEnvOverrides, _h as getCoordinatorGroupPreference, es as getEmbeddingClient, rg as getExtractionBenchmarkProfile, oi as getInjectionEvalScenarioByPrompt, ci as getInjectionEvalScenarioPack, li as getInjectionEvalScenarioPrompts, Q as getMaintenanceJob, kf as getMemoryRoleReport, Wt as getOpenCodeProviderConfig, sn as getProviderApiKey, an as getProviderBaseUrl, on as getProviderHeaders, rn as getProviderOptions, ri as getRawEventRelinkPlan, ni as getRawEventRelinkReport, jf as getRawEventStatus, Nf as getReliabilityMetrics, qu as getReplicationCursor, Rn as getSchemaVersion, Cs as getSemanticIndexDiagnostics, fg as getSessionExtractionEval, ug as getSessionExtractionEvalScenario, di as getSummaryMetadata, Cx as getSyncDaemonPhase, Ru as getSyncResetState, At as getWorkspaceCodememConfigPath, jt as getWorkspaceScopedCodememConfigPath, P_ as hasMeaningfulObservation, Sh as hasPendingDedupKeyBackfill, vy as hasPendingRefBackfill, kv as hasPendingScopeBackfill, Ny as hasPendingSessionContextBackfill, zy as hasPendingSummaryDedupBackfill, ad as hasUnsyncedSharedMemoryChanges, Yo as hashText, tg as importMemories, K_ as ingest, Y_ as ingestMain, ii as initDatabase, Bx as initTestSchema, Vx as insertTestSession, l as inviteLink, _x as isConnectivityError, Ln as isEmbeddingDisabled, Bg as isInternalMemoryTool, Hf as isLowSignalObservation, Qu as isNewerClock, Mg as isSensitiveFieldName, fi as isSummaryLikeMemory, h_ as isTrivialRequest, qa as kindBonus, gu as listCachedScopesForDevice, Jt as listConfiguredOpenCodeProviders, vh as listCoordinatorGroupPreferences, Ul as listCoordinatorJoinRequests, zl as listCoordinatorReciprocalApprovals, Gt as listCustomProviders, ig as listExtractionBenchmarkProfiles, Wd as listInboundScopeRejections, Kr as listMaintenanceJobs, Yt as listObserverProviderOptions, ly as listProjectScopeCandidates, ry as listProjectScopeSettingsMappings, ny as listSharingDomainSettingsScopes, id as loadMemorySnapshotPageForPeer, Vp as loadObserverConfig, Dt as loadOpenCodeConfig, op as loadOpenCodeOAuthCache, jb as loadPeerAddresses, rr as loadPrivateKey, er as loadPrivateKeyKeychain, nr as loadPublicKey, rd as loadReplicationOpsForPeer, nd as loadReplicationOpsSince, In as loadSqliteVec, Pl as lookupCoordinatorPeers, Ir as mapClaudeHookPayload, Kb as mdnsAddressesForPeer, Rb as mdnsEnabled, yl as mergeAddresses, Lh as mergeSummaryMetadata, jn as migrateLegacyDbPath, qd as migrateLegacyImportKeys, Xy as negotiateSyncCapability, C_ as normalizeAdapterEvents, _l as normalizeAddress, ma as normalizeConcept, S_ as normalizeEventsForSessionContext, Vf as normalizeObservation, Dr as normalizeProjectLabel, m_ as normalizeRequestText, Yy as normalizeSyncCapability, yu as normalizeTag, Vg as normalizeToolName, N_ as parseObserverResponse, Sa as parsePositiveMemoryId, xa as parseStrictInteger, Lx as parseSyncScopeRequest, yx as peerBackoffSeconds, Sd as peerCanSyncPrivateOpByPersonalScopeGrant, yd as personalScopeGrantStatusForPeer, ld as planReplicationOpsAgePrune, ga as populateMemoryRefs, dp as probeAvailableCredentials, qg as projectAdapterToolEvent, yi as projectBasename, xi as projectClause, bi as projectColumnClause, Si as projectMatchesFilter, od as pruneReplicationOps, sd as pruneReplicationOpsUntilCaughtUp, Pf as rawEventsGate, gp as readAuthFile, Rt as readCodememConfigFile, zt as readCodememConfigFileAtPath, Al as readCoordinatorSyncConfig, Kh as readImportPayload, Pt as readWorkspaceCodememConfigFile, Ka as recencyScore, vr as recordNonce, Pb as recordPeerSuccess, $u as recordReplicationOp, Nb as recordSyncAttempt, rp as redactText, hu as refreshConfiguredScopeMembershipCache, mu as refreshScopeMembershipCache, Ll as refreshStoredCoordinatorPeerAddresses, Nl as registerCoordinatorPresence, Hd as rejectInboundScopeFailures, Cp as renderObserverHeaders, _v as replayBatchExtraction, vv as replayBatchExtractionWithTierRouting, xd as replicationOpRequiresPersonalScopeAuthorization, xl as requestJson, Lo as rerankResults, Zt as resolveBuiltInProviderDefaultModel, Xt as resolveBuiltInProviderFromModel, Qt as resolveBuiltInProviderModel, It as resolveCodememConfigPath, cn as resolveCustomProviderDefaultModel, $t as resolveCustomProviderFromModel, ln as resolveCustomProviderModel, Dn as resolveDbPath, Ar as resolveHookProject, tr as resolveKeyPaths, sp as resolveOAuthProvider, en as resolvePlaceholder, wi as resolveProject, Bi as resolveProjectScope, Mf as retryRawEventFailures, hp as runAuthCommand, wh as runDedupKeyBackfillPass, xy as runRefBackfillPass, Fv as runScopeBackfillPass, Py as runSessionContextBackfillPass, Uy as runSummaryDedupBackfillPass, Dx as runSyncDaemon, px as runSyncPass, vb as runVectorMigrationPass, Fg as sanitizePayload, Rg as sanitizeToolOutput, Im as scanSecretsRetroactive, H as schema, a as scopeMembershipEpochStatus, Ro as search, Hx as seedMixedScopeFixture, Ab as selectDialAddresses, As as semanticSearch, rs as serializeFloat32, Ib as setPeerLocalActorClaim, Fb as setPeerProjectFilter, Ju as setReplicationCursor, Sx as setSyncDaemonError, xx as setSyncDaemonOk, wx as setSyncDaemonPhase, zu as setSyncResetState, bx as shouldSkipOfflinePeer, mr as signRequest, qr as startMaintenanceJob, $n as storePrivateKeyKeychain, Os as storeVectors, Tt as stripJsonComments, kg as stripPrivate, Ng as stripPrivateObj, Et as stripTrailingCommas, Ud as summarizeInboundScopeRejections, Ex as syncDaemonTick, fx as syncOnce, dx as syncPassPreflight, _d as syncProjectAllowedByFilters, zx as syncScopeResetRequiredPayload, vd as syncVisibilityAllowed, X as tableExists, Ho as timeline, Z as toJson, Gn as toJsonNullable, Jr as updateMaintenanceJob, Mb as updatePeerAddresses, iu as upsertCachedScopeMemberships, yh as upsertCoordinatorGroupPreference, uy as upsertProjectScopeSettingsMapping, ai as vacuumDatabase, ur as validateExistingKeypair, hr as verifySignature, Bt as writeCodememConfigFile, Vt as writeWorkspaceCodememConfigFile };
17449
+ export { ke as Api, V as BetterSqliteCoordinatorStore, Ft as CODEMEM_CONFIG_ENV_OVERRIDES, xh as DEDUP_KEY_BACKFILL_JOB, R as DEFAULT_COORDINATOR_DB_PATH, En as DEFAULT_DB_PATH, Wl as DEFAULT_SCOPE_MEMBERSHIP_CACHE_MAX_AGE_MS, Ab as DEFAULT_SERVICE_TYPE, Su as DEFAULT_SYNC_SCOPE_ID, o as DEFAULT_TIME_WINDOW_S, Th as DedupKeyBackfillRunner, si as INJECTION_EVAL_SCENARIO_PACKS, yv as LEGACY_SHARED_REVIEW_SCOPE_ID, Ti as LOCAL_DEFAULT_SCOPE_ID, Jy as LOCAL_SYNC_CAPABILITY, zg as LOW_SIGNAL_TOOLS, Sr as MAPPABLE_CLAUDE_HOOK_EVENTS, Cn as MIN_COMPATIBLE_SCHEMA, Ae as MUTATING_TOOL_NAMES, bf as MemoryStore, yp as ObserverAuthAdapter, Hp as ObserverAuthError, pm as ObserverClient, _y as REF_BACKFILL_JOB, mg as RICH_TIER_DEFAULTS, gy as RawEventSweeper, Cy as RefBackfillRunner, Sn as SCHEMA_VERSION, bv as SCOPE_BACKFILL_JOB, n as SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, wy as SESSION_CONTEXT_BACKFILL_JOB, fr as SIGNATURE_VERSION, pg as SIMPLE_TIER_DEFAULTS, Ry as SUMMARY_DEDUP_BACKFILL_JOB, Ky as SYNC_CAPABILITIES, qy as SYNC_CAPABILITY_HEADER, Lx as SYNC_SCOPE_QUERY_PARAM, Iv as ScopeBackfillRunner, Ly as SessionContextBackfillRunner, Gy as SummaryDedupBackfillRunner, Ix as SyncRetentionRunner, p_ as TRIVIAL_REQUESTS, Qy as VECTOR_MODEL_MIGRATION_JOB, Wx as VERSION, bb as VectorModelMigrationRunner, Qo as _resetEmbeddingClient, zx as addSyncScopeToBoundary, vl as addressDedupeKey, Gb as advertiseMdns, Om as aiBackfillStructuredContent, ly as analyzeProjectScopeMappingChangeGuardrails, Ob as applyBootstrapSnapshot, Zd as applyReplicationOps, zn as assertSchemaReady, ep as backfillMemoryDedupKeys, Yf as backfillNarrativeFromBody, Jd as backfillReplicationOps, Mv as backfillScopeIds, zf as backfillTagsText, ks as backfillVectors, hn as bootstrapSchema, Zg as budgetToolEvents, _r as buildAuthHeaders, bl as buildBaseUrl, pr as buildCanonicalRequest, mp as buildCodexHeaders, Ji as buildFilterClauses, Yi as buildFilterClausesWithContext, Ih as buildImportKey, zr as buildIngestPayloadFromHook, qc as buildMemoryPack, Yc as buildMemoryPackAsync, Jc as buildMemoryPackTrace, Xc as buildMemoryPackTraceAsync, d_ as buildObserverPrompt, Rr as buildRawEventEnvelopeFromHook, tv as buildSessionContext, v_ as buildTranscript, cd as bulkPruneReplicationOpsByAgeCutoff, mi as canonicalMemoryKind, ji as canonicalWorkspaceIdentity, Uu as chunkOpsBySize, Xo as chunkText, Cv as classifyLegacyMemoryScope, J_ as cleanOrphanSessions, yr as cleanupNonces, ha as clearMemoryRefs, Zu as clockTuple, Af as compareMemoryRoleReports, Yr as completeMaintenanceJob, Mn as connect, Xe as connectCoordinator, yx as consecutiveConnectivityFailures, qm as coordinatorArchiveGroupAction, Gm as coordinatorCreateGroupAction, ch as coordinatorCreateInviteAction, Zm as coordinatorCreateScopeAction, ah as coordinatorDisableDeviceAction, oh as coordinatorEnableDeviceAction, jl as coordinatorEnabled, nh as coordinatorEnrollDeviceAction, eh as coordinatorGrantScopeMembershipAction, lh as coordinatorImportInviteAction, fh as coordinatorListBootstrapGrantsAction, rh as coordinatorListDevicesAction, Ym as coordinatorListGroupsAction, uh as coordinatorListJoinRequestsAction, $m as coordinatorListScopeMembershipsAction, Xm as coordinatorListScopesAction, sh as coordinatorRemoveDeviceAction, ih as coordinatorRenameDeviceAction, Km as coordinatorRenameGroupAction, dh as coordinatorReviewJoinRequestAction, ph as coordinatorRevokeBootstrapGrantAction, th as coordinatorRevokeScopeMembershipAction, Hl as coordinatorStatusSnapshot, Jm as coordinatorUnarchiveGroupAction, Qm as coordinatorUpdateScopeAction, br as createBetterSqliteCoordinatorApp, c as createCoordinatorApp, Bl as createCoordinatorReciprocalApproval, $b as cursorAdvances, Kf as deactivateLowSignalMemories, Gf as deactivateLowSignalObservations, Tg as decideExtractionReplayTier, s as decodeInvitePayload, qf as dedupNearDuplicateMemories, Wo as dedupeOrderedIds, bh as deleteCoordinatorGroupPreference, fy as deleteProjectScopeSettingsMapping, __ as deriveRequest, xu as deriveTags, Kb as discoverPeersViaMdns, ts as embedTexts, t as encodeInvitePayload, dr as ensureDeviceIdentity, Zr as ensureMaintenanceJobsSchema, yn as ensureSchemaBootstrapped, Tv as ensureScopeBackfillScopes, Xl as ensureScopeMembershipCacheStateTable, Bs as estimateTokens, dg as evaluateSessionExtractionItems, Wg as eventToToolEvent, Ga as expandQuery, Jo as explain, e as explainScopeMembershipRevocation, Gh as exportMemories, Kg as extractAdapterEvent, je as extractApplyPatchPaths, y_ as extractAssistantMessages, b_ as extractAssistantUsage, r as extractInvitePayload, Jf as extractNarrativeFromBody, lp as extractOAuthAccess, fp as extractOAuthAccountId, pp as extractOAuthExpires, x_ as extractPrompts, up as extractProviderApiKey, Xu as extractReplicationOps, Gg as extractToolEvents, Xr as failMaintenanceJob, xb as fetchAllSnapshotPages, Rl as fetchCoordinatorStalePeers, bu as fileTags, jd as filterReplicationOpsForSync, Ad as filterReplicationOpsForSyncWithStatus, va as findByConcept, _a as findByFile, i as fingerprintPublicKey, g_ as firstSentence, rv as flushRawEvents, Un as fromJson, Wn as fromJsonStrict, sr as generateKeypair, _u as getCachedScopeAuthorization, Lt as getCodememConfigPath, Ht as getCodememEnvOverrides, _h as getCoordinatorGroupPreference, es as getEmbeddingClient, rg as getExtractionBenchmarkProfile, oi as getInjectionEvalScenarioByPrompt, ci as getInjectionEvalScenarioPack, li as getInjectionEvalScenarioPrompts, Q as getMaintenanceJob, kf as getMemoryRoleReport, Wt as getOpenCodeProviderConfig, sn as getProviderApiKey, an as getProviderBaseUrl, on as getProviderHeaders, rn as getProviderOptions, ri as getRawEventRelinkPlan, ni as getRawEventRelinkReport, jf as getRawEventStatus, Nf as getReliabilityMetrics, qu as getReplicationCursor, Rn as getSchemaVersion, Cs as getSemanticIndexDiagnostics, fg as getSessionExtractionEval, ug as getSessionExtractionEvalScenario, di as getSummaryMetadata, wx as getSyncDaemonPhase, Ru as getSyncResetState, At as getWorkspaceCodememConfigPath, jt as getWorkspaceScopedCodememConfigPath, P_ as hasMeaningfulObservation, Sh as hasPendingDedupKeyBackfill, yy as hasPendingRefBackfill, kv as hasPendingScopeBackfill, Py as hasPendingSessionContextBackfill, By as hasPendingSummaryDedupBackfill, ad as hasUnsyncedSharedMemoryChanges, Yo as hashText, tg as importMemories, K_ as ingest, Y_ as ingestMain, ii as initDatabase, Vx as initTestSchema, Hx as insertTestSession, l as inviteLink, vx as isConnectivityError, Ln as isEmbeddingDisabled, Bg as isInternalMemoryTool, Hf as isLowSignalObservation, Qu as isNewerClock, Mg as isSensitiveFieldName, fi as isSummaryLikeMemory, h_ as isTrivialRequest, qa as kindBonus, gu as listCachedScopesForDevice, Jt as listConfiguredOpenCodeProviders, vh as listCoordinatorGroupPreferences, Ul as listCoordinatorJoinRequests, zl as listCoordinatorReciprocalApprovals, Gt as listCustomProviders, ig as listExtractionBenchmarkProfiles, Wd as listInboundScopeRejections, Kr as listMaintenanceJobs, Yt as listObserverProviderOptions, uy as listProjectScopeCandidates, iy as listProjectScopeSettingsMappings, ry as listSharingDomainSettingsScopes, id as loadMemorySnapshotPageForPeer, Vp as loadObserverConfig, Dt as loadOpenCodeConfig, op as loadOpenCodeOAuthCache, Mb as loadPeerAddresses, rr as loadPrivateKey, er as loadPrivateKeyKeychain, nr as loadPublicKey, rd as loadReplicationOpsForPeer, nd as loadReplicationOpsSince, In as loadSqliteVec, Pl as lookupCoordinatorPeers, Ir as mapClaudeHookPayload, qb as mdnsAddressesForPeer, zb as mdnsEnabled, yl as mergeAddresses, Lh as mergeSummaryMetadata, jn as migrateLegacyDbPath, qd as migrateLegacyImportKeys, Zy as negotiateSyncCapability, C_ as normalizeAdapterEvents, _l as normalizeAddress, ma as normalizeConcept, S_ as normalizeEventsForSessionContext, Vf as normalizeObservation, Dr as normalizeProjectLabel, m_ as normalizeRequestText, Xy as normalizeSyncCapability, yu as normalizeTag, Vg as normalizeToolName, N_ as parseObserverResponse, Sa as parsePositiveMemoryId, xa as parseStrictInteger, Rx as parseSyncScopeRequest, bx as peerBackoffSeconds, Sd as peerCanSyncPrivateOpByPersonalScopeGrant, yd as personalScopeGrantStatusForPeer, ld as planReplicationOpsAgePrune, ga as populateMemoryRefs, dp as probeAvailableCredentials, qg as projectAdapterToolEvent, yi as projectBasename, xi as projectClause, bi as projectColumnClause, Si as projectMatchesFilter, od as pruneReplicationOps, sd as pruneReplicationOpsUntilCaughtUp, Pf as rawEventsGate, gp as readAuthFile, Rt as readCodememConfigFile, zt as readCodememConfigFileAtPath, Al as readCoordinatorSyncConfig, Kh as readImportPayload, Pt as readWorkspaceCodememConfigFile, Ka as recencyScore, vr as recordNonce, Fb as recordPeerSuccess, $u as recordReplicationOp, Pb as recordSyncAttempt, rp as redactText, hu as refreshConfiguredScopeMembershipCache, mu as refreshScopeMembershipCache, Ll as refreshStoredCoordinatorPeerAddresses, Nl as registerCoordinatorPresence, Hd as rejectInboundScopeFailures, Cp as renderObserverHeaders, _v as replayBatchExtraction, vv as replayBatchExtractionWithTierRouting, xd as replicationOpRequiresPersonalScopeAuthorization, xl as requestJson, Lo as rerankResults, Zt as resolveBuiltInProviderDefaultModel, Xt as resolveBuiltInProviderFromModel, Qt as resolveBuiltInProviderModel, It as resolveCodememConfigPath, cn as resolveCustomProviderDefaultModel, $t as resolveCustomProviderFromModel, ln as resolveCustomProviderModel, Dn as resolveDbPath, Ar as resolveHookProject, tr as resolveKeyPaths, sp as resolveOAuthProvider, en as resolvePlaceholder, wi as resolveProject, Bi as resolveProjectScope, Mf as retryRawEventFailures, hp as runAuthCommand, wh as runDedupKeyBackfillPass, Sy as runRefBackfillPass, Fv as runScopeBackfillPass, Fy as runSessionContextBackfillPass, Wy as runSummaryDedupBackfillPass, Ox as runSyncDaemon, mx as runSyncPass, yb as runVectorMigrationPass, Fg as sanitizePayload, Rg as sanitizeToolOutput, Im as scanSecretsRetroactive, H as schema, a as scopeMembershipEpochStatus, Ro as search, Ux as seedMixedScopeFixture, jb as selectDialAddresses, As as semanticSearch, rs as serializeFloat32, Lb as setPeerLocalActorClaim, Ib as setPeerProjectFilter, Ju as setReplicationCursor, Cx as setSyncDaemonError, Sx as setSyncDaemonOk, Tx as setSyncDaemonPhase, zu as setSyncResetState, xx as shouldSkipOfflinePeer, mr as signRequest, qr as startMaintenanceJob, $n as storePrivateKeyKeychain, Os as storeVectors, Tt as stripJsonComments, kg as stripPrivate, Ng as stripPrivateObj, Et as stripTrailingCommas, Ud as summarizeInboundScopeRejections, Dx as syncDaemonTick, px as syncOnce, fx as syncPassPreflight, _d as syncProjectAllowedByFilters, Bx as syncScopeResetRequiredPayload, vd as syncVisibilityAllowed, X as tableExists, Ho as timeline, Z as toJson, Gn as toJsonNullable, Jr as updateMaintenanceJob, Nb as updatePeerAddresses, iu as upsertCachedScopeMemberships, yh as upsertCoordinatorGroupPreference, dy as upsertProjectScopeSettingsMapping, ai as vacuumDatabase, ur as validateExistingKeypair, hr as verifySignature, Bt as writeCodememConfigFile, Vt as writeWorkspaceCodememConfigFile };
17431
17450
 
17432
17451
  //# sourceMappingURL=index.js.map