@sanqianx/project-knowledge 4.6.1 → 4.8.0

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 (198) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +817 -780
  4. package/README.md +48 -36
  5. package/_modules/knowledge-engine/README.md +88 -0
  6. package/_modules/knowledge-engine/package.json +38 -0
  7. package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
  8. package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
  9. package/_modules/knowledge-engine/src/bin.js +52 -0
  10. package/_modules/knowledge-engine/src/bridge-client.js +24 -0
  11. package/_modules/knowledge-engine/src/coordinator.js +255 -0
  12. package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
  13. package/_modules/knowledge-engine/src/memories.js +85 -0
  14. package/_modules/knowledge-engine/src/migration.js +88 -0
  15. package/_modules/knowledge-engine/src/retrieval.js +116 -0
  16. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  17. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  18. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  22. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  23. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  24. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  26. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  27. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  28. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  30. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  31. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  32. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  33. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  34. package/_modules/knowledge-engine/src/server.js +155 -0
  35. package/_modules/knowledge-engine/src/store.js +239 -0
  36. package/_modules/knowledge-engine/ui/app.css +172 -0
  37. package/_modules/knowledge-engine/ui/app.js +297 -0
  38. package/_modules/knowledge-engine/ui/index.html +95 -0
  39. package/_site/README.md +30 -30
  40. package/_site/_test/ai-profile-resolver-test.js +137 -137
  41. package/_site/_test/automation-queue-test.js +14 -14
  42. package/_site/_test/automation-ui-test.js +40 -40
  43. package/_site/_test/background-task-registry-test.js +43 -43
  44. package/_site/_test/baseline-schema-test.js +91 -91
  45. package/_site/_test/bridge-adapter-test.js +1 -1
  46. package/_site/_test/bridge-consumer-service-test.js +1 -1
  47. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  48. package/_site/_test/claude-executable-discovery-test.js +62 -62
  49. package/_site/_test/claude-workbench-test.js +170 -170
  50. package/_site/_test/client-capture-restart-e2e-test.js +4 -4
  51. package/_site/_test/codex-conversation-projection-test.js +2 -1
  52. package/_site/_test/commit-boundary-freeze-test.js +1 -1
  53. package/_site/_test/commit-conversation-binding-test.js +95 -95
  54. package/_site/_test/commit-evidence-test.js +110 -110
  55. package/_site/_test/conversation-api-test.js +109 -109
  56. package/_site/_test/conversation-store-test.js +136 -136
  57. package/_site/_test/cross-repo-isolation-e2e-test.js +2 -2
  58. package/_site/_test/data-dir-migration-test.js +57 -57
  59. package/_site/_test/desktop-browser-compat-test.js +28 -28
  60. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  61. package/_site/_test/explicit-commit-processor-test.js +37 -37
  62. package/_site/_test/fixtures/make-git-repos.js +12 -1
  63. package/_site/_test/folder-picker-output-test.js +19 -19
  64. package/_site/_test/full-integration-e2e-test.js +165 -165
  65. package/_site/_test/git-validation-test.js +2 -2
  66. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  67. package/_site/_test/hook-status-repair-api-test.js +152 -152
  68. package/_site/_test/hook-trigger-test.js +85 -85
  69. package/_site/_test/import-preflight-api-test.js +234 -233
  70. package/_site/_test/index-writer-concurrency-test.js +135 -135
  71. package/_site/_test/integration-adapters-test.js +171 -171
  72. package/_site/_test/integration-capture-setup-test.js +1 -1
  73. package/_site/_test/integration-surface-coverage-test.js +164 -164
  74. package/_site/_test/knowledge-language-control-test.js +170 -170
  75. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  76. package/_site/_test/knowledge-query-test.js +54 -54
  77. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  78. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  79. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  80. package/_site/_test/legacy-forward-compat-test.js +257 -257
  81. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -363
  82. package/_site/_test/logging-api-test.js +89 -89
  83. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  84. package/_site/_test/logging-ui-test.js +106 -104
  85. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  86. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  87. package/_site/_test/mcp-server-test.js +149 -149
  88. package/_site/_test/module-artifact-integrity-test.js +27 -0
  89. package/_site/_test/module-boundary-test.js +30 -0
  90. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  91. package/_site/_test/module-model-configuration-test.js +43 -0
  92. package/_site/_test/module-process-lifecycle-test.js +24 -0
  93. package/_site/_test/module-stream-proxy-test.js +34 -0
  94. package/_site/_test/non-release-ci-test.js +34 -34
  95. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  96. package/_site/_test/p0-data-migration-characterization-test.js +37 -37
  97. package/_site/_test/p0-e2e-gate-test.js +347 -347
  98. package/_site/_test/packaged-ui-smoke-test.js +19 -10
  99. package/_site/_test/path-consistency-test.js +151 -151
  100. package/_site/_test/pending-sweep-test.js +9 -9
  101. package/_site/_test/post-commit-automation-test.js +87 -87
  102. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  103. package/_site/_test/product-import-ui-test.js +92 -0
  104. package/_site/_test/project-delete-recovery-test.js +64 -64
  105. package/_site/_test/project-goal-editor-test.js +144 -144
  106. package/_site/_test/project-layout-v2-migration-test.js +127 -127
  107. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  108. package/_site/_test/prompt-settings-test.js +115 -115
  109. package/_site/_test/protected-architecture-gate-test.js +122 -122
  110. package/_site/_test/refactor-characterization-test.js +36 -36
  111. package/_site/_test/release-version-sync-test.js +1 -1
  112. package/_site/_test/requirement-recorder-test.js +173 -173
  113. package/_site/_test/run-all-tests.js +159 -156
  114. package/_site/_test/server-runtime-migration-safety-test.js +27 -27
  115. package/_site/_test/shared-contracts-test.js +58 -58
  116. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  117. package/_site/_test/storage-foundation-test.js +78 -78
  118. package/_site/_test/structured-logger-test.js +101 -101
  119. package/_site/_test/tracking-start-test.js +108 -108
  120. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -56
  121. package/_site/_test/workbench-permission-test.js +117 -117
  122. package/_site/_test/workspace-ui-contract-test.js +28 -43
  123. package/_site/lib/ai-profile-resolver.js +78 -78
  124. package/_site/lib/ai-workspace.js +101 -101
  125. package/_site/lib/automation-config.js +140 -140
  126. package/_site/lib/bridge-adapter.js +5 -1
  127. package/_site/lib/bridge-consumer-service.js +402 -402
  128. package/_site/lib/claude-cli-runner.js +1510 -1510
  129. package/_site/lib/commit-conversation-binder.js +234 -234
  130. package/_site/lib/commit-processing-ledger.js +27 -27
  131. package/_site/lib/commit-prompt.js +202 -202
  132. package/_site/lib/commit-reconciler.js +406 -406
  133. package/_site/lib/contracts.js +284 -279
  134. package/_site/lib/conversation-query-service.js +144 -144
  135. package/_site/lib/conversation-store.js +385 -385
  136. package/_site/lib/data-dir.js +74 -74
  137. package/_site/lib/data-state-classifier.js +40 -40
  138. package/_site/lib/engine-cutover.js +97 -0
  139. package/_site/lib/evidence-bundle.js +228 -228
  140. package/_site/lib/folder-picker-output.js +21 -21
  141. package/_site/lib/git-runner.js +62 -62
  142. package/_site/lib/github-team-store.js +1172 -1172
  143. package/_site/lib/hook-manager.js +203 -202
  144. package/_site/lib/index-service.js +173 -173
  145. package/_site/lib/integration-installer.js +907 -907
  146. package/_site/lib/kb-framework.js +176 -176
  147. package/_site/lib/kb-validator.js +124 -124
  148. package/_site/lib/knowledge-promotion.js +435 -435
  149. package/_site/lib/knowledge-retrieval-service.js +401 -401
  150. package/_site/lib/knowledge-tool-runtime.js +359 -359
  151. package/_site/lib/legacy-data-manifest.js +26 -26
  152. package/_site/lib/llm-client.js +161 -161
  153. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  154. package/_site/lib/migration-service.js +442 -442
  155. package/_site/lib/module-bridge.js +198 -33
  156. package/_site/lib/post-commit-automation.js +87 -87
  157. package/_site/lib/project-lifecycle-service.js +519 -497
  158. package/_site/lib/project-store.js +268 -262
  159. package/_site/lib/requirement-recorder.js +278 -278
  160. package/_site/lib/runtime-endpoint.js +155 -155
  161. package/_site/lib/scanner.js +298 -298
  162. package/_site/lib/server-app.js +1590 -1520
  163. package/_site/lib/settings-store.js +133 -113
  164. package/_site/lib/storage-layout.js +162 -162
  165. package/_site/lib/structured-logger.js +574 -574
  166. package/_site/scripts/folder-picker.ps1 +156 -156
  167. package/_site/scripts/hook-trigger.js +157 -156
  168. package/_site/scripts/install-module-candidates.js +69 -0
  169. package/_site/scripts/pack-module-candidates.js +72 -0
  170. package/_site/scripts/sync-release-version.js +2 -2
  171. package/_site/scripts/vendor-modules.js +47 -0
  172. package/_site/scripts/verify-module-runtime.js +45 -0
  173. package/_site/scripts/verify-product-runtime.js +34 -0
  174. package/bin/project-knowledge-mcp.js +194 -194
  175. package/docs/README.zh-CN.md +34 -25
  176. package/docs/project-registry-schema.md +22 -22
  177. package/docs/testing-strategy.md +33 -33
  178. package/module-runtime-manifest.json +220 -0
  179. package/package.json +13 -10
  180. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  181. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  182. package/plugins/project-knowledge/.mcp.json +1 -1
  183. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  184. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  185. package/templates/project-readme.md +34 -34
  186. package/ui/favicon.svg +38 -38
  187. package/ui/index.html +51 -149
  188. package/ui/product.css +9 -0
  189. package/ui/product.js +386 -0
  190. package/vendor-manifest.json +46 -0
  191. package/_site/_test/import-ui-flow-test.js +0 -171
  192. package/_site/_test/project-control-panel-task14-test.js +0 -63
  193. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  194. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  195. package/_site/_test/ui-smoke-test.js +0 -73
  196. package/ui/app.css +0 -58
  197. package/ui/app.js +0 -607
  198. package/ui/i18n.js +0 -146
