@sanqianx/project-knowledge 5.1.4 → 5.1.6

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 (37) 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 +57 -7
  4. package/_site/_test/agent-capture-ui-test.js +6 -4
  5. package/_site/_test/fixtures/integration-busy-worker.cjs +11 -3
  6. package/_site/_test/helpers/parallel-memory-shell.js +13 -2
  7. package/_site/_test/hook-relocation-rebind-test.js +120 -0
  8. package/_site/_test/integration-auto-repair-test.js +3 -1
  9. package/_site/_test/integration-intent-test.js +6 -2
  10. package/_site/_test/integration-runtime-binding-test.js +4 -4
  11. package/_site/_test/integration-status-scan-test.js +138 -7
  12. package/_site/_test/legacy-relocation-recovery-test.js +258 -0
  13. package/_site/_test/parallel-retrieval-followup-corpus-test.js +6 -4
  14. package/_site/_test/project-team-ui-test.js +124 -0
  15. package/_site/_test/recovery-label-contract-test.js +45 -0
  16. package/_site/lib/capture-hook-config.js +16 -7
  17. package/_site/lib/claude-plugin-status.js +60 -0
  18. package/_site/lib/commit-prompt.js +205 -202
  19. package/_site/lib/commit-reconciler.js +551 -444
  20. package/_site/lib/contracts.js +1 -0
  21. package/_site/lib/evidence-bundle.js +32 -5
  22. package/_site/lib/integration-auto-repair.js +3 -2
  23. package/_site/lib/integration-installer.js +153 -71
  24. package/_site/lib/integration-intent.js +12 -5
  25. package/_site/lib/integration-status-scan.js +101 -41
  26. package/_site/lib/integration-status-worker.js +4 -2
  27. package/_site/lib/knowledge-promotion.js +547 -435
  28. package/_site/lib/scanner.js +5 -3
  29. package/_site/lib/server-app.js +34 -7
  30. package/_site/scripts/refresh-runtime-manifest.js +1 -1
  31. package/module-runtime-manifest.json +85 -85
  32. package/package.json +6 -6
  33. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  34. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  35. package/plugins/project-knowledge/.mcp.json +1 -1
  36. package/ui/product.css +1 -0
  37. package/ui/product.js +239 -49
