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,162 @@
1
+ /**
2
+ * Minimal git runner over the Harness Host subprocess capability.
3
+ *
4
+ * Every command runs with a scrubbed environment, a bounded stdout, a hard
5
+ * timeout, and a caller-owned AbortSignal. A nonzero exit is a result, not an
6
+ * exception; infrastructure failures (timeout, abort, unavailable git) throw.
7
+ */
8
+
9
+ /** Milliseconds a git child gets to exit after termination starts. */
10
+ const TERMINATE_GRACE_MS = 2_000
11
+ /** Retained stderr tail for diagnostics. */
12
+ const STDERR_TAIL_BYTES = 16 * 1024
13
+ /** Output retained for one command unless the call overrides it. */
14
+ const DEFAULT_MAX_BYTES = 8 * 1024 * 1024
15
+ /** Default per-command deadline. */
16
+ const DEFAULT_TIMEOUT_MS = 30_000
17
+
18
+ /** A command that could not settle as an ordinary result. */
19
+ export class GitCommandError extends Error {
20
+ constructor(message, details = {}) {
21
+ super(message)
22
+ this.name = 'GitCommandError'
23
+ this.gitArgs = details.args
24
+ this.exitCode = details.exitCode
25
+ this.stderr = details.stderr
26
+ }
27
+ }
28
+
29
+ /** True when an error value is an abort. */
30
+ function isAbortError(error) {
31
+ return error?.name === 'AbortError' || error?.code === 'ABORT_ERR'
32
+ }
33
+
34
+ /**
35
+ * Runner for one resolved git executable.
36
+ */
37
+ export class GitRunner {
38
+ /**
39
+ * @param subprocess - Harness `ctx.subprocess` capability.
40
+ * @param options - limits and plugin lifetime.
41
+ */
42
+ constructor(subprocess, options = {}) {
43
+ this.subprocess = subprocess
44
+ this.timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_TIMEOUT_MS
45
+ this.maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : DEFAULT_MAX_BYTES
46
+ this.lifetime = options.lifetime
47
+ this.logger = options.logger
48
+ this.executable = undefined
49
+ this.resolveError = undefined
50
+ }
51
+
52
+ /**
53
+ * Resolve the git executable once.
54
+ * @returns {Promise<string|null>} the executable, or null when unavailable.
55
+ */
56
+ async ready() {
57
+ if (this.executable !== undefined) return this.executable
58
+ try {
59
+ const signal = this.lifetime?.signal
60
+ if (signal?.aborted) throw new Error('plugin lifetime ended')
61
+ const resolved = await this.subprocess.resolveExecutable('git', undefined, signal ?? new AbortController().signal)
62
+ this.executable = (await this.isUsableGit(resolved, signal)) ? resolved : null
63
+ } catch (error) {
64
+ this.executable = null
65
+ this.resolveError = error
66
+ if (this.logger) this.logger.warn?.(`timeback: git is unavailable (${error?.message ?? error}); file rollback is disabled`)
67
+ }
68
+ return this.executable
69
+ }
70
+
71
+ /**
72
+ * On macOS `/usr/bin/git` is an Xcode developer-tools stub that opens an
73
+ * installer dialog instead of running; probe it before trusting it.
74
+ * @returns {Promise<boolean>} whether the executable behaves as git.
75
+ */
76
+ async isUsableGit(executable, signal) {
77
+ if (process.platform !== 'darwin' || executable !== '/usr/bin/git') return true
78
+ try {
79
+ const probe = this.subprocess.spawn({
80
+ argv: ['/usr/bin/xcode-select', '-p'],
81
+ cwd: process.cwd(),
82
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 4096 }, stderr: { maxBytes: 4096 } },
83
+ graceMs: 1_000,
84
+ signal: signal ?? new AbortController().signal,
85
+ })
86
+ const outcome = await probe.done.catch(() => ({ exitCode: null }))
87
+ return outcome?.exitCode === 0
88
+ } catch {
89
+ return false
90
+ }
91
+ }
92
+
93
+ /** @returns {boolean} whether a usable git was resolved. */
94
+ get available() {
95
+ return typeof this.executable === 'string'
96
+ }
97
+
98
+ /**
99
+ * Run `git <args>` to completion.
100
+ * @param args - git arguments; never shell-interpreted.
101
+ * @param options - cwd, extra environment, stdin data, cancellation, output cap.
102
+ * @returns {Promise<{exitCode: number|null, stdout: string, stderr: string, truncated: boolean}>}
103
+ */
104
+ async run(args, options) {
105
+ const executable = await this.ready()
106
+ if (executable === null) throw new GitCommandError('git is not available on this Host', { args })
107
+ const lifetime = this.lifetime?.signal
108
+ const timeout = AbortSignal.timeout(
109
+ Number.isSafeInteger(options?.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : this.timeoutMs,
110
+ )
111
+ const signals = [timeout]
112
+ if (lifetime) signals.push(lifetime)
113
+ if (options?.signal) signals.push(options.signal)
114
+ const signal = AbortSignal.any(signals)
115
+ const env = {
116
+ GIT_TERMINAL_PROMPT: '0',
117
+ GIT_OPTIONAL_LOCKS: '0',
118
+ GIT_CONFIG_NOSYSTEM: '1',
119
+ GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null',
120
+ LC_ALL: 'C',
121
+ ...(options?.env ?? {}),
122
+ }
123
+ let handle
124
+ try {
125
+ handle = this.subprocess.spawn({
126
+ argv: [executable, ...args],
127
+ cwd: options?.cwd ?? process.cwd(),
128
+ stdio: {
129
+ stdin: options?.stdin === undefined ? 'ignore' : { data: options.stdin },
130
+ stdout: { maxBytes: options?.maxBytes ?? this.maxBytes },
131
+ stderr: { maxBytes: STDERR_TAIL_BYTES },
132
+ },
133
+ graceMs: TERMINATE_GRACE_MS,
134
+ signal,
135
+ env,
136
+ })
137
+ } catch (error) {
138
+ if (isAbortError(error) || timeout.aborted || lifetime?.aborted) {
139
+ throw new GitCommandError(`git ${args[0]} was cancelled`, { args })
140
+ }
141
+ throw new GitCommandError(`git ${args[0]} could not start: ${error?.message ?? error}`, { args })
142
+ }
143
+ let outcome
144
+ try {
145
+ outcome = await handle.done
146
+ } catch (error) {
147
+ throw new GitCommandError(`git ${args[0]} did not settle: ${error?.message ?? error}`, { args })
148
+ }
149
+ if (timeout.aborted) {
150
+ const limit = Number.isSafeInteger(options?.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : this.timeoutMs
151
+ throw new GitCommandError(`git ${args.join(' ')} timed out after ${limit}ms`, { args })
152
+ }
153
+ if (lifetime?.aborted) throw new GitCommandError(`git ${args.join(' ')} was cancelled (plugin disposal)`, { args })
154
+ if (options?.signal?.aborted) throw new GitCommandError(`git ${args.join(' ')} was cancelled`, { args })
155
+ const collected = handle.collected?.stdout
156
+ const stdout = collected?.readFrom(0) ?? { text: '', lossy: false }
157
+ const stderr = handle.collected?.stderr?.readFrom(0)?.text ?? ''
158
+ return { exitCode: outcome?.exitCode ?? null, stdout: stdout.text, stderr, truncated: Boolean(stdout.lossy) }
159
+ }
160
+ }
161
+
162
+ export default GitRunner
package/src/notes.js ADDED
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Notes board storage.
3
+ *
4
+ * The board is a Markdown note collection shared by the whole profile, not by a
5
+ * workspace: the user edits it from the panel, and the agent appends notes with
6
+ * a tool. Every mutation creates a numbered snapshot in `notes-history/`; a
7
+ * checkpoint records the board version it saw, and a rewind restores that board
8
+ * state together with the files and the conversation.
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto'
12
+ import { promises as fs } from 'node:fs'
13
+ import path from 'node:path'
14
+
15
+ const TITLE_LIMIT = 200
16
+ const BODY_LIMIT = 20_000
17
+ const SOURCES = new Set(['user', 'agent', 'session'])
18
+ const MAX_HISTORY = 800
19
+
20
+ /** One notes-board failure with a stable code. */
21
+ export class NotesError extends Error {
22
+ constructor(message, code = 'notes/failed') {
23
+ super(message)
24
+ this.name = 'NotesError'
25
+ this.code = code
26
+ }
27
+ }
28
+
29
+ function clip(value, limit) {
30
+ const text = typeof value === 'string' ? value : value == null ? '' : String(value)
31
+ return text.length <= limit ? text : text.slice(0, limit)
32
+ }
33
+
34
+ function normalizeEntry(input, now) {
35
+ const source = SOURCES.has(input?.source) ? input.source : 'user'
36
+ return {
37
+ id: typeof input?.id === 'string' && input.id !== '' ? input.id : `nt-${randomUUID()}`,
38
+ title: clip(input?.title, TITLE_LIMIT).trim() || '未命名记录',
39
+ body: clip(input?.body, BODY_LIMIT),
40
+ source,
41
+ sessionId: typeof input?.sessionId === 'string' && input.sessionId !== '' ? input.sessionId : null,
42
+ checkpointId: typeof input?.checkpointId === 'string' && input.checkpointId !== '' ? input.checkpointId : null,
43
+ workspace: typeof input?.workspace === 'string' && input.workspace !== '' ? input.workspace : null,
44
+ createdAt: Number.isFinite(input?.createdAt) ? input.createdAt : now,
45
+ updatedAt: Number.isFinite(input?.updatedAt) ? input.updatedAt : now,
46
+ }
47
+ }
48
+
49
+ /** Clone one board state without sharing references. */
50
+ function cloneBoard(board) {
51
+ return {
52
+ version: board.version,
53
+ updatedAt: board.updatedAt,
54
+ entries: board.entries.map((entry) => ({ ...entry })),
55
+ }
56
+ }
57
+
58
+ export class NotesStore {
59
+ /**
60
+ * @param options - data directory, logger, clock and id factories.
61
+ */
62
+ constructor(options = {}) {
63
+ this.dataDir = options.dataDir
64
+ if (typeof this.dataDir !== 'string' || this.dataDir === '') throw new NotesError('缺少 notes 数据目录', 'notes/no-dir')
65
+ this.file = path.join(this.dataDir, 'notes.json')
66
+ this.historyDir = path.join(this.dataDir, 'notes-history')
67
+ this.logger = options.logger
68
+ this.now = options.now ?? (() => Date.now())
69
+ this.maxHistory = Number.isSafeInteger(options.maxHistory) && options.maxHistory >= 10 ? options.maxHistory : MAX_HISTORY
70
+ this.state = null
71
+ this.opening = null
72
+ this.queue = Promise.resolve()
73
+ }
74
+
75
+ /** @returns {number} current board version. */
76
+ get version() {
77
+ return this.state?.version ?? 0
78
+ }
79
+
80
+ /** Load the board once. */
81
+ async open() {
82
+ if (this.state) return this
83
+ if (this.opening) return this.opening
84
+ this.opening = (async () => {
85
+ await fs.mkdir(this.dataDir, { recursive: true, mode: 0o700 })
86
+ await fs.mkdir(this.historyDir, { recursive: true, mode: 0o700 })
87
+ let loaded = null
88
+ try {
89
+ loaded = JSON.parse(await fs.readFile(this.file, 'utf8'))
90
+ } catch (error) {
91
+ if (error?.code !== 'ENOENT') throw new NotesError(`读取记录板失败:${error?.message ?? error}`, 'notes/read-failed')
92
+ }
93
+ const now = this.now()
94
+ const entries = Array.isArray(loaded?.entries) ? loaded.entries.filter((entry) => entry && typeof entry === 'object').map((entry) => normalizeEntry(entry, now)) : []
95
+ this.state = {
96
+ version: Number.isSafeInteger(loaded?.version) && loaded.version >= 0 ? loaded.version : 0,
97
+ updatedAt: Number.isFinite(loaded?.updatedAt) ? loaded.updatedAt : now,
98
+ entries,
99
+ }
100
+ return this
101
+ })().finally(() => {
102
+ this.opening = null
103
+ })
104
+ return this.opening
105
+ }
106
+
107
+ /** @returns {Promise<{version:number,updatedAt:number,entries:object[]}>} cloned board. */
108
+ async board() {
109
+ await this.open()
110
+ return cloneBoard(this.state)
111
+ }
112
+
113
+ /** One note by id (or undefined). */
114
+ async get(id) {
115
+ await this.open()
116
+ return this.state.entries.find((entry) => entry.id === id)
117
+ }
118
+
119
+ /** Run one board mutation under the write queue and snapshot the result. */
120
+ async mutate(mutator, what = '记录板操作') {
121
+ const run = async () => {
122
+ await this.open()
123
+ const draft = cloneBoard(this.state)
124
+ const result = await mutator(draft)
125
+ draft.version = this.state.version + 1
126
+ draft.updatedAt = this.now()
127
+ await this.writeHistory(draft)
128
+ this.state = draft
129
+ await this.writeCurrent(draft)
130
+ return { board: cloneBoard(draft), result }
131
+ }
132
+ const task = this.queue.then(run, run)
133
+ this.queue = task.catch(() => {})
134
+ const outcome = await task.catch((error) => {
135
+ throw error instanceof NotesError ? error : new NotesError(`${what}失败:${error?.message ?? error}`, 'notes/mutate-failed')
136
+ })
137
+ return outcome
138
+ }
139
+
140
+ /** Create one note. */
141
+ async create(input) {
142
+ const now = this.now()
143
+ const entry = normalizeEntry({ ...input, createdAt: now, updatedAt: now }, now)
144
+ const outcome = await this.mutate((draft) => {
145
+ draft.entries.push(entry)
146
+ return { entry }
147
+ }, '新建记录')
148
+ return { entry: outcome.result.entry, board: outcome.board }
149
+ }
150
+
151
+ /** Update one note's title and/or body. */
152
+ async update(id, patch) {
153
+ const outcome = await this.mutate((draft) => {
154
+ const entry = draft.entries.find((candidate) => candidate.id === id)
155
+ if (!entry) throw new NotesError('记录不存在或已删除', 'notes/not-found')
156
+ if (patch.title !== undefined) entry.title = clip(patch.title, TITLE_LIMIT).trim() || '未命名记录'
157
+ if (patch.body !== undefined) entry.body = clip(patch.body, BODY_LIMIT)
158
+ entry.updatedAt = this.now()
159
+ return { entry }
160
+ }, '更新记录')
161
+ return { entry: outcome.result.entry, board: outcome.board }
162
+ }
163
+
164
+ /** Delete one note. */
165
+ async remove(id) {
166
+ const outcome = await this.mutate((draft) => {
167
+ const index = draft.entries.findIndex((candidate) => candidate.id === id)
168
+ if (index === -1) throw new NotesError('记录不存在或已删除', 'notes/not-found')
169
+ const [entry] = draft.entries.splice(index, 1)
170
+ return { entry }
171
+ }, '删除记录')
172
+ return { entry: outcome.result.entry, board: outcome.board }
173
+ }
174
+
175
+ /**
176
+ * Restore the board to one version. The restore itself becomes a new version,
177
+ * so later rewinds can still point at older snapshots and the monotonic
178
+ * version numbers never collide.
179
+ * @returns {Promise<{restoredFrom:number,version:number,entries:number}|null>}
180
+ */
181
+ async restore(version) {
182
+ await this.open()
183
+ if (!Number.isSafeInteger(version) || version < 0) return null
184
+ // Version 0 is the empty board a profile starts with; its snapshot is
185
+ // implicit because the file is only written on the first mutation.
186
+ let snapshot = { entries: [] }
187
+ if (version > 0) {
188
+ try {
189
+ snapshot = JSON.parse(await fs.readFile(path.join(this.historyDir, `${version}.json`), 'utf8'))
190
+ } catch {
191
+ return null
192
+ }
193
+ }
194
+ if (!Array.isArray(snapshot?.entries)) return null
195
+ const outcome = await this.mutate((draft) => {
196
+ draft.entries = snapshot.entries.filter((entry) => entry && typeof entry === 'object').map((entry) => normalizeEntry(entry, this.now()))
197
+ return { restoredFrom: version }
198
+ }, '回溯记录板')
199
+ return { restoredFrom: version, version: outcome.board.version, entries: outcome.board.entries.length }
200
+ }
201
+
202
+ /** Keep history bounded: referenced versions plus the newest unreferenced ones. */
203
+ async pruneHistory(referenced, keep = 200) {
204
+ await this.open()
205
+ const keepVersions = new Set()
206
+ for (const version of referenced ?? []) {
207
+ if (Number.isSafeInteger(version) && version >= 0) keepVersions.add(version)
208
+ }
209
+ let names
210
+ try {
211
+ names = await fs.readdir(this.historyDir)
212
+ } catch {
213
+ return
214
+ }
215
+ const versions = names
216
+ .map((name) => /^(\d+)\.json$/.exec(name)?.[1])
217
+ .filter(Boolean)
218
+ .map(Number)
219
+ .sort((left, right) => right - left)
220
+ const newestUnreferenced = []
221
+ for (const version of versions) {
222
+ if (keepVersions.has(version)) continue
223
+ if (newestUnreferenced.length < Math.max(20, keep)) newestUnreferenced.push(version)
224
+ }
225
+ const drop = new Set(newestUnreferenced.slice(0, Math.max(0, newestUnreferenced.length - keep)))
226
+ for (const version of drop) {
227
+ if (keepVersions.has(version)) continue
228
+ await fs.rm(path.join(this.historyDir, `${version}.json`), { force: true }).catch(() => {})
229
+ }
230
+ }
231
+
232
+ /** Persist the current board atomically. */
233
+ async writeCurrent(board) {
234
+ await this.writeJson(this.file, board)
235
+ }
236
+
237
+ /** Persist one historical snapshot. */
238
+ async writeHistory(board) {
239
+ await this.writeJson(path.join(this.historyDir, `${board.version}.json`), board)
240
+ }
241
+
242
+ /** Write one JSON file atomically with private permissions. */
243
+ async writeJson(file, value) {
244
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
245
+ const temp = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`
246
+ await fs.writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
247
+ await fs.rename(temp, file)
248
+ await fs.chmod(file, 0o600).catch(() => {})
249
+ }
250
+ }
251
+
252
+ export default { NotesStore, NotesError }