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.
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Durable checkpoint registry.
3
+ *
4
+ * One small JSON document under the plugin data directory records which
5
+ * workspaces the user opted into recording, every session timeback has
6
+ * observed, its branch parent, and each snapshot checkpoint. Writes are atomic
7
+ * (write + rename) and serialized; the git objects the checkpoints point at
8
+ * live beside it in `repos/`.
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto'
12
+ import { promises as fs } from 'node:fs'
13
+ import path from 'node:path'
14
+
15
+ /** Current registry document version. */
16
+ export const REGISTRY_VERSION = 1
17
+
18
+ /** Checkpoints retained per session before the oldest are forgotten. */
19
+ const DEFAULT_MAX_CHECKPOINTS = 400
20
+
21
+ /** Normalize a workspace path used as a registry key. */
22
+ export function workspaceKey(value) {
23
+ const resolved = path.resolve(String(value))
24
+ return resolved.length > 1 && resolved.endsWith(path.sep) ? resolved.slice(0, -1) : resolved
25
+ }
26
+
27
+ /**
28
+ * Whether one directory is inside (or equal to) a workspace root.
29
+ * @param root - absolute workspace root.
30
+ * @param cwd - absolute directory to test.
31
+ * @returns {boolean}
32
+ */
33
+ export function workspaceContains(root, cwd) {
34
+ if (!root || !cwd) return false
35
+ const relative = path.relative(path.resolve(root), path.resolve(cwd))
36
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
37
+ }
38
+
39
+ /** One registry failure with a stable code for the UI. */
40
+ export class RegistryError extends Error {
41
+ constructor(message, code = 'registry/failed') {
42
+ super(message)
43
+ this.name = 'RegistryError'
44
+ this.code = code
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Load, mutate, and persist the checkpoint registry.
50
+ */
51
+ export class CheckpointRegistry {
52
+ /**
53
+ * @param options - data directory, optional clock/id factories.
54
+ */
55
+ constructor(options) {
56
+ this.dataDir = options.dataDir
57
+ this.file = path.join(options.dataDir, 'index.json')
58
+ this.maxCheckpoints = Number.isSafeInteger(options.maxCheckpoints) ? options.maxCheckpoints : DEFAULT_MAX_CHECKPOINTS
59
+ this.now = options.now ?? (() => Date.now())
60
+ this.uuid = options.uuid ?? (() => randomUUID())
61
+ this.logger = options.logger
62
+ this.onDrop = options.onDrop ?? null
63
+ this.state = null
64
+ this.loading = null
65
+ this.saving = Promise.resolve()
66
+ }
67
+
68
+ /** @returns {Promise<object>} the loaded registry state. */
69
+ async open() {
70
+ if (this.state) return this.state
71
+ if (this.loading) return this.loading
72
+ this.loading = (async () => {
73
+ let parsed
74
+ try {
75
+ parsed = JSON.parse(await fs.readFile(this.file, 'utf8'))
76
+ } catch (error) {
77
+ if (error?.code !== 'ENOENT') {
78
+ this.logger?.warn?.(`timeback: checkpoint registry unreadable, starting fresh: ${error?.message ?? error}`)
79
+ }
80
+ parsed = undefined
81
+ }
82
+ this.state = normalizeState(parsed)
83
+ return this.state
84
+ })()
85
+ return this.loading
86
+ }
87
+
88
+ /** Persist the current state atomically. */
89
+ flush() {
90
+ this.saving = this.saving.then(async () => {
91
+ if (!this.state) return
92
+ await fs.mkdir(this.dataDir, { recursive: true, mode: 0o700 })
93
+ await fs.chmod(this.dataDir, 0o700).catch(() => {})
94
+ const temporary = `${this.file}.tmp-${process.pid}-${this.uuid()}`
95
+ await fs.writeFile(temporary, `${JSON.stringify(this.state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
96
+ await fs.rename(temporary, this.file)
97
+ await fs.chmod(this.file, 0o600).catch(() => {})
98
+ })
99
+ return this.saving
100
+ }
101
+
102
+ /** @returns {object|undefined} one registered session record. */
103
+ session(sessionId) {
104
+ return this.state?.sessions?.[sessionId]
105
+ }
106
+
107
+ /** @returns {object[]} every registered session record. */
108
+ sessions() {
109
+ return Object.values(this.state?.sessions ?? {})
110
+ }
111
+
112
+ /**
113
+ * Ensure one session record exists and merge creation facts into it.
114
+ * @returns {Promise<object>} the session record.
115
+ */
116
+ async ensureSession(input) {
117
+ await this.open()
118
+ const existing = this.state.sessions[input.sessionId]
119
+ const at = this.now()
120
+ if (existing) {
121
+ let changed = false
122
+ for (const field of ['cwd', 'title', 'parentSessionId', 'forkAtSeq', 'forkCheckpointId']) {
123
+ const value = input[field]
124
+ if (value !== undefined && value !== null && existing[field] !== value) {
125
+ existing[field] = value
126
+ changed = true
127
+ }
128
+ }
129
+ if (changed) {
130
+ existing.updatedAt = at
131
+ await this.flush()
132
+ }
133
+ return existing
134
+ }
135
+ const record = {
136
+ id: input.sessionId,
137
+ cwd: input.cwd ?? null,
138
+ title: input.title ?? null,
139
+ captureError: null,
140
+ parentSessionId: input.parentSessionId ?? null,
141
+ forkAtSeq: input.forkAtSeq ?? null,
142
+ forkCheckpointId: input.forkCheckpointId ?? null,
143
+ createdAt: at,
144
+ updatedAt: at,
145
+ lastEndSeq: null,
146
+ note: null,
147
+ checkpoints: [],
148
+ }
149
+ this.state.sessions[input.sessionId] = record
150
+ await this.flush()
151
+ return record
152
+ }
153
+
154
+ /**
155
+ * Record one checkpoint.
156
+ * @param sessionId - owning session.
157
+ * @param checkpoint - checkpoint fields; `id` is minted when omitted.
158
+ * @returns {Promise<object>} the stored checkpoint.
159
+ */
160
+ async addCheckpoint(sessionId, checkpoint) {
161
+ await this.open()
162
+ const session = this.state.sessions[sessionId]
163
+ if (!session) throw new RegistryError(`未知会话:${sessionId}`, 'registry/session-unknown')
164
+ const stored = {
165
+ id: checkpoint.id ?? `cp-${this.uuid()}`,
166
+ turn: checkpoint.turn ?? null,
167
+ phase: checkpoint.phase ?? 'manual',
168
+ seq: Number.isSafeInteger(checkpoint.seq) ? checkpoint.seq : null,
169
+ createdAt: checkpoint.createdAt ?? this.now(),
170
+ label: checkpoint.label ?? null,
171
+ prompt: checkpoint.prompt ?? null,
172
+ snapshot: checkpoint.snapshot ?? null,
173
+ files: checkpoint.files ?? null,
174
+ note: normalizeNote(checkpoint.note),
175
+ boardVersion: Number.isSafeInteger(checkpoint.boardVersion) ? checkpoint.boardVersion : null,
176
+ error: checkpoint.error ?? null,
177
+ }
178
+ session.checkpoints.push(stored)
179
+ session.captureError = null
180
+ const excess = session.checkpoints.length - this.maxCheckpoints
181
+ let dropped = []
182
+ if (excess > 0) dropped = session.checkpoints.splice(0, excess)
183
+ session.updatedAt = this.now()
184
+ if (Number.isSafeInteger(checkpoint.lastEndSeq)) session.lastEndSeq = checkpoint.lastEndSeq
185
+ await this.flush()
186
+ if (dropped.length > 0 && this.onDrop) {
187
+ try {
188
+ await this.onDrop(sessionId, dropped)
189
+ } catch (error) {
190
+ this.logger?.warn?.(`timeback: dropping snapshot refs failed: ${error?.message ?? error}`)
191
+ }
192
+ }
193
+ return stored
194
+ }
195
+
196
+ /**
197
+ * Save the free-text note shown on one checkpoint card.
198
+ * @returns {Promise<object|undefined>} the updated checkpoint.
199
+ */
200
+ async updateCheckpointNote(sessionId, checkpointId, note) {
201
+ await this.open()
202
+ const session = this.state.sessions[sessionId]
203
+ if (!session) throw new RegistryError(`未知会话:${sessionId}`, 'registry/session-unknown')
204
+ const checkpoint = session.checkpoints.find((candidate) => candidate.id === checkpointId)
205
+ if (!checkpoint) throw new RegistryError('找不到该检查点', 'registry/checkpoint-unknown')
206
+ checkpoint.note = normalizeNote(note)
207
+ session.updatedAt = this.now()
208
+ await this.flush()
209
+ return checkpoint
210
+ }
211
+
212
+ /** Save the session-level note shown on the branch start card. */
213
+ async updateSessionNote(sessionId, note) {
214
+ await this.open()
215
+ const session = this.state.sessions[sessionId]
216
+ if (!session) throw new RegistryError(`未知会话:${sessionId}`, 'registry/session-unknown')
217
+ session.note = normalizeNote(note)
218
+ session.updatedAt = this.now()
219
+ await this.flush()
220
+ return session
221
+ }
222
+
223
+ /** @returns {{sessionId: string, checkpoint: object}|undefined} a checkpoint by id. */
224
+ findCheckpoint(checkpointId) {
225
+ for (const session of this.sessions()) {
226
+ const checkpoint = session.checkpoints.find((candidate) => candidate.id === checkpointId)
227
+ if (checkpoint) return { sessionId: session.id, checkpoint }
228
+ }
229
+ return undefined
230
+ }
231
+
232
+ /** @returns {object[]} one session's checkpoints in insertion order. */
233
+ checkpoints(sessionId) {
234
+ return this.session(sessionId)?.checkpoints?.slice() ?? []
235
+ }
236
+
237
+ /** @returns {{path: string, enabledAt: number}[]} workspaces opted into recording. */
238
+ workspaces() {
239
+ return Object.entries(this.state?.workspaces ?? {})
240
+ .map(([workspacePath, record]) => ({ path: workspacePath, enabledAt: record?.enabledAt ?? null }))
241
+ .sort((left, right) => left.path.localeCompare(right.path))
242
+ }
243
+
244
+ /**
245
+ * The most specific recording policy that covers `cwd`: the longest matching
246
+ * enabled root or explicitly disabled subdirectory.
247
+ * @returns {{path: string, enabled: boolean}|null}
248
+ */
249
+ policyFor(cwd) {
250
+ if (!cwd) return null
251
+ const key = workspaceKey(cwd)
252
+ let matched = null
253
+ const consider = (workspacePath, enabled) => {
254
+ if (!workspaceContains(workspacePath, key)) return
255
+ if (matched === null || workspacePath.length > matched.path.length) {
256
+ matched = { path: workspacePath, enabled }
257
+ } else if (workspacePath.length === matched.path.length && enabled) {
258
+ matched = { path: workspacePath, enabled }
259
+ }
260
+ }
261
+ for (const workspacePath of Object.keys(this.state?.workspaces ?? {})) consider(workspacePath, true)
262
+ for (const workspacePath of Object.keys(this.state?.excluded ?? {})) consider(workspacePath, false)
263
+ return matched
264
+ }
265
+
266
+ /**
267
+ * @returns {string|null} the enabled workspace root that covers `cwd`, or null
268
+ * when `cwd` was explicitly disabled or nothing covers it.
269
+ */
270
+ workspaceRootFor(cwd) {
271
+ const policy = this.policyFor(cwd)
272
+ return policy && policy.enabled ? policy.path : null
273
+ }
274
+
275
+ /** @returns {{path: string, disabledAt: number|null}[]} subdirectories opted out. */
276
+ excludedWorkspaces() {
277
+ return Object.entries(this.state?.excluded ?? {})
278
+ .map(([workspacePath, record]) => ({ path: workspacePath, disabledAt: record?.disabledAt ?? null }))
279
+ .sort((left, right) => left.path.localeCompare(right.path))
280
+ }
281
+
282
+ /** @returns {boolean} whether recording is enabled for this directory. */
283
+ isWorkspaceEnabled(cwd) {
284
+ return this.workspaceRootFor(cwd) !== null
285
+ }
286
+
287
+ /**
288
+ * Enable or disable recording for one workspace.
289
+ * @param cwd - absolute workspace directory.
290
+ * @param enabled - requested state.
291
+ * @returns {Promise<{path: string, enabled: boolean}>}
292
+ */
293
+ async setWorkspaceEnabled(cwd, enabled) {
294
+ await this.open()
295
+ const key = workspaceKey(cwd)
296
+ this.state.excluded ||= {}
297
+ if (enabled) {
298
+ delete this.state.excluded[key]
299
+ this.state.workspaces[key] = { enabledAt: this.now() }
300
+ } else {
301
+ delete this.state.workspaces[key]
302
+ // An explicit off on a subdirectory overrides an enabled parent, so the
303
+ // switch really stays off there instead of being inherited back on.
304
+ this.state.excluded[key] = { disabledAt: this.now() }
305
+ // A disabled workspace should not keep showing an old capture failure.
306
+ for (const session of Object.values(this.state.sessions)) {
307
+ if (typeof session.cwd === 'string' && workspaceContains(key, session.cwd)) session.captureError = null
308
+ }
309
+ }
310
+ await this.flush()
311
+ return { path: key, enabled: Boolean(enabled) }
312
+ }
313
+
314
+ /** Merge session-level facts such as the latest completed turn sequence. */
315
+ async updateSession(sessionId, patch) {
316
+ await this.open()
317
+ const session = this.state?.sessions?.[sessionId]
318
+ if (!session) return undefined
319
+ let changed = false
320
+ for (const [key, value] of Object.entries(patch)) {
321
+ if (value === undefined) continue
322
+ if (key === 'lastEndSeq' && !Number.isSafeInteger(value)) continue
323
+ if (session[key] !== value) {
324
+ session[key] = value
325
+ changed = true
326
+ }
327
+ }
328
+ if (changed) {
329
+ session.updatedAt = this.now()
330
+ await this.flush()
331
+ }
332
+ return session
333
+ }
334
+ }
335
+
336
+ const NOTE_LIMIT = 4000
337
+
338
+ /** Trim a user note to the stored shape. */
339
+ function normalizeNote(value) {
340
+ const text = typeof value === 'string' ? value.trim() : ''
341
+ return text === '' ? null : text.slice(0, NOTE_LIMIT)
342
+ }
343
+
344
+ /** Validate a loaded document and repair a missing or partial shape. */
345
+ function normalizeState(parsed) {
346
+ const state = parsed && typeof parsed === 'object' ? parsed : {}
347
+ if (!state.sessions || typeof state.sessions !== 'object' || Array.isArray(state.sessions)) state.sessions = {}
348
+ if (!state.workspaces || typeof state.workspaces !== 'object' || Array.isArray(state.workspaces)) state.workspaces = {}
349
+ if (!state.excluded || typeof state.excluded !== 'object' || Array.isArray(state.excluded)) state.excluded = {}
350
+ for (const map of [state.workspaces, state.excluded]) {
351
+ for (const [workspacePath, record] of Object.entries(map)) {
352
+ if (typeof workspacePath !== 'string' || workspacePath === '' || !path.isAbsolute(workspacePath)) {
353
+ delete map[workspacePath]
354
+ continue
355
+ }
356
+ if (!record || typeof record !== 'object') map[workspacePath] = map === state.workspaces ? { enabledAt: Date.now() } : { disabledAt: Date.now() }
357
+ }
358
+ }
359
+ // A path cannot be both enabled and excluded; latest write wins on load.
360
+ for (const workspacePath of Object.keys(state.excluded)) {
361
+ if (Object.prototype.hasOwnProperty.call(state.workspaces, workspacePath)) delete state.excluded[workspacePath]
362
+ }
363
+ state.version = REGISTRY_VERSION
364
+ for (const [sessionId, session] of Object.entries(state.sessions)) {
365
+ if (!session || typeof session !== 'object') {
366
+ delete state.sessions[sessionId]
367
+ continue
368
+ }
369
+ session.id = session.id ?? sessionId
370
+ session.checkpoints = Array.isArray(session.checkpoints) ? session.checkpoints.filter((entry) => entry && typeof entry === 'object') : []
371
+ session.note = typeof session.note === 'string' && session.note !== '' ? session.note.slice(0, NOTE_LIMIT) : null
372
+ for (const checkpoint of session.checkpoints) {
373
+ checkpoint.note = typeof checkpoint.note === 'string' && checkpoint.note !== '' ? checkpoint.note.slice(0, NOTE_LIMIT) : null
374
+ checkpoint.boardVersion = Number.isSafeInteger(checkpoint.boardVersion) ? checkpoint.boardVersion : null
375
+ }
376
+ session.updatedAt = Number.isFinite(session.updatedAt) ? session.updatedAt : Date.now()
377
+ session.createdAt = Number.isFinite(session.createdAt) ? session.createdAt : session.updatedAt
378
+ session.captureError = typeof session.captureError === 'string' ? session.captureError : null
379
+ }
380
+ return state
381
+ }
382
+
383
+ export default CheckpointRegistry