coding-agent-search 0.5.0

Unified TUI search over local coding agent histories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/**
 * cass Archive Crypto Worker
 *
 * Handles key derivation, DEK unwrapping, and chunk decryption in a Web Worker.
 * All expensive cryptographic operations run here to keep the main thread responsive.
 */

// State
let dek = null;
let config = null;

const MAX_ARCHIVE_CHUNK_SIZE = 32 * 1024 * 1024;
const MAX_ARCHIVE_CHUNKS = 0xFFFFFFFF;

function hashScopeId(input) {
    let hash = 0x811c9dc5;
    for (let i = 0; i < input.length; i++) {
        hash ^= input.charCodeAt(i);
        hash = Math.imul(hash, 0x01000193) >>> 0;
    }
    return hash.toString(16).padStart(8, '0');
}

function getArchiveScopeId() {
    try {
        return hashScopeId(new URL('./', self.location.href).href);
    } catch (error) {
        const href = typeof self?.location?.href === 'string'
            ? self.location.href
            : 'unknown';
        return hashScopeId(href.split('#')[0].split('?')[0]);
    }
}

function getArchiveOpfsDbName() {
    return `cass-archive-${getArchiveScopeId()}.db`;
}

/**
 * Handle messages from main thread
 */
self.onmessage = async (event) => {
    const payload = event?.data && typeof event.data === 'object' ? event.data : null;
    const requestId = payload && 'requestId' in payload ? payload.requestId : null;
    if (!payload || typeof payload.type !== 'string' || payload.type.length === 0) {
        console.warn('Ignoring malformed worker request payload');
        if (requestId !== null && requestId !== undefined) {
            self.postMessage({
                type: 'WORKER_ERROR',
                error: 'Malformed worker request payload',
                requestId,
            });
        }
        return;
    }

    const { type, ...data } = payload;

    try {
        switch (type) {
            case 'UNLOCK_PASSWORD':
                await handleUnlockPassword(data.password, data.config, requestId);
                break;

            case 'UNLOCK_RECOVERY':
                await handleUnlockRecovery(data.recoverySecret, data.config, requestId);
                break;

            case 'DECRYPT_DATABASE':
                await handleDecryptDatabase(data.dek, data.config, data.opfsEnabled, requestId);
                break;

            case 'CLEAR_KEYS':
                clearKeys();
                break;

            default:
                throw new Error(`Unknown worker message type: ${type}`);
        }
    } catch (error) {
        console.error('Worker error:', error);
        self.postMessage({
            type: getWorkerFailureMessageType(type),
            error: error?.message || String(error),
            requestId,
        });
    }
};

function getWorkerFailureMessageType(type) {
    switch (type) {
        case 'UNLOCK_PASSWORD':
        case 'UNLOCK_RECOVERY':
            return 'UNLOCK_FAILED';
        case 'DECRYPT_DATABASE':
            return 'DECRYPT_FAILED';
        default:
            return 'WORKER_ERROR';
    }
}

/**
 * Handle password-based unlock
 */
async function handleUnlockPassword(password, cfg, requestId) {
    config = cfg;
    validateSupportedPayloadFormat(config);

    // Find password slot
    const passwordSlots = config.key_slots.filter(s => s.slot_type === 'password');
    if (passwordSlots.length === 0) {
        throw new Error('No password slot found in archive');
    }

    self.postMessage({ type: 'PROGRESS', phase: 'Deriving key...', percent: 10, requestId });

    // Try each password slot
    for (const slot of passwordSlots) {
        try {
            const kek = await deriveKekFromPassword(password, slot);
            self.postMessage({ type: 'PROGRESS', phase: 'Unwrapping key...', percent: 80, requestId });

            const unwrappedDek = await unwrapDek(kek, slot, config.export_id);
            dek = unwrappedDek;

            self.postMessage({
                type: 'UNLOCK_SUCCESS',
                dek: arrayToBase64(dek),
                requestId,
            });
            return;
        } catch (error) {
            // Try next slot
            console.debug('Slot unlock failed:', error);
        }
    }

    throw new Error('Incorrect password');
}

/**
 * Handle recovery secret-based unlock
 */
