@sanqianx/project-knowledge 5.0.30 → 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 (135) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +26 -0
  3. package/README.md +5 -2
  4. package/_site/_test/appearance-settings-test.js +148 -0
  5. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +606 -0
  6. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +464 -0
  7. package/_site/_test/helpers/parallel-dock-acceptance-env.js +301 -0
  8. package/_site/_test/helpers/parallel-dock-acceptance-r2-env.js +378 -0
  9. package/_site/_test/helpers/parallel-dock-acceptance-r2-ui.js +314 -0
  10. package/_site/_test/helpers/parallel-dock-acceptance-ui.js +195 -0
  11. package/_site/_test/helpers/parallel-dock-isolation-r3-credential-preload.js +113 -0
  12. package/_site/_test/helpers/parallel-dock-isolation-r3-env.js +307 -0
  13. package/_site/_test/helpers/parallel-dock-isolation-r3-fixture.js +373 -0
  14. package/_site/_test/helpers/parallel-dock-isolation-r3-ui.js +314 -0
  15. package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
  16. package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
  17. package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
  18. package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
  19. package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
  20. package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
  21. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +340 -0
  22. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +82 -0
  23. package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
  24. package/_site/_test/helpers/parallel-memory-capture-r3-cap-shell.js +605 -0
  25. package/_site/_test/helpers/parallel-memory-capture-r3-shell.js +176 -0
  26. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +577 -0
  27. package/_site/_test/helpers/parallel-memory-injection-shell.js +723 -0
  28. package/_site/_test/helpers/parallel-memory-injection-wb-host.js +81 -0
  29. package/_site/_test/helpers/parallel-nav-shell.js +1 -1
  30. package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
  31. package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
  32. package/_site/_test/helpers/parallel-workbench-drafts-r5-fixture.js +295 -0
  33. package/_site/_test/helpers/parallel-workbench-drafts-r5-harness.js +573 -0
  34. package/_site/_test/helpers/parallel-workbench-drafts-r5-host.js +69 -0
  35. package/_site/_test/helpers/parallel-workbench-runtime-harness.js +587 -0
  36. package/_site/_test/helpers/qa-r45-harness.js +94 -0
  37. package/_site/_test/helpers/qa-r48-env.js +64 -0
  38. package/_site/_test/helpers/qa-r51-env.cjs +77 -0
  39. package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
  40. package/_site/_test/package-boundary-test.js +5 -0
  41. package/_site/_test/parallel-capture-safety-r5-cap006-probe.js +524 -0
  42. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +577 -0
  43. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +320 -0
  44. package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
  45. package/_site/_test/parallel-engine-reconcile-r4-eng007-probe.js +304 -0
  46. package/_site/_test/parallel-knowledge-engine-test.js +3 -3
  47. package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
  48. package/_site/_test/parallel-logging-acceptance-log003-probe.js +78 -0
  49. package/_site/_test/parallel-logging-acceptance-log004-probe.js +85 -0
  50. package/_site/_test/parallel-memory-capture-r3-cap001-probe.js +238 -0
  51. package/_site/_test/parallel-memory-capture-r3-cap006-probe.js +371 -0
  52. package/_site/_test/parallel-memory-capture-r3-cap008-probe.js +439 -0
  53. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +271 -0
  54. package/_site/_test/parallel-memory-capture-r4-cap006-probe.js +519 -0
  55. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +569 -0
  56. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +314 -0
  57. package/_site/_test/parallel-memory-injection-origin-probe.js +412 -0
  58. package/_site/_test/parallel-memory-injection-probe.js +411 -0
  59. package/_site/_test/parallel-nav-isolation-test.js +1 -1
  60. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
  61. package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
  62. package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
  63. package/_site/_test/parallel-workbench-drafts-r4-probe.js +477 -0
  64. package/_site/_test/parallel-workbench-drafts-r5-chrome-env-bisect.js +89 -0
  65. package/_site/_test/parallel-workbench-drafts-r5-probe.js +593 -0
  66. package/_site/_test/parallel-workbench-runtime-minimax-probe.js +321 -0
  67. package/_site/_test/parallel-workbench-runtime-wb004-ordering.js +307 -0
  68. package/_site/_test/parallel-workbench-runtime-wb005-drafts.js +313 -0
  69. package/_site/_test/parallel-workbench-runtime-wb008-abort.js +321 -0
  70. package/_site/_test/qa-r45-offline-backfill-test.js +279 -0
  71. package/_site/_test/qa-r48-sys003-blank-secret-test.js +258 -0
  72. package/_site/_test/t07c-cln-001-002-007-coverage-test.js +135 -0
  73. package/_site/_test/t07d-git-rel-coverage-test.js +226 -0
  74. package/_site/_test/t07e-qta-coverage-test.js +195 -0
  75. package/_site/_test/t07f-mem-008-coverage-test.js +101 -0
  76. package/_site/lib/module-bridge.js +2 -11
  77. package/_site/lib/server-app.js +11 -2
  78. package/_site/lib/settings-store.js +43 -1
  79. package/_site/scripts/install-module-candidates.js +1 -1
  80. package/_site/scripts/pack-module-candidates.js +2 -1
  81. package/_site/scripts/verify-module-runtime.js +17 -32
  82. package/_site/scripts/verify-product-runtime.js +7 -3
  83. package/docs/README.zh-CN.md +3 -1
  84. package/module-runtime-manifest.json +56 -6
  85. package/package.json +2 -4
  86. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  87. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  88. package/plugins/project-knowledge/.mcp.json +1 -1
  89. package/ui/index.html +18 -1
  90. package/ui/product.css +6 -2
  91. package/ui/product.js +86 -1
  92. package/_modules/knowledge-engine/README.md +0 -133
  93. package/_modules/knowledge-engine/package.json +0 -38
  94. package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
  95. package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
  96. package/_modules/knowledge-engine/src/analysis-output.js +0 -52
  97. package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
  98. package/_modules/knowledge-engine/src/bin.js +0 -52
  99. package/_modules/knowledge-engine/src/bridge-client.js +0 -24
  100. package/_modules/knowledge-engine/src/context.js +0 -140
  101. package/_modules/knowledge-engine/src/coordinator.js +0 -376
  102. package/_modules/knowledge-engine/src/diagnostics.js +0 -37
  103. package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
  104. package/_modules/knowledge-engine/src/index-request.js +0 -49
  105. package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
  106. package/_modules/knowledge-engine/src/memories.js +0 -281
  107. package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
  108. package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
  109. package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
  110. package/_modules/knowledge-engine/src/retrieval.js +0 -367
  111. package/_modules/knowledge-engine/src/runtime/README.md +0 -7
  112. package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
  113. package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
  114. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
  115. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
  116. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
  117. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
  118. package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
  119. package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
  120. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
  121. package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
  122. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
  123. package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
  124. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
  125. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
  126. package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
  127. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
  128. package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
  129. package/_modules/knowledge-engine/src/server.js +0 -166
  130. package/_modules/knowledge-engine/src/store.js +0 -267
  131. package/_modules/knowledge-engine/ui/app.css +0 -172
  132. package/_modules/knowledge-engine/ui/app.js +0 -318
  133. package/_modules/knowledge-engine/ui/index.html +0 -95
  134. package/_site/scripts/vendor-modules.js +0 -49
  135. package/vendor-manifest.json +0 -55
