@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,276 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { sha256 } = require('./content-hash');
4
- const { bodyText } = require('../retrieval-ranking');
5
-
6
- // Version 2: fence-aware heading boundaries changed real chunk geometry (a
7
- // fenced '#' comment no longer splits a section), so version-1 lexical caches
8
- // must miss their sealed document hash and rebuild through the delta overlay.
9
- const CHUNKER_VERSION = 2;
10
- const DEFAULT_MAX_CHARS = 1200;
11
- const DEFAULT_OVERLAP_CHARS = 120;
12
- const EXCLUDED_DIRS = new Set(['.git', '_ai', '_backup', 'node_modules', 'dev-conversations']);
13
- const DERIVED_INDEX_FILENAME = '00-index.md';
14
-
15
- function normalizeRel(value) {
16
- return String(value || '').replace(/\\/g, '/').replace(/^\.\//, '');
17
- }
18
-
19
- function isExcludedKnowledgePath(value) {
20
- return normalizeRel(value).split('/').some(segment => segment.startsWith('.') || EXCLUDED_DIRS.has(segment.toLowerCase()));
21
- }
22
-
23
- function stripFrontmatter(markdown) {
24
- return String(markdown || '').replace(/^---\s*\r?\n[\s\S]*?\r?\n---\s*\r?\n?/, '');
25
- }
26
-
27
- function parseListValue(value) {
28
- const raw = String(value || '').trim();
29
- const body = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1) : raw;
30
- return body.split(',').map(item => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
31
- }
32
-
33
- function parseKnowledgeMetadata(markdown) {
34
- const match = /^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/.exec(String(markdown || ''));
35
- if (!match) return { tags: [], sourcePaths: [], routes: [], symbols: [], affectedModules: [] };
36
- const values = {};
37
- for (const line of match[1].split(/\r?\n/)) {
38
- const field = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(line);
39
- if (field) values[field[1].toLowerCase()] = field[2];
40
- }
41
- return {
42
- tags: parseListValue(values.tags),
43
- sourcePaths: parseListValue(values.sourcepaths || values.source_paths),
44
- routes: parseListValue(values.routes),
45
- symbols: parseListValue(values.symbols),
46
- affectedModules: parseListValue(values.affectedmodules || values.affected_modules),
47
- };
48
- }
49
-
50
- function splitLongText(text, maxChars, overlapChars, base = 0) {
51
- const raw = String(text || '');
52
- const clean = raw.trim();
53
- if (!clean) return [];
54
- const origin = base + (raw.length - raw.trimStart().length);
55
- if (clean.length <= maxChars) return [{ text: clean, start: origin, end: origin + clean.length }];
56
- const parts = [];
57
- let start = 0;
58
- while (start < clean.length) {
59
- let end = Math.min(start + maxChars, clean.length);
60
- if (end < clean.length) {
61
- const floor = start + Math.floor(maxChars * 0.6);
62
- const boundary = Math.max(clean.lastIndexOf('\n\n', end), clean.lastIndexOf('。', end), clean.lastIndexOf('. ', end));
63
- if (boundary >= floor) end = boundary + 1;
64
- }
65
- const piece = clean.slice(start, end);
66
- const trimmed = piece.trim();
67
- if (trimmed) {
68
- const lead = piece.length - piece.trimStart().length;
69
- parts.push({ text: trimmed, start: origin + start + lead, end: origin + start + lead + trimmed.length });
70
- }
71
- if (end >= clean.length) break;
72
- start = Math.max(start + 1, end - overlapChars);
73
- }
74
- return parts;
75
- }
76
-
77
- // Heading and fence parsing must stay identical to the slice heading scan in
78
- // retrieval.js so vector slices report the same heading paths as chunks.
79
- function lineFenceState(line, fence) {
80
- const marker = /^([ \t]*)(`{3,}|~{3,})(.*)$/.exec(line);
81
- if (!marker) return fence;
82
- if (!fence) return marker[2];
83
- if (fence[0] === marker[2][0] && marker[2].length >= fence.length && !marker[3].trim()) return null;
84
- return fence;
85
- }
86
-
87
- function headingOf(line) {
88
- const match = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
89
- return match ? { level: match[1].length, text: match[2].trim() } : null;
90
- }
91
-
92
- function chunkMarkdown(markdown, options = {}) {
93
- const maxChars = Number(options.maxChars || DEFAULT_MAX_CHARS);
94
- const overlapChars = Math.min(Number(options.overlapChars || DEFAULT_OVERLAP_CHARS), Math.floor(maxChars / 3));
95
- const body = bodyText(markdown);
96
- const lines = body.split('\n');
97
- const headings = [];
98
- const sections = [];
99
- let buffer = [];
100
- let bufferStart = 0;
101
- let sectionHeadings = [];
102
- let fence = null;
103
-
104
- const flush = () => {
105
- const text = buffer.join('\n');
106
- const trimmed = text.trim();
107
- if (trimmed) {
108
- const lead = text.length - text.trimStart().length;
109
- const trail = text.length - text.trimEnd().length;
110
- sections.push({ headingPath: [...sectionHeadings], text: trimmed, start: bufferStart + lead, end: bufferStart + text.length - trail });
111
- }
112
- buffer = [];
113
- };
114
-
115
- let offset = 0;
116
- for (const line of lines) {
117
- const lineStart = offset;
118
- offset += line.length + 1;
119
- fence = lineFenceState(line, fence);
120
- // Only real headings outside code fences split sections; a fenced '#'
121
- // comment is plain content.
122
- const heading = fence ? null : headingOf(line);
123
- if (heading) {
124
- flush();
125
- headings.length = heading.level - 1;
126
- headings[heading.level - 1] = heading.text;
127
- sectionHeadings = headings.filter(Boolean);
128
- }
129
- if (!buffer.length) bufferStart = lineStart;
130
- buffer.push(line);
131
- }
132
- flush();
133
-
134
- const chunks = [];
135
- for (const section of sections) {
136
- for (const part of splitLongText(section.text, maxChars, overlapChars, section.start)) {
137
- chunks.push({
138
- chunkOrder: chunks.length,
139
- headingPath: section.headingPath,
140
- chunkText: part.text,
141
- startPos: part.start,
142
- endPos: part.end,
143
- });
144
- }
145
- }
146
- return chunks;
147
- }
148
-
149
- function isDerivedIndex(filePath) {
150
- return path.basename(String(filePath || '')).toLowerCase() === DERIVED_INDEX_FILENAME;
151
- }
152
-
153
- function listMarkdownFiles(root, options = {}) {
154
- const includeDerived = options.includeDerived === true;
155
- const files = [];
156
- const walk = (dir) => {
157
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
158
- if (entry.name.startsWith('.') || EXCLUDED_DIRS.has(entry.name.toLowerCase())) continue;
159
- const abs = path.join(dir, entry.name);
160
- if (entry.isDirectory()) walk(abs);
161
- else if (entry.isFile() && /\.md$/i.test(entry.name) && (includeDerived || !isDerivedIndex(entry.name))) files.push(abs);
162
- }
163
- };
164
- if (fs.existsSync(root)) walk(path.resolve(root));
165
- return files.sort();
166
- }
167
-
168
- function inferEntryType(relativePath) {
169
- const rel = normalizeRel(relativePath).toLowerCase();
170
- if (rel === 'goal.md') return 'goal';
171
- if (rel === 'architecture.md') return 'architecture';
172
- if (rel.startsWith('modules/')) return 'module';
173
- if (rel.startsWith('changes/')) return 'change';
174
- return 'document';
175
- }
176
-
177
- function inferTitle(markdown, relativePath) {
178
- const heading = /^#\s+(.+)$/m.exec(stripFrontmatter(markdown));
179
- return heading ? heading[1].trim() : path.basename(relativePath, path.extname(relativePath));
180
- }
181
-
182
- class MarkdownKnowledgeIndexer {
183
- constructor(options = {}) {
184
- if (!options.database) throw new Error('database is required');
185
- if (!options.embedder) throw new Error('embedder is required');
186
- this.database = options.database;
187
- this.embedder = options.embedder;
188
- this.maxChars = options.maxChars || DEFAULT_MAX_CHARS;
189
- this.overlapChars = options.overlapChars || DEFAULT_OVERLAP_CHARS;
190
- }
191
-
192
- async indexFile(input) {
193
- const filePath = path.resolve(input.filePath);
194
- const relativePath = normalizeRel(input.relativePath || path.basename(filePath));
195
- const markdown = fs.readFileSync(filePath, 'utf8');
196
- const documentHash = sha256(`chunker:${CHUNKER_VERSION}\n${markdown}`);
197
- const existing = await this.database.rowsForEntry(input.spaceId, relativePath);
198
- if (existing.length && existing.every(row => row.document_hash === documentHash)) {
199
- return { ok: true, action: 'unchanged', entryId: relativePath, chunks: existing.length, documentHash };
200
- }
201
- const title = inferTitle(markdown, relativePath);
202
- const metadata = parseKnowledgeMetadata(markdown);
203
- const rawChunks = chunkMarkdown(markdown, { maxChars: this.maxChars, overlapChars: this.overlapChars });
204
- const chunks = [];
205
- for (const chunk of rawChunks) {
206
- const embeddingText = [title, chunk.headingPath.join(' > '), chunk.chunkText].filter(Boolean).join('\n');
207
- chunks.push({
208
- ...chunk,
209
- title,
210
- entryType: inferEntryType(relativePath),
211
- // Keyword search now indexes chunk_text directly. Keep only compact
212
- // title/heading metadata in the legacy search_text column so new rows
213
- // do not duplicate the entire document body.
214
- searchText: [title, chunk.headingPath.join(' > ')].filter(Boolean).join('\n'),
215
- vector: await this.embedder.embedPassage(embeddingText),
216
- tags: [...new Set([...metadata.tags, ...metadata.affectedModules])],
217
- sourcePaths: metadata.sourcePaths.length ? metadata.sourcePaths : input.sourcePaths || [],
218
- routes: metadata.routes,
219
- symbols: metadata.symbols,
220
- sourceProjectId: input.sourceProjectId || '',
221
- sourceCommit: input.sourceCommit || '',
222
- documentHash,
223
- });
224
- }
225
- const result = await this.database.replaceEntry(input.spaceId, relativePath, chunks);
226
- return { ...result, entryId: relativePath, chunks: chunks.length, documentHash };
227
- }
228
-
229
- async indexDirectory(input) {
230
- const root = path.resolve(input.kbPath);
231
- const files = listMarkdownFiles(root);
232
- const present = new Set();
233
- const results = [];
234
- for (const filePath of files) {
235
- const relativePath = normalizeRel(path.relative(root, filePath));
236
- present.add(relativePath);
237
- results.push(await this.indexFile({ ...input, filePath, relativePath }));
238
- }
239
- const stale = (await this.database.entryIds(input.spaceId)).filter(entryId => !present.has(entryId));
240
- let deletedChunks = 0;
241
- for (const entryId of stale) deletedChunks += (await this.database.deleteEntry(input.spaceId, entryId)).deleted;
242
- const changed = results.filter(item => item.action !== 'unchanged');
243
- const operations = changed.length + stale.length;
244
- const rows = changed.reduce((sum, item) => sum + Number(item.upserted || 0) + Number(item.deleted || 0), 0) + deletedChunks;
245
- const mutationState = this.database.noteMutations({ operations, rows });
246
- let maintenance = { ok: true, optimized: false, deferred: input.deferMaintenance === true, state: mutationState };
247
- if (await this.database.count([input.spaceId])) {
248
- await this.database.ensureSearchIndexes();
249
- if (input.deferMaintenance !== true) maintenance = await this.database.maybeOptimize();
250
- }
251
- return {
252
- ok: true,
253
- spaceId: input.spaceId,
254
- files: files.length,
255
- indexed: changed.length,
256
- unchanged: results.filter(item => item.action === 'unchanged').length,
257
- deletedEntries: stale.length,
258
- deletedChunks,
259
- maintenance,
260
- results,
261
- };
262
- }
263
- }
264
-
265
- module.exports = {
266
- MarkdownKnowledgeIndexer,
267
- CHUNKER_VERSION,
268
- chunkMarkdown,
269
- lineFenceState,
270
- headingOf,
271
- listMarkdownFiles,
272
- isExcludedKnowledgePath,
273
- isDerivedIndex,
274
- inferEntryType,
275
- parseKnowledgeMetadata,
276
- };
@@ -1,298 +0,0 @@
1
- const crypto = require('crypto');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const { TextDecoder } = require('util');
5
- const { execGit } = require('./git-runner');
6
- const { DomainError } = require('./contracts');
7
- const { ExactPatchEvidenceBundle } = require('./evidence-bundle');
8
-
9
- const EMPTY_TREE_SHA = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
10
- const DEFAULT_MAX_PATCH_BYTES = 2 * 1024 * 1024;
11
-
12
- function sha256(value) {
13
- return `sha256:${crypto.createHash('sha256').update(value).digest('hex')}`;
14
- }
15
-
16
- function validateSha(value, name = 'commit') {
17
- const sha = String(value || '').trim().toLowerCase();
18
- if (!/^[0-9a-f]{40}$/.test(sha)) throw new DomainError('INVALID_ARGUMENT', `${name} must be a full Git commit SHA.`);
19
- return sha;
20
- }
21
-
22
- function parseNameStatus(text) {
23
- return String(text || '').split(/\r?\n/).filter(Boolean).map(line => {
24
- const columns = line.split('\t');
25
- const status = columns.shift() || '';
26
- const renamed = /^[RC]/.test(status) && columns.length >= 2;
27
- return {
28
- status,
29
- path: renamed ? columns[1] : columns[0] || '',
30
- oldPath: renamed ? columns[0] : null,
31
- binary: false,
32
- };
33
- });
34
- }
35
-
36
- function applyNumstat(files, text) {
37
- const byPath = new Map(files.map(file => [file.path, file]));
38
- for (const line of String(text || '').split(/\r?\n/).filter(Boolean)) {
39
- const [added, deleted, ...nameParts] = line.split('\t');
40
- const name = nameParts[nameParts.length - 1] || '';
41
- const file = byPath.get(name);
42
- if (!file) continue;
43
- file.binary = added === '-' && deleted === '-';
44
- file.added = added === '-' ? null : Number(added);
45
- file.deleted = deleted === '-' ? null : Number(deleted);
46
- }
47
- return files;
48
- }
49
-
50
- class TrustedGitReader {
51
- constructor(options = {}) {
52
- this.execGit = options.execGit || execGit;
53
- this.maxPatchBytes = Number(options.maxPatchBytes || DEFAULT_MAX_PATCH_BYTES);
54
- this.evidenceBundle = options.evidenceBundle || new ExactPatchEvidenceBundle(options);
55
- }
56
-
57
- async run(repoPath, args, timeoutMs = 30_000) {
58
- const result = await this.execGit(repoPath, args, timeoutMs);
59
- if (!result || !result.ok) {
60
- throw new DomainError('INVALID_ARGUMENT', 'Trusted Git read failed.', {
61
- status: 409,
62
- details: { args: args.slice(0, 4), code: result && result.code, error: String(result && (result.stderr || result.error) || '').slice(0, 1000) },
63
- });
64
- }
65
- return String(result.stdout || '');
66
- }
67
-
68
- async runBuffer(repoPath, args, timeoutMs = 30_000) {
69
- const result = await this.execGit(repoPath, args, timeoutMs);
70
- if (!result || !result.ok) {
71
- throw new DomainError('INVALID_ARGUMENT', 'Trusted Git read failed.', {
72
- status: 409,
73
- details: { args: args.slice(0, 4), code: result && result.code, error: String(result && (result.stderr || result.error) || '').slice(0, 1000) },
74
- });
75
- }
76
- return Buffer.isBuffer(result.stdoutBuffer) ? result.stdoutBuffer : Buffer.from(String(result.stdout || ''), 'utf8');
77
- }
78
-
79
- async isRepository(repoPath) {
80
- if (!repoPath || !fs.existsSync(repoPath)) return false;
81
- const result = await this.execGit(repoPath, ['rev-parse', '--is-inside-work-tree'], 10_000);
82
- return Boolean(result && result.ok && String(result.stdout || '').trim() === 'true');
83
- }
84
-
85
- async head(repoPath) {
86
- const result = await this.execGit(repoPath, ['rev-parse', '--verify', 'HEAD'], 10_000);
87
- if (!result || !result.ok) return null;
88
- const sha = String(result.stdout || '').trim().toLowerCase();
89
- return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
90
- }
91
-
92
- async branch(repoPath) {
93
- const result = await this.execGit(repoPath, ['symbolic-ref', '--quiet', '--short', 'HEAD'], 10_000);
94
- return result && result.ok ? String(result.stdout || '').trim() : '';
95
- }
96
-
97
- async isAncestor(repoPath, ancestor, commit) {
98
- validateSha(ancestor, 'baseline');
99
- validateSha(commit, 'HEAD');
100
- const result = await this.execGit(repoPath, ['merge-base', '--is-ancestor', ancestor, commit], 10_000);
101
- return Boolean(result && result.ok);
102
- }
103
-
104
- async listCommits(repoPath, baseline, head) {
105
- validateSha(head, 'HEAD');
106
- const revision = baseline ? `${validateSha(baseline, 'baseline')}..${head}` : head;
107
- const output = await this.run(repoPath, ['rev-list', '--reverse', '--topo-order', revision]);
108
- return output.split(/\r?\n/).map(value => value.trim().toLowerCase()).filter(value => /^[0-9a-f]{40}$/.test(value));
109
- }
110
-
111
- async collectEvidence(repoPath, commitSha, options = {}) {
112
- const commit = validateSha(commitSha);
113
- const raw = await this.run(repoPath, ['show', '-s', '--date=iso-strict', '--format=%H%x00%P%x00%an%x00%aI%x00%s', commit]);
114
- const [resolved, parentsRaw, author, date, ...subjectParts] = raw.replace(/\r?\n$/, '').split('\u0000');
115
- const parents = String(parentsRaw || '').split(/\s+/).filter(Boolean).map(parent => validateSha(parent, 'parent'));
116
- const nameStatus = await this.run(repoPath, ['diff-tree', '--root', '--find-renames', '--name-status', '-r', '--no-commit-id', commit]);
117
- const numstat = await this.run(repoPath, ['diff-tree', '--root', '--find-renames', '--numstat', '-r', '--no-commit-id', commit]);
118
- const files = applyNumstat(parseNameStatus(nameStatus), numstat);
119
- const base = parents.length ? parents[0] : EMPTY_TREE_SHA;
120
- const patchBuffer = await this.runBuffer(repoPath, ['diff', '--no-ext-diff', '--binary', '--find-renames', '--unified=3', base, commit], options.patchTimeoutMs || 60_000);
121
- const patchBytes = patchBuffer.length;
122
- const maxPatchBytes = Number(options.maxPatchBytes || this.maxPatchBytes);
123
- let patch = null;
124
- try { patch = new TextDecoder('utf-8', { fatal: true }).decode(patchBuffer); } catch { patch = null; }
125
- const patchChunked = patchBytes > maxPatchBytes || patch == null;
126
- const branch = options.branch != null ? String(options.branch) : await this.branch(repoPath);
127
- const metadata = {
128
- commitSha: resolved || commit,
129
- parents,
130
- author: author || '',
131
- date: date || '',
132
- subject: subjectParts.join('\u0000').trim(),
133
- branch,
134
- patchBase: base,
135
- patchMode: parents.length > 1 ? 'merge-first-parent' : parents.length === 0 ? 'root-empty-tree' : 'parent',
136
- };
137
- const patchHash = sha256(patchBuffer);
138
- if (patchChunked && !options.evidenceRoot) {
139
- throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Large patch requires an exact evidence bundle root.', { status: 500 });
140
- }
141
- const evidenceBundle = options.evidenceRoot ? this.evidenceBundle.build({
142
- evidenceRoot: options.evidenceRoot,
143
- patch: patchBuffer,
144
- patchHash,
145
- commit: metadata,
146
- files,
147
- }) : null;
148
- const evidenceHash = sha256(JSON.stringify({
149
- metadata,
150
- files,
151
- patchHash,
152
- patchBytes,
153
- evidenceManifestHash: evidenceBundle && evidenceBundle.manifestHash || null,
154
- }));
155
- return {
156
- schema: 'commit-evidence/v1',
157
- ...metadata,
158
- files,
159
- patch: patchChunked ? null : patch,
160
- patchHash,
161
- patchBytes,
162
- patchInline: !patchChunked,
163
- patchChunked,
164
- patchOmitted: false,
165
- patchLimitBytes: maxPatchBytes,
166
- omittedReason: null,
167
- evidenceBundle,
168
- evidenceHash,
169
- };
170
- }
171
-
172
- verifyEvidence(evidence) {
173
- if (!evidence || !evidence.patchHash || !Number.isInteger(evidence.patchBytes)) {
174
- throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Commit evidence is incomplete.', { status: 500 });
175
- }
176
- if (evidence.evidenceBundle) {
177
- return this.evidenceBundle.verify(evidence.evidenceBundle.root, {
178
- expectedPatchHash: evidence.patchHash,
179
- expectedBytes: evidence.patchBytes,
180
- });
181
- }
182
- if (evidence.patchChunked) {
183
- throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Chunked patch has no frozen evidence bundle.', { status: 500 });
184
- }
185
- if (sha256(evidence.patch || '') !== evidence.patchHash) {
186
- throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Inline patch hash does not match.', { status: 500 });
187
- }
188
- return null;
189
- }
190
- }
191
-
192
- class CommitScanner {
193
- constructor(options = {}) {
194
- this.git = options.gitReader || new TrustedGitReader(options);
195
- this.batchSize = Math.max(1, Number(options.batchSize || 200));
196
- }
197
-
198
- async scan(config, state, options = {}) {
199
- const repoPath = config && config.repoPath;
200
- if (!repoPath || !await this.git.isRepository(repoPath)) {
201
- return { status: 'not-git', head: null, baseline: null, commits: [], continuation: null, error: 'repoPath is not an available Git worktree' };
202
- }
203
- const head = await this.git.head(repoPath);
204
- if (!head) {
205
- return { status: 'empty-repo', head: null, baseline: null, commits: [], continuation: null, branch: await this.git.branch(repoPath) };
206
- }
207
- const branch = await this.git.branch(repoPath);
208
- const last = state && state.lastAnalyzedCommit || null;
209
- const tracking = state && state.trackingStartCommit || null;
210
- const baseline = last || tracking || null;
211
- if (!baseline && (!state || state.trackingMode !== 'empty-repo')) {
212
- return { status: 'establish-tracking', head, baseline: null, commits: [], continuation: null, branch };
213
- }
214
- if (baseline && !await this.git.isAncestor(repoPath, baseline, head)) {
215
- return { status: 'history-diverged', head, baseline, commits: [], continuation: null, branch, error: 'tracking baseline is not an ancestor of HEAD' };
216
- }
217
- const all = await this.git.listCommits(repoPath, baseline, head);
218
- const batchSize = Math.max(1, Number(options.batchSize || this.batchSize));
219
- const commits = all.slice(0, batchSize);
220
- return {
221
- status: 'ok',
222
- head,
223
- baseline,
224
- branch,
225
- commits,
226
- pendingCount: all.length,
227
- continuation: all.length > commits.length ? { remaining: all.length - commits.length, after: commits[commits.length - 1] } : null,
228
- };
229
- }
230
-
231
- collectEvidence(config, commitSha, options = {}) {
232
- return this.git.collectEvidence(config.repoPath, commitSha, options);
233
- }
234
-
235
- verifyEvidence(evidence) {
236
- return this.git.verifyEvidence(evidence);
237
- }
238
- }
239
-
240
- // Transitional read-only adapter for callers migrated in T10.
241
- async function scanProject(project, options = {}) {
242
- const scanner = options.scanner || new CommitScanner(options);
243
- const config = { repoPath: project && (project.repoPath || project.gitPath || project.localPath) };
244
- const state = {
245
- lastAnalyzedCommit: project && project.lastAnalyzedCommit || null,
246
- trackingStartCommit: project && project.trackingStartCommit || null,
247
- trackingMode: project && project.trackingMode || 'normal',
248
- };
249
- const scan = await scanner.scan(config, state, options);
250
- const result = {
251
- slug: project && (project.projectId || project.slug),
252
- repoStatus: scan.status === 'empty-repo' ? 'empty' : scan.status === 'not-git' ? 'not-git' : scan.status === 'history-diverged' ? 'diverged' : 'ok',
253
- headCommit: scan.head,
254
- lastAnalyzedCommit: state.lastAnalyzedCommit,
255
- trackingStartCommit: scan.status === 'establish-tracking' ? scan.head : state.trackingStartCommit,
256
- pendingCount: scan.commits.length,
257
- mode: scan.status === 'establish-tracking' ? 'tracking-start' : state.lastAnalyzedCommit ? 'incremental' : state.trackingMode === 'empty-repo' ? 'empty-repo-first-commit' : 'tracked',
258
- range: scan.baseline && scan.head ? `${scan.baseline}..${scan.head}` : null,
259
- commits: [],
260
- continuation: scan.continuation,
261
- error: scan.error || null,
262
- };
263
- for (const commitSha of scan.commits) {
264
- const evidence = await scanner.collectEvidence(config, commitSha, { branch: scan.branch });
265
- result.commits.push({
266
- hash: commitSha,
267
- short: commitSha.slice(0, 7),
268
- date: evidence.date,
269
- author: evidence.author,
270
- subject: evidence.subject,
271
- });
272
- }
273
- return result;
274
- }
275
-
276
- async function applyScanResult(project, scan) {
277
- project.headCommit = scan.headCommit;
278
- project.repoStatus = scan.repoStatus;
279
- if (!project.trackingStartCommit && scan.trackingStartCommit) project.trackingStartCommit = scan.trackingStartCommit;
280
- project.lastSeenCommit = scan.headCommit || project.lastSeenCommit;
281
- project.lastScanAt = new Date().toISOString();
282
- project.lastScanPendingCount = scan.pendingCount;
283
- project.lastScanMode = scan.mode;
284
- project.lastScanError = scan.error || null;
285
- return project;
286
- }
287
-
288
- module.exports = {
289
- EMPTY_TREE_SHA,
290
- DEFAULT_MAX_PATCH_BYTES,
291
- TrustedGitReader,
292
- CommitScanner,
293
- scanProject,
294
- applyScanResult,
295
- parseNameStatus,
296
- sha256,
297
- validateSha,
298
- };