dsh-timeback 0.0.0-stage → 0.6.0

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.
package/src/service.js ADDED
@@ -0,0 +1,1040 @@
1
+ /**
2
+ * Timeback service: capture a workspace snapshot at every conversation turn,
3
+ * expose the conversation/branch tree, and rewind conversation and files
4
+ * together by forking the Session and restoring the matching snapshot.
5
+ *
6
+ * The Session log remains the only authority for conversation state. The
7
+ * registry and the snapshot store are derived sidecars keyed by Session id and
8
+ * event sequence numbers; nothing here appends Session events.
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto'
12
+ import { promises as fs } from 'node:fs'
13
+ import path from 'node:path'
14
+ import { workspaceContains, workspaceKey } from './registry.js'
15
+
16
+ /** A user-facing operation failure. */
17
+ export class TimebackError extends Error {
18
+ constructor(message, code = 'timeback/failed', details = {}) {
19
+ super(message)
20
+ this.name = 'TimebackError'
21
+ this.code = code
22
+ this.details = details
23
+ }
24
+ }
25
+
26
+ /** The text of one direct human prompt, bounded for a tree label. */
27
+ function promptText(message, limit = 96) {
28
+ const blocks = Array.isArray(message?.content) ? message.content : []
29
+ for (const block of blocks) {
30
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') {
31
+ const collapsed = block.text.replace(/\s+/g, ' ').trim()
32
+ return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}…`
33
+ }
34
+ }
35
+ return null
36
+ }
37
+
38
+ /** Whether a session is a top-level conversation timeback should record. */
39
+ function eligible(session) {
40
+ const header = session?.header
41
+ if (!header) return false
42
+ if (header.origin === 'subagent' || (header.delegationDepth ?? 0) > 0) return false
43
+ return typeof header.cwd === 'string' && header.cwd !== ''
44
+ }
45
+
46
+ /** Shorten a session id for labels. */
47
+ function shortSession(sessionId) {
48
+ return String(sessionId).slice(0, 8)
49
+ }
50
+
51
+ /**
52
+ * Orchestrates checkpoints, the branch tree, and rewinds.
53
+ */
54
+ export class TimebackService {
55
+ /**
56
+ * @param options - Host context, resolved config, store, registry.
57
+ */
58
+ constructor(options) {
59
+ this.ctx = options.ctx
60
+ this.config = options.config
61
+ this.store = options.store
62
+ this.registry = options.registry
63
+ this.logger = options.logger
64
+ this.gitAvailable = false
65
+ this.captureMode = this.config.capture === 'off' ? 'off' : this.config.capture === 'all' ? 'all' : 'workspace'
66
+ this.started = false
67
+ this.records = new Map()
68
+ this.summaryCache = { at: 0, map: new Map() }
69
+ this.lifetime = options.lifetime
70
+ this.sessionController = options.sessionController
71
+ this.workingDirectory = options.workingDirectory ?? null
72
+ this.liveSessions = options.sessions ?? null
73
+ this.sessionTitle = options.sessionTitle ?? null
74
+ this.workspaceRegistry = options.workspaceRegistry ?? null
75
+ this.notes = options.notes ?? null
76
+ }
77
+
78
+ /** Prepare persistent state and probe git availability. */
79
+ async start() {
80
+ if (this.started) return
81
+ this.started = true
82
+ await this.registry.open()
83
+ this.gitAvailable = await this.store.available()
84
+ if (!this.gitAvailable) {
85
+ this.logger?.warn?.('timeback: git is unavailable, so file snapshots and restores are disabled; conversation branching stays available')
86
+ }
87
+ }
88
+
89
+ /** @returns {Promise<object>} plugin health and storage facts. */
90
+ async status() {
91
+ await this.start()
92
+ const sessions = this.registry.sessions()
93
+ return {
94
+ ok: true,
95
+ version: this.config.version ?? '0.0.0',
96
+ service: 'timeback',
97
+ git: this.gitAvailable,
98
+ dataDir: this.config.dataDir,
99
+ capture: this.captureMode,
100
+ workspaces: this.registry.workspaces().length,
101
+ sessions: sessions.length,
102
+ checkpoints: sessions.reduce((total, session) => total + session.checkpoints.length, 0),
103
+ pruneDependencies: this.config.exclude,
104
+ }
105
+ }
106
+
107
+ /** The effective working directory for one live Session. */
108
+ cwdOf(session) {
109
+ if (this.workingDirectory?.get) {
110
+ try {
111
+ return this.workingDirectory.get(session)
112
+ } catch {
113
+ // Fall through to the immutable header directory.
114
+ }
115
+ }
116
+ return session?.header?.cwd
117
+ }
118
+
119
+ /** The live Session object for one id, when this Host holds it. */
120
+ liveSession(sessionId) {
121
+ try {
122
+ return this.liveSessions?.get?.(sessionId) ?? undefined
123
+ } catch {
124
+ return undefined
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Whether automatic snapshots are enabled for one workspace.
130
+ * @param cwd - absolute directory.
131
+ * @returns {Promise<boolean>}
132
+ */
133
+ /** Canonical directory for workspace lookups, falling back to the raw path. */
134
+ async canonicalDir(cwd) {
135
+ if (!cwd) return ''
136
+ try {
137
+ return await fs.realpath(cwd)
138
+ } catch {
139
+ return cwd
140
+ }
141
+ }
142
+
143
+ async recordingEnabled(cwd) {
144
+ if (!cwd || this.captureMode === 'off') return false
145
+ if (this.captureMode === 'all') return true
146
+ await this.registry.open()
147
+ return this.registry.isWorkspaceEnabled(await this.canonicalDir(cwd))
148
+ }
149
+
150
+ /**
151
+ * Describe the workspace of one directory for the panel.
152
+ * @param cwd - absolute directory, or null when the session has none.
153
+ * @returns {Promise<object>}
154
+ */
155
+ async workspaceStatus(cwd) {
156
+ let root = null
157
+ let exists = false
158
+ if (cwd) {
159
+ try {
160
+ const stat = await fs.stat(cwd)
161
+ exists = stat.isDirectory()
162
+ } catch {
163
+ exists = false
164
+ }
165
+ root = this.registry.workspaceRootFor(await this.canonicalDir(cwd))
166
+ }
167
+ return {
168
+ cwd: cwd ?? null,
169
+ exists,
170
+ root,
171
+ mode: this.captureMode,
172
+ enabled: await this.recordingEnabled(cwd),
173
+ enabledWorkspaces: this.captureMode === 'workspace' ? this.registry.workspaces() : [],
174
+ excludedWorkspaces: this.captureMode === 'workspace' ? this.registry.excludedWorkspaces() : [],
175
+ }
176
+ }
177
+
178
+ /** Persist the reason a workspace could not be snapshotted for this Session. */
179
+ noteCaptureError(sessionId, message) {
180
+ this.registry
181
+ .updateSession(sessionId, { captureError: message ? String(message).slice(0, 400) : null })
182
+ .catch(() => {})
183
+ }
184
+
185
+ /** In-memory capture state for one live Session. */
186
+ record(session) {
187
+ const sessionId = String(session.id)
188
+ let record = this.records.get(sessionId)
189
+ if (!record) {
190
+ record = {
191
+ session,
192
+ sessionId,
193
+ turn: null,
194
+ prompt: null,
195
+ beforePromise: null,
196
+ beforeCheckpoint: null,
197
+ afterPending: null,
198
+ lastTree: null,
199
+ lastError: null,
200
+ }
201
+ this.records.set(sessionId, record)
202
+ }
203
+ record.session = session
204
+ return record
205
+ }
206
+
207
+ /** Start a baseline snapshot when a turn opens. */
208
+ onTurnStart(session, turn) {
209
+ if (!eligible(session)) return
210
+ const record = this.record(session)
211
+ record.turn = turn
212
+ record.prompt = null
213
+ record.afterPromise = null
214
+ record.afterSnapshot = null
215
+ record.afterCheckpoint = null
216
+ record.turnEndPromise = null
217
+ const cwd = this.cwdOf(session)
218
+ if (!cwd) return
219
+ const boundarySeq = Number.isSafeInteger(record.lastEndSeq) ? record.lastEndSeq : null
220
+ record.recording = false
221
+ record.beforePromise = this.recordingEnabled(cwd)
222
+ .then((enabled) => {
223
+ record.recording = enabled
224
+ if (!enabled) return null
225
+ return this.capture({
226
+ session,
227
+ cwd,
228
+ phase: 'before',
229
+ turn,
230
+ seq: boundarySeq,
231
+ label: null,
232
+ prompt: null,
233
+ previousTree: record.lastTree,
234
+ })
235
+ })
236
+ .then((checkpoint) => {
237
+ record.beforeCheckpoint = checkpoint
238
+ record.lastTree = checkpoint?.snapshot?.tree ?? record.lastTree
239
+ record.lastError = null
240
+ return checkpoint
241
+ })
242
+ .catch((error) => {
243
+ record.beforePromise = null
244
+ record.lastError = messageOf(error)
245
+ this.noteCaptureError(record.sessionId, record.lastError)
246
+ this.logger?.warn?.(`timeback: baseline snapshot failed for ${shortSession(session.id)} turn ${turn}: ${record.lastError}`)
247
+ return null
248
+ })
249
+ }
250
+
251
+ /** Remember the direct human prompt of the current turn for tree labels. */
252
+ onUserMessage(session, event) {
253
+ if (!eligible(session)) return
254
+ if (event?.data?.source?.kind !== 'user') return
255
+ const record = this.records.get(String(session.id))
256
+ if (!record) return
257
+ record.prompt = promptText(event.data)
258
+ }
259
+
260
+ /** Snapshot the settled work tree before the turn closes. */
261
+ async onTurnStopping(session, turn) {
262
+ if (!eligible(session)) return
263
+ const record = this.records.get(String(session.id))
264
+ if (!record || record.turn !== turn) return
265
+ await this.captureAfter(record)
266
+ }
267
+
268
+ /** Finish the turn checkpoint once its event sequence is known. */
269
+ onTurnEnd(session, turn, seq) {
270
+ if (!eligible(session)) return
271
+ const record = this.record(session)
272
+ record.lastEndSeq = seq
273
+ if (!record.beforePromise && record.turn === null) record.turn = turn
274
+ const pending = (async () => {
275
+ const after = await this.captureAfter(record)
276
+ if (!after) return
277
+ const checkpoint = await this.registry.addCheckpoint(String(session.id), {
278
+ id: after.checkpointId,
279
+ turn,
280
+ phase: 'after',
281
+ seq,
282
+ label: null,
283
+ prompt: record.prompt,
284
+ snapshot: after.snapshot,
285
+ files: after.files,
286
+ boardVersion: this.notes?.version ?? null,
287
+ lastEndSeq: seq,
288
+ })
289
+ record.lastTree = checkpoint?.snapshot?.tree ?? record.lastTree
290
+ record.afterCheckpoint = checkpoint
291
+ })().catch((error) => {
292
+ record.lastError = messageOf(error)
293
+ this.noteCaptureError(record.sessionId, record.lastError)
294
+ this.logger?.warn?.(`timeback: turn checkpoint failed for ${shortSession(session.id)} turn ${turn}: ${record.lastError}`)
295
+ })
296
+ record.turnEndPromise = pending
297
+ }
298
+
299
+ /** Capture the after-turn tree once per turn. */
300
+ async captureAfter(record) {
301
+ if (record.beforePromise) {
302
+ try {
303
+ await record.beforePromise
304
+ } catch {
305
+ // The baseline failure is logged where it happens.
306
+ }
307
+ }
308
+ if (!record.recording) return null
309
+ await this.notes?.open?.()
310
+ if (record.afterSnapshot) return record.afterSnapshot
311
+ if (record.afterPromise) return record.afterPromise
312
+ record.afterPromise = (async () => {
313
+ const session = record.session
314
+ const cwd = this.cwdOf(session)
315
+ if (!cwd) return null
316
+ const checkpointId = `cp-${randomUUID()}`
317
+ await this.registry.ensureSession({ sessionId: record.sessionId, cwd })
318
+ const snapshot = await this.store.capture({
319
+ cwd,
320
+ sessionId: record.sessionId,
321
+ checkpointId,
322
+ previousTree: record.beforeCheckpoint?.snapshot?.tree ?? record.lastTree,
323
+ signal: this.lifetime?.signal,
324
+ })
325
+ const result = { checkpointId, snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId }, files: snapshot.files }
326
+ record.afterSnapshot = result
327
+ return result
328
+ })().catch((error) => {
329
+ record.afterPromise = null
330
+ throw error
331
+ })
332
+ return record.afterPromise
333
+ }
334
+
335
+ /**
336
+ * Capture one snapshot and persist its checkpoint.
337
+ * @returns {Promise<object>} the stored checkpoint.
338
+ */
339
+ async capture(input) {
340
+ await this.notes?.open?.()
341
+ const sessionId = String(input.session.id)
342
+ await this.registry.ensureSession({ sessionId, cwd: input.cwd })
343
+ const checkpointId = `cp-${randomUUID()}`
344
+ const snapshot = await this.store.capture({
345
+ cwd: input.cwd,
346
+ sessionId,
347
+ checkpointId,
348
+ previousTree: input.previousTree,
349
+ signal: this.lifetime?.signal,
350
+ })
351
+ const checkpoint = await this.registry.addCheckpoint(sessionId, {
352
+ id: checkpointId,
353
+ turn: input.turn,
354
+ phase: input.phase,
355
+ seq: input.seq,
356
+ label: input.label,
357
+ prompt: input.prompt,
358
+ snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId },
359
+ files: snapshot.files,
360
+ boardVersion: this.notes?.version ?? null,
361
+ })
362
+ return checkpoint
363
+ }
364
+
365
+ /** Await the baseline snapshot before a tool can mutate the work tree. */
366
+ async gateTool(exec) {
367
+ const session = exec?.agent?.session
368
+ if (!session) return
369
+ const record = this.records.get(String(session.id))
370
+ if (!record?.beforePromise) return
371
+ try {
372
+ await record.beforePromise
373
+ } catch {
374
+ // Already logged; a missing baseline must not block the tool.
375
+ }
376
+ }
377
+
378
+ /** Drop in-memory capture state for a disposed Session. */
379
+ onSessionDisposed(session) {
380
+ this.records.delete(String(session.id))
381
+ }
382
+
383
+ /** Wrap a snapshot failure as a user-facing Timeback failure. */
384
+ toUserError(error) {
385
+ if (error instanceof TimebackError) return error
386
+ if (error?.code === 'snapshot/workspace-too-large') {
387
+ return new TimebackError(error.message, 'timeback/workspace-too-large', error.details ?? {})
388
+ }
389
+ if (error?.name === 'SnapshotError') return new TimebackError(error.message, error.code, error.details ?? {})
390
+ return error
391
+ }
392
+
393
+ /** One manual checkpoint at the current conversation position. */
394
+ async createCheckpoint(input) {
395
+ await this.start()
396
+ const sessionId = String(input.sessionId)
397
+ const session = this.liveSession(sessionId)
398
+ if (!session) throw new TimebackError(`会话 ${shortSession(sessionId)} 当前未打开,无法创建检查点`, 'timeback/session-closed')
399
+ const cwd = this.cwdOf(session)
400
+ if (!cwd) throw new TimebackError('该会话没有工作目录,无法创建文件快照', 'timeback/no-cwd')
401
+ if (this.captureMode === 'workspace' && !(await this.recordingEnabled(cwd))) {
402
+ throw new TimebackError(
403
+ '该工作区尚未开启记录。请在「时间回溯」面板勾选「记录此工作区并保存文件快照」后再创建检查点。',
404
+ 'timeback/workspace-not-recording',
405
+ )
406
+ }
407
+ const lastSeq = session.seq > 0 ? session.seq - 1 : null
408
+ let checkpoint
409
+ try {
410
+ checkpoint = await this.capture({
411
+ session,
412
+ cwd,
413
+ phase: 'manual',
414
+ turn: this.records.get(sessionId)?.turn ?? null,
415
+ seq: lastSeq,
416
+ label: input.label ?? null,
417
+ prompt: null,
418
+ previousTree: this.records.get(sessionId)?.lastTree ?? null,
419
+ })
420
+ } catch (error) {
421
+ const wrapped = this.toUserError(error)
422
+ this.noteCaptureError(sessionId, wrapped.message)
423
+ throw wrapped
424
+ }
425
+ return { checkpoint: presentCheckpoint(checkpoint, true) }
426
+ }
427
+
428
+ /** Sessions and checkpoints in the current Session's branch family. */
429
+ async tree(input) {
430
+ await this.start()
431
+ let currentSessionId = String(input.sessionId)
432
+ const liveAtStart = this.liveSession(currentSessionId)
433
+ if (liveAtStart?.header?.origin === 'subagent' && liveAtStart.header.parentSession) {
434
+ // A subagent inspecting its own tree means the conversation it was
435
+ // delegated from; do not register agent-scoped child sessions.
436
+ currentSessionId = String(liveAtStart.header.parentSession)
437
+ }
438
+ const summaries = await this.summaryMap()
439
+ const archivedIds = this.archivedSessionIds()
440
+ const live = this.liveSession(currentSessionId)
441
+ if (!this.registry.session(currentSessionId)) {
442
+ const summary = summaries.get(currentSessionId)
443
+ if (!summary && !live) throw new TimebackError(`未知会话:${shortSession(currentSessionId)}`, 'timeback/session-unknown')
444
+ await this.registry.ensureSession({
445
+ sessionId: currentSessionId,
446
+ cwd: summary?.cwd ?? live?.header?.cwd ?? null,
447
+ title: this.titleOf(live, summary),
448
+ })
449
+ }
450
+ const current = this.registry.session(currentSessionId)
451
+ if (current && archivedIds.has(String(current.id))) {
452
+ throw new TimebackError('该会话已归档,无法在时间回溯中显示;请切换到未归档的会话', 'timeback/session-archived')
453
+ }
454
+ let root = current
455
+ const visited = new Set()
456
+ while (root?.parentSessionId && !visited.has(root.parentSessionId)) {
457
+ visited.add(root.id)
458
+ if (archivedIds.has(String(root.parentSessionId))) break
459
+ const parent = this.registry.session(root.parentSessionId)
460
+ if (!parent) break
461
+ root = parent
462
+ }
463
+ const visibleSessions = this.registry.sessions().filter((session) => !archivedIds.has(String(session.id)))
464
+ const visibleIds = new Set(visibleSessions.map((session) => String(session.id)))
465
+ const children = new Map()
466
+ for (const session of visibleSessions) {
467
+ const key = session.parentSessionId ?? null
468
+ if (!children.has(key)) children.set(key, [])
469
+ children.get(key).push(session)
470
+ }
471
+ for (const list of children.values()) list.sort((left, right) => (left.forkAtSeq ?? 0) - (right.forkAtSeq ?? 0) || left.createdAt - right.createdAt)
472
+ const ordered = []
473
+ const walk = (session, depth) => {
474
+ ordered.push({ session, depth })
475
+ for (const child of children.get(session.id) ?? []) walk(child, depth + 1)
476
+ }
477
+ walk(root, 0)
478
+ const sessions = ordered.map(({ session, depth }) => {
479
+ const liveSession = this.liveSession(session.id)
480
+ const summary = summaries.get(session.id)
481
+ const captureRecord = this.records.get(session.id)
482
+ const recordingHere = this.captureMode === 'all' || (this.captureMode === 'workspace' && this.registry.workspaceRootFor(session.cwd ?? '') !== null)
483
+ return {
484
+ sessionId: session.id,
485
+ title: this.titleOf(liveSession, summary) ?? session.title ?? null,
486
+ cwd: session.cwd ?? summary?.cwd ?? null,
487
+ parentSessionId: session.parentSessionId && visibleIds.has(String(session.parentSessionId)) ? session.parentSessionId : null,
488
+ forkAtSeq: session.parentSessionId && visibleIds.has(String(session.parentSessionId)) ? session.forkAtSeq ?? null : null,
489
+ depth,
490
+ isCurrent: session.id === currentSessionId,
491
+ createdAt: session.createdAt,
492
+ running: summary?.running === true,
493
+ checkpointCount: session.checkpoints.length,
494
+ note: session.note ?? null,
495
+ recording: recordingHere,
496
+ status: { error: recordingHere ? captureRecord?.lastError ?? session.captureError ?? null : null },
497
+ checkpoints: session.checkpoints.map((checkpoint) => presentCheckpoint(checkpoint, input.includeFiles === true)),
498
+ }
499
+ })
500
+ const currentCwd = live ? this.cwdOf(live) : current.cwd
501
+ const workspace = await this.workspaceStatus(currentCwd)
502
+ return {
503
+ ok: true,
504
+ git: this.gitAvailable,
505
+ version: this.config.version ?? '0.0.0',
506
+ dataDir: this.config.dataDir,
507
+ currentSessionId,
508
+ rootSessionId: root.id,
509
+ boardVersion: this.notes?.version ?? null,
510
+ workspace,
511
+ sessions,
512
+ limits: {
513
+ restoreDeletesExtra: this.config.restoreDeletesExtra,
514
+ exclude: this.store?.exclude ?? this.config.exclude ?? [],
515
+ maxFiles: this.config.maxFiles ?? null,
516
+ },
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Fork the conversation at one checkpoint and/or restore its file snapshot.
522
+ * @param input - source session, checkpoint id, and requested mode.
523
+ * @returns branch session identity and restore facts.
524
+ */
525
+ async rewind(input) {
526
+ await this.start()
527
+ const mode = input.mode === 'files-only' || input.mode === 'branch-only' ? input.mode : 'branch-and-files'
528
+ const found = this.registry.findCheckpoint(input.checkpointId)
529
+ if (!found) throw new TimebackError('找不到该检查点', 'timeback/checkpoint-unknown')
530
+ const sessionId = String(input.sessionId ?? found.sessionId)
531
+ if (found.sessionId !== sessionId) throw new TimebackError('该检查点不属于当前会话', 'timeback/checkpoint-mismatch')
532
+ const checkpoint = found.checkpoint
533
+ const session = this.registry.session(sessionId)
534
+ if (!session) throw new TimebackError('该会话未被 timeback 记录', 'timeback/session-unknown')
535
+ if (await this.isRunning(sessionId)) {
536
+ throw new TimebackError('会话正在运行,请等待本轮结束或先停止后再回退', 'timeback/session-running')
537
+ }
538
+ const wantsFiles = mode !== 'branch-only'
539
+ const wantsBranch = mode !== 'files-only'
540
+ if (wantsFiles && !checkpoint.snapshot?.tree) {
541
+ throw new TimebackError('该检查点没有可恢复的文件快照,只能分支会话', 'timeback/no-file-snapshot')
542
+ }
543
+ if (wantsBranch && !Number.isSafeInteger(checkpoint.seq)) {
544
+ throw new TimebackError('该检查点没有可用的会话位置,只能恢复文件', 'timeback/no-branch-position')
545
+ }
546
+ let childSessionId = null
547
+ if (wantsBranch) {
548
+ let value
549
+ try {
550
+ value = await this.sessionController.fork({ sessionId, atSeq: checkpoint.seq })
551
+ } catch (error) {
552
+ throw new TimebackError(
553
+ `创建分支会话失败:${error?.message ? String(error.message) : String(error)}`,
554
+ error?.code ?? 'timeback/fork-failed',
555
+ error?.details ?? {},
556
+ )
557
+ }
558
+ childSessionId = String(value.sessionId)
559
+ const cwd = checkpoint.snapshot?.cwd ?? session.cwd ?? null
560
+ await this.registry.ensureSession({
561
+ sessionId: childSessionId,
562
+ cwd,
563
+ parentSessionId: sessionId,
564
+ forkAtSeq: checkpoint.seq,
565
+ forkCheckpointId: checkpoint.id,
566
+ })
567
+ this.nameBranch(childSessionId, sessionId, checkpoint)
568
+ await this.registry.addCheckpoint(childSessionId, {
569
+ turn: checkpoint.turn,
570
+ phase: 'inherited',
571
+ seq: checkpoint.seq,
572
+ label: null,
573
+ prompt: checkpoint.prompt,
574
+ snapshot: checkpoint.snapshot,
575
+ files: null,
576
+ boardVersion: checkpoint.boardVersion ?? null,
577
+ })
578
+ }
579
+ let safety = null
580
+ let restore = null
581
+ if (wantsFiles) {
582
+ const cwd = checkpoint.snapshot.cwd
583
+ const workingSession = this.liveSession(sessionId)
584
+ if (!workingSession) throw new TimebackError('源会话未打开,无法获取当前工作区状态;请先打开该会话再回退文件', 'timeback/source-closed')
585
+ const record = this.records.get(sessionId)
586
+ try {
587
+ safety = await this.capture({
588
+ session: workingSession,
589
+ cwd,
590
+ phase: 'safety',
591
+ turn: record?.turn ?? null,
592
+ seq: Number.isSafeInteger(checkpoint.seq) ? checkpoint.seq : null,
593
+ label: null,
594
+ prompt: null,
595
+ previousTree: record?.lastTree ?? null,
596
+ })
597
+ } catch (error) {
598
+ const wrapped = this.toUserError(error)
599
+ this.noteCaptureError(sessionId, wrapped.message)
600
+ throw wrapped
601
+ }
602
+ restore = await this.store.restore({
603
+ cwd,
604
+ targetTree: checkpoint.snapshot.tree,
605
+ currentTree: safety?.snapshot?.tree,
606
+ deleteExtra: this.config.restoreDeletesExtra,
607
+ signal: this.lifetime?.signal,
608
+ })
609
+ if (restore.failed.length > 0) {
610
+ this.logger?.warn?.(`timeback: restore left ${restore.failed.length} path(s) failed in ${cwd}`)
611
+ }
612
+ }
613
+ // The notes board travels with the rewind: a checkpoint stores the board
614
+ // version it saw, so rewinding restores that Markdown state too.
615
+ let board = null
616
+ if (this.notes && Number.isSafeInteger(checkpoint.boardVersion)) {
617
+ try {
618
+ board = await this.notes.restore(checkpoint.boardVersion)
619
+ } catch (error) {
620
+ this.logger?.warn?.(`timeback: board restore failed: ${error?.message ?? error}`)
621
+ board = { restoredFrom: checkpoint.boardVersion, error: error?.message ? String(error.message) : String(error) }
622
+ }
623
+ }
624
+ if (this.notes) {
625
+ const referenced = new Set()
626
+ for (const item of this.registry.sessions()) {
627
+ for (const candidate of item.checkpoints ?? []) {
628
+ if (Number.isSafeInteger(candidate.boardVersion)) referenced.add(candidate.boardVersion)
629
+ }
630
+ }
631
+ this.notes.pruneHistory(referenced).catch(() => {})
632
+ }
633
+ return {
634
+ ok: true,
635
+ mode,
636
+ childSessionId,
637
+ sourceSessionId: sessionId,
638
+ checkpointId: checkpoint.id,
639
+ checkpointTurn: checkpoint.turn,
640
+ safetyCheckpointId: safety?.id ?? null,
641
+ restore,
642
+ board,
643
+ warning: wantsFiles && restore?.skipped > 0 ? `${restore.skipped} 个新增文件被保留(restoreDeletesExtra=false)` : null,
644
+ }
645
+ }
646
+
647
+ /** Give the forked Session a recognizable title when the title service exists. */
648
+ nameBranch(childSessionId, parentSessionId, checkpoint) {
649
+ try {
650
+ const child = this.liveSession(childSessionId)
651
+ const parent = this.liveSession(parentSessionId)
652
+ if (!child || !this.sessionTitle?.rename) return
653
+ const parentTitle = this.sessionTitle.get?.(parent) ?? this.registry.session(parentSessionId)?.title ?? '会话'
654
+ const suffix = checkpoint.turn === null || checkpoint.turn === undefined ? '' : ` · T${checkpoint.turn}`
655
+ const title = `${parentTitle} · 分支${suffix}`.slice(0, 120)
656
+ Promise.resolve(this.sessionTitle.rename(child, title)).catch(() => {})
657
+ } catch {
658
+ // Naming is a convenience; the branch already exists.
659
+ }
660
+ }
661
+
662
+ /**
663
+ * Resolve the concrete workspace directory for an action.
664
+ * @param input - `{ sessionId?, cwd? }`; the session's directory wins.
665
+ * @returns {Promise<string>} canonical absolute directory.
666
+ */
667
+ async resolveWorkspace(input) {
668
+ let target = null
669
+ // An explicit directory wins over the session default, so callers can
670
+ // manage another workspace from the same Session.
671
+ if (typeof input.cwd === 'string' && input.cwd !== '') {
672
+ target = input.cwd
673
+ } else if (input.sessionId) {
674
+ const sessionId = String(input.sessionId)
675
+ const live = this.liveSession(sessionId)
676
+ target = live ? this.cwdOf(live) : this.registry.session(sessionId)?.cwd ?? null
677
+ if (!target) {
678
+ const summary = (await this.summaryMap()).get(sessionId)
679
+ target = summary?.cwd ?? null
680
+ }
681
+ }
682
+ if (!target) throw new TimebackError('无法确定该会话的工作区目录;请先打开会话', 'timeback/workspace-unknown')
683
+ let resolved
684
+ try {
685
+ resolved = await fs.realpath(target)
686
+ const stat = await fs.stat(resolved)
687
+ if (!stat.isDirectory()) throw new Error('not a directory')
688
+ } catch {
689
+ throw new TimebackError(`工作区目录不存在或不可访问:${target}`, 'timeback/workspace-missing')
690
+ }
691
+ return resolved
692
+ }
693
+
694
+ /**
695
+ * List the recording mode, enabled workspaces, and one workspace's state.
696
+ * @param input - `{ sessionId?, cwd? }`.
697
+ * @returns {Promise<object>}
698
+ */
699
+ async listWorkspaces(input) {
700
+ await this.start()
701
+ let current = null
702
+ try {
703
+ current = await this.workspaceStatus(await this.resolveWorkspace(input ?? {}))
704
+ } catch {
705
+ current = null
706
+ }
707
+ return {
708
+ mode: this.captureMode,
709
+ workspaces: this.registry.workspaces(),
710
+ workspace: current,
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Enable or disable automatic snapshots for one workspace.
716
+ * @param input - `{ sessionId?, cwd?, enabled }`; the session's directory wins.
717
+ * @returns {Promise<object>} the new workspace state.
718
+ */
719
+ async setWorkspace(input) {
720
+ await this.start()
721
+ const requested = typeof input.enabled === 'boolean' ? input.enabled : true
722
+ const resolved = await this.resolveWorkspace(input)
723
+ if (this.captureMode !== 'workspace') {
724
+ throw new TimebackError(
725
+ this.captureMode === 'off'
726
+ ? '插件配置 capture=off 已关闭自动记录;请修改插件配置后再开启'
727
+ : '插件配置 capture=all 已对所有工作区开启记录,无需单独勾选',
728
+ 'timeback/capture-mode-fixed',
729
+ )
730
+ }
731
+ const result = await this.registry.setWorkspaceEnabled(resolved, requested)
732
+ const workspace = await this.workspaceStatus(resolved)
733
+ return { workspace, workspaces: workspace.enabledWorkspaces, ...result }
734
+ }
735
+
736
+ /* ---------------------------------------------------------------- */
737
+ /* notes board */
738
+ /* ---------------------------------------------------------------- */
739
+
740
+ /** @returns {Promise<{version:number,updatedAt:number,entries:object[]}>} the Markdown board. */
741
+ async board() {
742
+ await this.start()
743
+ if (!this.notes) throw new TimebackError('记录板存储不可用', 'timeback/notes-unavailable')
744
+ return this.notes.board()
745
+ }
746
+
747
+ /**
748
+ * Create or update one board note.
749
+ * @param input - `{id?, title?, body?, sessionId?}`.
750
+ * @param source - `user` for panel edits, `agent` for tool calls.
751
+ */
752
+ async saveBoardNote(input, source = 'user') {
753
+ await this.start()
754
+ if (!this.notes) throw new TimebackError('记录板存储不可用', 'timeback/notes-unavailable')
755
+ const id = typeof input.id === 'string' && input.id !== '' ? input.id : ''
756
+ const title = typeof input.title === 'string' ? input.title : ''
757
+ const body = typeof input.body === 'string' ? input.body : ''
758
+ if (id) {
759
+ try {
760
+ return { ok: true, ...(await this.notes.update(id, { title, body })) }
761
+ } catch (error) {
762
+ if (error?.code === 'notes/not-found') throw new TimebackError('记录不存在或已删除', 'timeback/note-unknown')
763
+ throw error
764
+ }
765
+ }
766
+ if (body.trim() === '' && title.trim() === '') throw new TimebackError('记录内容不能为空', 'timeback/note-empty')
767
+ return {
768
+ ok: true,
769
+ ...(await this.notes.create({
770
+ title,
771
+ body,
772
+ source: source === 'agent' ? 'agent' : 'user',
773
+ sessionId: typeof input.sessionId === 'string' && input.sessionId !== '' ? input.sessionId : null,
774
+ workspace: typeof input.cwd === 'string' && input.cwd !== '' ? input.cwd : null,
775
+ })),
776
+ }
777
+ }
778
+
779
+ /** Delete one board note. */
780
+ async deleteBoardNote(id) {
781
+ await this.start()
782
+ if (!this.notes) throw new TimebackError('记录板存储不可用', 'timeback/notes-unavailable')
783
+ if (typeof id !== 'string' || id === '') throw new TimebackError('缺少记录 id', 'timeback/note-id-required')
784
+ try {
785
+ return { ok: true, ...(await this.notes.remove(id)) }
786
+ } catch (error) {
787
+ if (error?.code === 'notes/not-found') throw new TimebackError('记录不存在或已删除', 'timeback/note-unknown')
788
+ throw error
789
+ }
790
+ }
791
+
792
+ /**
793
+ * Save the free-text note attached to one checkpoint card (or to the session
794
+ * start card when `checkpointId` is omitted).
795
+ */
796
+ async saveCardNote(input) {
797
+ await this.start()
798
+ const sessionId = String(input.sessionId ?? '')
799
+ if (!sessionId) throw new TimebackError('缺少会话 id', 'timeback/session-required')
800
+ if (!this.registry.session(sessionId)) {
801
+ const live = this.liveSession(sessionId)
802
+ const summary = (await this.summaryMap()).get(sessionId)
803
+ if (!live && !summary) throw new TimebackError('未知会话', 'timeback/session-unknown')
804
+ await this.registry.ensureSession({
805
+ sessionId,
806
+ cwd: this.cwdOf(live) ?? summary?.cwd ?? null,
807
+ title: this.titleOf(live, summary),
808
+ })
809
+ }
810
+ const checkpointId = typeof input.checkpointId === 'string' && input.checkpointId !== '' ? input.checkpointId : ''
811
+ if (checkpointId) {
812
+ const found = this.registry.findCheckpoint(checkpointId)
813
+ if (!found) throw new TimebackError('找不到该检查点', 'timeback/checkpoint-unknown')
814
+ if (found.sessionId !== sessionId) throw new TimebackError('该检查点不属于当前会话', 'timeback/checkpoint-mismatch')
815
+ const checkpoint = await this.registry.updateCheckpointNote(sessionId, checkpointId, input.note)
816
+ return { ok: true, checkpoint: presentCheckpoint(checkpoint, false) }
817
+ }
818
+ const session = await this.registry.updateSessionNote(sessionId, input.note)
819
+ return { ok: true, sessionId, sessionNote: session.note ?? null }
820
+ }
821
+
822
+ /* ---------------------------------------------------------------- */
823
+ /* pruning / archiving */
824
+ /* ---------------------------------------------------------------- */
825
+
826
+ /** @returns {Set<string>} Session ids archived in the workspace registry. */
827
+ archivedSessionIds() {
828
+ try {
829
+ const ids = this.workspaceRegistry?.archivedSessionIds ?? []
830
+ return new Set(ids.map((id) => String(id)))
831
+ } catch {
832
+ return new Set()
833
+ }
834
+ }
835
+
836
+ /**
837
+ * Sessions a prune should archive: the source plus every branch forked after
838
+ * the cut, and all descendants of those discarded branches.
839
+ * @param sessionId - source Session.
840
+ * @param cutSeq - inclusive conversation position kept.
841
+ * @returns {string[]} sessions to archive, source first.
842
+ */
843
+ pruneTargets(sessionId, cutSeq) {
844
+ const children = new Map()
845
+ for (const session of this.registry.sessions()) {
846
+ const parent = session.parentSessionId ? String(session.parentSessionId) : null
847
+ if (parent === null) continue
848
+ if (!children.has(parent)) children.set(parent, [])
849
+ children.get(parent).push(session)
850
+ }
851
+ const targets = [sessionId]
852
+ const queue = [sessionId]
853
+ let first = true
854
+ while (queue.length > 0) {
855
+ const current = queue.shift()
856
+ for (const child of children.get(current) ?? []) {
857
+ // Direct children forked after the cut belong to the discarded segment;
858
+ // anything below an archived branch is discarded with it.
859
+ if (first && !(Number.isInteger(child.forkAtSeq) && child.forkAtSeq > cutSeq)) continue
860
+ targets.push(String(child.id))
861
+ queue.push(String(child.id))
862
+ }
863
+ first = false
864
+ }
865
+ return [...new Set(targets)]
866
+ }
867
+
868
+ /**
869
+ * Delete the conversation after one checkpoint: fork a truncated branch at
870
+ * the checkpoint, restore files (unless branch-only), then archive the
871
+ * discarded sessions. DSH logs are append-only, so deletion is archival; an
872
+ * archived Session remains recoverable from the DSH archive list.
873
+ * @param input - `{ sessionId, checkpointId, mode?, childSessionId? }`.
874
+ * @returns branch identity, restore facts, and archived sessions.
875
+ */
876
+ async prune(input) {
877
+ await this.start()
878
+ const found = this.registry.findCheckpoint(input.checkpointId)
879
+ if (!found) throw new TimebackError('找不到该检查点', 'timeback/checkpoint-unknown')
880
+ const sessionId = String(input.sessionId ?? found.sessionId)
881
+ if (found.sessionId !== sessionId) throw new TimebackError('该检查点不属于当前会话', 'timeback/checkpoint-mismatch')
882
+ const checkpoint = found.checkpoint
883
+ if (!Number.isSafeInteger(checkpoint.seq)) {
884
+ throw new TimebackError('该检查点没有可用的会话位置,无法删除其后内容', 'timeback/no-branch-position')
885
+ }
886
+ if (await this.isRunning(sessionId)) {
887
+ throw new TimebackError('会话正在运行,请等待本轮结束或先停止后再删除', 'timeback/session-running')
888
+ }
889
+ const mode = input.mode === 'branch-only' ? 'branch-only' : 'branch-and-files'
890
+ const targets = this.pruneTargets(sessionId, checkpoint.seq)
891
+ const hasLater = this.registry
892
+ .checkpoints(sessionId)
893
+ .some((candidate) => Number.isInteger(candidate.seq) && candidate.seq > checkpoint.seq)
894
+ if (!hasLater && targets.length === 1) {
895
+ throw new TimebackError(
896
+ '该节点之后没有可删除的内容(对话与分支都已经到此为止)',
897
+ 'timeback/nothing-to-prune',
898
+ )
899
+ }
900
+ let childSessionId = typeof input.childSessionId === 'string' && input.childSessionId !== '' ? input.childSessionId : null
901
+ const registeredChild = childSessionId ? this.registry.session(childSessionId) : null
902
+ const childUsable =
903
+ registeredChild !== null &&
904
+ registeredChild !== undefined &&
905
+ String(registeredChild.parentSessionId) === sessionId &&
906
+ registeredChild.forkAtSeq === checkpoint.seq
907
+ let rewind = null
908
+ if (!childUsable) {
909
+ rewind = await this.rewind({ sessionId, checkpointId: checkpoint.id, mode })
910
+ childSessionId = rewind.childSessionId
911
+ }
912
+ // The truncated branch replaces the old session, so it should look like the
913
+ // same conversation cut short rather than a differently named new branch.
914
+ const sourceTitle =
915
+ this.sessionTitle?.get?.(this.liveSession(sessionId)) ??
916
+ this.registry.session(sessionId)?.title ??
917
+ (await this.summaryMap()).get(sessionId)?.projections?.values?.title ??
918
+ null
919
+ if (childSessionId && sourceTitle) {
920
+ try {
921
+ this.registry.updateSession(childSessionId, { title: sourceTitle }).catch(() => {})
922
+ const childLive = this.liveSession(childSessionId)
923
+ if (childLive && this.sessionTitle?.rename) await this.sessionTitle.rename(childLive, sourceTitle)
924
+ } catch {
925
+ // Naming is cosmetic; the truncated branch still exists.
926
+ }
927
+ }
928
+ const archived = []
929
+ const failed = []
930
+ if (!this.workspaceRegistry?.archiveSession) {
931
+ failed.push({ sessionId, error: '工作区服务不可用,无法归档旧会话;已创建截断分支' })
932
+ } else {
933
+ for (const target of targets) {
934
+ try {
935
+ await this.workspaceRegistry.archiveSession(target, { stopActivity: false })
936
+ archived.push(target)
937
+ } catch (error) {
938
+ failed.push({ sessionId: target, error: error?.message ? String(error.message) : String(error) })
939
+ }
940
+ }
941
+ }
942
+ const warnings = []
943
+ if (archived.length > 0) warnings.push(`已归档 ${archived.length} 个旧会话(可在 DSH 归档列表恢复)`)
944
+ if (failed.length > 0) warnings.push(`${failed.length} 个旧会话未能归档(可能正在运行)`)
945
+ return {
946
+ ok: true,
947
+ childSessionId,
948
+ sourceSessionId: sessionId,
949
+ checkpointId: checkpoint.id,
950
+ checkpointTurn: checkpoint.turn,
951
+ restore: rewind?.restore ?? null,
952
+ archived,
953
+ failed,
954
+ warning: warnings.length > 0 ? warnings.join(';') : null,
955
+ }
956
+ }
957
+
958
+ /** Whether the Session currently runs a turn. */
959
+ async isRunning(sessionId) {
960
+ try {
961
+ const value = await this.sessionController.list({}, AbortSignal.timeout(3000))
962
+ const row = (value?.items ?? []).find((item) => String(item.sessionId) === sessionId)
963
+ return row?.running === true
964
+ } catch {
965
+ return false
966
+ }
967
+ }
968
+
969
+ /** Cached Session summaries for titles and cold cwd. */
970
+ async summaryMap() {
971
+ const now = Date.now()
972
+ if (now - this.summaryCache.at < 2_000 && this.summaryCache.map.size > 0) return this.summaryCache.map
973
+ const map = new Map()
974
+ try {
975
+ const value = await this.sessionController.list({}, AbortSignal.timeout(4000))
976
+ for (const item of value?.items ?? []) map.set(String(item.sessionId), item)
977
+ } catch (error) {
978
+ this.logger?.warn?.(`timeback: session list unavailable: ${messageOf(error)}`)
979
+ }
980
+ this.summaryCache = { at: now, map }
981
+ return map
982
+ }
983
+
984
+ /** Best available display title for one Session. */
985
+ titleOf(liveSession, summary) {
986
+ if (liveSession) {
987
+ try {
988
+ const title = this.sessionTitle?.get?.(liveSession)
989
+ if (typeof title === 'string' && title.trim() !== '') return title
990
+ } catch {
991
+ // Optional service: fall through.
992
+ }
993
+ }
994
+ const hints = summary?.projections?.values
995
+ const projected = hints?.title ?? summary?.projections?.title
996
+ if (typeof projected === 'string' && projected.trim() !== '') return projected
997
+ return null
998
+ }
999
+ }
1000
+
1001
+ /** Present one stored checkpoint to the Client or a tool. */
1002
+ export function presentCheckpoint(checkpoint, includeFiles) {
1003
+ const files = checkpoint.files
1004
+ return {
1005
+ id: checkpoint.id,
1006
+ turn: checkpoint.turn,
1007
+ phase: checkpoint.phase,
1008
+ seq: checkpoint.seq,
1009
+ createdAt: checkpoint.createdAt,
1010
+ label: checkpoint.label,
1011
+ prompt: checkpoint.prompt,
1012
+ note: checkpoint.note ?? null,
1013
+ hasSnapshot: Boolean(checkpoint.snapshot?.tree),
1014
+ snapshotCwd: checkpoint.snapshot?.cwd ?? null,
1015
+ files: files
1016
+ ? {
1017
+ total: files.total ?? 0,
1018
+ added: (files.added ?? []).length,
1019
+ modified: (files.modified ?? []).length,
1020
+ deleted: (files.deleted ?? []).length,
1021
+ truncated: Boolean(files.truncated),
1022
+ ...(includeFiles ? { paths: files.files ?? [] } : {}),
1023
+ }
1024
+ : null,
1025
+ error: checkpoint.error,
1026
+ }
1027
+ }
1028
+
1029
+ /** One error message string. */
1030
+ function messageOf(error) {
1031
+ return error?.message ? String(error.message) : String(error)
1032
+ }
1033
+
1034
+ /** Read the plugin data directory from the environment. */
1035
+ export function defaultDataDir() {
1036
+ const home = process.env.DSH_HOME || path.join(process.env.HOME || '/', '.dsh')
1037
+ return path.join(home, 'timeback')
1038
+ }
1039
+
1040
+ export default TimebackService