@sanqianx/project-knowledge 5.0.31 → 5.0.32

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 (89) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +5 -0
  3. package/README.md +5 -2
  4. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +1 -1
  5. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +1 -1
  6. package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
  7. package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
  8. package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
  9. package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
  10. package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
  11. package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
  12. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +1 -1
  13. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +1 -1
  14. package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
  15. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +1 -1
  16. package/_site/_test/helpers/parallel-memory-injection-shell.js +1 -1
  17. package/_site/_test/helpers/parallel-nav-shell.js +1 -1
  18. package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
  19. package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
  20. package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
  21. package/_site/_test/package-boundary-test.js +5 -0
  22. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +1 -1
  23. package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
  24. package/_site/_test/parallel-knowledge-engine-test.js +3 -3
  25. package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
  26. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +1 -1
  27. package/_site/_test/parallel-memory-injection-origin-probe.js +1 -1
  28. package/_site/_test/parallel-nav-isolation-test.js +1 -1
  29. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
  30. package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
  31. package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
  32. package/_site/_test/qa-r45-offline-backfill-test.js +2 -2
  33. package/_site/_test/t07d-git-rel-coverage-test.js +5 -3
  34. package/_site/_test/t07f-mem-008-coverage-test.js +1 -1
  35. package/_site/lib/module-bridge.js +2 -11
  36. package/_site/scripts/install-module-candidates.js +1 -1
  37. package/_site/scripts/pack-module-candidates.js +2 -1
  38. package/_site/scripts/verify-module-runtime.js +17 -32
  39. package/_site/scripts/verify-product-runtime.js +7 -3
  40. package/docs/README.zh-CN.md +3 -1
  41. package/module-runtime-manifest.json +53 -3
  42. package/package.json +2 -4
  43. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  44. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  45. package/plugins/project-knowledge/.mcp.json +1 -1
  46. package/_modules/knowledge-engine/README.md +0 -133
  47. package/_modules/knowledge-engine/package.json +0 -38
  48. package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
  49. package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
  50. package/_modules/knowledge-engine/src/analysis-output.js +0 -52
  51. package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
  52. package/_modules/knowledge-engine/src/bin.js +0 -52
  53. package/_modules/knowledge-engine/src/bridge-client.js +0 -24
  54. package/_modules/knowledge-engine/src/context.js +0 -140
  55. package/_modules/knowledge-engine/src/coordinator.js +0 -376
  56. package/_modules/knowledge-engine/src/diagnostics.js +0 -37
  57. package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
  58. package/_modules/knowledge-engine/src/index-request.js +0 -49
  59. package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
  60. package/_modules/knowledge-engine/src/memories.js +0 -281
  61. package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
  62. package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
  63. package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
  64. package/_modules/knowledge-engine/src/retrieval.js +0 -367
  65. package/_modules/knowledge-engine/src/runtime/README.md +0 -7
  66. package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
  67. package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
  68. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
  69. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
  70. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
  71. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
  72. package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
  73. package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
  74. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
  75. package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
  76. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
  77. package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
  78. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
  79. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
  80. package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
  81. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
  82. package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
  83. package/_modules/knowledge-engine/src/server.js +0 -166
  84. package/_modules/knowledge-engine/src/store.js +0 -267
  85. package/_modules/knowledge-engine/ui/app.css +0 -172
  86. package/_modules/knowledge-engine/ui/app.js +0 -318
  87. package/_modules/knowledge-engine/ui/index.html +0 -95
  88. package/_site/scripts/vendor-modules.js +0 -49
  89. package/vendor-manifest.json +0 -55
@@ -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 };
@@ -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,不启动第二份索引。