Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(desktop): optimize task search and SkillHub database access (#3950)

DavidShenXD859deed9ffbd
diff --git a/apps/desktop/drizzle/0102_optimal_ender_wiggin.sql b/apps/desktop/drizzle/0102_optimal_ender_wiggin.sql
new file mode 100644
index 0000000000..e0ac49d1ec
--- /dev/null
+++ b/apps/desktop/drizzle/0102_optimal_ender_wiggin.sql
@@ -0,0 +1 @@
+SELECT 1;
diff --git a/apps/desktop/drizzle/meta/0102_snapshot.json b/apps/desktop/drizzle/meta/0102_snapshot.json
new file mode 100644
index 0000000000..763c68807e
--- /dev/null
+++ b/apps/desktop/drizzle/meta/0102_snapshot.json
@@ -0,0 +1,4583 @@
+{
+ "id": "714b31a1-4bc0-4b96-9bf8-e2a2b923347d",
+ "prevId": "d8264c64-5ca7-459d-adc9-487a37db11d4",
+ "version": "6",
+ "dialect": "sqlite",
+ "tables": {
+ "account_usage_snapshots": {
+ "name": "account_usage_snapshots",
+ "columns": {
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agent_input_queue_snapshots": {
+ "name": "agent_input_queue_snapshots",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_input_queue_snapshots_session_id_sessions_id_fk": {
+ "name": "agent_input_queue_snapshots_session_id_sessions_id_fk",
+ "tableFrom": "agent_input_queue_snapshots",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_mcp_servers": {
+ "name": "custom_mcp_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "transport": {
+ "name": "transport",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_mcp_servers_sort_order": {
+ "name": "idx_custom_mcp_servers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "custom_providers": {
+ "name": "custom_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sort_order": {
+ "name": "sort_order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_custom_providers_sort_order": {
+ "name": "idx_custom_providers_sort_order",
+ "columns": [
+ "sort_order"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_model_usage": {
+ "name": "daily_model_usage",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_read_tokens": {
+ "name": "cache_read_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cache_create_tokens": {
+ "name": "cache_create_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_model_usage_day_agent_kind_model_cost_currency_pk": {
+ "columns": [
+ "day",
+ "agent_kind",
+ "model",
+ "cost_currency"
+ ],
+ "name": "daily_model_usage_day_agent_kind_model_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "daily_spend": {
+ "name": "daily_spend",
+ "columns": {
+ "day": {
+ "name": "day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'USD'"
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "daily_spend_day_cost_currency_pk": {
+ "columns": [
+ "day",
+ "cost_currency"
+ ],
+ "name": "daily_spend_day_cost_currency_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "device_link_ownership": {
+ "name": "device_link_ownership",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_pid": {
+ "name": "owner_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_label": {
+ "name": "owner_label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_jobs": {
+ "name": "embedding_jobs",
+ "columns": {
+ "rowid": {
+ "name": "rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scheduled_at": {
+ "name": "scheduled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "locked_at": {
+ "name": "locked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_embedding_jobs_natural": {
+ "name": "uniq_embedding_jobs_natural",
+ "columns": [
+ "source",
+ "source_id",
+ "chunk_index",
+ "model_id"
+ ],
+ "isUnique": true
+ },
+ "idx_embedding_jobs_status_scheduled": {
+ "name": "idx_embedding_jobs_status_scheduled",
+ "columns": [
+ "status",
+ "scheduled_at"
+ ],
+ "isUnique": false
+ },
+ "idx_embedding_jobs_source_id": {
+ "name": "idx_embedding_jobs_source_id",
+ "columns": [
+ "source",
+ "source_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "embedding_meta": {
+ "name": "embedding_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "ghost_cards": {
+ "name": "ghost_cards",
+ "columns": {
+ "call_id": {
+ "name": "call_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ghost_id": {
+ "name": "ghost_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "html": {
+ "name": "html",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "v": {
+ "name": "v",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "ghost_cards_updated_at_idx": {
+ "name": "ghost_cards_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_context_cursors": {
+ "name": "hook_group_context_cursors",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_key": {
+ "name": "cursor_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cursor_id": {
+ "name": "cursor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_context_cursors_updated_at_idx": {
+ "name": "hook_group_context_cursors_updated_at_idx",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "hook_group_context_cursors_provider_cursor_key_pk": {
+ "columns": [
+ "provider",
+ "cursor_key"
+ ],
+ "name": "hook_group_context_cursors_provider_cursor_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_message_stats": {
+ "name": "hook_group_message_stats",
+ "columns": {
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "row_count": {
+ "name": "row_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text_bytes": {
+ "name": "text_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "hook_group_messages": {
+ "name": "hook_group_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chat_name": {
+ "name": "chat_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author": {
+ "name": "author",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_bot": {
+ "name": "is_bot",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_names": {
+ "name": "file_names",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "hook_group_messages_msg_idx": {
+ "name": "hook_group_messages_msg_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "message_id"
+ ],
+ "isUnique": true
+ },
+ "hook_group_messages_window_idx": {
+ "name": "hook_group_messages_window_idx",
+ "columns": [
+ "provider",
+ "chat_id",
+ "thread_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "im_bindings": {
+ "name": "im_bindings",
+ "columns": {
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bot_context_id": {
+ "name": "bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope_key": {
+ "name": "scope_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_at": {
+ "name": "attached_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attached_via_card_message_id": {
+ "name": "attached_via_card_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_im_bindings_target": {
+ "name": "idx_im_bindings_target",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "im_bindings_target_session_id_sessions_id_fk": {
+ "name": "im_bindings_target_session_id_sessions_id_fk",
+ "tableFrom": "im_bindings",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "im_bindings_channel_bot_context_id_user_id_scope_key_pk": {
+ "columns": [
+ "channel",
+ "bot_context_id",
+ "user_id",
+ "scope_key"
+ ],
+ "name": "im_bindings_channel_bot_context_id_user_id_scope_key_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_blobs": {
+ "name": "media_blobs",
+ "columns": {
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ext": {
+ "name": "ext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_cache": {
+ "name": "is_cache",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_access_at": {
+ "name": "last_access_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_invocations": {
+ "name": "media_invocations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "capability": {
+ "name": "capability",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_revision": {
+ "name": "guide_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "guide_json": {
+ "name": "guide_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response_json": {
+ "name": "response_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_invocations_owner_created_at_idx": {
+ "name": "media_invocations_owner_created_at_idx",
+ "columns": [
+ "owner",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "media_invocations_owner_state_idx": {
+ "name": "media_invocations_owner_state_idx",
+ "columns": [
+ "owner",
+ "state"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "media_refs": {
+ "name": "media_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_kind": {
+ "name": "ref_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ref_id": {
+ "name": "ref_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "origin_session_id": {
+ "name": "origin_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_kind": {
+ "name": "origin_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin_id": {
+ "name": "origin_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_refs_hash_idx": {
+ "name": "media_refs_hash_idx",
+ "columns": [
+ "hash"
+ ],
+ "isUnique": false
+ },
+ "media_refs_ref_idx": {
+ "name": "media_refs_ref_idx",
+ "columns": [
+ "ref_kind",
+ "ref_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "media_refs_hash_media_blobs_hash_fk": {
+ "name": "media_refs_hash_media_blobs_hash_fk",
+ "tableFrom": "media_refs",
+ "columnsFrom": [
+ "hash"
+ ],
+ "tableTo": "media_blobs",
+ "columnsTo": [
+ "hash"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_meta": {
+ "name": "agent_meta",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_messages_session_client": {
+ "name": "uniq_messages_session_client",
+ "columns": [
+ "session_id",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_messages_session_created": {
+ "name": "idx_messages_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_created_at": {
+ "name": "idx_messages_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_rewind_at": {
+ "name": "idx_messages_rewind_at",
+ "columns": [
+ "rewind_at"
+ ],
+ "isUnique": false
+ },
+ "idx_messages_active_error_tail": {
+ "name": "idx_messages_active_error_tail",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "where": "\"messages\".\"role\" = 'error' AND \"messages\".\"rewind_at\" IS NULL",
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages_fts_rows": {
+ "name": "messages_fts_rows",
+ "columns": {
+ "fts_rowid": {
+ "name": "fts_rowid",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "messages_fts_rows_message_id_idx": {
+ "name": "messages_fts_rows_message_id_idx",
+ "columns": [
+ "message_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_history": {
+ "name": "migration_history",
+ "columns": {
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_name": {
+ "name": "file_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "applied_at": {
+ "name": "applied_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "migration_meta": {
+ "name": "migration_meta",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_teams": {
+ "name": "orca_teams",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lead_session_id": {
+ "name": "lead_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_active_team_per_lead": {
+ "name": "uniq_active_team_per_lead",
+ "columns": [
+ "lead_session_id"
+ ],
+ "where": "\"orca_teams\".\"status\" = 'active'",
+ "isUnique": true
+ },
+ "idx_orca_teams_status": {
+ "name": "idx_orca_teams_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_teams_lead_session_id_sessions_id_fk": {
+ "name": "orca_teams_lead_session_id_sessions_id_fk",
+ "tableFrom": "orca_teams",
+ "columnsFrom": [
+ "lead_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_worker_creation_reservations": {
+ "name": "orca_worker_creation_reservations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "name": "uniq_orca_worker_creation_reservations_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "idx_orca_worker_creation_reservations_expires_at": {
+ "name": "idx_orca_worker_creation_reservations_expires_at",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_worker_creation_reservations_team_id_orca_teams_id_fk": {
+ "name": "orca_worker_creation_reservations_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_worker_creation_reservations",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "tableTo": "orca_teams",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "orca_workers": {
+ "name": "orca_workers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'idle'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_branch": {
+ "name": "worktree_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'developer'"
+ },
+ "focused": {
+ "name": "focused",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "idle_since": {
+ "name": "idle_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_orca_workers_session_id": {
+ "name": "uniq_orca_workers_session_id",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_team_label": {
+ "name": "uniq_orca_workers_team_label",
+ "columns": [
+ "team_id",
+ "lower(\"label\")"
+ ],
+ "isUnique": true
+ },
+ "uniq_orca_workers_focused_per_team": {
+ "name": "uniq_orca_workers_focused_per_team",
+ "columns": [
+ "team_id"
+ ],
+ "where": "\"orca_workers\".\"focused\" = true",
+ "isUnique": true
+ },
+ "idx_orca_workers_team_id": {
+ "name": "idx_orca_workers_team_id",
+ "columns": [
+ "team_id"
+ ],
+ "isUnique": false
+ },
+ "idx_orca_workers_status": {
+ "name": "idx_orca_workers_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "orca_workers_team_id_orca_teams_id_fk": {
+ "name": "orca_workers_team_id_orca_teams_id_fk",
+ "tableFrom": "orca_workers",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "tableTo": "orca_teams",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "orca_workers_session_id_sessions_id_fk": {
+ "name": "orca_workers_session_id_sessions_id_fk",
+ "tableFrom": "orca_workers",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_aliases": {
+ "name": "project_aliases",
+ "columns": {
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_project_aliases_updated_at": {
+ "name": "idx_project_aliases_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_automation_consents": {
+ "name": "project_automation_consents",
+ "columns": {
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consented_at": {
+ "name": "consented_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config_hash": {
+ "name": "config_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "recent_workdirs": {
+ "name": "recent_workdirs",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_recent_workdirs_last_used_at": {
+ "name": "idx_recent_workdirs_last_used_at",
+ "columns": [
+ "last_used_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "right_sidebar_tabs": {
+ "name": "right_sidebar_tabs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "right_sidebar_tabs_session_idx": {
+ "name": "right_sidebar_tabs_session_idx",
+ "columns": [
+ "session_id",
+ "position"
+ ],
+ "isUnique": false
+ },
+ "right_sidebar_tabs_subagents_singleton_idx": {
+ "name": "right_sidebar_tabs_subagents_singleton_idx",
+ "columns": [
+ "session_id"
+ ],
+ "where": "\"right_sidebar_tabs\".\"kind\" = 'subagents'",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "right_sidebar_tabs_session_id_sessions_id_fk": {
+ "name": "right_sidebar_tabs_session_id_sessions_id_fk",
+ "tableFrom": "right_sidebar_tabs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_runs": {
+ "name": "schedule_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "error_msg": {
+ "name": "error_msg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_usd": {
+ "name": "estimated_value_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_amount": {
+ "name": "cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "estimated_value_amount": {
+ "name": "estimated_value_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "cost_currency": {
+ "name": "cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_is_approximate": {
+ "name": "cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cost_attribution": {
+ "name": "cost_attribution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'legacy'"
+ },
+ "result_text": {
+ "name": "result_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_result": {
+ "name": "pre_run_hook_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_runs_schedule": {
+ "name": "idx_schedule_runs_schedule",
+ "columns": [
+ "schedule_id",
+ "fired_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_schedule": {
+ "name": "idx_schedule_runs_running_schedule",
+ "columns": [
+ "schedule_id"
+ ],
+ "where": "\"schedule_runs\".\"status\" = 'running'",
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_heartbeat": {
+ "name": "idx_schedule_runs_running_heartbeat",
+ "columns": [
+ "heartbeat_at"
+ ],
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NOT NULL",
+ "isUnique": false
+ },
+ "idx_schedule_runs_running_legacy": {
+ "name": "idx_schedule_runs_running_legacy",
+ "columns": [
+ "fired_at"
+ ],
+ "where": "\"schedule_runs\".\"status\" = 'running' AND \"schedule_runs\".\"heartbeat_at\" IS NULL",
+ "isUnique": false
+ },
+ "idx_schedule_runs_unread_terminal": {
+ "name": "idx_schedule_runs_unread_terminal",
+ "columns": [
+ "schedule_id",
+ "status",
+ "fired_at"
+ ],
+ "where": "\"schedule_runs\".\"read_at\" IS NULL AND \"schedule_runs\".\"status\" IN ('success', 'failed', 'aborted', 'interrupted')",
+ "isUnique": false
+ },
+ "idx_schedule_runs_session_latest": {
+ "name": "idx_schedule_runs_session_latest",
+ "columns": [
+ "session_id",
+ "fired_at",
+ "id"
+ ],
+ "where": "\"schedule_runs\".\"session_id\" IS NOT NULL",
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedule_runs_schedule_id_schedules_id_fk": {
+ "name": "schedule_runs_schedule_id_schedules_id_fk",
+ "tableFrom": "schedule_runs",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "tableTo": "schedules",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "schedule_runs_session_id_sessions_id_fk": {
+ "name": "schedule_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_runs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedule_session_latest_runs": {
+ "name": "schedule_session_latest_runs",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fired_at": {
+ "name": "fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedule_session_latest_runs_run": {
+ "name": "idx_schedule_session_latest_runs_run",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "schedule_session_latest_runs_session_id_sessions_id_fk": {
+ "name": "schedule_session_latest_runs_session_id_sessions_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "schedule_session_latest_runs_run_id_schedule_runs_id_fk": {
+ "name": "schedule_session_latest_runs_run_id_schedule_runs_id_fk",
+ "tableFrom": "schedule_session_latest_runs",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "schedule_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "schedules": {
+ "name": "schedules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'prompt'"
+ },
+ "job_config": {
+ "name": "job_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "execution_mode": {
+ "name": "execution_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "script_config": {
+ "name": "script_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'user'"
+ },
+ "project_config_id": {
+ "name": "project_config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "legacy_session_fallback": {
+ "name": "legacy_session_fallback",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cron'"
+ },
+ "cron_expr": {
+ "name": "cron_expr",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recurring": {
+ "name": "recurring",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "manual": {
+ "name": "manual",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "interval_ms": {
+ "name": "interval_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "use_worktree": {
+ "name": "use_worktree",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "target_session_id": {
+ "name": "target_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "persistent_session": {
+ "name": "persistent_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "silent_when_idle": {
+ "name": "silent_when_idle",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "pre_run_hook_command": {
+ "name": "pre_run_hook_command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pre_run_hook_timeout_ms": {
+ "name": "pre_run_hook_timeout_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skip_log_session_id": {
+ "name": "skip_log_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "notify_desktop": {
+ "name": "notify_desktop",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "notify_feishu": {
+ "name": "notify_feishu",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "notify_wecom_group": {
+ "name": "notify_wecom_group",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_fired_at": {
+ "name": "last_fired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_finished_at": {
+ "name": "last_finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_fire_at": {
+ "name": "next_fire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expire_at": {
+ "name": "expire_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_schedules_active_next": {
+ "name": "idx_schedules_active_next",
+ "columns": [
+ "status",
+ "next_fire_at"
+ ],
+ "isUnique": false
+ },
+ "idx_schedules_target_session": {
+ "name": "idx_schedules_target_session",
+ "columns": [
+ "target_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "schedules_target_session_id_sessions_id_fk": {
+ "name": "schedules_target_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "columnsFrom": [
+ "target_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ },
+ "schedules_skip_log_session_id_sessions_id_fk": {
+ "name": "schedules_skip_log_session_id_sessions_id_fk",
+ "tableFrom": "schedules",
+ "columnsFrom": [
+ "skip_log_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_goals": {
+ "name": "session_goals",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objective": {
+ "name": "objective",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "budget_tokens": {
+ "name": "budget_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_turns": {
+ "name": "max_turns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "no_progress_limit": {
+ "name": "no_progress_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "turns_used": {
+ "name": "turns_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tokens_used": {
+ "name": "tokens_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "no_progress_streak": {
+ "name": "no_progress_streak",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "usage_reset_at": {
+ "name": "usage_reset_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reason": {
+ "name": "last_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_session_goals_status": {
+ "name": "idx_session_goals_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_goals_session_id_sessions_id_fk": {
+ "name": "session_goals_session_id_sessions_id_fk",
+ "tableFrom": "session_goals",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_pr_refs": {
+ "name": "session_pr_refs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner": {
+ "name": "owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo": {
+ "name": "repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_session_pr_refs": {
+ "name": "uniq_session_pr_refs",
+ "columns": [
+ "session_id",
+ "owner",
+ "repo",
+ "pr_number"
+ ],
+ "isUnique": true
+ },
+ "idx_session_pr_refs_session_last_seen": {
+ "name": "idx_session_pr_refs_session_last_seen",
+ "columns": [
+ "session_id",
+ "last_seen_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "session_pr_refs_session_id_sessions_id_fk": {
+ "name": "session_pr_refs_session_id_sessions_id_fk",
+ "tableFrom": "session_pr_refs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'New Maker'"
+ },
+ "working_dir": {
+ "name": "working_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_kind": {
+ "name": "workspace_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'project'"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude-sonnet-4-6'"
+ },
+ "effort": {
+ "name": "effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'high'"
+ },
+ "permission_mode": {
+ "name": "permission_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ask'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_token_usage": {
+ "name": "total_token_usage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_usd": {
+ "name": "total_cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_amount": {
+ "name": "total_cost_amount",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_cost_currency": {
+ "name": "total_cost_currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_cost_is_approximate": {
+ "name": "total_cost_is_approximate",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "context_tokens": {
+ "name": "context_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "context_window": {
+ "name": "context_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "fast_mode": {
+ "name": "fast_mode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "plan_mode_enabled": {
+ "name": "plan_mode_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "cleared_at": {
+ "name": "cleared_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_send_at": {
+ "name": "user_send_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cc'"
+ },
+ "orca_role": {
+ "name": "orca_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "parent_session_id": {
+ "name": "parent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "forked_at_message_id": {
+ "name": "forked_at_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "worktree_path": {
+ "name": "worktree_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'desktop'"
+ },
+ "feishu_open_id": {
+ "name": "feishu_open_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "feishu_bot_app_id": {
+ "name": "feishu_bot_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_bot_context_id": {
+ "name": "im_bot_context_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "im_user_id": {
+ "name": "im_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "used_project_context": {
+ "name": "used_project_context",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "codex_history_has_product_prompt": {
+ "name": "codex_history_has_product_prompt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "codex_plan_json": {
+ "name": "codex_plan_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "extra_dirs": {
+ "name": "extra_dirs",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "remote_host_id": {
+ "name": "remote_host_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_started_at": {
+ "name": "active_turn_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_turn_pid": {
+ "name": "active_turn_pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_turn_ended_at": {
+ "name": "last_turn_ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview": {
+ "name": "list_preview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_preview_role": {
+ "name": "list_preview_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "list_message_count": {
+ "name": "list_message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_sessions_updated_at": {
+ "name": "idx_sessions_updated_at",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_user_send_at": {
+ "name": "idx_sessions_user_send_at",
+ "columns": [
+ "user_send_at"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_sdk_session_id": {
+ "name": "idx_sessions_sdk_session_id",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workdir_created": {
+ "name": "idx_sessions_workdir_created",
+ "columns": [
+ "working_dir",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_created_at": {
+ "name": "idx_sessions_created_at",
+ "columns": [
+ "created_at",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_workspace_kind": {
+ "name": "idx_sessions_workspace_kind",
+ "columns": [
+ "workspace_kind"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_parent_session_id": {
+ "name": "idx_sessions_parent_session_id",
+ "columns": [
+ "parent_session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_orca_role": {
+ "name": "idx_sessions_orca_role",
+ "columns": [
+ "orca_role"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_worktree_path": {
+ "name": "idx_sessions_worktree_path",
+ "columns": [
+ "worktree_path"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_feishu_lookup": {
+ "name": "idx_sessions_feishu_lookup",
+ "columns": [
+ "source",
+ "feishu_bot_app_id",
+ "feishu_open_id"
+ ],
+ "isUnique": false
+ },
+ "idx_sessions_im_lookup": {
+ "name": "idx_sessions_im_lookup",
+ "columns": [
+ "source",
+ "im_bot_context_id",
+ "im_user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_parent_session_id_sessions_id_fk": {
+ "name": "sessions_parent_session_id_sessions_id_fk",
+ "tableFrom": "sessions",
+ "columnsFrom": [
+ "parent_session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_exposures": {
+ "name": "skill_usage_exposures",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "raw_line_no": {
+ "name": "raw_line_no",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_name": {
+ "name": "skill_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "skill_path": {
+ "name": "skill_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skill_document_hash": {
+ "name": "skill_document_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exposure_content_hash": {
+ "name": "exposure_content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_hash_source": {
+ "name": "document_hash_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_use_id": {
+ "name": "tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "seen_at": {
+ "name": "seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tool_call_count": {
+ "name": "tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "repeated_tool_call_count": {
+ "name": "repeated_tool_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "tool_error_count": {
+ "name": "tool_error_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_call_count": {
+ "name": "command_call_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "command_failure_count": {
+ "name": "command_failure_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_exposures_skill_document_version": {
+ "name": "idx_skill_usage_exposures_skill_document_version",
+ "columns": [
+ "analyzer_version",
+ "skill_name",
+ "skill_document_hash"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent": {
+ "name": "idx_skill_usage_exposures_skill_recent",
+ "columns": [
+ "skill_name",
+ "analyzer_version",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_skill_recent_any_version": {
+ "name": "idx_skill_usage_exposures_skill_recent_any_version",
+ "columns": [
+ "skill_name",
+ "seen_at"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_analyzer_recent_source": {
+ "name": "idx_skill_usage_exposures_analyzer_recent_source",
+ "columns": [
+ "analyzer_version",
+ "seen_at",
+ "raw_file_path"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_session": {
+ "name": "idx_skill_usage_exposures_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_exposures_raw_file": {
+ "name": "idx_skill_usage_exposures_raw_file",
+ "columns": [
+ "raw_file_path"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk": {
+ "name": "skill_usage_exposures_raw_file_path_skill_usage_sources_raw_file_path_fk",
+ "tableFrom": "skill_usage_exposures",
+ "columnsFrom": [
+ "raw_file_path"
+ ],
+ "tableTo": "skill_usage_sources",
+ "columnsTo": [
+ "raw_file_path"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "skill_usage_sources": {
+ "name": "skill_usage_sources",
+ "columns": {
+ "raw_file_path": {
+ "name": "raw_file_path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "analyzer_version": {
+ "name": "analyzer_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'6'"
+ },
+ "agent_kind": {
+ "name": "agent_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sdk_session_id": {
+ "name": "sdk_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mtime_ms": {
+ "name": "mtime_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_scanned_at": {
+ "name": "last_scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ok'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_skill_usage_sources_session": {
+ "name": "idx_skill_usage_sources_session",
+ "columns": [
+ "session_id"
+ ],
+ "isUnique": false
+ },
+ "idx_skill_usage_sources_sdk_session": {
+ "name": "idx_skill_usage_sources_sdk_session",
+ "columns": [
+ "sdk_session_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_run_aliases": {
+ "name": "subagent_run_aliases",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "alias": {
+ "name": "alias",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_run_aliases_lookup_idx": {
+ "name": "subagent_run_aliases_lookup_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "alias",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_run_aliases_session_id_sessions_id_fk": {
+ "name": "subagent_run_aliases_session_id_sessions_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "subagent_run_aliases_run_id_subagent_runs_id_fk": {
+ "name": "subagent_run_aliases_run_id_subagent_runs_id_fk",
+ "tableFrom": "subagent_run_aliases",
+ "columnsFrom": [
+ "run_id"
+ ],
+ "tableTo": "subagent_runs",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subagent_run_aliases_run_id_alias_pk": {
+ "columns": [
+ "run_id",
+ "alias"
+ ],
+ "name": "subagent_run_aliases_run_id_alias_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subagent_runs": {
+ "name": "subagent_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logical_agent_id": {
+ "name": "logical_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parent_tool_use_id": {
+ "name": "parent_tool_use_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "provider_run_ids": {
+ "name": "provider_run_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'running'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result": {
+ "name": "returned_result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_empty": {
+ "name": "returned_result_empty",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "returned_result_truncated": {
+ "name": "returned_result_truncated",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reasoning_effort": {
+ "name": "reasoning_effort",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool_uses": {
+ "name": "tool_uses",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "activity": {
+ "name": "activity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rewind_at": {
+ "name": "rewind_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "subagent_runs_logical_idx": {
+ "name": "subagent_runs_logical_idx",
+ "columns": [
+ "session_id",
+ "provider",
+ "logical_agent_id"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_session_idx": {
+ "name": "subagent_runs_session_idx",
+ "columns": [
+ "session_id",
+ "rewind_at",
+ "deleted_at",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "subagent_runs_parent_tool_use_idx": {
+ "name": "subagent_runs_parent_tool_use_idx",
+ "columns": [
+ "session_id",
+ "parent_tool_use_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "subagent_runs_session_id_sessions_id_fk": {
+ "name": "subagent_runs_session_id_sessions_id_fk",
+ "tableFrom": "subagent_runs",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "vec_table_meta": {
+ "name": "vec_table_meta",
+ "columns": {
+ "vec_table": {
+ "name": "vec_table",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dim": {
+ "name": "dim",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "registered_at": {
+ "name": "registered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_file_attachments": {
+ "name": "wechat_file_attachments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "abs_path": {
+ "name": "abs_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bytes": {
+ "name": "bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'staged'"
+ },
+ "promoted_at": {
+ "name": "promoted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_wechat_file_attachments_task": {
+ "name": "idx_wechat_file_attachments_task",
+ "columns": [
+ "binding_epoch",
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_file_attachments_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_file_attachments",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "tableTo": "wechat_sync_state",
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "wechat_file_attachments_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_file_attachments_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "tableTo": "wechat_inbox",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "wechat_file_attachments_session_id_sessions_id_fk": {
+ "name": "wechat_file_attachments_session_id_sessions_id_fk",
+ "tableFrom": "wechat_file_attachments",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_inbox": {
+ "name": "wechat_inbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_message_id": {
+ "name": "platform_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_seq": {
+ "name": "platform_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "peer_id": {
+ "name": "peer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "platform_created_at": {
+ "name": "platform_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "conversation_epoch": {
+ "name": "conversation_epoch",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "payload_json": {
+ "name": "payload_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_nonce": {
+ "name": "context_nonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_ciphertext": {
+ "name": "context_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context_tag": {
+ "name": "context_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_inbox_platform_message": {
+ "name": "uniq_wechat_inbox_platform_message",
+ "columns": [
+ "binding_epoch",
+ "platform_message_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_inbox_queue": {
+ "name": "idx_wechat_inbox_queue",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "received_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_lease": {
+ "name": "idx_wechat_inbox_lease",
+ "columns": [
+ "binding_epoch",
+ "lease_until"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_inbox_conversation": {
+ "name": "idx_wechat_inbox_conversation",
+ "columns": [
+ "binding_epoch",
+ "peer_id",
+ "conversation_epoch"
+ ],
+ "isUnique": false
+ },
+ "uniq_wechat_inbox_running_session": {
+ "name": "uniq_wechat_inbox_running_session",
+ "columns": [
+ "binding_epoch",
+ "session_id"
+ ],
+ "where": "\"wechat_inbox\".\"session_id\" IS NOT NULL AND \"wechat_inbox\".\"status\" IN ('dispatching', 'accepted_running', 'waiting_desktop', 'delivery_pending')",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_inbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_inbox",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "tableTo": "wechat_sync_state",
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "wechat_inbox_session_id_sessions_id_fk": {
+ "name": "wechat_inbox_session_id_sessions_id_fk",
+ "tableFrom": "wechat_inbox",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "tableTo": "sessions",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_outbox": {
+ "name": "wechat_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "chunk_index": {
+ "name": "chunk_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "media_json": {
+ "name": "media_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_outbox_client_id": {
+ "name": "uniq_wechat_outbox_client_id",
+ "columns": [
+ "binding_epoch",
+ "client_id"
+ ],
+ "isUnique": true
+ },
+ "idx_wechat_outbox_delivery": {
+ "name": "idx_wechat_outbox_delivery",
+ "columns": [
+ "binding_epoch",
+ "status",
+ "next_retry_at"
+ ],
+ "isUnique": false
+ },
+ "idx_wechat_outbox_task": {
+ "name": "idx_wechat_outbox_task",
+ "columns": [
+ "binding_epoch",
+ "task_id",
+ "chunk_index"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk": {
+ "name": "wechat_outbox_binding_epoch_wechat_sync_state_binding_epoch_fk",
+ "tableFrom": "wechat_outbox",
+ "columnsFrom": [
+ "binding_epoch"
+ ],
+ "tableTo": "wechat_sync_state",
+ "columnsTo": [
+ "binding_epoch"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "wechat_outbox_task_id_wechat_inbox_id_fk": {
+ "name": "wechat_outbox_task_id_wechat_inbox_id_fk",
+ "tableFrom": "wechat_outbox",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "tableTo": "wechat_inbox",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "wechat_sync_state": {
+ "name": "wechat_sync_state",
+ "columns": {
+ "binding_epoch": {
+ "name": "binding_epoch",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "sync_cursor": {
+ "name": "sync_cursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_poll_at": {
+ "name": "last_poll_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error_code": {
+ "name": "last_error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "uniq_wechat_sync_active": {
+ "name": "uniq_wechat_sync_active",
+ "columns": [
+ "is_active"
+ ],
+ "where": "\"wechat_sync_state\".\"is_active\" = 1",
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ },
+ "internal": {
+ "indexes": {
+ "uniq_orca_worker_creation_reservations_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ },
+ "uniq_orca_workers_team_label": {
+ "columns": {
+ "lower(\"label\")": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apps/desktop/drizzle/meta/_journal.json b/apps/desktop/drizzle/meta/_journal.json
index c88ba85439..13143a5b2f 100644
--- a/apps/desktop/drizzle/meta/_journal.json
+++ b/apps/desktop/drizzle/meta/_journal.json
@@ -715,6 +715,13 @@
"when": 1788431426308,
"tag": "0101_repair_cjk_fts_missing_rows",
"breakpoints": true
+ },
+ {
+ "idx": 102,
+ "version": "6",
+ "when": 1788503589671,
+ "tag": "0102_optimal_ender_wiggin",
+ "breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/apps/desktop/drizzle/scripts/0102_optimal_ender_wiggin.ts b/apps/desktop/drizzle/scripts/0102_optimal_ender_wiggin.ts
new file mode 100644
index 0000000000..686d64684d
--- /dev/null
+++ b/apps/desktop/drizzle/scripts/0102_optimal_ender_wiggin.ts
@@ -0,0 +1,36 @@
+function tableHasColumns(db, name, requiredColumns) {
+ const table = db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?")
+ .get(name);
+ if (!table) return false;
+ const columns = new Set(
+ db
+ .prepare(`PRAGMA table_info(${name})`)
+ .all()
+ .map((row) => row.name),
+ );
+ return requiredColumns.every((column) => columns.has(column));
+}
+
+function run(db) {
+ if (
+ !tableHasColumns(db, 'skill_usage_exposures', [
+ 'skill_name',
+ 'analyzer_version',
+ 'seen_at',
+ 'raw_file_path',
+ ])
+ ) {
+ return;
+ }
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS idx_skill_usage_exposures_skill_recent
+ ON skill_usage_exposures (skill_name, analyzer_version, seen_at);
+ CREATE INDEX IF NOT EXISTS idx_skill_usage_exposures_skill_recent_any_version
+ ON skill_usage_exposures (skill_name, seen_at);
+ CREATE INDEX IF NOT EXISTS idx_skill_usage_exposures_analyzer_recent_source
+ ON skill_usage_exposures (analyzer_version, seen_at, raw_file_path);
+ `);
+}
+
+module.exports = { run };
diff --git a/apps/desktop/src/main/localDb/__tests__/chatHistorySearch.test.ts b/apps/desktop/src/main/localDb/__tests__/chatHistorySearch.test.ts
index 2ec2bee928..e9438efb3a 100644
--- a/apps/desktop/src/main/localDb/__tests__/chatHistorySearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/chatHistorySearch.test.ts
@@ -96,9 +96,7 @@ describe('searchChatHistoryHybrid', () => {
expect(dbMocks.queryOne).not.toHaveBeenCalled();
expect(embeddingMocks.embedSync).not.toHaveBeenCalled();
expect(result.vectorUsed).toBe(false);
- expect(result.vectorSkipReason).toBe(
- '聊天记录语义索引未启用, 本次仅用 FTS 全文检索。',
- );
+ expect(result.vectorSkipReason).toBe('聊天记录语义索引未启用, 本次仅用 FTS 全文检索。');
});
it('short-circuits before both arms when the workdir filter matches no stored directory', async () => {
@@ -128,6 +126,188 @@ describe('searchChatHistoryHybrid', () => {
expect(result.vectorSkipReason).toBe('workdir 过滤在历史库中无匹配目录, 已短路跳过检索。');
});
+ it('hydrates every radius-zero anchor with one batch query', async () => {
+ dbMocks.query.mockResolvedValue([
+ { messageId: 'm1', sessionId: 's1', role: 'user', createdAt: 1_000, snippet: 'first' },
+ { messageId: 'm2', sessionId: 's1', role: 'assistant', createdAt: 2_000, snippet: 'second' },
+ ]);
+ const anchorRows = [
+ {
+ id: 'm1',
+ clientId: 'c1',
+ sessionId: 's1',
+ role: 'user',
+ content: JSON.stringify('first'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 1_000,
+ rewindAt: null,
+ },
+ {
+ id: 'm2',
+ clientId: 'c2',
+ sessionId: 's1',
+ role: 'assistant',
+ content: JSON.stringify('second'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 2_000,
+ rewindAt: null,
+ },
+ ];
+ dbMocks.select.mockImplementation((selection?: unknown) => ({
+ from: () => ({
+ where: () => Promise.resolve(selection ? [] : anchorRows),
+ }),
+ }));
+
+ const result = await searchChatHistoryHybrid({
+ query: 'message',
+ sessionIds: null,
+ workdir: null,
+ fromMs: null,
+ toMs: null,
+ agentKind: null,
+ roles: null,
+ contextRadius: 0,
+ limit: 10,
+ offset: 0,
+ skipVector: true,
+ });
+
+ expect(dbMocks.select.mock.calls.filter(([selection]) => selection === undefined)).toHaveLength(
+ 1,
+ );
+ expect(result.hits.map((hit) => hit.context.map((item) => item.id))).toEqual([['m1'], ['m2']]);
+ });
+
+ it('keeps a radius-zero hit when its anchor row is missing', async () => {
+ dbMocks.query.mockResolvedValue([
+ { messageId: 'm1', sessionId: 's1', role: 'user', createdAt: 1_000, snippet: 'first' },
+ { messageId: 'm2', sessionId: 's1', role: 'assistant', createdAt: 2_000, snippet: 'second' },
+ ]);
+ dbMocks.select.mockImplementation((selection?: unknown) => ({
+ from: () => ({
+ where: () =>
+ Promise.resolve(
+ selection
+ ? []
+ : [
+ {
+ id: 'm1',
+ clientId: 'c1',
+ sessionId: 's1',
+ role: 'user',
+ content: JSON.stringify('first'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 1_000,
+ rewindAt: null,
+ },
+ ],
+ ),
+ }),
+ }));
+
+ const result = await searchChatHistoryHybrid({
+ query: 'message',
+ sessionIds: null,
+ workdir: null,
+ fromMs: null,
+ toMs: null,
+ agentKind: null,
+ roles: null,
+ contextRadius: 0,
+ limit: 10,
+ offset: 0,
+ skipVector: true,
+ });
+
+ expect(result.hits.map((hit) => [hit.messageId, hit.context.length])).toEqual([
+ ['m1', 1],
+ ['m2', 0],
+ ]);
+ });
+
+ it('keeps the per-hit context window queries when radius is positive', async () => {
+ dbMocks.query.mockResolvedValue([
+ { messageId: 'm2', sessionId: 's1', role: 'assistant', createdAt: 2_000, snippet: 'anchor' },
+ ]);
+ const rows = {
+ before: {
+ id: 'm1',
+ clientId: 'c1',
+ sessionId: 's1',
+ role: 'user',
+ content: JSON.stringify('before'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 1_000,
+ rewindAt: null,
+ },
+ anchor: {
+ id: 'm2',
+ clientId: 'c2',
+ sessionId: 's1',
+ role: 'assistant',
+ content: JSON.stringify('anchor'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 2_000,
+ rewindAt: null,
+ },
+ after: {
+ id: 'm3',
+ clientId: 'c3',
+ sessionId: 's1',
+ role: 'user',
+ content: JSON.stringify('after'),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: 3_000,
+ rewindAt: null,
+ },
+ };
+ let messageSelectCount = 0;
+ dbMocks.select.mockImplementation((selection?: unknown) => {
+ if (selection) {
+ return { from: () => ({ where: () => Promise.resolve([]) }) };
+ }
+ messageSelectCount += 1;
+ const resultRows =
+ messageSelectCount === 1
+ ? [rows.anchor]
+ : messageSelectCount === 2
+ ? [rows.before]
+ : [rows.after];
+ return {
+ from: () => ({
+ where: () =>
+ messageSelectCount === 1
+ ? { limit: () => Promise.resolve(resultRows) }
+ : { orderBy: () => ({ limit: () => Promise.resolve(resultRows) }) },
+ }),
+ };
+ });
+
+ const result = await searchChatHistoryHybrid({
+ query: 'anchor',
+ sessionIds: null,
+ workdir: null,
+ fromMs: null,
+ toMs: null,
+ agentKind: null,
+ roles: null,
+ contextRadius: 1,
+ limit: 10,
+ offset: 0,
+ skipVector: true,
+ });
+
+ expect(messageSelectCount).toBe(3);
+ expect(result.hits[0].context.map((item) => item.id)).toEqual(['m1', 'm2', 'm3']);
+ });
+
it('can page beyond the default FTS pool for conversation search', async () => {
const ftsRows = Array.from({ length: 51 }, (_, index) => ({
messageId: `m${index + 1}`,
@@ -144,8 +324,8 @@ describe('searchChatHistoryHybrid', () => {
from: () => ({
where: () => {
if (selection) return Promise.resolve([]);
- return {
- limit: async () => [{
+ return Promise.resolve([
+ {
id: 'm51',
clientId: 'c51',
sessionId: 's2',
@@ -155,8 +335,8 @@ describe('searchChatHistoryHybrid', () => {
agentMeta: null,
createdAt: 1_050,
rewindAt: null,
- }],
- };
+ },
+ ]);
},
}),
}));
@@ -204,8 +384,8 @@ describe('searchChatHistoryHybrid', () => {
from: () => ({
where: () => {
if (selection) return Promise.resolve([]);
- return {
- limit: async () => [{
+ return Promise.resolve([
+ {
id: 'm51',
clientId: 'c51',
sessionId: 's2',
@@ -215,8 +395,8 @@ describe('searchChatHistoryHybrid', () => {
agentMeta: null,
createdAt: 1_050,
rewindAt: null,
- }],
- };
+ },
+ ]);
},
}),
}));
@@ -270,8 +450,8 @@ describe('searchChatHistoryHybrid', () => {
from: () => ({
where: () => {
if (selection) return Promise.resolve([]);
- return {
- limit: async () => [{
+ return Promise.resolve([
+ {
id: 'm1',
clientId: 'c1',
sessionId: 's1',
@@ -281,8 +461,8 @@ describe('searchChatHistoryHybrid', () => {
agentMeta: null,
createdAt: 1_000,
rewindAt: null,
- }],
- };
+ },
+ ]);
},
}),
}));
diff --git a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
index 117fcfe7dc..805b6a0674 100644
--- a/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/migrationReplay.test.ts
@@ -156,6 +156,9 @@ describeMigrationReplay('migration replay', () => {
expect(indexExists(db, 'idx_schedule_runs_running_legacy')).toBe(true);
expect(indexExists(db, 'idx_schedule_runs_unread_terminal')).toBe(true);
expect(indexExists(db, 'idx_schedule_runs_session_latest')).toBe(true);
+ expect(indexExists(db, 'idx_skill_usage_exposures_skill_recent')).toBe(true);
+ expect(indexExists(db, 'idx_skill_usage_exposures_skill_recent_any_version')).toBe(true);
+ expect(indexExists(db, 'idx_skill_usage_exposures_analyzer_recent_source')).toBe(true);
expect(triggerExists(db, 'schedule_session_latest_run_insert')).toBe(true);
expect(triggerExists(db, 'schedule_session_latest_run_delete')).toBe(true);
expect(triggerExists(db, 'schedule_session_latest_run_update')).toBe(true);
diff --git a/apps/desktop/src/main/localDb/chatHistorySearch.ts b/apps/desktop/src/main/localDb/chatHistorySearch.ts
index 793f967edb..63c043be91 100644
--- a/apps/desktop/src/main/localDb/chatHistorySearch.ts
+++ b/apps/desktop/src/main/localDb/chatHistorySearch.ts
@@ -178,18 +178,29 @@ export async function searchChatHistoryHybrid(
const pageEntries = pool.slice(start, start + args.limit);
const nextOffset = start + args.limit < pool.length ? start + args.limit : null;
- // 5) 逐条命中拼上下文窗口
+ // radius=0 is the conversation-search hot path. Hydrate the whole page in
+ // one worker RPC; callers that need neighbours keep the original window query.
+ const anchorContexts =
+ args.contextRadius <= 0
+ ? await fetchAnchorContexts(pageEntries.map((entry) => entry.messageId))
+ : null;
+
+ // 5) 按命中顺序组装上下文窗口
const hits: SearchChatHistoryHit[] = [];
for (const fe of pageEntries) {
const meta = metaById.get(fe.messageId);
if (!meta) continue; // 理论不会发生(fused 的 id 必来自两路 arm)
- const context = await fetchContextWindow(
- fe.messageId,
- meta.sessionId,
- meta.createdAt,
- args.roles,
- args.contextRadius,
- );
+ const context =
+ anchorContexts?.get(fe.messageId) ??
+ (anchorContexts
+ ? []
+ : await fetchContextWindow(
+ fe.messageId,
+ meta.sessionId,
+ meta.createdAt,
+ args.roles,
+ args.contextRadius,
+ ));
hits.push({
messageId: fe.messageId,
sessionId: meta.sessionId,
@@ -221,6 +232,20 @@ export async function searchChatHistoryHybrid(
// ── FTS arm ──────────────────────────────────────────────────────────────────
+async function fetchAnchorContexts(
+ anchorIds: readonly string[],
+): Promise<Map<string, SearchChatHistoryContextMessage[]>> {
+ const uniqueIds = [...new Set(anchorIds)];
+ if (uniqueIds.length === 0) return new Map();
+
+ const rows = await getDbClient()
+ .drizzle.select()
+ .from(messagesTable)
+ .where(inArray(messagesTable.id, uniqueIds));
+
+ return new Map(rows.map((row) => [row.id, [rowToContext(row, true)]]));
+}
+
async function runFtsArm(
args: SearchChatHistoryEngineArgs,
workdirCandidates: string[] | null,
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index 373aeaca98..0ea9118346 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -416,6 +416,8 @@ function dispatchTx(readyDb, payload) {
return imDeleteBindings(readyDb, request.args);
case 'im.replaceBinding':
return imReplaceBinding(readyDb, request.args);
+ case 'skillUsage.applyMutation':
+ return skillUsageApplyMutation(readyDb, request.args);
case 'session.importShare':
return sessionImportShare(readyDb, request.args);
default:
@@ -423,6 +425,80 @@ function dispatchTx(readyDb, payload) {
}
}
+// Keep in sync with worker/opHandlers/tx.ts:skillUsageApplyMutation.
+function skillUsageApplyMutation(readyDb, args) {
+ const payload = asRecord(args, 'skillUsage.applyMutation args');
+ const kind = expectString(payload.kind, 'kind');
+ if (kind === 'persist') {
+ const rawSource = asRecord(payload.source, 'source');
+ const source = {
+ rawFilePath: expectString(rawSource.rawFilePath, 'source.rawFilePath'),
+ analyzerVersion: expectString(rawSource.analyzerVersion, 'source.analyzerVersion'),
+ agentKind: expectString(rawSource.agentKind, 'source.agentKind'),
+ sessionId: expectString(rawSource.sessionId, 'source.sessionId'),
+ sdkSessionId: expectString(rawSource.sdkSessionId, 'source.sdkSessionId'),
+ mtimeMs: expectNumber(rawSource.mtimeMs, 'source.mtimeMs'),
+ sizeBytes: expectNumber(rawSource.sizeBytes, 'source.sizeBytes'),
+ scannedAt: expectNumber(rawSource.scannedAt, 'source.scannedAt'),
+ };
+ const exposures = expectArray(payload.exposures, 'exposures');
+ const upsertSource = readyDb.prepare(
+ "INSERT INTO skill_usage_sources (raw_file_path, analyzer_version, agent_kind, session_id, sdk_session_id, mtime_ms, size_bytes, last_scanned_at, status, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ok', NULL) ON CONFLICT(raw_file_path) DO UPDATE SET analyzer_version = excluded.analyzer_version, agent_kind = excluded.agent_kind, session_id = excluded.session_id, sdk_session_id = excluded.sdk_session_id, mtime_ms = excluded.mtime_ms, size_bytes = excluded.size_bytes, last_scanned_at = excluded.last_scanned_at, status = 'ok', error = NULL",
+ );
+ const deleteExposure = readyDb.prepare(
+ 'DELETE FROM skill_usage_exposures WHERE raw_file_path = ? AND analyzer_version = ?',
+ );
+ const insertExposure = readyDb.prepare(
+ 'INSERT INTO skill_usage_exposures (id, analyzer_version, raw_file_path, raw_line_no, session_id, sdk_session_id, agent_kind, skill_name, skill_path, skill_document_hash, exposure_content_hash, document_hash_source, source, tool_use_id, seen_at, tool_call_count, repeated_tool_call_count, tool_error_count, command_call_count, command_failure_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ );
+ return readyDb.transaction(() => {
+ upsertSource.run(source.rawFilePath, source.analyzerVersion, source.agentKind, source.sessionId, source.sdkSessionId, source.mtimeMs, source.sizeBytes, source.scannedAt);
+ deleteExposure.run(source.rawFilePath, source.analyzerVersion);
+ for (let index = 0; index < exposures.length; index += 1) {
+ const row = asRecord(exposures[index], 'exposures.' + index);
+ insertExposure.run(
+ source.analyzerVersion + ':' + expectString(row.id, 'exposures.' + index + '.id'),
+ source.analyzerVersion,
+ expectString(row.rawFilePath, 'exposures.' + index + '.rawFilePath'),
+ expectNumber(row.rawLineNo, 'exposures.' + index + '.rawLineNo'),
+ expectString(row.sessionId, 'exposures.' + index + '.sessionId'),
+ expectString(row.sdkSessionId, 'exposures.' + index + '.sdkSessionId'),
+ expectString(row.agentKind, 'exposures.' + index + '.agentKind'),
+ expectString(row.skillName, 'exposures.' + index + '.skillName'),
+ nullableString(row.skillPath),
+ nullableString(row.skillDocumentHash),
+ expectString(row.exposureContentHash, 'exposures.' + index + '.exposureContentHash'),
+ expectString(row.documentHashSource, 'exposures.' + index + '.documentHashSource'),
+ expectString(row.source, 'exposures.' + index + '.source'),
+ nullableString(row.toolUseId),
+ expectNumber(row.seenAt, 'exposures.' + index + '.seenAt'),
+ expectNumber(row.toolCallCount, 'exposures.' + index + '.toolCallCount'),
+ expectNumber(row.repeatedToolCallCount, 'exposures.' + index + '.repeatedToolCallCount'),
+ expectNumber(row.toolErrorCount, 'exposures.' + index + '.toolErrorCount'),
+ expectNumber(row.commandCallCount, 'exposures.' + index + '.commandCallCount'),
+ expectNumber(row.commandFailureCount, 'exposures.' + index + '.commandFailureCount'),
+ );
+ }
+ })();
+ }
+ if (kind === 'deleteBefore') {
+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');
+ const recentSince = expectNumber(payload.recentSince, 'recentSince');
+ return readyDb.transaction(() => {
+ readyDb.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version = ? AND seen_at < ?').run(analyzerVersion, recentSince);
+ readyDb.prepare('DELETE FROM skill_usage_sources WHERE analyzer_version = ? AND mtime_ms < ? AND raw_file_path NOT IN (SELECT raw_file_path FROM skill_usage_exposures)').run(analyzerVersion, recentSince);
+ })();
+ }
+ if (kind === 'promote') {
+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');
+ return readyDb.transaction(() => {
+ readyDb.prepare("INSERT INTO migration_meta (key, value) VALUES ('skill_usage_analyzer_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(analyzerVersion);
+ readyDb.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);
+ })();
+ }
+ throw invalidArgs('unknown skill usage mutation: ' + kind);
+}
+
// ⚠️ 与 worker/opHandlers/tx.ts 的 imDeleteBindings 保持一致。
function imDeleteBindings(readyDb, args) {
const payload = asRecord(args, 'im.deleteBindings args');
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index e4872709f0..c1280dd575 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -9,6 +9,7 @@ import { SESSION_SOURCES } from '../../../../shared/sessionSource.js';
import { buildDbWorkerBundle } from '../../__tests__/dbWorkerTestUtils.js';
import type { DbClient } from '../DbClient.js';
import { createDbClient } from '../DbClient.js';
+import type { SkillUsageApplyMutationArgs } from '../tx/types.js';
const INIT_SQL = `
CREATE TABLE migration_meta (key TEXT PRIMARY KEY, value TEXT);
@@ -18,6 +19,40 @@ CREATE TABLE migration_history (
content_hash TEXT NOT NULL,
applied_at INTEGER NOT NULL
);
+CREATE TABLE skill_usage_sources (
+ raw_file_path TEXT PRIMARY KEY,
+ analyzer_version TEXT NOT NULL,
+ agent_kind TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ sdk_session_id TEXT NOT NULL,
+ mtime_ms INTEGER NOT NULL,
+ size_bytes INTEGER NOT NULL,
+ last_scanned_at INTEGER NOT NULL,
+ status TEXT NOT NULL,
+ error TEXT
+);
+CREATE TABLE skill_usage_exposures (
+ id TEXT PRIMARY KEY,
+ analyzer_version TEXT NOT NULL,
+ raw_file_path TEXT NOT NULL,
+ raw_line_no INTEGER NOT NULL,
+ session_id TEXT NOT NULL,
+ sdk_session_id TEXT NOT NULL,
+ agent_kind TEXT NOT NULL,
+ skill_name TEXT NOT NULL,
+ skill_path TEXT,
+ skill_document_hash TEXT,
+ exposure_content_hash TEXT NOT NULL,
+ document_hash_source TEXT NOT NULL,
+ source TEXT NOT NULL,
+ tool_use_id TEXT,
+ seen_at INTEGER NOT NULL,
+ tool_call_count INTEGER NOT NULL,
+ repeated_tool_call_count INTEGER NOT NULL,
+ tool_error_count INTEGER NOT NULL,
+ command_call_count INTEGER NOT NULL,
+ command_failure_count INTEGER NOT NULL
+);
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New Maker',
@@ -2845,6 +2880,111 @@ describe('db worker tx handlers', () => {
});
});
+ it.each([
+ { label: 'bundled worker', useInlineWorker: false },
+ { label: 'inline worker', useInlineWorker: true },
+ ])('applies SkillHub usage mutations atomically through the $label tx path', async ({ useInlineWorker }) => {
+ await withClient(async (client) => {
+ type PersistArgs = Extract<SkillUsageApplyMutationArgs, { kind: 'persist' }>;
+ const source = (rawFilePath: string, analyzerVersion: string, mtimeMs: number): PersistArgs['source'] => ({
+ rawFilePath,
+ analyzerVersion,
+ agentKind: 'codex',
+ sessionId: `session-${rawFilePath}`,
+ sdkSessionId: `sdk-${rawFilePath}`,
+ mtimeMs,
+ sizeBytes: 10,
+ scannedAt: mtimeMs,
+ });
+ const exposure = (
+ id: string,
+ rawFilePath: string,
+ analyzerVersion: string,
+ seenAt: number,
+ ): PersistArgs['exposures'][number] => ({
+ id,
+ rawFilePath,
+ rawLineNo: 1,
+ sessionId: `session-${rawFilePath}`,
+ sdkSessionId: `sdk-${rawFilePath}`,
+ agentKind: 'codex',
+ skillName: 'word-doc',
+ skillPath: null,
+ skillDocumentHash: `doc-${analyzerVersion}`,
+ exposureContentHash: `content-${id}`,
+ documentHashSource: 'transcript_file_read',
+ source: 'codex_skill_file_read',
+ toolUseId: null,
+ seenAt,
+ toolCallCount: 1,
+ repeatedToolCallCount: 0,
+ toolErrorCount: 0,
+ commandCallCount: 0,
+ commandFailureCount: 0,
+ });
+
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source: source('current.jsonl', '6', 1),
+ exposures: [exposure('first', 'current.jsonl', '6', 200)],
+ });
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source: source('current.jsonl', '6', 2),
+ exposures: [exposure('replacement', 'current.jsonl', '6', 201)],
+ });
+ await expect(client.query<{ id: string }>(
+ 'SELECT id FROM skill_usage_exposures WHERE raw_file_path = ?',
+ ['current.jsonl'],
+ )).resolves.toEqual([{ id: '6:replacement' }]);
+
+ await expect(client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source: source('current.jsonl', '6', 999),
+ exposures: [
+ exposure('duplicate', 'current.jsonl', '6', 300),
+ exposure('duplicate', 'current.jsonl', '6', 301),
+ ],
+ })).rejects.toThrow();
+ await expect(client.queryOne(
+ 'SELECT mtime_ms, status FROM skill_usage_sources WHERE raw_file_path = ?',
+ ['current.jsonl'],
+ )).resolves.toEqual({ mtime_ms: 2, status: 'ok' });
+ await expect(client.query<{ id: string }>(
+ 'SELECT id FROM skill_usage_exposures WHERE raw_file_path = ?',
+ ['current.jsonl'],
+ )).resolves.toEqual([{ id: '6:replacement' }]);
+
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source: source('old.jsonl', '6', 10),
+ exposures: [exposure('old', 'old.jsonl', '6', 10)],
+ });
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'deleteBefore',
+ analyzerVersion: '6',
+ recentSince: 100,
+ });
+ await expect(client.queryOne(
+ 'SELECT raw_file_path FROM skill_usage_sources WHERE raw_file_path = ?',
+ ['old.jsonl'],
+ )).resolves.toBeUndefined();
+
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source: source('previous.jsonl', '5', 200),
+ exposures: [exposure('previous', 'previous.jsonl', '5', 200)],
+ });
+ await client.tx('skillUsage.applyMutation', { kind: 'promote', analyzerVersion: '6' });
+ await expect(client.queryOne(
+ "SELECT value FROM migration_meta WHERE key = 'skill_usage_analyzer_version'",
+ )).resolves.toEqual({ value: '6' });
+ await expect(client.queryOne(
+ "SELECT id FROM skill_usage_exposures WHERE analyzer_version = '5'",
+ )).resolves.toBeUndefined();
+ }, { useInlineWorker });
+ });
+
it.each([
{ label: 'bundled worker', useInlineWorker: false },
{ label: 'inline worker', useInlineWorker: true },
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 482f36b64a..7d11a9b5d1 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -47,6 +47,7 @@ export type DbTxName =
| 'wechatPromoteTaskAttachments'
| 'wechatRefreshOutboxContexts'
| 'wechatUnbindCleanup'
+ | 'skillUsage.applyMutation'
| 'session.importShare';
export interface CodexImportMessagesArgs {
@@ -538,6 +539,37 @@ export interface ImDeleteBindingsArgs {
}>;
}
+export interface ImRotateSessionArgs {
+ previousSessionId: string | null;
+ detachBinding: {
+ channel: string;
+ botContextId: string;
+ userId: string;
+ scopeKey: string;
+ targetSessionId: string;
+ } | null;
+ session: {
+ id: string;
+ title: string;
+ workingDir: string;
+ workspaceKind: 'project' | 'dialogue';
+ model: string;
+ effort: string;
+ permissionMode: string;
+ fastMode: boolean;
+ agentKind: string;
+ source: string;
+ providerId: string | null;
+ imBotContextId: string;
+ imUserId: string;
+ };
+ now: number;
+}
+
+export interface ImRotateSessionResult {
+ previousStatus: 'active' | 'archived' | 'deleted' | null;
+}
+
export type WechatInboxStatus =
| 'pending'
| 'dispatching'
@@ -817,36 +849,43 @@ export interface WechatUnbindCleanupResult {
filePaths: string[];
}
-export interface ImRotateSessionArgs {
- previousSessionId: string | null;
- detachBinding: {
- channel: string;
- botContextId: string;
- userId: string;
- scopeKey: string;
- targetSessionId: string;
- } | null;
- session: {
- id: string;
- title: string;
- workingDir: string;
- workspaceKind: 'project' | 'dialogue';
- model: string;
- effort: string;
- permissionMode: string;
- fastMode: boolean;
- agentKind: string;
- providerId: string | null;
- source: string;
- imBotContextId: string;
- imUserId: string;
- };
- now: number;
-}
-
-export interface ImRotateSessionResult {
- previousStatus: 'active' | 'archived' | 'deleted' | null;
-}
+export type SkillUsageApplyMutationArgs =
+ | {
+ kind: 'persist';
+ source: {
+ rawFilePath: string;
+ analyzerVersion: string;
+ agentKind: string;
+ sessionId: string;
+ sdkSessionId: string;
+ mtimeMs: number;
+ sizeBytes: number;
+ scannedAt: number;
+ };
+ exposures: Array<{
+ id: string;
+ rawFilePath: string;
+ rawLineNo: number;
+ sessionId: string;
+ sdkSessionId: string;
+ agentKind: string;
+ skillName: string;
+ skillPath: string | null;
+ skillDocumentHash: string | null;
+ exposureContentHash: string;
+ documentHashSource: string;
+ source: string;
+ toolUseId: string | null;
+ seenAt: number;
+ toolCallCount: number;
+ repeatedToolCallCount: number;
+ toolErrorCount: number;
+ commandCallCount: number;
+ commandFailureCount: number;
+ }>;
+ }
+ | { kind: 'deleteBefore'; analyzerVersion: string; recentSince: number }
+ | { kind: 'promote'; analyzerVersion: string };
export type DbTxArgsByName = {
'codex.importMessages': CodexImportMessagesArgs;
@@ -897,6 +936,7 @@ export type DbTxArgsByName = {
wechatPromoteTaskAttachments: WechatPromoteTaskAttachmentsArgs;
wechatRefreshOutboxContexts: WechatRefreshOutboxContextsArgs;
wechatUnbindCleanup: WechatUnbindCleanupArgs;
+ 'skillUsage.applyMutation': SkillUsageApplyMutationArgs;
'session.importShare': SessionImportShareArgs;
};
@@ -949,5 +989,6 @@ export type DbTxResultByName = {
wechatPromoteTaskAttachments: WechatPromoteTaskAttachmentsResult;
wechatRefreshOutboxContexts: WechatRefreshOutboxContextsResult;
wechatUnbindCleanup: WechatUnbindCleanupResult;
+ 'skillUsage.applyMutation': undefined;
'session.importShare': { messageCount: number };
};
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 40f54df3ed..d6edbbcf67 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -1386,6 +1386,20 @@ export const skillUsageExposures = sqliteTable(
t.skillName,
t.skillDocumentHash,
),
+ bySkillRecent: index('idx_skill_usage_exposures_skill_recent').on(
+ t.skillName,
+ t.analyzerVersion,
+ t.seenAt,
+ ),
+ bySkillRecentAnyVersion: index('idx_skill_usage_exposures_skill_recent_any_version').on(
+ t.skillName,
+ t.seenAt,
+ ),
+ byAnalyzerRecentSource: index('idx_skill_usage_exposures_analyzer_recent_source').on(
+ t.analyzerVersion,
+ t.seenAt,
+ t.rawFilePath,
+ ),
bySession: index('idx_skill_usage_exposures_session').on(t.sessionId),
byRawFile: index('idx_skill_usage_exposures_raw_file').on(t.rawFilePath),
}),
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index c3fe1c51a6..ad8c7e6b8c 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -132,6 +132,8 @@ export function tx(db: Database.Database, args: unknown): unknown {
return wechatRefreshOutboxContexts(db, txArgs);
case 'wechatUnbindCleanup':
return wechatUnbindCleanup(db, txArgs);
+ case 'skillUsage.applyMutation':
+ return skillUsageApplyMutation(db, txArgs);
case 'session.importShare':
return sessionImportShare(db, txArgs);
default:
@@ -139,6 +141,146 @@ export function tx(db: Database.Database, args: unknown): unknown {
}
}
+function skillUsageApplyMutation(db: Database.Database, args: unknown): void {
+ const payload = asRecord(args, 'skillUsage.applyMutation args');
+ const kind = expectString(payload.kind, 'kind');
+
+ if (kind === 'persist') {
+ const rawSource = asRecord(payload.source, 'source');
+ const source = {
+ rawFilePath: expectString(rawSource.rawFilePath, 'source.rawFilePath'),
+ analyzerVersion: expectString(rawSource.analyzerVersion, 'source.analyzerVersion'),
+ agentKind: expectString(rawSource.agentKind, 'source.agentKind'),
+ sessionId: expectString(rawSource.sessionId, 'source.sessionId'),
+ sdkSessionId: expectString(rawSource.sdkSessionId, 'source.sdkSessionId'),
+ mtimeMs: expectNumber(rawSource.mtimeMs, 'source.mtimeMs'),
+ sizeBytes: expectNumber(rawSource.sizeBytes, 'source.sizeBytes'),
+ scannedAt: expectNumber(rawSource.scannedAt, 'source.scannedAt'),
+ };
+ const exposures = expectArray(payload.exposures, 'exposures').map((raw, index) => {
+ const row = asRecord(raw, `exposures.${index}`);
+ return {
+ id: expectString(row.id, `exposures.${index}.id`),
+ rawFilePath: expectString(row.rawFilePath, `exposures.${index}.rawFilePath`),
+ rawLineNo: expectNumber(row.rawLineNo, `exposures.${index}.rawLineNo`),
+ sessionId: expectString(row.sessionId, `exposures.${index}.sessionId`),
+ sdkSessionId: expectString(row.sdkSessionId, `exposures.${index}.sdkSessionId`),
+ agentKind: expectString(row.agentKind, `exposures.${index}.agentKind`),
+ skillName: expectString(row.skillName, `exposures.${index}.skillName`),
+ skillPath: nullableString(row.skillPath),
+ skillDocumentHash: nullableString(row.skillDocumentHash),
+ exposureContentHash: expectString(row.exposureContentHash, `exposures.${index}.exposureContentHash`),
+ documentHashSource: expectString(row.documentHashSource, `exposures.${index}.documentHashSource`),
+ source: expectString(row.source, `exposures.${index}.source`),
+ toolUseId: nullableString(row.toolUseId),
+ seenAt: expectNumber(row.seenAt, `exposures.${index}.seenAt`),
+ toolCallCount: expectNumber(row.toolCallCount, `exposures.${index}.toolCallCount`),
+ repeatedToolCallCount: expectNumber(row.repeatedToolCallCount, `exposures.${index}.repeatedToolCallCount`),
+ toolErrorCount: expectNumber(row.toolErrorCount, `exposures.${index}.toolErrorCount`),
+ commandCallCount: expectNumber(row.commandCallCount, `exposures.${index}.commandCallCount`),
+ commandFailureCount: expectNumber(row.commandFailureCount, `exposures.${index}.commandFailureCount`),
+ };
+ });
+
+ const upsertSource = db.prepare(`
+ INSERT INTO skill_usage_sources (
+ raw_file_path, analyzer_version, agent_kind, session_id, sdk_session_id,
+ mtime_ms, size_bytes, last_scanned_at, status, error
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ok', NULL)
+ ON CONFLICT(raw_file_path) DO UPDATE SET
+ analyzer_version = excluded.analyzer_version,
+ agent_kind = excluded.agent_kind,
+ session_id = excluded.session_id,
+ sdk_session_id = excluded.sdk_session_id,
+ mtime_ms = excluded.mtime_ms,
+ size_bytes = excluded.size_bytes,
+ last_scanned_at = excluded.last_scanned_at,
+ status = 'ok',
+ error = NULL
+ `);
+ const deleteExposure = db.prepare(
+ 'DELETE FROM skill_usage_exposures WHERE raw_file_path = ? AND analyzer_version = ?',
+ );
+ const insertExposure = db.prepare(`
+ INSERT INTO skill_usage_exposures (
+ id, analyzer_version, raw_file_path, raw_line_no, session_id, sdk_session_id, agent_kind,
+ skill_name, skill_path, skill_document_hash, exposure_content_hash, document_hash_source,
+ source, tool_use_id, seen_at, tool_call_count, repeated_tool_call_count,
+ tool_error_count, command_call_count, command_failure_count
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `);
+ db.transaction(() => {
+ upsertSource.run(
+ source.rawFilePath,
+ source.analyzerVersion,
+ source.agentKind,
+ source.sessionId,
+ source.sdkSessionId,
+ source.mtimeMs,
+ source.sizeBytes,
+ source.scannedAt,
+ );
+ deleteExposure.run(source.rawFilePath, source.analyzerVersion);
+ for (const exposure of exposures) {
+ insertExposure.run(
+ `${source.analyzerVersion}:${exposure.id}`,
+ source.analyzerVersion,
+ exposure.rawFilePath,
+ exposure.rawLineNo,
+ exposure.sessionId,
+ exposure.sdkSessionId,
+ exposure.agentKind,
+ exposure.skillName,
+ exposure.skillPath,
+ exposure.skillDocumentHash,
+ exposure.exposureContentHash,
+ exposure.documentHashSource,
+ exposure.source,
+ exposure.toolUseId,
+ exposure.seenAt,
+ exposure.toolCallCount,
+ exposure.repeatedToolCallCount,
+ exposure.toolErrorCount,
+ exposure.commandCallCount,
+ exposure.commandFailureCount,
+ );
+ }
+ })();
+ return;
+ }
+
+ if (kind === 'deleteBefore') {
+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');
+ const recentSince = expectNumber(payload.recentSince, 'recentSince');
+ db.transaction(() => {
+ db.prepare(
+ 'DELETE FROM skill_usage_exposures WHERE analyzer_version = ? AND seen_at < ?',
+ ).run(analyzerVersion, recentSince);
+ db.prepare(`
+ DELETE FROM skill_usage_sources
+ WHERE analyzer_version = ? AND mtime_ms < ?
+ AND raw_file_path NOT IN (SELECT raw_file_path FROM skill_usage_exposures)
+ `).run(analyzerVersion, recentSince);
+ })();
+ return;
+ }
+
+ if (kind === 'promote') {
+ const analyzerVersion = expectString(payload.analyzerVersion, 'analyzerVersion');
+ db.transaction(() => {
+ db.prepare(`
+ INSERT INTO migration_meta (key, value)
+ VALUES ('skill_usage_analyzer_version', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
+ `).run(analyzerVersion);
+ db.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);
+ })();
+ return;
+ }
+
+ throw invalidArgs(`unknown skill usage mutation: ${kind}`);
+}
+
/** Remove every stale startup binding as one all-or-nothing repair. */
function imDeleteBindings(db: Database.Database, args: unknown): void {
const payload = asRecord(args, 'im.deleteBindings args');
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 375139ae94..597cb17b6c 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -44,12 +44,18 @@ vi.mock('../../appSessionState', () => ({
}));
const ensureReady = vi.fn();
-const getRawDb = vi.fn(() => ({ id: 'db' }));
vi.mock('../../localDb', () => ({
ensureReady,
- getRawDb,
}));
+const defaultDbClient = { id: 'client' };
+const getCurrentDbClientSnapshot = vi.fn(() => ({
+ client: defaultDbClient,
+ userId: 'local-v1',
+ clientEpoch: 1,
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot }));
+
const readSkillRawFile = vi.fn();
const readSkillContent = vi.fn();
const listSkillFolderChildren = vi.fn();
@@ -111,6 +117,12 @@ describe('registerSkillhubIpc usage handlers', () => {
handlers.clear();
vi.clearAllMocks();
getCurrentDataOwnerId.mockReturnValue('local-v1');
+ getCurrentDbClientSnapshot.mockReset();
+ getCurrentDbClientSnapshot.mockReturnValue({
+ client: defaultDbClient,
+ userId: 'local-v1',
+ clientEpoch: 1,
+ });
ensureReady.mockResolvedValue({ ready: true });
requestLocalSkillUsageAnalyticsRefresh.mockReturnValue(null);
showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });
@@ -428,6 +440,13 @@ describe('registerSkillhubIpc usage handlers', () => {
});
it('retries usage summary after local DB becomes ready', async () => {
+ const firstClient = { id: 'first-client' };
+ const readyClient = { id: 'ready-client' };
+ const firstSnapshot = { client: firstClient, userId: 'local-v1', clientEpoch: 1 };
+ const readySnapshot = { client: readyClient, userId: 'local-v1', clientEpoch: 2 };
+ getCurrentDbClientSnapshot
+ .mockReturnValueOnce(firstSnapshot)
+ .mockReturnValue(readySnapshot);
getLocalSkillUsageSummary
.mockRejectedValueOnce(new Error('localDb not ready: pending'))
.mockResolvedValueOnce({ success: true, summary: { totalUseCount: 1 }, refreshing: false });
@@ -437,7 +456,18 @@ describe('registerSkillhubIpc usage handlers', () => {
const result = await handler?.({}, { name: 'word-doc' });
expect(ensureReady).toHaveBeenCalledWith('local-v1');
+ expect(getCurrentDbClientSnapshot).toHaveBeenCalledTimes(3);
expect(getLocalSkillUsageSummary).toHaveBeenCalledTimes(2);
+ expect(getLocalSkillUsageSummary).toHaveBeenNthCalledWith(1, {
+ skillName: 'word-doc',
+ currentSkillContent: null,
+ client: firstClient,
+ });
+ expect(getLocalSkillUsageSummary).toHaveBeenNthCalledWith(2, {
+ skillName: 'word-doc',
+ currentSkillContent: null,
+ client: readyClient,
+ });
expect(result).toEqual({ success: true, summary: { totalUseCount: 1 }, refreshing: false });
});
@@ -450,6 +480,36 @@ describe('registerSkillhubIpc usage handlers', () => {
expect(result).toEqual({ success: false, error: 'bad transcript' });
});
+ it('does not return a usage summary from the previous database owner', async () => {
+ const previousClient = { id: 'previous-client' };
+ const currentClient = { id: 'current-client' };
+ const previousSnapshot = { client: previousClient, userId: 'owner-a', clientEpoch: 1 };
+ const currentSnapshot = { client: currentClient, userId: 'owner-b', clientEpoch: 2 };
+ getCurrentDbClientSnapshot
+ .mockReturnValueOnce(previousSnapshot)
+ .mockReturnValue(currentSnapshot);
+ getLocalSkillUsageSummary
+ .mockResolvedValueOnce({ success: true, summary: { totalUseCount: 99 }, refreshing: false })
+ .mockResolvedValueOnce({ success: true, summary: { totalUseCount: 1 }, refreshing: false });
+ getCurrentDataOwnerId.mockReturnValue('owner-b');
+
+ const handler = handlers.get('skillhub:get-usage-summary');
+ const result = await handler?.({}, { name: 'word-doc' });
+
+ expect(ensureReady).toHaveBeenCalledWith('owner-b');
+ expect(getLocalSkillUsageSummary).toHaveBeenNthCalledWith(1, {
+ skillName: 'word-doc',
+ currentSkillContent: null,
+ client: previousClient,
+ });
+ expect(getLocalSkillUsageSummary).toHaveBeenNthCalledWith(2, {
+ skillName: 'word-doc',
+ currentSkillContent: null,
+ client: currentClient,
+ });
+ expect(result).toEqual({ success: true, summary: { totalUseCount: 1 }, refreshing: false });
+ });
+
it('passes readable SKILL.md content and path into diagnosis context', async () => {
readSkillRawFile.mockResolvedValueOnce({ success: true, content: 'skill body' });
getLocalSkillUsageDiagnosisContext.mockResolvedValueOnce({
@@ -465,6 +525,7 @@ describe('registerSkillhubIpc usage handlers', () => {
skillName: 'word-doc',
currentSkillContent: 'skill body',
skillPath: 'C:\\skills\\word-doc\\SKILL.md',
+ client: defaultDbClient,
});
expect(result).toEqual({ success: true, context: { prompt: 'diagnose' } });
});
diff --git a/apps/desktop/src/main/skillhub/__tests__/usageIndexer.test.ts b/apps/desktop/src/main/skillhub/__tests__/usageIndexer.test.ts
index 0c86c6039d..efb9ac577a 100644
--- a/apps/desktop/src/main/skillhub/__tests__/usageIndexer.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/usageIndexer.test.ts
@@ -3,7 +3,18 @@ import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { DbClient } from '../../localDb/client/DbClient';
+
+const currentDbClientMocks = vi.hoisted(() => ({
+ getDbClient: vi.fn(),
+ getCurrentDbClientSnapshot: vi.fn(),
+}));
+
+vi.mock('../../localDb/client/current', () => ({
+ getDbClient: currentDbClientMocks.getDbClient,
+ getCurrentDbClientSnapshot: currentDbClientMocks.getCurrentDbClientSnapshot,
+}));
import { discoverTranscriptSources, refreshLocalSkillUsageAnalytics } from '../usageIndexer';
@@ -143,17 +154,141 @@ function insertUsageExposure(
'codex_skill_file_read', NULL, ?,
0, 0, 0, 0, 0
)
- `).run(`${analyzerVersion}:stale`, analyzerVersion, rawFilePath, options.seenAt ?? nowMs - dayMs);
+ `).run(`${analyzerVersion}:${rawFilePath}`, analyzerVersion, rawFilePath, options.seenAt ?? nowMs - dayMs);
}
describe('discoverTranscriptSources', () => {
afterEach(async () => {
+ currentDbClientMocks.getDbClient.mockReset();
+ currentDbClientMocks.getCurrentDbClientSnapshot.mockReset();
await Promise.all(
tempRoots.map((dir) => rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })),
);
tempRoots = [];
});
+ it('coalesces refreshes per database without reusing another owner refresh', async () => {
+ const root = await makeTempRoot();
+ const firstDb = createUsageDb();
+ const secondDb = createUsageDb();
+ const options = {
+ homeDir: path.join(root, 'home'),
+ appDataDir: path.join(root, 'app-data'),
+ userDataDir: path.join(root, 'user-data'),
+ env: {},
+ platform: 'win32' as const,
+ nowMs,
+ };
+
+ try {
+ const firstRefresh = refreshLocalSkillUsageAnalytics(firstDb, options);
+ const coalescedRefresh = refreshLocalSkillUsageAnalytics(firstDb, options);
+ const secondRefresh = refreshLocalSkillUsageAnalytics(secondDb, options);
+
+ expect(coalescedRefresh).toBe(firstRefresh);
+ expect(secondRefresh).not.toBe(firstRefresh);
+ await Promise.all([firstRefresh, secondRefresh]);
+ } finally {
+ firstDb.close();
+ secondDb.close();
+ }
+ });
+
+ it('uses the current DbClient and batches freshness lookup for multiple transcripts', async () => {
+ const root = await makeTempRoot();
+ const db = createUsageDb();
+ const firstPath = path.join(root, 'first.jsonl');
+ const secondPath = path.join(root, 'second.jsonl');
+ insertUsageExposure(db, firstPath, { sourceMtimeMs: 100 });
+ insertUsageExposure(db, secondPath, { sourceMtimeMs: 200 });
+ db.prepare(
+ "INSERT INTO migration_meta (key, value) VALUES ('skill_usage_analyzer_version', '6')",
+ ).run();
+
+ const query = vi.fn(async (sql: string, params: unknown[] = []) => (
+ db.prepare(sql).all(...params) as unknown[]
+ ));
+ const client = {
+ query,
+ queryOne: vi.fn(async (sql: string, params: unknown[] = []) => db.prepare(sql).get(...params)),
+ exec: vi.fn(async (sql: string, params: unknown[] = []) => db.prepare(sql).run(...params)),
+ tx: vi.fn(async () => undefined),
+ } as unknown as DbClient;
+ currentDbClientMocks.getDbClient.mockReturnValue(client);
+ currentDbClientMocks.getCurrentDbClientSnapshot.mockReturnValue({
+ client,
+ userId: 'owner-a',
+ clientEpoch: 1,
+ });
+
+ try {
+ await refreshLocalSkillUsageAnalytics(undefined, {
+ homeDir: path.join(root, 'home'),
+ appDataDir: path.join(root, 'app-data'),
+ userDataDir: path.join(root, 'user-data'),
+ env: {},
+ platform: 'win32',
+ nowMs,
+ statSource: async (file) => {
+ if (file === firstPath) return { mtimeMs: 100, sizeBytes: 1 };
+ if (file === secondPath) return { mtimeMs: 200, sizeBytes: 1 };
+ return null;
+ },
+ });
+
+ const freshnessCalls = query.mock.calls.filter(([sql]) => (
+ typeof sql === 'string' && sql.includes('FROM json_each(?) wanted')
+ ));
+ expect(currentDbClientMocks.getDbClient).toHaveBeenCalledTimes(1);
+ expect(freshnessCalls).toHaveLength(1);
+ expect(JSON.parse(String(freshnessCalls[0][1]?.[0]))).toEqual([secondPath, firstPath]);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('cancels an in-flight client refresh when the database owner changes', async () => {
+ const root = await makeTempRoot();
+ const db = createUsageDb();
+ const file = path.join(root, 'switch.jsonl');
+ await writeJsonl(file);
+ insertUsageExposure(db, file, { sourceMtimeMs: 100 });
+ let switched = false;
+ const query = vi.fn(async (sql: string, params: unknown[] = []) => (
+ db.prepare(sql).all(...params) as unknown[]
+ ));
+ const client = {
+ query,
+ queryOne: vi.fn(async (sql: string, params: unknown[] = []) => db.prepare(sql).get(...params)),
+ exec: vi.fn(async (sql: string, params: unknown[] = []) => db.prepare(sql).run(...params)),
+ tx: vi.fn(async () => undefined),
+ } as unknown as DbClient;
+ currentDbClientMocks.getDbClient.mockReturnValue(client);
+ currentDbClientMocks.getCurrentDbClientSnapshot.mockImplementation(() => switched
+ ? { client, userId: 'owner-b', clientEpoch: 2 }
+ : { client, userId: 'owner-a', clientEpoch: 1 });
+
+ try {
+ await refreshLocalSkillUsageAnalytics(undefined, {
+ homeDir: path.join(root, 'home'),
+ appDataDir: path.join(root, 'app-data'),
+ userDataDir: path.join(root, 'user-data'),
+ env: {},
+ platform: 'win32',
+ nowMs,
+ statSource: async () => ({ mtimeMs: 101, sizeBytes: 1 }),
+ readTranscriptFile: async () => {
+ switched = true;
+ return '{}\n';
+ },
+ });
+
+ expect(client.tx).not.toHaveBeenCalled();
+ } finally {
+ db.close();
+ }
+ });
+
it('discovers default, XDMaker and configured transcript homes without dropping subagent files', async () => {
const root = await makeTempRoot();
const homeDir = path.join(root, 'home');
diff --git a/apps/desktop/src/main/skillhub/__tests__/usageStore.test.ts b/apps/desktop/src/main/skillhub/__tests__/usageStore.test.ts
index b2cb4c3cee..72c7fdfcfb 100644
--- a/apps/desktop/src/main/skillhub/__tests__/usageStore.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/usageStore.test.ts
@@ -1,8 +1,10 @@
import Database from 'better-sqlite3';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import type { DbClient } from '../../localDb/client/DbClient';
import * as usageStore from '../usageStore';
import {
deleteSkillUsageRecordsBefore,
+ getSkillUsageDiagnosisContextFromDb,
getSkillUsageSummaryFromDb,
markSkillUsageSourceFailed,
persistSkillUsageAnalysis,
@@ -47,10 +49,23 @@ function createDb(): Database.Database {
command_failure_count INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (raw_file_path) REFERENCES skill_usage_sources(raw_file_path) ON DELETE CASCADE
);
+ CREATE INDEX idx_skill_usage_exposures_skill_recent
+ ON skill_usage_exposures (skill_name, analyzer_version, seen_at);
+ CREATE INDEX idx_skill_usage_exposures_skill_recent_any_version
+ ON skill_usage_exposures (skill_name, seen_at);
+ CREATE INDEX idx_skill_usage_exposures_analyzer_recent_source
+ ON skill_usage_exposures (analyzer_version, seen_at, raw_file_path);
`);
return db;
}
+function createQueryClient(db: Database.Database): DbClient {
+ return {
+ query: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).all(...params) as T[],
+ queryOne: async <T>(sql: string, params: unknown[] = []) => db.prepare(sql).get(...params) as T | undefined,
+ } as DbClient;
+}
+
type DiagnosisContextGetter = (
db: Database.Database,
params: {
@@ -165,6 +180,134 @@ const fixtureNowMs = 10_000;
const dayMs = 24 * 60 * 60 * 1000;
describe('skill usage store', () => {
+ it.each([
+ { analyzerVersion: '6', suffix: 'AND analyzer_version = ?' },
+ { analyzerVersion: null, suffix: '' },
+ ])('uses the recent-skill index when analyzerVersion is $analyzerVersion', ({ analyzerVersion, suffix }) => {
+ const db = createDb();
+ try {
+ const plan = db.prepare(`
+ EXPLAIN QUERY PLAN
+ SELECT COUNT(*)
+ FROM skill_usage_exposures
+ WHERE skill_name = ?
+ ${suffix}
+ AND seen_at >= ?
+ `).all(...(analyzerVersion === null
+ ? ['word-doc', 0]
+ : ['word-doc', analyzerVersion, 0])) as Array<{ detail: string }>;
+
+ expect(plan.map((row) => row.detail).join('\n')).toContain(
+ analyzerVersion === null
+ ? 'idx_skill_usage_exposures_skill_recent_any_version'
+ : 'idx_skill_usage_exposures_skill_recent',
+ );
+ expect(plan.some((row) => /^SCAN skill_usage_exposures\b/.test(row.detail))).toBe(false);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('uses the analyzer and recent-time prefix for transcript source discovery', () => {
+ const db = createDb();
+ try {
+ const plan = db.prepare(`
+ EXPLAIN QUERY PLAN
+ SELECT raw_file_path
+ FROM skill_usage_exposures
+ WHERE analyzer_version = ?
+ AND seen_at >= ?
+ GROUP BY raw_file_path
+ ORDER BY MAX(seen_at) DESC
+ `).all('6', 0) as Array<{ detail: string }>;
+
+ expect(plan.map((row) => row.detail).join('\n')).toContain(
+ 'idx_skill_usage_exposures_analyzer_recent_source',
+ );
+ expect(plan.some((row) => /^SCAN skill_usage_exposures\b/.test(row.detail))).toBe(false);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('returns the same summary through the asynchronous DbClient path', async () => {
+ const db = createDb();
+ try {
+ persistExposure(db, {
+ id: 'async-summary',
+ rawFilePath: 'async-summary.jsonl',
+ rawLineNo: 1,
+ sessionId: 'codex-async-summary',
+ sdkSessionId: 'async-summary',
+ skillDocumentHash: 'doc-current',
+ seenAt: fixtureNowMs,
+ analyzerVersion: '6',
+ toolCallCount: 3,
+ });
+ const params = {
+ skillName: 'word-doc',
+ currentDocumentHash: 'doc-current',
+ currentDocumentContent: '# Word doc',
+ analyzerVersion: '6',
+ nowMs: fixtureNowMs,
+ };
+
+ const syncSummary = getSkillUsageSummaryFromDb(db, params);
+ const asyncSummary = await usageStore.getSkillUsageSummaryFromClient(createQueryClient(db), params);
+
+ expect(asyncSummary).toEqual(syncSummary);
+ } finally {
+ db.close();
+ }
+ });
+
+ it('reads diagnosis summary and evidence from one asynchronous snapshot query', async () => {
+ const db = createDb();
+ try {
+ persistExposure(db, {
+ id: 'async-diagnosis-read',
+ rawFilePath: 'async-diagnosis-read.jsonl',
+ rawLineNo: 1,
+ sessionId: 'codex-async-diagnosis-read',
+ sdkSessionId: 'async-diagnosis-read',
+ skillDocumentHash: 'doc-current',
+ seenAt: fixtureNowMs,
+ analyzerVersion: '6',
+ });
+ persistExposure(db, {
+ id: 'async-diagnosis-failure',
+ rawFilePath: 'async-diagnosis-failure.jsonl',
+ rawLineNo: 2,
+ sessionId: 'codex-async-diagnosis-failure',
+ sdkSessionId: 'async-diagnosis-failure',
+ skillDocumentHash: 'doc-current',
+ seenAt: fixtureNowMs - 1,
+ analyzerVersion: '6',
+ source: 'codex_skill_tool',
+ toolErrorCount: 2,
+ });
+ const params = {
+ skillName: 'word-doc',
+ currentDocumentHash: 'doc-current',
+ currentDocumentContent: '# Word doc',
+ analyzerVersion: '6',
+ skillPath: '/skills/word-doc/SKILL.md',
+ nowMs: fixtureNowMs,
+ };
+ const client = createQueryClient(db);
+ const querySpy = vi.spyOn(client, 'query');
+
+ const syncContext = getSkillUsageDiagnosisContextFromDb(db, params);
+ const asyncContext = await usageStore.getSkillUsageDiagnosisContextFromClient(client, params);
+
+ expect(asyncContext).toEqual(syncContext);
+ expect(querySpy).toHaveBeenCalledTimes(1);
+ expect(String(querySpy.mock.calls[0]?.[0])).toContain('MATERIALIZED');
+ } finally {
+ db.close();
+ }
+ });
+
it('persists document and exposure hashes without token metrics', () => {
const db = createDb();
try {
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 9721c3f4dc..0836419af6 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -4,7 +4,11 @@ import type { Maker } from '@cindy/maker-core';
import { BrowserWindow, dialog, ipcMain } from 'electron';
import { getCurrentDataOwnerId } from '../authManager';
import { isAppSessionBoundaryPending } from '../appSessionState';
-import { ensureReady as ensureLocalDbReady, getRawDb } from '../localDb';
+import { ensureReady as ensureLocalDbReady } from '../localDb';
+import {
+ getCurrentDbClientSnapshot,
+ type CurrentDbClientSnapshot,
+} from '../localDb/client/current.js';
import { createLogger } from '../logger';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
@@ -241,8 +245,28 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
onProgress: broadcastPublishProgress,
});
let usageRefreshBroadcastPromise: Promise<void> | null = null;
- const scheduleUsageAnalyticsRefresh = (db: ReturnType<typeof getRawDb>) => {
- const promise = requestLocalSkillUsageAnalyticsRefresh(db);
+ const captureUsageDbSnapshot = (): CurrentDbClientSnapshot => {
+ if (isAppSessionBoundaryPending()) {
+ throw new Error('localDb not ready: app session is switching');
+ }
+ const snapshot = getCurrentDbClientSnapshot();
+ if (!snapshot) throw new Error('DbClient not ready');
+ return snapshot;
+ };
+ const assertUsageDbSnapshotCurrent = (snapshot: CurrentDbClientSnapshot): void => {
+ const current = getCurrentDbClientSnapshot();
+ if (
+ isAppSessionBoundaryPending()
+ || !current
+ || current.client !== snapshot.client
+ || current.clientEpoch !== snapshot.clientEpoch
+ || current.userId !== snapshot.userId
+ ) {
+ throw new Error('localDb not ready: app session switched during Skill usage query');
+ }
+ };
+ const scheduleUsageAnalyticsRefresh = (snapshot: CurrentDbClientSnapshot) => {
+ const promise = requestLocalSkillUsageAnalyticsRefresh(snapshot.client);
if (!promise || usageRefreshBroadcastPromise === promise) return;
usageRefreshBroadcastPromise = promise;
void promise
@@ -250,7 +274,15 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
log.warn('[skillhub:usage-refresh] failed:', err instanceof Error ? err.message : String(err));
})
.finally(() => {
- broadcastUsageAnalyticsRefreshed();
+ const current = getCurrentDbClientSnapshot();
+ if (
+ !isAppSessionBoundaryPending()
+ && current?.client === snapshot.client
+ && current.clientEpoch === snapshot.clientEpoch
+ && current.userId === snapshot.userId
+ ) {
+ broadcastUsageAnalyticsRefreshed();
+ }
if (usageRefreshBroadcastPromise === promise) usageRefreshBroadcastPromise = null;
});
};
@@ -655,12 +687,15 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
if (raw.success) currentSkillContent = raw.content ?? null;
}
const readSummary = async () => {
- if (isAppSessionBoundaryPending()) {
- throw new Error('localDb not ready: app session is switching');
- }
- const db = getRawDb();
- scheduleUsageAnalyticsRefresh(db);
- return await getLocalSkillUsageSummary({ skillName: name, currentSkillContent, db });
+ const snapshot = captureUsageDbSnapshot();
+ scheduleUsageAnalyticsRefresh(snapshot);
+ const result = await getLocalSkillUsageSummary({
+ skillName: name,
+ currentSkillContent,
+ client: snapshot.client,
+ });
+ assertUsageDbSnapshotCurrent(snapshot);
+ return result;
};
try {
return await readSummary();
@@ -688,24 +723,24 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
const raw = await readSkillRawFile({ filePath: mdPath });
if (raw.success) currentSkillContent = raw.content ?? null;
}
- try {
- if (isAppSessionBoundaryPending()) {
- return { success: false, error: 'localDb not ready: app session is switching' };
- }
- return await getLocalSkillUsageDiagnosisContext({
+ const readDiagnosisContext = async () => {
+ const snapshot = captureUsageDbSnapshot();
+ const result = await getLocalSkillUsageDiagnosisContext({
skillName: name,
currentSkillContent,
skillPath: mdPath ?? null,
+ client: snapshot.client,
});
+ assertUsageDbSnapshotCurrent(snapshot);
+ return result;
+ };
+ try {
+ return await readDiagnosisContext();
} catch (err) {
if (!isLocalDbNotReady(err)) throw err;
const ready = await ensureSkillUsageLocalDbReady();
if (!ready.success) return ready;
- return await getLocalSkillUsageDiagnosisContext({
- skillName: name,
- currentSkillContent,
- skillPath: mdPath ?? null,
- });
+ return await readDiagnosisContext();
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
diff --git a/apps/desktop/src/main/skillhub/usageIndexer.ts b/apps/desktop/src/main/skillhub/usageIndexer.ts
index ac1a64196c..eb7f15a858 100644
--- a/apps/desktop/src/main/skillhub/usageIndexer.ts
+++ b/apps/desktop/src/main/skillhub/usageIndexer.ts
@@ -6,16 +6,24 @@ import type Database from 'better-sqlite3';
import { brandUserDataDirName } from '@cindy/maker-shared/brand-identity';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
-import { getRawDb } from '../localDb';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { getCurrentDbClientSnapshot, getDbClient, type CurrentDbClientSnapshot } from '../localDb/client/current.js';
import { analyzeSkillUsageTranscript, hashSkillContent, type SkillUsageAgentKind } from './usageAnalyzer';
import {
deleteSkillUsageRecordsBefore,
+ deleteSkillUsageRecordsBeforeWithClient,
+ getSkillUsageDiagnosisContextFromClient,
getSkillUsageDiagnosisContextFromDb,
+ getSkillUsageSummaryFromClient,
getSkillUsageSummaryFromDb,
listSkillUsageSourcesWithRecentExposures,
+ listSkillUsageSourcesWithRecentExposuresFromClient,
markSkillUsageSourceFailed,
+ markSkillUsageSourceFailedWithClient,
persistSkillUsageAnalysis,
+ persistSkillUsageAnalysisWithClient,
+ promoteSkillUsageAnalyzerVersionWithClient,
type SkillUsageDiagnosisContext,
type SkillUsageRecentSourceRecord,
type SkillUsageSummary,
@@ -76,6 +84,8 @@ interface CachedSourceStat {
status: string;
}
+type SkillUsageDatabase = Database.Database | DbClient;
+
export interface SkillUsageSummaryResult {
success: true;
summary: SkillUsageSummary;
@@ -95,28 +105,40 @@ const ANALYZER_VERSION_META_KEY = 'skill_usage_analyzer_version';
const MIN_BACKGROUND_REFRESH_INTERVAL_MS = 15_000;
// 解析规则变化时递增。新版完整构建完成前,UI 继续读取旧 active 版本。
const ANALYZER_VERSION = '6';
-let refreshPromise: Promise<void> | null = null;
-let lastBackgroundRefreshFinishedAt = 0;
+interface SkillUsageRefreshState {
+ promise: Promise<void> | null;
+ lastBackgroundRefreshFinishedAt: number;
+}
+const refreshStateByDatabase = new WeakMap<object, SkillUsageRefreshState>();
+let activeRefreshCount = 0;
export async function getLocalSkillUsageSummary(params: {
skillName: string;
currentSkillContent?: string | null;
db?: Database.Database;
+ client?: DbClient;
}): Promise<SkillUsageSummaryResult> {
const currentDocumentHash = params.currentSkillContent
? hashSkillContent(params.currentSkillContent)
: null;
- const db = params.db ?? getRawDb();
- const analyzerVersion = readActiveAnalyzerVersion(db);
+ const database = params.db ?? params.client ?? getDbClient();
+ const analyzerVersion = await readActiveAnalyzerVersion(database);
return {
success: true,
- summary: getSkillUsageSummaryFromDb(db, {
- skillName: params.skillName,
- currentDocumentHash,
- currentDocumentContent: params.currentSkillContent ?? null,
- analyzerVersion,
- }),
- refreshing: isLocalSkillUsageAnalyticsRefreshing(),
+ summary: isRawDatabase(database)
+ ? getSkillUsageSummaryFromDb(database, {
+ skillName: params.skillName,
+ currentDocumentHash,
+ currentDocumentContent: params.currentSkillContent ?? null,
+ analyzerVersion,
+ })
+ : await getSkillUsageSummaryFromClient(database, {
+ skillName: params.skillName,
+ currentDocumentHash,
+ currentDocumentContent: params.currentSkillContent ?? null,
+ analyzerVersion,
+ }),
+ refreshing: isLocalSkillUsageAnalyticsRefreshing(database),
};
}
@@ -125,81 +147,118 @@ export async function getLocalSkillUsageDiagnosisContext(params: {
currentSkillContent?: string | null;
skillPath?: string | null;
db?: Database.Database;
+ client?: DbClient;
}): Promise<SkillUsageDiagnosisContextResult> {
const currentDocumentHash = params.currentSkillContent
? hashSkillContent(params.currentSkillContent)
: null;
- const db = params.db ?? getRawDb();
- await refreshLocalSkillUsageAnalytics(db);
- const analyzerVersion = readActiveAnalyzerVersion(db);
+ const database = params.db ?? params.client ?? getDbClient();
+ await refreshLocalSkillUsageAnalytics(database);
+ const analyzerVersion = await readActiveAnalyzerVersion(database);
return {
success: true,
- context: getSkillUsageDiagnosisContextFromDb(db, {
- skillName: params.skillName,
- currentDocumentHash,
- currentDocumentContent: params.currentSkillContent ?? null,
- analyzerVersion,
- skillPath: params.skillPath ?? null,
- }),
+ context: isRawDatabase(database)
+ ? getSkillUsageDiagnosisContextFromDb(database, {
+ skillName: params.skillName,
+ currentDocumentHash,
+ currentDocumentContent: params.currentSkillContent ?? null,
+ analyzerVersion,
+ skillPath: params.skillPath ?? null,
+ })
+ : await getSkillUsageDiagnosisContextFromClient(database, {
+ skillName: params.skillName,
+ currentDocumentHash,
+ currentDocumentContent: params.currentSkillContent ?? null,
+ analyzerVersion,
+ skillPath: params.skillPath ?? null,
+ }),
};
}
-export function isLocalSkillUsageAnalyticsRefreshing(): boolean {
- return refreshPromise !== null;
+export function isLocalSkillUsageAnalyticsRefreshing(database?: SkillUsageDatabase): boolean {
+ return database
+ ? getRefreshState(database).promise !== null
+ : activeRefreshCount > 0;
}
-export function requestLocalSkillUsageAnalyticsRefresh(db: Database.Database): Promise<void> | null {
- if (refreshPromise) return refreshPromise;
+export function requestLocalSkillUsageAnalyticsRefresh(
+ database: SkillUsageDatabase = getDbClient(),
+): Promise<void> | null {
+ const state = getRefreshState(database);
+ if (state.promise) return state.promise;
const now = Date.now();
- if (now - lastBackgroundRefreshFinishedAt < MIN_BACKGROUND_REFRESH_INTERVAL_MS) return null;
- return startLocalSkillUsageAnalyticsRefresh(db);
+ if (now - state.lastBackgroundRefreshFinishedAt < MIN_BACKGROUND_REFRESH_INTERVAL_MS) return null;
+ return startLocalSkillUsageAnalyticsRefresh(database);
}
export function refreshLocalSkillUsageAnalytics(
- db: Database.Database,
+ database: SkillUsageDatabase = getDbClient(),
options: SkillUsageRefreshOptions = {},
): Promise<void> {
- return startLocalSkillUsageAnalyticsRefresh(db, options);
+ return startLocalSkillUsageAnalyticsRefresh(database, options);
}
function startLocalSkillUsageAnalyticsRefresh(
- db: Database.Database,
+ database: SkillUsageDatabase,
options: SkillUsageRefreshOptions = {},
): Promise<void> {
- if (!refreshPromise) {
- refreshPromise = runLocalSkillUsageAnalyticsRefresh(db, options).finally(() => {
- lastBackgroundRefreshFinishedAt = Date.now();
- refreshPromise = null;
+ const state = getRefreshState(database);
+ if (!state.promise) {
+ activeRefreshCount += 1;
+ state.promise = runLocalSkillUsageAnalyticsRefresh(database, options).finally(() => {
+ state.lastBackgroundRefreshFinishedAt = Date.now();
+ state.promise = null;
+ activeRefreshCount -= 1;
});
}
- return refreshPromise;
+ return state.promise;
+}
+
+function getRefreshState(database: SkillUsageDatabase): SkillUsageRefreshState {
+ const existing = refreshStateByDatabase.get(database);
+ if (existing) return existing;
+ const state: SkillUsageRefreshState = {
+ promise: null,
+ lastBackgroundRefreshFinishedAt: 0,
+ };
+ refreshStateByDatabase.set(database, state);
+ return state;
}
async function runLocalSkillUsageAnalyticsRefresh(
- db: Database.Database,
+ database: SkillUsageDatabase,
options: SkillUsageRefreshOptions = {},
): Promise<void> {
- const activeBeforeRefresh = readActiveAnalyzerVersion(db);
- ensureActiveAnalyzerVersionMeta(db, activeBeforeRefresh);
+ // In-process DbClient resolves getRawDb() dynamically. Keep the refresh tied
+ // to the owner/epoch it started with so an account switch cannot redirect a
+ // later write, cleanup, or promotion into the next owner's database.
+ const snapshot = captureRefreshSnapshot(database);
+ if (!isRefreshDatabaseStable(snapshot)) return;
+ const activeBeforeRefresh = await readActiveAnalyzerVersion(database);
+ if (!isRefreshDatabaseStable(snapshot)) return;
+ await ensureActiveAnalyzerVersionMeta(database, activeBeforeRefresh);
const nowMs = options.nowMs ?? Date.now();
const recentSince = recentWindowStartMs(nowMs);
const platform = options.platform ?? process.platform;
const discovery = await discoverTranscriptSourcesForRefresh({ ...options, nowMs });
const cachedRecent = await statCachedRecentSources(
- db,
+ database,
activeBeforeRefresh,
recentSince,
options.statSource ?? statSource,
);
+ if (!isRefreshDatabaseStable(snapshot)) return;
const readTranscriptFile = options.readTranscriptFile ?? ((file: string) => fs.readFile(file, 'utf-8'));
const sourceBatchSize = Math.max(1, options.maxSourcesPerRefresh ?? MAX_SOURCES_PER_REFRESH);
const sources = mergeTranscriptSources(discovery.sources, cachedRecent.sources, platform);
- const dirtySources = sources.filter((source) => !isCachedSourceFresh(db, source));
+ const cachedSourceStats = await readCachedSourceStats(database, sources.map((source) => source.rawFilePath));
+ const dirtySources = sources.filter((source) => !isCachedSourceFresh(cachedSourceStats, source));
const scannedAt = Date.now();
let failedCount = 0;
for (let start = 0; start < dirtySources.length; start += sourceBatchSize) {
const batch = dirtySources.slice(start, start + sourceBatchSize);
for (const source of batch) {
+ if (!isRefreshDatabaseStable(snapshot)) return;
try {
const text = await readTranscriptFile(source.rawFilePath);
const analysis = analyzeSkillUsageTranscript({
@@ -209,7 +268,8 @@ async function runLocalSkillUsageAnalyticsRefresh(
rawFilePath: source.rawFilePath,
lines: text.split(/\r?\n/),
});
- persistSkillUsageAnalysis(db, {
+ if (!isRefreshDatabaseStable(snapshot)) return;
+ await persistSkillUsageAnalysisInDatabase(database, {
rawFilePath: source.rawFilePath,
analyzerVersion: ANALYZER_VERSION,
agentKind: source.agentKind,
@@ -221,7 +281,8 @@ async function runLocalSkillUsageAnalyticsRefresh(
}, analysis);
} catch (err) {
failedCount += 1;
- markSkillUsageSourceFailed(db, {
+ if (!isRefreshDatabaseStable(snapshot)) return;
+ await markSkillUsageSourceFailedInDatabase(database, {
rawFilePath: source.rawFilePath,
analyzerVersion: ANALYZER_VERSION,
agentKind: source.agentKind,
@@ -236,56 +297,128 @@ async function runLocalSkillUsageAnalyticsRefresh(
}
if (start + sourceBatchSize < dirtySources.length) await yieldToEventLoop();
}
+ if (!isRefreshDatabaseStable(snapshot)) return;
if (!discovery.hadDiscoveryFailure && !cachedRecent.hadStatFailure) {
- deleteSkillUsageRecordsBefore(db, ANALYZER_VERSION, recentSince);
+ await deleteSkillUsageRecordsBeforeInDatabase(database, ANALYZER_VERSION, recentSince);
}
if (!discovery.hadDiscoveryFailure && !cachedRecent.hadStatFailure && failedCount === 0) {
- promoteAnalyzerVersion(db, ANALYZER_VERSION);
+ await promoteAnalyzerVersion(database, ANALYZER_VERSION);
}
}
-function readActiveAnalyzerVersion(db: Database.Database): string {
- const row = db.prepare('SELECT value FROM migration_meta WHERE key = ?').get(ANALYZER_VERSION_META_KEY) as
- | { value: string | null }
- | undefined;
+type RefreshSnapshot = CurrentDbClientSnapshot | null;
+
+function captureRefreshSnapshot(database: SkillUsageDatabase): RefreshSnapshot {
+ if (isRawDatabase(database)) return null;
+ const snapshot = getCurrentDbClientSnapshot();
+ return snapshot?.client === database ? snapshot : null;
+}
+
+function isRefreshDatabaseStable(snapshot: RefreshSnapshot): boolean {
+ if (!snapshot) return true;
+ const current = getCurrentDbClientSnapshot();
+ return current?.client === snapshot.client
+ && current.userId === snapshot.userId
+ && current.clientEpoch === snapshot.clientEpoch;
+}
+
+async function readActiveAnalyzerVersion(database: SkillUsageDatabase): Promise<string> {
+ const row = isRawDatabase(database)
+ ? database.prepare('SELECT value FROM migration_meta WHERE key = ?').get(ANALYZER_VERSION_META_KEY) as
+ | { value: string | null }
+ | undefined
+ : await database.queryOne<{ value: string | null }>(
+ 'SELECT value FROM migration_meta WHERE key = ?', [ANALYZER_VERSION_META_KEY],
+ );
if (row?.value) return row.value;
- const latestPreviousExposure = db.prepare(`
+ const previousSql = `
SELECT analyzer_version AS analyzerVersion
FROM skill_usage_exposures
WHERE analyzer_version <> ?
ORDER BY seen_at DESC
LIMIT 1
- `).get(ANALYZER_VERSION) as { analyzerVersion: string | null } | undefined;
+ `;
+ const latestPreviousExposure = isRawDatabase(database)
+ ? database.prepare(previousSql).get(ANALYZER_VERSION) as { analyzerVersion: string | null } | undefined
+ : await database.queryOne<{ analyzerVersion: string | null }>(previousSql, [ANALYZER_VERSION]);
if (latestPreviousExposure?.analyzerVersion) return latestPreviousExposure.analyzerVersion;
- const latestExposure = db.prepare(`
+ const latestSql = `
SELECT analyzer_version AS analyzerVersion
FROM skill_usage_exposures
ORDER BY seen_at DESC
LIMIT 1
- `).get() as { analyzerVersion: string | null } | undefined;
+ `;
+ const latestExposure = isRawDatabase(database)
+ ? database.prepare(latestSql).get() as { analyzerVersion: string | null } | undefined
+ : await database.queryOne<{ analyzerVersion: string | null }>(latestSql);
return latestExposure?.analyzerVersion || ANALYZER_VERSION;
}
-function ensureActiveAnalyzerVersionMeta(db: Database.Database, analyzerVersion: string): void {
- db.prepare(`
+async function ensureActiveAnalyzerVersionMeta(
+ database: SkillUsageDatabase,
+ analyzerVersion: string,
+): Promise<void> {
+ const sql = `
INSERT INTO migration_meta (key, value)
VALUES (?, ?)
ON CONFLICT(key) DO NOTHING
- `).run(ANALYZER_VERSION_META_KEY, analyzerVersion);
+ `;
+ if (isRawDatabase(database)) {
+ database.prepare(sql).run(ANALYZER_VERSION_META_KEY, analyzerVersion);
+ } else {
+ await database.exec(sql, [ANALYZER_VERSION_META_KEY, analyzerVersion]);
+ }
}
-function promoteAnalyzerVersion(db: Database.Database, analyzerVersion: string): void {
- const tx = db.transaction(() => {
- db.prepare(`
+async function promoteAnalyzerVersion(
+ database: SkillUsageDatabase,
+ analyzerVersion: string,
+): Promise<void> {
+ if (!isRawDatabase(database)) {
+ await promoteSkillUsageAnalyzerVersionWithClient(database, analyzerVersion);
+ return;
+ }
+ const tx = database.transaction(() => {
+ database.prepare(`
INSERT INTO migration_meta (key, value)
VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`).run(ANALYZER_VERSION_META_KEY, analyzerVersion);
- db.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);
+ database.prepare('DELETE FROM skill_usage_exposures WHERE analyzer_version <> ?').run(analyzerVersion);
});
tx();
}
+function isRawDatabase(database: SkillUsageDatabase): database is Database.Database {
+ return 'prepare' in database && typeof database.prepare === 'function';
+}
+
+async function persistSkillUsageAnalysisInDatabase(
+ database: SkillUsageDatabase,
+ source: Parameters<typeof persistSkillUsageAnalysis>[1],
+ analysis: Parameters<typeof persistSkillUsageAnalysis>[2],
+): Promise<void> {
+ if (isRawDatabase(database)) persistSkillUsageAnalysis(database, source, analysis);
+ else await persistSkillUsageAnalysisWithClient(database, source, analysis);
+}
+
+async function markSkillUsageSourceFailedInDatabase(
+ database: SkillUsageDatabase,
+ source: Parameters<typeof markSkillUsageSourceFailed>[1],
+): Promise<void> {
+ if (isRawDatabase(database)) markSkillUsageSourceFailed(database, source);
+ else await markSkillUsageSourceFailedWithClient(database, source);
+}
+
+async function deleteSkillUsageRecordsBeforeInDatabase(
+ database: SkillUsageDatabase,
+ analyzerVersion: string,
+ recentSince: number,
+): Promise<void> {
+ if (isRawDatabase(database)) deleteSkillUsageRecordsBefore(database, analyzerVersion, recentSince);
+ else await deleteSkillUsageRecordsBeforeWithClient(database, analyzerVersion, recentSince);
+}
+
export async function discoverTranscriptSources(options: TranscriptDiscoveryOptions = {}): Promise<TranscriptSource[]> {
const result = await discoverTranscriptSourcesForRefresh(options);
return result.sources;
@@ -497,12 +630,14 @@ function isMissingCollectionRoot(root: string, dir: string, err: unknown): boole
}
async function statCachedRecentSources(
- db: Database.Database,
+ database: SkillUsageDatabase,
analyzerVersion: string,
recentSince: number,
statFile: (file: string) => Promise<SourceStat | null>,
): Promise<{ sources: TranscriptSource[]; hadStatFailure: boolean }> {
- const cachedSources = listSkillUsageSourcesWithRecentExposures(db, analyzerVersion, recentSince);
+ const cachedSources = isRawDatabase(database)
+ ? listSkillUsageSourcesWithRecentExposures(database, analyzerVersion, recentSince)
+ : await listSkillUsageSourcesWithRecentExposuresFromClient(database, analyzerVersion, recentSince);
if (cachedSources.length === 0) return { sources: [], hadStatFailure: false };
const result = await statTranscriptSourcesWithoutRecentFilter(cachedSources, statFile);
return result;
@@ -583,8 +718,11 @@ function compareTranscriptSourcesByRecency(a: TranscriptSource, b: TranscriptSou
return b.mtimeMs - a.mtimeMs || a.rawFilePath.localeCompare(b.rawFilePath);
}
-function isCachedSourceFresh(db: Database.Database, source: TranscriptSource): boolean {
- const cached = readCachedSourceStat(db, source.rawFilePath);
+function isCachedSourceFresh(
+ cachedSourceStats: ReadonlyMap<string, CachedSourceStat>,
+ source: TranscriptSource,
+): boolean {
+ const cached = cachedSourceStats.get(source.rawFilePath);
return (
cached?.status === 'ok' &&
cached.analyzerVersion === ANALYZER_VERSION &&
@@ -603,13 +741,27 @@ async function statSource(file: string): Promise<SourceStat | null> {
}
}
-function readCachedSourceStat(db: Database.Database, rawFilePath: string): CachedSourceStat | null {
- const row = db.prepare(`
- SELECT analyzer_version AS analyzerVersion, mtime_ms AS mtimeMs, size_bytes AS sizeBytes, status
- FROM skill_usage_sources
- WHERE raw_file_path = ?
- `).get(rawFilePath) as CachedSourceStat | undefined;
- return row ?? null;
+async function readCachedSourceStats(
+ database: SkillUsageDatabase,
+ rawFilePaths: string[],
+): Promise<Map<string, CachedSourceStat>> {
+ if (rawFilePaths.length === 0) return new Map();
+ const sql = `
+ SELECT
+ s.raw_file_path AS rawFilePath,
+ s.analyzer_version AS analyzerVersion,
+ s.mtime_ms AS mtimeMs,
+ s.size_bytes AS sizeBytes,
+ s.status
+ FROM json_each(?) wanted
+ JOIN skill_usage_sources s
+ ON s.raw_file_path = CAST(wanted.value AS TEXT)
+ `;
+ const params = [JSON.stringify(rawFilePaths)];
+ const rows = isRawDatabase(database)
+ ? database.prepare(sql).all(...params) as Array<CachedSourceStat & { rawFilePath: string }>
+ : await database.query<CachedSourceStat & { rawFilePath: string }>(sql, params);
+ return new Map(rows.map((row) => [row.rawFilePath, row]));
}
function yieldToEventLoop(): Promise<void> {
diff --git a/apps/desktop/src/main/skillhub/usageStore.ts b/apps/desktop/src/main/skillhub/usageStore.ts
index 7c6acb98ba..6e3b819459 100644
--- a/apps/desktop/src/main/skillhub/usageStore.ts
+++ b/apps/desktop/src/main/skillhub/usageStore.ts
@@ -1,4 +1,5 @@
import type Database from 'better-sqlite3';
+import type { DbClient } from '../localDb/client/DbClient.js';
import {
MIN_VERSION_COMPARISON_USE_COUNT,
@@ -235,6 +236,38 @@ export function persistSkillUsageAnalysis(
tx();
}
+export async function persistSkillUsageAnalysisWithClient(
+ client: DbClient,
+ source: SkillUsageSourceRecord,
+ analysis: SkillUsageAnalysisResult,
+): Promise<void> {
+ await client.tx('skillUsage.applyMutation', {
+ kind: 'persist',
+ source,
+ exposures: analysis.exposures.map((exposure) => ({
+ id: exposure.id,
+ rawFilePath: exposure.rawFilePath,
+ rawLineNo: exposure.rawLineNo,
+ sessionId: exposure.sessionId,
+ sdkSessionId: exposure.sdkSessionId,
+ agentKind: exposure.agentKind,
+ skillName: exposure.skillName,
+ skillPath: exposure.skillPath,
+ skillDocumentHash: exposure.skillDocumentHash,
+ exposureContentHash: exposure.exposureContentHash,
+ documentHashSource: exposure.documentHashSource,
+ source: exposure.source,
+ toolUseId: exposure.toolUseId,
+ seenAt: exposure.seenAt,
+ toolCallCount: exposure.observation.toolCallCount,
+ repeatedToolCallCount: exposure.observation.repeatedToolCallCount,
+ toolErrorCount: exposure.observation.toolErrorCount,
+ commandCallCount: exposure.observation.commandCallCount,
+ commandFailureCount: exposure.observation.commandFailureCount,
+ })),
+ });
+}
+
export function markSkillUsageSourceFailed(
db: Database.Database,
source: SkillUsageFailedSourceRecord,
@@ -266,6 +299,32 @@ export function markSkillUsageSourceFailed(
tx();
}
+export async function markSkillUsageSourceFailedWithClient(
+ client: DbClient,
+ source: SkillUsageFailedSourceRecord,
+): Promise<void> {
+ await client.exec(`
+ INSERT INTO skill_usage_sources (
+ raw_file_path, analyzer_version, agent_kind, session_id, sdk_session_id,
+ mtime_ms, size_bytes, last_scanned_at, status, error
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'failed', ?)
+ ON CONFLICT(raw_file_path) DO UPDATE SET
+ analyzer_version = excluded.analyzer_version,
+ agent_kind = excluded.agent_kind,
+ session_id = excluded.session_id,
+ sdk_session_id = excluded.sdk_session_id,
+ mtime_ms = excluded.mtime_ms,
+ size_bytes = excluded.size_bytes,
+ last_scanned_at = excluded.last_scanned_at,
+ status = 'failed',
+ error = excluded.error
+ `, [
+ source.rawFilePath, source.analyzerVersion, source.agentKind, source.sessionId,
+ source.sdkSessionId, source.mtimeMs, source.sizeBytes, source.scannedAt, source.error,
+ ]);
+}
+
export function listSkillUsageSourcesWithRecentExposures(
db: Database.Database,
analyzerVersion: string,
@@ -284,15 +343,27 @@ export function listSkillUsageSourcesWithRecentExposures(
ORDER BY MAX(e.seen_at) DESC
`).all(analyzerVersion, recentSince) as Array<Record<string, unknown>>;
- return rows.map((row) => {
- const agentKind: SkillUsageAgentKind = stringValue(row.agentKind) === 'claude-code' ? 'claude-code' : stringValue(row.agentKind) === 'pi' ? 'pi' : 'codex';
- return {
- rawFilePath: stringValue(row.rawFilePath),
- agentKind,
- sessionId: stringValue(row.sessionId),
- sdkSessionId: stringValue(row.sdkSessionId),
- };
- }).filter((row) => row.rawFilePath && row.sessionId && row.sdkSessionId);
+ return toRecentSourceRecords(rows);
+}
+
+export async function listSkillUsageSourcesWithRecentExposuresFromClient(
+ client: DbClient,
+ analyzerVersion: string,
+ recentSince: number,
+): Promise<SkillUsageRecentSourceRecord[]> {
+ const rows = await client.query<Record<string, unknown>>(`
+ SELECT
+ e.raw_file_path AS rawFilePath,
+ e.agent_kind AS agentKind,
+ e.session_id AS sessionId,
+ e.sdk_session_id AS sdkSessionId
+ FROM skill_usage_exposures e
+ WHERE e.analyzer_version = ?
+ AND e.seen_at >= ?
+ GROUP BY e.raw_file_path
+ ORDER BY MAX(e.seen_at) DESC
+ `, [analyzerVersion, recentSince]);
+ return toRecentSourceRecords(rows);
}
export function deleteSkillUsageRecordsBefore(
@@ -320,12 +391,28 @@ export function deleteSkillUsageRecordsBefore(
tx();
}
+export async function deleteSkillUsageRecordsBeforeWithClient(
+ client: DbClient,
+ analyzerVersion: string,
+ recentSince: number,
+): Promise<void> {
+ await client.tx('skillUsage.applyMutation', { kind: 'deleteBefore', analyzerVersion, recentSince });
+}
+
+export async function promoteSkillUsageAnalyzerVersionWithClient(
+ client: DbClient,
+ analyzerVersion: string,
+): Promise<void> {
+ await client.tx('skillUsage.applyMutation', { kind: 'promote', analyzerVersion });
+}
+
export function getSkillUsageSummaryFromDb(
db: Database.Database,
params: SkillUsageQueryScope,
): SkillUsageSummary {
const analyzerVersion = params.analyzerVersion ?? null;
const recentSince = recentWindowStartMs(params.nowMs ?? Date.now());
+ const filter = skillUsageFilter(params.skillName, analyzerVersion, recentSince);
const versionRows = db.prepare(`
SELECT
skill_document_hash AS skillDocumentHash,
@@ -347,13 +434,11 @@ export function getSkillUsageSummaryFromDb(
SUM(command_call_count) AS commandCallCount,
SUM(command_failure_count) AS commandFailureCount
FROM skill_usage_exposures
- WHERE skill_name = ?
- AND (? IS NULL OR analyzer_version = ?)
- AND seen_at >= ?
+ WHERE ${filter.sql}
AND skill_document_hash IS NOT NULL
GROUP BY skill_document_hash
ORDER BY latestSeenAt DESC
- `).all(params.skillName, analyzerVersion, analyzerVersion, recentSince) as Array<Record<string, unknown>>;
+ `).all(...filter.params) as Array<Record<string, unknown>>;
const totalRow = db.prepare(`
SELECT
@@ -370,12 +455,35 @@ export function getSkillUsageSummaryFromDb(
END) AS passiveUseCount,
SUM(CASE WHEN skill_document_hash IS NULL THEN 1 ELSE 0 END) AS unversionedUseCount
FROM skill_usage_exposures
- WHERE skill_name = ?
- AND (? IS NULL OR analyzer_version = ?)
- AND seen_at >= ?
- `).get(params.skillName, analyzerVersion, analyzerVersion, recentSince) as Record<string, unknown> | undefined;
+ WHERE ${filter.sql}
+ `).get(...filter.params) as Record<string, unknown> | undefined;
const readObservations = getReadObservationsFromDb(db, params.skillName, analyzerVersion, recentSince);
+ const trend = getSkillUsageTrendFromDb(db, params.skillName, analyzerVersion, recentSince);
+ return buildSkillUsageSummary(params, versionRows, totalRow, readObservations, trend);
+}
+
+export async function getSkillUsageSummaryFromClient(
+ client: DbClient,
+ params: SkillUsageQueryScope,
+): Promise<SkillUsageSummary> {
+ const snapshot = await readSkillUsageSnapshotFromClient(client, params, false);
+ return buildSkillUsageSummary(
+ params,
+ snapshot.versionRows,
+ snapshot.totalRow,
+ buildReadObservations(snapshot.readRows),
+ snapshot.trendRows.map(toTrendPointFromRow),
+ );
+}
+
+function buildSkillUsageSummary(
+ params: SkillUsageQueryScope,
+ versionRows: Array<Record<string, unknown>>,
+ totalRow: Record<string, unknown> | undefined,
+ readObservations: { overall: SkillUsageReadObservation; byVersion: Map<string, SkillUsageReadObservation> },
+ trend: SkillUsageTrendPoint[],
+): SkillUsageSummary {
const documentVersions = versionRows.map((row) => toDocumentVersionSummary(row, readObservations.byVersion));
const currentDocumentHash = params.currentDocumentHash ?? null;
const totalUseCount = numberValue(totalRow?.totalUseCount);
@@ -394,8 +502,6 @@ export function getSkillUsageSummaryFromDb(
? documentVersions.find((version) => version.skillDocumentHash === currentDocumentHash) ?? null
: null;
const latestSeenAt = totalUseCount > 0 ? numberValue(totalRow?.latestSeenAt) : null;
- const trend = getSkillUsageTrendFromDb(db, params.skillName, analyzerVersion, recentSince);
-
return {
skillName: params.skillName,
currentDocumentHash,
@@ -420,32 +526,18 @@ function getReadObservationsFromDb(
analyzerVersion: string | null,
recentSince: number,
): { overall: SkillUsageReadObservation; byVersion: Map<string, SkillUsageReadObservation> } {
+ const filter = skillUsageFilter(skillName, analyzerVersion, recentSince);
const rows = db.prepare(`
SELECT
skill_document_hash AS skillDocumentHash,
COALESCE(NULLIF(sdk_session_id, ''), session_id) AS sessionKey,
seen_at AS seenAt
FROM skill_usage_exposures
- WHERE skill_name = ?
- AND (? IS NULL OR analyzer_version = ?)
- AND seen_at >= ?
+ WHERE ${filter.sql}
AND source IN ('claude_skill_file_read', 'codex_skill_file_read')
ORDER BY sessionKey ASC, seen_at ASC
- `).all(skillName, analyzerVersion, analyzerVersion, recentSince) as Array<Record<string, unknown>>;
-
- const grouped = new Map<string, Array<Record<string, unknown>>>();
- for (const row of rows) {
- const hash = stringValue(row.skillDocumentHash);
- if (!hash) continue;
- const items = grouped.get(hash) ?? [];
- items.push(row);
- grouped.set(hash, items);
- }
-
- return {
- overall: readObservationFromRows(rows),
- byVersion: new Map([...grouped].map(([hash, items]) => [hash, readObservationFromRows(items)])),
- };
+ `).all(...filter.params) as Array<Record<string, unknown>>;
+ return buildReadObservations(rows);
}
export function getSkillUsageDiagnosisContextFromDb(
@@ -490,12 +582,283 @@ export function getSkillUsageDiagnosisContextFromDb(
};
}
+export async function getSkillUsageDiagnosisContextFromClient(
+ client: DbClient,
+ params: {
+ skillName: string;
+ currentDocumentHash?: string | null;
+ currentDocumentContent?: string | null;
+ analyzerVersion?: string | null;
+ skillPath?: string | null;
+ maxEvidence?: number;
+ nowMs?: number;
+ },
+): Promise<SkillUsageDiagnosisContext> {
+ const currentDocumentHash = params.currentDocumentHash ?? null;
+ const snapshot = await readSkillUsageSnapshotFromClient(client, params, true);
+ const summary = buildSkillUsageSummary(
+ params,
+ snapshot.versionRows,
+ snapshot.totalRow,
+ buildReadObservations(snapshot.readRows),
+ snapshot.trendRows.map(toTrendPointFromRow),
+ );
+ const evidence = selectDiagnosisEvidence(
+ snapshot.evidenceRows.map(toEvidenceIndex),
+ params.maxEvidence ?? 12,
+ );
+ return {
+ skillName: params.skillName,
+ skillPath: params.skillPath ?? null,
+ currentDocumentHash,
+ summary,
+ evidence,
+ prompt: buildSkillUsageDiagnosisPrompt({
+ skillName: params.skillName,
+ skillPath: params.skillPath ?? null,
+ summary,
+ evidence,
+ }),
+ };
+}
+
+interface SkillUsageSnapshotRow {
+ rowKind: 'version' | 'total' | 'read' | 'trend' | 'evidence';
+ payload: string;
+}
+
+interface SkillUsageSnapshot {
+ versionRows: Array<Record<string, unknown>>;
+ totalRow: Record<string, unknown> | undefined;
+ readRows: Array<Record<string, unknown>>;
+ trendRows: Array<Record<string, unknown>>;
+ evidenceRows: Array<Record<string, unknown>>;
+}
+
+/**
+ * Read every derived view from one SQLite statement. The materialized CTE uses
+ * the selective skill/version/time index once, and all aggregates observe the
+ * same snapshot even when a background refresh is queued on the DB worker.
+ */
+async function readSkillUsageSnapshotFromClient(
+ client: DbClient,
+ params: SkillUsageQueryScope,
+ includeEvidence: boolean,
+): Promise<SkillUsageSnapshot> {
+ const analyzerVersion = params.analyzerVersion ?? null;
+ const recentSince = recentWindowStartMs(params.nowMs ?? Date.now());
+ const filter = skillUsageFilter(params.skillName, analyzerVersion, recentSince);
+ const currentDocumentHash = params.currentDocumentHash ?? null;
+ const evidenceHash = currentDocumentHash || null;
+ const evidenceCte = includeEvidence
+ ? `,
+ evidence_rows AS (
+ SELECT *
+ FROM filtered
+ WHERE ${evidenceHash === null
+ ? '1 = 1'
+ : `(
+ NOT EXISTS (
+ SELECT 1 FROM filtered WHERE skill_document_hash = ?
+ )
+ OR skill_document_hash = ?
+ )`}
+ ORDER BY seen_at DESC
+ LIMIT 500
+ )`
+ : '';
+ const evidenceSelect = includeEvidence
+ ? `
+ UNION ALL
+ SELECT 'evidence', json_object(
+ 'id', id,
+ 'rawFilePath', raw_file_path,
+ 'rawLineNo', raw_line_no,
+ 'sessionId', session_id,
+ 'sdkSessionId', sdk_session_id,
+ 'agentKind', agent_kind,
+ 'skillName', skill_name,
+ 'skillPath', skill_path,
+ 'skillDocumentHash', skill_document_hash,
+ 'exposureContentHash', exposure_content_hash,
+ 'documentHashSource', document_hash_source,
+ 'source', source,
+ 'toolUseId', tool_use_id,
+ 'seenAt', seen_at,
+ 'toolCallCount', tool_call_count,
+ 'repeatedToolCallCount', repeated_tool_call_count,
+ 'toolErrorCount', tool_error_count,
+ 'commandCallCount', command_call_count,
+ 'commandFailureCount', command_failure_count
+ )
+ FROM evidence_rows`
+ : '';
+ const queryParams = evidenceHash !== null && includeEvidence
+ ? [...filter.params, evidenceHash, evidenceHash]
+ : filter.params;
+ const rows = await client.query<SkillUsageSnapshotRow>(`
+ WITH filtered AS MATERIALIZED (
+ SELECT *
+ FROM skill_usage_exposures
+ WHERE ${filter.sql}
+ ),
+ version_rows AS (
+ SELECT
+ skill_document_hash AS skillDocumentHash,
+ COUNT(*) AS useCount,
+ MIN(seen_at) AS firstSeenAt,
+ MAX(seen_at) AS latestSeenAt,
+ SUM(CASE WHEN agent_kind = 'claude-code' THEN 1 ELSE 0 END) AS claudeUseCount,
+ SUM(CASE WHEN agent_kind = 'codex' THEN 1 ELSE 0 END) AS codexUseCount,
+ SUM(CASE WHEN source = 'claude_skill_tool' THEN 1 ELSE 0 END) AS strongActiveUseCount,
+ SUM(CASE WHEN source IN ('claude_skill_file_read', 'codex_skill_file_read') THEN 1 ELSE 0 END) AS semiActiveUseCount,
+ SUM(CASE
+ WHEN source = 'claude_skill_tool' THEN 0
+ WHEN source IN ('claude_skill_file_read', 'codex_skill_file_read') THEN 0
+ ELSE 1
+ END) AS passiveUseCount,
+ SUM(tool_call_count) AS toolCallCount,
+ SUM(repeated_tool_call_count) AS repeatedToolCallCount,
+ SUM(tool_error_count) AS toolErrorCount,
+ SUM(command_call_count) AS commandCallCount,
+ SUM(command_failure_count) AS commandFailureCount
+ FROM filtered
+ WHERE skill_document_hash IS NOT NULL
+ GROUP BY skill_document_hash
+ ),
+ total_row AS (
+ SELECT
+ COUNT(*) AS totalUseCount,
+ MAX(seen_at) AS latestSeenAt,
+ SUM(CASE WHEN agent_kind = 'claude-code' THEN 1 ELSE 0 END) AS claudeUseCount,
+ SUM(CASE WHEN agent_kind = 'codex' THEN 1 ELSE 0 END) AS codexUseCount,
+ SUM(CASE WHEN source = 'claude_skill_tool' THEN 1 ELSE 0 END) AS strongActiveUseCount,
+ SUM(CASE WHEN source IN ('claude_skill_file_read', 'codex_skill_file_read') THEN 1 ELSE 0 END) AS semiActiveUseCount,
+ SUM(CASE
+ WHEN source = 'claude_skill_tool' THEN 0
+ WHEN source IN ('claude_skill_file_read', 'codex_skill_file_read') THEN 0
+ ELSE 1
+ END) AS passiveUseCount,
+ SUM(CASE WHEN skill_document_hash IS NULL THEN 1 ELSE 0 END) AS unversionedUseCount
+ FROM filtered
+ ),
+ read_rows AS (
+ SELECT
+ skill_document_hash AS skillDocumentHash,
+ COALESCE(NULLIF(sdk_session_id, ''), session_id) AS sessionKey,
+ seen_at AS seenAt
+ FROM filtered
+ WHERE source IN ('claude_skill_file_read', 'codex_skill_file_read')
+ ),
+ trend_rows AS (
+ SELECT
+ strftime('%Y-%m-%d', seen_at / 1000, 'unixepoch', 'localtime') AS day,
+ COUNT(*) AS useCount,
+ SUM(tool_call_count) AS toolCallCount,
+ SUM(repeated_tool_call_count) AS repeatedToolCallCount,
+ SUM(command_call_count) AS commandCallCount,
+ SUM(command_failure_count) AS commandFailureCount
+ FROM filtered
+ GROUP BY day
+ ORDER BY day DESC
+ LIMIT 30
+ )${evidenceCte}
+ SELECT 'version' AS rowKind, json_object(
+ 'skillDocumentHash', skillDocumentHash,
+ 'useCount', useCount,
+ 'firstSeenAt', firstSeenAt,
+ 'latestSeenAt', latestSeenAt,
+ 'claudeUseCount', claudeUseCount,
+ 'codexUseCount', codexUseCount,
+ 'strongActiveUseCount', strongActiveUseCount,
+ 'semiActiveUseCount', semiActiveUseCount,
+ 'passiveUseCount', passiveUseCount,
+ 'toolCallCount', toolCallCount,
+ 'repeatedToolCallCount', repeatedToolCallCount,
+ 'toolErrorCount', toolErrorCount,
+ 'commandCallCount', commandCallCount,
+ 'commandFailureCount', commandFailureCount
+ ) AS payload
+ FROM version_rows
+ UNION ALL
+ SELECT 'total', json_object(
+ 'totalUseCount', totalUseCount,
+ 'latestSeenAt', latestSeenAt,
+ 'claudeUseCount', claudeUseCount,
+ 'codexUseCount', codexUseCount,
+ 'strongActiveUseCount', strongActiveUseCount,
+ 'semiActiveUseCount', semiActiveUseCount,
+ 'passiveUseCount', passiveUseCount,
+ 'unversionedUseCount', unversionedUseCount
+ )
+ FROM total_row
+ UNION ALL
+ SELECT 'read', json_object(
+ 'skillDocumentHash', skillDocumentHash,
+ 'sessionKey', sessionKey,
+ 'seenAt', seenAt
+ )
+ FROM read_rows
+ UNION ALL
+ SELECT 'trend', json_object(
+ 'day', day,
+ 'useCount', useCount,
+ 'toolCallCount', toolCallCount,
+ 'repeatedToolCallCount', repeatedToolCallCount,
+ 'commandCallCount', commandCallCount,
+ 'commandFailureCount', commandFailureCount
+ )
+ FROM trend_rows
+ ${evidenceSelect}
+ `, queryParams);
+
+ const snapshot: SkillUsageSnapshot = {
+ versionRows: [],
+ totalRow: undefined,
+ readRows: [],
+ trendRows: [],
+ evidenceRows: [],
+ };
+ for (const row of rows) {
+ const payload = parseSkillUsageSnapshotPayload(row.payload);
+ switch (row.rowKind) {
+ case 'version':
+ snapshot.versionRows.push(payload);
+ break;
+ case 'total':
+ snapshot.totalRow = payload;
+ break;
+ case 'read':
+ snapshot.readRows.push(payload);
+ break;
+ case 'trend':
+ snapshot.trendRows.push(payload);
+ break;
+ case 'evidence':
+ snapshot.evidenceRows.push(payload);
+ break;
+ }
+ }
+ snapshot.versionRows.sort((a, b) => numberValue(b.latestSeenAt) - numberValue(a.latestSeenAt));
+ snapshot.trendRows.sort((a, b) => stringValue(b.day).localeCompare(stringValue(a.day)));
+ return snapshot;
+}
+
+function parseSkillUsageSnapshotPayload(payload: string): Record<string, unknown> {
+ const parsed: unknown = JSON.parse(payload);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('invalid skill usage snapshot payload');
+ }
+ return parsed as Record<string, unknown>;
+}
+
function getSkillUsageTrendFromDb(
db: Database.Database,
skillName: string,
analyzerVersion: string | null,
recentSince: number,
): SkillUsageTrendPoint[] {
+ const filter = skillUsageFilter(skillName, analyzerVersion, recentSince);
const rows = db.prepare(`
SELECT
strftime('%Y-%m-%d', seen_at / 1000, 'unixepoch', 'localtime') AS day,
@@ -505,23 +868,12 @@ function getSkillUsageTrendFromDb(
SUM(command_call_count) AS commandCallCount,
SUM(command_failure_count) AS commandFailureCount
FROM skill_usage_exposures
- WHERE skill_name = ?
- AND (? IS NULL OR analyzer_version = ?)
- AND seen_at >= ?
+ WHERE ${filter.sql}
GROUP BY day
ORDER BY day DESC
LIMIT 30
- `).all(skillName, analyzerVersion, analyzerVersion, recentSince) as Array<Record<string, unknown>>;
- return rows.map((row) =>
- toTrendPoint({
- day: stringValue(row.day),
- useCount: numberValue(row.useCount),
- toolCallCount: numberValue(row.toolCallCount),
- repeatedToolCallCount: numberValue(row.repeatedToolCallCount),
- commandCallCount: numberValue(row.commandCallCount),
- commandFailureCount: numberValue(row.commandFailureCount),
- }),
- );
+ `).all(...filter.params) as Array<Record<string, unknown>>;
+ return rows.map(toTrendPointFromRow);
}
function readEvidenceCandidates(
@@ -531,6 +883,7 @@ function readEvidenceCandidates(
analyzerVersion: string | null,
recentSince: number,
): SkillUsageEvidenceIndex[] {
+ const filter = skillUsageEvidenceFilter(skillName, skillDocumentHash, analyzerVersion, recentSince);
const rows = db.prepare(`
SELECT
id,
@@ -553,22 +906,15 @@ function readEvidenceCandidates(
command_call_count AS commandCallCount,
command_failure_count AS commandFailureCount
FROM skill_usage_exposures
- WHERE skill_name = ?
- AND (? IS NULL OR analyzer_version = ?)
- AND (? IS NULL OR skill_document_hash = ?)
- AND seen_at >= ?
+ WHERE ${filter.sql}
ORDER BY seen_at DESC
LIMIT 500
- `).all(
- skillName,
- analyzerVersion,
- analyzerVersion,
- skillDocumentHash,
- skillDocumentHash,
- recentSince,
- ) as Array<Record<string, unknown>>;
+ `).all(...filter.params) as Array<Record<string, unknown>>;
+ return rows.map(toEvidenceIndex);
+}
- return rows.map((row) => ({
+function toEvidenceIndex(row: Record<string, unknown>): SkillUsageEvidenceIndex {
+ return {
id: stringValue(row.id),
bucket: 'recent',
rawFilePath: stringValue(row.rawFilePath),
@@ -591,7 +937,7 @@ function readEvidenceCandidates(
commandCallCount: numberValue(row.commandCallCount),
commandFailureCount: numberValue(row.commandFailureCount),
},
- }));
+ };
}
function selectDiagnosisEvidence(
@@ -848,6 +1194,17 @@ function toDocumentVersionSummary(
return addDerivedMetrics(summary);
}
+function toTrendPointFromRow(row: Record<string, unknown>): SkillUsageTrendPoint {
+ return toTrendPoint({
+ day: stringValue(row.day),
+ useCount: numberValue(row.useCount),
+ toolCallCount: numberValue(row.toolCallCount),
+ repeatedToolCallCount: numberValue(row.repeatedToolCallCount),
+ commandCallCount: numberValue(row.commandCallCount),
+ commandFailureCount: numberValue(row.commandFailureCount),
+ });
+}
+
function toTrendPoint(raw: {
day: string;
useCount: number;
@@ -927,6 +1284,23 @@ function readObservationFromRows(rows: Array<Record<string, unknown>>): SkillUsa
};
}
+function buildReadObservations(
+ rows: Array<Record<string, unknown>>,
+): { overall: SkillUsageReadObservation; byVersion: Map<string, SkillUsageReadObservation> } {
+ const grouped = new Map<string, Array<Record<string, unknown>>>();
+ for (const row of rows) {
+ const hash = stringValue(row.skillDocumentHash);
+ if (!hash) continue;
+ const items = grouped.get(hash) ?? [];
+ items.push(row);
+ grouped.set(hash, items);
+ }
+ return {
+ overall: readObservationFromRows(rows),
+ byVersion: new Map([...grouped].map(([hash, items]) => [hash, readObservationFromRows(items)])),
+ };
+}
+
function createEmptyReadObservation(): SkillUsageReadObservation {
return {
fileReadCount: 0,
@@ -957,6 +1331,48 @@ function estimateDocumentSize(content: string): SkillUsageDocumentSize {
};
}
+function skillUsageFilter(
+ skillName: string,
+ analyzerVersion: string | null,
+ recentSince: number,
+): { sql: string; params: unknown[] } {
+ const clauses = ['skill_name = ?'];
+ const params: unknown[] = [skillName];
+ if (analyzerVersion !== null) {
+ clauses.push('analyzer_version = ?');
+ params.push(analyzerVersion);
+ }
+ clauses.push('seen_at >= ?');
+ params.push(recentSince);
+ return { sql: clauses.join('\n AND '), params };
+}
+
+function skillUsageEvidenceFilter(
+ skillName: string,
+ skillDocumentHash: string | null,
+ analyzerVersion: string | null,
+ recentSince: number,
+): { sql: string; params: unknown[] } {
+ const filter = skillUsageFilter(skillName, analyzerVersion, recentSince);
+ if (skillDocumentHash === null) return filter;
+ return {
+ sql: `${filter.sql}\n AND skill_document_hash = ?`,
+ params: [...filter.params, skillDocumentHash],
+ };
+}
+
+function toRecentSourceRecords(rows: Array<Record<string, unknown>>): SkillUsageRecentSourceRecord[] {
+ return rows.map((row) => {
+ const agentKind: SkillUsageAgentKind = stringValue(row.agentKind) === 'claude-code' ? 'claude-code' : stringValue(row.agentKind) === 'pi' ? 'pi' : 'codex';
+ return {
+ rawFilePath: stringValue(row.rawFilePath),
+ agentKind,
+ sessionId: stringValue(row.sessionId),
+ sdkSessionId: stringValue(row.sdkSessionId),
+ };
+ }).filter((row) => row.rawFilePath && row.sessionId && row.sdkSessionId);
+}
+
function stringValue(value: unknown): string {
return typeof value === 'string' ? value : '';
}