@@ -1,435 +1,547 @@
1
- const crypto = require('crypto');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const { TextDecoder } = require('util');
5
- const AtomicFile = require('./atomic-file');
6
- const { DomainError, createId, validateProjectId } = require('./contracts');
7
- const { StorageLayout } = require('./storage-layout');
8
- const { ProjectStore } = require('./project-store');
9
- const { buildAutomationToolPolicy } = require('./automation-config');
10
- const { execGit } = require('./git-runner');
11
-
12
- const MANIFEST_SCHEMA = 'knowledge-staging-manifest/v1';
13
- const JOURNAL_SCHEMA = 'promotion-journal/v1';
14
- const MAX_KNOWLEDGE_FILE_BYTES = 1024 * 1024;
15
- const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
16
-
17
- function hashBuffer(value) {
18
- return `sha256:${crypto.createHash('sha256').update(value).digest('hex')}`;
19
- }
20
-
21
- function fileHash(filePath) {
22
- return fs.existsSync(filePath) && fs.statSync(filePath).isFile()
23
- ? hashBuffer(fs.readFileSync(filePath))
24
- : null;
25
- }
26
-
27
- function canonicalRelativePath(value) {
28
- const raw = String(value || '');
29
- if (!raw || raw.includes('\\') || raw.includes('\u0000') || path.posix.isAbsolute(raw) || path.win32.isAbsolute(raw)) {
30
- throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path must be a canonical relative POSIX path.');
31
- }
32
- const segments = raw.split('/');
33
- if (segments.some(segment => !segment || segment === '.' || segment === '..' || segment.includes(':') || /[. ]$/.test(segment) || WINDOWS_RESERVED.test(segment))) {
34
- throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path contains an unsafe segment.');
35
- }
36
- if (!raw.toLowerCase().endsWith('.md') || segments.some(segment => segment.toLowerCase() === '00-index.md')) {
37
- throw new DomainError('INVALID_ARGUMENT', 'Knowledge operations may target non-derived Markdown files only.');
38
- }
39
- const topLevel = segments.length === 1 && ['README.md', 'GOAL.md', 'ARCHITECTURE.md'].includes(segments[0]);
40
- const collection = segments.length >= 2 && ['modules', 'changes'].includes(segments[0]);
41
- if (!topLevel && !collection) throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path is outside the allowed knowledge structure.');
42
- return raw;
43
- }
44
-
45
- function decodeUtf8(buffer) {
46
- try { return new TextDecoder('utf-8', { fatal: true }).decode(buffer); }
47
- catch (error) { throw new DomainError('INVALID_ARGUMENT', 'Staged Markdown must be valid UTF-8.', { cause: error }); }
48
- }
49
-
50
- function validateMarkdown(content, relativePath) {
51
- if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(content)) {
52
- throw new DomainError('INVALID_ARGUMENT', `Staged Markdown contains disallowed control characters: ${relativePath}.`);
53
- }
54
- if (!content.trim() || !/^#\s+\S+/m.test(content)) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown must contain a title: ${relativePath}.`);
55
- if (/(?:\[TODO:|\bTODO:\s|\bTBD\b|PLACEHOLDER)/i.test(content)) throw new DomainError('INVALID_ARGUMENT', `Placeholder knowledge is not allowed: ${relativePath}.`);
56
- const fences = content.match(/^```/gm) || [];
57
- if (fences.length % 2 !== 0) throw new DomainError('INVALID_ARGUMENT', `Markdown code fences are unbalanced: ${relativePath}.`);
58
- if (content.startsWith('---\n') && !/^---\n[\s\S]*?\n---\n/.test(content)) {
59
- throw new DomainError('INVALID_ARGUMENT', `Markdown frontmatter is incomplete: ${relativePath}.`);
60
- }
61
- return true;
62
- }
63
-
64
- async function gitStatus(repoPath) {
65
- if (!repoPath || !fs.existsSync(repoPath)) return null;
66
- const result = await execGit(repoPath, ['status', '--porcelain=v1', '-z'], 15_000);
67
- return result && result.ok ? String(result.stdout || '') : null;
68
- }
69
-
70
- class KnowledgePromotionService {
71
- constructor(options = {}) {
72
- this.layout = options.layout || new StorageLayout(options);
73
- this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
74
- this.analyzer = options.analyzer || null;
75
- this.indexService = options.indexService || null;
76
- this.atomic = options.atomic || AtomicFile;
77
- this.logger = options.logger || null;
78
- this.maxFileBytes = Number(options.maxFileBytes || MAX_KNOWLEDGE_FILE_BYTES);
79
- this.fault = options.fault || (() => {});
80
- }
81
-
82
- runRoot(projectId, runId) { return this.layout.getRuntimePath('runs', validateProjectId(projectId), String(runId)); }
83
- stagingPath(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'output'); }
84
- evidenceRoot(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'input', 'evidence'); }
85
-
86
- manifestPath(projectId, runId) { return path.join(this.stagingPath(projectId, runId), 'manifest.json'); }
87
- journalPath(projectId, runId) { return this.layout.getRuntimePath('promotions', validateProjectId(projectId), `${runId}.json`); }
88
- backupRoot(projectId, runId) { return this.layout.getRecoveryPath('promotions', validateProjectId(projectId), String(runId)); }
89
-
90
- async log(level, event, message, context) {
91
- if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
92
- }
93
-
94
- prepareStaging(projectId, runId) {
95
- const staging = this.stagingPath(projectId, runId);
96
- if (fs.existsSync(staging)) {
97
- const entries = fs.readdirSync(staging);
98
- if (entries.length) {
99
- const journalFile = this.journalPath(projectId, runId);
100
- if (!fs.existsSync(journalFile)) {
101
- fs.rmSync(staging, { recursive: true, force: true });
102
- } else {
103
- const journal = this.atomic.readJsonStrict(journalFile, { category: 'promotion-journal' });
104
- if (journal.phase === 'rolled-back') fs.rmSync(staging, { recursive: true, force: true });
105
- else throw new DomainError('MIGRATION_TARGET_CONFLICT', 'Run staging is owned by an unfinished promotion journal.', { status: 409 });
106
- }
107
- }
108
- }
109
- fs.mkdirSync(path.join(staging, 'files'), { recursive: true });
110
- return staging;
111
- }
112
-
113
- readManifest(projectId, runId) {
114
- return this.atomic.readJsonStrict(this.manifestPath(projectId, runId), {
115
- category: 'knowledge-staging-manifest',
116
- validate: manifest => {
117
- if (!manifest || manifest.schema !== MANIFEST_SCHEMA || manifest.projectId !== projectId || manifest.runId !== runId || !Array.isArray(manifest.operations)) {
118
- throw new DomainError('DATA_CORRUPT', 'Knowledge staging manifest is invalid.', { status: 500 });
119
- }
120
- return manifest;
121
- },
122
- });
123
- }
124
-
125
- validateManifest(input) {
126
- const { projectId, config, claim } = input;
127
- const manifest = this.readManifest(projectId, claim.runId);
128
- if (manifest.commitSha !== claim.commitSha || manifest.operations.length === 0) {
129
- throw new DomainError('INVALID_ARGUMENT', 'Manifest must contain operations for the active commit.');
130
- }
131
- const seen = new Set();
132
- const operations = [];
133
- for (const [index, raw] of manifest.operations.entries()) {
134
- const relativePath = canonicalRelativePath(raw.path);
135
- if (seen.has(relativePath.toLowerCase())) throw new DomainError('INVALID_ARGUMENT', `Duplicate manifest path: ${relativePath}.`);
136
- seen.add(relativePath.toLowerCase());
137
- const operation = String(raw.operation || '');
138
- if (!['create', 'replace', 'delete'].includes(operation)) throw new DomainError('INVALID_ARGUMENT', `Invalid manifest operation: ${operation}.`);
139
- if (!String(raw.reason || '').trim() || !Array.isArray(raw.evidenceReferences) || raw.evidenceReferences.length === 0) {
140
- throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks reason/evidence: ${relativePath}.`);
141
- }
142
- const evidenceReferences = raw.evidenceReferences.map(String);
143
- const requiredEvidence = [
144
- `commit:${claim.commitSha}`,
145
- claim.patchHash && `patch:${claim.patchHash}`,
146
- claim.conversationSnapshotHash && `conversation:${claim.conversationSnapshotHash}`,
147
- claim.retrievalManifestHash && `retrieval:${claim.retrievalManifestHash}`,
148
- ].filter(Boolean);
149
- const missingEvidence = requiredEvidence.filter(reference => !evidenceReferences.includes(reference));
150
- if (missingEvidence.length) {
151
- throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks frozen claim evidence: ${relativePath}.`, {
152
- details: { missingEvidence },
153
- });
154
- }
155
- const target = path.resolve(config.knowledgePath, ...relativePath.split('/'));
156
- if (!this.layout.isPathInside(config.knowledgePath, target, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge path escapes its project: ${relativePath}.`);
157
- const targetExists = fs.existsSync(target);
158
- if (targetExists && fs.lstatSync(target).isSymbolicLink()) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge target is a symlink: ${relativePath}.`);
159
- if (operation === 'create' && targetExists) throw new DomainError('MIGRATION_TARGET_CONFLICT', `Create target already exists: ${relativePath}.`, { status: 409 });
160
- if ((operation === 'replace' || operation === 'delete') && (!targetExists || !fs.statSync(target).isFile())) {
161
- throw new DomainError('INVALID_ARGUMENT', `${operation} target is not an owned project knowledge file: ${relativePath}.`);
162
- }
163
- let stagedPath = null;
164
- let newHash = null;
165
- if (operation !== 'delete') {
166
- stagedPath = path.join(this.stagingPath(projectId, claim.runId), 'files', ...relativePath.split('/'));
167
- if (!fs.existsSync(stagedPath) || !fs.statSync(stagedPath).isFile() || fs.lstatSync(stagedPath).isSymbolicLink()) {
168
- throw new DomainError('INVALID_ARGUMENT', `Staged Markdown is missing or unsafe: ${relativePath}.`);
169
- }
170
- const realStaged = fs.realpathSync(stagedPath);
171
- if (!this.layout.isPathInside(this.stagingPath(projectId, claim.runId), realStaged, { realpath: true })) {
172
- throw new DomainError('PATH_OUTSIDE_ROOT', `Staged file escapes run staging: ${relativePath}.`);
173
- }
174
- const buffer = fs.readFileSync(stagedPath);
175
- if (buffer.length > this.maxFileBytes) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown exceeds size limit: ${relativePath}.`);
176
- const content = decodeUtf8(buffer);
177
- validateMarkdown(content, relativePath);
178
- newHash = hashBuffer(buffer);
179
- if (raw.sha256 !== newHash) throw new DomainError('DATA_CORRUPT', `Staged Markdown hash mismatch: ${relativePath}.`, { status: 409 });
180
- } else if (raw.sha256 != null) {
181
- throw new DomainError('INVALID_ARGUMENT', `Delete operation must not declare a new hash: ${relativePath}.`);
182
- }
183
- operations.push({
184
- index,
185
- path: relativePath,
186
- operation,
187
- reason: String(raw.reason),
188
- evidenceReferences,
189
- target,
190
- stagedPath,
191
- originalExists: targetExists,
192
- originalHash: targetExists ? fileHash(target) : null,
193
- newHash,
194
- });
195
- }
196
- return { manifest, operations: operations.sort((left, right) => left.path.localeCompare(right.path)) };
197
- }
198
-
199
- writeJournal(journal) {
200
- journal.updatedAt = new Date().toISOString();
201
- this.atomic.writeJsonAtomic(this.journalPath(journal.projectId, journal.runId), journal);
202
- }
203
-
204
- prepareJournal(projectId, config, claim, validated) {
205
- const backupRoot = this.backupRoot(projectId, claim.runId);
206
- const journal = {
207
- schema: JOURNAL_SCHEMA,
208
- projectId,
209
- runId: claim.runId,
210
- commitSha: claim.commitSha,
211
- claimFingerprint: claim.fingerprint,
212
- evidence: {
213
- promptHash: claim.promptHash || null,
214
- patchHash: claim.patchHash || null,
215
- evidenceManifestHash: claim.evidenceManifestHash || null,
216
- conversationSnapshotHash: claim.conversationSnapshotHash || null,
217
- retrievalManifestHash: claim.retrievalManifestHash || null,
218
- },
219
- knowledgePath: config.knowledgePath,
220
- phase: 'preparing',
221
- createdAt: new Date().toISOString(),
222
- operations: validated.operations.map((operation, index) => ({
223
- ...operation,
224
- backupPath: operation.originalExists ? path.join(backupRoot, `${String(index).padStart(4, '0')}.backup`) : null,
225
- applied: false,
226
- })),
227
- };
228
- this.writeJournal(journal);
229
- for (const operation of journal.operations) {
230
- if (!operation.originalExists) continue;
231
- const currentHash = fileHash(operation.target);
232
- if (currentHash !== operation.originalHash) throw new DomainError('PROJECT_BUSY', `Knowledge changed before backup: ${operation.path}.`, { status: 409, retryable: true });
233
- this.atomic.writeFileAtomic(operation.backupPath, fs.readFileSync(operation.target));
234
- if (fileHash(operation.backupPath) !== operation.originalHash) throw new DomainError('DATA_CORRUPT', `Knowledge backup verification failed: ${operation.path}.`, { status: 500 });
235
- }
236
- journal.phase = 'prepared';
237
- this.writeJournal(journal);
238
- this.fault('journal-prepared', journal);
239
- return journal;
240
- }
241
-
242
- applyJournal(journal) {
243
- journal.phase = 'applying';
244
- this.writeJournal(journal);
245
- for (let index = 0; index < journal.operations.length; index += 1) {
246
- const operation = journal.operations[index];
247
- const currentHash = fileHash(operation.target);
248
- if (currentHash !== operation.originalHash) {
249
- throw new DomainError('PROJECT_BUSY', `Knowledge changed before promotion: ${operation.path}.`, { status: 409, retryable: true });
250
- }
251
- if (operation.operation === 'delete') fs.unlinkSync(operation.target);
252
- else this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.stagedPath));
253
- operation.applied = true;
254
- this.writeJournal(journal);
255
- this.fault(`operation-applied:${index}`, journal);
256
- }
257
- this.verifyPromoted(journal);
258
- journal.phase = 'awaiting-state-advance';
259
- this.writeJournal(journal);
260
- this.fault('promotion-verified', journal);
261
- return journal;
262
- }
263
-
264
- verifyPromoted(journal) {
265
- for (const operation of journal.operations) {
266
- const actual = fileHash(operation.target);
267
- if (operation.operation === 'delete' ? actual !== null : actual !== operation.newHash) {
268
- throw new DomainError('DATA_CORRUPT', `Promoted knowledge verification failed: ${operation.path}.`, { status: 500 });
269
- }
270
- }
271
- return true;
272
- }
273
-
274
- async advanceState(journal) {
275
- const current = this.projectStore.readState(journal.projectId);
276
- if (current.lastAnalyzedCommit === journal.commitSha && !current.analysis.activeClaim) return current;
277
- const advanced = await this.projectStore.updateState(journal.projectId, state => {
278
- const active = state.analysis.activeClaim;
279
- if (!active || active.runId !== journal.runId || active.commitSha !== journal.commitSha || active.fingerprint !== journal.claimFingerprint) {
280
- throw new DomainError('PROJECT_BUSY', 'Promotion journal no longer matches the active claim.', { status: 409, retryable: true });
281
- }
282
- state.lastAnalyzedCommit = journal.commitSha;
283
- state.analysis.consumedRequirementIds = [...new Set([
284
- ...(state.analysis.consumedRequirementIds || []),
285
- ...(active.requirementIds || []),
286
- ])];
287
- state.analysis.activeClaim = null;
288
- state.analysis.status = 'state.advanced';
289
- state.analysis.lastError = null;
290
- state.index.dirty = true;
291
- state.index.sinceCommit = state.index.sinceCommit || journal.commitSha;
292
- state.index.generation = Number(state.index.generation || 0) + 1;
293
- state.index.lastError = null;
294
- });
295
- this.fault('state-advanced', journal);
296
- return advanced;
297
- }
298
-
299
- async processClaim(input = {}) {
300
- const projectId = validateProjectId(input.projectId);
301
- const config = input.config || this.projectStore.readConfig(projectId);
302
- const claim = input.claim;
303
- if (!claim || claim.projectId !== projectId || !claim.runId || !claim.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Active claim is required for knowledge promotion.');
304
- const operationId = input.operationId || claim.operationId || createId('op');
305
- const stagingPath = this.prepareStaging(projectId, claim.runId);
306
- const beforeSource = await gitStatus(config.repoPath);
307
- try {
308
- if (!this.analyzer || typeof this.analyzer.runClaim !== 'function') throw new DomainError('INVALID_ARGUMENT', 'Knowledge analyzer is unavailable.', { status: 503, retryable: true });
309
- const analyzerResult = await this.analyzer.runClaim({
310
- ...input,
311
- projectId,
312
- config,
313
- claim,
314
- stagingPath,
315
- manifestPath: this.manifestPath(projectId, claim.runId),
316
- evidenceRoot: this.evidenceRoot(projectId, claim.runId),
317
- safetyPolicy: buildAutomationToolPolicy({
318
- stagingPath,
319
- evidenceRoot: this.evidenceRoot(projectId, claim.runId),
320
- }),
321
- });
322
- if (analyzerResult && analyzerResult.ok === false) throw new DomainError('INVALID_ARGUMENT', analyzerResult.error || 'Knowledge analyzer failed.', { status: 500, retryable: true });
323
- const afterSource = await gitStatus(config.repoPath);
324
- if (beforeSource != null && afterSource != null && beforeSource !== afterSource) {
325
- throw new DomainError('PROJECT_BUSY', 'Source repository changed during knowledge analysis.', { status: 409, retryable: true });
326
- }
327
- this.fault('analysis-completed', { projectId, claim, stagingPath });
328
- const validated = this.validateManifest({ projectId, config, claim });
329
- this.fault('manifest-validated', validated);
330
- const journal = this.prepareJournal(projectId, config, claim, validated);
331
- this.applyJournal(journal);
332
- await this.advanceState(journal);
333
- journal.phase = 'completed';
334
- journal.completedAt = new Date().toISOString();
335
- this.writeJournal(journal);
336
- await this.log('info', 'knowledge.promotion_completed', 'Validated knowledge was promoted and state advanced.', {
337
- projectId,
338
- operationId,
339
- runId: claim.runId,
340
- commitSha: claim.commitSha,
341
- phase: 'state.advanced',
342
- operationCount: journal.operations.length,
343
- });
344
- if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(projectId).catch(() => {});
345
- return { ok: true, stateAdvanced: true, projectId, runId: claim.runId, commitSha: claim.commitSha, operations: journal.operations.length };
346
- } catch (error) {
347
- await this.log('error', 'knowledge.promotion_failed', 'Knowledge analysis/promotion failed without advancing state.', {
348
- projectId,
349
- operationId,
350
- runId: claim.runId,
351
- commitSha: claim.commitSha,
352
- phase: 'promotion',
353
- error,
354
- });
355
- throw error;
356
- }
357
- }
358
-
359
- rollbackJournal(journal) {
360
- let conflict = null;
361
- for (const operation of [...journal.operations].reverse()) {
362
- if (!operation.applied) continue;
363
- const currentHash = fileHash(operation.target);
364
- const expectedApplied = operation.operation === 'delete' ? null : operation.newHash;
365
- if (currentHash !== expectedApplied) {
366
- conflict = operation.path;
367
- break;
368
- }
369
- if (operation.originalExists) this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.backupPath));
370
- else if (fs.existsSync(operation.target)) fs.unlinkSync(operation.target);
371
- }
372
- if (conflict) {
373
- journal.phase = 'recovery-conflict';
374
- journal.error = `User-visible knowledge changed after crash: ${conflict}`;
375
- } else {
376
- journal.phase = 'rolled-back';
377
- journal.rolledBackAt = new Date().toISOString();
378
- }
379
- this.writeJournal(journal);
380
- return { ok: !conflict, phase: journal.phase, conflict };
381
- }
382
-
383
- async recoverJournal(journal) {
384
- if (journal.phase === 'completed' || journal.phase === 'rolled-back') return { ok: true, phase: journal.phase, skipped: true };
385
- const appliedCount = journal.operations.filter(operation => operation.applied).length;
386
- const allApplied = appliedCount === journal.operations.length;
387
- if (journal.phase === 'awaiting-state-advance' || (allApplied && ['applying', 'prepared'].includes(journal.phase))) {
388
- this.verifyPromoted(journal);
389
- await this.advanceState(journal);
390
- journal.phase = 'completed';
391
- journal.recoveredAt = new Date().toISOString();
392
- this.writeJournal(journal);
393
- if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(journal.projectId).catch(() => {});
394
- return { ok: true, phase: 'completed', stateAdvanced: true };
395
- }
396
- return this.rollbackJournal(journal);
397
- }
398
-
399
- async recoverAll() {
400
- const root = this.layout.getRuntimePath('promotions');
401
- if (!fs.existsSync(root)) return [];
402
- const files = [];
403
- const walk = current => {
404
- for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
405
- const absolute = path.join(current, entry.name);
406
- if (entry.isDirectory()) walk(absolute);
407
- else if (entry.isFile() && entry.name.endsWith('.json')) files.push(absolute);
408
- }
409
- };
410
- walk(root);
411
- const results = [];
412
- for (const file of files.sort()) {
413
- const journal = this.atomic.readJsonStrict(file, {
414
- category: 'promotion-journal',
415
- validate: value => {
416
- if (!value || value.schema !== JOURNAL_SCHEMA || !Array.isArray(value.operations)) throw new DomainError('DATA_CORRUPT', 'Promotion journal is corrupt.', { status: 500 });
417
- return value;
418
- },
419
- });
420
- results.push({ file, ...(await this.recoverJournal(journal)) });
421
- }
422
- return results;
423
- }
424
- }
425
-
426
- module.exports = {
427
- JOURNAL_SCHEMA,
428
- MANIFEST_SCHEMA,
429
- MAX_KNOWLEDGE_FILE_BYTES,
430
- KnowledgePromotionService,
431
- canonicalRelativePath,
432
- fileHash,
433
- hashBuffer,
434
- validateMarkdown,
435
- };
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { TextDecoder } = require('util');
5
+ const AtomicFile = require('./atomic-file');
6
+ const { DomainError, createId, validateProjectId } = require('./contracts');
7
+ const { StorageLayout } = require('./storage-layout');
8
+ const { ProjectStore } = require('./project-store');
9
+ const { buildAutomationToolPolicy } = require('./automation-config');
10
+ const { execGit } = require('./git-runner');
11
+
12
+ const MANIFEST_SCHEMA = 'knowledge-staging-manifest/v1';
13
+ const JOURNAL_SCHEMA = 'promotion-journal/v1';
14
+ const JOURNAL_SCHEMA_V2 = 'promotion-journal/v2';
15
+ const JOURNAL_SCHEMAS = [JOURNAL_SCHEMA, JOURNAL_SCHEMA_V2];
16
+ const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
17
+ const MAX_KNOWLEDGE_FILE_BYTES = 1024 * 1024;
18
+ const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
19
+
20
+ function validateRunIdSegment(runId) {
21
+ const value = String(runId || '');
22
+ if (!RUN_ID_PATTERN.test(value)) {
23
+ throw new DomainError('DATA_CORRUPT', 'Promotion journal run id is invalid.', { status: 500 });
24
+ }
25
+ return value;
26
+ }
27
+
28
+ function hashBuffer(value) {
29
+ return `sha256:${crypto.createHash('sha256').update(value).digest('hex')}`;
30
+ }
31
+
32
+ function fileHash(filePath) {
33
+ return fs.existsSync(filePath) && fs.statSync(filePath).isFile()
34
+ ? hashBuffer(fs.readFileSync(filePath))
35
+ : null;
36
+ }
37
+
38
+ function canonicalRelativePath(value) {
39
+ const raw = String(value || '');
40
+ if (!raw || raw.includes('\\') || raw.includes('\u0000') || path.posix.isAbsolute(raw) || path.win32.isAbsolute(raw)) {
41
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path must be a canonical relative POSIX path.');
42
+ }
43
+ const segments = raw.split('/');
44
+ if (segments.some(segment => !segment || segment === '.' || segment === '..' || segment.includes(':') || /[. ]$/.test(segment) || WINDOWS_RESERVED.test(segment))) {
45
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path contains an unsafe segment.');
46
+ }
47
+ if (!raw.toLowerCase().endsWith('.md') || segments.some(segment => segment.toLowerCase() === '00-index.md')) {
48
+ throw new DomainError('INVALID_ARGUMENT', 'Knowledge operations may target non-derived Markdown files only.');
49
+ }
50
+ const topLevel = segments.length === 1 && ['README.md', 'GOAL.md', 'ARCHITECTURE.md'].includes(segments[0]);
51
+ const collection = segments.length >= 2 && ['modules', 'changes'].includes(segments[0]);
52
+ if (!topLevel && !collection) throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path is outside the allowed knowledge structure.');
53
+ return raw;
54
+ }
55
+
56
+ function decodeUtf8(buffer) {
57
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(buffer); }
58
+ catch (error) { throw new DomainError('INVALID_ARGUMENT', 'Staged Markdown must be valid UTF-8.', { cause: error }); }
59
+ }
60
+
61
+ function validateMarkdown(content, relativePath) {
62
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(content)) {
63
+ throw new DomainError('INVALID_ARGUMENT', `Staged Markdown contains disallowed control characters: ${relativePath}.`);
64
+ }
65
+ if (!content.trim() || !/^#\s+\S+/m.test(content)) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown must contain a title: ${relativePath}.`);
66
+ if (/(?:\[TODO:|\bTODO:\s|\bTBD\b|PLACEHOLDER)/i.test(content)) throw new DomainError('INVALID_ARGUMENT', `Placeholder knowledge is not allowed: ${relativePath}.`);
67
+ const fences = content.match(/^```/gm) || [];
68
+ if (fences.length % 2 !== 0) throw new DomainError('INVALID_ARGUMENT', `Markdown code fences are unbalanced: ${relativePath}.`);
69
+ if (content.startsWith('---\n') && !/^---\n[\s\S]*?\n---\n/.test(content)) {
70
+ throw new DomainError('INVALID_ARGUMENT', `Markdown frontmatter is incomplete: ${relativePath}.`);
71
+ }
72
+ return true;
73
+ }
74
+
75
+ async function gitStatus(repoPath) {
76
+ if (!repoPath || !fs.existsSync(repoPath)) return null;
77
+ const result = await execGit(repoPath, ['status', '--porcelain=v1', '-z'], 15_000);
78
+ return result && result.ok ? String(result.stdout || '') : null;
79
+ }
80
+
81
+ class KnowledgePromotionService {
82
+ constructor(options = {}) {
83
+ this.layout = options.layout || new StorageLayout(options);
84
+ this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
85
+ this.analyzer = options.analyzer || null;
86
+ this.indexService = options.indexService || null;
87
+ this.atomic = options.atomic || AtomicFile;
88
+ this.logger = options.logger || null;
89
+ this.maxFileBytes = Number(options.maxFileBytes || MAX_KNOWLEDGE_FILE_BYTES);
90
+ this.fault = options.fault || (() => {});
91
+ }
92
+
93
+ runRoot(projectId, runId) { return this.layout.getRuntimePath('runs', validateProjectId(projectId), String(runId)); }
94
+ stagingPath(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'output'); }
95
+ evidenceRoot(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'input', 'evidence'); }
96
+
97
+ manifestPath(projectId, runId) { return path.join(this.stagingPath(projectId, runId), 'manifest.json'); }
98
+ journalPath(projectId, runId) { return this.layout.getRuntimePath('promotions', validateProjectId(projectId), `${runId}.json`); }
99
+ backupRoot(projectId, runId) { return this.layout.getRecoveryPath('promotions', validateProjectId(projectId), String(runId)); }
100
+
101
+ async log(level, event, message, context) {
102
+ if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
103
+ }
104
+
105
+ prepareStaging(projectId, runId) {
106
+ const staging = this.stagingPath(projectId, runId);
107
+ if (fs.existsSync(staging)) {
108
+ const entries = fs.readdirSync(staging);
109
+ if (entries.length) {
110
+ const journalFile = this.journalPath(projectId, runId);
111
+ if (!fs.existsSync(journalFile)) {
112
+ fs.rmSync(staging, { recursive: true, force: true });
113
+ } else {
114
+ const journal = this.atomic.readJsonStrict(journalFile, { category: 'promotion-journal' });
115
+ if (journal.phase === 'rolled-back') fs.rmSync(staging, { recursive: true, force: true });
116
+ else throw new DomainError('MIGRATION_TARGET_CONFLICT', 'Run staging is owned by an unfinished promotion journal.', { status: 409 });
117
+ }
118
+ }
119
+ }
120
+ fs.mkdirSync(path.join(staging, 'files'), { recursive: true });
121
+ return staging;
122
+ }
123
+
124
+ readManifest(projectId, runId) {
125
+ return this.atomic.readJsonStrict(this.manifestPath(projectId, runId), {
126
+ category: 'knowledge-staging-manifest',
127
+ validate: manifest => {
128
+ if (!manifest || manifest.schema !== MANIFEST_SCHEMA || manifest.projectId !== projectId || manifest.runId !== runId || !Array.isArray(manifest.operations)) {
129
+ throw new DomainError('DATA_CORRUPT', 'Knowledge staging manifest is invalid.', { status: 500 });
130
+ }
131
+ return manifest;
132
+ },
133
+ });
134
+ }
135
+
136
+ validateManifest(input) {
137
+ const { projectId, config, claim } = input;
138
+ const manifest = this.readManifest(projectId, claim.runId);
139
+ if (manifest.commitSha !== claim.commitSha || manifest.operations.length === 0) {
140
+ throw new DomainError('INVALID_ARGUMENT', 'Manifest must contain operations for the active commit.');
141
+ }
142
+ const seen = new Set();
143
+ const operations = [];
144
+ for (const [index, raw] of manifest.operations.entries()) {
145
+ const relativePath = canonicalRelativePath(raw.path);
146
+ if (seen.has(relativePath.toLowerCase())) throw new DomainError('INVALID_ARGUMENT', `Duplicate manifest path: ${relativePath}.`);
147
+ seen.add(relativePath.toLowerCase());
148
+ const operation = String(raw.operation || '');
149
+ if (!['create', 'replace', 'delete'].includes(operation)) throw new DomainError('INVALID_ARGUMENT', `Invalid manifest operation: ${operation}.`);
150
+ if (!String(raw.reason || '').trim() || !Array.isArray(raw.evidenceReferences) || raw.evidenceReferences.length === 0) {
151
+ throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks reason/evidence: ${relativePath}.`);
152
+ }
153
+ const evidenceReferences = raw.evidenceReferences.map(String);
154
+ const requiredEvidence = [
155
+ `commit:${claim.commitSha}`,
156
+ claim.patchHash && `patch:${claim.patchHash}`,
157
+ claim.conversationSnapshotHash && `conversation:${claim.conversationSnapshotHash}`,
158
+ claim.retrievalManifestHash && `retrieval:${claim.retrievalManifestHash}`,
159
+ ].filter(Boolean);
160
+ const missingEvidence = requiredEvidence.filter(reference => !evidenceReferences.includes(reference));
161
+ if (missingEvidence.length) {
162
+ throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks frozen claim evidence: ${relativePath}.`, {
163
+ details: { missingEvidence },
164
+ });
165
+ }
166
+ const target = path.resolve(config.knowledgePath, ...relativePath.split('/'));
167
+ if (!this.layout.isPathInside(config.knowledgePath, target, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge path escapes its project: ${relativePath}.`);
168
+ const targetExists = fs.existsSync(target);
169
+ if (targetExists && fs.lstatSync(target).isSymbolicLink()) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge target is a symlink: ${relativePath}.`);
170
+ if (operation === 'create' && targetExists) throw new DomainError('MIGRATION_TARGET_CONFLICT', `Create target already exists: ${relativePath}.`, { status: 409 });
171
+ if ((operation === 'replace' || operation === 'delete') && (!targetExists || !fs.statSync(target).isFile())) {
172
+ throw new DomainError('INVALID_ARGUMENT', `${operation} target is not an owned project knowledge file: ${relativePath}.`);
173
+ }
174
+ let stagedPath = null;
175
+ let newHash = null;
176
+ if (operation !== 'delete') {
177
+ stagedPath = path.join(this.stagingPath(projectId, claim.runId), 'files', ...relativePath.split('/'));
178
+ if (!fs.existsSync(stagedPath) || !fs.statSync(stagedPath).isFile() || fs.lstatSync(stagedPath).isSymbolicLink()) {
179
+ throw new DomainError('INVALID_ARGUMENT', `Staged Markdown is missing or unsafe: ${relativePath}.`);
180
+ }
181
+ const realStaged = fs.realpathSync(stagedPath);
182
+ if (!this.layout.isPathInside(this.stagingPath(projectId, claim.runId), realStaged, { realpath: true })) {
183
+ throw new DomainError('PATH_OUTSIDE_ROOT', `Staged file escapes run staging: ${relativePath}.`);
184
+ }
185
+ const buffer = fs.readFileSync(stagedPath);
186
+ if (buffer.length > this.maxFileBytes) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown exceeds size limit: ${relativePath}.`);
187
+ const content = decodeUtf8(buffer);
188
+ validateMarkdown(content, relativePath);
189
+ newHash = hashBuffer(buffer);
190
+ if (raw.sha256 !== newHash) throw new DomainError('DATA_CORRUPT', `Staged Markdown hash mismatch: ${relativePath}.`, { status: 409 });
191
+ } else if (raw.sha256 != null) {
192
+ throw new DomainError('INVALID_ARGUMENT', `Delete operation must not declare a new hash: ${relativePath}.`);
193
+ }
194
+ operations.push({
195
+ index,
196
+ path: relativePath,
197
+ operation,
198
+ reason: String(raw.reason),
199
+ evidenceReferences,
200
+ target,
201
+ stagedPath,
202
+ originalExists: targetExists,
203
+ originalHash: targetExists ? fileHash(target) : null,
204
+ newHash,
205
+ });
206
+ }
207
+ return { manifest, operations: operations.sort((left, right) => left.path.localeCompare(right.path)) };
208
+ }
209
+
210
+ // New journals (v2) persist only relative references: the knowledge-relative
211
+ // operation path plus a backup file name inside the run's recovery root.
212
+ // Absolute locations are re-derived on every read, so a renamed or moved
213
+ // data directory never leaves a journal pointing at stale paths.
214
+ writeJournal(journal) {
215
+ journal.updatedAt = new Date().toISOString();
216
+ const { operations, ...head } = journal;
217
+ const payload = {
218
+ schema: JOURNAL_SCHEMA_V2,
219
+ ...head,
220
+ operations: (operations || []).map(operation => {
221
+ const { target, stagedPath, backupPath, ...relative } = operation;
222
+ void target; void stagedPath; void backupPath;
223
+ return { ...relative, rolledBack: operation.rolledBack === true };
224
+ }),
225
+ };
226
+ this.atomic.writeJsonAtomic(this.journalPath(journal.projectId, journal.runId), payload);
227
+ }
228
+
229
+ // Recompute absolute locations for a journal read from disk (either schema)
230
+ // against the RUNNING layout and the CURRENTLY registered knowledge
231
+ // directory. A journal whose recorded knowledge root no longer matches the
232
+ // registration is a path conflict: the site stays untouched and recovery
233
+ // reports a diagnosable conflict instead of writing into the wrong tree.
234
+ resolveJournalLocations(journal, config) {
235
+ const projectId = validateProjectId(journal.projectId);
236
+ const runId = validateRunIdSegment(journal.runId);
237
+ if (!config || !config.knowledgePath) {
238
+ throw new DomainError('MIGRATION_TARGET_CONFLICT', `Project ${projectId} has no registered knowledge directory; promotion journal ${runId} cannot be located.`, { status: 409 });
239
+ }
240
+ if (journal.knowledgePath && !this.layout.pathsEqual(journal.knowledgePath, config.knowledgePath)) {
241
+ throw new DomainError('MIGRATION_TARGET_CONFLICT', `Knowledge directory for project ${projectId} changed since promotion journal ${runId} was written; preserving the site.`, {
242
+ status: 409,
243
+ details: { journalKnowledgePath: journal.knowledgePath, registeredKnowledgePath: config.knowledgePath },
244
+ });
245
+ }
246
+ const backupRoot = this.backupRoot(projectId, runId);
247
+ const runRoot = this.layout.getRuntimePath('runs', projectId, runId, 'output');
248
+ journal.operations = (journal.operations || []).map((operation, index) => {
249
+ const relativePath = canonicalRelativePath(operation.path);
250
+ // Backup names follow the journal's own array position (the rule every
251
+ // version has used when writing); operation.index is the manifest order
252
+ // and must not pick the backup file.
253
+ const backupFile = operation.backupFile || `${String(index).padStart(4, '0')}.backup`;
254
+ return {
255
+ ...operation,
256
+ path: relativePath,
257
+ backupFile,
258
+ target: path.resolve(config.knowledgePath, ...relativePath.split('/')),
259
+ stagedPath: path.join(runRoot, 'files', ...relativePath.split('/')),
260
+ backupPath: operation.originalExists ? path.join(backupRoot, backupFile) : operation.backupPath || null,
261
+ };
262
+ });
263
+ return journal;
264
+ }
265
+
266
+ prepareJournal(projectId, config, claim, validated) {
267
+ const backupRoot = this.backupRoot(projectId, claim.runId);
268
+ const journal = {
269
+ schema: JOURNAL_SCHEMA_V2,
270
+ projectId,
271
+ runId: claim.runId,
272
+ commitSha: claim.commitSha,
273
+ claimFingerprint: claim.fingerprint,
274
+ evidence: {
275
+ promptHash: claim.promptHash || null,
276
+ patchHash: claim.patchHash || null,
277
+ evidenceManifestHash: claim.evidenceManifestHash || null,
278
+ conversationSnapshotHash: claim.conversationSnapshotHash || null,
279
+ retrievalManifestHash: claim.retrievalManifestHash || null,
280
+ },
281
+ knowledgePath: config.knowledgePath,
282
+ phase: 'preparing',
283
+ createdAt: new Date().toISOString(),
284
+ operations: validated.operations.map((operation, index) => ({
285
+ ...operation,
286
+ backupFile: `${String(index).padStart(4, '0')}.backup`,
287
+ backupPath: operation.originalExists ? path.join(backupRoot, `${String(index).padStart(4, '0')}.backup`) : null,
288
+ applied: false,
289
+ })),
290
+ };
291
+ this.writeJournal(journal);
292
+ for (const operation of journal.operations) {
293
+ if (!operation.originalExists) continue;
294
+ const currentHash = fileHash(operation.target);
295
+ if (currentHash !== operation.originalHash) throw new DomainError('PROJECT_BUSY', `Knowledge changed before backup: ${operation.path}.`, { status: 409, retryable: true });
296
+ this.atomic.writeFileAtomic(operation.backupPath, fs.readFileSync(operation.target));
297
+ if (fileHash(operation.backupPath) !== operation.originalHash) throw new DomainError('DATA_CORRUPT', `Knowledge backup verification failed: ${operation.path}.`, { status: 500 });
298
+ }
299
+ journal.phase = 'prepared';
300
+ this.writeJournal(journal);
301
+ this.fault('journal-prepared', journal);
302
+ return journal;
303
+ }
304
+
305
+ applyJournal(journal) {
306
+ journal.phase = 'applying';
307
+ this.writeJournal(journal);
308
+ for (let index = 0; index < journal.operations.length; index += 1) {
309
+ const operation = journal.operations[index];
310
+ const currentHash = fileHash(operation.target);
311
+ if (currentHash !== operation.originalHash) {
312
+ throw new DomainError('PROJECT_BUSY', `Knowledge changed before promotion: ${operation.path}.`, { status: 409, retryable: true });
313
+ }
314
+ if (operation.operation === 'delete') fs.unlinkSync(operation.target);
315
+ else this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.stagedPath));
316
+ operation.applied = true;
317
+ this.writeJournal(journal);
318
+ this.fault(`operation-applied:${index}`, journal);
319
+ }
320
+ this.verifyPromoted(journal);
321
+ journal.phase = 'awaiting-state-advance';
322
+ this.writeJournal(journal);
323
+ this.fault('promotion-verified', journal);
324
+ return journal;
325
+ }
326
+
327
+ verifyPromoted(journal) {
328
+ for (const operation of journal.operations) {
329
+ const actual = fileHash(operation.target);
330
+ if (operation.operation === 'delete' ? actual !== null : actual !== operation.newHash) {
331
+ throw new DomainError('DATA_CORRUPT', `Promoted knowledge verification failed: ${operation.path}.`, { status: 500 });
332
+ }
333
+ }
334
+ return true;
335
+ }
336
+
337
+ async advanceState(journal) {
338
+ const current = this.projectStore.readState(journal.projectId);
339
+ if (current.lastAnalyzedCommit === journal.commitSha && !current.analysis.activeClaim) return current;
340
+ const advanced = await this.projectStore.updateState(journal.projectId, state => {
341
+ const active = state.analysis.activeClaim;
342
+ if (!active || active.runId !== journal.runId || active.commitSha !== journal.commitSha || active.fingerprint !== journal.claimFingerprint) {
343
+ throw new DomainError('PROJECT_BUSY', 'Promotion journal no longer matches the active claim.', { status: 409, retryable: true });
344
+ }
345
+ state.lastAnalyzedCommit = journal.commitSha;
346
+ state.analysis.consumedRequirementIds = [...new Set([
347
+ ...(state.analysis.consumedRequirementIds || []),
348
+ ...(active.requirementIds || []),
349
+ ])];
350
+ state.analysis.activeClaim = null;
351
+ state.analysis.status = 'state.advanced';
352
+ state.analysis.lastError = null;
353
+ state.index.dirty = true;
354
+ state.index.sinceCommit = state.index.sinceCommit || journal.commitSha;
355
+ state.index.generation = Number(state.index.generation || 0) + 1;
356
+ state.index.lastError = null;
357
+ });
358
+ this.fault('state-advanced', journal);
359
+ return advanced;
360
+ }
361
+
362
+ async processClaim(input = {}) {
363
+ const projectId = validateProjectId(input.projectId);
364
+ const config = input.config || this.projectStore.readConfig(projectId);
365
+ const claim = input.claim;
366
+ if (!claim || claim.projectId !== projectId || !claim.runId || !claim.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Active claim is required for knowledge promotion.');
367
+ const operationId = input.operationId || claim.operationId || createId('op');
368
+ const stagingPath = this.prepareStaging(projectId, claim.runId);
369
+ const beforeSource = await gitStatus(config.repoPath);
370
+ try {
371
+ if (!this.analyzer || typeof this.analyzer.runClaim !== 'function') throw new DomainError('INVALID_ARGUMENT', 'Knowledge analyzer is unavailable.', { status: 503, retryable: true });
372
+ const analyzerResult = await this.analyzer.runClaim({
373
+ ...input,
374
+ projectId,
375
+ config,
376
+ claim,
377
+ stagingPath,
378
+ manifestPath: this.manifestPath(projectId, claim.runId),
379
+ evidenceRoot: this.evidenceRoot(projectId, claim.runId),
380
+ safetyPolicy: buildAutomationToolPolicy({
381
+ stagingPath,
382
+ evidenceRoot: this.evidenceRoot(projectId, claim.runId),
383
+ }),
384
+ });
385
+ if (analyzerResult && analyzerResult.ok === false) throw new DomainError('INVALID_ARGUMENT', analyzerResult.error || 'Knowledge analyzer failed.', { status: 500, retryable: true });
386
+ const afterSource = await gitStatus(config.repoPath);
387
+ if (beforeSource != null && afterSource != null && beforeSource !== afterSource) {
388
+ throw new DomainError('PROJECT_BUSY', 'Source repository changed during knowledge analysis.', { status: 409, retryable: true });
389
+ }
390
+ this.fault('analysis-completed', { projectId, claim, stagingPath });
391
+ const validated = this.validateManifest({ projectId, config, claim });
392
+ this.fault('manifest-validated', validated);
393
+ const journal = this.prepareJournal(projectId, config, claim, validated);
394
+ this.applyJournal(journal);
395
+ await this.advanceState(journal);
396
+ journal.phase = 'completed';
397
+ journal.completedAt = new Date().toISOString();
398
+ this.writeJournal(journal);
399
+ await this.log('info', 'knowledge.promotion_completed', 'Validated knowledge was promoted and state advanced.', {
400
+ projectId,
401
+ operationId,
402
+ runId: claim.runId,
403
+ commitSha: claim.commitSha,
404
+ phase: 'state.advanced',
405
+ operationCount: journal.operations.length,
406
+ });
407
+ if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(projectId).catch(() => {});
408
+ return { ok: true, stateAdvanced: true, projectId, runId: claim.runId, commitSha: claim.commitSha, operations: journal.operations.length };
409
+ } catch (error) {
410
+ await this.log('error', 'knowledge.promotion_failed', 'Knowledge analysis/promotion failed without advancing state.', {
411
+ projectId,
412
+ operationId,
413
+ runId: claim.runId,
414
+ commitSha: claim.commitSha,
415
+ phase: 'promotion',
416
+ error,
417
+ });
418
+ throw error;
419
+ }
420
+ }
421
+
422
+ // Rollback is safe to re-enter: an operation already restored to its
423
+ // original hash (or removed, when it never existed) is recognized as done
424
+ // instead of a conflict, and every restore is journalled before moving on.
425
+ rollbackJournal(journal) {
426
+ let conflict = null;
427
+ for (const operation of [...journal.operations].reverse()) {
428
+ if (!operation.applied || operation.rolledBack === true) continue;
429
+ const currentHash = fileHash(operation.target);
430
+ const expectedApplied = operation.operation === 'delete' ? null : operation.newHash;
431
+ const alreadyRestored = operation.originalExists
432
+ ? currentHash === operation.originalHash
433
+ : currentHash === null;
434
+ if (currentHash !== expectedApplied && !alreadyRestored) {
435
+ conflict = `${operation.path} (target no longer the promoted version)`;
436
+ break;
437
+ }
438
+ if (!alreadyRestored) {
439
+ if (operation.originalExists) {
440
+ if (!fs.existsSync(operation.backupPath)) {
441
+ conflict = `${operation.path} (backup missing)`;
442
+ break;
443
+ }
444
+ if (fileHash(operation.backupPath) !== operation.originalHash) {
445
+ conflict = `${operation.path} (backup content does not match originalHash)`;
446
+ break;
447
+ }
448
+ this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.backupPath));
449
+ } else if (fs.existsSync(operation.target)) fs.unlinkSync(operation.target);
450
+ }
451
+ operation.rolledBack = true;
452
+ this.writeJournal(journal);
453
+ this.fault(`operation-rolled-back:${operation.index}`, journal);
454
+ }
455
+ if (conflict) {
456
+ journal.phase = 'recovery-conflict';
457
+ journal.error = `User-visible knowledge changed after crash: ${conflict}`;
458
+ } else {
459
+ journal.phase = 'rolled-back';
460
+ journal.rolledBackAt = new Date().toISOString();
461
+ }
462
+ this.writeJournal(journal);
463
+ return { ok: !conflict, phase: journal.phase, conflict };
464
+ }
465
+
466
+ async recoverJournal(journal) {
467
+ if (journal.phase === 'completed' || journal.phase === 'rolled-back') return { ok: true, phase: journal.phase, skipped: true };
468
+ const config = this.projectStore.readConfig(journal.projectId);
469
+ this.resolveJournalLocations(journal, config);
470
+ // An operation may still carry applied=true from before a partially
471
+ // completed rollback; once restored it is no longer promoted, so the
472
+ // advance path must not treat the journal as fully applied.
473
+ const promotedCount = journal.operations.filter(operation => operation.applied && operation.rolledBack !== true).length;
474
+ const allApplied = promotedCount === journal.operations.length;
475
+ if (journal.phase === 'awaiting-state-advance' || (allApplied && ['applying', 'prepared'].includes(journal.phase))) {
476
+ try {
477
+ this.verifyPromoted(journal);
478
+ } catch (error) {
479
+ if (error instanceof DomainError && error.code === 'DATA_CORRUPT') {
480
+ // The target stopped matching what this promotion wrote (user edit or
481
+ // external corruption): preserve the site and report the conflict.
482
+ journal.phase = 'recovery-conflict';
483
+ journal.error = `Promoted knowledge no longer matches the promotion journal: ${error.message}`;
484
+ this.writeJournal(journal);
485
+ return { ok: false, phase: 'recovery-conflict', conflict: journal.error };
486
+ }
487
+ throw error;
488
+ }
489
+ await this.advanceState(journal);
490
+ journal.phase = 'completed';
491
+ journal.recoveredAt = new Date().toISOString();
492
+ this.writeJournal(journal);
493
+ if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(journal.projectId).catch(() => {});
494
+ return { ok: true, phase: 'completed', stateAdvanced: true };
495
+ }
496
+ return this.rollbackJournal(journal);
497
+ }
498
+
499
+ async recoverAll() {
500
+ const root = this.layout.getRuntimePath('promotions');
501
+ if (!fs.existsSync(root)) return [];
502
+ const files = [];
503
+ const walk = current => {
504
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
505
+ const absolute = path.join(current, entry.name);
506
+ if (entry.isDirectory()) walk(absolute);
507
+ else if (entry.isFile() && entry.name.endsWith('.json')) files.push(absolute);
508
+ }
509
+ };
510
+ walk(root);
511
+ const results = [];
512
+ for (const file of files.sort()) {
513
+ const journal = this.atomic.readJsonStrict(file, {
514
+ category: 'promotion-journal',
515
+ validate: value => {
516
+ if (!value || !JOURNAL_SCHEMAS.includes(value.schema) || !Array.isArray(value.operations)) throw new DomainError('DATA_CORRUPT', 'Promotion journal is corrupt.', { status: 500 });
517
+ return value;
518
+ },
519
+ });
520
+ // One broken or conflicting journal must neither abort the recovery
521
+ // sweep nor mutate an ambiguous site: it lands in a diagnosable
522
+ // recovery-conflict state and its evidence stays on disk.
523
+ try {
524
+ results.push({ file, ...(await this.recoverJournal(journal)) });
525
+ } catch (error) {
526
+ if (error instanceof DomainError && error.code === 'DATA_CORRUPT') throw error;
527
+ journal.phase = 'recovery-conflict';
528
+ journal.error = String(error && error.message || error);
529
+ this.writeJournal(journal);
530
+ results.push({ file, ok: false, phase: 'recovery-conflict', error: journal.error, conflict: journal.error });
531
+ }
532
+ }
533
+ return results;
534
+ }
535
+ }
536
+
537
+ module.exports = {
538
+ JOURNAL_SCHEMA,
539
+ JOURNAL_SCHEMA_V2,
540
+ MANIFEST_SCHEMA,
541
+ MAX_KNOWLEDGE_FILE_BYTES,
542
+ KnowledgePromotionService,
543
+ canonicalRelativePath,
544
+ fileHash,
545
+ hashBuffer,
546
+ validateMarkdown,
547
+ };