async function handleUnlockRecovery(recoverySecret, cfg, requestId) {
    config = cfg;
    validateSupportedPayloadFormat(config);

    // Find recovery slot
    const recoverySlots = config.key_slots.filter(s => s.slot_type === 'recovery');
    if (recoverySlots.length === 0) {
        throw new Error('No recovery slot found in archive');
    }

    self.postMessage({ type: 'PROGRESS', phase: 'Deriving key...', percent: 10, requestId });

    // Convert recovery secret to bytes
    let secretBytes;
    if (typeof recoverySecret === 'string') {
        // Try base64 first, then UTF-8
        try {
            secretBytes = base64ToArray(recoverySecret);
        } catch {
            secretBytes = new TextEncoder().encode(recoverySecret);
        }
    } else {
        secretBytes = recoverySecret;
    }

    // Try each recovery slot
    for (const slot of recoverySlots) {
        try {
            const kek = await deriveKekFromRecovery(secretBytes, slot);
            self.postMessage({ type: 'PROGRESS', phase: 'Unwrapping key...', percent: 80, requestId });

            const unwrappedDek = await unwrapDek(kek, slot, config.export_id);
            dek = unwrappedDek;

            self.postMessage({
                type: 'UNLOCK_SUCCESS',
                dek: arrayToBase64(dek),
                requestId,
            });
            return;
        } catch (error) {
            // Try next slot
            console.debug('Recovery slot unlock failed:', error);
        }
    }

    throw new Error('Invalid recovery code');
}

/**
 * Derive KEK from password using Argon2id
 */
async function deriveKekFromPassword(password, slot) {
    const params = slot.argon2_params || config.kdf_defaults;
    const salt = base64ToArray(slot.salt);

    // Load Argon2 if not loaded
    if (!self.argon2) {
        await loadArgon2();
    }

    const result = await self.argon2.hash({
        pass: password,
        salt: salt,
        time: params.iterations,
        mem: params.memory_kb,
        parallelism: params.parallelism,
        hashLen: 32,
        type: self.argon2.ArgonType.Argon2id,
    });

    return new Uint8Array(result.hash);
}

/**
 * Derive KEK from recovery secret using HKDF-SHA256
 */
async function deriveKekFromRecovery(secretBytes, slot) {
    const salt = base64ToArray(slot.salt);
    const info = new TextEncoder().encode('cass-pages-kek-v2');

    // Import secret as HKDF key
    const baseKey = await crypto.subtle.importKey(
        'raw',
        secretBytes,
        'HKDF',
        false,
        ['deriveBits']
    );

    // Derive KEK
    const kekBits = await crypto.subtle.deriveBits(
        {
            name: 'HKDF',
            hash: 'SHA-256',
            salt: salt,
            info: info,
        },
        baseKey,
        256
    );

    return new Uint8Array(kekBits);
}

/**
 * Unwrap DEK using AES-256-GCM
 */
async function unwrapDek(kek, slot, exportId) {
    const wrappedDek = base64ToArray(slot.wrapped_dek);
    const nonce = base64ToArray(slot.nonce);
    const exportIdBytes = base64ToArray(exportId);

    // Build AAD: export_id || slot_id
    const aad = new Uint8Array(exportIdBytes.length + 1);
    aad.set(exportIdBytes);
    aad[exportIdBytes.length] = slot.id;

    // Import KEK
    const kekKey = await crypto.subtle.importKey(
        'raw',
        kek,
        { name: 'AES-GCM' },
        false,
        ['decrypt']
    );

    // Unwrap DEK
    const dekBytes = await crypto.subtle.decrypt(
        {
            name: 'AES-GCM',
            iv: nonce,
            additionalData: aad,
        },
        kekKey,
        wrappedDek
    );

    return new Uint8Array(dekBytes);
}

/**
 * Handle database decryption
 */
