@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Automatic sync scheduling for DSH增强.
3
+ *
4
+ * Three triggers share one serial runner:
5
+ * - interval: every N minutes (settings.syncIntervalMinutes, 0 = off)
6
+ * - daily: one run per day at HH:MM (settings.syncDailyAt)
7
+ * - idle: the first time every agent leaves the running state
8
+ *
9
+ * A run never starts while a session is running, never overlaps another run, and
10
+ * backs off after repeated failures. The engine itself stays the PowerShell
11
+ * script; this module only decides when to call it.
12
+ */
13
+ import { promises as fsp } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { readSettings } from './trash.js';
16
+ import { runSync } from './sync.js';
17
+ import { restartApplication } from './restart.js';
18
+
19
+ const TICK_MS = 60_000;
20
+ const IDLE_DELAY_MS = 30_000;
21
+ const FAILURE_LIMIT = 3;
22
+
23
+ function localDateKey(date) {
24
+ return `${String(date.getFullYear())}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
25
+ }
26
+
27
+ function localClock(date) {
28
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
29
+ }
30
+
31
+ /** Local timestamp with offset, e.g. 2026-11-04 15:17:25+08:00 (human-readable log). */
32
+ function localStamp(date) {
33
+ const pad = (value) => String(value).padStart(2, '0');
34
+ const offset = -date.getTimezoneOffset();
35
+ const sign = offset >= 0 ? '+' : '-';
36
+ const hours = pad(Math.floor(Math.abs(offset) / 60));
37
+ const minutes = pad(Math.abs(offset) % 60);
38
+ return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${sign}${hours}${minutes}`;
39
+ }
40
+
41
+ /**
42
+ * Install the scheduler.
43
+ * @param ctx - owning Cordis context.
44
+ * @param deps - resolved paths and the agent registry.
45
+ * @returns disposer that clears every timer and listener.
46
+ */
47
+ export function installSyncScheduler(ctx, deps) {
48
+ const { paths, agents } = deps;
49
+ // One small trace file makes "why did it not run" answerable without a debugger.
50
+ // It is trimmed to the newest 500 lines so it can stay on permanently.
51
+ const traceFile = path.join(paths.base, 'scheduler.log');
52
+ const TRACE_MAX_LINES = 500;
53
+ let traceWrites = 0;
54
+ const trimTrace = async () => {
55
+ try {
56
+ const text = await fsp.readFile(traceFile, 'utf8');
57
+ const lines = text.split('\n');
58
+ if (lines.length <= TRACE_MAX_LINES + 20) return;
59
+ const kept = lines.slice(-(TRACE_MAX_LINES + 1));
60
+ await fsp.writeFile(traceFile, kept.join('\n'), 'utf8');
61
+ } catch {
62
+ // Tracing is diagnostic only; never let it interfere.
63
+ }
64
+ };
65
+ const trace = (message) => {
66
+ void (async () => {
67
+ try {
68
+ await fsp.appendFile(traceFile, `${localStamp(new Date())} ${message}\n`, 'utf8');
69
+ traceWrites += 1;
70
+ if (traceWrites % 20 === 0) await trimTrace();
71
+ } catch {
72
+ // Ignore: the log is best effort.
73
+ }
74
+ })();
75
+ };
76
+ void trimTrace();
77
+ trace(`install agents=${agents === undefined ? 'missing' : 'ok'} syncDir=${String(deps.settings?.syncDir ?? '')}`);
78
+ let tick = null;
79
+ let idleTimer = null;
80
+ let retryTimer = null;
81
+ let disposed = false;
82
+ let running = false;
83
+ // Subscribers are told about start and finish so a reader can follow the run
84
+ // without polling.
85
+ const watchers = new Set();
86
+ const notifyWatchers = () => {
87
+ for (const watcher of [...watchers]) {
88
+ try {
89
+ watcher();
90
+ } catch {
91
+ // A broken watcher must not affect the run.
92
+ }
93
+ }
94
+ };
95
+ let cooldownUntil = 0;
96
+ let failures = 0;
97
+ let paused = false;
98
+ let pausedAt = null;
99
+ let lastIntervalAt = 0;
100
+ let lastDailyKey = '';
101
+
102
+ const note = (message, level = 'warn') => {
103
+ const line = `dsh-enhanced sync: ${message}`;
104
+ const logger = ctx.logger;
105
+ if (logger !== undefined && typeof logger[level] === 'function') logger[level](line);
106
+ else if (level === 'error') console.error(line);
107
+ else console.warn(line);
108
+ };
109
+
110
+ const busy = () => {
111
+ try {
112
+ return (agents?.list?.() ?? []).some((agent) => agent?.status === 'running');
113
+ } catch {
114
+ return false;
115
+ }
116
+ };
117
+
118
+ /**
119
+ * Restart so newly synced sessions become visible, but only when nobody is
120
+ * working and the last automatic restart was long enough ago.
121
+ */
122
+ async function restartForNewSessions(record, context) {
123
+ const pulled = Number(record?.summary?.sessions?.pulled) || Number(record?.summary?.sessions?.created) || 0;
124
+ const repaired = Number(record?.summary?.blankGuard?.repaired) || 0;
125
+ const archiveChanged = Number(record?.summary?.archive?.changed) || 0;
126
+ // A repaired shard or a share-side archive change alters the list just like a
127
+ // new session does.
128
+ if (pulled <= 0 && repaired <= 0 && archiveChanged <= 0) return false;
129
+ const { paths, settings, agents } = context;
130
+ const busy = (agents?.list?.() ?? []).some((agent) => agent?.status === 'running');
131
+ if (busy) {
132
+ trace(`restart skipped: a session is running (${String(pulled)} new)`);
133
+ return false;
134
+ }
135
+ const marker = path.join(paths.base, 'restart-last.json');
136
+ let last = 0;
137
+ try {
138
+ const stored = JSON.parse(await fsp.readFile(marker, 'utf8'));
139
+ if (Number.isFinite(Number(stored?.at))) last = Number(stored.at);
140
+ } catch {
141
+ last = 0;
142
+ }
143
+ // Reuse the sync cooldown: it already describes how often this machine acts.
144
+ const gapMs = Math.max(0, Number(settings.syncCooldownMinutes) || 0) * 60_000;
145
+ if (last > 0 && Date.now() - last < gapMs) {
146
+ trace(`restart skipped: only ${String(Math.round((Date.now() - last) / 1000))}s since the last one`);
147
+ return false;
148
+ }
149
+ try {
150
+ await fsp.writeFile(marker, JSON.stringify({ at: Date.now(), pulled }), 'utf8');
151
+ } catch {
152
+ // A missing marker only means the next run may restart sooner.
153
+ }
154
+ trace(`restarting for ${String(pulled)} pulled / ${String(repaired)} repaired / ${String(archiveChanged)} archive`);
155
+ await restartApplication(paths);
156
+ return true;
157
+ }
158
+
159
+ async function autoRun(reason) {
160
+ if (disposed || running || paused) {
161
+ trace(`autoRun ${reason}: ignored (disposed=${String(disposed)} running=${String(running)} paused=${String(paused)})`);
162
+ return false;
163
+ }
164
+ if (Date.now() < cooldownUntil) {
165
+ trace(`autoRun ${reason}: cooldown until ${new Date(cooldownUntil).toISOString()}`);
166
+ // The cooldown is the only thing blocking; without this the run is lost,
167
+ // because an idle that lasts minutes produces no further idle edge.
168
+ if (retryTimer === null && !disposed) {
169
+ const delay = Math.max(1000, cooldownUntil - Date.now() + 500);
170
+ trace(`retry scheduled in ${String(Math.round(delay / 1000))}s (after cooldown)`);
171
+ retryTimer = setTimeout(() => {
172
+ retryTimer = null;
173
+ void autoRun('cooldown-retry');
174
+ }, delay);
175
+ }
176
+ return false;
177
+ }
178
+ let settings;
179
+ try {
180
+ settings = await readSettings(paths);
181
+ } catch {
182
+ trace(`autoRun ${reason}: settings unreadable`);
183
+ return false;
184
+ }
185
+ if (settings.syncEnabled !== true) {
186
+ trace(`autoRun ${reason}: syncEnabled is false`);
187
+ return false;
188
+ }
189
+ if (busy()) {
190
+ note(`${reason}: skipped, a session is running`);
191
+ trace(`autoRun ${reason}: skipped, a session is running`);
192
+ return false;
193
+ }
194
+ running = true;
195
+ notifyWatchers();
196
+ trace(`autoRun ${reason}: start`);
197
+ try {
198
+ const record = await runSync({ paths, settings, agents }, { probe: false });
199
+ if (record.ok === true) {
200
+ failures = 0;
201
+ note(`${reason}: ok in ${String(record.durationMs)} ms`, 'info');
202
+ await restartForNewSessions(record, { paths, settings, agents }).catch(() => {});
203
+ } else {
204
+ failures += 1;
205
+ paused = failures >= FAILURE_LIMIT;
206
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
207
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
208
+ note(`${reason}: failed (${String(failures)}/${String(FAILURE_LIMIT)})${paused ? ', auto sync paused' : ''}`, 'error');
209
+ }
210
+ } catch (error) {
211
+ if (error?.code === 'webdav-throttled') {
212
+ // The cloud asked us to back off: skip quietly instead of counting a failure.
213
+ const minutes = Math.max(1, Math.ceil((Number(error.until) - Date.now()) / 60_000));
214
+ note(`${reason}: throttled, waiting ${String(minutes)} min`, 'info');
215
+ trace(`autoRun ${reason}: throttled until ${new Date(Number(error.until)).toISOString()}`);
216
+ return false;
217
+ }
218
+ failures += 1;
219
+ paused = failures >= FAILURE_LIMIT;
220
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
221
+ trace(`autoRun ${reason} failed: ${String(error?.code ?? '')} ${String(error?.message ?? error)}`);
222
+ if (!paused && retryTimer === null) {
223
+ trace('retry scheduled in 60s');
224
+ retryTimer = setTimeout(() => {
225
+ retryTimer = null;
226
+ void autoRun('retry');
227
+ }, 60_000);
228
+ }
229
+ note(`${reason}: ${String(error?.message ?? error)}${paused ? ', auto sync paused' : ''}`, 'error');
230
+ } finally {
231
+ running = false;
232
+ notifyWatchers();
233
+ cooldownUntil = Date.now() + Math.max(1, Number(settings.syncCooldownMinutes) || 5) * 60_000;
234
+ }
235
+ }
236
+
237
+ async function onTick() {
238
+ if (disposed || paused) return;
239
+ let settings;
240
+ try {
241
+ settings = await readSettings(paths);
242
+ } catch {
243
+ return;
244
+ }
245
+ if (settings.syncEnabled !== true) return;
246
+
247
+ const now = new Date();
248
+ const intervalMinutes = Number(settings.syncIntervalMinutes) || 0;
249
+ if (intervalMinutes > 0) {
250
+ const due = lastIntervalAt === 0 ? false : Date.now() - lastIntervalAt >= intervalMinutes * 60_000;
251
+ if (due && (await autoRun('interval'))) lastIntervalAt = Date.now();
252
+ }
253
+
254
+ const dailyAt = typeof settings.syncDailyAt === 'string' ? settings.syncDailyAt : '';
255
+ if (dailyAt !== '' && localClock(now) === dailyAt && lastDailyKey !== localDateKey(now)) {
256
+ // 只有真的跑起来才记日期,被忙碌/草稿挡住时下一分钟还会再试
257
+ if (await autoRun('daily')) lastDailyKey = localDateKey(now);
258
+ }
259
+ }
260
+
261
+ /** Arm one idle run; a later idle edge (or an emptied composer) replaces it. */
262
+ function armIdle() {
263
+ if (idleTimer !== null) clearTimeout(idleTimer);
264
+ trace('idle armed (+30s)');
265
+ idleTimer = setTimeout(() => {
266
+ idleTimer = null;
267
+ trace('idle timer fired');
268
+ void autoRun('idle');
269
+ }, IDLE_DELAY_MS);
270
+ }
271
+
272
+ const status = () => ({ paused, failures, pausedAt, cooldownUntil, running });
273
+
274
+ /** Wake every waiting reader; the returned function unsubscribes. */
275
+ const subscribe = (watcher) => {
276
+ watchers.add(watcher);
277
+ return () => watchers.delete(watcher);
278
+ };
279
+
280
+ const resume = () => {
281
+ failures = 0;
282
+ paused = false;
283
+ pausedAt = null;
284
+ cooldownUntil = 0;
285
+ trace('auto sync resumed by the user');
286
+ return status();
287
+ };
288
+
289
+ // Launch-time catch-up is driven by the client, so the reader sees the restart
290
+ // countdown before the window closes. Host-side runs stay on idle/interval/daily.
291
+
292
+ const statusListener = ctx.on('agent/status', (payload) => {
293
+ trace(`agent/status=${String(payload?.status)}`);
294
+ if (payload?.status === 'running' && retryTimer !== null) {
295
+ clearTimeout(retryTimer);
296
+ retryTimer = null;
297
+ trace('retry cancelled: a new task started');
298
+ }
299
+ if (payload?.status !== 'idle') return;
300
+ armIdle();
301
+ });
302
+
303
+ tick = setInterval(() => { void onTick(); }, TICK_MS);
304
+
305
+ const dispose = () => {
306
+ disposed = true;
307
+ if (tick !== null) clearInterval(tick);
308
+ if (idleTimer !== null) clearTimeout(idleTimer);
309
+ if (retryTimer !== null) clearTimeout(retryTimer);
310
+ if (typeof statusListener === 'function') statusListener();
311
+ watchers.clear();
312
+ };
313
+
314
+ // Any caller (idle, archive, …) goes through autoRun, so the cooldown and its
315
+ // deferred retry apply to every trigger alike.
316
+ const trigger = (reason) => { void autoRun(reason); };
317
+
318
+ return { dispose, status, resume, subscribe, trigger };
319
+ }
package/host/search.js ADDED
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Full-corpus session text search for DSH增强.
3
+ *
4
+ * The shipped composition mounts `session-query-sqlite` with `openAt: never`
5
+ * and an in-memory index, so full-text search is off by default; its
6
+ * `unicode61` tokenizer would also split Chinese poorly. This module keeps its
7
+ * own derived text cache instead: one plain document per session, rebuilt only
8
+ * when the persistence revision changes, matched by literal substring.
9
+ *
10
+ * Nothing here writes to a session log or activates an Agent.
11
+ */
12
+ const MAX_SEGMENT_CHARS = 24000;
13
+ const MAX_MATCHES_PER_SESSION = Number.POSITIVE_INFINITY;
14
+ const MAX_TOTAL_MATCHES = 500;
15
+ const CONTEXT_CHARS = 42;
16
+ // The hover preview needs a readable passage, not just one line around the hit.
17
+ const PREVIEW_CHARS = 420;
18
+
19
+ /**
20
+ * Wrappers the app injects into a message but never shows in the conversation.
21
+ * Matching inside them would surface hits the reader cannot see on screen.
22
+ */
23
+ const HIDDEN_WRAPPERS = ['system-reminder', 'available_skills', 'compacted-summary'];
24
+
25
+ /**
26
+ * User-message sources the transcript actually renders. Everything else the log
27
+ * stores as a `user/message` is model-facing context: runtime snapshots, time
28
+ * stamps, skill catalogs, model switches, approval notes, background-job
29
+ * notices, and compaction checkpoints. Those never appear in the conversation,
30
+ * so indexing them would return hits the reader cannot see.
31
+ */
32
+ const VISIBLE_USER_SOURCES = new Set(['user', 'user-question-reply']);
33
+
34
+ /** True when a stored user message is one the transcript shows. */
35
+ function isVisibleUserMessage(message) {
36
+ const source = message?.source;
37
+ // Logs written before sources existed have no marker; keep them searchable.
38
+ if (source === null || typeof source !== 'object') return true;
39
+ return VISIBLE_USER_SOURCES.has(source.kind);
40
+ }
41
+
42
+ /** Drop hidden wrapper blocks (and stray closing tags) from one text block. */
43
+ function stripHidden(text) {
44
+ let out = text;
45
+ // Only a leading wrapper is model-facing context. A wrapper quoted inside
46
+ // prose or a fenced code block is visible content and stays searchable.
47
+ for (const tag of HIDDEN_WRAPPERS) {
48
+ const leading = new RegExp(`^\\s*<${tag}>[\\s\\S]*?</${tag}>`, 'iu');
49
+ while (leading.test(out)) out = out.replace(leading, ' ');
50
+ }
51
+ // A block that is only a closing tag belongs to a wrapper split across blocks.
52
+ if (/^<\/[a-z-]+>$/iu.test(out.trim())) return '';
53
+ return out;
54
+ }
55
+
56
+ /** Text blocks of one message, tolerating every message shape the log stores. */
57
+ function messageText(message) {
58
+ if (message === null || typeof message !== 'object') return '';
59
+ const content = message.content;
60
+ if (typeof content === 'string') return stripHidden(content).trim();
61
+ if (!Array.isArray(content)) return '';
62
+ const parts = [];
63
+ for (const block of content) {
64
+ if (block === null || typeof block !== 'object') continue;
65
+ if (block.type !== 'text' || typeof block.text !== 'string') continue;
66
+ const text = stripHidden(block.text);
67
+ if (text.trim() !== '') parts.push(text);
68
+ }
69
+ return parts.join('\n').trim();
70
+ }
71
+
72
+ function clip(text) {
73
+ if (text.length <= MAX_SEGMENT_CHARS) return text;
74
+ return text.slice(0, MAX_SEGMENT_CHARS);
75
+ }
76
+
77
+ /** Fold one stored log into the searchable shape, keeping seq for citations. */
78
+ function buildDocument(sessionId, header, events) {
79
+ const segments = [];
80
+ let title = '';
81
+ let updatedAt = typeof header.createdAt === 'number' ? header.createdAt : 0;
82
+ let firstUserText = '';
83
+ let turn = 0;
84
+ for (const event of events) {
85
+ if (event.type === 'turn/start' && typeof event.data?.turn === 'number') turn = event.data.turn;
86
+ if (typeof event.time === 'number' && event.time > updatedAt) updatedAt = event.time;
87
+ if (event.type === 'user/message') {
88
+ if (!isVisibleUserMessage(event.data)) continue;
89
+ const text = messageText(event.data);
90
+ if (text !== '') {
91
+ if (firstUserText === '') firstUserText = text;
92
+ segments.push({ seq: event.seq, role: 'user', text: clip(text), time: event.time, turn });
93
+ }
94
+ } else if (event.type === 'assistant/message') {
95
+ const text = messageText(event.data?.message);
96
+ if (text !== '') segments.push({ seq: event.seq, role: 'assistant', text: clip(text), time: event.time, turn });
97
+ } else if (event.type === 'tool/result') {
98
+ const text = messageText(event.data?.message);
99
+ if (text !== '') segments.push({ seq: event.seq, role: 'tool', text: clip(text), time: event.time, turn });
100
+ } else if (event.type === 'session/title') {
101
+ const value = event.data?.title;
102
+ if (typeof value === 'string' && value.trim() !== '') title = value.trim();
103
+ }
104
+ }
105
+ if (title === '' && firstUserText !== '') title = firstUserText.split('\n', 1)[0].slice(0, 60);
106
+ return { sessionId, title, updatedAt, segments };
107
+ }
108
+
109
+ async function readDocument(persistence, sessionId, header, signal) {
110
+ const handle = await persistence.open(sessionId, 'read', { signal });
111
+ try {
112
+ const result = await handle.read(undefined, undefined, { signal });
113
+ return buildDocument(sessionId, header, result.events);
114
+ } finally {
115
+ await handle.close();
116
+ }
117
+ }
118
+
119
+ /** The excerpt around one hit plus the offset of that hit inside it. */
120
+ function snippetAround(text, index, length) {
121
+ const start = Math.max(0, index - CONTEXT_CHARS);
122
+ const end = Math.min(text.length, index + length + CONTEXT_CHARS);
123
+ const prefix = start > 0 ? '…' : '';
124
+ const suffix = end < text.length ? '…' : '';
125
+ return `${prefix}${text.slice(start, end)}${suffix}`;
126
+ }
127
+
128
+ function previewAround(text, index, length) {
129
+ const start = Math.max(0, index - PREVIEW_CHARS);
130
+ const end = Math.min(text.length, index + length + PREVIEW_CHARS);
131
+ const prefix = start > 0 ? '…' : '';
132
+ const suffix = end < text.length ? '…' : '';
133
+ return {
134
+ text: `${prefix}${text.slice(start, end)}${suffix}`,
135
+ hit: index - start + prefix.length,
136
+ };
137
+ }
138
+
139
+ /** One document's matches, capped per session. */
140
+ function matchDocument(document, needle, settings, budget) {
141
+ const matches = [];
142
+ if (settings.matchTitle === true && document.title !== '') {
143
+ if (document.title.toLowerCase().includes(needle)) {
144
+ matches.push({ kind: 'title', role: 'title', snippet: document.title, preview: document.title, previewHit: 0, at: document.title.toLowerCase().indexOf(needle), time: document.updatedAt });
145
+ budget.total += 1;
146
+ }
147
+ }
148
+ if (settings.matchBody !== true && settings.matchTools !== true) return matches;
149
+ for (const segment of document.segments) {
150
+ if (matches.length >= MAX_MATCHES_PER_SESSION) break;
151
+ if (segment.role === 'tool' && settings.matchTools !== true) continue;
152
+ if (segment.role !== 'tool' && settings.matchBody !== true) continue;
153
+ if (budget.total >= MAX_TOTAL_MATCHES) break;
154
+ const haystack = segment.text.toLowerCase();
155
+ let from = 0;
156
+ while (matches.length < MAX_MATCHES_PER_SESSION && budget.total < MAX_TOTAL_MATCHES) {
157
+ const at = haystack.indexOf(needle, from);
158
+ if (at < 0) break;
159
+ const preview = previewAround(segment.text, at, needle.length);
160
+ matches.push({
161
+ kind: 'body',
162
+ role: segment.role,
163
+ seq: segment.seq,
164
+ turn: segment.turn,
165
+ snippet: snippetAround(segment.text, at, needle.length),
166
+ preview: preview.text,
167
+ previewHit: preview.hit,
168
+ at,
169
+ time: segment.time,
170
+ });
171
+ budget.total += 1;
172
+ from = at + needle.length;
173
+ }
174
+ }
175
+ // Newest first inside one session; rows without a timestamp sink to the end.
176
+ matches.sort((left, right) => (Number(right.time) || 0) - (Number(left.time) || 0));
177
+ return matches;
178
+ }
179
+
180
+ /**
181
+ * Build the search service: one document cache keyed by persistence revision.
182
+ * @param options - Host services the document builder reads.
183
+ * @returns search, plus a cache reset for settings changes.
184
+ */
185
+ export function createSearch(options) {
186
+ const { persistence } = options;
187
+ const cache = new Map();
188
+
189
+ async function ensureDocument(snapshot, signal) {
190
+ const sessionId = snapshot.header.id;
191
+ const revision = String(snapshot.revision ?? '');
192
+ const cached = cache.get(sessionId);
193
+ if (cached !== undefined && cached.revision === revision) return cached.document;
194
+ const document = await readDocument(persistence, sessionId, snapshot.header, signal);
195
+ cache.set(sessionId, { revision, document });
196
+ return document;
197
+ }
198
+
199
+ async function search(query, settings, signal) {
200
+ const started = Date.now();
201
+ const trimmed = query.trim();
202
+ if (trimmed === '') return { groups: [], scanned: 0, truncated: false, tookMs: 0 };
203
+ const needle = trimmed.toLowerCase();
204
+ const snapshotList = await persistence.list({ signal });
205
+ const budget = { total: 0 };
206
+ const groups = [];
207
+ const seen = new Set();
208
+ for (const snapshot of snapshotList) {
209
+ if (signal?.aborted === true) throw Object.assign(new Error('搜索已取消'), { code: 'cancelled' });
210
+ if (snapshot.formatStatus === 'migration-required') continue;
211
+ let document;
212
+ try {
213
+ document = await ensureDocument(snapshot, signal);
214
+ } catch {
215
+ continue;
216
+ }
217
+ seen.add(document.sessionId);
218
+ const matches = matchDocument(document, needle, settings, budget);
219
+ if (matches.length === 0) continue;
220
+ groups.push({
221
+ sessionId: document.sessionId,
222
+ title: document.title !== '' ? document.title : '未命名会话',
223
+ updatedAt: document.updatedAt,
224
+ cwd: typeof snapshot.header.cwd === 'string' ? snapshot.header.cwd : undefined,
225
+ matches,
226
+ });
227
+ if (budget.total >= MAX_TOTAL_MATCHES) break;
228
+ }
229
+ // Drop cache rows whose session log no longer exists.
230
+ for (const id of cache.keys()) if (!seen.has(id)) cache.delete(id);
231
+ // Newest hit first: a session with a fresh match outranks one whose file is newer.
232
+ const newestHit = (group) => (group.matches ?? []).reduce(
233
+ (max, match) => Math.max(max, Number(match.time) || 0),
234
+ 0,
235
+ );
236
+ groups.sort((a, b) => newestHit(b) - newestHit(a) || b.updatedAt - a.updatedAt);
237
+ return {
238
+ groups,
239
+ scanned: snapshotList.length,
240
+ truncated: budget.total >= MAX_TOTAL_MATCHES,
241
+ tookMs: Date.now() - started,
242
+ };
243
+ }
244
+
245
+ function reset() {
246
+ cache.clear();
247
+ }
248
+
249
+ return { search, reset };
250
+ }