@sanqianx/project-knowledge 5.0.31 → 5.0.33

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +5 -2
  4. package/_site/_test/automatic-context-test.js +19 -0
  5. package/_site/_test/context-session-index-test.js +244 -0
  6. package/_site/_test/fixtures/retrieval-gold-queries.json +4 -0
  7. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +1 -1
  8. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +1 -1
  9. package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
  10. package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
  11. package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
  12. package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
  13. package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
  14. package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
  15. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +1 -1
  16. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +1 -1
  17. package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
  18. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +1 -1
  19. package/_site/_test/helpers/parallel-memory-injection-shell.js +1 -1
  20. package/_site/_test/helpers/parallel-nav-shell.js +1 -1
  21. package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
  22. package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
  23. package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
  24. package/_site/_test/package-boundary-test.js +5 -0
  25. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +1 -1
  26. package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
  27. package/_site/_test/parallel-knowledge-engine-test.js +3 -3
  28. package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
  29. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +1 -1
  30. package/_site/_test/parallel-memory-injection-origin-probe.js +1 -1
  31. package/_site/_test/parallel-nav-isolation-test.js +1 -1
  32. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
  33. package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
  34. package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
  35. package/_site/_test/qa-r45-offline-backfill-test.js +2 -2
  36. package/_site/_test/t07d-git-rel-coverage-test.js +5 -3
  37. package/_site/_test/t07f-mem-008-coverage-test.js +1 -1
  38. package/_site/lib/module-bridge.js +2 -11
  39. package/_site/scripts/ab-rank-v2-v3.js +142 -0
  40. package/_site/scripts/install-module-candidates.js +1 -1
  41. package/_site/scripts/pack-module-candidates.js +2 -1
  42. package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
  43. package/_site/scripts/verify-module-runtime.js +17 -32
  44. package/_site/scripts/verify-product-runtime.js +7 -3
  45. package/_site/scripts/verify-retrieval-gold.js +57 -10
  46. package/docs/README.zh-CN.md +3 -1
  47. package/module-runtime-manifest.json +54 -4
  48. package/package.json +2 -4
  49. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  50. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  51. package/plugins/project-knowledge/.mcp.json +1 -1
  52. package/plugins/project-knowledge/scripts/context-hook.cjs +9 -5
  53. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +39 -28
  54. package/_modules/knowledge-engine/README.md +0 -133
  55. package/_modules/knowledge-engine/package.json +0 -38
  56. package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
  57. package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
  58. package/_modules/knowledge-engine/src/analysis-output.js +0 -52
  59. package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
  60. package/_modules/knowledge-engine/src/bin.js +0 -52
  61. package/_modules/knowledge-engine/src/bridge-client.js +0 -24
  62. package/_modules/knowledge-engine/src/context.js +0 -140
  63. package/_modules/knowledge-engine/src/coordinator.js +0 -376
  64. package/_modules/knowledge-engine/src/diagnostics.js +0 -37
  65. package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
  66. package/_modules/knowledge-engine/src/index-request.js +0 -49
  67. package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
  68. package/_modules/knowledge-engine/src/memories.js +0 -281
  69. package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
  70. package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
  71. package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
  72. package/_modules/knowledge-engine/src/retrieval.js +0 -367
  73. package/_modules/knowledge-engine/src/runtime/README.md +0 -7
  74. package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
  75. package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
  76. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
  77. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
  78. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
  79. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
  80. package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
  81. package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
  82. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
  83. package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
  84. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
  85. package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
  86. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
  87. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
  88. package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
  89. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
  90. package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
  91. package/_modules/knowledge-engine/src/server.js +0 -166
  92. package/_modules/knowledge-engine/src/store.js +0 -267
  93. package/_modules/knowledge-engine/ui/app.css +0 -172
  94. package/_modules/knowledge-engine/ui/app.js +0 -318
  95. package/_modules/knowledge-engine/ui/index.html +0 -95
  96. package/_site/scripts/vendor-modules.js +0 -49
  97. package/vendor-manifest.json +0 -55