async function handleDecryptDatabase(dekBase64, cfg, opfsEnabled, requestId) {
    config = cfg;
    validateSupportedPayloadFormat(config);
    dek = base64ToArray(dekBase64);
    const { payload } = config;
    const totalChunks = payload.chunk_count;
    const baseNonce = base64ToArray(config.base_nonce);
    const exportId = base64ToArray(config.export_id);

    self.postMessage({ type: 'PROGRESS', phase: 'Decrypting...', percent: 0, requestId });

    // Import DEK for decryption
    const dekKey = await crypto.subtle.importKey(
        'raw',
        dek,
        { name: 'AES-GCM' },
        false,
        ['decrypt']
    );

    // Decrypt and decompress each chunk. Rust writes one independent deflate
    // stream per encrypted chunk, so concatenating compressed streams before
    // inflate would drop data in browsers/engines that stop at the first stream.
    const plaintextChunks = [];
    let totalDecrypted = 0;

    for (let i = 0; i < totalChunks; i++) {
        const chunkName = `chunk-${String(i).padStart(5, '0')}.bin`;
        const expectedChunkPath = `payload/${chunkName}`;
        if (payload.files[i] !== expectedChunkPath) {
            throw new Error(`Invalid payload file entry ${i}: expected ${expectedChunkPath}`);
        }
        const chunkUrl = `./payload/${chunkName}`;

        try {
            const response = await fetch(chunkUrl);
            if (!response.ok) {
                throw new Error(`Failed to fetch chunk ${i}: ${response.status}`);
            }
            const encryptedChunk = await response.arrayBuffer();

            // Derive chunk nonce: first 8 bytes from base_nonce, last 4 bytes are counter
            const chunkNonce = deriveChunkNonce(baseNonce, i);

            // Build chunk AAD: export_id || chunk_index (big-endian u32)
            const aad = buildChunkAad(exportId, i);

            // Decrypt chunk
            const decrypted = await crypto.subtle.decrypt(
                {
                    name: 'AES-GCM',
                    iv: chunkNonce,
                    additionalData: aad,
                },
                dekKey,
                encryptedChunk
            );

            const plaintext = await decompressDeflate(new Uint8Array(decrypted));
            plaintextChunks.push(plaintext);
            totalDecrypted += plaintext.byteLength;

            // Report progress
            const percent = Math.round(((i + 1) / totalChunks) * 90);
            self.postMessage({
                type: 'PROGRESS',
                phase: `Decrypting chunk ${i + 1}/${totalChunks}...`,
                percent: percent,
                requestId,
            });
        } catch (error) {
            throw new Error(`Failed to decrypt chunk ${i}: ${error.message}`);
        }
    }

    self.postMessage({ type: 'PROGRESS', phase: 'Loading database...', percent: 95, requestId });

    // Store in OPFS or memory
    const dbBytes = concatenateChunks(plaintextChunks);

    const transfer = dbBytes.buffer.slice(
        dbBytes.byteOffset,
        dbBytes.byteOffset + dbBytes.byteLength
    );

    self.postMessage(
        {
            type: 'DECRYPT_SUCCESS',
            dbSize: dbBytes.byteLength,
            dbBytes: transfer,
            requestId,
        },
        [transfer]
    );
}

function validateSupportedPayloadFormat(cfg) {
    if (!cfg || typeof cfg !== 'object') {
        throw new Error('Invalid archive config');
    }

    if (cfg.version !== 2) {
        throw new Error(`Unsupported archive schema version: ${cfg.version ?? 'missing'}`);
    }

    if (cfg.compression !== 'deflate') {
        throw new Error(`Unsupported archive compression: ${cfg.compression ?? 'missing'}`);
    }

    const payload = cfg.payload;
    if (!payload || typeof payload !== 'object') {
        throw new Error('Invalid archive payload metadata');
    }

    if (!Number.isSafeInteger(payload.chunk_size) || payload.chunk_size <= 0) {
        throw new Error(`Invalid archive chunk_size: ${payload.chunk_size ?? 'missing'}`);
    }

    if (payload.chunk_size > MAX_ARCHIVE_CHUNK_SIZE) {
        throw new Error(`Invalid archive chunk_size: ${payload.chunk_size} exceeds maximum ${MAX_ARCHIVE_CHUNK_SIZE}`);
    }

    if (!Number.isSafeInteger(payload.chunk_count) || payload.chunk_count < 0) {
        throw new Error(`Invalid archive chunk_count: ${payload.chunk_count ?? 'missing'}`);
    }

    if (payload.chunk_count > MAX_ARCHIVE_CHUNKS) {
        throw new Error(`Invalid archive chunk_count: ${payload.chunk_count} exceeds maximum`);
    }

    if (!Array.isArray(payload.files) || payload.files.length !== payload.chunk_count) {
        throw new Error('Invalid archive payload files list');
    }
}

/**
 * Derive chunk nonce from base nonce and counter.
 * Uses deterministic counter mode: first 8 bytes from base_nonce,
 * last 4 bytes are the chunk index (big-endian).
 */
function deriveChunkNonce(baseNonce, counter) {
    const nonce = new Uint8Array(12);
    // Copy first 8 bytes from base nonce
    nonce.set(baseNonce.subarray(0, 8));

    // Set last 4 bytes to counter (big-endian u32)
    const counterView = new DataView(new ArrayBuffer(4));
    counterView.setUint32(0, counter, false); // big-endian
    const counterBytes = new Uint8Array(counterView.buffer);
    nonce.set(counterBytes, 8);

    return nonce;
}

/**
 * Build chunk AAD: export_id || chunk_index || schema_version
 * Must match Rust's build_chunk_aad for interoperability
 */
function buildChunkAad(exportId, chunkIndex) {
    const SCHEMA_VERSION = 2;
    const aad = new Uint8Array(exportId.length + 4 + 1); // 16 + 4 + 1 = 21 bytes
    aad.set(exportId);

    // Big-endian u32 chunk index
    const view = new DataView(aad.buffer, exportId.length, 4);
    view.setUint32(0, chunkIndex, false);

    // Schema version byte
    aad[exportId.length + 4] = SCHEMA_VERSION;

    return aad;
}

