@sanqianx/project-knowledge 5.1.3 → 5.1.5

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +13 -0
  3. package/_site/_test/agent-capture-mcp-ui-test.js +21 -7
  4. package/_site/_test/agent-capture-ui-test.js +4 -3
  5. package/_site/_test/bin-cli-test.js +3 -2
  6. package/_site/_test/capture-hook-dedup-test.js +41 -1
  7. package/_site/_test/cli-version-report-test.js +22 -0
  8. package/_site/_test/codex-notify-upgrade-test.js +7 -0
  9. package/_site/_test/fixtures/integration-busy-worker.cjs +11 -3
  10. package/_site/_test/helpers/parallel-memory-shell.js +13 -2
  11. package/_site/_test/hook-relocation-rebind-test.js +120 -0
  12. package/_site/_test/integration-auto-repair-test.js +3 -1
  13. package/_site/_test/integration-intent-test.js +6 -2
  14. package/_site/_test/integration-runtime-binding-test.js +4 -4
  15. package/_site/_test/integration-status-scan-test.js +138 -7
  16. package/_site/_test/legacy-relocation-recovery-test.js +258 -0
  17. package/_site/_test/parallel-retrieval-followup-corpus-test.js +6 -4
  18. package/_site/_test/project-team-ui-test.js +124 -0
  19. package/_site/_test/recovery-label-contract-test.js +45 -0
  20. package/_site/lib/capture-hook-config.js +25 -9
  21. package/_site/lib/claude-plugin-status.js +60 -0
  22. package/_site/lib/commit-prompt.js +205 -202
  23. package/_site/lib/commit-reconciler.js +551 -444
  24. package/_site/lib/contracts.js +1 -0
  25. package/_site/lib/evidence-bundle.js +32 -5
  26. package/_site/lib/integration-auto-repair.js +3 -2
  27. package/_site/lib/integration-installer.js +153 -71
  28. package/_site/lib/integration-intent.js +12 -5
  29. package/_site/lib/integration-status-scan.js +101 -41
  30. package/_site/lib/integration-status-worker.js +4 -2
  31. package/_site/lib/knowledge-promotion.js +547 -435
  32. package/_site/lib/module-bridge.js +1 -1
  33. package/_site/lib/scanner.js +5 -3
  34. package/_site/lib/server-app.js +34 -7
  35. package/_site/scripts/refresh-runtime-manifest.js +1 -1
  36. package/bin/project-knowledge.js +51 -1
  37. package/module-runtime-manifest.json +84 -84
  38. package/package.json +6 -6
  39. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  40. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  41. package/plugins/project-knowledge/.mcp.json +1 -1
  42. package/ui/product.css +1 -0
  43. package/ui/product.js +125 -30