@@ -1,367 +0,0 @@
1
- 'use strict';
2
- const fs = require('node:fs');
3
- const path = require('node:path');
4
- const crypto = require('node:crypto');
5
- const { KnowledgeRetrievalService } = require('./runtime/knowledge-retrieval-service');
6
- const { listMarkdownFiles, isExcludedKnowledgePath, CHUNKER_VERSION, lineFenceState, headingOf } = require('./runtime/markdown-knowledge-indexer');
7
- const { DomainError } = require('./runtime/contracts');
8
- const { sha256 } = require('./runtime/content-hash');
9
- const ranking = require('./retrieval-ranking');
10
- const fileNames = query => [...new Set((String(query).match(/[\p{L}\p{N}_./\\-]+\.(?:cjs|mjs|js|jsx|ts|tsx|py|cs|cpp|c|h|hpp|rs|go|html|css|scss|json|ya?ml|toml|md|txt|sh|ps1)\b/giu) || []).map(value => path.posix.basename(value.replace(/\\/g, '/')).toLowerCase()))].slice(0, 20);
11
- const mentionsFile = (candidate, name) => new RegExp(`(?<![\\p{L}\\p{N}_-])${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}_.-])`, 'iu').test([candidate.entryId, candidate.title, candidate.chunkText, ...(candidate.metadata?.sourcePaths || [])].join('\n'));
12
-
13
- const headingPathAt = (body, pos) => {
14
- const headings = [];
15
- let fence = null;
16
- let offset = 0;
17
- for (const line of String(body).split('\n')) {
18
- const lineStart = offset;
19
- offset += line.length + 1;
20
- if (lineStart > pos) break;
21
- fence = lineFenceState(line, fence);
22
- if (fence) continue;
23
- const heading = headingOf(line);
24
- if (heading) { headings.length = heading.level - 1; headings[heading.level - 1] = heading.text; }
25
- }
26
- return headings.filter(Boolean);
27
- };
28
- const overlapOf = (aStart, aEnd, bStart, bEnd) => Math.max(0, Math.min(aEnd, bEnd) - Math.max(aStart, bStart));
29
-
30
- class EngineRetrieval extends KnowledgeRetrievalService {
31
- constructor(options) { super(options); this.store = options.store; this.memories = options.memories; this.vectorUrl = options.vectorUrl || 'http://127.0.0.1:8787'; this.retrievalPolicy = options.retrievalPolicy || require('./retrieval-policy.json'); }
32
- async retrieve(input = {}) {
33
- const project = this.project(input), scopes = input.scopes || this.scopes(project), signals = this.signalSet(input.signals);
34
- const registrationBefore = this.store.getProject(project.projectId);
35
- const scopeStamp = p => JSON.stringify(p && [p.repoPath, p.knowledgePath, p.brainId, p.domainId, p.enabled]);
36
- const stamp = scopeStamp(registrationBefore);
37
- const stamps = new Map(scopes.map(scope => [scope.projectId, scopeStamp(this.store.getProject(scope.projectId) || this.store.state.sharedScopes.find(s => s.id === scope.projectId))]));
38
- const scanned = this.scanCurrent(scopes), health = { index: 'unknown', scopes: scanned.scopeHealth };
39
- const bodies = new Map();
40
- for (const [id, c] of scanned.candidates) {
41
- const key = `${c.spaceId}:${c.entryId}`;
42
- try {
43
- if (!bodies.has(key)) {
44
- const source = scanned.sources && scanned.sources.get(key);
45
- bodies.set(key, ranking.bodyText(source !== undefined ? source : fs.readFileSync(path.join(c.knowledgePath, c.entryId), 'utf8')));
46
- }
47
- } catch { scanned.candidates.delete(id); }
48
- }
49
- // The canonical chunker emits authoritative half-open offsets into the same
50
- // body coordinate system. A position is accepted only when the current
51
- // body still slices to the exact chunk text; anything else degrades to
52
- // unpositioned instead of guessing by search.
53
- for (const c of scanned.candidates.values()) {
54
- const body = bodies.get(`${c.spaceId}:${c.entryId}`);
55
- const positioned = Boolean(body) && Number.isInteger(c.chunkStart) && Number.isInteger(c.chunkEnd)
56
- && c.chunkStart >= 0 && c.chunkEnd > c.chunkStart && c.chunkEnd <= body.length && body.slice(c.chunkStart, c.chunkEnd) === c.chunkText;
57
- c.bodyHash = body ? ranking.bodyHash(body) : null;
58
- c.bodyLength = body ? body.length : 0;
59
- c.startPos = positioned ? c.chunkStart : -1;
60
- c.endPos = positioned ? c.chunkEnd : -1;
61
- }
62
- const lexicalChunkCount = scanned.candidates.size;
63
- if (!['greeting', 'followup'].includes(ranking.intent(signals.indexQuery))) await this.recallIndex(scopes, signals.indexQuery, scanned.candidates, health, bodies);
64
- else health.index = 'not-requested';
65
- if (stamp !== scopeStamp(this.store.getProject(project.projectId))) throw new DomainError('PROJECT_SCOPE_CHANGED', '项目归属或绑定已变化,请重新检索。', { status: 409 });
66
- for (const [id, c] of scanned.candidates) {
67
- if (stamps.get(c.projectId) !== scopeStamp(this.store.getProject(c.projectId) || this.store.state.sharedScopes.find(s => s.id === c.projectId))) { scanned.candidates.delete(id); continue; }
68
- if (c.entryId.startsWith('memories/')) {
69
- const shared = this.store.state.sharedScopes.find(s => s.id === c.projectId);
70
- if (!this.memories?.readableEntry(shared, c.entryId, registrationBefore) || !this.memories.memoryForChunk(shared, c.entryId, c.headingPath)) scanned.candidates.delete(id);
71
- }
72
- }
73
- const ranked = ['greeting', 'followup'].includes(ranking.intent(signals.indexQuery)) ? [] : ranking.rank([...scanned.candidates.values()], signals.indexQuery, c => {
74
- const scored = this.score(c, signals);
75
- return { ...scored, excluded: Boolean(signals.commitPrefixes?.length || c.knownFileQuery) && scored.score <= 0 };
76
- }, { commitPrefixes: signals.commitPrefixes });
77
- const ordered = input.policy === 'project-first' ? [...ranked.filter(c => c.scopeReason === 'primary'), ...ranked.filter(c => c.scopeReason !== 'primary')] : ranked;
78
- const checked = new Map(), candidates = [];
79
- // Revalidate every returned document after the asynchronous vector call,
80
- // not every unrelated file a second time. Changed/deleted/escaped facts
81
- // are discarded before leaving this service, then the next rank is tried.
82
- for (const c of ordered) {
83
- const key = `${c.spaceId}:${c.entryId}`;
84
- if (!checked.has(key)) {
85
- try {
86
- const file = path.join(c.knowledgePath, c.entryId);
87
- checked.set(key, this.layout.isPathInside(c.knowledgePath, file, { realpath: true }) && !fs.lstatSync(file).isSymbolicLink()
88
- && crypto.createHash('sha256').update(`chunker:${CHUNKER_VERSION}\n${fs.readFileSync(file, 'utf8')}`).digest('hex') === c.documentHash);
89
- } catch { checked.set(key, false); }
90
- }
91
- if (checked.get(key)) candidates.push(c);
92
- if (candidates.length >= this.candidateLimit) break;
93
- }
94
- return { project, scopes, signals, health, candidates, totalCurrentChunks: lexicalChunkCount, intent: ranking.intent(signals.indexQuery) };
95
- }
96
- signalSet(input = {}) {
97
- const signals = super.signalSet(input);
98
- const query = signals.indexQuery.trim().toLowerCase();
99
- const promoted = this.store.listRuns().filter(run => run.promotedAt && run.commitSha);
100
- const identifiers = [...query.matchAll(/(?:^|[^a-z0-9])([a-f0-9]{7,64})(?=$|[^a-z0-9])/g)].map(match => match[1]);
101
- signals.commitPrefixes = [...new Set(identifiers.filter(id => promoted.some(run => run.commitSha.startsWith(id))))];
102
- return signals;
103
- }
104
- score(candidate, signals) {
105
- if (signals.commitPrefixes?.length) {
106
- // A known commit is an identifier, not a semantic topic. Unrelated
107
- // vector hits must not crowd its current, provenance-checked files out.
108
- const source = this.store.listRuns(candidate.projectId).find(run => run.promotedAt && run.staging?.operations?.some(operation => operation.path === candidate.entryId));
109
- if (!signals.commitPrefixes.some(prefix => source?.commitSha?.startsWith(prefix))) return { score: 0, selectionSignals: [] };
110
- const result = super.score(candidate, signals);
111
- return { score: Math.max(1, result.score), selectionSignals: [...result.selectionSignals, 'exact-commit'] };
112
- }
113
- if (candidate.knownFileQuery && !candidate.fileReferences.length) return { score: 0, selectionSignals: [] };
114
- const result = super.score(candidate, signals);
115
- if (candidate.fileReferences?.length) return { score: Math.max(1, result.score), selectionSignals: [...result.selectionSignals, ...candidate.fileReferences.map(name => `exact-source-file:${name}`)] };
116
- return result;
117
- }
118
- resolve(input = {}) {
119
- let project = this.store.getProject(input.projectId || input.projectSlug || input.project);
120
- if (!project && (input.repoPath || input.path)) project = this.store.listProjects().find(p => this.layout.pathsEqual(p.repoPath, input.repoPath || input.path));
121
- if (!project || project.enabled === false) throw new DomainError('PROJECT_NOT_FOUND', '项目尚未登记。', { status: 404 });
122
- return project;
123
- }
124
- project(input = {}) {
125
- if (input.project && input.project.projectId) return input.project;
126
- const p = this.resolve(input);
127
- return { projectId: p.projectId, projectSlug: p.projectId, primarySpaceId: `project:${p.projectId}`, knowledgePath: p.knowledgePath, relatedProjectIds: p.relatedProjectIds || [], index: this.store.readRuntime(p.projectId).index };
128
- }
129
- scopes(project) {
130
- const registration = this.store.getProject(project.projectId);
131
- return [...super.scopes(project), ...this.sharedScopes(registration, 'domain')];
132
- }
133
- sharedScopes(registration, range) {
134
- return this.store.state.sharedScopes.filter(s => s.brainId === registration.brainId && (s.kind === 'brain' || range === 'brain' || registration.domainId && s.domainId === registration.domainId)).map(s => ({ projectId: s.id, spaceId: `${s.kind}:${s.id}`, knowledgePath: s.knowledgePath, weight: s.kind === 'brain' ? 0.6 : 0.75, reason: s.kind }));
135
- }
136
- scanCurrent(scopes) {
137
- const registration = this.store.getProject(scopes.find(s => s.reason === 'primary')?.projectId);
138
- const ordinary = scopes.filter(s => this.store.getProject(s.projectId));
139
- const shared = scopes.filter(s => !this.store.getProject(s.projectId));
140
- const result = super.scanCurrent(ordinary);
141
- for (const [id, candidate] of result.candidates) if (candidate.entryId.startsWith('memories/')) result.candidates.delete(id);
142
- if (!shared.length) return result;
143
- const scanner = new KnowledgeRetrievalService({ layout: this.layout, projectStore: { readState: () => ({ index: {} }) } });
144
- const extra = scanner.scanCurrent(shared);
145
- for (const [id, candidate] of extra.candidates) {
146
- const scope = this.store.state.sharedScopes.find(s => s.id === candidate.projectId);
147
- if (candidate.entryId.startsWith('memories/')) {
148
- if (!this.memories?.readableEntry(scope, candidate.entryId, registration) || !this.memories.memoryForChunk(scope, candidate.entryId, candidate.headingPath)) continue;
149
- const memory = this.memories.memoryForChunk(scope, candidate.entryId, candidate.headingPath), type = this.memories.scopeOf(memory).type;
150
- candidate.scopeWeight = { project: 1, domain: 0.75, global: 0.6 }[type];
151
- candidate.title = `${{ project: '项目记忆', domain: '领域记忆', global: '全局记忆' }[type]} · ${this.memories.target(memory).name}`;
152
- } else if (scopes.find(s => s.projectId === candidate.projectId)?.memoryOnly) continue;
153
- result.candidates.set(id, candidate);
154
- }
155
- result.scopeHealth.push(...extra.scopeHealth);
156
- if (extra.sources) for (const [sourceKey, sourceMarkdown] of extra.sources) result.sources.set(sourceKey, sourceMarkdown);
157
- return result;
158
- }
159
- async recallIndex(scopes, query, current, health, bodies) {
160
- if (!query) { health.index = 'unavailable'; return; }
161
- // File identifiers, like commit IDs, select current facts before semantic
162
- // ranking. A not-yet-known filename still permits analogous background.
163
- const named = fileNames(query), known = named.filter(name => [...current.values()].some(candidate => mentionsFile(candidate, name)));
164
- for (const candidate of current.values()) { candidate.knownFileQuery = known.length > 0; candidate.fileReferences = known.filter(name => mentionsFile(candidate, name)); }
165
- const mappings = scopes.map(s => ({ scope: s, registration: this.store.getProject(s.projectId) || (() => { const shared = this.store.state.sharedScopes.find(p => p.id === s.projectId); return shared ? { vectorProjectId: `scope-${shared.kind}-${shared.id}` } : null; })() })).filter(m => m.registration);
166
- const recall = { rows: 0, merges: 0, slices: 0, rejected: {} };
167
- const reject = reason => { recall.rejected[reason] = (recall.rejected[reason] || 0) + 1; };
168
- const anchors = new Map();
169
- for (const candidate of current.values()) {
170
- const key = `${candidate.spaceId}:${candidate.entryId}`;
171
- if (!anchors.has(key)) anchors.set(key, candidate);
172
- }
173
- const pending = [];
174
- try {
175
- const url = new URL('/api/search', this.vectorUrl);
176
- url.searchParams.set('q', query);
177
- url.searchParams.set('projects', mappings.map(m => m.registration.vectorProjectId || m.scope.projectId).join(','));
178
- url.searchParams.set('maxResults', String(this.candidateLimit));
179
- url.searchParams.set('resultLevel', 'chunk');
180
- url.searchParams.set('perProjectLimit', '30');
181
- const response = await fetch(url, { signal: AbortSignal.timeout(8000) });
182
- if (!response.ok) throw new Error('VECTOR_UNAVAILABLE');
183
- const payload = await response.json();
184
- if (payload.errors && payload.errors.length) throw new Error('VECTOR_QUERY_FAILED');
185
- const calibrated = this.retrievalPolicy.rankingVersion === ranking.VERSION && this.retrievalPolicy.models?.find(p => p.model === payload.model && p.dimensions === payload.dimensions && Number.isFinite(p.minScore));
186
- health.calibration = calibrated ? 'validated' : 'lexical-support-required';
187
- // Vectors only contribute a rank. Displayed text/hash always comes from
188
- // current canonical files, so deleted or stale index bodies cannot leak.
189
- for (const row of payload.results || []) {
190
- recall.rows += 1;
191
- const mapping = mappings.find(m => (m.registration.vectorProjectId || m.scope.projectId) === row.project);
192
- if (!mapping) { reject('unknown-project'); continue; }
193
- const uri = row.uri || row.documentUri || '';
194
- const entry = path.isAbsolute(uri) ? path.relative(mapping.scope.knowledgePath, uri).replace(/\\/g, '/') : String(uri).replace(/\\/g, '/');
195
- const key = `${mapping.scope.spaceId}:${entry}`;
196
- const anchor = anchors.get(key);
197
- if (!anchor || !bodies || !bodies.has(key)) { reject('no-current-document'); continue; }
198
- const valid = row.scoreType === 'cosine' && row.bodyHash === anchor.bodyHash && Number.isInteger(row.startPos) && Number.isInteger(row.endPos)
199
- && row.startPos >= 0 && row.endPos > row.startPos && row.endPos <= anchor.bodyLength;
200
- if (!valid) { reject(row.bodyHash === anchor.bodyHash ? 'invalid-range' : 'body-hash-mismatch'); continue; }
201
- const value = Number(row.score);
202
- if (!Number.isFinite(value) || value < -1 || value > 1) { reject('invalid-score'); continue; }
203
- for (const candidate of current.values()) {
204
- if (candidate.fromVectorRange || candidate.spaceId !== mapping.scope.spaceId || candidate.entryId !== entry || candidate.startPos < 0) continue;
205
- const overlap = Math.max(0, Math.min(candidate.endPos, row.endPos) - Math.max(candidate.startPos, row.startPos));
206
- if (!overlap) continue;
207
- recall.merges += 1;
208
- candidate.indexScore = Math.max(candidate.indexScore || 0, Math.max(0, value));
209
- candidate.vectorRanges ||= [];
210
- candidate.vectorRanges.push([Math.max(candidate.startPos, row.startPos), Math.min(candidate.endPos, row.endPos)]);
211
- const ranges = [...candidate.vectorRanges].sort((a, b) => a[0] - b[0]);
212
- let covered = 0, end = -1;
213
- for (const range of ranges) { covered += Math.max(0, range[1] - Math.max(end, range[0])); end = Math.max(end, range[1]); }
214
- if (covered >= candidate.chunkText.length * 0.5) { candidate.indexChannels = ['vector-hub']; candidate.vectorVerified = true; }
215
- if (calibrated) { candidate.vectorCalibrated = true; candidate.vectorMinScore = calibrated.minScore; }
216
- }
217
- const sliceText = bodies.get(key).slice(row.startPos, row.endPos);
218
- if (!sliceText.trim()) { reject('empty-slice'); continue; }
219
- let duplicate = false;
220
- for (const candidate of current.values()) {
221
- if (!candidate.fromVectorRange || candidate.spaceId !== mapping.scope.spaceId || candidate.entryId !== entry) continue;
222
- if (overlapOf(candidate.startPos, candidate.endPos, row.startPos, row.endPos) * 2 >= Math.min(candidate.endPos - candidate.startPos, row.endPos - row.startPos)) { duplicate = true; break; }
223
- }
224
- for (const prior of pending) {
225
- if (prior.scope.spaceId !== mapping.scope.spaceId || prior.entry !== entry) continue;
226
- if (overlapOf(prior.row.startPos, prior.row.endPos, row.startPos, row.endPos) * 2 >= Math.min(prior.row.endPos - prior.row.startPos, row.endPos - row.startPos)) { duplicate = true; break; }
227
- }
228
- if (duplicate) continue;
229
- pending.push({ scope: mapping.scope, key, entry, anchor, row, sliceText, value, calibrated });
230
- }
231
- for (const p of pending) {
232
- recall.slices += 1;
233
- const recordId = `${p.scope.spaceId}:${p.entry}:vector:${p.row.startPos}-${p.row.endPos}`;
234
- current.set(recordId, {
235
- recordId,
236
- spaceId: p.scope.spaceId,
237
- projectId: p.scope.projectId,
238
- scopeReason: p.scope.reason,
239
- // A slice inherits the anchor candidate's own scope weight: a project
240
- // memory keeps project weight even inside a lower-weight shared scope.
241
- scopeWeight: p.anchor.scopeWeight,
242
- fromVectorRange: true,
243
- knowledgePath: p.scope.knowledgePath,
244
- entryId: p.entry,
245
- entryType: p.anchor.entryType,
246
- chunkId: `${p.entry}:vector:${p.row.startPos}-${p.row.endPos}`,
247
- chunkOrder: null,
248
- title: p.anchor.title,
249
- headingPath: headingPathAt(bodies.get(p.key), p.row.startPos),
250
- chunkText: p.sliceText,
251
- documentHash: p.anchor.documentHash,
252
- contentHash: sha256(p.sliceText),
253
- metadata: p.anchor.metadata,
254
- fromOverlay: p.anchor.fromOverlay,
255
- bodyHash: p.anchor.bodyHash,
256
- bodyLength: p.anchor.bodyLength,
257
- startPos: p.row.startPos,
258
- endPos: p.row.endPos,
259
- indexScore: Math.min(1, Math.max(0, p.value)),
260
- indexChannels: ['vector-hub'],
261
- vectorRanges: [[p.row.startPos, p.row.endPos]],
262
- vectorVerified: true,
263
- knownFileQuery: known.length > 0,
264
- fileReferences: known.filter(name => mentionsFile({ entryId: p.entry, title: p.anchor.title, chunkText: p.sliceText, metadata: p.anchor.metadata }, name)),
265
- ...(p.calibrated ? { vectorCalibrated: true, vectorMinScore: p.calibrated.minScore } : {}),
266
- });
267
- }
268
- health.index = payload.projectsSkipped?.length ? 'partial' : 'ok';
269
- health.verifiedVectorChunks = [...current.values()].filter(c => c.vectorVerified && !c.fromVectorRange).length;
270
- health.vectorMode = payload.resultLevel === 'chunk' ? 'verified-chunks' : 'legacy-document-results';
271
- } catch { health.index = 'degraded'; health.reason = 'vector-hub-unavailable'; }
272
- health.vectorRecall = recall;
273
- health.verifiedVectorSlices = recall.slices;
274
- }
275
- async search(input = {}) {
276
- const registration = this.resolve(input);
277
- const selectedIntent = input.intent && input.intent !== 'auto' ? input.intent : ranking.intent(input.query);
278
- if (input.intent !== undefined && !['auto', 'search', 'recent'].includes(input.intent)) throw new DomainError('INVALID_ARGUMENT', '检索意图无效。');
279
- if (input.scope !== undefined && !['project', 'domain', 'brain'].includes(input.scope)) throw new DomainError('INVALID_ARGUMENT', '知识范围无效。');
280
- const knownCommits = this.signalSet({ primaryTexts: [String(input.query || '')] }).commitPrefixes;
281
- if (selectedIntent === 'recent' && !knownCommits?.length) {
282
- const history = await this.history(input);
283
- const hasKnowledge = listMarkdownFiles(registration.knowledgePath).length > 0;
284
- const currentProjectStatus = { hasKnowledge, matchedCount: history.results.length, note: history.results.length ? '已匹配当前项目的维护变更。' : hasKnowledge ? '本次没有匹配到当前项目的维护变更;已有知识仍然保留,不代表知识为空。' : '当前项目尚无可读取的已维护知识。' };
285
- return { ...history, query: input.query, intent: 'recent', rankingVersion: ranking.VERSION, currentProjectStatus,
286
- matchStatus: history.results.length ? 'matched' : hasKnowledge ? 'no-reliable-match' : 'knowledge-empty',
287
- health: { index: 'not-requested' }, results: history.results.slice(0, Math.max(1, Math.min(30, Number(input.limit) || 8))).map((r, i) => ({ ...r,
288
- record_id: `project:${registration.projectId}:${r.entry_id}:history`, space_id: `project:${registration.projectId}`, chunk_id: `${r.entry_id}:history`,
289
- scope_project_id: registration.projectId, scope_reason: 'primary', projectId: registration.projectId, projectName: registration.name, path: r.entry_id,
290
- snippet: r.chunk_text, relevance_score: 1 / (i + 1), score: 1 / (i + 1), match_channels: ['intent:recent', 'scope:primary'], matchReason: '当前项目已维护变更,按依据时间排序' })) };
291
- }
292
- const project = this.project({ projectId: registration.projectId });
293
- let scopes = [{ projectId: project.projectId, spaceId: project.primarySpaceId, knowledgePath: project.knowledgePath, weight: 1, reason: 'primary' }];
294
- if (input.scope === 'domain' || input.scope === 'brain') {
295
- scopes = this.store.listProjects().filter(p => p.enabled !== false && p.brainId === registration.brainId
296
- && (input.scope === 'brain' || p.projectId === registration.projectId || registration.domainId && p.domainId === registration.domainId)).map(p => ({ projectId: p.projectId, spaceId: `project:${p.projectId}`, knowledgePath: p.knowledgePath, weight: p.projectId === registration.projectId ? 1 : 0.88, reason: p.projectId === registration.projectId ? 'primary' : input.scope }));
297
- scopes.push(...this.sharedScopes(registration, input.scope));
298
- }
299
- if (!scopes.some(s => s.spaceId === `brain:${registration.brainId}`)) {
300
- scopes.push(...this.sharedScopes(registration, 'domain').filter(s => s.reason === 'brain').map(s => ({ ...s, memoryOnly: true })));
301
- }
302
- const result = await super.search({ ...input, project, scopes });
303
- const vectorUsed = result.results.some(row => row.match_channels.includes('index:vector-hub'));
304
- result.retrievalModes = vectorUsed ? ['lexical', 'vector'] : ['lexical'];
305
- result.backend = vectorUsed ? 'hybrid+markdown-truth' : 'markdown-hybrid-fallback';
306
- result.intent = selectedIntent; result.rankingVersion = ranking.VERSION;
307
- result.matchStatus = result.results.length ? 'matched' : ranking.intent(input.query) === 'greeting' ? 'not-needed' : 'no-reliable-match';
308
- const primaryCount = result.results.filter(r => r.scope_project_id === registration.projectId && !r.entry_id.startsWith('memories/')).length;
309
- const hasKnowledge = listMarkdownFiles(registration.knowledgePath).length > 0;
310
- result.currentProjectStatus = { hasKnowledge, matchedCount: primaryCount,
311
- note: primaryCount ? '已匹配当前项目知识。' : hasKnowledge ? '当前项目已有知识,本次问题未可靠命中;不代表知识为空。' : '当前项目尚无可读取的已维护知识。' };
312
- result.results = result.results.map(row => {
313
- const run = this.store.listRuns(row.scope_project_id).find(r => r.promotedAt && r.staging?.operations?.some(op => op.path === row.entry_id));
314
- const source = this.store.getProject(row.scope_project_id) || this.store.state.sharedScopes.find(s => s.id === row.scope_project_id);
315
- const memory = source?.kind === 'brain' && row.entry_id.startsWith('memories/') ? this.memories.memoryForChunk(source, row.entry_id, row.heading_path) : null;
316
- const commitSha = memory ? memory.evidence?.commitSha || null : run?.commitSha || null;
317
- return { ...row, projectName: source?.name || row.scope_project_id, path: row.entry_id, snippet: row.chunk_text, score: row.relevance_score, projectId: row.scope_project_id, commitSha,
318
- matchReason: row.match_channels.includes('exact-commit') ? '提交标识匹配' : row.match_channels.some(c => c.startsWith('exact-source-file:')) ? '源文件匹配' : row.match_channels.includes('index:vector-hub') ? row.match_channels.includes('lexical:bm25') ? '正文关键词与向量片段融合' : '已校验向量片段匹配' : '当前正文词法匹配',
319
- ...(memory ? { memoryScopeType: this.memories.scopeOf(memory).type, memoryScopeId: this.memories.scopeOf(memory).id, memoryId: memory.id, ...(memory.sourceType === 'manual' ? { memorySourceType: 'manual' } : {}) } : {}) };
320
- });
321
- const slots = result.results.map((r, i) => r.memoryId ? i : -1).filter(i => i >= 0);
322
- const ordered = slots.map(i => result.results[i]).sort((a, b) => ({ project: 0, domain: 1, global: 2 }[a.memoryScopeType] - { project: 0, domain: 1, global: 2 }[b.memoryScopeType]) || b.score - a.score);
323
- slots.forEach((slot, i) => { result.results[slot] = ordered[i]; });
324
- return result;
325
- }
326
- async ask(input) {
327
- const result = await this.search(input);
328
- const citations = result.results.slice(0, 5).map((r, i) => ({ index: i + 1, ref: i + 1, projectId: r.scope_project_id, projectName: r.projectName, spaceId: r.space_id, commitSha: r.commitSha, score: r.relevance_score, entryId: r.entry_id, path: r.entry_id, title: r.title, text: r.chunk_text }));
329
- return { ...result, answer: citations.length ? citations.map(r => `${r.index}. ${r.title}: ${r.text}`).join('\n') : result.matchStatus === 'not-needed' ? '本次输入无需知识检索。' : result.currentProjectStatus?.note || '没有可靠匹配;这不代表知识库为空。', citations };
330
- }
331
- async get(input) {
332
- const registration = this.resolve(input);
333
- const scope = input.spaceId && this.store.state.sharedScopes.find(s => `${s.kind}:${s.id}` === input.spaceId && s.brainId === registration.brainId);
334
- if (input.spaceId && !scope && input.spaceId !== `project:${registration.projectId}`) throw new DomainError('PROJECT_NOT_FOUND', '知识范围与项目归属不匹配。', { status: 404 });
335
- const project = scope ? { projectId: scope.id, knowledgePath: scope.knowledgePath } : registration;
336
- const entryId = String(input.entryId || input.entry || '').replace(/\\/g, '/');
337
- if (isExcludedKnowledgePath(entryId)) throw new DomainError('PATH_OUTSIDE_ROOT', '会话证据与内部数据不能作为正式知识读取。', { status: 403 });
338
- const target = path.resolve(project.knowledgePath, entryId);
339
- if (!entryId || !/\.md$/i.test(target) || !this.layout.isPathInside(project.knowledgePath, target, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', '知识文件越界。', { status: 403 });
340
- if (!fs.existsSync(target) || !fs.statSync(target).isFile() || fs.lstatSync(target).isSymbolicLink()) throw new DomainError('PROJECT_NOT_FOUND', '知识文件不存在。', { status: 404 });
341
- if (entryId.startsWith('memories/') && (!scope || !this.memories?.readableEntry(scope, entryId, registration))) throw new DomainError('PROJECT_NOT_FOUND', '记忆尚未同步或不适用于当前项目。', { status: 404 });
342
- return { ok: true, projectId: project.projectId, projectSlug: project.projectId, entryId, source: 'markdown', chunks: [{ chunk_text: fs.readFileSync(target, 'utf8'), entry_id: entryId, space_id: scope ? `${scope.kind}:${scope.id}` : `project:${project.projectId}` }] };
343
- }
344
- async history(input) {
345
- const project = this.resolve(input);
346
- const namedFiles = fileNames(input.query || '');
347
- const results = listMarkdownFiles(project.knowledgePath).filter(file => this.layout.isPathInside(path.join(project.knowledgePath, 'changes'), file, { realpath: true })).map(file => {
348
- const content = fs.readFileSync(file, 'utf8');
349
- const entry = path.relative(project.knowledgePath, file).replace(/\\/g, '/');
350
- const run = this.store.listRuns(project.projectId).find(r => r.promotedAt && r.staging?.operations?.some(op => op.path === entry));
351
- const declared = /(?:^|\n)(?:-\s*)?(?:date|日期|时间):\s*([0-9T:+.Z-]+)/i.exec(content)?.[1];
352
- const timestamp = run?.evidence?.commitDate || run?.commitDate || declared || run?.promotedAt;
353
- const valid = timestamp && Number.isFinite(Date.parse(timestamp));
354
- const excerpt = content.slice(0, 1200);
355
- return { entry_id: entry, title: (/^#\s+(.+)$/m.exec(content) || [null, path.basename(file)])[1], chunk_text: excerpt, sourceText: content,
356
- content_hash: crypto.createHash('sha256').update(excerpt).digest('hex'), history_excerpt_length: excerpt.length,
357
- document_hash: crypto.createHash('sha256').update(content).digest('hex'),
358
- commitSha: run?.commitSha || /(?:^|\n)(?:-\s*)?commit:\s*`?([a-f0-9]{40})/i.exec(content)?.[1] || null,
359
- updated_at: valid ? new Date(timestamp).toISOString() : fs.statSync(file).mtime.toISOString(), dateSource: valid ? run?.promotedAt === timestamp ? 'promotion' : 'commit-evidence' : 'mtime-fallback' };
360
- }).filter(row => !namedFiles.length || namedFiles.some(name => mentionsFile({ entryId: row.entry_id, title: row.title, chunkText: row.sourceText }, name)))
361
- .sort((a, b) => (a.dateSource === 'mtime-fallback' ? 1 : 0) - (b.dateSource === 'mtime-fallback' ? 1 : 0) || b.updated_at.localeCompare(a.updated_at))
362
- .slice(0, Math.min(100, Math.max(1, Number(input.limit) || 20))).map(({ sourceText, ...row }) => row);
363
- return { ok: true, projectId: project.projectId, projectSlug: project.projectId, backend: 'markdown', source: 'markdown', results };
364
- }
365
- }
366
-
367
- module.exports = { EngineRetrieval };
@@ -1,7 +0,0 @@
1
- # 迁入的知识运行逻辑
2
-
3
- 来源:project-knowledge-base/_site/lib,基线 0c62f528f66794ca5de055a137f632dfc5c57bc3。
4
-
5
- 复用提交证据冻结、会话边界绑定、检索事实校验、提示词、安全工具策略、晋升事务及崩溃恢复。只迁入知识运行职责,没有复制外壳的项目注册表、SettingsStore、凭据或旧 LanceDB/embedding 写入能力。
6
-
7
- 构造函数改为注入 layout 与只读项目投影/运行状态适配器;内容哈希提取为零依赖文件。项目和配置的所有权仍在外壳,引擎本地登记只是运行所需投影。向量召回接 vector-hub,不启动第二份索引。
@@ -1,204 +0,0 @@
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
- };