@sanqianx/project-knowledge 5.0.19 → 5.0.20-rc.1

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 (200) hide show
  1. package/.agents/plugins/marketplace.json +3 -3
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +5 -0
  4. package/LICENSE +201 -201
  5. package/NOTICE +5 -5
  6. package/README.md +349 -349
  7. package/_modules/knowledge-engine/README.md +4 -0
  8. package/_modules/knowledge-engine/src/analysis-failures.js +39 -0
  9. package/_modules/knowledge-engine/src/analysis-worker.js +6 -2
  10. package/_modules/knowledge-engine/src/coordinator.js +7 -0
  11. package/_modules/knowledge-engine/src/headless-analyzer.js +2 -1
  12. package/_modules/knowledge-engine/src/server.js +1 -1
  13. package/_site/_test/agent-capture-mcp-ui-test.js +67 -67
  14. package/_site/_test/ai-profile-test.js +75 -75
  15. package/_site/_test/ai-vendor-presets-test.js +91 -91
  16. package/_site/_test/automatic-context-test.js +70 -70
  17. package/_site/_test/bin-cli-test.js +230 -230
  18. package/_site/_test/bridge-adapter-test.js +95 -95
  19. package/_site/_test/bridge-consumer-service-test.js +310 -310
  20. package/_site/_test/candidate-bin-content-test.js +35 -35
  21. package/_site/_test/candidate-product-assets-test.js +13 -13
  22. package/_site/_test/candidate-release-contract-test.js +14 -14
  23. package/_site/_test/capture-hook-dedup-test.js +158 -158
  24. package/_site/_test/claude-executable-discovery-test.js +28 -28
  25. package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -252
  26. package/_site/_test/cli-instance-management-test.js +62 -62
  27. package/_site/_test/client-capture-restart-e2e-test.js +189 -189
  28. package/_site/_test/codex-conversation-projection-test.js +60 -60
  29. package/_site/_test/codex-marketplace-scoped-path-test.js +186 -186
  30. package/_site/_test/codex-notify-capture-e2e-test.js +101 -101
  31. package/_site/_test/codex-notify-fanout-test.js +134 -134
  32. package/_site/_test/codex-notify-upgrade-test.js +253 -253
  33. package/_site/_test/commit-boundary-freeze-test.js +147 -147
  34. package/_site/_test/commit-conversation-binding-test.js +4 -4
  35. package/_site/_test/configuration-generation-test.js +22 -22
  36. package/_site/_test/context-pack-test.js +200 -200
  37. package/_site/_test/conversation-api-test.js +10 -10
  38. package/_site/_test/conversation-origin-test.js +15 -15
  39. package/_site/_test/cross-repo-isolation-e2e-test.js +187 -187
  40. package/_site/_test/embedding-config-test.js +32 -32
  41. package/_site/_test/fixtures/fake-browser-exit.js +10 -10
  42. package/_site/_test/fixtures/fake-browser-hang.js +10 -10
  43. package/_site/_test/fixtures/integration-busy-worker.cjs +6 -6
  44. package/_site/_test/fixtures/make-git-repos.js +92 -92
  45. package/_site/_test/fixtures/retrieval-gold-queries.json +32 -32
  46. package/_site/_test/fresh-hook-reimport-test.js +53 -53
  47. package/_site/_test/fresh-product-data-test.js +56 -56
  48. package/_site/_test/git-path-compatibility-test.js +80 -80
  49. package/_site/_test/git-validation-test.js +81 -81
  50. package/_site/_test/hook-worktree-test.js +42 -42
  51. package/_site/_test/index-builder-test.js +41 -41
  52. package/_site/_test/index-error-display-contract-test.js +10 -10
  53. package/_site/_test/integration-adapters-test.js +67 -67
  54. package/_site/_test/integration-capture-setup-test.js +118 -118
  55. package/_site/_test/integration-runtime-binding-a2-test.js +566 -566
  56. package/_site/_test/integration-runtime-binding-a3-test.js +227 -227
  57. package/_site/_test/integration-runtime-binding-test.js +473 -473
  58. package/_site/_test/integration-status-scan-test.js +29 -29
  59. package/_site/_test/kb-framework-test.js +57 -57
  60. package/_site/_test/kbpath-follow-test.js +63 -63
  61. package/_site/_test/knowledge-db-test.js +144 -144
  62. package/_site/_test/knowledge-engine-client-test.js +109 -109
  63. package/_site/_test/knowledge-maintenance-test.js +40 -40
  64. package/_site/_test/knowledge-panel-ui-contract-test.js +112 -0
  65. package/_site/_test/knowledge-scopes-test.js +37 -37
  66. package/_site/_test/knowledge-storage-location-test.js +28 -28
  67. package/_site/_test/launcher-readiness-test.js +80 -80
  68. package/_site/_test/legacy-claude-session-alias-test.js +106 -106
  69. package/_site/_test/legacy-routes-removed-test.js +47 -47
  70. package/_site/_test/legacy-workbench-exclusion-test.js +92 -92
  71. package/_site/_test/live-gateway-test.js +48 -48
  72. package/_site/_test/local-marketplace-test.js +16 -16
  73. package/_site/_test/log-redaction-test.js +58 -58
  74. package/_site/_test/markdown-maintenance-test.js +11 -11
  75. package/_site/_test/model-context-windows-test.js +89 -89
  76. package/_site/_test/module-agent-start-proxy-test.js +65 -65
  77. package/_site/_test/module-artifact-integrity-test.js +27 -27
  78. package/_site/_test/module-boundary-test.js +30 -30
  79. package/_site/_test/module-bridge-eventbridge-test.js +202 -202
  80. package/_site/_test/module-dynamic-port-test.js +118 -118
  81. package/_site/_test/module-index-proxy-test.js +33 -33
  82. package/_site/_test/module-model-configuration-test.js +44 -44
  83. package/_site/_test/module-process-lifecycle-test.js +35 -35
  84. package/_site/_test/module-stream-proxy-test.js +34 -34
  85. package/_site/_test/module-terminal-restart-test.js +63 -63
  86. package/_site/_test/module-wiring-unbind-race-test.js +59 -59
  87. package/_site/_test/native-context-integrations-test.js +86 -86
  88. package/_site/_test/orphaned-claim-recovery-test.js +80 -80
  89. package/_site/_test/package-boundary-test.js +43 -42
  90. package/_site/_test/package-startup-test.js +56 -56
  91. package/_site/_test/packaged-ui-smoke-test.js +88 -88
  92. package/_site/_test/pr-consumer-contract-test.js +55 -55
  93. package/_site/_test/product-brand-contract-test.js +25 -25
  94. package/_site/_test/product-diagnostics-ui-test.js +93 -93
  95. package/_site/_test/product-import-ui-test.js +104 -104
  96. package/_site/_test/product-progress-status-test.js +12 -1
  97. package/_site/_test/project-remove-running-guard-test.js +79 -79
  98. package/_site/_test/project-store-test.js +90 -90
  99. package/_site/_test/registry-events-test.js +38 -38
  100. package/_site/_test/release-version-sync-test.js +115 -115
  101. package/_site/_test/requirement-binding-test.js +113 -113
  102. package/_site/_test/runtime-endpoint-test.js +64 -64
  103. package/_site/_test/scanner-test.js +83 -83
  104. package/_site/_test/server-security-test.js +96 -96
  105. package/_site/_test/sessions-stream-test.js +93 -93
  106. package/_site/_test/shared-scope-root-binding-test.js +67 -67
  107. package/_site/_test/simple-import-test.js +98 -98
  108. package/_site/_test/startup-analysis-disabled-test.js +6 -6
  109. package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -196
  110. package/_site/_test/team-knowledge-store-test.js +132 -132
  111. package/_site/_test/test-server-cleanup-test.js +35 -35
  112. package/_site/_test/test-server-module-isolation-test.js +37 -37
  113. package/_site/_test/tracking-start-test.js +35 -35
  114. package/_site/_test/workbench-context-receipts-test.js +22 -22
  115. package/_site/_test/workspace-ui-contract-test.js +31 -31
  116. package/_site/_test/zcode-capture-integration-test.js +108 -108
  117. package/_site/lib/ai-vendor-presets.js +83 -83
  118. package/_site/lib/ai-workspace.js +3 -3
  119. package/_site/lib/atomic-file.js +204 -204
  120. package/_site/lib/bridge-adapter.js +260 -260
  121. package/_site/lib/capture-hook-config.js +108 -108
  122. package/_site/lib/claude-cli-runner.js +89 -89
  123. package/_site/lib/cli-instances.js +43 -43
  124. package/_site/lib/codex-context-status.js +17 -17
  125. package/_site/lib/codex-notify-config.js +193 -193
  126. package/_site/lib/commit-conversation-binder.js +12 -12
  127. package/_site/lib/commit-reconciler.js +38 -38
  128. package/_site/lib/context-pack-builder.js +299 -299
  129. package/_site/lib/conversation-exclusions.js +204 -204
  130. package/_site/lib/conversation-query-service.js +17 -17
  131. package/_site/lib/data-dir.js +13 -13
  132. package/_site/lib/embedding-service.js +85 -85
  133. package/_site/lib/engine-connection.js +93 -93
  134. package/_site/lib/engine-knowledge-client.js +72 -72
  135. package/_site/lib/folder-picker-output.js +3 -3
  136. package/_site/lib/git-path.js +14 -14
  137. package/_site/lib/github-team-store.js +3 -3
  138. package/_site/lib/index-builder.js +157 -157
  139. package/_site/lib/integration-status-scan.js +99 -99
  140. package/_site/lib/integration-status-worker.js +14 -14
  141. package/_site/lib/kb-framework.js +15 -15
  142. package/_site/lib/knowledge-db.js +363 -363
  143. package/_site/lib/knowledge-schema.js +121 -121
  144. package/_site/lib/live-gateway.js +78 -78
  145. package/_site/lib/llm-client.js +12 -12
  146. package/_site/lib/model-context-windows.js +82 -82
  147. package/_site/lib/module-bridge.js +874 -874
  148. package/_site/lib/module-port-resolver.js +57 -57
  149. package/_site/lib/post-commit-automation.js +54 -54
  150. package/_site/lib/product-data.js +35 -35
  151. package/_site/lib/project-lifecycle-service.js +14 -14
  152. package/_site/lib/project-registry-store.js +129 -129
  153. package/_site/lib/prompt-registry.js +148 -148
  154. package/_site/lib/registry-events.js +16 -16
  155. package/_site/lib/requirement-adapters.js +10 -10
  156. package/_site/lib/requirement-binder.js +112 -112
  157. package/_site/lib/runtime-control.js +89 -89
  158. package/_site/lib/runtime-endpoint.js +5 -5
  159. package/_site/lib/zcode-context-integration.js +60 -60
  160. package/_site/scripts/codex-notify-fanout.cjs +95 -95
  161. package/_site/scripts/install-module-candidates.js +69 -69
  162. package/_site/scripts/pack-module-candidates.js +89 -89
  163. package/_site/scripts/sync-product-content.js +28 -28
  164. package/_site/scripts/sync-release-version.js +164 -164
  165. package/_site/scripts/vendor-modules.js +49 -49
  166. package/_site/scripts/verify-module-runtime.js +50 -50
  167. package/_site/scripts/verify-product-runtime.js +36 -36
  168. package/_site/scripts/verify-retrieval-gold.js +83 -83
  169. package/_site/server.js +15 -15
  170. package/_site/start.bat +26 -26
  171. package/_site/stop.bat +11 -11
  172. package/bin/project-knowledge-integrations.js +254 -254
  173. package/bin/project-knowledge-kb.js +67 -67
  174. package/bin/project-knowledge-mcp.js +8 -8
  175. package/bin/project-knowledge.js +170 -170
  176. package/claude-prompts.json +21 -21
  177. package/docs/README.zh-CN.md +205 -205
  178. package/docs/assets/architecture.svg +181 -181
  179. package/docs/assets/logo.svg +49 -49
  180. package/docs/fresh-v5-start.md +42 -42
  181. package/docs/leader-glm-workbench-playbook.md +122 -122
  182. package/docs/project-registry-schema.md +11 -11
  183. package/docs/release-5.0.16-acceptance.md +176 -176
  184. package/docs/release-5.0.17-acceptance.md +117 -117
  185. package/docs/release-5.0.19-acceptance.md +39 -25
  186. package/docs/team-knowledge-mode-a-plan.md +73 -73
  187. package/module-runtime-manifest.json +53 -33
  188. package/package.json +3 -2
  189. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  190. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  191. package/plugins/project-knowledge/.mcp.json +1 -1
  192. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  193. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  194. package/templates/change.md +30 -30
  195. package/templates/project-readme.md +18 -18
  196. package/ui/index.html +1 -1
  197. package/ui/knowledge-panel.html +118 -0
  198. package/ui/product.css +8 -0
  199. package/ui/product.js +146 -4
  200. package/vendor-manifest.json +55 -54
