dsh-memory-bond 0.0.0-stage → 1.0.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.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
package/src/domain.ts ADDED
@@ -0,0 +1,254 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs'
4
+ import { hostname } from 'node:os'
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
6
+ import { SignatureCache } from './cache.ts'
7
+
8
+ export interface AccessDomain {
9
+ id: string
10
+ profileDir: string
11
+ root: string
12
+ cwd: string
13
+ machine: string
14
+ git: boolean
15
+ }
16
+
17
+ export const digest = (value: string): string => createHash('sha256').update(value).digest('hex')
18
+
19
+ export function inside(root: string, child: string): boolean {
20
+ const rel = relative(root, child)
21
+ return rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel)
22
+ }
23
+
24
+ function gitValue(cwd: string, ...args: string[]): string | undefined {
25
+ // Ignore process-level repository overrides inherited from a parent Git command.
26
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')))
27
+ try {
28
+ return execFileSync('git', ['-C', cwd, ...args], {
29
+ env,
30
+ encoding: 'utf8',
31
+ stdio: ['ignore', 'pipe', 'ignore'],
32
+ timeout: 1500,
33
+ }).replace(/\r?\n$/, '')
34
+ } catch {
35
+ return undefined
36
+ }
37
+ }
38
+
39
+ export function resolveDomain(
40
+ profileDir: string,
41
+ cwd: string,
42
+ nonGitRoots: readonly string[] = [],
43
+ ): AccessDomain | undefined {
44
+ try {
45
+ if (!isAbsolute(cwd) || !isAbsolute(profileDir)) return
46
+ cwd = realpathSync(cwd)
47
+ profileDir = realpathSync(profileDir)
48
+ if (!statSync(cwd).isDirectory() || !statSync(profileDir).isDirectory()) return
49
+ const machine = digest(JSON.stringify([hostname(), process.getuid?.() ?? process.env.USERNAME]))
50
+ const top = gitValue(cwd, 'rev-parse', '--show-toplevel')
51
+ let root: string, identity: string
52
+ if (top) {
53
+ root = realpathSync(top)
54
+ // --git-common-dir predates --path-format. Some desktop PATHs select a Git
55
+ // that prints the unrecognized switch literally with a successful exit status.
56
+ const common = gitValue(cwd, 'rev-parse', '--git-common-dir')
57
+ if (!common || !inside(root, cwd)) return
58
+ identity = realpathSync(resolve(cwd, common))
59
+ } else {
60
+ // A broken/inaccessible Git checkout cannot be reinterpreted as a trusted non-Git root.
61
+ for (let dir = cwd; ; dir = dirname(dir)) {
62
+ if (existsSync(join(dir, '.git'))) return
63
+ if (dir === dirname(dir)) break
64
+ }
65
+ const allowed: string[] = []
66
+ for (const candidate of nonGitRoots) {
67
+ if (!isAbsolute(candidate)) continue
68
+ try {
69
+ const real = realpathSync(candidate)
70
+ if (inside(real, cwd)) allowed.push(real)
71
+ } catch {
72
+ /* unavailable configured root */
73
+ }
74
+ }
75
+ if (!allowed.length) return
76
+ root = allowed.sort((a, b) => b.length - a.length)[0]
77
+ identity = root
78
+ }
79
+ const location = statSync(identity, { bigint: true })
80
+ const id = digest(
81
+ JSON.stringify([
82
+ machine,
83
+ profileDir,
84
+ top ? 'git' : 'directory',
85
+ identity,
86
+ String(location.dev),
87
+ String(location.ino),
88
+ ]),
89
+ )
90
+ return { id, profileDir, root, cwd, machine, git: Boolean(top) }
91
+ } catch {
92
+ return undefined
93
+ }
94
+ }
95
+
96
+ export function branchOf(domain: AccessDomain): string | undefined {
97
+ return domain.git ? gitValue(domain.root, 'symbolic-ref', '--quiet', '--short', 'HEAD') : undefined
98
+ }
99
+
100
+ // --- Cached variants ---------------------------------------------------------------------
101
+ // resolveDomain()/branchOf() above are kept exact and uncached: tests and maintenance-import.ts
102
+ // rely on calling them directly for a guaranteed-fresh answer. The cached wrappers below exist
103
+ // for the hot, repeated call sites (one resolution per model step, searched multiple times per
104
+ // query) and are safe to reuse there because their signature is re-derived, cheaply, on every
105
+ // call from exactly the filesystem facts that could change the answer - never a blind TTL.
106
+
107
+ const domainCache = new SignatureCache<AccessDomain | undefined>()
108
+
109
+ /** Every directory from cwd to the filesystem root, by its `.git` marker - a repo/worktree boundary. */
110
+ function gitBoundary(cwd: string): string[] {
111
+ const watch = [cwd]
112
+ let dir = cwd
113
+ for (let depth = 0; depth < 256; depth++) {
114
+ watch.push(join(dir, '.git'))
115
+ const parent = dirname(dir)
116
+ if (parent === dir) break
117
+ dir = parent
118
+ }
119
+ return watch
120
+ }
121
+
122
+ /**
123
+ * Cached resolveDomain(): re-validated on every call via a stat-only walk of exactly the
124
+ * boundary a new/removed repository or worktree would touch (no process spawn), so a real cd,
125
+ * `git init`, worktree add/remove, or clone is always seen on the next call.
126
+ */
127
+ export function resolveDomainCached(
128
+ profileDir: string,
129
+ cwd: string,
130
+ nonGitRoots: readonly string[] = [],
131
+ ): AccessDomain | undefined {
132
+ if (!isAbsolute(cwd) || !isAbsolute(profileDir)) return resolveDomain(profileDir, cwd, nonGitRoots)
133
+ let real: string
134
+ try {
135
+ real = realpathSync(cwd)
136
+ } catch {
137
+ return resolveDomain(profileDir, cwd, nonGitRoots)
138
+ }
139
+ const key = [profileDir, real, ...nonGitRoots].join('\u0000')
140
+ const watch = gitBoundary(real)
141
+ // A launch-time Git timeout in an existing checkout says nothing about its identity.
142
+ // Its .git marker will not change when the executable recovers. Retry on the next lookup.
143
+ return domainCache.get(key, watch, () => resolveDomain(profileDir, cwd, nonGitRoots),
144
+ domain => domain !== undefined || !watch.slice(1).some(marker => existsSync(marker)))
145
+ }
146
+
147
+ /** The exact HEAD file this checkout's symbolic ref lives in, resolving a worktree's private gitdir. */
148
+ function headFile(root: string): string | undefined {
149
+ try {
150
+ const marker = join(root, '.git')
151
+ const info = lstatSync(marker)
152
+ if (info.isDirectory()) return join(marker, 'HEAD')
153
+ if (!info.isFile()) return undefined
154
+ const pointer = readFileSync(marker, 'utf8').match(/^gitdir:\s*(.+?)\s*$/mu)?.[1]
155
+ return pointer ? join(isAbsolute(pointer) ? pointer : resolve(root, pointer), 'HEAD') : undefined
156
+ } catch {
157
+ return undefined
158
+ }
159
+ }
160
+
161
+ const branchCache = new SignatureCache<string | undefined>()
162
+
163
+ /** Cached branchOf(): invalidated by this exact checkout's own HEAD file, never a blind TTL. */
164
+ export function branchOfCached(domain: AccessDomain): string | undefined {
165
+ if (!domain.git) return undefined
166
+ const head = headFile(domain.root)
167
+ if (!head) return branchOf(domain)
168
+ return branchCache.get(domain.root, [head], () => branchOf(domain))
169
+ }
170
+
171
+ // Stored project paths and tool schemas use slash-separated paths on every platform.
172
+ export function projectRelative(root: string, path: string): string {
173
+ return relative(root, path).split(sep).join('/')
174
+ }
175
+
176
+ export function cleanRelative(value: string): string {
177
+ const p = value.trim()
178
+ if (
179
+ !p ||
180
+ isAbsolute(p) ||
181
+ p.includes('\\') ||
182
+ /[\x00-\x1f\x7f]/u.test(p) ||
183
+ /^[A-Za-z]:/.test(p) ||
184
+ p.split('/').some((part) => part === '..' || part.toLowerCase() === '.git')
185
+ )
186
+ throw new Error('invalid_path')
187
+ return (
188
+ p
189
+ .split('/')
190
+ .filter((part) => part && part !== '.')
191
+ .join('/') || '.'
192
+ )
193
+ }
194
+
195
+ /** Resolve inside the active checkout. A same-tree symlink is allowed, a foreign checkout is not. */
196
+ export function projectPath(domain: AccessDomain, rel: string): string {
197
+ const clean = cleanRelative(rel)
198
+ let path = domain.root
199
+ for (const part of clean === '.' ? [] : clean.split('/')) {
200
+ path = join(path, part)
201
+ // Checking every existing ancestor also catches dangling symlinks on optional paths.
202
+ let symbolic = false
203
+ try {
204
+ symbolic = lstatSync(path).isSymbolicLink()
205
+ } catch (error) {
206
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
207
+ }
208
+ if (symbolic) {
209
+ try {
210
+ path = realpathSync(path)
211
+ } catch {
212
+ throw new Error('invalid_path')
213
+ }
214
+ if (!inside(domain.root, path)) throw new Error('invalid_path')
215
+ const target = cleanRelative(projectRelative(domain.root, path) || '.')
216
+ // A link directly to a file in a nested checkout skips that checkout's root lexically.
217
+ for (let dir = resolve(domain.root, target); dir !== domain.root; dir = dirname(dir)) {
218
+ if (existsSync(join(dir, '.git'))) throw new Error('invalid_path')
219
+ }
220
+ }
221
+ if (path !== domain.root && existsSync(join(path, '.git'))) throw new Error('invalid_path')
222
+ }
223
+ return path
224
+ }
225
+
226
+ /** Walk components in filesystem order so a symlink followed by ".." cannot hide an escape. */
227
+ export function scopedPath(domain: AccessDomain, target: string, base = domain.cwd): string {
228
+ if (!target || typeof target !== 'string') throw new Error('invalid_path')
229
+ let current = base
230
+ if (isAbsolute(target)) {
231
+ const prefix = domain.root.endsWith(sep) ? domain.root : domain.root + sep
232
+ if (target === domain.root) return domain.root
233
+ if (!target.startsWith(prefix)) throw new Error('invalid_path')
234
+ target = target.slice(prefix.length)
235
+ current = domain.root
236
+ }
237
+ for (const part of target.replaceAll(sep, '/').split('/')) {
238
+ if (!part || part === '.') continue
239
+ current = part === '..' ? dirname(current) : join(current, part)
240
+ if (!inside(domain.root, current)) throw new Error('invalid_path')
241
+ current = projectPath(domain, projectRelative(domain.root, current) || '.')
242
+ }
243
+ return current
244
+ }
245
+
246
+ /** Resolve the effective target of a file tool (or a reported Bash cwd) in this worktree. */
247
+ export function toolPathInDomain(domain: AccessDomain, target: string, workdir = domain.cwd): boolean {
248
+ try {
249
+ scopedPath(domain, target, scopedPath(domain, workdir))
250
+ return true
251
+ } catch {
252
+ return false
253
+ }
254
+ }
package/src/encoder.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { createRequire } from 'node:module'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { Worker } from 'node:worker_threads'
4
+
5
+ export const modelLanguages = ['en', 'zh'] as const
6
+ export type ModelLanguage = (typeof modelLanguages)[number]
7
+ export const language = (text: string): ModelLanguage => /\p{Script=Han}/u.test(text) ? 'zh' : 'en'
8
+ // Mixed queries can search both installed monolingual indexes. Each query vector
9
+ // is compared only to passages encoded by that same model.
10
+ export function queryLanguages(text: string): ModelLanguage[] {
11
+ return modelLanguages.filter(lang => lang === 'zh' ? /\p{Script=Han}/u.test(text) : /\p{Script=Latin}/u.test(text))
12
+ }
13
+ export const encoderId = (language: 'en' | 'zh') =>
14
+ language === 'zh' ? 'bge-small-zh-v1.5/int8/75c43b06/cls-v1' : 'bge-small-en-v1.5/int8/ea104dac/cls-v1'
15
+
16
+ export interface Encoder {
17
+ readonly languages?: readonly ModelLanguage[]
18
+ encode(lang: 'en' | 'zh', texts: string[]): Promise<Float32Array[]>
19
+ close(): void
20
+ }
21
+
22
+ function installedModels() {
23
+ const require = createRequire(import.meta.url)
24
+ const models: Partial<Record<ModelLanguage, string>> = {}
25
+ let worker: URL | undefined
26
+ for (const lang of modelLanguages) {
27
+ try {
28
+ const manifest = require.resolve(`dsh-memory-bond-model-${lang}/package.json`)
29
+ const fromModel = createRequire(manifest)
30
+ fromModel.resolve('./model.onnx')
31
+ fromModel.resolve('./vocab.txt')
32
+ const entry = fromModel.resolve('dsh-memory-bond-onnx/worker.mjs')
33
+ models[lang] = pathToFileURL(manifest).href
34
+ worker ??= pathToFileURL(entry)
35
+ } catch {
36
+ // An absent model or its runtime leaves this language on the FTS path.
37
+ }
38
+ }
39
+ return { models, worker }
40
+ }
41
+ // A stalled WASM call (not a crash) would otherwise wait forever: nothing but this deadline
42
+ // settles the pending request, and the worker's queue is strictly sequential,
43
+ // so every later call on the same worker would starve behind it too.
44
+ const encodeDeadlineMs = 10_000
45
+ // Frees the ONNX runtime and loaded model (hundreds of MB) once nothing has asked for an
46
+ // embedding in a while; the next encode() call pays the cold-start cost again on demand.
47
+ const idleUnloadMs = 5 * 60_000
48
+
49
+ /** Lazily own one inference worker. No installation, network or external executable on the search path. */
50
+ export class SentenceEncoder implements Encoder {
51
+ private worker?: Worker
52
+ private serial = 0
53
+ private pending = new Map<
54
+ number,
55
+ { resolve: (vectors: Float32Array[]) => void; reject: (error: Error) => void }
56
+ >()
57
+ private idleTimer?: ReturnType<typeof setTimeout>
58
+ readonly languages: readonly ModelLanguage[]
59
+ private readonly models?: Partial<Record<ModelLanguage, string>>
60
+ private readonly workerUrl?: URL
61
+ private readonly deadlineMs: number
62
+ private readonly idleMs: number
63
+
64
+ constructor(workerUrl?: URL, deadlineMs = encodeDeadlineMs, idleMs = idleUnloadMs) {
65
+ if (workerUrl) {
66
+ this.workerUrl = workerUrl
67
+ this.languages = modelLanguages
68
+ } else {
69
+ const { models, worker } = installedModels()
70
+ this.models = models
71
+ this.workerUrl = worker
72
+ this.languages = modelLanguages.filter(lang => models[lang])
73
+ }
74
+ this.deadlineMs = deadlineMs
75
+ this.idleMs = idleMs
76
+ }
77
+ private start() {
78
+ const worker = new Worker(this.workerUrl!, { execArgv: [], workerData: this.models })
79
+ this.worker = worker
80
+ worker.on('message', (m: { id: number; vectors?: Float32Array[]; error?: string }) => {
81
+ const pending = this.pending.get(m.id)
82
+ if (!pending) return
83
+ this.pending.delete(m.id)
84
+ if (m.vectors) pending.resolve(m.vectors)
85
+ else pending.reject(new Error('embedding_unavailable'))
86
+ if (!this.pending.size) {
87
+ worker.unref()
88
+ this.scheduleIdleUnload(worker)
89
+ }
90
+ })
91
+ const stopped = () => {
92
+ if (this.worker !== worker) return
93
+ this.worker = undefined
94
+ clearTimeout(this.idleTimer)
95
+ for (const request of this.pending.values()) request.reject(new Error('embedding_unavailable'))
96
+ this.pending.clear()
97
+ }
98
+ worker.once('error', stopped)
99
+ worker.once('exit', stopped)
100
+ return worker
101
+ }
102
+ private scheduleIdleUnload(worker: Worker) {
103
+ clearTimeout(this.idleTimer)
104
+ if (!(this.idleMs > 0) || !Number.isFinite(this.idleMs)) return
105
+ this.idleTimer = setTimeout(() => {
106
+ // Only this exact worker, and only if nothing started using it again meanwhile.
107
+ if (this.worker === worker && !this.pending.size) void worker.terminate()
108
+ }, this.idleMs)
109
+ this.idleTimer.unref?.()
110
+ }
111
+ encode(lang: 'en' | 'zh', texts: string[]) {
112
+ if (!this.languages.includes(lang)) return Promise.reject(new Error('embedding_unavailable'))
113
+ clearTimeout(this.idleTimer)
114
+ const worker = this.worker ?? this.start(),
115
+ id = ++this.serial
116
+ worker.ref()
117
+ return new Promise<Float32Array[]>((resolve, reject) => {
118
+ const timer = setTimeout(() => {
119
+ // The worker received this request but never answered it: replace the worker so a
120
+ // stalled inference call doesn't starve every request queued behind it forever, not
121
+ // just this one. The 'exit' handler above settles this and every other pending request.
122
+ if (this.worker === worker) void worker.terminate()
123
+ }, this.deadlineMs)
124
+ timer.unref?.()
125
+ this.pending.set(id, {
126
+ resolve: (v) => {
127
+ clearTimeout(timer)
128
+ resolve(v)
129
+ },
130
+ reject: (e) => {
131
+ clearTimeout(timer)
132
+ reject(e)
133
+ },
134
+ })
135
+ worker.postMessage({ id, lang, texts })
136
+ })
137
+ }
138
+ close() {
139
+ clearTimeout(this.idleTimer)
140
+ if (this.worker) void this.worker.terminate()
141
+ }
142
+ }
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import {
3
+ closeSync,
4
+ constants,
5
+ existsSync,
6
+ fstatSync,
7
+ fsyncSync,
8
+ linkSync,
9
+ lstatSync,
10
+ mkdirSync,
11
+ openSync,
12
+ readFileSync,
13
+ renameSync,
14
+ statSync,
15
+ unlinkSync,
16
+ writeFileSync,
17
+ } from 'node:fs'
18
+ import { tmpdir } from 'node:os'
19
+ import { basename, dirname, join } from 'node:path'
20
+ import { DatabaseSync } from 'node:sqlite'
21
+ import { digest } from './domain.ts'
22
+ import { StoreError } from './store.ts'
23
+
24
+ export const snapshotHash = (s: string | null) => digest(JSON.stringify(s))
25
+ const missing = (error: unknown) => (error as NodeJS.ErrnoException)?.code === 'ENOENT'
26
+ function unlink(path: string) {
27
+ try {
28
+ unlinkSync(path)
29
+ } catch (error) {
30
+ if (!missing(error)) throw error
31
+ }
32
+ }
33
+ function create(path: string, text: string, mode: number) {
34
+ const fd = openSync(path, 'wx', mode)
35
+ try {
36
+ writeFileSync(fd, text)
37
+ fsyncSync(fd)
38
+ } finally {
39
+ closeSync(fd)
40
+ }
41
+ }
42
+ function hashFile(path: string) {
43
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
44
+ try {
45
+ const stat = fstatSync(fd)
46
+ if (!stat.isFile() || stat.size > 2_000_000) return undefined
47
+ return snapshotHash(readFileSync(fd, 'utf8'))
48
+ } finally {
49
+ closeSync(fd)
50
+ }
51
+ }
52
+ function identity(path: string) {
53
+ try {
54
+ const s = lstatSync(path, { bigint: true })
55
+ return String(s.dev) + '/' + s.ino
56
+ } catch (error) {
57
+ if (!missing(error)) throw error
58
+ }
59
+ }
60
+ interface Intent {
61
+ nonce: string
62
+ before: string
63
+ after: string
64
+ }
65
+ function siblings(target: string, nonce: string) {
66
+ const base = join(dirname(target), '.' + basename(target) + '.dsh-export-' + nonce)
67
+ return { next: base + '.next', previous: base + '.previous' }
68
+ }
69
+ function recover(target: string, journal: string) {
70
+ // Preparing the intent precedes all changes to the checkout. Only a complete atomic record counts.
71
+ unlink(journal + '.prepare')
72
+ if (!existsSync(journal)) return
73
+ const record: Intent = JSON.parse(readFileSync(journal, 'utf8'))
74
+ if (!/^[a-f0-9-]{36}$/u.test(record.nonce) || !/^[a-f0-9]{64}$/u.test(record.before))
75
+ throw new StoreError('invalid_export_journal')
76
+ const { next, previous } = siblings(target, record.nonce)
77
+ let preserved = false
78
+ if (identity(previous)) {
79
+ if (!identity(target)) {
80
+ try {
81
+ linkSync(previous, target)
82
+ } catch (error) {
83
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
84
+ }
85
+ }
86
+ // Editors may replace a path, or keep writing the inode they had open. Preserve both versions on divergence.
87
+ if (identity(previous) === identity(target) || hashFile(previous) === record.before) unlink(previous)
88
+ else preserved = true
89
+ }
90
+ unlink(next)
91
+ unlink(journal)
92
+ if (preserved)
93
+ throw new StoreError(
94
+ 'export_conflict',
95
+ '并发修改已保留在 ' + basename(previous) + ',当前目标文件也已保留。',
96
+ )
97
+ }
98
+
99
+ /** A SQLite writer lock is released by the kernel on process exit, without a racy PID/age-based unlock. */
100
+ export function withExportTarget<T>(path: string, work: (journal: string) => T, authorize?: () => void): T {
101
+ // macOS and Linux can run separate DSH profiles with separate HOME and TMPDIR against the same checkout.
102
+ const folder = process.getuid
103
+ ? join('/tmp', 'dsh-export-' + process.getuid())
104
+ : join(tmpdir(), 'dsh-project-memory-exports')
105
+ try {
106
+ mkdirSync(folder, { mode: 0o700 })
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
109
+ }
110
+ const owner = lstatSync(folder)
111
+ if (!owner.isDirectory() || (process.getuid && (owner.uid !== process.getuid() || !!(owner.mode & 0o077))))
112
+ throw new StoreError('invalid_export_lock')
113
+ const key = join(folder, digest(path))
114
+ const lock = new DatabaseSync(key + '.sqlite')
115
+ try {
116
+ lock.exec('PRAGMA busy_timeout=3000; BEGIN IMMEDIATE')
117
+ authorize?.()
118
+ recover(path, key + '.json')
119
+ return work(key + '.json')
120
+ } finally {
121
+ lock.close()
122
+ }
123
+ }
124
+
125
+ export function publishExport(
126
+ path: string,
127
+ before: string | null,
128
+ after: string,
129
+ journal: string,
130
+ append: boolean,
131
+ ) {
132
+ if (before !== null && append && lstatSync(path).nlink === 1) {
133
+ // An append never replaces the bytes of an uncoordinated editor, even if it races the final comparison.
134
+ const fd = openSync(
135
+ path,
136
+ constants.O_RDWR | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK,
137
+ )
138
+ try {
139
+ const stat = fstatSync(fd, { bigint: true })
140
+ if (
141
+ !stat.isFile() ||
142
+ stat.nlink !== 1n ||
143
+ stat.size > 2_000_000n ||
144
+ readFileSync(fd, 'utf8') !== before
145
+ )
146
+ throw new StoreError('stale_preview')
147
+ writeFileSync(fd, after.slice(before.length))
148
+ fsyncSync(fd)
149
+ if (identity(path) !== String(stat.dev) + '/' + stat.ino || hashFile(path) !== snapshotHash(after))
150
+ throw new StoreError('stale_preview')
151
+ } finally {
152
+ closeSync(fd)
153
+ }
154
+ return
155
+ }
156
+ const record: Intent = { nonce: randomUUID(), before: snapshotHash(before), after: snapshotHash(after) }
157
+ const { next, previous } = siblings(path, record.nonce)
158
+ create(journal + '.prepare', JSON.stringify(record), 0o600)
159
+ renameSync(journal + '.prepare', journal)
160
+ try {
161
+ const mode = before === null ? 0o644 : statSync(path).mode & 0o777
162
+ create(next, after, mode)
163
+ if (before !== null) {
164
+ // Claim exactly the version being replaced. A normal rename onto the destination could silently
165
+ // overwrite an editor's newer inode between checking its hash and publishing the replacement.
166
+ renameSync(path, previous)
167
+ if (hashFile(previous) !== record.before) throw new StoreError('stale_preview')
168
+ }
169
+ try {
170
+ linkSync(next, path)
171
+ } catch (error) {
172
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new StoreError('stale_preview')
173
+ throw error
174
+ }
175
+ } finally {
176
+ recover(path, journal)
177
+ }
178
+ }