@@ -1,205 +0,0 @@
1
- const crypto = require('crypto');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const {
5
- DEFAULT_COMMIT_PROMPT_TEMPLATE,
6
- PROMPT_TEMPLATE_VERSION,
7
- normalizeAutomationConfig,
8
- renderTemplate,
9
- } = require('./automation-config');
10
-
11
- const REQUIREMENT_UNAVAILABLE = '需求上下文未记录。只能记录代码可以证明的变化,不得猜测业务目的。';
12
- const REQUIRED_SECTIONS = Object.freeze([
13
- ['userRequirement', '用户需求'],
14
- ['aiConversationEvidence', 'AI 对话证据'],
15
- ['commitMetadata', 'Commit 信息'],
16
- ['actualChanges', 'Commit 实际变更文件'],
17
- ['actualPatch', 'Commit 实际 Patch'],
18
- ['existingKnowledge', '现有相关知识'],
19
- ]);
20
-
21
- function sha256(value) {
22
- return `sha256:${crypto.createHash('sha256').update(value, 'utf8').digest('hex')}`;
23
- }
24
-
25
- function formatRequirements(records) {
26
- if (!Array.isArray(records) || records.length === 0) return REQUIREMENT_UNAVAILABLE;
27
- return records.map(record => [
28
- `- requirementId: ${record.id}`,
29
- ` client/session: ${record.client}/${record.sessionId}`,
30
- ` recordedAt: ${record.ts}`,
31
- ' requirement: |',
32
- ...String(record.requirement || '').split(/\r?\n/).map(line => ` ${line}`),
33
- ].join('\n')).join('\n');
34
- }
35
-
36
- function formatConversationUserTruth(snapshot) {
37
- if (!snapshot || !Array.isArray(snapshot.turns) || snapshot.turns.length === 0) return REQUIREMENT_UNAVAILABLE;
38
- const rendered = snapshot.turns.flatMap(turn => turn.userEvents.map(event => [
39
- `- turnId: ${turn.turnId}`,
40
- ` eventId: ${event.eventId}`,
41
- ` inputOrigin: ${event.inputOrigin || 'unknown'}`,
42
- ` contentHash: ${event.contentHash}`,
43
- ` source/session: ${turn.source}/${turn.sessionId || '(unavailable)'}`,
44
- ` binding: ${turn.bindingKind}`,
45
- ` capturedAt: ${event.capturedAt}`,
46
- ' userPrompt: |',
47
- ...String(event.content || '').split(/\r?\n/).map(line => ` ${line}`),
48
- ].join('\n'))).join('\n');
49
- return `inputOrigin marks who typed each frozen user event: only "human" is the owner speaking; "agent-delegation" is a delegated task order from another agent; "unknown" cannot be verified. Memory candidates may rely on "human" events only.\n${rendered}`;
50
- }
51
-
52
- function formatAssistantEvidence(snapshot) {
53
- if (!snapshot || !Array.isArray(snapshot.turns)) return '(no assistant conversation evidence was frozen)';
54
- const entries = snapshot.turns.flatMap(turn => turn.assistantEvents.map(event => [
55
- `- turnId: ${turn.turnId}`,
56
- ` eventId: ${event.eventId}`,
57
- ` capturedAt: ${event.capturedAt}`,
58
- ' assistantResponse: |',
59
- ...String(event.content || '').split(/\r?\n/).map(line => ` ${line}`),
60
- ].join('\n')));
61
- return entries.length ? entries.join('\n') : '(no assistant conversation evidence was frozen)';
62
- }
63
-
64
- function formatCommitMetadata(evidence) {
65
- return [
66
- `fullSha: ${evidence.commitSha}`,
67
- `parents: ${(evidence.parents || []).join(', ') || '(root commit)'}`,
68
- `author: ${evidence.author || ''}`,
69
- `date: ${evidence.date || ''}`,
70
- `subject: ${evidence.subject || ''}`,
71
- `branchAtScan: ${evidence.branch || '(detached/unavailable)'}`,
72
- `patchMode: ${evidence.patchMode}`,
73
- `patchHash: ${evidence.patchHash}`,
74
- `patchBytes: ${evidence.patchBytes}`,
75
- ].join('\n');
76
- }
77
-
78
- function formatChanges(evidence) {
79
- if (!evidence.files || evidence.files.length === 0) return '(no changed paths reported by Git)';
80
- return evidence.files.map(file => {
81
- const rename = file.oldPath ? ` ${file.oldPath} -> ${file.path}` : ` ${file.path}`;
82
- const stats = file.binary ? ' binary' : ` +${file.added == null ? '?' : file.added}/-${file.deleted == null ? '?' : file.deleted}`;
83
- return `- ${file.status}${rename}${stats}`;
84
- }).join('\n');
85
- }
86
-
87
- function formatPatch(evidence) {
88
- if (!evidence.patchChunked) return evidence.patch || '(empty patch)';
89
- const bundle = evidence.evidenceBundle || {};
90
- return [
91
- '[EXACT PATCH AVAILABLE AS READ-ONLY CHUNKS]',
92
- `fullPatchHash: ${evidence.patchHash}`,
93
- `fullPatchBytes: ${evidence.patchBytes}`,
94
- `patchManifestHash: ${bundle.manifestHash || '(unavailable)'}`,
95
- `patchManifestPath: ${bundle.manifestPath || '(unavailable)'}`,
96
- `chunkCount: ${bundle.chunkCount == null ? '(unavailable)' : bundle.chunkCount}`,
97
- 'Read patch-manifest.json, then Read exact patch chunks in manifest sequence. The chunks cover the full Git diff.',
98
- 'Do not read the source worktree and do not infer unread evidence.',
99
- ].join('\n');
100
- }
101
-
102
- function formatExistingKnowledge(existing) {
103
- if (!existing || !Array.isArray(existing.entries) || existing.entries.length === 0) {
104
- return '(no existing project knowledge was available)';
105
- }
106
- const sections = existing.entries.map(entry => `--- ${entry.path} (${entry.hash}) ---\n${entry.content}`);
107
- if (existing.omitted && existing.omitted.length) {
108
- sections.push(`[EXISTING KNOWLEDGE OMITTED: ${existing.omitted.join(', ')}]`);
109
- }
110
- return sections.join('\n\n');
111
- }
112
-
113
- function ensureRequiredSections(template, rendered, vars) {
114
- const missing = REQUIRED_SECTIONS.filter(([name]) => !new RegExp(`\\{\\{\\s*${name}\\s*\\}\\}`, 'i').test(template));
115
- if (!missing.length) return rendered;
116
- const footer = missing.map(([name, label]) => `${label}:\n${vars[name]}`).join('\n\n');
117
- return `${rendered.trimEnd()}\n\n${footer}`;
118
- }
119
-
120
- function renderCommitPrompt(input = {}) {
121
- const config = input.config || {};
122
- const evidence = input.evidence || {};
123
- const automation = normalizeAutomationConfig(config.automation);
124
- const template = automation.commitPromptTemplate || DEFAULT_COMMIT_PROMPT_TEMPLATE;
125
- const vars = {
126
- userRequirement: input.conversationSnapshot
127
- ? formatConversationUserTruth(input.conversationSnapshot)
128
- : formatRequirements(input.requirements),
129
- aiConversationEvidence: formatAssistantEvidence(input.conversationSnapshot),
130
- commitMetadata: formatCommitMetadata(evidence),
131
- actualChanges: formatChanges(evidence),
132
- actualPatch: formatPatch(evidence),
133
- existingKnowledge: formatExistingKnowledge(input.existingKnowledge),
134
- projectId: config.projectId || input.projectId || '',
135
- displayName: config.displayName || config.projectId || '',
136
- knowledgePath: config.knowledgePath || '',
137
- repoPath: config.repoPath || '',
138
- commitHash: evidence.commitSha || '',
139
- commitSubject: evidence.subject || '',
140
- commitAuthor: evidence.author || '',
141
- commitDate: evidence.date || '',
142
- branch: evidence.branch || '',
143
- changedFiles: formatChanges(evidence),
144
- diffSummary: formatPatch(evidence),
145
- };
146
- const rendered = ensureRequiredSections(template, renderTemplate(template, vars), vars).trimEnd() + '\n';
147
- return {
148
- prompt: rendered,
149
- promptHash: sha256(rendered),
150
- promptTemplateVersion: PROMPT_TEMPLATE_VERSION,
151
- promptLength: rendered.length,
152
- vars,
153
- };
154
- }
155
-
156
- class KnowledgeEvidenceReader {
157
- constructor(options = {}) {
158
- this.maxBytes = Number(options.maxBytes || 256 * 1024);
159
- this.maxFiles = Number(options.maxFiles || 24);
160
- }
161
-
162
- read(config) {
163
- const root = config && config.knowledgePath ? path.resolve(config.knowledgePath) : '';
164
- if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) return { entries: [], omitted: [] };
165
- const realRoot = fs.realpathSync(root);
166
- const files = [];
167
- const walk = current => {
168
- for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
169
- if (entry.isSymbolicLink()) continue;
170
- const absolute = path.join(current, entry.name);
171
- if (entry.isDirectory()) walk(absolute);
172
- else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) files.push(absolute);
173
- }
174
- };
175
- walk(root);
176
- let used = 0;
177
- const entries = [];
178
- const omitted = [];
179
- for (const file of files) {
180
- const realFile = fs.realpathSync(file);
181
- const relativeBoundary = path.relative(realRoot, realFile);
182
- if (relativeBoundary.startsWith('..') || path.isAbsolute(relativeBoundary)) continue;
183
- const relativePath = path.relative(root, file).replace(/\\/g, '/');
184
- const content = fs.readFileSync(file, 'utf8');
185
- const bytes = Buffer.byteLength(content, 'utf8');
186
- if (entries.length >= this.maxFiles || used + bytes > this.maxBytes) {
187
- omitted.push(relativePath);
188
- continue;
189
- }
190
- used += bytes;
191
- entries.push({ path: relativePath, hash: sha256(content), content });
192
- }
193
- return { entries, omitted, totalBytes: used, limitBytes: this.maxBytes, limitFiles: this.maxFiles };
194
- }
195
- }
196
-
197
- module.exports = {
198
- REQUIREMENT_UNAVAILABLE,
199
- KnowledgeEvidenceReader,
200
- formatRequirements,
201
- formatConversationUserTruth,
202
- formatAssistantEvidence,
203
- renderCommitPrompt,
204
- sha256,
205
- };
@@ -1,432 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const AtomicFile = require('./atomic-file');
4
- const {
5
- SCHEMAS,
6
- DomainError,
7
- createId,
8
- validateProjectId,
9
- validateTrigger,
10
- } = require('./contracts');
11
- const { CommitScanner, validateSha } = require('./scanner');
12
- const { ConversationStore } = require('./conversation-store');
13
- const { CommitConversationBinder, snapshotRequirementRecords } = require('./commit-conversation-binder');
14
- const { renderCommitPrompt, sha256 } = require('./commit-prompt');
15
- const { KnowledgeRetrievalService } = require('./knowledge-retrieval-service');
16
- const { manifestHash: calculateRetrievalManifestHash } = require('./knowledge-retrieval-service');
17
- const { sha256: knowledgeContentHash } = require('./content-hash');
18
- const { CommitProcessingLedger } = require('./commit-processing-ledger');
19
-
20
- const explicitQueues = new Map();
21
-
22
- function publicFailure(error, phase) {
23
- return {
24
- code: error && error.code || 'INVALID_ARGUMENT',
25
- message: String(error && error.message || 'Commit reconciliation failed.'),
26
- phase: error && error.phase || phase,
27
- retryable: error && error.retryable === true,
28
- ts: new Date().toISOString(),
29
- };
30
- }
31
-
32
- function validateClaim(claim, projectId, commitSha) {
33
- if (!claim || typeof claim !== 'object' || claim.schema !== SCHEMAS.commitClaim) {
34
- throw new DomainError('DATA_CORRUPT', 'Active commit claim is corrupt.', { status: 500 });
35
- }
36
- if (claim.projectId !== projectId || claim.commitSha !== commitSha) {
37
- throw new DomainError('DATA_CORRUPT', 'Active commit claim identity does not match the pending commit.', { status: 500 });
38
- }
39
- if (!Array.isArray(claim.requirementIds) || !claim.patchHash || !claim.promptHash || !claim.evidenceHash
40
- || !claim.evidenceManifestHash || !claim.retrievalManifestHash || !claim.knowledgePath || !claim.runId) {
41
- throw new DomainError('DATA_CORRUPT', 'Active commit claim is incomplete.', { status: 500 });
42
- }
43
- return claim;
44
- }
45
-
46
- function claimFingerprint(claim) {
47
- return sha256(JSON.stringify({
48
- schema: claim.schema,
49
- projectId: claim.projectId,
50
- commitSha: claim.commitSha,
51
- parents: claim.parents,
52
- requirementIds: claim.requirementIds,
53
- requirementBinding: claim.requirementBinding,
54
- conversationSnapshotHash: claim.conversationSnapshotHash || '',
55
- promptTemplateVersion: claim.promptTemplateVersion,
56
- promptHash: claim.promptHash,
57
- patchHash: claim.patchHash,
58
- evidenceHash: claim.evidenceHash,
59
- evidenceManifestHash: claim.evidenceManifestHash,
60
- retrievalManifestHash: claim.retrievalManifestHash,
61
- knowledgePath: claim.knowledgePath,
62
- }));
63
- }
64
-
65
- class CommitClaimStore {
66
- constructor(options = {}) {
67
- this.layout = options.layout;
68
- this.atomic = options.atomic || AtomicFile;
69
- }
70
-
71
- filePath(projectId, commitSha) {
72
- return this.layout.getRuntimePath('claims', validateProjectId(projectId), `${validateSha(commitSha)}.json`);
73
- }
74
-
75
- write(projectId, commitSha, snapshot) {
76
- const file = this.filePath(projectId, commitSha);
77
- this.atomic.writeJsonAtomic(file, { schema: 'commit-claim-snapshot/v1', ...snapshot });
78
- return file;
79
- }
80
-
81
- read(projectId, commitSha) {
82
- return this.atomic.readJsonStrict(this.filePath(projectId, commitSha), {
83
- category: 'commit-claim-snapshot',
84
- validate: snapshot => {
85
- if (!snapshot || snapshot.schema !== 'commit-claim-snapshot/v1' || snapshot.projectId !== projectId || snapshot.commitSha !== commitSha) {
86
- throw new DomainError('DATA_CORRUPT', 'Commit claim snapshot is corrupt.', { status: 500 });
87
- }
88
- return snapshot;
89
- },
90
- });
91
- }
92
-
93
- remove(projectId, commitSha) {
94
- const file = this.filePath(projectId, commitSha);
95
- try { fs.unlinkSync(file); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
96
- }
97
- }
98
-
99
- class CommitReconciler {
100
- constructor(options = {}) {
101
- this.layout = options.layout;
102
- this.registryStore = options.registryStore;
103
- this.projectStore = options.projectStore;
104
- this.scanner = options.scanner || new CommitScanner(options);
105
- this.conversationStore = options.conversationStore || new ConversationStore({
106
- layout: this.layout,
107
- projectStore: this.projectStore,
108
- logger: options.logger,
109
- });
110
- this.binder = options.conversationBinder || new CommitConversationBinder({
111
- layout: this.layout,
112
- projectStore: this.projectStore,
113
- conversationStore: this.conversationStore,
114
- logger: options.logger,
115
- });
116
- this.retrievalService = options.retrievalService || new KnowledgeRetrievalService({
117
- layout: this.layout,
118
- registryStore: this.registryStore,
119
- projectStore: this.projectStore,
120
- databaseProvider: options.databaseProvider,
121
- embedderProvider: options.embedderProvider,
122
- logger: options.logger,
123
- });
124
- this.claimStore = options.claimStore || new CommitClaimStore({ layout: this.layout });
125
- this.processingLedger = options.processingLedger || new CommitProcessingLedger({ layout: this.layout });
126
- this.claimProcessor = options.claimProcessor || null;
127
- this.logger = options.logger || null;
128
- this.batchSize = Math.max(1, Number(options.batchSize || 200));
129
- }
130
-
131
- async log(level, event, message, context) {
132
- if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
133
- }
134
-
135
- async reconcile(projectId, trigger, context = {}) {
136
- validateProjectId(projectId);
137
- validateTrigger(trigger);
138
- if (!context.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Commit reconciliation requires an explicit Hook commit SHA.');
139
- return this.processCommitEvent({ projectId, commitSha: context.commitSha, branch: context.branch || '', operationId: context.operationId || createId('op') });
140
- }
141
-
142
- async processCommitEvent({ projectId, commitSha, branch = '', operationId = '' } = {}) {
143
- validateProjectId(projectId);
144
- validateSha(commitSha);
145
- const existingQueue = explicitQueues.get(projectId) || { tail: Promise.resolve(), pending: new Map() };
146
- explicitQueues.set(projectId, existingQueue);
147
- if (existingQueue.pending.has(commitSha)) return existingQueue.pending.get(commitSha);
148
- const queued = existingQueue.tail.catch(() => {}).then(async () => {
149
- const completed = this.processingLedger.read(projectId, commitSha);
150
- if (completed) return { ok: true, projectId, commitSha, status: 'already-completed', processed: [], ledger: completed };
151
- const config = this.projectStore.readConfig(projectId);
152
- if (config.enabled === false) return { ok: true, projectId, commitSha, status: 'disabled', processed: [] };
153
- const result = await this.processCommit(projectId, 'git-hook', operationId || createId('op'), config, branch, commitSha);
154
- if (!result.ok) return { ok: false, projectId, commitSha, status: 'failed', processed: [result], error: result.error };
155
- const ledger = this.processingLedger.complete(projectId, commitSha, { runId: result.runId, claimFingerprint: result.claimFingerprint || '' });
156
- return { ok: true, projectId, commitSha, status: 'completed', processed: [result], ledger };
157
- });
158
- existingQueue.pending.set(commitSha, queued);
159
- existingQueue.tail = queued.catch(() => {});
160
- try { return await queued; }
161
- finally {
162
- existingQueue.pending.delete(commitSha);
163
- if (!existingQueue.pending.size) explicitQueues.delete(projectId);
164
- }
165
- }
166
-
167
- async prepareClaim(projectId, trigger, operationId, config, branch, commitSha) {
168
- const state = this.projectStore.readState(projectId);
169
- if (state.analysis.activeClaim) {
170
- const activeClaim = state.analysis.activeClaim;
171
- // A terminal failure must not turn a project into a permanent dead end.
172
- // We only release it while processing a *new, explicit* Hook SHA; the
173
- // failed SHA is never retried, scanned, or inferred from history.
174
- if (activeClaim.commitSha !== commitSha) {
175
- validateClaim(activeClaim, projectId, activeClaim.commitSha);
176
- const terminalFailure = activeClaim.phase === 'failed'
177
- && activeClaim.error
178
- && activeClaim.error.retryable !== true;
179
- if (!terminalFailure) {
180
- throw new DomainError('PROJECT_BUSY', 'Another unfinished commit claim already exists.', { status: 409, retryable: true });
181
- }
182
- await this.projectStore.updateState(projectId, draft => {
183
- const current = draft.analysis.activeClaim;
184
- if (!current || current.commitSha !== activeClaim.commitSha || current.fingerprint !== activeClaim.fingerprint) {
185
- throw new DomainError('PROJECT_BUSY', 'The active commit claim changed while preparing this Hook event.', { status: 409, retryable: true });
186
- }
187
- draft.analysis.activeClaim = null;
188
- draft.analysis.status = 'idle';
189
- draft.analysis.lastError = {
190
- code: 'FAILED_CLAIM_SUPERSEDED',
191
- message: 'A terminal failed claim was preserved for diagnostics and superseded by a newer explicit Hook commit.',
192
- retryable: false,
193
- ts: new Date().toISOString(),
194
- };
195
- });
196
- await this.log('warn', 'reconcile.failed_claim_superseded', 'A terminal failed claim was superseded by a newer explicit Hook commit.', {
197
- projectId,
198
- previousCommitSha: activeClaim.commitSha,
199
- commitSha,
200
- previousFailure: activeClaim.error,
201
- });
202
- return this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
203
- }
204
- const claim = validateClaim(activeClaim, projectId, commitSha);
205
- const snapshot = this.claimStore.read(projectId, commitSha);
206
- if (snapshot.claimFingerprint !== claimFingerprint(claim)
207
- || snapshot.evidence.patchHash !== claim.patchHash
208
- || snapshot.evidence.evidenceHash !== claim.evidenceHash
209
- || !snapshot.evidence.evidenceBundle
210
- || snapshot.evidence.evidenceBundle.manifestHash !== claim.evidenceManifestHash
211
- || !snapshot.existingKnowledge || snapshot.existingKnowledge.manifestHash !== claim.retrievalManifestHash
212
- || sha256(snapshot.prompt) !== claim.promptHash
213
- || (claim.conversationSnapshotHash && (!snapshot.conversationSnapshot || snapshot.conversationSnapshot.snapshotHash !== claim.conversationSnapshotHash))) {
214
- throw new DomainError('DATA_CORRUPT', 'Frozen commit claim snapshot does not match active state.', { status: 500 });
215
- }
216
- this.scanner.verifyEvidence(snapshot.evidence);
217
- const retrievalManifest = this.claimStore.atomic.readJsonStrict(snapshot.existingKnowledge.manifestPath, {
218
- category: 'knowledge-retrieval-manifest',
219
- validate: value => {
220
- if (!value || value.schema !== 'knowledge-retrieval-manifest/v1'
221
- || value.manifestHash !== claim.retrievalManifestHash
222
- || calculateRetrievalManifestHash(value) !== value.manifestHash) {
223
- throw new DomainError('DATA_CORRUPT', 'Frozen knowledge retrieval manifest is corrupt.', { status: 500 });
224
- }
225
- return value;
226
- },
227
- });
228
- const selectedById = new Map(retrievalManifest.selected.map(item => [`${item.spaceId}:${item.chunkId}`, item]));
229
- for (const entry of snapshot.existingKnowledge.entries || []) {
230
- const selected = selectedById.get(`${entry.spaceId || `project:${entry.projectId}`}:${entry.chunkId}`);
231
- if (!selected || knowledgeContentHash(entry.content) !== entry.hash || selected.contentHash !== entry.hash) {
232
- throw new DomainError('DATA_CORRUPT', 'Frozen authoritative Markdown context does not match its retrieval manifest.', { status: 500 });
233
- }
234
- }
235
- claim.attempt = Number(claim.attempt || 1) + 1;
236
- claim.phase = 'evidence.prepared';
237
- await this.projectStore.updateState(projectId, draft => {
238
- draft.analysis.activeClaim = claim;
239
- draft.analysis.status = 'evidence.prepared';
240
- draft.analysis.lastError = null;
241
- });
242
- return {
243
- claim,
244
- evidence: snapshot.evidence,
245
- prompt: snapshot.prompt,
246
- requirements: snapshot.requirements || [],
247
- conversationSnapshot: snapshot.conversationSnapshot || null,
248
- existingKnowledge: snapshot.existingKnowledge,
249
- retry: true,
250
- };
251
- }
252
-
253
- const runId = createId('run');
254
- const evidenceRoot = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'evidence');
255
- const evidence = await this.scanner.collectEvidence(config, commitSha, { branch, evidenceRoot });
256
- this.scanner.verifyEvidence(evidence);
257
- const conversationSnapshot = await this.binder.bind({ projectId, commitSha, branch });
258
- const requirements = snapshotRequirementRecords(conversationSnapshot);
259
- const existingKnowledge = await this.retrievalService.retrieveForCommit({
260
- projectId,
261
- conversationSnapshot,
262
- commitEvidence: evidence,
263
- });
264
- existingKnowledge.manifestPath = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'retrieval', 'manifest.json');
265
- this.claimStore.atomic.writeJsonAtomic(existingKnowledge.manifestPath, existingKnowledge.manifest);
266
- const rendered = renderCommitPrompt({ projectId, config, evidence, requirements, conversationSnapshot, existingKnowledge });
267
- const claim = {
268
- schema: SCHEMAS.commitClaim,
269
- projectId,
270
- commitSha,
271
- parents: evidence.parents,
272
- triggerFirstSeen: trigger,
273
- requirementIds: requirements.map(requirement => requirement.id),
274
- requirementBinding: conversationSnapshot.status,
275
- conversationSnapshotHash: conversationSnapshot.snapshotHash,
276
- conversationTurnIds: conversationSnapshot.turns.map(turn => turn.turnId),
277
- conversationEventIds: conversationSnapshot.turns.flatMap(turn => [...turn.userEvents, ...turn.assistantEvents].map(event => event.eventId)),
278
- promptTemplateVersion: rendered.promptTemplateVersion,
279
- promptHash: rendered.promptHash,
280
- patchHash: evidence.patchHash,
281
- evidenceHash: evidence.evidenceHash,
282
- evidenceManifestHash: evidence.evidenceBundle.manifestHash,
283
- retrievalManifestHash: existingKnowledge.manifestHash,
284
- knowledgePath: config.knowledgePath,
285
- runId,
286
- operationId,
287
- phase: 'evidence.prepared',
288
- attempt: 1,
289
- };
290
- claim.fingerprint = claimFingerprint(claim);
291
- this.claimStore.write(projectId, commitSha, {
292
- projectId,
293
- commitSha,
294
- claimFingerprint: claim.fingerprint,
295
- evidence,
296
- prompt: rendered.prompt,
297
- requirements,
298
- conversationSnapshot,
299
- existingKnowledge,
300
- createdAt: new Date().toISOString(),
301
- });
302
- try {
303
- await this.projectStore.updateState(projectId, draft => {
304
- if (draft.analysis.activeClaim) throw new DomainError('PROJECT_BUSY', 'Another active claim already exists.', { status: 409, retryable: true });
305
- draft.analysis.activeClaim = claim;
306
- draft.analysis.status = 'evidence.prepared';
307
- draft.analysis.lastError = null;
308
- });
309
- } catch (error) {
310
- this.claimStore.remove(projectId, commitSha);
311
- throw error;
312
- }
313
- await this.log('info', 'reconcile.claim_prepared', 'Commit evidence and claim prepared.', {
314
- projectId,
315
- operationId,
316
- runId: claim.runId,
317
- commitSha,
318
- phase: claim.phase,
319
- promptHash: claim.promptHash,
320
- patchHash: claim.patchHash,
321
- patchBytes: evidence.patchBytes,
322
- evidenceManifestHash: claim.evidenceManifestHash,
323
- evidenceChunkCount: evidence.evidenceBundle.chunkCount,
324
- evidenceChunkBytes: evidence.evidenceBundle.chunkBytes,
325
- retrievalManifestHash: claim.retrievalManifestHash,
326
- retrievalSelectedCount: existingKnowledge.entries.length,
327
- retrievalBytes: existingKnowledge.totalBytes,
328
- fileCount: evidence.files.length,
329
- requirementBinding: claim.requirementBinding,
330
- requirementCount: claim.requirementIds.length,
331
- });
332
- return { claim, evidence, prompt: rendered.prompt, requirements, conversationSnapshot, existingKnowledge, retry: false };
333
- }
334
-
335
- async processCommit(projectId, trigger, operationId, config, branch, commitSha) {
336
- let prepared;
337
- try {
338
- prepared = await this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
339
- // Runtime configuration is resolved by the headless analyzer. This
340
- // service must never load the shell's settings or persist credentials.
341
- if (!this.claimProcessor || typeof this.claimProcessor.processClaim !== 'function') {
342
- throw new DomainError('INVALID_ARGUMENT', 'Knowledge claim processor is unavailable.', { status: 503, retryable: true });
343
- }
344
- const result = await this.claimProcessor.processClaim({
345
- projectId,
346
- config,
347
- claim: prepared.claim,
348
- evidence: prepared.evidence,
349
- prompt: prepared.prompt,
350
- requirements: prepared.requirements,
351
- conversationSnapshot: prepared.conversationSnapshot,
352
- existingKnowledge: prepared.existingKnowledge,
353
- operationId,
354
- });
355
- if (!result || result.stateAdvanced !== true) {
356
- throw new DomainError('INVALID_ARGUMENT', 'Knowledge promotion did not prove state advancement.', { status: 500, retryable: true });
357
- }
358
- const advanced = this.projectStore.readState(projectId);
359
- if (advanced.lastAnalyzedCommit !== commitSha || advanced.analysis.activeClaim) {
360
- throw new DomainError('DATA_CORRUPT', 'Claim processor reported success without atomically advancing project state.', { status: 500 });
361
- }
362
- this.claimStore.remove(projectId, commitSha);
363
- await this.log('info', 'reconcile.commit_completed', 'Commit knowledge was promoted and state advanced.', {
364
- projectId,
365
- operationId,
366
- runId: prepared.claim.runId,
367
- commitSha,
368
- phase: 'state.advanced',
369
- });
370
- return { ok: true, commitSha, runId: prepared.claim.runId, claimFingerprint: prepared.claim.fingerprint, retry: prepared.retry };
371
- } catch (error) {
372
- const failure = publicFailure(error, prepared && prepared.claim && prepared.claim.phase || 'evidence.prepared');
373
- let stateUpdateError = null;
374
- try {
375
- await this.projectStore.updateState(projectId, draft => {
376
- const active = draft.analysis.activeClaim;
377
- if (active && active.commitSha === commitSha) {
378
- active.phase = 'failed';
379
- active.error = failure;
380
- }
381
- draft.analysis.status = 'failed';
382
- draft.analysis.lastError = failure;
383
- });
384
- } catch (updateError) {
385
- stateUpdateError = updateError;
386
- }
387
- await this.log('error', 'reconcile.commit_failed', 'Commit reconciliation stopped at the first failed commit.', {
388
- projectId,
389
- operationId,
390
- runId: prepared && prepared.claim && prepared.claim.runId,
391
- commitSha,
392
- phase: failure.phase,
393
- error,
394
- context: stateUpdateError ? { failureStateWriteError: stateUpdateError } : {},
395
- });
396
- return { ok: false, commitSha, error: failure, retry: prepared && prepared.retry || false };
397
- }
398
- }
399
-
400
- async markDiverged(projectId, operationId, message, processed = []) {
401
- const error = new DomainError('HISTORY_DIVERGED', message || 'Git history diverged from the stored baseline.', { status: 409 });
402
- await this.projectStore.updateState(projectId, state => {
403
- state.analysis.status = 'history-diverged';
404
- state.analysis.lastError = publicFailure(error, 'history-diverged');
405
- });
406
- await this.log('error', 'reconcile.history_diverged', 'Git history diverged; reconciliation stopped without moving pointers.', { projectId, operationId, phase: 'history-diverged', error });
407
- return { ok: false, status: 'history-diverged', processed, error: publicFailure(error, 'history-diverged') };
408
- }
409
-
410
- async failWithoutClaim(projectId, operationId, error, phase, processed = []) {
411
- await this.projectStore.updateState(projectId, state => {
412
- state.analysis.status = 'failed';
413
- state.analysis.lastError = publicFailure(error, phase);
414
- });
415
- await this.log('error', 'reconcile.failed', 'Reconciliation failed before claim processing.', { projectId, operationId, phase, error });
416
- return { ok: false, status: 'failed', processed, error: publicFailure(error, phase) };
417
- }
418
- }
419
-
420
- async function reconcileProjectCommits(projectId, trigger, deps = {}) {
421
- const reconciler = deps.reconciler instanceof CommitReconciler ? deps.reconciler : new CommitReconciler(deps);
422
- return reconciler.reconcile(projectId, trigger, { operationId: deps.operationId || '', commitSha: deps.commitSha || '', branch: deps.branch || '' });
423
- }
424
-
425
- module.exports = {
426
- CommitClaimStore,
427
- CommitReconciler,
428
- CommitProcessingLedger,
429
- claimFingerprint,
430
- reconcileProjectCommits,
431
- validateClaim,
432
- };
@@ -1,4 +0,0 @@
1
- 'use strict';
2
- const crypto = require('node:crypto');
3
- function sha256(value) { return crypto.createHash('sha256').update(String(value || ''), 'utf8').digest('hex'); }
4
- module.exports = { sha256 };