@@ -0,0 +1,444 @@
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 { buildAutomationToolPolicy } = require('./automation-config');
8
+ const { execGit } = require('./git-runner');
9
+
10
+ const MANIFEST_SCHEMA = 'knowledge-staging-manifest/v1';
11
+ const JOURNAL_SCHEMA = 'promotion-journal/v1';
12
+ const MAX_KNOWLEDGE_FILE_BYTES = 1024 * 1024;
13
+ const WINDOWS_RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
14
+
15
+ function hashBuffer(value) {
16
+ return `sha256:${crypto.createHash('sha256').update(value).digest('hex')}`;
17
+ }
18
+
19
+ function fileHash(filePath) {
20
+ return fs.existsSync(filePath) && fs.statSync(filePath).isFile()
21
+ ? hashBuffer(fs.readFileSync(filePath))
22
+ : null;
23
+ }
24
+
25
+ function canonicalRelativePath(value) {
26
+ const raw = String(value || '');
27
+ if (!raw || raw.includes('\\') || raw.includes('\u0000') || path.posix.isAbsolute(raw) || path.win32.isAbsolute(raw)) {
28
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path must be a canonical relative POSIX path.');
29
+ }
30
+ const segments = raw.split('/');
31
+ if (segments.some(segment => !segment || segment === '.' || segment === '..' || segment.includes(':') || /[. ]$/.test(segment) || WINDOWS_RESERVED.test(segment))) {
32
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path contains an unsafe segment.');
33
+ }
34
+ if (!raw.toLowerCase().endsWith('.md') || segments.some(segment => segment.toLowerCase() === '00-index.md')) {
35
+ throw new DomainError('INVALID_ARGUMENT', 'Knowledge operations may target non-derived Markdown files only.');
36
+ }
37
+ const topLevel = segments.length === 1 && ['README.md', 'GOAL.md', 'ARCHITECTURE.md'].includes(segments[0]);
38
+ const collection = segments.length >= 2 && ['modules', 'changes'].includes(segments[0]);
39
+ if (!topLevel && !collection) throw new DomainError('PATH_OUTSIDE_ROOT', 'Manifest path is outside the allowed knowledge structure.');
40
+ return raw;
41
+ }
42
+
43
+ function decodeUtf8(buffer) {
44
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(buffer); }
45
+ catch (error) { throw new DomainError('INVALID_ARGUMENT', 'Staged Markdown must be valid UTF-8.', { cause: error }); }
46
+ }
47
+
48
+ function validateMarkdown(content, relativePath) {
49
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(content)) {
50
+ throw new DomainError('INVALID_ARGUMENT', `Staged Markdown contains disallowed control characters: ${relativePath}.`);
51
+ }
52
+ if (!content.trim() || !/^#\s+\S+/m.test(content)) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown must contain a title: ${relativePath}.`);
53
+ if (/(?:\[TODO:|\bTODO:\s|\bTBD\b|PLACEHOLDER)/i.test(content)) throw new DomainError('INVALID_ARGUMENT', `Placeholder knowledge is not allowed: ${relativePath}.`);
54
+ const fences = content.match(/^```/gm) || [];
55
+ if (fences.length % 2 !== 0) throw new DomainError('INVALID_ARGUMENT', `Markdown code fences are unbalanced: ${relativePath}.`);
56
+ if (content.startsWith('---\n') && !/^---\n[\s\S]*?\n---\n/.test(content)) {
57
+ throw new DomainError('INVALID_ARGUMENT', `Markdown frontmatter is incomplete: ${relativePath}.`);
58
+ }
59
+ return true;
60
+ }
61
+
62
+ async function gitStatus(repoPath) {
63
+ if (!repoPath || !fs.existsSync(repoPath)) return null;
64
+ const result = await execGit(repoPath, ['status', '--porcelain=v1', '-z'], 15_000);
65
+ return result && result.ok ? String(result.stdout || '') : null;
66
+ }
67
+
68
+ class KnowledgePromotionService {
69
+ constructor(options = {}) {
70
+ this.layout = options.layout;
71
+ this.projectStore = options.projectStore;
72
+ this.analyzer = options.analyzer || null;
73
+ this.indexService = options.indexService || null;
74
+ this.atomic = options.atomic || AtomicFile;
75
+ this.logger = options.logger || null;
76
+ this.maxFileBytes = Number(options.maxFileBytes || MAX_KNOWLEDGE_FILE_BYTES);
77
+ this.fault = options.fault || (() => {});
78
+ }
79
+
80
+ runRoot(projectId, runId) { return this.layout.getRuntimePath('runs', validateProjectId(projectId), String(runId)); }
81
+ stagingPath(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'output'); }
82
+ evidenceRoot(projectId, runId) { return path.join(this.runRoot(projectId, runId), 'input', 'evidence'); }
83
+
84
+ manifestPath(projectId, runId) { return path.join(this.stagingPath(projectId, runId), 'manifest.json'); }
85
+ journalPath(projectId, runId) { return this.layout.getRuntimePath('promotions', validateProjectId(projectId), `${runId}.json`); }
86
+ backupRoot(projectId, runId) { return this.layout.getRecoveryPath('promotions', validateProjectId(projectId), String(runId)); }
87
+
88
+ async log(level, event, message, context) {
89
+ if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
90
+ }
91
+
92
+ prepareStaging(projectId, runId) {
93
+ const staging = this.stagingPath(projectId, runId);
94
+ const discardStaging = () => {
95
+ if (!this.layout.isPathInside(this.runRoot(projectId, runId), staging, { realpath: true }) || fs.lstatSync(staging).isSymbolicLink()) throw new DomainError('PATH_OUTSIDE_ROOT', 'Unsafe staging cleanup.');
96
+ const remove = directory => {
97
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
98
+ const target = path.join(directory, entry.name);
99
+ if (entry.isDirectory() && !entry.isSymbolicLink()) remove(target); else fs.unlinkSync(target);
100
+ }
101
+ fs.rmdirSync(directory);
102
+ };
103
+ remove(staging);
104
+ };
105
+ if (fs.existsSync(staging)) {
106
+ const entries = fs.readdirSync(staging);
107
+ if (entries.length) {
108
+ const journalFile = this.journalPath(projectId, runId);
109
+ if (!fs.existsSync(journalFile)) {
110
+ discardStaging();
111
+ } else {
112
+ const journal = this.atomic.readJsonStrict(journalFile, { category: 'promotion-journal' });
113
+ if (journal.phase === 'rolled-back') discardStaging();
114
+ else throw new DomainError('MIGRATION_TARGET_CONFLICT', 'Run staging is owned by an unfinished promotion journal.', { status: 409 });
115
+ }
116
+ }
117
+ }
118
+ fs.mkdirSync(path.join(staging, 'files'), { recursive: true });
119
+ return staging;
120
+ }
121
+
122
+ readManifest(projectId, runId) {
123
+ return this.atomic.readJsonStrict(this.manifestPath(projectId, runId), {
124
+ category: 'knowledge-staging-manifest',
125
+ validate: manifest => {
126
+ if (!manifest || manifest.schema !== MANIFEST_SCHEMA || manifest.projectId !== projectId || manifest.runId !== runId || !Array.isArray(manifest.operations)) {
127
+ throw new DomainError('DATA_CORRUPT', 'Knowledge staging manifest is invalid.', { status: 500 });
128
+ }
129
+ return manifest;
130
+ },
131
+ });
132
+ }
133
+
134
+ validateManifest(input) {
135
+ const { projectId, config, claim } = input;
136
+ const manifest = this.readManifest(projectId, claim.runId);
137
+ if (manifest.commitSha !== claim.commitSha || manifest.operations.length === 0) {
138
+ throw new DomainError('INVALID_ARGUMENT', 'Manifest must contain operations for the active commit.');
139
+ }
140
+ const seen = new Set();
141
+ const operations = [];
142
+ for (const [index, raw] of manifest.operations.entries()) {
143
+ const relativePath = canonicalRelativePath(raw.path);
144
+ if (seen.has(relativePath.toLowerCase())) throw new DomainError('INVALID_ARGUMENT', `Duplicate manifest path: ${relativePath}.`);
145
+ seen.add(relativePath.toLowerCase());
146
+ const operation = String(raw.operation || '');
147
+ if (!['create', 'replace', 'delete'].includes(operation)) throw new DomainError('INVALID_ARGUMENT', `Invalid manifest operation: ${operation}.`);
148
+ if (!String(raw.reason || '').trim() || !Array.isArray(raw.evidenceReferences) || raw.evidenceReferences.length === 0) {
149
+ throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks reason/evidence: ${relativePath}.`);
150
+ }
151
+ const evidenceReferences = raw.evidenceReferences.map(String);
152
+ const requiredEvidence = [
153
+ `commit:${claim.commitSha}`,
154
+ claim.patchHash && `patch:${claim.patchHash}`,
155
+ claim.conversationSnapshotHash && `conversation:${claim.conversationSnapshotHash}`,
156
+ claim.retrievalManifestHash && `retrieval:${claim.retrievalManifestHash}`,
157
+ ].filter(Boolean);
158
+ const missingEvidence = requiredEvidence.filter(reference => !evidenceReferences.includes(reference));
159
+ if (missingEvidence.length) {
160
+ throw new DomainError('INVALID_ARGUMENT', `Manifest operation lacks frozen claim evidence: ${relativePath}.`, {
161
+ details: { missingEvidence },
162
+ });
163
+ }
164
+ const target = path.resolve(config.knowledgePath, ...relativePath.split('/'));
165
+ if (!this.layout.isPathInside(config.knowledgePath, target, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge path escapes its project: ${relativePath}.`);
166
+ const targetExists = fs.existsSync(target);
167
+ if (targetExists && fs.lstatSync(target).isSymbolicLink()) throw new DomainError('PATH_OUTSIDE_ROOT', `Final knowledge target is a symlink: ${relativePath}.`);
168
+ if (operation === 'create' && targetExists) throw new DomainError('MIGRATION_TARGET_CONFLICT', `Create target already exists: ${relativePath}.`, { status: 409 });
169
+ if ((operation === 'replace' || operation === 'delete') && (!targetExists || !fs.statSync(target).isFile())) {
170
+ throw new DomainError('INVALID_ARGUMENT', `${operation} target is not an owned project knowledge file: ${relativePath}.`);
171
+ }
172
+ let stagedPath = null;
173
+ let newHash = null;
174
+ if (operation !== 'delete') {
175
+ stagedPath = path.join(this.stagingPath(projectId, claim.runId), 'files', ...relativePath.split('/'));
176
+ if (!fs.existsSync(stagedPath) || !fs.statSync(stagedPath).isFile() || fs.lstatSync(stagedPath).isSymbolicLink()) {
177
+ throw new DomainError('INVALID_ARGUMENT', `Staged Markdown is missing or unsafe: ${relativePath}.`);
178
+ }
179
+ const realStaged = fs.realpathSync(stagedPath);
180
+ if (!this.layout.isPathInside(this.stagingPath(projectId, claim.runId), realStaged, { realpath: true })) {
181
+ throw new DomainError('PATH_OUTSIDE_ROOT', `Staged file escapes run staging: ${relativePath}.`);
182
+ }
183
+ const buffer = fs.readFileSync(stagedPath);
184
+ if (buffer.length > this.maxFileBytes) throw new DomainError('INVALID_ARGUMENT', `Staged Markdown exceeds size limit: ${relativePath}.`);
185
+ const content = decodeUtf8(buffer);
186
+ validateMarkdown(content, relativePath);
187
+ newHash = hashBuffer(buffer);
188
+ if (raw.sha256 !== newHash) throw new DomainError('DATA_CORRUPT', `Staged Markdown hash mismatch: ${relativePath}.`, { status: 409 });
189
+ } else if (raw.sha256 != null) {
190
+ throw new DomainError('INVALID_ARGUMENT', `Delete operation must not declare a new hash: ${relativePath}.`);
191
+ }
192
+ operations.push({
193
+ index,
194
+ path: relativePath,
195
+ operation,
196
+ reason: String(raw.reason),
197
+ evidenceReferences,
198
+ target,
199
+ stagedPath,
200
+ originalExists: targetExists,
201
+ originalHash: targetExists ? fileHash(target) : null,
202
+ newHash,
203
+ });
204
+ }
205
+ return { manifest, operations: operations.sort((left, right) => left.path.localeCompare(right.path)) };
206
+ }
207
+
208
+ writeJournal(journal) {
209
+ journal.updatedAt = new Date().toISOString();
210
+ this.atomic.writeJsonAtomic(this.journalPath(journal.projectId, journal.runId), journal);
211
+ }
212
+
213
+ prepareJournal(projectId, config, claim, validated) {
214
+ const backupRoot = this.backupRoot(projectId, claim.runId);
215
+ const journal = {
216
+ schema: JOURNAL_SCHEMA,
217
+ projectId,
218
+ runId: claim.runId,
219
+ commitSha: claim.commitSha,
220
+ claimFingerprint: claim.fingerprint,
221
+ evidence: {
222
+ promptHash: claim.promptHash || null,
223
+ patchHash: claim.patchHash || null,
224
+ evidenceManifestHash: claim.evidenceManifestHash || null,
225
+ conversationSnapshotHash: claim.conversationSnapshotHash || null,
226
+ retrievalManifestHash: claim.retrievalManifestHash || null,
227
+ },
228
+ knowledgePath: config.knowledgePath,
229
+ phase: 'preparing',
230
+ createdAt: new Date().toISOString(),
231
+ operations: validated.operations.map((operation, index) => ({
232
+ ...operation,
233
+ backupPath: operation.originalExists ? path.join(backupRoot, `${String(index).padStart(4, '0')}.backup`) : null,
234
+ applied: false,
235
+ })),
236
+ };
237
+ this.writeJournal(journal);
238
+ for (const operation of journal.operations) {
239
+ if (!operation.originalExists) continue;
240
+ const currentHash = fileHash(operation.target);
241
+ if (currentHash !== operation.originalHash) throw new DomainError('PROJECT_BUSY', `Knowledge changed before backup: ${operation.path}.`, { status: 409, retryable: true });
242
+ this.atomic.writeFileAtomic(operation.backupPath, fs.readFileSync(operation.target));
243
+ if (fileHash(operation.backupPath) !== operation.originalHash) throw new DomainError('DATA_CORRUPT', `Knowledge backup verification failed: ${operation.path}.`, { status: 500 });
244
+ }
245
+ journal.phase = 'prepared';
246
+ this.writeJournal(journal);
247
+ this.fault('journal-prepared', journal);
248
+ return journal;
249
+ }
250
+
251
+ applyJournal(journal) {
252
+ journal.phase = 'applying';
253
+ this.writeJournal(journal);
254
+ for (let index = 0; index < journal.operations.length; index += 1) {
255
+ const operation = journal.operations[index];
256
+ const currentHash = fileHash(operation.target);
257
+ if (currentHash !== operation.originalHash) {
258
+ throw new DomainError('PROJECT_BUSY', `Knowledge changed before promotion: ${operation.path}.`, { status: 409, retryable: true });
259
+ }
260
+ if (operation.operation === 'delete') fs.unlinkSync(operation.target);
261
+ else this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.stagedPath));
262
+ operation.applied = true;
263
+ this.writeJournal(journal);
264
+ this.fault(`operation-applied:${index}`, journal);
265
+ }
266
+ this.verifyPromoted(journal);
267
+ journal.phase = 'awaiting-state-advance';
268
+ this.writeJournal(journal);
269
+ this.fault('promotion-verified', journal);
270
+ return journal;
271
+ }
272
+
273
+ verifyPromoted(journal) {
274
+ for (const operation of journal.operations) {
275
+ const actual = fileHash(operation.target);
276
+ if (operation.operation === 'delete' ? actual !== null : actual !== operation.newHash) {
277
+ throw new DomainError('DATA_CORRUPT', `Promoted knowledge verification failed: ${operation.path}.`, { status: 500 });
278
+ }
279
+ }
280
+ return true;
281
+ }
282
+
283
+ async advanceState(journal) {
284
+ const current = this.projectStore.readState(journal.projectId);
285
+ if (current.lastAnalyzedCommit === journal.commitSha && !current.analysis.activeClaim) return current;
286
+ const advanced = await this.projectStore.updateState(journal.projectId, state => {
287
+ const active = state.analysis.activeClaim;
288
+ if (!active || active.runId !== journal.runId || active.commitSha !== journal.commitSha || active.fingerprint !== journal.claimFingerprint) {
289
+ throw new DomainError('PROJECT_BUSY', 'Promotion journal no longer matches the active claim.', { status: 409, retryable: true });
290
+ }
291
+ state.lastAnalyzedCommit = journal.commitSha;
292
+ state.analysis.consumedRequirementIds = [...new Set([
293
+ ...(state.analysis.consumedRequirementIds || []),
294
+ ...(active.requirementIds || []),
295
+ ])];
296
+ state.analysis.activeClaim = null;
297
+ state.analysis.status = 'state.advanced';
298
+ state.analysis.lastError = null;
299
+ state.index.dirty = true;
300
+ state.index.sinceCommit = state.index.sinceCommit || journal.commitSha;
301
+ state.index.generation = Number(state.index.generation || 0) + 1;
302
+ state.index.lastError = null;
303
+ });
304
+ this.fault('state-advanced', journal);
305
+ return advanced;
306
+ }
307
+
308
+ async processClaim(input = {}) {
309
+ const projectId = validateProjectId(input.projectId);
310
+ const config = input.config || this.projectStore.readConfig(projectId);
311
+ const claim = input.claim;
312
+ if (!claim || claim.projectId !== projectId || !claim.runId || !claim.commitSha) throw new DomainError('INVALID_ARGUMENT', 'Active claim is required for knowledge promotion.');
313
+ const operationId = input.operationId || claim.operationId || createId('op');
314
+ const stagingPath = this.prepareStaging(projectId, claim.runId);
315
+ const beforeSource = await gitStatus(config.repoPath);
316
+ try {
317
+ if (!this.analyzer || typeof this.analyzer.runClaim !== 'function') throw new DomainError('INVALID_ARGUMENT', 'Knowledge analyzer is unavailable.', { status: 503, retryable: true });
318
+ const analyzerResult = await this.analyzer.runClaim({
319
+ ...input,
320
+ projectId,
321
+ config,
322
+ claim,
323
+ stagingPath,
324
+ manifestPath: this.manifestPath(projectId, claim.runId),
325
+ evidenceRoot: this.evidenceRoot(projectId, claim.runId),
326
+ safetyPolicy: buildAutomationToolPolicy({
327
+ stagingPath,
328
+ evidenceRoot: this.evidenceRoot(projectId, claim.runId),
329
+ }),
330
+ });
331
+ if (analyzerResult && analyzerResult.ok === false) throw new DomainError('INVALID_ARGUMENT', analyzerResult.error || 'Knowledge analyzer failed.', { status: 500, retryable: true });
332
+ const afterSource = await gitStatus(config.repoPath);
333
+ if (beforeSource != null && afterSource != null && beforeSource !== afterSource) {
334
+ throw new DomainError('PROJECT_BUSY', 'Source repository changed during knowledge analysis.', { status: 409, retryable: true });
335
+ }
336
+ this.fault('analysis-completed', { projectId, claim, stagingPath });
337
+ const validated = this.validateManifest({ projectId, config, claim });
338
+ this.fault('manifest-validated', validated);
339
+ const journal = this.prepareJournal(projectId, config, claim, validated);
340
+ this.applyJournal(journal);
341
+ await this.advanceState(journal);
342
+ journal.phase = 'completed';
343
+ journal.completedAt = new Date().toISOString();
344
+ this.writeJournal(journal);
345
+ await this.log('info', 'knowledge.promotion_completed', 'Validated knowledge was promoted and state advanced.', {
346
+ projectId,
347
+ operationId,
348
+ runId: claim.runId,
349
+ commitSha: claim.commitSha,
350
+ phase: 'state.advanced',
351
+ operationCount: journal.operations.length,
352
+ });
353
+ if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(projectId).catch(() => {});
354
+ return { ok: true, stateAdvanced: true, projectId, runId: claim.runId, commitSha: claim.commitSha, operations: journal.operations.length };
355
+ } catch (error) {
356
+ await this.log('error', 'knowledge.promotion_failed', 'Knowledge analysis/promotion failed without advancing state.', {
357
+ projectId,
358
+ operationId,
359
+ runId: claim.runId,
360
+ commitSha: claim.commitSha,
361
+ phase: 'promotion',
362
+ error,
363
+ });
364
+ throw error;
365
+ }
366
+ }
367
+
368
+ rollbackJournal(journal) {
369
+ let conflict = null;
370
+ for (const operation of [...journal.operations].reverse()) {
371
+ if (!operation.applied) continue;
372
+ const currentHash = fileHash(operation.target);
373
+ const expectedApplied = operation.operation === 'delete' ? null : operation.newHash;
374
+ if (currentHash !== expectedApplied) {
375
+ conflict = operation.path;
376
+ break;
377
+ }
378
+ if (operation.originalExists) this.atomic.writeFileAtomic(operation.target, fs.readFileSync(operation.backupPath));
379
+ else if (fs.existsSync(operation.target)) fs.unlinkSync(operation.target);
380
+ }
381
+ if (conflict) {
382
+ journal.phase = 'recovery-conflict';
383
+ journal.error = `User-visible knowledge changed after crash: ${conflict}`;
384
+ } else {
385
+ journal.phase = 'rolled-back';
386
+ journal.rolledBackAt = new Date().toISOString();
387
+ }
388
+ this.writeJournal(journal);
389
+ return { ok: !conflict, phase: journal.phase, conflict };
390
+ }
391
+
392
+ async recoverJournal(journal) {
393
+ if (journal.phase === 'completed' || journal.phase === 'rolled-back') return { ok: true, phase: journal.phase, skipped: true };
394
+ const appliedCount = journal.operations.filter(operation => operation.applied).length;
395
+ const allApplied = appliedCount === journal.operations.length;
396
+ if (journal.phase === 'awaiting-state-advance' || (allApplied && ['applying', 'prepared'].includes(journal.phase))) {
397
+ this.verifyPromoted(journal);
398
+ await this.advanceState(journal);
399
+ journal.phase = 'completed';
400
+ journal.recoveredAt = new Date().toISOString();
401
+ this.writeJournal(journal);
402
+ if (this.indexService && typeof this.indexService.enqueue === 'function') this.indexService.enqueue(journal.projectId).catch(() => {});
403
+ return { ok: true, phase: 'completed', stateAdvanced: true };
404
+ }
405
+ return this.rollbackJournal(journal);
406
+ }
407
+
408
+ async recoverAll() {
409
+ const root = this.layout.getRuntimePath('promotions');
410
+ if (!fs.existsSync(root)) return [];
411
+ const files = [];
412
+ const walk = current => {
413
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
414
+ const absolute = path.join(current, entry.name);
415
+ if (entry.isDirectory()) walk(absolute);
416
+ else if (entry.isFile() && entry.name.endsWith('.json')) files.push(absolute);
417
+ }
418
+ };
419
+ walk(root);
420
+ const results = [];
421
+ for (const file of files.sort()) {
422
+ const journal = this.atomic.readJsonStrict(file, {
423
+ category: 'promotion-journal',
424
+ validate: value => {
425
+ if (!value || value.schema !== JOURNAL_SCHEMA || !Array.isArray(value.operations)) throw new DomainError('DATA_CORRUPT', 'Promotion journal is corrupt.', { status: 500 });
426
+ return value;
427
+ },
428
+ });
429
+ results.push({ file, ...(await this.recoverJournal(journal)) });
430
+ }
431
+ return results;
432
+ }
433
+ }
434
+
435
+ module.exports = {
436
+ JOURNAL_SCHEMA,
437
+ MANIFEST_SCHEMA,
438
+ MAX_KNOWLEDGE_FILE_BYTES,
439
+ KnowledgePromotionService,
440
+ canonicalRelativePath,
441
+ fileHash,
442
+ hashBuffer,
443
+ validateMarkdown,
444
+ };