/**
 * Concatenate array of Uint8Arrays
 */
function concatenateChunks(chunks) {
    const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
    const result = new Uint8Array(totalLength);

    let offset = 0;
    for (const chunk of chunks) {
        result.set(chunk, offset);
        offset += chunk.byteLength;
    }

    return result;
}

/**
 * Decompress deflate data
 */
async function decompressDeflate(compressed) {
    // Use fflate if available, otherwise DecompressionStream
    if (self.fflate?.inflateSync) {
        return self.fflate.inflateSync(compressed);
    }

    // Try native DecompressionStream (Chrome 80+, Firefox 113+, Safari 16.4+)
    if (self.DecompressionStream) {
        const ds = new DecompressionStream('deflate-raw');
        const writer = ds.writable.getWriter();
        const reader = ds.readable.getReader();

        writer.write(compressed);
        writer.close();

        const chunks = [];
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            chunks.push(value);
        }

        return concatenateChunks(chunks);
    }

    // Fallback: load fflate
    await loadFflate();
    return self.fflate.inflateSync(compressed);
}

/**
 * Initialize sqlite-wasm with decrypted database
 */
async function initDatabase(dbBytes, opfsEnabled, requestId) {
    // Load sqlite-wasm if not loaded
    if (!self.sqlite3) {
        await loadSqlite();
    }

    try {
        // Initialize sqlite-wasm
        const sqlite3 = await self.sqlite3InitModule();

        // Try OPFS first (persistent, better performance) if user opted in
        let db;
        if (opfsEnabled && sqlite3.oo1.OpfsDb) {
            try {
                const opfsDbName = getArchiveOpfsDbName();
                // Write to OPFS
                const opfs = await navigator.storage.getDirectory();
                const fileHandle = await opfs.getFileHandle(opfsDbName, { create: true });
                const writable = await fileHandle.createWritable();
                await writable.write(dbBytes);
                await writable.close();

                db = new sqlite3.oo1.OpfsDb(opfsDbName);
            } catch (opfsError) {
                console.warn('OPFS not available, using in-memory:', opfsError);
                db = new sqlite3.oo1.DB();
                db.deserialize(dbBytes);
            }
        } else {
            // In-memory database
            db = new sqlite3.oo1.DB();
            db.deserialize(dbBytes);
        }

        // Store database reference
        self.cassDb = db;

        self.postMessage({
            type: 'DB_READY',
            conversationCount: getConversationCount(db),
            messageCount: getMessageCount(db),
            requestId,
        });
    } catch (error) {
        throw new Error(`Failed to initialize database: ${error.message}`);
    }
}

/**
 * Get conversation count from database
 */
function getConversationCount(db) {
    try {
        const result = db.exec('SELECT COUNT(*) FROM conversations');
        return result[0]?.values[0][0] || 0;
    } catch {
        return 0;
    }
}

/**
 * Get message count from database
 */
function getMessageCount(db) {
    try {
        const result = db.exec('SELECT COUNT(*) FROM messages');
        return result[0]?.values[0][0] || 0;
    } catch {
        return 0;
    }
}

/**
 * Clear keys from memory
 */
function clearKeys() {
    if (dek) {
        // Zero out the DEK
        dek.fill(0);
        dek = null;
    }
    config = null;

    // Close database
    if (self.cassDb) {
        try {
            self.cassDb.close();
        } catch {
            // Ignore
        }
        self.cassDb = null;
    }
}

/**
 * Load Argon2 library
 */
async function loadArgon2() {
    try {
        importScripts('./vendor/argon2-wasm.js');
    } catch (error) {
        throw new Error('Failed to load Argon2 library. Ensure argon2-wasm.js is in the vendor folder.');
    }
}

/**
 * Load fflate library
 */
async function loadFflate() {
    try {
        importScripts('./vendor/fflate.min.js');
    } catch (error) {
        throw new Error('Failed to load decompression library.');
    }
}

/**
 * Load sqlite-wasm library
 */
async function loadSqlite() {
    try {
        importScripts('./vendor/sqlite3.js');
    } catch (error) {
        throw new Error('Failed to load SQLite library.');
    }
}

/**
 * Convert base64 to Uint8Array
 */
function base64ToArray(base64) {
    const normalized = normalizeBase64(base64);
    const binary = atob(normalized);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
}

function normalizeBase64(base64) {
    const trimmed = base64.trim().replace(/-/g, '+').replace(/_/g, '/');
    const padding = trimmed.length % 4;
    if (padding === 0) {
        return trimmed;
    }
    return trimmed + '='.repeat(4 - padding);
}

/**
 * Convert Uint8Array to base64
 */
function arrayToBase64(bytes) {
    let binary = '';
    for (let i = 0; i < bytes.length; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}