"use strict";exports.id=7425,exports.ids=[7425],exports.modules={97425:(e,t,r)=>{r.d(t,{n:()=>p});var s=r(85890),a=r.n(s),o=r(55315),i=r.n(o),_=r(75748);let n=[{version:1,name:"initial-schema",up:e=>{(0,_.qZ)(e)},down:e=>{e.exec("DROP TABLE IF EXISTS session_states;"),e.exec("DROP TABLE IF EXISTS chat_messages;"),e.exec("DROP TABLE IF EXISTS worktrees;")}},{version:2,name:"add-multi-repo-and-memo-support",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN repository_path TEXT;
        ALTER TABLE worktrees ADD COLUMN repository_name TEXT;
        ALTER TABLE worktrees ADD COLUMN memo TEXT;
        ALTER TABLE worktrees ADD COLUMN last_user_message TEXT;
        ALTER TABLE worktrees ADD COLUMN last_user_message_at INTEGER;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_worktrees_repository
        ON worktrees(repository_path);
      `);let t=e.prepare("SELECT id, path FROM worktrees").all(),r=e.prepare(`
        UPDATE worktrees
        SET repository_path = ?,
            repository_name = ?
        WHERE id = ?
      `);for(let e of t){let t=E(e.path),s=i().basename(t);r.run(t,s,e.id)}let s=e.prepare(`
        UPDATE worktrees
        SET last_user_message = ?,
            last_user_message_at = ?
        WHERE id = ?
      `);for(let r of t){let t=e.prepare(`
          SELECT content, timestamp
          FROM chat_messages
          WHERE worktree_id = ? AND role = 'user'
          ORDER BY timestamp DESC
          LIMIT 1
        `).get(r.id);if(t){let e=t.content.substring(0,200);s.run(e,t.timestamp,r.id)}}},down:e=>{e.exec(`
        -- Create backup table
        CREATE TABLE worktrees_backup AS
        SELECT id, name, path, last_message_summary, updated_at
        FROM worktrees;

        -- Drop original table
        DROP TABLE worktrees;

        -- Recreate original table
        CREATE TABLE worktrees (
          id TEXT PRIMARY KEY,
          name TEXT NOT NULL,
          path TEXT NOT NULL UNIQUE,
          last_message_summary TEXT,
          updated_at INTEGER
        );

        -- Restore data
        INSERT INTO worktrees (id, name, path, last_message_summary, updated_at)
        SELECT id, name, path, last_message_summary, updated_at
        FROM worktrees_backup;

        -- Drop backup table
        DROP TABLE worktrees_backup;

        -- Drop index
        DROP INDEX IF EXISTS idx_worktrees_repository;
      `)}},{version:3,name:"fix-worktree-repository-paths",up:e=>{let t=e.prepare("SELECT id, path FROM worktrees").all(),r=e.prepare(`
        UPDATE worktrees
        SET repository_path = ?,
            repository_name = ?
        WHERE id = ?
      `);for(let e of t){let t=E(e.path),s=i().basename(t);r.run(t,s,e.id)}},down:()=>{console.log("No rollback needed for repository path fix")}},{version:4,name:"add-favorite-field",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN favorite INTEGER DEFAULT 0;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_worktrees_favorite
        ON worktrees(favorite DESC, updated_at DESC);
      `)},down:e=>{e.exec(`
        -- Drop the index first
        DROP INDEX IF EXISTS idx_worktrees_favorite;

        -- Note: In production, you'd need to recreate the table without the favorite column
        -- This is a simplified down migration
      `)}},{version:5,name:"add-status-field",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN status TEXT DEFAULT NULL;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_worktrees_status
        ON worktrees(status);
      `)},down:e=>{e.exec(`
        DROP INDEX IF EXISTS idx_worktrees_status;
      `)}},{version:6,name:"add-link-field",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN link TEXT DEFAULT NULL;
      `)},down:()=>{console.log("No rollback needed for link field")}},{version:7,name:"add-cli-tool-id",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN cli_tool_id TEXT DEFAULT 'claude';
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_worktrees_cli_tool
        ON worktrees(cli_tool_id);
      `),e.exec(`
        UPDATE worktrees SET cli_tool_id = 'claude' WHERE cli_tool_id IS NULL;
      `)},down:e=>{e.exec(`
        DROP INDEX IF EXISTS idx_worktrees_cli_tool;
      `),console.log("No full rollback for cli_tool_id column (SQLite limitation)")}},{version:8,name:"change-role-claude-to-assistant",up:e=>{e.exec(`
        CREATE TABLE chat_messages_new (
          id TEXT PRIMARY KEY,
          worktree_id TEXT NOT NULL,
          role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
          content TEXT NOT NULL,
          summary TEXT,
          timestamp INTEGER NOT NULL,
          log_file_name TEXT,
          request_id TEXT,
          message_type TEXT DEFAULT 'normal',
          prompt_data TEXT,
          cli_tool_id TEXT DEFAULT 'claude',
          FOREIGN KEY (worktree_id) REFERENCES worktrees(id) ON DELETE CASCADE
        );
      `),e.exec(`
        INSERT INTO chat_messages_new
        SELECT
          id,
          worktree_id,
          CASE WHEN role = 'claude' THEN 'assistant' ELSE role END as role,
          content,
          summary,
          timestamp,
          log_file_name,
          request_id,
          message_type,
          prompt_data,
          cli_tool_id
        FROM chat_messages;
      `),e.exec("DROP TABLE chat_messages;"),e.exec("ALTER TABLE chat_messages_new RENAME TO chat_messages;"),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_chat_messages_worktree
        ON chat_messages(worktree_id);
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_chat_messages_timestamp
        ON chat_messages(timestamp);
      `),console.log('✓ Changed role constraint from "claude" to "assistant"'),console.log('✓ Updated existing messages with role="claude" to role="assistant"')},down:e=>{e.exec(`
        CREATE TABLE chat_messages_new (
          id TEXT PRIMARY KEY,
          worktree_id TEXT NOT NULL,
          role TEXT NOT NULL CHECK (role IN ('user', 'claude')),
          content TEXT NOT NULL,
          summary TEXT,
          timestamp INTEGER NOT NULL,
          log_file_name TEXT,
          request_id TEXT,
          message_type TEXT DEFAULT 'normal',
          prompt_data TEXT,
          cli_tool_id TEXT DEFAULT 'claude',
          FOREIGN KEY (worktree_id) REFERENCES worktrees(id) ON DELETE CASCADE
        );
      `),e.exec(`
        INSERT INTO chat_messages_new
        SELECT
          id,
          worktree_id,
          CASE WHEN role = 'assistant' THEN 'claude' ELSE role END as role,
          content,
          summary,
          timestamp,
          log_file_name,
          request_id,
          message_type,
          prompt_data,
          cli_tool_id
        FROM chat_messages;
      `),e.exec("DROP TABLE chat_messages;"),e.exec("ALTER TABLE chat_messages_new RENAME TO chat_messages;"),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_chat_messages_worktree
        ON chat_messages(worktree_id);
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_chat_messages_timestamp
        ON chat_messages(timestamp);
      `),console.log('✓ Rolled back: Changed role constraint from "assistant" to "claude"')}},{version:9,name:"add-in-progress-message-id-to-session-states",up:e=>{e.exec(`
        ALTER TABLE session_states ADD COLUMN in_progress_message_id TEXT DEFAULT NULL;
      `),console.log("✓ Added in_progress_message_id column to session_states table")},down:()=>{console.log("No full rollback for in_progress_message_id column (SQLite limitation)")}},{version:10,name:"add-worktree-memos-table",up:e=>{e.exec(`
        CREATE TABLE worktree_memos (
          id TEXT PRIMARY KEY,
          worktree_id TEXT NOT NULL,
          title TEXT NOT NULL DEFAULT 'Memo',
          content TEXT NOT NULL DEFAULT '',
          position INTEGER NOT NULL DEFAULT 0,
          created_at INTEGER NOT NULL,
          updated_at INTEGER NOT NULL,

          FOREIGN KEY (worktree_id) REFERENCES worktrees(id) ON DELETE CASCADE,
          UNIQUE(worktree_id, position)
        );
      `),e.exec(`
        CREATE INDEX idx_worktree_memos_worktree
          ON worktree_memos(worktree_id, position);
      `);let{randomUUID:t}=r(84770),s=e.prepare(`
        SELECT id, memo FROM worktrees WHERE memo IS NOT NULL AND memo != ''
      `).all(),a=e.prepare(`
        INSERT INTO worktree_memos (id, worktree_id, title, content, position, created_at, updated_at)
        VALUES (?, ?, 'Memo', ?, 0, ?, ?)
      `),o=Date.now();for(let e of s)a.run(t(),e.id,e.memo,o,o);console.log(`✓ Created worktree_memos table`),console.log(`✓ Migrated ${s.length} existing memos to new table`)},down:e=>{e.exec("DROP TABLE IF EXISTS worktree_memos"),console.log("✓ Dropped worktree_memos table")}},{version:11,name:"add-viewed-tracking",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN last_viewed_at TEXT;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_chat_messages_assistant_latest
        ON chat_messages(worktree_id, role, timestamp DESC);
      `),console.log("✓ Added last_viewed_at column to worktrees table"),console.log("✓ Created index for assistant message queries")},down:e=>{e.exec("DROP INDEX IF EXISTS idx_chat_messages_assistant_latest"),console.log("✓ Dropped idx_chat_messages_assistant_latest index")}},{version:12,name:"add-external-apps-table",up:e=>{e.exec(`
        CREATE TABLE IF NOT EXISTS external_apps (
          id TEXT PRIMARY KEY,

          -- Basic info
          name TEXT NOT NULL UNIQUE,
          display_name TEXT NOT NULL,
          description TEXT,

          -- Routing config
          path_prefix TEXT NOT NULL UNIQUE,
          target_port INTEGER NOT NULL,
          target_host TEXT DEFAULT 'localhost',

          -- App type
          app_type TEXT NOT NULL CHECK(app_type IN ('sveltekit', 'streamlit', 'nextjs', 'other')),

          -- WebSocket config
          websocket_enabled INTEGER DEFAULT 0,
          websocket_path_pattern TEXT,

          -- Status
          enabled INTEGER DEFAULT 1,

          -- Metadata
          created_at INTEGER NOT NULL,
          updated_at INTEGER NOT NULL
        );
      `),e.exec(`
        CREATE INDEX idx_external_apps_path_prefix ON external_apps(path_prefix);
      `),e.exec(`
        CREATE INDEX idx_external_apps_enabled ON external_apps(enabled);
      `),console.log("✓ Created external_apps table"),console.log("✓ Created indexes for external_apps")},down:e=>{e.exec("DROP INDEX IF EXISTS idx_external_apps_enabled"),e.exec("DROP INDEX IF EXISTS idx_external_apps_path_prefix"),e.exec("DROP TABLE IF EXISTS external_apps"),console.log("✓ Dropped external_apps table and indexes")}},{version:13,name:"rename-worktree-memo-to-description",up:e=>{e.exec(`
        ALTER TABLE worktrees RENAME COLUMN memo TO description;
      `),console.log("✓ Renamed worktrees.memo column to description")},down:e=>{e.exec(`
        ALTER TABLE worktrees RENAME COLUMN description TO memo;
      `),console.log("✓ Rolled back: Renamed worktrees.description column back to memo")}},{version:14,name:"add-repositories-and-clone-jobs-tables",up:e=>{e.exec(`
        CREATE TABLE IF NOT EXISTS repositories (
          id TEXT PRIMARY KEY,
          name TEXT NOT NULL,
          path TEXT NOT NULL UNIQUE,
          enabled INTEGER NOT NULL DEFAULT 1,
          clone_url TEXT,
          normalized_clone_url TEXT,
          clone_source TEXT CHECK(clone_source IN ('local', 'https', 'ssh')) DEFAULT 'local',
          is_env_managed INTEGER NOT NULL DEFAULT 0,
          created_at INTEGER NOT NULL,
          updated_at INTEGER NOT NULL
        );
      `),e.exec(`
        CREATE UNIQUE INDEX IF NOT EXISTS idx_repositories_normalized_clone_url
        ON repositories(normalized_clone_url)
        WHERE normalized_clone_url IS NOT NULL;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_repositories_path
        ON repositories(path);
      `),e.exec(`
        CREATE TABLE IF NOT EXISTS clone_jobs (
          id TEXT PRIMARY KEY,
          clone_url TEXT NOT NULL,
          normalized_clone_url TEXT NOT NULL,
          target_path TEXT NOT NULL,
          repository_id TEXT,
          status TEXT NOT NULL CHECK(status IN ('pending', 'running', 'completed', 'failed', 'cancelled')) DEFAULT 'pending',
          pid INTEGER,
          progress INTEGER NOT NULL DEFAULT 0,
          error_category TEXT,
          error_code TEXT,
          error_message TEXT,
          started_at INTEGER,
          completed_at INTEGER,
          created_at INTEGER NOT NULL,

          FOREIGN KEY (repository_id) REFERENCES repositories(id) ON DELETE SET NULL
        );
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_clone_jobs_status
        ON clone_jobs(status);
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_clone_jobs_normalized_clone_url
        ON clone_jobs(normalized_clone_url);
      `),console.log("✓ Created repositories table"),console.log("✓ Created clone_jobs table"),console.log("✓ Created indexes for repositories and clone_jobs")},down:e=>{e.exec("DROP INDEX IF EXISTS idx_clone_jobs_normalized_clone_url"),e.exec("DROP INDEX IF EXISTS idx_clone_jobs_status"),e.exec("DROP TABLE IF EXISTS clone_jobs"),e.exec("DROP INDEX IF EXISTS idx_repositories_path"),e.exec("DROP INDEX IF EXISTS idx_repositories_normalized_clone_url"),e.exec("DROP TABLE IF EXISTS repositories"),console.log("✓ Dropped repositories and clone_jobs tables")}},{version:15,name:"add-initial-branch-column",up:e=>{e.exec(`
        ALTER TABLE worktrees ADD COLUMN initial_branch TEXT;
      `),console.log("✓ Added initial_branch column to worktrees table")},down:e=>{e.exec(`
        -- 1. Create backup table without initial_branch
        CREATE TABLE worktrees_backup AS
        SELECT id, name, path, repository_path, repository_name, description,
               last_user_message, last_user_message_at, last_message_summary,
               favorite, status, link, cli_tool_id, updated_at, last_viewed_at
        FROM worktrees;

        -- 2. Drop original table
        DROP TABLE worktrees;

        -- 3. Recreate table without initial_branch
        CREATE TABLE worktrees (
          id TEXT PRIMARY KEY,
          name TEXT NOT NULL,
          path TEXT NOT NULL UNIQUE,
          repository_path TEXT,
          repository_name TEXT,
          description TEXT,
          last_user_message TEXT,
          last_user_message_at INTEGER,
          last_message_summary TEXT,
          favorite INTEGER DEFAULT 0,
          status TEXT DEFAULT NULL,
          link TEXT DEFAULT NULL,
          cli_tool_id TEXT DEFAULT 'claude',
          updated_at INTEGER,
          last_viewed_at TEXT
        );

        -- 4. Restore data
        INSERT INTO worktrees (id, name, path, repository_path, repository_name,
               description, last_user_message, last_user_message_at, last_message_summary,
               favorite, status, link, cli_tool_id, updated_at, last_viewed_at)
        SELECT id, name, path, repository_path, repository_name,
               description, last_user_message, last_user_message_at, last_message_summary,
               favorite, status, link, cli_tool_id, updated_at, last_viewed_at
        FROM worktrees_backup;

        -- 5. Drop backup
        DROP TABLE worktrees_backup;

        -- 6. Recreate indexes
        CREATE INDEX IF NOT EXISTS idx_worktrees_updated_at
        ON worktrees(updated_at DESC);

        CREATE INDEX IF NOT EXISTS idx_worktrees_repository
        ON worktrees(repository_path);

        CREATE INDEX IF NOT EXISTS idx_worktrees_favorite
        ON worktrees(favorite DESC, updated_at DESC);

        CREATE INDEX IF NOT EXISTS idx_worktrees_status
        ON worktrees(status);

        CREATE INDEX IF NOT EXISTS idx_worktrees_cli_tool
        ON worktrees(cli_tool_id);
      `),console.log("✓ Removed initial_branch column from worktrees table")}},{version:16,name:"add-issue-no-to-external-apps",up:e=>{e.exec(`
        ALTER TABLE external_apps ADD COLUMN issue_no INTEGER;
      `),e.exec(`
        CREATE INDEX IF NOT EXISTS idx_external_apps_issue_no ON external_apps(issue_no);
      `),console.log("✓ Added issue_no column to external_apps table"),console.log("✓ Created index idx_external_apps_issue_no")},down:e=>{e.exec(`
        -- 1. Create backup table without issue_no
        CREATE TABLE external_apps_backup AS
        SELECT id, name, display_name, description, path_prefix, target_port,
               target_host, app_type, websocket_enabled, websocket_path_pattern,
               enabled, created_at, updated_at
        FROM external_apps;

        -- 2. Drop original table (this also drops indexes)
        DROP TABLE external_apps;

        -- 3. Recreate table without issue_no
        CREATE TABLE external_apps (
          id TEXT PRIMARY KEY,
          name TEXT NOT NULL UNIQUE,
          display_name TEXT NOT NULL,
          description TEXT,
          path_prefix TEXT NOT NULL UNIQUE,
          target_port INTEGER NOT NULL,
          target_host TEXT DEFAULT 'localhost',
          app_type TEXT NOT NULL CHECK(app_type IN ('sveltekit', 'streamlit', 'nextjs', 'other')),
          websocket_enabled INTEGER DEFAULT 0,
          websocket_path_pattern TEXT,
          enabled INTEGER DEFAULT 1,
          created_at INTEGER NOT NULL,
          updated_at INTEGER NOT NULL
        );

        -- 4. Restore data
        INSERT INTO external_apps (id, name, display_name, description, path_prefix,
               target_port, target_host, app_type, websocket_enabled, websocket_path_pattern,
               enabled, created_at, updated_at)
        SELECT id, name, display_name, description, path_prefix,
               target_port, target_host, app_type, websocket_enabled, websocket_path_pattern,
               enabled, created_at, updated_at
        FROM external_apps_backup;

        -- 5. Drop backup
        DROP TABLE external_apps_backup;

        -- 6. Recreate original indexes
        CREATE INDEX idx_external_apps_path_prefix ON external_apps(path_prefix);
        CREATE INDEX idx_external_apps_enabled ON external_apps(enabled);
      `),console.log("✓ Removed issue_no column from external_apps table")}}];function E(e){let t=r(92048),s=e;for(;s!==i().dirname(s);){let e=i().join(s,".git");if(t.existsSync(e)){let r=t.statSync(e);if(r.isDirectory())return s;if(r.isFile()){let r=t.readFileSync(e,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(r)return r[1].split("/.git/")[0]}}s=i().dirname(s)}return e}function l(e){try{let t=e.prepare("SELECT MAX(version) as version FROM schema_version").get();return t?.version??0}catch{return 0}}var d=r(93346);let T=null;function p(){if(!T){let e=(0,d.dU)().CM_DB_PATH,t=r(92048),s=i().dirname(e);t.existsSync(s)||t.mkdirSync(s,{recursive:!0,mode:448}),function(e){!function(e){e.exec(`
    CREATE TABLE IF NOT EXISTS schema_version (
      version INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      applied_at INTEGER NOT NULL
    );
  `)}(e);let t=l(e);console.log(`Current schema version: ${t}`);let r=n.filter(e=>e.version>t);if(0===r.length){console.log("✓ Schema is up to date");return}for(let t of(console.log(`Found ${r.length} pending migration(s)`),r)){console.log(`Applying migration ${t.version}: ${t.name}...`);try{e.transaction(()=>{t.up(e),e.prepare(`
          INSERT INTO schema_version (version, name, applied_at)
          VALUES (?, ?, ?)
        `).run(t.version,t.name,Date.now())})(),console.log(`✓ Migration ${t.version} applied successfully`)}catch(r){let e=r instanceof Error?r.message:String(r);throw console.error(`✗ Migration ${t.version} failed:`,e),Error(`Migration ${t.version} (${t.name}) failed: ${e}`)}}console.log(`✓ All migrations completed. Current version: ${l(e)}`)}(T=new(a())(e))}return T}},75748:(e,t,r)=>{r.d(t,{DF:()=>b,Db:()=>h,ER:()=>_,Ek:()=>M,GA:()=>A,GP:()=>g,HE:()=>u,IH:()=>L,Mf:()=>R,Nf:()=>S,Nr:()=>U,OK:()=>I,Of:()=>T,Pv:()=>y,Q7:()=>F,R3:()=>D,S$:()=>O,VW:()=>k,Xv:()=>i,ZI:()=>X,_U:()=>c,_e:()=>f,dD:()=>x,gU:()=>n,j8:()=>w,ly:()=>E,pM:()=>v,qZ:()=>o,tn:()=>p,vX:()=>m,xr:()=>l,y:()=>d,zl:()=>N});var s=r(84770);function a(e){return{id:e.id,worktreeId:e.worktree_id,role:e.role,content:e.content,summary:e.summary||void 0,timestamp:new Date(e.timestamp),logFileName:e.log_file_name||void 0,requestId:e.request_id||void 0,messageType:e.message_type||"normal",promptData:e.prompt_data?JSON.parse(e.prompt_data):void 0,cliToolId:e.cli_tool_id??"claude"}}function o(e){e.exec(`
    CREATE TABLE IF NOT EXISTS worktrees (
      id TEXT PRIMARY KEY,
      name TEXT NOT NULL,
      path TEXT NOT NULL UNIQUE,
      last_message_summary TEXT,
      updated_at INTEGER
    );
  `),e.exec(`
    CREATE INDEX IF NOT EXISTS idx_worktrees_updated_at
    ON worktrees(updated_at DESC);
  `),e.exec(`
    CREATE TABLE IF NOT EXISTS chat_messages (
      id TEXT PRIMARY KEY,
      worktree_id TEXT NOT NULL,
      role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
      content TEXT NOT NULL,
      summary TEXT,
      timestamp INTEGER NOT NULL,
      log_file_name TEXT,
      request_id TEXT,
      message_type TEXT DEFAULT 'normal',
      prompt_data TEXT,
      cli_tool_id TEXT DEFAULT 'claude',

      FOREIGN KEY (worktree_id) REFERENCES worktrees(id) ON DELETE CASCADE
    );
  `),e.exec(`
    CREATE INDEX IF NOT EXISTS idx_messages_worktree_time
    ON chat_messages(worktree_id, timestamp DESC);
  `),e.exec(`
    CREATE INDEX IF NOT EXISTS idx_messages_request_id
    ON chat_messages(request_id);
  `),e.exec(`
    CREATE INDEX IF NOT EXISTS idx_messages_type
    ON chat_messages(message_type, worktree_id);
  `),e.exec(`
    CREATE INDEX IF NOT EXISTS idx_messages_cli_tool
    ON chat_messages(worktree_id, cli_tool_id, timestamp DESC);
  `),e.exec(`
    CREATE TABLE IF NOT EXISTS session_states (
      worktree_id TEXT NOT NULL,
      cli_tool_id TEXT NOT NULL DEFAULT 'claude',
      last_captured_line INTEGER DEFAULT 0,

      PRIMARY KEY (worktree_id, cli_tool_id),
      FOREIGN KEY (worktree_id) REFERENCES worktrees(id) ON DELETE CASCADE
    );
  `)}function i(e,t){let r=`
    SELECT
      w.id, w.name, w.path, w.repository_path, w.repository_name, w.description,
      w.last_user_message, w.last_user_message_at, w.last_message_summary,
      w.updated_at, w.favorite, w.status, w.link, w.cli_tool_id, w.last_viewed_at,
      (SELECT MAX(timestamp) FROM chat_messages
       WHERE worktree_id = w.id AND role = 'assistant') as last_assistant_message_at
    FROM worktrees w
  `,s=[];t&&(r+=" WHERE w.repository_path = ?",s.push(t)),r+=" ORDER BY w.updated_at DESC NULLS LAST";let a=e.prepare(r).all(...s),o=function(e,t){if(0===t.length)return new Map;let r=t.map(()=>"?").join(","),s=e.prepare(`
    WITH ranked_messages AS (
      SELECT
        worktree_id,
        cli_tool_id,
        content,
        ROW_NUMBER() OVER (
          PARTITION BY worktree_id, cli_tool_id
          ORDER BY timestamp DESC
        ) as rn
      FROM chat_messages
      WHERE worktree_id IN (${r})
        AND role = 'user'
        AND cli_tool_id IN ('claude', 'codex', 'gemini')
    )
    SELECT worktree_id, cli_tool_id, content
    FROM ranked_messages
    WHERE rn = 1
  `).all(...t),a=new Map;for(let e of t)a.set(e,{});for(let e of s){let t=a.get(e.worktree_id)||{};t[e.cli_tool_id]=e.content.substring(0,50),a.set(e.worktree_id,t)}return a}(e,a.map(e=>e.id));return a.map(e=>{let t=o.get(e.id)||{};return{id:e.id,name:e.name,path:e.path,repositoryPath:e.repository_path||"",repositoryName:e.repository_name||"",description:e.description||void 0,lastUserMessage:e.last_user_message||void 0,lastUserMessageAt:e.last_user_message_at?new Date(e.last_user_message_at):void 0,lastMessageSummary:e.last_message_summary||void 0,lastMessagesByCli:t,updatedAt:e.updated_at?new Date(e.updated_at):void 0,lastViewedAt:e.last_viewed_at?new Date(e.last_viewed_at):void 0,lastAssistantMessageAt:e.last_assistant_message_at?new Date(e.last_assistant_message_at):void 0,favorite:1===e.favorite,status:e.status||null,link:e.link||void 0,cliToolId:e.cli_tool_id??"claude"}})}function _(e){return e.prepare(`
    SELECT
      repository_path as path,
      repository_name as name,
      COUNT(*) as worktree_count
    FROM worktrees
    WHERE repository_path IS NOT NULL
    GROUP BY repository_path, repository_name
    ORDER BY repository_name ASC
  `).all().map(e=>({path:e.path,name:e.name,worktreeCount:e.worktree_count}))}function n(e,t){let r=e.prepare(`
    SELECT
      w.id, w.name, w.path, w.repository_path, w.repository_name, w.description,
      w.last_user_message, w.last_user_message_at, w.last_message_summary,
      w.updated_at, w.favorite, w.status, w.link, w.cli_tool_id, w.last_viewed_at,
      (SELECT MAX(timestamp) FROM chat_messages
       WHERE worktree_id = w.id AND role = 'assistant') as last_assistant_message_at
    FROM worktrees w
    WHERE w.id = ?
  `).get(t);return r?{id:r.id,name:r.name,path:r.path,repositoryPath:r.repository_path||"",repositoryName:r.repository_name||"",description:r.description||void 0,lastUserMessage:r.last_user_message||void 0,lastUserMessageAt:r.last_user_message_at?new Date(r.last_user_message_at):void 0,lastMessageSummary:r.last_message_summary||void 0,updatedAt:r.updated_at?new Date(r.updated_at):void 0,lastViewedAt:r.last_viewed_at?new Date(r.last_viewed_at):void 0,lastAssistantMessageAt:r.last_assistant_message_at?new Date(r.last_assistant_message_at):void 0,favorite:1===r.favorite,status:r.status||null,link:r.link||void 0,cliToolId:r.cli_tool_id??"claude"}:null}function E(e,t){e.prepare("DELETE FROM worktrees WHERE path = ? AND id != ?").run(t.path,t.id),e.prepare(`
    INSERT INTO worktrees (
      id, name, path, repository_path, repository_name, description,
      last_user_message, last_user_message_at, last_message_summary, updated_at, cli_tool_id
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT(id) DO UPDATE SET
      name = excluded.name,
      path = excluded.path,
      repository_path = excluded.repository_path,
      repository_name = excluded.repository_name,
      description = COALESCE(excluded.description, worktrees.description),
      last_user_message = COALESCE(excluded.last_user_message, worktrees.last_user_message),
      last_user_message_at = COALESCE(excluded.last_user_message_at, worktrees.last_user_message_at),
      last_message_summary = COALESCE(excluded.last_message_summary, worktrees.last_message_summary),
      updated_at = COALESCE(excluded.updated_at, worktrees.updated_at),
      cli_tool_id = COALESCE(excluded.cli_tool_id, worktrees.cli_tool_id)
  `).run(t.id,t.name,t.path,t.repositoryPath||null,t.repositoryName||null,t.description||null,t.lastUserMessage||null,t.lastUserMessageAt?.getTime()||null,t.lastMessageSummary||null,t.updatedAt?.getTime()||null,t.cliToolId||"claude")}function l(e,t,r){e.prepare(`
    UPDATE worktrees
    SET description = ?
    WHERE id = ?
  `).run(r||null,t)}function d(e,t,r){e.prepare(`
    UPDATE worktrees
    SET link = ?
    WHERE id = ?
  `).run(r||null,t)}function T(e,t,r){e.prepare(`
    UPDATE worktrees
    SET last_viewed_at = ?
    WHERE id = ?
  `).run(r.toISOString(),t)}function p(e,t){let r=(0,s.randomUUID)();return e.prepare(`
    INSERT INTO chat_messages
    (id, worktree_id, role, content, summary, timestamp, log_file_name, request_id, message_type, prompt_data, cli_tool_id)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(r,t.worktreeId,t.role,t.content,t.summary||null,t.timestamp.getTime(),t.logFileName||null,t.requestId||null,t.messageType||"normal",t.promptData?JSON.stringify(t.promptData):null,t.cliToolId||"claude"),function(e,t,r){e.prepare(`
    UPDATE worktrees
    SET updated_at = ?
    WHERE id = ?
  `).run(r.getTime(),t)}(e,t.worktreeId,t.timestamp),"user"===t.role&&I(e,t.worktreeId,t.content,t.timestamp),{id:r,...t}}function c(e,t,r,s=50,o){let i=`
    SELECT id, worktree_id, role, content, summary, timestamp, log_file_name, request_id, message_type, prompt_data, cli_tool_id
    FROM chat_messages
    WHERE worktree_id = ? AND (? IS NULL OR timestamp < ?)
  `,_=[t,r?.getTime()||null,r?.getTime()||null];return o&&(i+=" AND cli_tool_id = ?",_.push(o)),i+=" ORDER BY timestamp DESC LIMIT ?",_.push(s),e.prepare(i).all(..._).map(a)}function m(e,t){let r=e.prepare(`
    SELECT id, worktree_id, role, content, summary, timestamp, log_file_name, request_id, message_type, prompt_data, cli_tool_id
    FROM chat_messages
    WHERE worktree_id = ? AND role = 'user'
    ORDER BY timestamp DESC
    LIMIT 1
  `).get(t);return r?a(r):null}function u(e,t){e.prepare(`
    DELETE FROM chat_messages
    WHERE worktree_id = ?
  `).run(t),console.log(`[deleteAllMessages] Deleted all messages for worktree: ${t}`)}function N(e,t,r="claude"){let s=e.prepare(`
    SELECT worktree_id, cli_tool_id, last_captured_line, in_progress_message_id
    FROM session_states
    WHERE worktree_id = ? AND cli_tool_id = ?
  `).get(t,r);return s?{worktreeId:s.worktree_id,cliToolId:s.cli_tool_id,lastCapturedLine:s.last_captured_line,inProgressMessageId:s.in_progress_message_id||null}:null}function L(e,t,r,s){e.prepare(`
    INSERT INTO session_states (worktree_id, cli_tool_id, last_captured_line)
    VALUES (?, ?, ?)
    ON CONFLICT(worktree_id, cli_tool_id) DO UPDATE SET
      last_captured_line = excluded.last_captured_line
  `).run(t,r,s)}function R(e,t,r){!function(e,t,r,s){e.prepare(`
    INSERT INTO session_states (worktree_id, cli_tool_id, last_captured_line, in_progress_message_id)
    VALUES (?, ?, 0, ?)
    ON CONFLICT(worktree_id, cli_tool_id) DO UPDATE SET
      in_progress_message_id = excluded.in_progress_message_id
  `).run(t,r,null)}(e,t,r,0)}function w(e,t,r){r?e.prepare(`
      DELETE FROM session_states
      WHERE worktree_id = ? AND cli_tool_id = ?
    `).run(t,r):e.prepare(`
      DELETE FROM session_states
      WHERE worktree_id = ?
    `).run(t)}function I(e,t,r,s){let a=e.prepare(`
    UPDATE worktrees
    SET last_user_message = ?,
        last_user_message_at = ?
    WHERE id = ?
  `),o=r.substring(0,200);a.run(o,s.getTime(),t)}function O(e,t){let r=e.prepare(`
    SELECT id, worktree_id, role, content, summary, timestamp, log_file_name, request_id, message_type, prompt_data, cli_tool_id
    FROM chat_messages
    WHERE id = ?
  `).get(t);return r?a(r):null}function A(e,t,r){e.prepare(`
    UPDATE chat_messages
    SET prompt_data = ?
    WHERE id = ?
  `).run(JSON.stringify(r),t)}function g(e,t,r){let s=e.prepare(`
    SELECT id, prompt_data
    FROM chat_messages
    WHERE worktree_id = ?
      AND cli_tool_id = ?
      AND message_type = 'prompt'
      AND json_extract(prompt_data, '$.status') = 'pending'
    ORDER BY timestamp DESC
  `).all(t,r);if(0===s.length)return 0;let a=e.prepare(`
    UPDATE chat_messages
    SET prompt_data = ?
    WHERE id = ?
  `),o=0;for(let e of s)try{let t=JSON.parse(e.prompt_data);t.status="answered",t.answer="(answered via terminal)",t.answeredAt=new Date().toISOString(),a.run(JSON.stringify(t),e.id),o++}catch{}return o}function D(e,t,r){e.prepare(`
    UPDATE worktrees
    SET favorite = ?
    WHERE id = ?
  `).run(r?1:0,t)}function S(e,t,r){e.prepare(`
    UPDATE worktrees
    SET status = ?
    WHERE id = ?
  `).run(r,t)}function k(e,t,r){e.prepare(`
    UPDATE worktrees
    SET cli_tool_id = ?
    WHERE id = ?
  `).run(r,t)}function C(e){return{id:e.id,worktreeId:e.worktree_id,title:e.title,content:e.content,position:e.position,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function h(e,t){return e.prepare(`
    SELECT id, worktree_id, title, content, position, created_at, updated_at
    FROM worktree_memos
    WHERE worktree_id = ?
    ORDER BY position ASC
  `).all(t).map(C)}function X(e,t){let r=e.prepare(`
    SELECT id, worktree_id, title, content, position, created_at, updated_at
    FROM worktree_memos
    WHERE id = ?
  `).get(t);return r?C(r):null}function x(e,t,r){let a=(0,s.randomUUID)(),o=Date.now(),i=r.title??"Memo",_=r.content??"";return e.prepare(`
    INSERT INTO worktree_memos (id, worktree_id, title, content, position, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?)
  `).run(a,t,i,_,r.position,o,o),{id:a,worktreeId:t,title:i,content:_,position:r.position,createdAt:new Date(o),updatedAt:new Date(o)}}function U(e,t,r){let s=Date.now(),a=["updated_at = ?"],o=[s];void 0!==r.title&&(a.push("title = ?"),o.push(r.title)),void 0!==r.content&&(a.push("content = ?"),o.push(r.content)),o.push(t),e.prepare(`
    UPDATE worktree_memos
    SET ${a.join(", ")}
    WHERE id = ?
  `).run(...o)}function f(e,t){e.prepare(`
    DELETE FROM worktree_memos
    WHERE id = ?
  `).run(t)}function M(e,t,r){e.prepare(`
    UPDATE worktrees
    SET initial_branch = ?
    WHERE id = ?
  `).run(r,t)}function F(e,t){let r=e.prepare(`
    SELECT initial_branch
    FROM worktrees
    WHERE id = ?
  `).get(t);return r?.initial_branch??null}function y(e,t){return e.prepare(`
    SELECT id FROM worktrees WHERE repository_path = ?
  `).all(t).map(e=>e.id)}function b(e,t){return{deletedCount:e.prepare(`
    DELETE FROM worktrees WHERE repository_path = ?
  `).run(t).changes}}function v(e,t){if(0===t.length)return{deletedCount:0};let r=t.map(()=>"?").join(",");return{deletedCount:e.prepare(`
    DELETE FROM worktrees WHERE id IN (${r})
  `).run(...t).changes}}},93346:(e,t,r)=>{r.d(t,{dU:()=>m,Hb:()=>T,LI:()=>c});var s=r(55315),a=r.n(s),o=r(19801);function i(){let e=(0,s.dirname)(__dirname);return e.includes("/lib/node_modules/")||e.includes("\\node_modules\\")||e.includes("/node_modules/commandmate")}r(92048);let _=["/etc","/usr","/bin","/sbin","/var","/tmp","/dev","/sys","/proc"];function n(){return i()?a().join((0,o.homedir)(),".commandmate","data","cm.db"):a().resolve(process.cwd(),"data","cm.db")}function E(e){let t=a().resolve(e);if(i()){let e=(0,o.homedir)();if(!t.startsWith(e))throw Error(`Security error: DB path must be within home directory: ${t}`)}else if(_.some(e=>t.startsWith(e)))throw Error(`Security error: DB path cannot be in system directory: ${t}`);return t}let l={CM_ROOT_DIR:"MCBD_ROOT_DIR",CM_PORT:"MCBD_PORT",CM_BIND:"MCBD_BIND",CM_AUTH_TOKEN:"MCBD_AUTH_TOKEN",CM_LOG_LEVEL:"MCBD_LOG_LEVEL",CM_LOG_FORMAT:"MCBD_LOG_FORMAT",CM_LOG_DIR:"MCBD_LOG_DIR",CM_DB_PATH:"MCBD_DB_PATH"},d=new Set;function T(e){return function(e,t){let r=process.env[e];if(void 0!==r)return r;let s=process.env[t];if(void 0!==s)return d.has(t)||(console.warn(`[DEPRECATED] ${t} is deprecated, use ${e} instead`),d.add(t)),s}(e,l[e])}let p=!1;function c(){let e=T("CM_LOG_LEVEL")?.toLowerCase(),t=T("CM_LOG_FORMAT")?.toLowerCase();return{level:void 0!==e&&["debug","info","warn","error"].includes(e)?e:"info",format:"json"===t?"json":"text"}}function m(){let e;let t=T("CM_ROOT_DIR")||process.cwd(),r=parseInt(T("CM_PORT")||"3000",10),s=T("CM_BIND")||"127.0.0.1",o=T("CM_AUTH_TOKEN"),i=T("CM_DB_PATH")||function(){let e=process.env.DATABASE_PATH;return e&&!p&&(console.warn("[DEPRECATED] DATABASE_PATH is deprecated. Use CM_DB_PATH instead."),p=!0),e}()||n();if(!t)throw Error("CM_ROOT_DIR (or MCBD_ROOT_DIR) is required");if(isNaN(r)||r<1||r>65535)throw Error(`Invalid CM_PORT: ${T("CM_PORT")}. Must be between 1 and 65535.`);if("127.0.0.1"!==s&&"0.0.0.0"!==s&&"localhost"!==s)throw Error(`Invalid CM_BIND: ${s}. Must be '127.0.0.1', '0.0.0.0', or 'localhost'.`);if("0.0.0.0"===s&&!o)throw Error("CM_AUTH_TOKEN (or MCBD_AUTH_TOKEN) is required when CM_BIND=0.0.0.0");try{e=E(i)}catch{console.warn(`[Security] Invalid DB path "${i}", using default.`),e=E(n())}return{CM_ROOT_DIR:a().resolve(t),CM_PORT:r,CM_BIND:s,CM_AUTH_TOKEN:o,CM_DB_PATH:e}}}};