Repository navigation
Expand file tree
/
Copy pathsession-cache.js
More file actions
1956 lines (1850 loc) · 93.3 KB
/
Copy pathsession-cache.js
File metadata and controls
1956 lines (1850 loc) · 93.3 KB
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const fs = require('fs');
const { performance } = require('node:perf_hooks');
const { Worker: NativeWorker } = require('worker_threads');
const scanWorkers = new Set();
const subsetScans = new Set();
let stopping = false;
class Worker extends NativeWorker {
constructor(...args) {
super(...args);
scanWorkers.add(this);
this.once('exit', () => scanWorkers.delete(this));
}
}
async function shutdownProducers() {
stopping = true;
clearTimeout(populateRetryTimer);
populateRetryTimer = null;
clearTimeout(_activityTimer);
clearTimeout(_notifyTimer);
_activityTimer = null;
_notifyTimer = null;
_notifyCooldown = false;
_notifyCauses.clear();
await Promise.all([...scanWorkers].map(worker => worker.terminate()));
await Promise.allSettled([...subsetScans, populatePromise, entrypointBackfill, customTitleBackfill].filter(Boolean));
}
const { getFolderIndexMtimeMs } = require('./folder-index-state');
const { getHarness, DEFAULT_HARNESS, harnessForFolder, prefixedHarnesses, harnessFolderIndexMtimeMs } = require('./harnesses');
const { setRemappedProjectReader } = require('./encode-project-path');
const { deriveProjectPath, storedProjectPathMatchesFolder, resolveWorktreePath } = require('./derive-project-path');
const { readSessionFile, readSessionDisplayHeader, readSessionEntrypoint, isSdkEntrypoint, enumerateSessionFiles, resolveJsonlPath, mergeBridgeGroups, isCanonicalWorkflowPath } = require('./read-session-file');
const { classifyTranscriptPath, isWorkflowRunId } = require('./subagent-attribution');
const { readMessageCount } = require('./src/main/session-index/message-count');
const { encodeProjectPath, decodeProjectFolderBestEffort } = require('./encode-project-path');
const { parseFolderKey, joinFolderKey } = require('./src/main/remote/remote-hosts');
const { isPanelShellSession } = require('./src/main/terminals/panel-terminal-target');
const { SETTING_DEFAULTS } = require('./public/setting-defaults');
const { scanContinuationIndex, resolveContinuations, validId, continuationStamp, matchesContinuationStamp, continuationMtime, continuationRollup } = require('./session-continuations');
const { mergeLocalBackgroundSessions, conversationGroups, conversationMemberIds: resolveConversationMemberIds, scopedConversationRows } = require('./sidebar-bg-sessions');
const { projectionScope } = require('./public/session-projection-diagnostics');
const { conversationMeta } = require('./conversation-meta');
const { cleanDisplayName } = require('./public/utils');
const { isHostedJob } = require('./src/main/bg-agents/bg-agents-roster');
const { state: TRACE, trace } = require('./src/main/shared/activity-trace');
const { fullIndexConfig, SESSION_CONTENT_INDEX_VERSION, matchesFullRead, observation, nameDerivationWitness, sourceRelativePath, startupInventoryMatches, deferStartupSources } = require('./src/main/session-index/full-read-state');
/**
* Session cache module.
* Call init(ctx) once with the shared context object.
*/
let PROJECTS_DIR, activeSessions, getMainWindow, log, writer;
let isProjectWriteBlocked;
let deleteCachedFolder, getCachedByFolder, upsertCachedSessions, deleteCachedSession, touchCachedModified, setCachedFileSize, replaceSessionMetrics;
let deleteSearchFolder, deleteSearchSession, upsertSearchEntries;
let setFolderMeta, getFolderMeta, getAllFolderMeta, getAllMeta, getAllCached, getSetting, setSetting, getMeta, setName;
let isInitialScanComplete, setInitialScanComplete;
let cacheBackend;
let getCachedMissingEntrypoint, setCachedEntrypoints, getCachedSession, setCachedContinuationIndex;
let entrypointBackfill = null;
let getLocalDescriptors = () => [];
let getLocalJobs = () => new Map();
let setCachedCustomTitles, getCachedMissingCustomTitle;
let customTitleBackfill = null;
const continuationFiles = new Map();
const deferredContinuationFiles = new Map();
const deferredContinuationVersions = new Map();
let nextDeferralVersion = 0;
const CONTINUATION_BYTE_BUDGET = 1024 * 1024;
function continuationRefreshScope(folder, opts = {}) {
if (!(opts.files instanceof Set) || !opts.files.size) return opts;
return { ...opts, files: new Set([...opts.files, ...(deferredContinuationFiles.get(folder) || [])]) };
}
function applyContinuationRefresh(folder, collector, committed = false) {
const outstanding = new Set(deferredContinuationFiles.get(folder) || []);
for (const file of collector.deferred) {
outstanding.add(file);
deferredContinuationVersions.set(folder + '\0' + file, ++nextDeferralVersion);
}
if (committed) for (const file of collector.accounted) {
const key = folder + '\0' + file;
if (collector.versions && collector.versions.get(file) !== deferredContinuationVersions.get(key)) continue;
outstanding.delete(file);
deferredContinuationVersions.delete(key);
}
if (outstanding.size) deferredContinuationFiles.set(folder, outstanding);
else deferredContinuationFiles.delete(folder);
}
function linkedContinuation(row) {
if (row.parentSessionId || parseFolderKey(row.folder).alias !== null) return false;
try {
const index = JSON.parse(row.continuationIndex);
return index?.format === 3 && index.version === 3 && Array.isArray(index.ids) && index.ids.length > 0;
} catch { return false; }
}
function changedContinuation(row, file, stat) {
const snapshot = continuationFiles.get(file);
if (snapshot?.serialized === row.continuationIndex) return !sameContinuationStamp(snapshot, stat);
let stamp;
try { stamp = JSON.parse(row.continuationIndex)?.stamp; } catch {}
return stamp ? !matchesContinuationStamp(stamp, stat)
: row.fileMtime !== continuationMtime(stat);
}
async function scanContinuationFile(file, id, previous, chunkBytes = CONTINUATION_BYTE_BUDGET) {
if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1) throw new RangeError('chunkBytes must be a positive integer');
chunkBytes = Math.min(chunkBytes, CONTINUATION_BYTE_BUDGET);
let serialized = previous, index, stat, grew;
let bytes = 0;
do {
serialized = scanCachedContinuation(file, id, serialized, chunkBytes);
if (serialized === null) return null;
index = JSON.parse(serialized);
stat = continuationFiles.get(file);
await new Promise(resolve => setImmediate(resolve));
const after = fs.statSync(file, { bigint: true });
grew = sameContinuationFile(stat, after) && after.size > stat.size;
if (!sameContinuationStamp(stat, after) && !grew) {
continuationFiles.delete(file);
return null;
}
if (index.bytes <= bytes && (grew || (!index.complete && index.bytes < index.size))) {
continuationFiles.delete(file);
return null;
}
bytes = index.bytes;
} while (grew || (!index.complete && index.bytes < index.size));
return { serialized, stat };
}
async function prepareContinuationRefresh(folder, opts = {}) {
opts = continuationRefreshScope(folder, opts);
const prepared = new Map(), folderPath = resolveFolderDir(folder);
if (!folderPath || parseFolderKey(folder).alias !== null) return prepared;
for (const row of getCachedByFolder(folder)) {
if (!linkedContinuation(row)) continue;
const file = resolveJsonlPath(folderPath, { ...row, folder: '.' });
if (opts.files?.size && !opts.files.has(path.relative(folderPath, file))) continue;
try {
const stat = fs.statSync(file, { bigint: true });
if (!changedContinuation(row, file, stat)) continue;
const previous = row.continuationIndex;
const result = await scanContinuationFile(file, row.sessionId, previous);
prepared.set(row.sessionId, result && { ...result, previous });
} catch (error) {
log?.warn?.(`[session-cache] ${row.sessionId} continuation read failed: ${error.message}`, error);
prepared.set(row.sessionId, null);
}
}
return prepared;
}
function sameContinuationFile(a, b) {
return a?.dev === b.dev && a.ino === b.ino && a.birthtimeNs === b.birthtimeNs;
}
function sameContinuationStamp(a, b) {
return sameContinuationFile(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs;
}
function continuationHead(file, size, maxBytes = 64) {
const fd = fs.openSync(file, 'r');
const buffer = Buffer.alloc(Math.min(64, Number(size), maxBytes));
try { return buffer.toString('hex', 0, fs.readSync(fd, buffer, 0, buffer.length, 0)); }
finally { fs.closeSync(fd); }
}
function rememberContinuation(file, stat, head, serialized) {
continuationFiles.delete(file);
continuationFiles.set(file, { dev: stat.dev, ino: stat.ino, birthtimeNs: stat.birthtimeNs,
size: stat.size, mtimeNs: stat.mtimeNs, head, serialized });
while (continuationFiles.size > 128) continuationFiles.delete(continuationFiles.keys().next().value);
}
function resumesPersistedContinuation(previous, stat, head) {
let index;
try { index = JSON.parse(previous); } catch { return false; }
const stamp = index?.stamp;
if (matchesContinuationStamp(stamp, stat)) return true;
if (!stamp || typeof index.head !== 'string' || !head.startsWith(index.head)) return false;
try {
return stamp.dev === stat.dev.toString() && stamp.ino === stat.ino.toString()
&& stamp.birthtimeNs === stat.birthtimeNs.toString() && BigInt(stamp.size) < stat.size;
} catch { return false; }
}
// see .ai/contexts/session-cache.md ("Continuation index")
function scanCachedContinuation(file, id, previous, maxBytes, stat = fs.statSync(file, { bigint: true })) {
const cached = continuationFiles.get(file);
const head = continuationHead(file, stat.size, Math.max(0, maxBytes - 1));
const reuse = cached?.serialized === previous && sameContinuationFile(cached, stat)
? sameContinuationStamp(cached, stat) || (stat.size > cached.size && head.startsWith(cached.head))
: resumesPersistedContinuation(previous, stat, head);
let serialized = scanContinuationIndex(file, id, reuse ? previous : undefined, maxBytes - head.length / 2);
const after = fs.statSync(file, { bigint: true });
if (!sameContinuationStamp(stat, after)) { continuationFiles.delete(file); return null; }
serialized = JSON.stringify({ ...JSON.parse(serialized), stamp: continuationStamp(stat), head,
mtime: continuationMtime(stat) });
rememberContinuation(file, stat, head, serialized);
return serialized;
}
function init(ctx) {
continuationFiles.clear();
deferredContinuationFiles.clear();
deferredContinuationVersions.clear();
stopping = false;
clearTimeout(populateRetryTimer);
populateRetryTimer = null;
populateRetry = null;
forcePopulateFollowup = false;
populateNow = ctx.now || Date.now;
PROJECTS_DIR = ctx.PROJECTS_DIR;
cacheBackend = ctx.db;
isProjectWriteBlocked = ctx.isProjectWriteBlocked;
activeSessions = ctx.activeSessions;
getLocalDescriptors = ctx.getLocalDescriptors || (() => []);
getLocalJobs = ctx.getLocalJobs || (() => new Map());
setCachedCustomTitles = ctx.db.setCachedCustomTitles;
getCachedMissingCustomTitle = ctx.db.getCachedMissingCustomTitle;
customTitleBackfill = null;
getMainWindow = ctx.getMainWindow;
log = ctx.log;
// DB functions
deleteCachedFolder = ctx.db.deleteCachedFolder;
getCachedByFolder = ctx.db.getCachedByFolder;
upsertCachedSessions = ctx.db.upsertCachedSessions;
touchCachedModified = ctx.db.touchCachedModified;
setCachedFileSize = ctx.db.setCachedFileSize;
deleteCachedSession = ctx.db.deleteCachedSession;
replaceSessionMetrics = ctx.db.replaceSessionMetrics;
deleteSearchFolder = ctx.db.deleteSearchFolder;
deleteSearchSession = ctx.db.deleteSearchSession;
upsertSearchEntries = ctx.db.upsertSearchEntries;
setFolderMeta = ctx.db.setFolderMeta;
getFolderMeta = ctx.db.getFolderMeta;
getAllFolderMeta = ctx.db.getAllFolderMeta;
getAllMeta = ctx.db.getAllMeta;
getAllCached = ctx.db.getAllCached;
getSetting = ctx.db.getSetting;
setSetting = ctx.db.setSetting;
setRemappedProjectReader((folder) => remappedProjectsSetting()[folder]);
getMeta = ctx.db.getMeta;
setName = ctx.db.setName;
isInitialScanComplete = ctx.db.isInitialScanComplete;
setInitialScanComplete = ctx.db.setInitialScanComplete;
getCachedMissingEntrypoint = ctx.db.getCachedMissingEntrypoint;
getCachedSession = ctx.db.getCachedSession;
setCachedContinuationIndex = ctx.db.setCachedContinuationIndex;
setCachedEntrypoints = ctx.db.setCachedEntrypoints;
entrypointBackfill = null;
lastReconcileAt = 0;
writer = ctx.writer || {
writeScannedFolder, writeScannedFolderPartial,
setCachedEntrypoints, setCachedCustomTitles, setCachedContinuationIndex,
setInitialScanComplete, setSetting,
};
}
function hasCollisionName(id) {
return getLocalDescriptors().some(d => d.sessionId?.toLowerCase() === id.toLowerCase() && d.nameSource === 'collision')
|| [...getLocalJobs().values()].some(job => job.sessionId?.toLowerCase() === id.toLowerCase() && job.nameSource === 'collision');
}
function setTranscriptName(id, name) {
if (!hasCollisionName(id)) setName(id, name, 'transcript');
}
// alias -> that host's mirrored projects root; empty unless one is declared.
let remoteRoots = new Map();
function setRemoteRoots(roots) {
remoteRoots = roots instanceof Map ? new Map(roots) : new Map();
}
function getRemoteRoots() {
return new Map(remoteRoots);
}
/** Absolute directory for a folder key, local or `<alias>::<folder>`.
* Returns null when the key names a host that is not declared. */
function resolveFolderDir(folderKey) {
const { alias, folder } = parseFolderKey(folderKey);
if (alias === null) return path.join(PROJECTS_DIR, folder);
const root = remoteRoots.get(alias);
return root ? path.join(root, folder) : null;
}
// readSessionFile is imported from read-session-file.js (shared with worker)
const warnedRejectedFolders = new Set();
function warnRejectedCwd(folder, cwd) {
if (warnedRejectedFolders.has(folder)) return;
warnedRejectedFolders.add(folder);
if (log && log.warn) log.warn(`[session-cache] no transcript of folder ${folder} has a cwd that encodes to it; first rejected cwd: ${JSON.stringify(cwd)}`);
}
// see .ai/contexts/session-cache.md ("A running session keeps its row")
const keptLiveRows = new Map();
function resetProjectsWorkerRetainedRows() { keptLiveRows.clear(); }
function getProjectsWorkerRetainedRows() { return [...keptLiveRows]; }
// see .ai/contexts/session-cache.md ("Projects query worker")
function applyProjectsWorkerEffects(result) {
const writers = { upsertCachedSessions, deleteCachedSession, deleteCachedFolder,
touchCachedModified, setCachedFileSize, setFolderMeta, setName, replaceSessionMetrics,
deleteSearchFolder, deleteSearchSession, upsertSearchEntries };
for (const { name, args } of result.effects) writers[name](...args);
for (const [id, folder] of result.keptLiveRows) keptLiveRows.set(id, folder);
}
function isRunningSession(sessionId) {
const s = activeSessions && activeSessions.get(sessionId);
return !!s && !s.exited && !s.isPlainTerminal;
}
function keepIfRunning(sessionId, folder) {
if (!isRunningSession(sessionId)) return false;
keptLiveRows.set(sessionId, folder);
return true;
}
function dropFolderRows(folder, { search = false, preserveFullIndex = false } = {}) {
const rows = getCachedByFolder(folder);
const dropped = rows.filter(r => !keepIfRunning(r.sessionId, folder));
if (dropped.length === rows.length) {
const hadProject = !!getFolderMeta?.(folder)?.projectPath;
deleteCachedFolder(folder, { preserveFullIndex });
if (search) deleteSearchFolder(folder);
return dropped.length > 0 || hadProject;
}
for (const { sessionId } of dropped) {
deleteCachedSession(sessionId);
if (search) deleteSearchSession(sessionId);
}
return dropped.length > 0;
}
function getRetainedFolder(sessionId) { return keptLiveRows.get(sessionId); }
function releaseLiveSession(sessionId, opts = {}) {
const folder = keptLiveRows.get(sessionId) ?? opts.retainedFolder;
if (folder === undefined || isRunningSession(sessionId)) return false;
if (opts.retainedFolder !== undefined && opts.retainedFolder !== folder) return false;
keptLiveRows.delete(sessionId);
refreshFolder(folder, opts);
return true;
}
function deriveFolderProjectPath(folderPath, folderKey, onIncomplete) {
const { alias, folder } = parseFolderKey(folderKey);
return deriveProjectPath(folderPath, folder, {
remote: alias !== null,
onRejected: (cwd) => warnRejectedCwd(folder, cwd),
onIncomplete,
});
}
function remappedProjectsSetting() {
const stored = getSetting ? getSetting('projectRemaps') : null;
return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {};
}
/** Read one folder from filesystem by scanning .jsonl files directly */
function readFolderFromFilesystem(folder) {
const folderPath = resolveFolderDir(folder);
if (!folderPath) return { projectPath: null, sessions: [] };
const projectPath = deriveFolderProjectPath(folderPath, folder);
if (!projectPath) return { projectPath: null, sessions: [] };
const sessions = [];
for (const { filePath, parentSessionId, workflowRunId } of enumerateSessionFiles(folderPath)) {
const s = readSessionFile(filePath, folder, projectPath, { parentSessionId, workflowRunId });
if (s) sessions.push(s);
}
// Merge compaction mirrors sharing a bridgeSessionId -- see mergeBridgeGroups.
// existingRows=[] (fresh scan): every group member is re-derived from scratch.
const reread = (sessionId, cutoff, excludedMessageUuids, excludedMessageSignatures) => readSessionFile(
path.join(folderPath, sessionId + '.jsonl'), folder, projectPath, { dedupeSinceTimestamp: cutoff, excludedMessageUuids, excludedMessageSignatures }
);
const { toUpsert } = mergeBridgeGroups([], sessions, reread);
return { projectPath, sessions: toUpsert };
}
// see .ai/contexts/session-cache.md ("Watcher notification rules")
const PROJECT_ROW_FIELDS = ['sessionId', 'folder', 'projectPath', 'summary', 'firstPrompt',
'created', 'slug', 'scheduleSlug', 'aiTitle', 'customTitle',
'parentSessionId', 'agentId', 'subagentType', 'description', 'workflowRunId', 'bridgeSessionId',
'mergedIntoSessionId', 'entrypoint'];
const PROJECT_META_FIELDS = ['name', 'starred', 'archived', 'nameSource', 'nameRevision'];
const PROJECT_ACTIVITY_FIELDS = ['modified', 'fileMtime', 'messageCount'];
function sidebarContinuation(row) {
if (row.parentSessionId || parseFolderKey(row.folder).alias !== null) return null;
let index;
try { index = JSON.parse(row.continuationIndex); } catch {}
if (!index) return null;
if (index.format !== 3 || !index.complete || index.unresolved || !Array.isArray(index.ids)
|| (row.fileMtime && index.mtime !== row.fileMtime)) return false;
return index.ids.length ? index.ids.map(id => String(id).toLowerCase()).sort() : null;
}
function sidebarRowState(row) {
if (!row) return null;
const meta = getMeta(row.sessionId, true);
return JSON.stringify([
...PROJECT_ROW_FIELDS.map(field => field === 'entrypoint' ? isSdkEntrypoint(row[field]) : row[field] || null),
...PROJECT_META_FIELDS.map(field => meta?.[field] || null), sidebarContinuation(row),
]);
}
// see .ai/contexts/session-cache.md ("Harness folders")
function refreshHarnessFolder(harness, folder) {
const dir = harness.folderPath(folder);
if (!dir || !fs.existsSync(dir)) return dropFolderRows(folder, { search: true });
const cached = new Map(getCachedByFolder(folder).map(row => [row.sessionId, row]));
const titles = harness.readSessionTitles ? harness.readSessionTitles() : null;
const files = harness.listTranscripts(dir);
const current = new Set();
const sessionsToUpsert = [];
const searchEntriesToUpsert = [];
for (const file of files) {
const sessionId = harness.sessionIdFromPath(file);
if (!sessionId) continue;
current.add(sessionId);
let stat;
try { stat = fs.statSync(file); } catch { continue; }
const row = cached.get(sessionId);
const title = titles instanceof Map ? titles.get(sessionId) || null : row?.aiTitle || null;
if (row && row.fileMtime === stat.mtime.toISOString() && (row.fileSize ?? null) === stat.size && (row.aiTitle || null) === title) continue;
const session = harness.readSessionFile(file, folder, null);
if (!session) continue;
sessionsToUpsert.push(session);
const name = getMeta(session.sessionId)?.name || session.customTitle || session.aiTitle || '';
searchEntriesToUpsert.push({ id: session.sessionId, type: 'session', folder,
title: (name ? name + ' ' : '') + session.summary, body: session.textContent });
}
let changed = false;
if (sessionsToUpsert.length) {
upsertCachedSessions(sessionsToUpsert);
for (const session of sessionsToUpsert) if (session.dailyMetrics) replaceSessionMetrics(session.sessionId, session.dailyMetrics);
for (const entry of searchEntriesToUpsert) deleteSearchSession(entry.id);
upsertSearchEntries(searchEntriesToUpsert);
changed = true;
}
for (const sessionId of cached.keys()) {
if (current.has(sessionId) || keepIfRunning(sessionId, folder)) continue;
deleteCachedSession(sessionId);
deleteSearchSession(sessionId);
changed = true;
}
setFolderMeta(folder, null, harnessFolderIndexMtimeMs(harness, dir, files));
return changed;
}
// see .ai/contexts/cli-harnesses.md ("Picker, toggles and settings")
function disabledHarnessIds() {
const disabled = getSetting ? getSetting('global')?.disabledHarnesses : null;
return Array.isArray(disabled) ? disabled : [];
}
function harnessReconciliationFolders(metaMap) {
const out = [];
for (const harness of prefixedHarnesses(disabledHarnessIds())) {
const listed = new Set(harness.listFolders());
for (const folder of metaMap.keys()) {
if (folder.startsWith(harness.folderPrefix) && !listed.has(folder)) out.push({ folder, refresh: true });
}
for (const folder of listed) {
const meta = metaMap.get(folder);
const dir = harness.folderPath(folder);
const refresh = !meta || !dir || harnessFolderIndexMtimeMs(harness, dir, harness.listTranscripts(dir)) > (meta.indexMtimeMs || 0);
out.push({ folder, refresh });
}
}
return out;
}
function refreshFolder(folder, opts = {}) {
if (pendingRepairFolders().includes(folder)) cacheBackend.invalidateFullIndex?.(folder);
const harness = harnessForFolder(folder);
if (harness.folderPrefix) return refreshHarnessFolder(harness, folder);
opts = continuationRefreshScope(folder, opts);
const collector = opts.continuationCollector || { deferred: new Set(), accounted: new Set() };
const clearDeferred = () => {
for (const file of deferredContinuationFiles.get(folder) || []) collector.accounted.add(file);
if (!opts.managedContinuations) applyContinuationRefresh(folder, collector, true);
};
// null when the key names a host no longer declared — treated as vanished.
const folderPath = resolveFolderDir(folder);
if (!folderPath || !fs.existsSync(folderPath)) {
clearDeferred();
return dropFolderRows(folder, { search: true });
}
// Reuse the previously-derived projectPath when its directory still exists.
// deriveProjectPath reads session JSONL heads, and refreshFolder runs on
// every watcher flush -- deriving each time is wasted I/O on hot folders.
// A vanished directory falls through to a fresh derive so the missing-
// project remap detection keeps working.
const knownMeta = getFolderMeta ? getFolderMeta(folder) : null;
let projectPath = knownMeta && knownMeta.projectPath && fs.existsSync(knownMeta.projectPath)
&& (parseFolderKey(folder).alias !== null || (storedProjectPathMatchesFolder(knownMeta.projectPath, folder)
&& resolveWorktreePath(knownMeta.projectPath) === knownMeta.projectPath))
? knownMeta.projectPath
: null;
let incomplete = false;
if (!projectPath) projectPath = deriveFolderProjectPath(folderPath, folder, () => { incomplete = true; });
if (!projectPath) {
clearDeferred();
const dropped = parseFolderKey(folder).alias === null && dropFolderRows(folder, { search: true });
setFolderMeta(folder, null, incomplete ? 0 : getFolderIndexMtimeMs(folderPath));
return !!dropped || !!knownMeta?.projectPath;
}
// Get what's currently cached for this folder.
// cachedMap: DB sessionId -> { modified, filePath } so we can do mtime comparison
// even for subagents whose DB sessionId differs from the on-disk filename.
// filePathToDbId: inverted index so the per-file lookup is O(1) -- without it,
// refreshing a folder with N cached sessions costs O(N^2) per flush (the watcher
// fires frequently while live Claude sessions append JSONL, freezing the main
// process for folders with thousands of subagents).
const cachedSessions = getCachedByFolder(folder);
// `folder` may carry an `<alias>::` prefix, which is not a path component.
const jsonlPathFor = (row) => resolveJsonlPath(folderPath, { ...row, folder: '.' });
const cachedMap = new Map();
const filePathToDbId = new Map();
for (const row of cachedSessions) {
const filePath = jsonlPathFor(row);
// Keep the full row so refresh can merge display-only header updates with
// unchanged fields (created, textContent) without re-reading
// the file body.
cachedMap.set(row.sessionId, { ...row, filePath });
filePathToDbId.set(filePath, row.sessionId);
}
// Targeted refresh: walk only the files the watcher said changed, not the
// entire folder. Skips enumerateSessionFiles (which does many readdirSyncs on
// every subagent subdir) and only stats the dirty files. Falls back to full
// walk when opts.files is omitted (bootstrap / folder-level events / cold
// delete-detection).
const regrouping = knownMeta?.projectPath && knownMeta.projectPath !== projectPath;
const targeted = !regrouping && opts.files instanceof Set && opts.files.size > 0;
let filesToScan;
if (targeted) {
filesToScan = [];
for (const rel of opts.files) {
const classified = classifyTranscriptPath(rel);
if (!classified || !isCanonicalWorkflowPath(folderPath, classified)) continue;
const filePath = path.join(folderPath, ...rel.split(/[\\/]/));
filesToScan.push({ filePath, ...classified });
}
} else {
filesToScan = enumerateSessionFiles(folderPath);
}
for (const file of deferredContinuationFiles.get(folder) || []) {
if (!fs.existsSync(path.join(folderPath, file))) collector.accounted.add(file);
}
let continuationBytesLeft = CONTINUATION_BYTE_BUDGET;
const currentIds = new Set();
let sidebarChanged = (knownMeta?.projectPath ?? null) !== projectPath;
let activityChanged = false;
// Collect all changes first, then batch DB writes to minimize lock duration
const sessionsToUpsert = [];
const searchEntriesToUpsert = [];
const namesToSet = [];
const sessionsToDelete = [];
const sessionsToTouch = [];
const sizesToAdopt = [];
const metricsToReplace = [];
const linkedVersions = new Map();
const countRecountMtimes = new Map();
// Full reads only (the "NEW file" branch below) -- kept separate from
// sessionsToUpsert so mergeBridgeGroups never sees a header-only-refreshed
// row and mistakes it for a safe-to-reread fresh read (it isn't: the whole
// point of header-only refresh is to avoid a full re-read of a live file).
const newFileReads = [];
// Refresh strategy:
// - NEW file (no cache row): full readSessionFile -- small at first turn,
// seeds session_cache + FTS body in one shot.
// - EXISTING file (already cached): header-only read (~256 KB / 500 lines).
// Updates display fields (summary, slug, titles, mtime) without reading
// the full body. Avoids re-reading 200+ MB live host-session JSONLs on
// every watcher flush. Side-effect: FTS body for live sessions goes
// stale until the next cold-start (acceptable trade-off).
// - Header read failing (truncated chunk, partial JSON): fall back to a
// mtime-only DB touch so the sidebar still reflects activity.
for (const { filePath, parentSessionId, workflowRunId } of filesToScan) {
let stat, fileMtime;
try {
stat = fs.statSync(filePath, { bigint: true });
fileMtime = continuationMtime(stat);
} catch {
collector.accounted.add(path.relative(folderPath, filePath));
continue;
}
const cachedDbId = filePathToDbId.get(filePath) || null;
const cachedEntry = cachedDbId ? cachedMap.get(cachedDbId) : null;
const fileSize = Number(stat.size);
const changedSize = cachedEntry && cachedEntry.fileSize != null && cachedEntry.fileSize !== fileSize;
if (cachedEntry && cachedEntry.fileSize == null) sizesToAdopt.push({ sessionId: cachedDbId, fileSize });
if (cachedDbId !== null) currentIds.add(cachedDbId);
const relativeFile = path.relative(folderPath, filePath);
const linked = cachedEntry && !parentSessionId && linkedContinuation(cachedEntry);
const changedLinked = linked && changedContinuation(cachedEntry, filePath, stat);
const plan = opts.preparedContinuations?.get(cachedDbId);
const validPlan = changedLinked && plan && plan.previous === cachedEntry.continuationIndex && sameContinuationStamp(plan.stat, stat);
const defer = () => {
collector.deferred.add(relativeFile);
if (opts.continuationRetry) log?.info?.(`[session-cache] ${cachedDbId} continuation-refresh-raced`);
};
// Invalidation compares against the dedicated fileMtime column, not
// `modified`. Upstream split the two (v7 migration): `modified` now holds
// the last *message* timestamp for display, so it no longer tracks the
// file's mtime and can't serve as the change-detection key. Comparing
// `modified` here would miss on nearly every row and re-read every dirty
// file on every watcher flush.
const snapshot = continuationFiles.get(filePath);
let persistedStamp;
if (!snapshot) {
try { persistedStamp = JSON.parse(cachedEntry?.continuationIndex)?.stamp; } catch {}
}
const changedIndex = snapshot ? !sameContinuationStamp(snapshot, stat)
: persistedStamp && !matchesContinuationStamp(persistedStamp, stat);
if (!changedLinked && !changedSize && cachedEntry && cachedEntry.fileMtime === fileMtime && cachedEntry.projectPath === projectPath
&& (!cachedEntry.continuationIndex || !changedIndex || parentSessionId || cachedEntry.parentSessionId)) {
collector.accounted.add(relativeFile);
continue; // unchanged, skip
}
const fullReadPinned = changedSize && !linked && cachedEntry.fileMtime === fileMtime && fileSize <= continuationBytesLeft;
if (fullReadPinned) continuationBytesLeft = 0;
if (cachedEntry && !fullReadPinned) {
let continuationIndex = cachedEntry.continuationIndex;
if (validPlan) continuationIndex = plan.serialized;
else if (opts.preparedContinuations?.has(cachedDbId) && changedLinked) { defer(); continue; }
else if (parentSessionId || cachedEntry.parentSessionId) continuationIndex = null;
else if (continuationBytesLeft) {
continuationIndex = scanCachedContinuation(filePath, cachedEntry.sessionId, continuationIndex, continuationBytesLeft, stat);
continuationBytesLeft = 0;
} else if (changedIndex) continuationIndex = null;
if (changedLinked) {
let index;
try { index = JSON.parse(continuationIndex); } catch {}
if (!index || index.bytes !== Number(stat.size) || !matchesContinuationStamp(index.stamp, stat)) { defer(); continue; }
}
if (!changedSize && cachedEntry.fileMtime === fileMtime && cachedEntry.projectPath === projectPath
&& continuationIndex === cachedEntry.continuationIndex) { collector.accounted.add(relativeFile); continue; }
// EXISTING -- header-only refresh.
const h = readSessionDisplayHeader(filePath, { parentSessionId, workflowRunId });
let count = readMessageCount(filePath, cachedEntry.messageCountIndex, stat,
!!(cachedEntry.mergedIntoSessionId || (cachedEntry.bridgeSessionId && !cachedEntry.messageCountIndex)), parseFolderKey(folder).alias !== null);
collector.accounted.add(relativeFile);
if (linked) linkedVersions.set(cachedDbId, { stat, filePath, relativeFile });
if (count?.needsFullRead) {
const s = readSessionFile(filePath, folder, projectPath, { parentSessionId, workflowRunId });
if (s) {
newFileReads.push(s);
countRecountMtimes.set(s.sessionId, fileMtime);
continue;
}
count = null;
}
if (h) {
const merged = {
...cachedEntry,
...count,
fullReadStamp: null,
continuationIndex,
folder, projectPath,
summary: h.summary || cachedEntry.summary,
firstPrompt: h.firstPrompt || cachedEntry.firstPrompt,
// The header read only sees the first 256 KB of the transcript, so it
// cannot know the last message timestamp that upstream's `modified`
// now means. Keep bumping `modified` to the file mtime here so live
// sessions still sort to the top of the sidebar; the cold-start full
// read (readSessionFile) corrects it to the real last-message time.
// Same class of trade-off as the stale-FTS-body note above.
modified: fileMtime,
fileMtime,
fileSize,
slug: h.slug || cachedEntry.slug,
scheduleSlug: h.scheduleSlugComplete ? h.scheduleSlug : h.scheduleSlug || cachedEntry.scheduleSlug,
aiTitle: h.aiTitle || cachedEntry.aiTitle,
customTitle: h.tailTitle || cachedEntry.customTitle || h.headTitle,
parentSessionId: h.parentSessionId || cachedEntry.parentSessionId,
workflowRunId: h.workflowRunId || cachedEntry.workflowRunId,
agentId: h.agentId || cachedEntry.agentId,
subagentType: h.subagentType || cachedEntry.subagentType,
description: h.description || cachedEntry.description,
};
// see .ai/contexts/session-cache.md ("SDK-launched sessions")
if (isSdkEntrypoint(cachedEntry.entrypoint)) {
merged.entrypoint = readSessionEntrypoint(filePath) ?? cachedEntry.entrypoint;
}
sessionsToUpsert.push(merged);
if (merged.customTitle && merged.customTitle !== cachedEntry.customTitle) {
namesToSet.push({ id: merged.sessionId, name: merged.customTitle });
}
} else {
// Header read couldn't extract signal -- just bump mtime so sort order
// stays current. fileMtime has to move too, otherwise this file stays
// permanently "dirty" and gets re-read on every watcher flush.
if (count || changedSize || continuationIndex !== cachedEntry.continuationIndex) {
sessionsToUpsert.push({ ...cachedEntry, ...count, fullReadStamp: null, continuationIndex, modified: fileMtime, fileMtime, fileSize });
} else sessionsToTouch.push({ sessionId: cachedDbId, fileMtime });
}
continue;
}
// NEW file -- full readSessionFile so the FTS index gets seeded. Search
// entry / metrics / name are built AFTER merge resolution below, from
// whatever object actually survives (a compaction mirror's raw read here
// may still be replaced by a cutoff-filtered re-derivation, or dropped).
const s = readSessionFile(filePath, folder, projectPath, { parentSessionId, workflowRunId });
if (s) {
if (!parentSessionId && s.continuationIndex) {
const head = continuationHead(filePath, stat.size);
const after = fs.statSync(filePath, { bigint: true });
if (sameContinuationStamp(stat, after)) rememberContinuation(filePath, stat, head, s.continuationIndex);
else s.continuationIndex = null;
}
currentIds.add(s.sessionId);
newFileReads.push(s);
}
collector.accounted.add(relativeFile);
}
// Remove sessions whose .jsonl files were deleted. Skip in targeted mode --
// we only stat'd the dirty files, so cachedMap entries not in currentIds
// weren't checked and may still exist on disk. Targeted-mode deletions are
// handled by the watcher path-stat: missing files surface via statSync's
// ENOENT in the loop above and produce no upsert. A full walk picks up any
// drift on the next folder-level event.
if (!targeted) {
for (const sessionId of cachedMap.keys()) {
if (!currentIds.has(sessionId) && !keepIfRunning(sessionId, folder)) {
sessionsToDelete.push(sessionId);
}
}
} else {
// Targeted mode still needs to delete entries for files explicitly deleted
// in this flush -- detected by statSync failing on a path we tried to scan.
for (const { filePath } of filesToScan) {
const dbId = filePathToDbId.get(filePath);
if (!dbId) continue;
try { fs.statSync(filePath); } catch {
if (keepIfRunning(dbId, folder)) continue;
sessionsToDelete.push(dbId);
}
}
}
// Merge compaction mirrors sharing a bridgeSessionId -- see mergeBridgeGroups.
// Only newFileReads (this pass's full reads) are eligible for re-derivation;
// cachedSessions is the folder's full pre-refresh state, independent of
// `targeted`, so an already-cached parent is recognised without re-reading it.
const reread = (sessionId, cutoff, excludedMessageUuids, excludedMessageSignatures) => readSessionFile(
jsonlPathFor({ folder, sessionId }), folder, projectPath, { dedupeSinceTimestamp: cutoff, excludedMessageUuids, excludedMessageSignatures }
);
const deletedBridges = new Set(cachedSessions.filter(row => sessionsToDelete.includes(row.sessionId)).map(row => row.bridgeSessionId).filter(Boolean));
for (const row of cachedSessions) {
if (row.parentSessionId || !deletedBridges.has(row.bridgeSessionId) || sessionsToDelete.includes(row.sessionId)) continue;
if (newFileReads.some(fresh => fresh.sessionId === row.sessionId)) continue;
const full = reread(row.sessionId, null);
if (full) newFileReads.push(full);
}
const { toUpsert: mergedRows, toDelete: mergeDeletes } = newFileReads.length
? mergeBridgeGroups(cachedSessions.filter(row => !sessionsToDelete.includes(row.sessionId)), newFileReads, reread)
: { toUpsert: [], toDelete: [] };
// Now that merge resolution is final, build the search entry / metrics /
// name-set for each surviving row -- a plain fresh read, OR an
// already-cached member re-derived because its recorded mergedIntoSessionId
// disagreed with the winner just computed (see mergeBridgeGroups).
for (const s of mergedRows) {
if (countRecountMtimes.has(s.sessionId)) {
s.modified = countRecountMtimes.get(s.sessionId);
s.fullReadStamp = null;
}
sessionsToUpsert.push(s);
metricsToReplace.push({ sessionId: s.sessionId, dailyMetrics: s.dailyMetrics });
const name = getMeta(s.sessionId)?.name || s.customTitle || s.aiTitle || '';
searchEntriesToUpsert.push({
id: s.sessionId, type: 'session', folder: s.folder,
title: (name ? name + ' ' : '') + s.summary, body: s.textContent,
});
if (s.customTitle) namesToSet.push({ id: s.sessionId, name: s.customTitle });
}
// An already-cached member whose re-derivation found nothing surviving the
// newly-applicable cutoff must be removed outright -- leaving its old,
// pre-cutoff row in place would keep the exact double-count this fix exists
// to close.
sessionsToDelete.push(...mergeDeletes);
const racedRows = new Set([...collector.deferred].map(file => filePathToDbId.get(path.join(folderPath, file))).filter(Boolean));
for (const [id, observed] of linkedVersions) {
let current;
try { current = fs.statSync(observed.filePath, { bigint: true }); } catch {}
if (current && sameContinuationStamp(observed.stat, current)) continue;
racedRows.add(id);
collector.accounted.delete(observed.relativeFile);
collector.deferred.add(observed.relativeFile);
if (opts.continuationRetry) log?.info?.(`[session-cache] ${id} continuation-refresh-raced`);
}
for (let i = sessionsToUpsert.length - 1; i >= 0; i--) if (racedRows.has(sessionsToUpsert[i].sessionId)) sessionsToUpsert.splice(i, 1);
for (let i = namesToSet.length - 1; i >= 0; i--) if (racedRows.has(namesToSet[i].id)) namesToSet.splice(i, 1);
for (let i = metricsToReplace.length - 1; i >= 0; i--) if (racedRows.has(metricsToReplace[i].sessionId)) metricsToReplace.splice(i, 1);
for (let i = searchEntriesToUpsert.length - 1; i >= 0; i--) if (racedRows.has(searchEntriesToUpsert[i].id)) searchEntriesToUpsert.splice(i, 1);
for (let i = sessionsToDelete.length - 1; i >= 0; i--) if (racedRows.has(sessionsToDelete[i])) sessionsToDelete.splice(i, 1);
const updatedRows = new Map(sessionsToUpsert.map(row => [row.sessionId, row]));
const beforeRows = new Map([...updatedRows.keys()].map(id => [id, sidebarRowState(cachedMap.get(id))]));
// Batch all DB writes to reduce lock contention
if (sessionsToUpsert.length > 0) {
stripBridgeEvidence(sessionsToUpsert);
upsertCachedSessions(sessionsToUpsert);
}
for (const { sessionId, fileSize } of sizesToAdopt) {
if (!racedRows.has(sessionId) && !updatedRows.has(sessionId) && !sessionsToDelete.includes(sessionId)) setCachedFileSize(sessionId, fileSize);
}
for (const { sessionId, fileMtime } of sessionsToTouch) {
if (racedRows.has(sessionId)) continue;
const before = cachedMap.get(sessionId);
if (before.modified !== fileMtime || before.fileMtime !== fileMtime) activityChanged = true;
touchCachedModified(sessionId, fileMtime);
}
for (const { sessionId, dailyMetrics } of metricsToReplace) {
replaceSessionMetrics(sessionId, dailyMetrics);
}
for (const entry of searchEntriesToUpsert) {
deleteSearchSession(entry.id);
}
if (searchEntriesToUpsert.length > 0) {
upsertSearchEntries(searchEntriesToUpsert);
}
for (const { id, name } of namesToSet) {
setTranscriptName(id, name);
}
for (const sessionId of sessionsToDelete) {
if (keepIfRunning(sessionId, folder)) continue;
if (cachedMap.has(sessionId)) sidebarChanged = true;
deleteCachedSession(sessionId);
deleteSearchSession(sessionId);
}
// Update folder mtime
const outstanding = new Set([...(deferredContinuationFiles.get(folder) || []), ...collector.deferred]);
for (const file of collector.accounted) outstanding.delete(file);
setFolderMeta(folder, projectPath, outstanding.size ? 0 : getFolderIndexMtimeMs(folderPath));
if (!opts.managedContinuations) applyContinuationRefresh(folder, collector, true);
if (sidebarChanged || [...updatedRows].some(([id, row]) => beforeRows.get(id) !== sidebarRowState(row))) return true;
if (activityChanged || [...updatedRows].some(([id, row]) =>
PROJECT_ACTIVITY_FIELDS.some(field => row[field] !== cachedMap.get(id)?.[field]))) return 'activity';
return false;
}
// see .ai/contexts/session-cache.md ("Projects query worker")
const RECONCILE_THROTTLE_MS = 5000;
let lastReconcileAt = 0;
function reconciliationFolders(throttle) {
const now = Date.now();
if (throttle && now - lastReconcileAt < RECONCILE_THROTTLE_MS) return [];
lastReconcileAt = now;
const metaMap = getAllFolderMeta();
if (disabledHarnessIds().includes(DEFAULT_HARNESS)) return harnessReconciliationFolders(metaMap);
const ghostFolders = new Set(getAllCached().filter(row => {
if (row.parentSessionId || !row.sessionId.startsWith('agent-') || parseFolderKey(row.folder).alias !== null) return false;
try { fs.statSync(path.join(PROJECTS_DIR, row.folder, row.sessionId + '.jsonl')); return false; } catch { return true; }
}).map(row => row.folder));
let projectDirs = [];
try { projectDirs = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true }); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
return projectDirs
.filter(d => d.isDirectory() && d.name !== '.git')
.filter(d => {
if (!isProjectWriteBlocked) return true;
const stored = metaMap.get(d.name)?.projectPath;
const projectPath = stored && storedProjectPathMatchesFolder(stored, d.name)
? stored : deriveFolderProjectPath(path.join(PROJECTS_DIR, d.name), d.name);
return !isProjectWriteBlocked(null, projectPath);
})
.map(d => {
const folder = d.name, meta = metaMap.get(folder);
const refresh = ghostFolders.has(folder) || !meta || getFolderIndexMtimeMs(path.join(PROJECTS_DIR, folder)) > (meta.indexMtimeMs || 0)
|| (meta.projectPath && (!storedProjectPathMatchesFolder(meta.projectPath, folder)
|| resolveWorktreePath(meta.projectPath) !== meta.projectPath));
return { folder, refresh };
})
.concat(harnessReconciliationFolders(metaMap));
}
async function reconcileCacheFromFilesystemAsync({ onFolder, throttle = true } = {}) {
try {
for (const { folder, refresh } of reconciliationFolders(throttle)) {
try {
if (refresh) {
for (let attempt = 0; attempt < 2; attempt++) {
const preparedContinuations = await prepareContinuationRefresh(folder);
const continuationCollector = { deferred: new Set(), accounted: new Set() };
refreshFolder(folder, { preparedContinuations, continuationCollector, continuationRetry: attempt === 1 });
if (!continuationCollector.deferred.size) break;
}
}
if (onFolder) onFolder(folder);
} catch (err) {
console.error('Error reconciling cache:', err);
}
}
} catch (err) {
console.error('Error reconciling cache:', err);
}
}
function reconcileCacheFromFilesystem({ onFolder, throttle = true } = {}) {
try {
for (const { folder, refresh } of reconciliationFolders(throttle)) {
if (refresh) refreshFolder(folder);
if (onFolder) onFolder(folder);
}
} catch (err) {
console.error('Error reconciling cache:', err);
}
}
const ENTRYPOINT_BACKFILL_BATCH = 200;
// see .ai/contexts/session-cache.md ("SDK-launched sessions")
function backfillEntrypoints() {
if (stopping) return Promise.resolve();
if (entrypointBackfill) return entrypointBackfill;
entrypointBackfill = new Promise((resolve, reject) => {
const rows = getCachedMissingEntrypoint ? getCachedMissingEntrypoint() : [];
let next = 0;
let sdkFound = false;
const step = async () => {
const pairs = [];
const end = Math.min(next + ENTRYPOINT_BACKFILL_BATCH, rows.length);
for (; next < end; next++) {
const row = rows[next];
const dir = resolveFolderDir(row.folder);
if (!dir) continue;
const entrypoint = readSessionEntrypoint(resolveJsonlPath(dir, { ...row, folder: '.' }), { full: true });
if (entrypoint === null) continue;
if (isSdkEntrypoint(entrypoint)) sdkFound = true;
pairs.push({ sessionId: row.sessionId, entrypoint });
}
if (pairs.length) await writer.setCachedEntrypoints(pairs);
if (next < rows.length) {
setImmediate(() => step().catch(reject));
return;
}
if (sdkFound) notifyRendererProjectsChanged('entrypoint-backfill');
resolve();
};
step().catch(reject);
});
return entrypointBackfill;
}
// see .ai/contexts/session-cache.md ("Local background sidebar rows")
function backfillCustomTitles() {
if (stopping) return Promise.resolve();
if (customTitleBackfill) return customTitleBackfill;
if (!setCachedCustomTitles || !getCachedMissingCustomTitle) return (customTitleBackfill = Promise.resolve());
const rows = getCachedMissingCustomTitle().filter(row => validId(row.sessionId) && parseFolderKey(row.folder).alias === null);
if (!rows.length) return (customTitleBackfill = Promise.resolve());
const files = rows.map(row => ({ sessionId: row.sessionId, fileMtime: row.fileMtime,
file: resolveJsonlPath(resolveFolderDir(row.folder), { ...row, folder: '.' }) }));
customTitleBackfill = new Promise(resolve => {
let worker, settled = false;
const finish = ok => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(ok);
};
const timer = setTimeout(() => { worker?.terminate(); finish(false); }, SUBSET_SCAN_TIMEOUT_MS);
try {
worker = new Worker(path.join(__dirname, 'workers', 'scan-session-titles.js'), { workerData: { files } });
} catch (err) {
log.warn(`Title backfill failed: ${err.message}`);
finish(false);
return;
}
let writes = Promise.resolve();
worker.on('message', pairs => {