@@ -1,444 +1,551 @@
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 { StorageLayout } = require('./storage-layout');
12
- const { ProjectRegistryStore } = require('./project-registry-store');
13
- const { ProjectStore } = require('./project-store');
14
- const { CommitScanner, validateSha } = require('./scanner');
15
- const { ConversationStore } = require('./conversation-store');
16
- const { CommitConversationBinder, snapshotRequirementRecords } = require('./commit-conversation-binder');
17
- const { renderCommitPrompt, sha256 } = require('./commit-prompt');
18
- const { KnowledgeRetrievalService } = require('./knowledge-retrieval-service');
19
- const { manifestHash: calculateRetrievalManifestHash } = require('./knowledge-retrieval-service');
20
- const { sha256: knowledgeContentHash } = require('./knowledge-schema');
21
- const { resolveEffectiveAiProfile } = require('./ai-profile-resolver');
22
- const { CommitProcessingLedger } = require('./commit-processing-ledger');
23
-
24
- const explicitQueues = new Map();
25
-
26
- function publicFailure(error, phase) {
27
- return {
28
- code: error && error.code || 'INVALID_ARGUMENT',
29
- message: String(error && error.message || 'Commit reconciliation failed.'),
30
- phase,
31
- retryable: error && error.retryable === true,
32
- ts: new Date().toISOString(),
33
- };
34
- }
35
-
36
- function validateClaim(claim, projectId, commitSha) {
37
- if (!claim || typeof claim !== 'object' || claim.schema !== SCHEMAS.commitClaim) {
38
- throw new DomainError('DATA_CORRUPT', 'Active commit claim is corrupt.', { status: 500 });
39
- }
40
- if (claim.projectId !== projectId || claim.commitSha !== commitSha) {
41
- throw new DomainError('DATA_CORRUPT', 'Active commit claim identity does not match the pending commit.', { status: 500 });
42
- }
43
- if (!Array.isArray(claim.requirementIds) || !claim.patchHash || !claim.promptHash || !claim.evidenceHash
44
- || !claim.evidenceManifestHash || !claim.retrievalManifestHash || !claim.knowledgePath || !claim.runId) {
45
- throw new DomainError('DATA_CORRUPT', 'Active commit claim is incomplete.', { status: 500 });
46
- }
47
- return claim;
48
- }
49
-
50
- function claimFingerprint(claim) {
51
- return sha256(JSON.stringify({
52
- schema: claim.schema,
53
- projectId: claim.projectId,
54
- commitSha: claim.commitSha,
55
- parents: claim.parents,
56
- requirementIds: claim.requirementIds,
57
- requirementBinding: claim.requirementBinding,
58
- conversationSnapshotHash: claim.conversationSnapshotHash || '',
59
- promptTemplateVersion: claim.promptTemplateVersion,
60
- promptHash: claim.promptHash,
61
- patchHash: claim.patchHash,
62
- evidenceHash: claim.evidenceHash,
63
- evidenceManifestHash: claim.evidenceManifestHash,
64
- retrievalManifestHash: claim.retrievalManifestHash,
65
- knowledgePath: claim.knowledgePath,
66
- }));
67
- }
68
-
69
- class CommitClaimStore {
70
- constructor(options = {}) {
71
- this.layout = options.layout || new StorageLayout(options);
72
- this.atomic = options.atomic || AtomicFile;
73
- }
74
-
75
- filePath(projectId, commitSha) {
76
- return this.layout.getRuntimePath('claims', validateProjectId(projectId), `${validateSha(commitSha)}.json`);
77
- }
78
-
79
- write(projectId, commitSha, snapshot) {
80
- const file = this.filePath(projectId, commitSha);
81
- this.atomic.writeJsonAtomic(file, { schema: 'commit-claim-snapshot/v1', ...snapshot });
82
- return file;
83
- }
84
-
85
- read(projectId, commitSha) {
86
- return this.atomic.readJsonStrict(this.filePath(projectId, commitSha), {
87
- category: 'commit-claim-snapshot',
88
- validate: snapshot => {
89
- if (!snapshot || snapshot.schema !== 'commit-claim-snapshot/v1' || snapshot.projectId !== projectId || snapshot.commitSha !== commitSha) {
90
- throw new DomainError('DATA_CORRUPT', 'Commit claim snapshot is corrupt.', { status: 500 });
91
- }
92
- return snapshot;
93
- },
94
- });
95
- }
96
-
97
- remove(projectId, commitSha) {
98
- const file = this.filePath(projectId, commitSha);
99
- try { fs.unlinkSync(file); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
100
- }
101
- }
102
-
103
- class CommitReconciler {
104
- constructor(options = {}) {
105
- this.layout = options.layout || new StorageLayout(options);
106
- this.registryStore = options.registryStore || new ProjectRegistryStore({ layout: this.layout });
107
- this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
108
- this.scanner = options.scanner || new CommitScanner(options);
109
- this.conversationStore = options.conversationStore || new ConversationStore({
110
- layout: this.layout,
111
- projectStore: this.projectStore,
112
- logger: options.logger,
113
- });
114
- this.binder = options.conversationBinder || new CommitConversationBinder({
115
- layout: this.layout,
116
- projectStore: this.projectStore,
117
- conversationStore: this.conversationStore,
118
- logger: options.logger,
119
- });
120
- this.retrievalService = options.retrievalService || new KnowledgeRetrievalService({
121
- layout: this.layout,
122
- registryStore: this.registryStore,
123
- projectStore: this.projectStore,
124
- databaseProvider: options.databaseProvider,
125
- embedderProvider: options.embedderProvider,
126
- logger: options.logger,
127
- });
128
- this.claimStore = options.claimStore || new CommitClaimStore({ layout: this.layout });
129
- this.processingLedger = options.processingLedger || new CommitProcessingLedger({ layout: this.layout });
130
- this.claimProcessor = options.claimProcessor || null;
131
- this.logger = options.logger || null;
132
- this.settingsStore = options.settingsStore || null;
133
- this.batchSize = Math.max(1, Number(options.batchSize || 200));
134
- this.requireAiProfile = options.requireAiProfile !== false;
135
- }
136
-
137
- async log(level, event, message, context) {
138
- if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
139
- }
140
-
141
- async reconcile(projectId, trigger, context = {}) {
142
- validateProjectId(projectId);
143
- validateTrigger(trigger);
144
- if (!context.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Commit reconciliation requires an explicit Hook commit SHA.');
145
- return this.processCommitEvent({ projectId, commitSha: context.commitSha, branch: context.branch || '', operationId: context.operationId || createId('op') });
146
- }
147
-
148
- async processCommitEvent({ projectId, commitSha, branch = '', operationId = '' } = {}) {
149
- validateProjectId(projectId);
150
- validateSha(commitSha);
151
- const existingQueue = explicitQueues.get(projectId) || { tail: Promise.resolve(), pending: new Map() };
152
- explicitQueues.set(projectId, existingQueue);
153
- if (existingQueue.pending.has(commitSha)) return existingQueue.pending.get(commitSha);
154
- const queued = existingQueue.tail.catch(() => {}).then(async () => {
155
- const completed = this.processingLedger.read(projectId, commitSha);
156
- if (completed) return { ok: true, projectId, commitSha, status: 'already-completed', processed: [], ledger: completed };
157
- const config = this.projectStore.readConfig(projectId);
158
- if (config.enabled === false) return { ok: true, projectId, commitSha, status: 'disabled', processed: [] };
159
- const result = await this.processCommit(projectId, 'git-hook', operationId || createId('op'), config, branch, commitSha);
160
- if (!result.ok) return { ok: false, projectId, commitSha, status: 'failed', processed: [result], error: result.error };
161
- const ledger = this.processingLedger.complete(projectId, commitSha, { runId: result.runId, claimFingerprint: result.claimFingerprint || '' });
162
- return { ok: true, projectId, commitSha, status: 'completed', processed: [result], ledger };
163
- });
164
- existingQueue.pending.set(commitSha, queued);
165
- existingQueue.tail = queued.catch(() => {});
166
- try { return await queued; }
167
- finally {
168
- existingQueue.pending.delete(commitSha);
169
- if (!existingQueue.pending.size) explicitQueues.delete(projectId);
170
- }
171
- }
172
-
173
- async prepareClaim(projectId, trigger, operationId, config, branch, commitSha) {
174
- const state = this.projectStore.readState(projectId);
175
- if (state.analysis.activeClaim) {
176
- const activeClaim = state.analysis.activeClaim;
177
- // A terminal failure must not turn a project into a permanent dead end.
178
- // We only release it while processing a *new, explicit* Hook SHA; the
179
- // failed SHA is never retried, scanned, or inferred from history.
180
- if (activeClaim.commitSha !== commitSha) {
181
- validateClaim(activeClaim, projectId, activeClaim.commitSha);
182
- const terminalFailure = activeClaim.phase === 'failed'
183
- && activeClaim.error
184
- && activeClaim.error.retryable !== true;
185
- if (!terminalFailure) {
186
- throw new DomainError('PROJECT_BUSY', 'Another unfinished commit claim already exists.', { status: 409, retryable: true });
187
- }
188
- await this.projectStore.updateState(projectId, draft => {
189
- const current = draft.analysis.activeClaim;
190
- if (!current || current.commitSha !== activeClaim.commitSha || current.fingerprint !== activeClaim.fingerprint) {
191
- throw new DomainError('PROJECT_BUSY', 'The active commit claim changed while preparing this Hook event.', { status: 409, retryable: true });
192
- }
193
- draft.analysis.activeClaim = null;
194
- draft.analysis.status = 'idle';
195
- draft.analysis.lastError = {
196
- code: 'FAILED_CLAIM_SUPERSEDED',
197
- message: 'A terminal failed claim was preserved for diagnostics and superseded by a newer explicit Hook commit.',
198
- retryable: false,
199
- ts: new Date().toISOString(),
200
- };
201
- });
202
- await this.log('warn', 'reconcile.failed_claim_superseded', 'A terminal failed claim was superseded by a newer explicit Hook commit.', {
203
- projectId,
204
- previousCommitSha: activeClaim.commitSha,
205
- commitSha,
206
- previousFailure: activeClaim.error,
207
- });
208
- return this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
209
- }
210
- const claim = validateClaim(activeClaim, projectId, commitSha);
211
- const snapshot = this.claimStore.read(projectId, commitSha);
212
- if (snapshot.claimFingerprint !== claimFingerprint(claim)
213
- || snapshot.evidence.patchHash !== claim.patchHash
214
- || snapshot.evidence.evidenceHash !== claim.evidenceHash
215
- || !snapshot.evidence.evidenceBundle
216
- || snapshot.evidence.evidenceBundle.manifestHash !== claim.evidenceManifestHash
217
- || !snapshot.existingKnowledge || snapshot.existingKnowledge.manifestHash !== claim.retrievalManifestHash
218
- || sha256(snapshot.prompt) !== claim.promptHash
219
- || (claim.conversationSnapshotHash && (!snapshot.conversationSnapshot || snapshot.conversationSnapshot.snapshotHash !== claim.conversationSnapshotHash))) {
220
- throw new DomainError('DATA_CORRUPT', 'Frozen commit claim snapshot does not match active state.', { status: 500 });
221
- }
222
- this.scanner.verifyEvidence(snapshot.evidence);
223
- const retrievalManifest = this.claimStore.atomic.readJsonStrict(snapshot.existingKnowledge.manifestPath, {
224
- category: 'knowledge-retrieval-manifest',
225
- validate: value => {
226
- if (!value || value.schema !== 'knowledge-retrieval-manifest/v1'
227
- || value.manifestHash !== claim.retrievalManifestHash
228
- || calculateRetrievalManifestHash(value) !== value.manifestHash) {
229
- throw new DomainError('DATA_CORRUPT', 'Frozen knowledge retrieval manifest is corrupt.', { status: 500 });
230
- }
231
- return value;
232
- },
233
- });
234
- const selectedById = new Map(retrievalManifest.selected.map(item => [`${item.spaceId}:${item.chunkId}`, item]));
235
- for (const entry of snapshot.existingKnowledge.entries || []) {
236
- const selected = selectedById.get(`${entry.projectId === projectId ? `project:${projectId}` : `project:${entry.projectId}`}:${entry.chunkId}`);
237
- if (!selected || knowledgeContentHash(entry.content) !== entry.hash || selected.contentHash !== entry.hash) {
238
- throw new DomainError('DATA_CORRUPT', 'Frozen authoritative Markdown context does not match its retrieval manifest.', { status: 500 });
239
- }
240
- }
241
- claim.attempt = Number(claim.attempt || 1) + 1;
242
- claim.phase = 'evidence.prepared';
243
- await this.projectStore.updateState(projectId, draft => {
244
- draft.analysis.activeClaim = claim;
245
- draft.analysis.status = 'evidence.prepared';
246
- draft.analysis.lastError = null;
247
- });
248
- return {
249
- claim,
250
- evidence: snapshot.evidence,
251
- prompt: snapshot.prompt,
252
- requirements: snapshot.requirements || [],
253
- conversationSnapshot: snapshot.conversationSnapshot || null,
254
- existingKnowledge: snapshot.existingKnowledge,
255
- retry: true,
256
- };
257
- }
258
-
259
- const runId = createId('run');
260
- const evidenceRoot = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'evidence');
261
- const evidence = await this.scanner.collectEvidence(config, commitSha, { branch, evidenceRoot });
262
- this.scanner.verifyEvidence(evidence);
263
- const conversationSnapshot = await this.binder.bind({ projectId, commitSha, branch });
264
- const requirements = snapshotRequirementRecords(conversationSnapshot);
265
- const existingKnowledge = await this.retrievalService.retrieveForCommit({
266
- projectId,
267
- conversationSnapshot,
268
- commitEvidence: evidence,
269
- });
270
- existingKnowledge.manifestPath = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'retrieval', 'manifest.json');
271
- this.claimStore.atomic.writeJsonAtomic(existingKnowledge.manifestPath, existingKnowledge.manifest);
272
- const rendered = renderCommitPrompt({ projectId, config, evidence, requirements, conversationSnapshot, existingKnowledge });
273
- const claim = {
274
- schema: SCHEMAS.commitClaim,
275
- projectId,
276
- commitSha,
277
- parents: evidence.parents,
278
- triggerFirstSeen: trigger,
279
- requirementIds: requirements.map(requirement => requirement.id),
280
- requirementBinding: conversationSnapshot.status,
281
- conversationSnapshotHash: conversationSnapshot.snapshotHash,
282
- conversationTurnIds: conversationSnapshot.turns.map(turn => turn.turnId),
283
- conversationEventIds: conversationSnapshot.turns.flatMap(turn => [...turn.userEvents, ...turn.assistantEvents].map(event => event.eventId)),
284
- promptTemplateVersion: rendered.promptTemplateVersion,
285
- promptHash: rendered.promptHash,
286
- patchHash: evidence.patchHash,
287
- evidenceHash: evidence.evidenceHash,
288
- evidenceManifestHash: evidence.evidenceBundle.manifestHash,
289
- retrievalManifestHash: existingKnowledge.manifestHash,
290
- knowledgePath: config.knowledgePath,
291
- runId,
292
- operationId,
293
- phase: 'evidence.prepared',
294
- attempt: 1,
295
- };
296
- claim.fingerprint = claimFingerprint(claim);
297
- this.claimStore.write(projectId, commitSha, {
298
- projectId,
299
- commitSha,
300
- claimFingerprint: claim.fingerprint,
301
- evidence,
302
- prompt: rendered.prompt,
303
- requirements,
304
- conversationSnapshot,
305
- existingKnowledge,
306
- createdAt: new Date().toISOString(),
307
- });
308
- try {
309
- await this.projectStore.updateState(projectId, draft => {
310
- if (draft.analysis.activeClaim) throw new DomainError('PROJECT_BUSY', 'Another active claim already exists.', { status: 409, retryable: true });
311
- draft.analysis.activeClaim = claim;
312
- draft.analysis.status = 'evidence.prepared';
313
- draft.analysis.lastError = null;
314
- });
315
- } catch (error) {
316
- this.claimStore.remove(projectId, commitSha);
317
- throw error;
318
- }
319
- await this.log('info', 'reconcile.claim_prepared', 'Commit evidence and claim prepared.', {
320
- projectId,
321
- operationId,
322
- runId: claim.runId,
323
- commitSha,
324
- phase: claim.phase,
325
- promptHash: claim.promptHash,
326
- patchHash: claim.patchHash,
327
- patchBytes: evidence.patchBytes,
328
- evidenceManifestHash: claim.evidenceManifestHash,
329
- evidenceChunkCount: evidence.evidenceBundle.chunkCount,
330
- evidenceChunkBytes: evidence.evidenceBundle.chunkBytes,
331
- retrievalManifestHash: claim.retrievalManifestHash,
332
- retrievalSelectedCount: existingKnowledge.entries.length,
333
- retrievalBytes: existingKnowledge.totalBytes,
334
- fileCount: evidence.files.length,
335
- requirementBinding: claim.requirementBinding,
336
- requirementCount: claim.requirementIds.length,
337
- });
338
- return { claim, evidence, prompt: rendered.prompt, requirements, conversationSnapshot, existingKnowledge, retry: false };
339
- }
340
-
341
- async processCommit(projectId, trigger, operationId, config, branch, commitSha) {
342
- let prepared;
343
- try {
344
- prepared = await this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
345
- if (this.requireAiProfile) {
346
- // Use the shared effective-profile resolver so a project with no explicit
347
- // aiProfileId can still analyze via the global default or first-usable
348
- // profile. The resolver throws AI_PROFILE_REQUIRED if nothing usable
349
- // exists, which becomes a clear actionable error rather than a silent
350
- // null deref.
351
- resolveEffectiveAiProfile(this.settingsStore ? this.settingsStore.read() : null, config);
352
- }
353
- if (!this.claimProcessor || typeof this.claimProcessor.processClaim !== 'function') {
354
- throw new DomainError('INVALID_ARGUMENT', 'Knowledge claim processor is unavailable.', { status: 503, retryable: true });
355
- }
356
- const result = await this.claimProcessor.processClaim({
357
- projectId,
358
- config,
359
- claim: prepared.claim,
360
- evidence: prepared.evidence,
361
- prompt: prepared.prompt,
362
- requirements: prepared.requirements,
363
- conversationSnapshot: prepared.conversationSnapshot,
364
- existingKnowledge: prepared.existingKnowledge,
365
- operationId,
366
- });
367
- if (!result || result.stateAdvanced !== true) {
368
- throw new DomainError('INVALID_ARGUMENT', 'Knowledge promotion did not prove state advancement.', { status: 500, retryable: true });
369
- }
370
- const advanced = this.projectStore.readState(projectId);
371
- if (advanced.lastAnalyzedCommit !== commitSha || advanced.analysis.activeClaim) {
372
- throw new DomainError('DATA_CORRUPT', 'Claim processor reported success without atomically advancing project state.', { status: 500 });
373
- }
374
- this.claimStore.remove(projectId, commitSha);
375
- await this.log('info', 'reconcile.commit_completed', 'Commit knowledge was promoted and state advanced.', {
376
- projectId,
377
- operationId,
378
- runId: prepared.claim.runId,
379
- commitSha,
380
- phase: 'state.advanced',
381
- });
382
- return { ok: true, commitSha, runId: prepared.claim.runId, claimFingerprint: prepared.claim.fingerprint, retry: prepared.retry };
383
- } catch (error) {
384
- const failure = publicFailure(error, prepared && prepared.claim && prepared.claim.phase || 'evidence.prepared');
385
- let stateUpdateError = null;
386
- try {
387
- await this.projectStore.updateState(projectId, draft => {
388
- const active = draft.analysis.activeClaim;
389
- if (active && active.commitSha === commitSha) {
390
- active.phase = 'failed';
391
- active.error = failure;
392
- }
393
- draft.analysis.status = 'failed';
394
- draft.analysis.lastError = failure;
395
- });
396
- } catch (updateError) {
397
- stateUpdateError = updateError;
398
- }
399
- await this.log('error', 'reconcile.commit_failed', 'Commit reconciliation stopped at the first failed commit.', {
400
- projectId,
401
- operationId,
402
- runId: prepared && prepared.claim && prepared.claim.runId,
403
- commitSha,
404
- phase: failure.phase,
405
- error,
406
- context: stateUpdateError ? { failureStateWriteError: stateUpdateError } : {},
407
- });
408
- return { ok: false, commitSha, error: failure, retry: prepared && prepared.retry || false };
409
- }
410
- }
411
-
412
- async markDiverged(projectId, operationId, message, processed = []) {
413
- const error = new DomainError('HISTORY_DIVERGED', message || 'Git history diverged from the stored baseline.', { status: 409 });
414
- await this.projectStore.updateState(projectId, state => {
415
- state.analysis.status = 'history-diverged';
416
- state.analysis.lastError = publicFailure(error, 'history-diverged');
417
- });
418
- await this.log('error', 'reconcile.history_diverged', 'Git history diverged; reconciliation stopped without moving pointers.', { projectId, operationId, phase: 'history-diverged', error });
419
- return { ok: false, status: 'history-diverged', processed, error: publicFailure(error, 'history-diverged') };
420
- }
421
-
422
- async failWithoutClaim(projectId, operationId, error, phase, processed = []) {
423
- await this.projectStore.updateState(projectId, state => {
424
- state.analysis.status = 'failed';
425
- state.analysis.lastError = publicFailure(error, phase);
426
- });
427
- await this.log('error', 'reconcile.failed', 'Reconciliation failed before claim processing.', { projectId, operationId, phase, error });
428
- return { ok: false, status: 'failed', processed, error: publicFailure(error, phase) };
429
- }
430
- }
431
-
432
- async function reconcileProjectCommits(projectId, trigger, deps = {}) {
433
- const reconciler = deps.reconciler instanceof CommitReconciler ? deps.reconciler : new CommitReconciler(deps);
434
- return reconciler.reconcile(projectId, trigger, { operationId: deps.operationId || '', commitSha: deps.commitSha || '', branch: deps.branch || '' });
435
- }
436
-
437
- module.exports = {
438
- CommitClaimStore,
439
- CommitReconciler,
440
- CommitProcessingLedger,
441
- claimFingerprint,
442
- reconcileProjectCommits,
443
- validateClaim,
444
- };
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 { StorageLayout } = require('./storage-layout');
12
+ const { ProjectRegistryStore } = require('./project-registry-store');
13
+ const { ProjectStore } = require('./project-store');
14
+ const { CommitScanner, validateSha } = require('./scanner');
15
+ const { ConversationStore } = require('./conversation-store');
16
+ const { CommitConversationBinder, snapshotRequirementRecords } = require('./commit-conversation-binder');
17
+ const { renderCommitPrompt, sha256 } = require('./commit-prompt');
18
+ const { KnowledgeRetrievalService } = require('./knowledge-retrieval-service');
19
+ const { manifestHash: calculateRetrievalManifestHash } = require('./knowledge-retrieval-service');
20
+ const { sha256: knowledgeContentHash } = require('./knowledge-schema');
21
+ const { resolveEffectiveAiProfile } = require('./ai-profile-resolver');
22
+ const { CommitProcessingLedger } = require('./commit-processing-ledger');
23
+
24
+ const explicitQueues = new Map();
25
+
26
+ const SNAPSHOT_SCHEMA_V1 = 'commit-claim-snapshot/v1';
27
+ const SNAPSHOT_SCHEMA_V2 = 'commit-claim-snapshot/v2';
28
+ const SNAPSHOT_SCHEMAS = [SNAPSHOT_SCHEMA_V1, SNAPSHOT_SCHEMA_V2];
29
+ // Frozen inputs live under <dataDir>/runtime/runs/<projectId>/<runId>/input and
30
+ // are ALWAYS re-derived from the running layout: a renamed or relocated data
31
+ // directory keeps every claim working without rewriting historical snapshots.
32
+ const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
33
+
34
+ function validateRunIdSegment(runId) {
35
+ const value = String(runId || '');
36
+ if (!RUN_ID_PATTERN.test(value)) {
37
+ throw new DomainError('DATA_CORRUPT', 'Claim run id is invalid for frozen evidence location.', { status: 500 });
38
+ }
39
+ return value;
40
+ }
41
+
42
+ function publicFailure(error, phase) {
43
+ const failure = {
44
+ code: error && error.code || 'INVALID_ARGUMENT',
45
+ message: String(error && error.message || 'Commit reconciliation failed.'),
46
+ phase,
47
+ retryable: error && error.retryable === true,
48
+ ts: new Date().toISOString(),
49
+ };
50
+ // Evidence failures must surface the concrete resource and reason so the UI
51
+ // can point at what is missing instead of a generic retry loop.
52
+ if (error && error.details && typeof error.details === 'object') failure.details = error.details;
53
+ return failure;
54
+ }
55
+
56
+ function validateClaim(claim, projectId, commitSha) {
57
+ if (!claim || typeof claim !== 'object' || claim.schema !== SCHEMAS.commitClaim) {
58
+ throw new DomainError('DATA_CORRUPT', 'Active commit claim is corrupt.', { status: 500 });
59
+ }
60
+ if (claim.projectId !== projectId || claim.commitSha !== commitSha) {
61
+ throw new DomainError('DATA_CORRUPT', 'Active commit claim identity does not match the pending commit.', { status: 500 });
62
+ }
63
+ if (!Array.isArray(claim.requirementIds) || !claim.patchHash || !claim.promptHash || !claim.evidenceHash
64
+ || !claim.evidenceManifestHash || !claim.retrievalManifestHash || !claim.knowledgePath || !claim.runId) {
65
+ throw new DomainError('DATA_CORRUPT', 'Active commit claim is incomplete.', { status: 500 });
66
+ }
67
+ return claim;
68
+ }
69
+
70
+ function claimFingerprint(claim) {
71
+ return sha256(JSON.stringify({
72
+ schema: claim.schema,
73
+ projectId: claim.projectId,
74
+ commitSha: claim.commitSha,
75
+ parents: claim.parents,
76
+ requirementIds: claim.requirementIds,
77
+ requirementBinding: claim.requirementBinding,
78
+ conversationSnapshotHash: claim.conversationSnapshotHash || '',
79
+ promptTemplateVersion: claim.promptTemplateVersion,
80
+ promptHash: claim.promptHash,
81
+ patchHash: claim.patchHash,
82
+ evidenceHash: claim.evidenceHash,
83
+ evidenceManifestHash: claim.evidenceManifestHash,
84
+ retrievalManifestHash: claim.retrievalManifestHash,
85
+ knowledgePath: claim.knowledgePath,
86
+ }));
87
+ }
88
+
89
+ class CommitClaimStore {
90
+ constructor(options = {}) {
91
+ this.layout = options.layout || new StorageLayout(options);
92
+ this.atomic = options.atomic || AtomicFile;
93
+ }
94
+
95
+ filePath(projectId, commitSha) {
96
+ return this.layout.getRuntimePath('claims', validateProjectId(projectId), `${validateSha(commitSha)}.json`);
97
+ }
98
+
99
+ write(projectId, commitSha, snapshot) {
100
+ const file = this.filePath(projectId, commitSha);
101
+ // v2 persists only locating IDs and validation metadata; every path is
102
+ // derived at run time from the current layout, so a relocated data
103
+ // directory needs no snapshot rewrite. Marker snapshots without evidence
104
+ // (existence-only records) stay valid without a run id.
105
+ const { evidence, existingKnowledge, ...rest } = snapshot;
106
+ const payload = { schema: SNAPSHOT_SCHEMA_V2, ...rest, evidence: stripFrozenEvidencePaths(evidence), existingKnowledge: stripRetrievalPaths(existingKnowledge) };
107
+ if (payload.evidence && !payload.runId) throw new DomainError('DATA_CORRUPT', 'Claim snapshot requires a run id.', { status: 500 });
108
+ this.atomic.writeJsonAtomic(file, payload);
109
+ return file;
110
+ }
111
+
112
+ read(projectId, commitSha) {
113
+ return this.atomic.readJsonStrict(this.filePath(projectId, commitSha), {
114
+ category: 'commit-claim-snapshot',
115
+ validate: snapshot => {
116
+ if (!snapshot || !SNAPSHOT_SCHEMAS.includes(snapshot.schema) || snapshot.projectId !== projectId || snapshot.commitSha !== commitSha) {
117
+ throw new DomainError('DATA_CORRUPT', 'Commit claim snapshot is corrupt.', { status: 500 });
118
+ }
119
+ if (snapshot.schema === SNAPSHOT_SCHEMA_V2 && !snapshot.runId) {
120
+ throw new DomainError('DATA_CORRUPT', 'Commit claim snapshot is missing its run id.', { status: 500 });
121
+ }
122
+ return snapshot;
123
+ },
124
+ });
125
+ }
126
+
127
+ remove(projectId, commitSha) {
128
+ const file = this.filePath(projectId, commitSha);
129
+ try { fs.unlinkSync(file); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
130
+ }
131
+ }
132
+
133
+ // Absolute evidence locations are build-time facts of the instance that wrote
134
+ // them; only hashes and IDs cross a data-directory relocation.
135
+ function stripFrozenEvidencePaths(evidence) {
136
+ if (!evidence || typeof evidence !== 'object') return evidence;
137
+ const bundle = evidence.evidenceBundle;
138
+ if (!bundle || typeof bundle !== 'object') return { ...evidence };
139
+ const { root, commitPath, manifestPath, ...bundleRest } = bundle;
140
+ void root; void commitPath; void manifestPath;
141
+ return { ...evidence, evidenceBundle: bundleRest };
142
+ }
143
+
144
+ function stripRetrievalPaths(existingKnowledge) {
145
+ if (!existingKnowledge || typeof existingKnowledge !== 'object') return existingKnowledge;
146
+ const { manifestPath, ...rest } = existingKnowledge;
147
+ void manifestPath;
148
+ return rest;
149
+ }
150
+
151
+ class CommitReconciler {
152
+ constructor(options = {}) {
153
+ this.layout = options.layout || new StorageLayout(options);
154
+ this.registryStore = options.registryStore || new ProjectRegistryStore({ layout: this.layout });
155
+ this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
156
+ this.scanner = options.scanner || new CommitScanner(options);
157
+ this.conversationStore = options.conversationStore || new ConversationStore({
158
+ layout: this.layout,
159
+ projectStore: this.projectStore,
160
+ logger: options.logger,
161
+ });
162
+ this.binder = options.conversationBinder || new CommitConversationBinder({
163
+ layout: this.layout,
164
+ projectStore: this.projectStore,
165
+ conversationStore: this.conversationStore,
166
+ logger: options.logger,
167
+ });
168
+ this.retrievalService = options.retrievalService || new KnowledgeRetrievalService({
169
+ layout: this.layout,
170
+ registryStore: this.registryStore,
171
+ projectStore: this.projectStore,
172
+ databaseProvider: options.databaseProvider,
173
+ embedderProvider: options.embedderProvider,
174
+ logger: options.logger,
175
+ });
176
+ this.claimStore = options.claimStore || new CommitClaimStore({ layout: this.layout });
177
+ this.processingLedger = options.processingLedger || new CommitProcessingLedger({ layout: this.layout });
178
+ this.claimProcessor = options.claimProcessor || null;
179
+ this.logger = options.logger || null;
180
+ this.settingsStore = options.settingsStore || null;
181
+ this.batchSize = Math.max(1, Number(options.batchSize || 200));
182
+ this.requireAiProfile = options.requireAiProfile !== false;
183
+ }
184
+
185
+ async log(level, event, message, context) {
186
+ if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
187
+ }
188
+
189
+ // First preparation, failed retries and recovery all share one construction
190
+ // rule: the ACTIVE claim's runId plus the RUNNING layout decide where frozen
191
+ // evidence is read. Absolute paths inside historical snapshots are archival
192
+ // facts and never select the read location, even if the old directory still
193
+ // exists.
194
+ resolveFrozenLocations(projectId, runId) {
195
+ const safeRunId = validateRunIdSegment(runId);
196
+ const runtimeRoot = path.join(this.layout.dataDir, 'runtime');
197
+ const evidenceRoot = this.layout.getRuntimePath('runs', validateProjectId(projectId), safeRunId, 'input', 'evidence');
198
+ const retrievalManifestPath = this.layout.getRuntimePath('runs', validateProjectId(projectId), safeRunId, 'input', 'retrieval', 'manifest.json');
199
+ // The legacy layout joins paths without containment checks; enforce the
200
+ // same real-path boundary the engine layout guarantees (symlink/junction
201
+ // escapes on parent directories included).
202
+ for (const candidate of [evidenceRoot, retrievalManifestPath]) {
203
+ if (!this.layout.isPathInside(runtimeRoot, candidate, { realpath: true, allowRoot: false })) {
204
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Frozen evidence location escapes the runtime root.', { status: 403 });
205
+ }
206
+ }
207
+ return { runId: safeRunId, evidenceRoot, retrievalManifestPath };
208
+ }
209
+
210
+ relocateFrozenEvidence(evidence, locations) {
211
+ return {
212
+ ...evidence,
213
+ evidenceBundle: {
214
+ ...evidence.evidenceBundle,
215
+ root: locations.evidenceRoot,
216
+ commitPath: path.join(locations.evidenceRoot, 'commit.json'),
217
+ manifestPath: path.join(locations.evidenceRoot, 'patch-manifest.json'),
218
+ },
219
+ };
220
+ }
221
+
222
+ async reconcile(projectId, trigger, context = {}) {
223
+ validateProjectId(projectId);
224
+ validateTrigger(trigger);
225
+ if (!context.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Commit reconciliation requires an explicit Hook commit SHA.');
226
+ return this.processCommitEvent({ projectId, commitSha: context.commitSha, branch: context.branch || '', operationId: context.operationId || createId('op') });
227
+ }
228
+
229
+ async processCommitEvent({ projectId, commitSha, branch = '', operationId = '' } = {}) {
230
+ validateProjectId(projectId);
231
+ validateSha(commitSha);
232
+ const existingQueue = explicitQueues.get(projectId) || { tail: Promise.resolve(), pending: new Map() };
233
+ explicitQueues.set(projectId, existingQueue);
234
+ if (existingQueue.pending.has(commitSha)) return existingQueue.pending.get(commitSha);
235
+ const queued = existingQueue.tail.catch(() => {}).then(async () => {
236
+ const completed = this.processingLedger.read(projectId, commitSha);
237
+ if (completed) return { ok: true, projectId, commitSha, status: 'already-completed', processed: [], ledger: completed };
238
+ const config = this.projectStore.readConfig(projectId);
239
+ if (config.enabled === false) return { ok: true, projectId, commitSha, status: 'disabled', processed: [] };
240
+ const result = await this.processCommit(projectId, 'git-hook', operationId || createId('op'), config, branch, commitSha);
241
+ if (!result.ok) return { ok: false, projectId, commitSha, status: 'failed', processed: [result], error: result.error };
242
+ const ledger = this.processingLedger.complete(projectId, commitSha, { runId: result.runId, claimFingerprint: result.claimFingerprint || '' });
243
+ return { ok: true, projectId, commitSha, status: 'completed', processed: [result], ledger };
244
+ });
245
+ existingQueue.pending.set(commitSha, queued);
246
+ existingQueue.tail = queued.catch(() => {});
247
+ try { return await queued; }
248
+ finally {
249
+ existingQueue.pending.delete(commitSha);
250
+ if (!existingQueue.pending.size) explicitQueues.delete(projectId);
251
+ }
252
+ }
253
+
254
+ async prepareClaim(projectId, trigger, operationId, config, branch, commitSha) {
255
+ const state = this.projectStore.readState(projectId);
256
+ if (state.analysis.activeClaim) {
257
+ const activeClaim = state.analysis.activeClaim;
258
+ // A terminal failure must not turn a project into a permanent dead end.
259
+ // We only release it while processing a *new, explicit* Hook SHA; the
260
+ // failed SHA is never retried, scanned, or inferred from history.
261
+ if (activeClaim.commitSha !== commitSha) {
262
+ validateClaim(activeClaim, projectId, activeClaim.commitSha);
263
+ const terminalFailure = activeClaim.phase === 'failed'
264
+ && activeClaim.error
265
+ && activeClaim.error.retryable !== true;
266
+ if (!terminalFailure) {
267
+ throw new DomainError('PROJECT_BUSY', 'Another unfinished commit claim already exists.', { status: 409, retryable: true });
268
+ }
269
+ await this.projectStore.updateState(projectId, draft => {
270
+ const current = draft.analysis.activeClaim;
271
+ if (!current || current.commitSha !== activeClaim.commitSha || current.fingerprint !== activeClaim.fingerprint) {
272
+ throw new DomainError('PROJECT_BUSY', 'The active commit claim changed while preparing this Hook event.', { status: 409, retryable: true });
273
+ }
274
+ draft.analysis.activeClaim = null;
275
+ draft.analysis.status = 'idle';
276
+ draft.analysis.lastError = {
277
+ code: 'FAILED_CLAIM_SUPERSEDED',
278
+ message: 'A terminal failed claim was preserved for diagnostics and superseded by a newer explicit Hook commit.',
279
+ retryable: false,
280
+ ts: new Date().toISOString(),
281
+ };
282
+ });
283
+ await this.log('warn', 'reconcile.failed_claim_superseded', 'A terminal failed claim was superseded by a newer explicit Hook commit.', {
284
+ projectId,
285
+ previousCommitSha: activeClaim.commitSha,
286
+ commitSha,
287
+ previousFailure: activeClaim.error,
288
+ });
289
+ return this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
290
+ }
291
+ const claim = validateClaim(activeClaim, projectId, commitSha);
292
+ const snapshot = this.claimStore.read(projectId, commitSha);
293
+ if ((snapshot.schema === SNAPSHOT_SCHEMA_V2 && snapshot.runId !== claim.runId)
294
+ || snapshot.claimFingerprint !== claimFingerprint(claim)
295
+ || snapshot.evidence.patchHash !== claim.patchHash
296
+ || snapshot.evidence.evidenceHash !== claim.evidenceHash
297
+ || !snapshot.evidence.evidenceBundle
298
+ || snapshot.evidence.evidenceBundle.manifestHash !== claim.evidenceManifestHash
299
+ || !snapshot.existingKnowledge || snapshot.existingKnowledge.manifestHash !== claim.retrievalManifestHash
300
+ || sha256(snapshot.prompt) !== claim.promptHash
301
+ || (claim.conversationSnapshotHash && (!snapshot.conversationSnapshot || snapshot.conversationSnapshot.snapshotHash !== claim.conversationSnapshotHash))) {
302
+ throw new DomainError('DATA_CORRUPT', 'Frozen commit claim snapshot does not match active state.', { status: 500 });
303
+ }
304
+ // Recompute every frozen-input location from the current data directory
305
+ // and the active claim's run id, then verify the SAME historical evidence
306
+ // (commit SHA, patch/manifest/chunk hashes) at those current paths.
307
+ const locations = this.resolveFrozenLocations(projectId, claim.runId);
308
+ const evidence = this.relocateFrozenEvidence(snapshot.evidence, locations);
309
+ const existingKnowledge = { ...snapshot.existingKnowledge, manifestPath: locations.retrievalManifestPath };
310
+ this.scanner.verifyEvidence(evidence, {
311
+ expectedCommitSha: claim.commitSha,
312
+ expectedManifestHash: claim.evidenceManifestHash,
313
+ });
314
+ let retrievalManifest;
315
+ try {
316
+ retrievalManifest = this.claimStore.atomic.readJsonStrict(existingKnowledge.manifestPath, {
317
+ category: 'knowledge-retrieval-manifest',
318
+ validate: value => {
319
+ if (!value || value.schema !== 'knowledge-retrieval-manifest/v1'
320
+ || value.manifestHash !== claim.retrievalManifestHash
321
+ || calculateRetrievalManifestHash(value) !== value.manifestHash) {
322
+ throw new DomainError('DATA_CORRUPT', 'Frozen knowledge retrieval manifest is corrupt.', { status: 500 });
323
+ }
324
+ return value;
325
+ },
326
+ });
327
+ } catch (error) {
328
+ if (error instanceof DomainError) throw error;
329
+ if (error && error.code === 'ENOENT') {
330
+ throw new DomainError('EVIDENCE_MISSING', 'Frozen knowledge retrieval manifest is missing at the current data directory.', {
331
+ status: 500,
332
+ details: { resource: 'input/retrieval/manifest.json', runId: claim.runId },
333
+ cause: error,
334
+ });
335
+ }
336
+ throw error;
337
+ }
338
+ const selectedById = new Map(retrievalManifest.selected.map(item => [`${item.spaceId}:${item.chunkId}`, item]));
339
+ for (const entry of existingKnowledge.entries || []) {
340
+ const selected = selectedById.get(`${entry.projectId === projectId ? `project:${projectId}` : `project:${entry.projectId}`}:${entry.chunkId}`);
341
+ if (!selected || knowledgeContentHash(entry.content) !== entry.hash || selected.contentHash !== entry.hash) {
342
+ throw new DomainError('DATA_CORRUPT', 'Frozen authoritative Markdown context does not match its retrieval manifest.', { status: 500 });
343
+ }
344
+ }
345
+ claim.attempt = Number(claim.attempt || 1) + 1;
346
+ claim.phase = 'evidence.prepared';
347
+ await this.projectStore.updateState(projectId, draft => {
348
+ draft.analysis.activeClaim = claim;
349
+ draft.analysis.status = 'evidence.prepared';
350
+ draft.analysis.lastError = null;
351
+ });
352
+ return {
353
+ claim,
354
+ evidence,
355
+ prompt: snapshot.prompt,
356
+ requirements: snapshot.requirements || [],
357
+ conversationSnapshot: snapshot.conversationSnapshot || null,
358
+ existingKnowledge,
359
+ retry: true,
360
+ };
361
+ }
362
+
363
+ const runId = createId('run');
364
+ const evidenceRoot = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'evidence');
365
+ const evidence = await this.scanner.collectEvidence(config, commitSha, { branch, evidenceRoot });
366
+ this.scanner.verifyEvidence(evidence);
367
+ const conversationSnapshot = await this.binder.bind({ projectId, commitSha, branch });
368
+ const requirements = snapshotRequirementRecords(conversationSnapshot);
369
+ const existingKnowledge = await this.retrievalService.retrieveForCommit({
370
+ projectId,
371
+ conversationSnapshot,
372
+ commitEvidence: evidence,
373
+ });
374
+ existingKnowledge.manifestPath = this.layout.getRuntimePath('runs', projectId, runId, 'input', 'retrieval', 'manifest.json');
375
+ this.claimStore.atomic.writeJsonAtomic(existingKnowledge.manifestPath, existingKnowledge.manifest);
376
+ const rendered = renderCommitPrompt({ projectId, config, evidence, requirements, conversationSnapshot, existingKnowledge });
377
+ const claim = {
378
+ schema: SCHEMAS.commitClaim,
379
+ projectId,
380
+ commitSha,
381
+ parents: evidence.parents,
382
+ triggerFirstSeen: trigger,
383
+ requirementIds: requirements.map(requirement => requirement.id),
384
+ requirementBinding: conversationSnapshot.status,
385
+ conversationSnapshotHash: conversationSnapshot.snapshotHash,
386
+ conversationTurnIds: conversationSnapshot.turns.map(turn => turn.turnId),
387
+ conversationEventIds: conversationSnapshot.turns.flatMap(turn => [...turn.userEvents, ...turn.assistantEvents].map(event => event.eventId)),
388
+ promptTemplateVersion: rendered.promptTemplateVersion,
389
+ promptHash: rendered.promptHash,
390
+ patchHash: evidence.patchHash,
391
+ evidenceHash: evidence.evidenceHash,
392
+ evidenceManifestHash: evidence.evidenceBundle.manifestHash,
393
+ retrievalManifestHash: existingKnowledge.manifestHash,
394
+ knowledgePath: config.knowledgePath,
395
+ runId,
396
+ operationId,
397
+ phase: 'evidence.prepared',
398
+ attempt: 1,
399
+ };
400
+ claim.fingerprint = claimFingerprint(claim);
401
+ this.claimStore.write(projectId, commitSha, {
402
+ projectId,
403
+ commitSha,
404
+ runId: claim.runId,
405
+ claimFingerprint: claim.fingerprint,
406
+ evidence,
407
+ prompt: rendered.prompt,
408
+ requirements,
409
+ conversationSnapshot,
410
+ existingKnowledge,
411
+ createdAt: new Date().toISOString(),
412
+ });
413
+ try {
414
+ await this.projectStore.updateState(projectId, draft => {
415
+ if (draft.analysis.activeClaim) throw new DomainError('PROJECT_BUSY', 'Another active claim already exists.', { status: 409, retryable: true });
416
+ draft.analysis.activeClaim = claim;
417
+ draft.analysis.status = 'evidence.prepared';
418
+ draft.analysis.lastError = null;
419
+ });
420
+ } catch (error) {
421
+ this.claimStore.remove(projectId, commitSha);
422
+ throw error;
423
+ }
424
+ await this.log('info', 'reconcile.claim_prepared', 'Commit evidence and claim prepared.', {
425
+ projectId,
426
+ operationId,
427
+ runId: claim.runId,
428
+ commitSha,
429
+ phase: claim.phase,
430
+ promptHash: claim.promptHash,
431
+ patchHash: claim.patchHash,
432
+ patchBytes: evidence.patchBytes,
433
+ evidenceManifestHash: claim.evidenceManifestHash,
434
+ evidenceChunkCount: evidence.evidenceBundle.chunkCount,
435
+ evidenceChunkBytes: evidence.evidenceBundle.chunkBytes,
436
+ retrievalManifestHash: claim.retrievalManifestHash,
437
+ retrievalSelectedCount: existingKnowledge.entries.length,
438
+ retrievalBytes: existingKnowledge.totalBytes,
439
+ fileCount: evidence.files.length,
440
+ requirementBinding: claim.requirementBinding,
441
+ requirementCount: claim.requirementIds.length,
442
+ });
443
+ return { claim, evidence, prompt: rendered.prompt, requirements, conversationSnapshot, existingKnowledge, retry: false };
444
+ }
445
+
446
+ async processCommit(projectId, trigger, operationId, config, branch, commitSha) {
447
+ let prepared;
448
+ try {
449
+ prepared = await this.prepareClaim(projectId, trigger, operationId, config, branch, commitSha);
450
+ if (this.requireAiProfile) {
451
+ // Use the shared effective-profile resolver so a project with no explicit
452
+ // aiProfileId can still analyze via the global default or first-usable
453
+ // profile. The resolver throws AI_PROFILE_REQUIRED if nothing usable
454
+ // exists, which becomes a clear actionable error rather than a silent
455
+ // null deref.
456
+ resolveEffectiveAiProfile(this.settingsStore ? this.settingsStore.read() : null, config);
457
+ }
458
+ if (!this.claimProcessor || typeof this.claimProcessor.processClaim !== 'function') {
459
+ throw new DomainError('INVALID_ARGUMENT', 'Knowledge claim processor is unavailable.', { status: 503, retryable: true });
460
+ }
461
+ const result = await this.claimProcessor.processClaim({
462
+ projectId,
463
+ config,
464
+ claim: prepared.claim,
465
+ evidence: prepared.evidence,
466
+ prompt: prepared.prompt,
467
+ requirements: prepared.requirements,
468
+ conversationSnapshot: prepared.conversationSnapshot,
469
+ existingKnowledge: prepared.existingKnowledge,
470
+ operationId,
471
+ });
472
+ if (!result || result.stateAdvanced !== true) {
473
+ throw new DomainError('INVALID_ARGUMENT', 'Knowledge promotion did not prove state advancement.', { status: 500, retryable: true });
474
+ }
475
+ const advanced = this.projectStore.readState(projectId);
476
+ if (advanced.lastAnalyzedCommit !== commitSha || advanced.analysis.activeClaim) {
477
+ throw new DomainError('DATA_CORRUPT', 'Claim processor reported success without atomically advancing project state.', { status: 500 });
478
+ }
479
+ this.claimStore.remove(projectId, commitSha);
480
+ await this.log('info', 'reconcile.commit_completed', 'Commit knowledge was promoted and state advanced.', {
481
+ projectId,
482
+ operationId,
483
+ runId: prepared.claim.runId,
484
+ commitSha,
485
+ phase: 'state.advanced',
486
+ });
487
+ return { ok: true, commitSha, runId: prepared.claim.runId, claimFingerprint: prepared.claim.fingerprint, retry: prepared.retry };
488
+ } catch (error) {
489
+ const failure = publicFailure(error, prepared && prepared.claim && prepared.claim.phase || 'evidence.prepared');
490
+ let stateUpdateError = null;
491
+ try {
492
+ await this.projectStore.updateState(projectId, draft => {
493
+ const active = draft.analysis.activeClaim;
494
+ if (active && active.commitSha === commitSha) {
495
+ active.phase = 'failed';
496
+ active.error = failure;
497
+ }
498
+ draft.analysis.status = 'failed';
499
+ draft.analysis.lastError = failure;
500
+ });
501
+ } catch (updateError) {
502
+ stateUpdateError = updateError;
503
+ }
504
+ await this.log('error', 'reconcile.commit_failed', 'Commit reconciliation stopped at the first failed commit.', {
505
+ projectId,
506
+ operationId,
507
+ runId: prepared && prepared.claim && prepared.claim.runId,
508
+ commitSha,
509
+ phase: failure.phase,
510
+ error,
511
+ context: stateUpdateError ? { failureStateWriteError: stateUpdateError } : {},
512
+ });
513
+ return { ok: false, commitSha, error: failure, retry: prepared && prepared.retry || false };
514
+ }
515
+ }
516
+
517
+ async markDiverged(projectId, operationId, message, processed = []) {
518
+ const error = new DomainError('HISTORY_DIVERGED', message || 'Git history diverged from the stored baseline.', { status: 409 });
519
+ await this.projectStore.updateState(projectId, state => {
520
+ state.analysis.status = 'history-diverged';
521
+ state.analysis.lastError = publicFailure(error, 'history-diverged');
522
+ });
523
+ await this.log('error', 'reconcile.history_diverged', 'Git history diverged; reconciliation stopped without moving pointers.', { projectId, operationId, phase: 'history-diverged', error });
524
+ return { ok: false, status: 'history-diverged', processed, error: publicFailure(error, 'history-diverged') };
525
+ }
526
+
527
+ async failWithoutClaim(projectId, operationId, error, phase, processed = []) {
528
+ await this.projectStore.updateState(projectId, state => {
529
+ state.analysis.status = 'failed';
530
+ state.analysis.lastError = publicFailure(error, phase);
531
+ });
532
+ await this.log('error', 'reconcile.failed', 'Reconciliation failed before claim processing.', { projectId, operationId, phase, error });
533
+ return { ok: false, status: 'failed', processed, error: publicFailure(error, phase) };
534
+ }
535
+ }
536
+
537
+ async function reconcileProjectCommits(projectId, trigger, deps = {}) {
538
+ const reconciler = deps.reconciler instanceof CommitReconciler ? deps.reconciler : new CommitReconciler(deps);
539
+ return reconciler.reconcile(projectId, trigger, { operationId: deps.operationId || '', commitSha: deps.commitSha || '', branch: deps.branch || '' });
540
+ }
541
+
542
+ module.exports = {
543
+ CommitClaimStore,
544
+ CommitReconciler,
545
+ CommitProcessingLedger,
546
+ claimFingerprint,
547
+ reconcileProjectCommits,
548
+ validateClaim,
549
+ SNAPSHOT_SCHEMA_V1,
550
+ SNAPSHOT_SCHEMA_V2,
551
+ };