@@ -1,204 +1,204 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const { DomainError } = require('./contracts');
5
-
6
- const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
7
- const DEFAULT_STALE_LOCK_MS = 120_000;
8
-
9
- function delay(ms) {
10
- return new Promise(resolve => setTimeout(resolve, ms));
11
- }
12
-
13
- function isProcessAlive(pid) {
14
- if (!Number.isInteger(pid) || pid <= 0) return false;
15
- try {
16
- process.kill(pid, 0);
17
- return true;
18
- } catch (error) {
19
- return error && error.code === 'EPERM';
20
- }
21
- }
22
-
23
- function readLockOwner(lockPath) {
24
- try { return JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch { return null; }
25
- }
26
-
27
- function canBreakStaleLock(lockPath, staleMs) {
28
- let stat;
29
- try { stat = fs.statSync(lockPath); } catch { return false; }
30
- const owner = readLockOwner(lockPath);
31
- // A complete owner record lets us recover immediately after a process
32
- // crash. The age threshold is only needed for an incomplete/unreadable
33
- // file that another process may still be creating.
34
- if (owner && Number.isInteger(Number(owner.pid))) return !isProcessAlive(Number(owner.pid));
35
- return (Date.now() - stat.mtimeMs) >= staleMs;
36
- }
37
-
38
- async function acquireFileLock(lockPath, options = {}) {
39
- const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_LOCK_TIMEOUT_MS;
40
- const staleMs = Number.isFinite(options.staleMs) ? options.staleMs : DEFAULT_STALE_LOCK_MS;
41
- const retryMs = Number.isFinite(options.retryMs) ? options.retryMs : 25;
42
- const started = Date.now();
43
- const nonce = crypto.randomBytes(12).toString('hex');
44
- fs.mkdirSync(path.dirname(lockPath), { recursive: true });
45
- while (true) {
46
- try {
47
- const fd = fs.openSync(lockPath, 'wx', 0o600);
48
- const owner = { pid: process.pid, startedAt: new Date().toISOString(), nonce };
49
- fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');
50
- fs.fsyncSync(fd);
51
- fs.closeSync(fd);
52
- return async function release() {
53
- const current = readLockOwner(lockPath);
54
- if (!current || current.nonce !== nonce) return;
55
- try { fs.unlinkSync(lockPath); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
56
- };
57
- } catch (error) {
58
- if (!error || error.code !== 'EEXIST') throw error;
59
- if (canBreakStaleLock(lockPath, staleMs)) {
60
- try { fs.unlinkSync(lockPath); continue; } catch (unlinkError) {
61
- // A competing process may recover the same stale lock first; retry through the normal wait path.
62
- }
63
- }
64
- if ((Date.now() - started) >= timeoutMs) {
65
- throw new DomainError('PROJECT_BUSY', 'Timed out waiting for a file lock.', {
66
- status: 409,
67
- retryable: true,
68
- details: { lockCategory: path.basename(lockPath) },
69
- });
70
- }
71
- await delay(retryMs);
72
- }
73
- }
74
- }
75
-
76
- async function withFileLock(lockPath, fn, options = {}) {
77
- const release = await acquireFileLock(lockPath, options);
78
- try { return await fn(); } finally { await release(); }
79
- }
80
-
81
- function syncDirectoryBestEffort(directory) {
82
- let fd;
83
- try {
84
- fd = fs.openSync(directory, 'r');
85
- fs.fsyncSync(fd);
86
- } catch {
87
- // Directory fsync is unsupported on some filesystems; the file replace is already durable.
88
- } finally {
89
- if (fd != null) try { fs.closeSync(fd); } catch {
90
- // Closing a best-effort directory descriptor cannot invalidate the completed file replace.
91
- }
92
- }
93
- }
94
-
95
- function replaceWithRetry(tempPath, targetPath, options = {}) {
96
- const retries = Number.isInteger(options.renameRetries) ? options.renameRetries : 8;
97
- const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
98
- let lastError;
99
- for (let attempt = 0; attempt <= retries; attempt += 1) {
100
- try {
101
- fs.renameSync(tempPath, targetPath);
102
- return;
103
- } catch (error) {
104
- lastError = error;
105
- if (!error || !['EPERM', 'EACCES', 'EBUSY', 'EEXIST'].includes(error.code) || attempt === retries) break;
106
- Atomics.wait(waitBuffer, 0, 0, Math.min(250, 10 * (2 ** attempt)));
107
- }
108
- }
109
- throw lastError;
110
- }
111
-
112
- function writeFileAtomic(filePath, content, options = {}) {
113
- const directory = path.dirname(filePath);
114
- fs.mkdirSync(directory, { recursive: true });
115
- const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`);
116
- let fd;
117
- try {
118
- fd = fs.openSync(tempPath, 'wx', options.mode || 0o600);
119
- fs.writeFileSync(fd, content, options.encoding || 'utf8');
120
- fs.fsyncSync(fd);
121
- fs.closeSync(fd);
122
- fd = null;
123
- if (typeof options.beforeRename === 'function') options.beforeRename(tempPath, filePath);
124
- replaceWithRetry(tempPath, filePath, options);
125
- syncDirectoryBestEffort(directory);
126
- return { path: filePath };
127
- } catch (error) {
128
- if (fd != null) try { fs.closeSync(fd); } catch {
129
- // Preserve the original write error.
130
- }
131
- try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch {
132
- // Preserve the original write error; stale temp files are never treated as live data.
133
- }
134
- throw error;
135
- }
136
- }
137
-
138
- function writeJsonAtomic(filePath, value, options = {}) {
139
- return writeFileAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`, options);
140
- }
141
-
142
- function readJsonStrict(filePath, options = {}) {
143
- let raw;
144
- try { raw = fs.readFileSync(filePath, 'utf8'); }
145
- catch (error) {
146
- if (error && error.code === 'ENOENT' && options.allowMissing) return options.defaultValue;
147
- throw error;
148
- }
149
- try {
150
- const parsed = JSON.parse(raw);
151
- if (typeof options.validate === 'function') options.validate(parsed);
152
- return parsed;
153
- } catch (error) {
154
- if (error instanceof DomainError) throw error;
155
- throw new DomainError('DATA_CORRUPT', 'A JSON data file is corrupt.', {
156
- status: 500,
157
- cause: error,
158
- details: { category: options.category || 'json' },
159
- });
160
- }
161
- }
162
-
163
- async function appendJsonlLocked(filePath, value, options = {}) {
164
- const lockPath = options.lockPath || `${filePath}.lock`;
165
- return withFileLock(lockPath, async () => {
166
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
167
- const fd = fs.openSync(filePath, 'a', options.mode || 0o600);
168
- try {
169
- fs.writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8');
170
- fs.fsyncSync(fd);
171
- } finally {
172
- fs.closeSync(fd);
173
- }
174
- return value;
175
- }, options);
176
- }
177
-
178
- function cleanupStaleTemps(directory, options = {}) {
179
- if (!fs.existsSync(directory)) return [];
180
- const olderThanMs = Number.isFinite(options.olderThanMs) ? options.olderThanMs : 24 * 60 * 60 * 1000;
181
- const now = Date.now();
182
- const removed = [];
183
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
184
- if (!entry.isFile() || !/^\..+\.\d+\.\d+\.[a-f0-9]+\.tmp$/i.test(entry.name)) continue;
185
- const absolute = path.join(directory, entry.name);
186
- const stat = fs.statSync(absolute);
187
- if ((now - stat.mtimeMs) < olderThanMs) continue;
188
- fs.unlinkSync(absolute);
189
- removed.push(absolute);
190
- }
191
- return removed;
192
- }
193
-
194
- module.exports = {
195
- DEFAULT_LOCK_TIMEOUT_MS,
196
- DEFAULT_STALE_LOCK_MS,
197
- acquireFileLock,
198
- withFileLock,
199
- writeFileAtomic,
200
- writeJsonAtomic,
201
- readJsonStrict,
202
- appendJsonlLocked,
203
- cleanupStaleTemps,
204
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { DomainError } = require('./contracts');
5
+
6
+ const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
7
+ const DEFAULT_STALE_LOCK_MS = 120_000;
8
+
9
+ function delay(ms) {
10
+ return new Promise(resolve => setTimeout(resolve, ms));
11
+ }
12
+
13
+ function isProcessAlive(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ } catch (error) {
19
+ return error && error.code === 'EPERM';
20
+ }
21
+ }
22
+
23
+ function readLockOwner(lockPath) {
24
+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch { return null; }
25
+ }
26
+
27
+ function canBreakStaleLock(lockPath, staleMs) {
28
+ let stat;
29
+ try { stat = fs.statSync(lockPath); } catch { return false; }
30
+ const owner = readLockOwner(lockPath);
31
+ // A complete owner record lets us recover immediately after a process
32
+ // crash. The age threshold is only needed for an incomplete/unreadable
33
+ // file that another process may still be creating.
34
+ if (owner && Number.isInteger(Number(owner.pid))) return !isProcessAlive(Number(owner.pid));
35
+ return (Date.now() - stat.mtimeMs) >= staleMs;
36
+ }
37
+
38
+ async function acquireFileLock(lockPath, options = {}) {
39
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_LOCK_TIMEOUT_MS;
40
+ const staleMs = Number.isFinite(options.staleMs) ? options.staleMs : DEFAULT_STALE_LOCK_MS;
41
+ const retryMs = Number.isFinite(options.retryMs) ? options.retryMs : 25;
42
+ const started = Date.now();
43
+ const nonce = crypto.randomBytes(12).toString('hex');
44
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
45
+ while (true) {
46
+ try {
47
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
48
+ const owner = { pid: process.pid, startedAt: new Date().toISOString(), nonce };
49
+ fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');
50
+ fs.fsyncSync(fd);
51
+ fs.closeSync(fd);
52
+ return async function release() {
53
+ const current = readLockOwner(lockPath);
54
+ if (!current || current.nonce !== nonce) return;
55
+ try { fs.unlinkSync(lockPath); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
56
+ };
57
+ } catch (error) {
58
+ if (!error || error.code !== 'EEXIST') throw error;
59
+ if (canBreakStaleLock(lockPath, staleMs)) {
60
+ try { fs.unlinkSync(lockPath); continue; } catch (unlinkError) {
61
+ // A competing process may recover the same stale lock first; retry through the normal wait path.
62
+ }
63
+ }
64
+ if ((Date.now() - started) >= timeoutMs) {
65
+ throw new DomainError('PROJECT_BUSY', 'Timed out waiting for a file lock.', {
66
+ status: 409,
67
+ retryable: true,
68
+ details: { lockCategory: path.basename(lockPath) },
69
+ });
70
+ }
71
+ await delay(retryMs);
72
+ }
73
+ }
74
+ }
75
+
76
+ async function withFileLock(lockPath, fn, options = {}) {
77
+ const release = await acquireFileLock(lockPath, options);
78
+ try { return await fn(); } finally { await release(); }
79
+ }
80
+
81
+ function syncDirectoryBestEffort(directory) {
82
+ let fd;
83
+ try {
84
+ fd = fs.openSync(directory, 'r');
85
+ fs.fsyncSync(fd);
86
+ } catch {
87
+ // Directory fsync is unsupported on some filesystems; the file replace is already durable.
88
+ } finally {
89
+ if (fd != null) try { fs.closeSync(fd); } catch {
90
+ // Closing a best-effort directory descriptor cannot invalidate the completed file replace.
91
+ }
92
+ }
93
+ }
94
+
95
+ function replaceWithRetry(tempPath, targetPath, options = {}) {
96
+ const retries = Number.isInteger(options.renameRetries) ? options.renameRetries : 8;
97
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
98
+ let lastError;
99
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
100
+ try {
101
+ fs.renameSync(tempPath, targetPath);
102
+ return;
103
+ } catch (error) {
104
+ lastError = error;
105
+ if (!error || !['EPERM', 'EACCES', 'EBUSY', 'EEXIST'].includes(error.code) || attempt === retries) break;
106
+ Atomics.wait(waitBuffer, 0, 0, Math.min(250, 10 * (2 ** attempt)));
107
+ }
108
+ }
109
+ throw lastError;
110
+ }
111
+
112
+ function writeFileAtomic(filePath, content, options = {}) {
113
+ const directory = path.dirname(filePath);
114
+ fs.mkdirSync(directory, { recursive: true });
115
+ const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`);
116
+ let fd;
117
+ try {
118
+ fd = fs.openSync(tempPath, 'wx', options.mode || 0o600);
119
+ fs.writeFileSync(fd, content, options.encoding || 'utf8');
120
+ fs.fsyncSync(fd);
121
+ fs.closeSync(fd);
122
+ fd = null;
123
+ if (typeof options.beforeRename === 'function') options.beforeRename(tempPath, filePath);
124
+ replaceWithRetry(tempPath, filePath, options);
125
+ syncDirectoryBestEffort(directory);
126
+ return { path: filePath };
127
+ } catch (error) {
128
+ if (fd != null) try { fs.closeSync(fd); } catch {
129
+ // Preserve the original write error.
130
+ }
131
+ try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch {
132
+ // Preserve the original write error; stale temp files are never treated as live data.
133
+ }
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ function writeJsonAtomic(filePath, value, options = {}) {
139
+ return writeFileAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`, options);
140
+ }
141
+
142
+ function readJsonStrict(filePath, options = {}) {
143
+ let raw;
144
+ try { raw = fs.readFileSync(filePath, 'utf8'); }
145
+ catch (error) {
146
+ if (error && error.code === 'ENOENT' && options.allowMissing) return options.defaultValue;
147
+ throw error;
148
+ }
149
+ try {
150
+ const parsed = JSON.parse(raw);
151
+ if (typeof options.validate === 'function') options.validate(parsed);
152
+ return parsed;
153
+ } catch (error) {
154
+ if (error instanceof DomainError) throw error;
155
+ throw new DomainError('DATA_CORRUPT', 'A JSON data file is corrupt.', {
156
+ status: 500,
157
+ cause: error,
158
+ details: { category: options.category || 'json' },
159
+ });
160
+ }
161
+ }
162
+
163
+ async function appendJsonlLocked(filePath, value, options = {}) {
164
+ const lockPath = options.lockPath || `${filePath}.lock`;
165
+ return withFileLock(lockPath, async () => {
166
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
167
+ const fd = fs.openSync(filePath, 'a', options.mode || 0o600);
168
+ try {
169
+ fs.writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8');
170
+ fs.fsyncSync(fd);
171
+ } finally {
172
+ fs.closeSync(fd);
173
+ }
174
+ return value;
175
+ }, options);
176
+ }
177
+
178
+ function cleanupStaleTemps(directory, options = {}) {
179
+ if (!fs.existsSync(directory)) return [];
180
+ const olderThanMs = Number.isFinite(options.olderThanMs) ? options.olderThanMs : 24 * 60 * 60 * 1000;
181
+ const now = Date.now();
182
+ const removed = [];
183
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
184
+ if (!entry.isFile() || !/^\..+\.\d+\.\d+\.[a-f0-9]+\.tmp$/i.test(entry.name)) continue;
185
+ const absolute = path.join(directory, entry.name);
186
+ const stat = fs.statSync(absolute);
187
+ if ((now - stat.mtimeMs) < olderThanMs) continue;
188
+ fs.unlinkSync(absolute);
189
+ removed.push(absolute);
190
+ }
191
+ return removed;
192
+ }
193
+
194
+ module.exports = {
195
+ DEFAULT_LOCK_TIMEOUT_MS,
196
+ DEFAULT_STALE_LOCK_MS,
197
+ acquireFileLock,
198
+ withFileLock,
199
+ writeFileAtomic,
200
+ writeJsonAtomic,
201
+ readJsonStrict,
202
+ appendJsonlLocked,
203
+ cleanupStaleTemps,
204
+ };