@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,281 +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 AtomicFile = require('./runtime/atomic-file');
6
- const { RuntimeLayout } = require('./runtime/layout');
7
- const { validateProjectId, DomainError } = require('./runtime/contracts');
8
- const { MemoryEligibility } = require('./memory-eligibility');
9
-
10
- const TYPES = ['global', 'domain', 'project'];
11
- const normalized = text => String(text).toLowerCase().replace(/\s+/g, ' ').trim();
12
- const fingerprint = (brainId, type, id, text) => crypto.createHash('sha256').update(`${brainId}:${type}:${id}:${normalized(text)}`).digest('hex');
13
-
14
- class MemoryService {
15
- constructor(store, options = {}) {
16
- this.store = store; this.layout = new RuntimeLayout(store.dataDir); this.onMaterialized = options.onMaterialized;
17
- this.syncErrors = new Map(); this.closed = false; this.onSyncChange = options.onSyncChange; this.writes = new Set();
18
- this.getIndexStatus = options.getIndexStatus;
19
- this.eligibility = new MemoryEligibility({ readSnapshot: options.readSnapshot || null });
20
- }
21
- lock() { return this.layout.getRuntimePath('locks', 'memories.lock'); }
22
- scopeOf(memory) { return { type: memory.scopeType || 'global', id: memory.scopeId || memory.brainId || 'brain-default' }; }
23
- brainScope(brainId) { return this.store.state.sharedScopes.find(s => s.kind === 'brain' && s.brainId === brainId); }
24
- target(memory) {
25
- const scope = this.scopeOf(memory), brainId = memory.brainId || 'brain-default';
26
- const target = scope.type === 'global' ? this.brainScope(brainId) : scope.type === 'domain'
27
- ? this.store.state.sharedScopes.find(s => s.kind === 'domain' && s.id === scope.id && s.brainId === brainId)
28
- : this.store.listProjects().find(p => p.projectId === scope.id && p.brainId === brainId && p.enabled !== false);
29
- return { name: target?.name || scope.id, available: Boolean(target) };
30
- }
31
- validateScope(type, id, brainId) {
32
- if (!TYPES.includes(type)) throw new DomainError('INVALID_ARGUMENT', '适用范围无效。');
33
- validateProjectId(id);
34
- if (type === 'global' && id !== brainId || type !== 'global' && !this.target({ brainId, scopeType: type, scopeId: id }).available) throw new DomainError('INVALID_ARGUMENT', '所选记忆目标不存在或不属于当前智脑。');
35
- }
36
- entry(memory) {
37
- const scope = this.scopeOf(memory);
38
- if (scope.type === 'global') return 'memories/confirmed.md';
39
- validateProjectId(scope.id);
40
- return `memories/${scope.type === 'domain' ? 'domains' : 'projects'}/${scope.id}.md`;
41
- }
42
- descriptor(entry) {
43
- if (entry === 'memories/confirmed.md') return { type: 'global' };
44
- const match = /^memories\/(domains|projects)\/([A-Za-z0-9][A-Za-z0-9._-]*)\.md$/.exec(entry);
45
- if (!match) return null;
46
- try { validateProjectId(match[2]); } catch { return null; }
47
- return { type: match[1] === 'domains' ? 'domain' : 'project', id: match[2] };
48
- }
49
- file(scope, entry = 'memories/confirmed.md') { return path.join(scope.knowledgePath, ...entry.split('/')); }
50
- safeFile(scope, entry) {
51
- const file = this.file(scope, entry);
52
- if (!this.descriptor(entry) || !this.layout.isPathInside(scope.knowledgePath, file, { realpath: true }) || fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new DomainError('PATH_OUTSIDE_ROOT', '记忆文件目录越界。', { status: 403 });
53
- return file;
54
- }
55
- confirmed(brainId, entry) { return this.store.state.memories.filter(m => m.status === 'confirmed' && (m.brainId || 'brain-default') === brainId && this.entry(m) === entry); }
56
- applicable(memory, project) {
57
- if (!project || memory.status !== 'confirmed' || (memory.brainId || 'brain-default') !== project.brainId || !this.target(memory).available) return false;
58
- const scope = this.scopeOf(memory);
59
- return scope.type === 'global' || scope.type === 'domain' && scope.id === project.domainId || scope.type === 'project' && scope.id === project.projectId;
60
- }
61
- readableEntry(scope, entry, project) {
62
- return scope.kind === 'brain' && !this.syncErrors.has(scope.id) && this.validFile(scope, entry) && this.confirmed(scope.brainId, entry).some(m => this.applicable(m, project));
63
- }
64
- memoryForChunk(scope, entry, heading) {
65
- return this.confirmed(scope.brainId, entry).find(m => (Array.isArray(heading) ? heading : String(heading).split(' > ')).includes(m.id));
66
- }
67
- project(memory) {
68
- const scope = this.scopeOf(memory), target = this.target(memory), brain = this.brainScope(memory.brainId || 'brain-default');
69
- return { ...memory, scopeType: scope.type, scopeId: scope.id, targetName: target.name, targetAvailable: target.available,
70
- syncStatus: memory.status !== 'confirmed' ? 'not-required' : brain && !this.syncErrors.has(brain.id) && this.validFile(brain, this.entry(memory)) ? 'ready' : 'pending',
71
- indexStatus: memory.status === 'confirmed' ? this.getIndexStatus?.(brain) || (brain?.index?.error ? 'failed' : brain?.index?.status || 'pending') : 'not-required',
72
- ...(brain && this.syncErrors.has(brain.id) ? { syncError: this.syncErrors.get(brain.id) } : {}) };
73
- }
74
- async configure(scopes) {
75
- if (!Array.isArray(scopes)) throw new DomainError('INVALID_ARGUMENT', '共享范围必须是数组。');
76
- const ids = new Set();
77
- const projected = scopes.map(scope => {
78
- validateProjectId(scope.id); validateProjectId(scope.brainId);
79
- if (scope.domainId) validateProjectId(scope.domainId);
80
- if (ids.has(scope.id) || !['brain', 'domain'].includes(scope.kind) || !path.isAbsolute(scope.knowledgePath || '')) throw new DomainError('INVALID_ARGUMENT', '共享范围绑定无效。');
81
- ids.add(scope.id);
82
- const index = this.store.state.sharedScopes.find(s => s.id === scope.id)?.index;
83
- return { id: scope.id, kind: scope.kind, brainId: scope.brainId, domainId: scope.domainId || null, name: String(scope.name || scope.id), knowledgePath: path.resolve(scope.knowledgePath), ...(index ? { index } : {}) };
84
- });
85
- const overlaps = (a, b) => this.layout.isPathInside(a, b, { realpath: true }) || this.layout.isPathInside(b, a, { realpath: true });
86
- for (const scope of projected) {
87
- if (this.store.listProjects().some(p => overlaps(p.knowledgePath, scope.knowledgePath) || overlaps(p.repoPath, scope.knowledgePath)) || projected.some(s => s.id !== scope.id && overlaps(s.knowledgePath, scope.knowledgePath))) throw new DomainError('PATH_OUTSIDE_ROOT', '共享目录与其他知识或代码目录冲突。', { status: 409 });
88
- const prior = this.store.state.sharedScopes.find(s => s.id === scope.id);
89
- if (prior && !this.layout.pathsEqual(prior.knowledgePath, scope.knowledgePath)) throw new DomainError('IMMUTABLE_FIELD', '共享目录已绑定,不能隐式移动知识。', { status: 409 });
90
- }
91
- // The shell remains the registry owner; this is a whitelisted projection.
92
- this.store.state.sharedScopes = projected; this.store.save();
93
- for (const scope of projected) fs.mkdirSync(scope.knowledgePath, { recursive: true });
94
- await this.recover();
95
- return projected;
96
- }
97
- list({ brainId, status, scopeType, scopeId } = {}) {
98
- if (scopeType && !TYPES.includes(scopeType)) throw new DomainError('INVALID_ARGUMENT', '记忆筛选范围无效。');
99
- return this.store.state.memories.filter(m => (m.status !== 'deleted' || status === 'deleted') && (!brainId || m.brainId === brainId) && (!status || m.status === status) && (!scopeType || this.scopeOf(m).type === scopeType) && (!scopeId || this.scopeOf(m).id === scopeId)).map(m => this.project(m));
100
- }
101
- capture(run) {
102
- const report = { accepted: 0, deduplicated: 0, rejected: [] };
103
- const project = this.store.getProject(run.projectId);
104
- if (!project || !run.promotedAt) return report;
105
- const candidates = Array.isArray(run.staging?.memoryCandidates) ? run.staging.memoryCandidates : [];
106
- const snapshot = this.eligibility.resolve(run);
107
- const before = this.store.state.memories, next = [...before];
108
- for (const [index, raw] of candidates.slice(0, 20).entries()) {
109
- const reject = code => report.rejected.push({ index, code });
110
- if (!raw || typeof raw !== 'object') { reject('INVALID_CANDIDATE'); continue; }
111
- const text = String(raw.text || '').trim();
112
- const quote = String(raw.quote || '').trim();
113
- const entryId = String(raw.entryId || '');
114
- const file = path.resolve(project.knowledgePath, entryId);
115
- if (!text || text.length > 2000 || quote.length < 8) { reject('INVALID_TEXT_OR_QUOTE'); continue; }
116
- if (!run.staging.operations?.some(op => op.operation !== 'delete' && op.path === entryId)) { reject('ENTRY_NOT_PROMOTED'); continue; }
117
- if (!this.layout.isPathInside(project.knowledgePath, file, { realpath: true })) { reject('PATH_OUTSIDE_ROOT'); continue; }
118
- try { if (!fs.readFileSync(file, 'utf8').includes(quote)) { reject('QUOTE_MISMATCH'); continue; } }
119
- catch { reject('EVIDENCE_UNREADABLE'); continue; }
120
- const provenance = this.eligibility.verify(raw, snapshot, project);
121
- if (!provenance.ok) { reject(provenance.code); continue; }
122
- const brainId = project.brainId || 'brain-default';
123
- const scopeType = raw.scopeType;
124
- const scopeId = scopeType === 'global' ? brainId : project.domainId;
125
- const key = fingerprint(brainId, scopeType, scopeId, text);
126
- // Tombstones never hold text, so they dedup through their fingerprints:
127
- // the fresh pair covers the record's last scope and text, while the kept
128
- // original capture key still covers a pre-edit/pre-move scope.
129
- const duplicateOf = m => {
130
- if (m.captureFingerprint === key) return true;
131
- if (m.status === 'deleted') return m.fingerprint === key || m.originalCaptureFingerprint === key;
132
- return fingerprint(m.brainId || 'brain-default', this.scopeOf(m).type, this.scopeOf(m).id, m.text) === key || !m.scopeType && m.evidence?.projectId === project.projectId && normalized(m.originalText || m.text) === normalized(text);
133
- };
134
- if (next.some(duplicateOf)) { report.deduplicated++; continue; }
135
- next.push({ id: `memory-${crypto.randomUUID()}`, fingerprint: key, captureFingerprint: key, brainId, domainId: project.domainId || null, scopeType, scopeId, text, originalText: text, status: 'candidate', sourceEventId: provenance.sourceEventId, sourceHash: provenance.sourceHash, eligibility: provenance.eligibility, evidence: { projectId: project.projectId, commitSha: run.commitSha, runId: run.runId, entryId, quote }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
136
- report.accepted++;
137
- }
138
- if (report.accepted) {
139
- this.store.state.memories = next;
140
- try { this.store.save(); } catch (error) { this.store.state.memories = before; throw error; }
141
- }
142
- return report;
143
- }
144
- async create(input) {
145
- if (this.closed) throw new DomainError('PROJECT_BUSY', '引擎正在关闭,请稍后重试。', { status: 409 });
146
- if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['text', 'brainId', 'scopeType', 'scopeId'].includes(key))) throw new DomainError('INVALID_ARGUMENT', '只支持填写记忆内容与适用范围,不能指定来源证据。');
147
- if (typeof input.text !== 'string' || !input.text.trim() || input.text.length > 2000) throw new DomainError('INVALID_ARGUMENT', '记忆内容必须为 1–2000 个字符。');
148
- const brainId = input.brainId === undefined ? 'brain-default' : input.brainId;
149
- validateProjectId(brainId);
150
- const type = input.scopeType === undefined ? 'global' : input.scopeType;
151
- const targetId = input.scopeId === undefined && type === 'global' ? brainId : input.scopeId;
152
- const job = AtomicFile.withFileLock(this.lock(), async () => {
153
- this.validateScope(type, targetId, brainId);
154
- if (!this.brainScope(brainId)) throw new DomainError('INVALID_ARGUMENT', '请先绑定智脑共享目录。', { status: 409 });
155
- const text = input.text.trim(), key = fingerprint(brainId, type, targetId, text);
156
- // An explicit manual add is the user changing their mind after a delete:
157
- // tombstones never block it, only another live record in the same scope does.
158
- if (this.store.state.memories.some(m => m.status !== 'deleted' && fingerprint(m.brainId || 'brain-default', this.scopeOf(m).type, this.scopeOf(m).id, m.text) === key)) throw new DomainError('MEMORY_DUPLICATE', '该范围内已存在相同记忆。', { status: 409 });
159
- // User confirmation is the provenance; never invent a model run or Git commit.
160
- const now = new Date().toISOString();
161
- const memory = { id: `memory-${crypto.randomUUID()}`, fingerprint: key, brainId, scopeType: type, scopeId: targetId, sourceType: 'manual', text, originalText: text, status: 'confirmed', evidence: null, createdAt: now, updatedAt: now };
162
- const before = this.store.state.memories;
163
- this.store.state.memories = [...before, memory];
164
- try { this.store.save(); } catch (error) { this.store.state.memories = before; throw error; }
165
- await this.materialize(); return this.project(memory);
166
- });
167
- this.writes.add(job);
168
- try { return await job; } finally { this.writes.delete(job); }
169
- }
170
- async update(id, input) {
171
- if (this.closed) throw new DomainError('PROJECT_BUSY', '引擎正在关闭,请稍后重试。', { status: 409 });
172
- if (Object.keys(input).some(key => !['text', 'status', 'scopeType', 'scopeId'].includes(key))) throw new DomainError('INVALID_ARGUMENT', '来源证据和文件路径不能修改。');
173
- const job = AtomicFile.withFileLock(this.lock(), async () => {
174
- const memory = this.store.state.memories.find(m => m.id === id);
175
- if (!memory || memory.status === 'deleted') throw new DomainError('PROJECT_NOT_FOUND', '记忆不存在。', { status: 404 });
176
- if (input.text !== undefined && (typeof input.text !== 'string' || !input.text.trim() || input.text.length > 2000)) throw new DomainError('INVALID_ARGUMENT', '记忆内容必须为 1–2000 个字符。');
177
- if (input.status !== undefined && !['confirmed', 'ignored'].includes(input.status)) throw new DomainError('INVALID_ARGUMENT', '记忆状态无效。');
178
- if (memory.status === 'ignored') throw new DomainError('INVALID_ARGUMENT', '该候选已忽略。', { status: 409 });
179
- const brainId = memory.brainId || 'brain-default', old = this.scopeOf(memory);
180
- const type = input.scopeType === undefined ? old.type : input.scopeType;
181
- const targetId = input.scopeId === undefined ? (type === 'global' ? brainId : type === old.type ? old.id : '') : input.scopeId;
182
- if (input.status !== 'ignored' || input.scopeType !== undefined || input.scopeId !== undefined) this.validateScope(type, targetId, brainId);
183
- if ((input.status || memory.status) === 'confirmed' && !this.brainScope(brainId)) throw new DomainError('INVALID_ARGUMENT', '请先绑定智脑共享目录。', { status: 409 });
184
- const text = input.text?.trim() || memory.text, key = fingerprint(brainId, type, targetId, text);
185
- if (this.store.state.memories.some(m => m.id !== id && m.status !== 'deleted' && fingerprint(m.brainId || 'brain-default', this.scopeOf(m).type, this.scopeOf(m).id, m.text) === key)) throw new DomainError('MEMORY_DUPLICATE', '该范围内已存在相同记忆。', { status: 409 });
186
- const next = { ...memory, originalText: memory.originalText || memory.text, captureFingerprint: memory.captureFingerprint || fingerprint(brainId, old.type, old.id, memory.originalText || memory.text), fingerprint: key, scopeType: type, scopeId: targetId, text, status: input.status || memory.status, updatedAt: new Date().toISOString() };
187
- const before = this.store.state.memories;
188
- this.store.state.memories = before.map(m => m.id === id ? next : m);
189
- try { this.store.save(); } catch (error) { this.store.state.memories = before; throw error; }
190
- await this.materialize(); return this.project(next);
191
- });
192
- this.writes.add(job);
193
- try { return await job; } finally { this.writes.delete(job); }
194
- }
195
- async remove(id) {
196
- if (this.closed) throw new DomainError('PROJECT_BUSY', '引擎正在关闭,请稍后重试。', { status: 409 });
197
- if (typeof id !== 'string' || !id.trim()) throw new DomainError('INVALID_ARGUMENT', '记忆 ID 无效。');
198
- const job = AtomicFile.withFileLock(this.lock(), async () => {
199
- const memory = this.store.state.memories.find(m => m.id === id);
200
- if (!memory || memory.status === 'deleted') throw new DomainError('PROJECT_NOT_FOUND', '记忆不存在。', { status: 404 });
201
- const brainId = memory.brainId || 'brain-default', scope = this.scopeOf(memory);
202
- // A tombstone keeps only the dedup fingerprints and audit metadata; the
203
- // text and quote are dropped so a deleted memory never returns through
204
- // lists, markdown, retrieval or context injection, and the fingerprints
205
- // stop the same candidate from coming back on the next capture. Legacy
206
- // records may predate originalText/captureFingerprint/createdAt, so both
207
- // keys are always computed from the live record, and a stored original
208
- // capture key from before an edit or scope move is preserved separately.
209
- const now = new Date().toISOString();
210
- const captureKey = fingerprint(brainId, scope.type, scope.id, memory.originalText || memory.text);
211
- const originalCaptureKey = typeof memory.captureFingerprint === 'string' && /^[a-f0-9]{64}$/.test(memory.captureFingerprint) && memory.captureFingerprint !== captureKey ? memory.captureFingerprint : null;
212
- const tombstone = {
213
- id: memory.id, brainId, scopeType: scope.type, scopeId: scope.id,
214
- ...(memory.sourceType !== undefined ? { sourceType: memory.sourceType } : {}),
215
- status: 'deleted',
216
- fingerprint: fingerprint(brainId, scope.type, scope.id, memory.text),
217
- captureFingerprint: captureKey,
218
- ...(originalCaptureKey ? { originalCaptureFingerprint: originalCaptureKey } : {}),
219
- evidence: memory.evidence ? { projectId: memory.evidence.projectId, commitSha: memory.evidence.commitSha, runId: memory.evidence.runId || null, entryId: memory.evidence.entryId || '' } : null,
220
- createdAt: typeof memory.createdAt === 'string' && Number.isFinite(Date.parse(memory.createdAt)) ? memory.createdAt : now, updatedAt: now, deletedAt: now,
221
- };
222
- const before = this.store.state.memories;
223
- this.store.state.memories = before.map(m => m.id === id ? tombstone : m);
224
- try { this.store.save(); } catch (error) { this.store.state.memories = before; throw error; }
225
- await this.materialize(); return this.project(tombstone);
226
- });
227
- this.writes.add(job);
228
- try { return await job; } finally { this.writes.delete(job); }
229
- }
230
- content(brainId, entry = 'memories/confirmed.md') {
231
- return '# 已确认的长期记忆\n\n' + this.confirmed(brainId, entry).map(m => {
232
- const scope = this.scopeOf(m);
233
- // Preserve legacy global bytes until the user actually edits that record.
234
- const scopeText = m.scopeType ? `适用范围:${{ global: '全局', domain: '领域', project: '项目' }[scope.type]} · ${scope.id}\n\n` : '';
235
- const text = m.scopeType ? m.text.replace(/^\s*(#{1,6})\s/gm, '\\$1 ') : m.text;
236
- const source = m.sourceType === 'manual' ? '手动添加(用户确认)' : m.evidence ? `${m.evidence.projectId} · ${m.evidence.commitSha} · ${m.evidence.entryId}` : '历史记录(来源未记录)';
237
- return `## ${m.id}\n\n${scopeText}${text}\n\n来源:${source}\n`;
238
- }).join('\n');
239
- }
240
- existingEntries(scope) {
241
- const entries = new Set(['memories/confirmed.md']);
242
- for (const group of ['domains', 'projects']) {
243
- const directory = path.join(scope.knowledgePath, 'memories', group);
244
- if (!fs.existsSync(directory)) continue;
245
- if (fs.lstatSync(directory).isSymbolicLink() || !this.layout.isPathInside(scope.knowledgePath, directory, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', '记忆目录越界。', { status: 403 });
246
- for (const name of fs.readdirSync(directory)) if (this.descriptor(`memories/${group}/${name}`)) entries.add(`memories/${group}/${name}`);
247
- }
248
- for (const memory of this.store.state.memories.filter(m => m.status === 'confirmed' && (m.brainId || 'brain-default') === scope.brainId)) entries.add(this.entry(memory));
249
- return entries;
250
- }
251
- async materialize() {
252
- clearTimeout(this.retryTimer);
253
- for (const scope of this.store.state.sharedScopes.filter(s => s.kind === 'brain')) {
254
- try {
255
- let changed = false;
256
- for (const entry of this.existingEntries(scope)) {
257
- const file = this.safeFile(scope, entry), content = this.content(scope.brainId, entry);
258
- if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== content) { AtomicFile.writeFileAtomic(file, content); changed = true; }
259
- }
260
- const recovered = this.syncErrors.delete(scope.id);
261
- if (recovered) this.onSyncChange?.(scope, null);
262
- if (changed) await this.onMaterialized?.(scope);
263
- } catch (error) {
264
- const code = error.code || 'MEMORY_WRITE_FAILED', prior = this.syncErrors.get(scope.id);
265
- this.syncErrors.set(scope.id, code);
266
- if (prior !== code) this.onSyncChange?.(scope, code);
267
- }
268
- }
269
- if (this.syncErrors.size && !this.closed) { this.retryTimer = setTimeout(() => this.recover().catch(() => {}), 5000); this.retryTimer.unref(); }
270
- }
271
- async recover() {
272
- if (this.recovery) return this.recovery;
273
- this.recovery = AtomicFile.withFileLock(this.lock(), () => this.materialize()).finally(() => { this.recovery = null; });
274
- return this.recovery;
275
- }
276
- validFile(scope, entry = 'memories/confirmed.md') {
277
- try { const file = this.safeFile(scope, entry); return fs.existsSync(file) && fs.readFileSync(file, 'utf8') === this.content(scope.brainId, entry); } catch { return false; }
278
- }
279
- async close() { this.closed = true; clearTimeout(this.retryTimer); await Promise.allSettled([...this.writes, this.recovery].filter(Boolean)); }
280
- }
281
- module.exports = { MemoryService };
@@ -1,74 +0,0 @@
1
- 'use strict';
2
-
3
- // Hard provenance gate for automatic long-term memory admission. The
4
- // maintenance model owns the semantic judgment (its prompt contract demands
5
- // durable, cross-project owner preferences); this gate never re-classifies
6
- // text and never trusts model self-reports over the frozen snapshot of the
7
- // claim being captured.
8
- const SHARED_SCOPES = new Set(['domain', 'global']);
9
-
10
- function indexUserEvents(snapshot) {
11
- const events = new Map();
12
- for (const turn of snapshot?.turns || []) {
13
- for (const event of turn.userEvents || []) {
14
- if (event?.eventId) events.set(String(event.eventId), event);
15
- }
16
- }
17
- return events;
18
- }
19
-
20
- function conversationReferences(run) {
21
- const references = new Set();
22
- for (const operation of run?.staging?.operations || []) {
23
- for (const reference of operation.evidenceReferences || []) {
24
- if (typeof reference === 'string' && reference.startsWith('conversation:')) references.add(reference.slice('conversation:'.length));
25
- }
26
- }
27
- return references;
28
- }
29
-
30
- class MemoryEligibility {
31
- constructor(options = {}) {
32
- this.readSnapshot = typeof options.readSnapshot === 'function' ? options.readSnapshot : null;
33
- }
34
-
35
- // The snapshot must exist AND be bound to this run's promoted operations
36
- // through a `conversation:<snapshotHash>` evidence reference, so a foreign
37
- // or later-frozen conversation can never vouch for this claim.
38
- resolve(run) {
39
- if (!this.readSnapshot) return null;
40
- const references = conversationReferences(run);
41
- if (!references.size) return null;
42
- let snapshot = null;
43
- try { snapshot = this.readSnapshot(run.projectId, run.commitSha); } catch { return null; }
44
- return snapshot && references.has(snapshot.snapshotHash) ? snapshot : null;
45
- }
46
-
47
- verify(candidate, snapshot, project) {
48
- if (!snapshot) return { ok: false, code: 'SNAPSHOT_UNAVAILABLE' };
49
- const sourceEventId = String(candidate.sourceEventId || '');
50
- if (!sourceEventId) return { ok: false, code: 'SOURCE_EVENT_MISSING' };
51
- const event = indexUserEvents(snapshot).get(sourceEventId);
52
- if (!event) return { ok: false, code: 'SOURCE_EVENT_NOT_FOUND' };
53
- if ((event.inputOrigin || 'unknown') !== 'human') return { ok: false, code: 'SOURCE_NOT_HUMAN' };
54
- if (String(candidate.sourceHash || '') !== String(event.contentHash || '')) return { ok: false, code: 'SOURCE_HASH_MISMATCH' };
55
- if (!String(event.content || '').includes(String(candidate.quote || '').trim())) return { ok: false, code: 'QUOTE_NOT_IN_SOURCE' };
56
- if (!String(candidate.quote || '').includes(String(candidate.text || '').trim())) return { ok: false, code: 'TEXT_NOT_IN_QUOTE' };
57
- const eligibility = candidate.eligibility;
58
- if (!eligibility || typeof eligibility !== 'object' || Array.isArray(eligibility)) return { ok: false, code: 'ELIGIBILITY_MISSING' };
59
- if (eligibility.durable !== true) return { ok: false, code: 'ELIGIBILITY_NOT_DURABLE' };
60
- if (eligibility.crossProject !== true) return { ok: false, code: 'ELIGIBILITY_NOT_CROSS_PROJECT' };
61
- if (!String(eligibility.reason || '').trim()) return { ok: false, code: 'ELIGIBILITY_REASON_MISSING' };
62
- if (!String(eligibility.scopeReason || '').trim()) return { ok: false, code: 'ELIGIBILITY_SCOPE_REASON_MISSING' };
63
- if (!SHARED_SCOPES.has(candidate.scopeType)) return { ok: false, code: 'SCOPE_NOT_SHARED' };
64
- if (candidate.scopeType === 'domain' && !project.domainId) return { ok: false, code: 'SCOPE_DOMAIN_UNBOUND' };
65
- return {
66
- ok: true,
67
- sourceEventId,
68
- sourceHash: String(event.contentHash),
69
- eligibility: { durable: true, crossProject: true, reason: String(eligibility.reason).trim(), scopeReason: String(eligibility.scopeReason).trim() },
70
- };
71
- }
72
- }
73
-
74
- module.exports = { MemoryEligibility };
@@ -1,14 +0,0 @@
1
- {
2
- "schema": "retrieval-policy/v1",
3
- "rankingVersion": "project-knowledge/ranking-v2",
4
- "models": [
5
- {
6
- "model": "embo-01",
7
- "dimensions": 1536,
8
- "minScore": 0.5,
9
- "calibration": "real-vector-1791886299549/train-families",
10
- "trainingFalsePositiveRate": 0,
11
- "trainingSemanticRecall": 0.8888888888888888
12
- }
13
- ]
14
- }
@@ -1,153 +0,0 @@
1
- 'use strict';
2
- const crypto = require('node:crypto');
3
-
4
- const VERSION = 'project-knowledge/ranking-v2';
5
- const STOP = new Set(('当前 最近 项目 开发 功能 实现 修改 添加 需要 使用 这个 那个 什么 怎么 一个 可以 是否 请 帮我 进行 相关 信息 内容 问题 代码 hello hi the a an is are of to in for and with please implement current project feature').split(' '));
6
- const ALIASES = [
7
- ['unsaved', '未保存'], ['dirty', '脏状态'], ['dialog', '弹窗'], ['popup', '弹窗'], ['export', '导出'],
8
- ['recipe', '配方'], ['plate', '配方'], ['alignment', '对齐'], ['report', '报表'], ['commit', '提交'],
9
- ['vector', '向量'], ['retrieval', '检索'], ['search', '检索'], ['knowledge', '知识'], ['timeout', '超时'],
10
- ['cancel', '取消'], ['connection', '连接'], ['save', '保存'],
11
- ['engine', '引擎'], ['promotion', '晋升'], ['writer', '写入'],
12
- ['one writer', '单写者'], ['single-writer', '单写者'],
13
- ];
14
- const segmenter = typeof Intl.Segmenter === 'function' ? new Intl.Segmenter('zh', { granularity: 'word' }) : null;
15
- const termCache = new Map();
16
-
17
- function terms(text) {
18
- // Cache only tokenization by content hash, never selected facts or scope
19
- // permissions. Canonical file and membership checks still run on every query.
20
- const key = crypto.createHash('sha256').update(String(text || '')).digest('hex');
21
- const prior = termCache.get(key);
22
- if (prior) { termCache.delete(key); termCache.set(key, prior); return prior; }
23
- const source = String(text || '').replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();
24
- const words = segmenter ? [...segmenter.segment(source)].filter(s => s.isWordLike).map(s => s.segment) : source.match(/[\p{L}\p{N}_-]+/gu) || [];
25
- for (const token of source.match(/[a-z][a-z0-9_.\/-]+/g) || []) words.push(token);
26
- const main = words.filter(w => w.length > 1 && !STOP.has(w) && !/^\d+$/.test(w));
27
- const grams = [];
28
- for (const part of source.match(/[\p{Script=Han}]+/gu) || []) for (let i = 0; i < part.length - 1; i++) {
29
- const gram = part.slice(i, i + 2); if (!STOP.has(gram)) grams.push(gram);
30
- }
31
- for (const [english, chinese] of ALIASES) {
32
- if (new RegExp(`\\b${english}\\b`, 'i').test(source)) main.push(chinese);
33
- if (source.includes(chinese)) main.push(english);
34
- }
35
- const result = Object.freeze({ main: Object.freeze(main), grams: Object.freeze(grams) });
36
- termCache.set(key, result);
37
- while (termCache.size > 4096) termCache.delete(termCache.keys().next().value);
38
- return result;
39
- }
40
-
41
- function bodyText(markdown) {
42
- return String(markdown || '').replace(/\r\n/g, '\n').replace(/^---[^\S\n]*\n[\s\S]*?\n---[^\S\n]*(?:\n|$)/, '').replace(/^\n+/, '');
43
- }
44
- const bodyHash = text => crypto.createHash('sha256').update(bodyText(text), 'utf8').digest('hex');
45
-
46
- function intent(query) {
47
- const text = String(query || '').trim();
48
- if (/^(?:hello|hi|hey|你好|您好|早上好|晚上好|在吗)[\s!!。??]*$/i.test(text)) return 'greeting';
49
- if (/^(?:为什么|怎么回事|这是什么意思|继续|然后呢|展开说说|why|continue|tell me more)[\s!!。??]*$/i.test(text)) return 'followup';
50
- const concreteTask = /(修复|实现|新增|设计|为什么|为何|如何|怎样|避免|并发|草稿|implement|fix|design|why|how)/i.test(text);
51
- if (!concreteTask && /(你|本轮|本次|刚才|上一条|这段).*(知识|记忆|上下文|context|memory).*(来源|哪里|什么地方|收到|读取|获取|from|received)/i.test(text)) return 'followup';
52
- if (/(最近|最新|上次|上一[次回]|recent|latest|last)/i.test(text) && /(进度|开发|提交|修改|更新|改动|progress|commit|develop|change|update)/i.test(text)) return 'recent';
53
- return 'search';
54
- }
55
-
56
- function lexical(candidates, query, ignoredTerms = []) {
57
- const q = terms(query), wanted = new Map();
58
- const ignored = new Set(ignoredTerms);
59
- for (const word of q.main) if (!ignored.has(word)) wanted.set(word, 1);
60
- for (const gram of q.grams) if (!wanted.has(gram)) wanted.set(gram, 0.2);
61
- const rows = candidates.map(c => {
62
- const body = terms(c.chunkText), title = terms(`${c.title} ${c.headingPath.join(' ')} ${c.entryId}`), freq = new Map();
63
- for (const word of body.main) freq.set(word, (freq.get(word) || 0) + 1);
64
- for (const word of body.grams) freq.set(word, (freq.get(word) || 0) + 0.2);
65
- for (const word of title.main) freq.set(word, (freq.get(word) || 0) + 2);
66
- for (const word of title.grams) freq.set(word, (freq.get(word) || 0) + 0.4);
67
- return { c, freq, length: Math.max(1, body.main.length + body.grams.length * 0.2 + title.main.length) };
68
- });
69
- const average = rows.reduce((sum, r) => sum + r.length, 0) / Math.max(1, rows.length), df = new Map();
70
- for (const r of rows) for (const word of wanted.keys()) if (r.freq.has(word)) df.set(word, (df.get(word) || 0) + 1);
71
- for (const r of rows) {
72
- let score = 0, anchors = 0;
73
- for (const [word, weight] of wanted) {
74
- const tf = r.freq.get(word) || 0; if (!tf) continue;
75
- const count = df.get(word) || 0, idf = Math.log(1 + (rows.length - count + 0.5) / (count + 0.5));
76
- score += weight * idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * r.length / Math.max(1, average)));
77
- if (weight === 1 || word.length >= 2 && weight === 0.2) anchors++;
78
- }
79
- r.c.lexicalScore = score; r.c.lexicalAnchors = anchors;
80
- }
81
- }
82
-
83
- function rank(candidates, query, scoreIdentity, options = {}) {
84
- // Named technologies select evidence, not merely a similar subject. A
85
- // calibrated embedding can place an unrelated document nearby; it cannot
86
- // establish that PostgreSQL/OpenTelemetry exists in the current knowledge.
87
- // Filenames are excluded because new files legitimately seek analogies.
88
- const topicQuery = String(query).replace(/[A-Za-z0-9_./\\-]+\.[A-Za-z0-9]{1,8}\b/g, '');
89
- const named = [...new Set((topicQuery.match(/\b[A-Z][A-Za-z0-9]*[a-z][A-Z][A-Za-z0-9]*\b/g) || []).map(name => name.toLowerCase()))];
90
- if (named.length) {
91
- const documented = new Map();
92
- for (const c of candidates) {
93
- const key = `${c.spaceId}:${c.entryId}`;
94
- const text = `${c.title}\n${c.chunkText}`.toLowerCase();
95
- const found = documented.get(key) || new Set();
96
- for (const name of named) if (text.includes(name)) found.add(name);
97
- documented.set(key, found);
98
- }
99
- candidates = candidates.filter(c => named.every(name => documented.get(`${c.spaceId}:${c.entryId}`)?.has(name)));
100
- }
101
- // A resolved commit already constrains provenance. Repeated SHA text in a
102
- // heading is not evidence for the topic asked about within that commit.
103
- lexical(candidates, query, options.commitPrefixes || []);
104
- const eligible = [];
105
- for (const c of candidates) {
106
- const identified = scoreIdentity(c);
107
- const exact = identified.selectionSignals.filter(s => /^(exact-|source-basename:|structured:)/.test(s));
108
- if (identified.excluded) continue;
109
- // Raw vector rank is not confidence. Uncalibrated and legacy results need
110
- // independent current-text support; only verified calibrated cosine may stand alone.
111
- const semantic = c.vectorVerified === true && c.vectorCalibrated === true && c.indexScore >= c.vectorMinScore;
112
- if (!exact.length && !c.lexicalAnchors && !semantic) continue;
113
- c.selectionSignals = [...exact, ...(c.lexicalScore > 0 ? ['lexical:bm25'] : []), ...(c.vectorVerified ? ['index:vector-hub'] : []),
114
- `scope:${c.scopeReason}`, ...(c.fromOverlay ? ['markdown-delta-overlay'] : [])];
115
- c.identityMatch = exact.length > 0;
116
- c.commitMatch = exact.includes('exact-commit');
117
- eligible.push(c);
118
- }
119
- const order = (a, b) => a.recordId.localeCompare(b.recordId);
120
- const lexicalRows = eligible.filter(c => c.lexicalScore > 0).sort((a, b) => b.lexicalScore - a.lexicalScore || order(a, b));
121
- const vectorRows = eligible.filter(c => c.vectorVerified && c.indexScore > 0).sort((a, b) => b.indexScore - a.indexScore || order(a, b));
122
- const scores = new Map();
123
- for (const list of [lexicalRows, vectorRows]) list.forEach((c, i) => scores.set(c.recordId, (scores.get(c.recordId) || 0) + 1 / (60 + i + 1)));
124
- // For a resolved commit, order its snippets by the remaining topic, not by
125
- // having two recall channels. Normal semantic queries keep RRF unchanged.
126
- for (const c of eligible) c.relevanceScore = c.commitMatch ? 1 + c.lexicalScore / (1 + c.lexicalScore)
127
- : (scores.get(c.recordId) || 0) + (c.identityMatch ? 1 : 0);
128
- eligible.sort((a, b) => b.relevanceScore - a.relevanceScore
129
- || Number(b.scopeReason === 'primary') - Number(a.scopeReason === 'primary') || order(a, b));
130
- const selected = [], byDocument = new Map();
131
- for (const c of eligible) {
132
- const key = `${c.spaceId}:${c.entryId}`, prior = byDocument.get(key) || [];
133
- const words = new Set(terms(c.chunkText.replace(/^#+.*$/gm, '')).main);
134
- if (prior.length >= 2 || prior.some(row => {
135
- if (row.contentHash === c.contentHash) return true;
136
- // Both offsets were verified against the same current body. A vector
137
- // substring and its containing Markdown chunk are one fact, even when
138
- // the small substring has low token-set similarity to the full section.
139
- const positioned = row.bodyHash && row.bodyHash === c.bodyHash
140
- && Number.isInteger(row.startPos) && Number.isInteger(row.endPos) && row.startPos >= 0 && row.endPos > row.startPos
141
- && Number.isInteger(c.startPos) && Number.isInteger(c.endPos) && c.startPos >= 0 && c.endPos > c.startPos;
142
- const smallSlice = Math.min(row.endPos - row.startPos, c.endPos - c.startPos) * 2 < Math.max(row.endPos - row.startPos, c.endPos - c.startPos);
143
- if (positioned && smallSlice && (row.startPos <= c.startPos && row.endPos >= c.endPos || c.startPos <= row.startPos && c.endPos >= row.endPos)) return true;
144
- const others = new Set(terms(row.chunkText.replace(/^#+.*$/gm, '')).main);
145
- const common = [...words].filter(w => others.has(w)).length;
146
- return common / Math.max(1, new Set([...words, ...others]).size) >= 0.9;
147
- })) continue;
148
- prior.push(c); byDocument.set(key, prior); selected.push(c);
149
- }
150
- return selected;
151
- }
152
-
153
- module.exports = { VERSION, terms, lexical, rank, intent, bodyText, bodyHash };