@sanqianx/project-knowledge 4.7.0 → 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 (192) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +817 -799
  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/chat-claudecodeui-match-test.js +92 -92
  46. package/_site/_test/claude-executable-discovery-test.js +62 -62
  47. package/_site/_test/claude-workbench-test.js +170 -170
  48. package/_site/_test/codex-conversation-projection-test.js +2 -1
  49. package/_site/_test/commit-conversation-binding-test.js +95 -95
  50. package/_site/_test/commit-evidence-test.js +110 -110
  51. package/_site/_test/conversation-api-test.js +109 -109
  52. package/_site/_test/conversation-store-test.js +136 -136
  53. package/_site/_test/data-dir-migration-test.js +57 -57
  54. package/_site/_test/desktop-browser-compat-test.js +28 -28
  55. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  56. package/_site/_test/explicit-commit-processor-test.js +37 -37
  57. package/_site/_test/fixtures/make-git-repos.js +12 -1
  58. package/_site/_test/folder-picker-output-test.js +19 -19
  59. package/_site/_test/full-integration-e2e-test.js +165 -165
  60. package/_site/_test/git-validation-test.js +2 -2
  61. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  62. package/_site/_test/hook-status-repair-api-test.js +152 -152
  63. package/_site/_test/hook-trigger-test.js +85 -85
  64. package/_site/_test/import-preflight-api-test.js +234 -233
  65. package/_site/_test/index-writer-concurrency-test.js +135 -135
  66. package/_site/_test/integration-adapters-test.js +171 -171
  67. package/_site/_test/integration-surface-coverage-test.js +164 -164
  68. package/_site/_test/knowledge-language-control-test.js +170 -170
  69. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  70. package/_site/_test/knowledge-query-test.js +54 -54
  71. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  72. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  73. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  74. package/_site/_test/legacy-forward-compat-test.js +257 -257
  75. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -363
  76. package/_site/_test/logging-api-test.js +89 -89
  77. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  78. package/_site/_test/logging-ui-test.js +106 -104
  79. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  80. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  81. package/_site/_test/mcp-server-test.js +149 -149
  82. package/_site/_test/module-artifact-integrity-test.js +27 -0
  83. package/_site/_test/module-boundary-test.js +30 -0
  84. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  85. package/_site/_test/module-model-configuration-test.js +43 -0
  86. package/_site/_test/module-process-lifecycle-test.js +24 -0
  87. package/_site/_test/module-stream-proxy-test.js +34 -0
  88. package/_site/_test/non-release-ci-test.js +34 -34
  89. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  90. package/_site/_test/p0-data-migration-characterization-test.js +37 -37
  91. package/_site/_test/p0-e2e-gate-test.js +347 -347
  92. package/_site/_test/packaged-ui-smoke-test.js +11 -9
  93. package/_site/_test/path-consistency-test.js +151 -151
  94. package/_site/_test/pending-sweep-test.js +9 -9
  95. package/_site/_test/post-commit-automation-test.js +87 -87
  96. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  97. package/_site/_test/product-import-ui-test.js +92 -0
  98. package/_site/_test/project-delete-recovery-test.js +64 -64
  99. package/_site/_test/project-goal-editor-test.js +144 -144
  100. package/_site/_test/project-layout-v2-migration-test.js +127 -127
  101. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  102. package/_site/_test/prompt-settings-test.js +115 -115
  103. package/_site/_test/protected-architecture-gate-test.js +122 -122
  104. package/_site/_test/refactor-characterization-test.js +36 -36
  105. package/_site/_test/release-version-sync-test.js +1 -1
  106. package/_site/_test/requirement-recorder-test.js +173 -173
  107. package/_site/_test/run-all-tests.js +159 -156
  108. package/_site/_test/server-runtime-migration-safety-test.js +27 -27
  109. package/_site/_test/shared-contracts-test.js +58 -58
  110. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  111. package/_site/_test/storage-foundation-test.js +78 -78
  112. package/_site/_test/structured-logger-test.js +101 -101
  113. package/_site/_test/tracking-start-test.js +108 -108
  114. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -56
  115. package/_site/_test/workbench-permission-test.js +117 -117
  116. package/_site/_test/workspace-ui-contract-test.js +28 -43
  117. package/_site/lib/ai-profile-resolver.js +78 -78
  118. package/_site/lib/ai-workspace.js +101 -101
  119. package/_site/lib/automation-config.js +140 -140
  120. package/_site/lib/bridge-adapter.js +1 -0
  121. package/_site/lib/bridge-consumer-service.js +402 -402
  122. package/_site/lib/claude-cli-runner.js +1510 -1510
  123. package/_site/lib/commit-conversation-binder.js +234 -234
  124. package/_site/lib/commit-processing-ledger.js +27 -27
  125. package/_site/lib/commit-prompt.js +202 -202
  126. package/_site/lib/commit-reconciler.js +406 -406
  127. package/_site/lib/contracts.js +284 -279
  128. package/_site/lib/conversation-query-service.js +144 -144
  129. package/_site/lib/conversation-store.js +385 -385
  130. package/_site/lib/data-dir.js +74 -74
  131. package/_site/lib/data-state-classifier.js +40 -40
  132. package/_site/lib/engine-cutover.js +97 -0
  133. package/_site/lib/evidence-bundle.js +228 -228
  134. package/_site/lib/folder-picker-output.js +21 -21
  135. package/_site/lib/git-runner.js +62 -62
  136. package/_site/lib/github-team-store.js +1172 -1172
  137. package/_site/lib/hook-manager.js +203 -202
  138. package/_site/lib/index-service.js +173 -173
  139. package/_site/lib/integration-installer.js +907 -907
  140. package/_site/lib/kb-framework.js +176 -176
  141. package/_site/lib/kb-validator.js +124 -124
  142. package/_site/lib/knowledge-promotion.js +435 -435
  143. package/_site/lib/knowledge-retrieval-service.js +401 -401
  144. package/_site/lib/knowledge-tool-runtime.js +359 -359
  145. package/_site/lib/legacy-data-manifest.js +26 -26
  146. package/_site/lib/llm-client.js +161 -161
  147. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  148. package/_site/lib/migration-service.js +442 -442
  149. package/_site/lib/module-bridge.js +198 -33
  150. package/_site/lib/post-commit-automation.js +87 -87
  151. package/_site/lib/project-lifecycle-service.js +519 -497
  152. package/_site/lib/project-store.js +268 -262
  153. package/_site/lib/requirement-recorder.js +278 -278
  154. package/_site/lib/runtime-endpoint.js +155 -155
  155. package/_site/lib/scanner.js +298 -298
  156. package/_site/lib/server-app.js +1590 -1520
  157. package/_site/lib/settings-store.js +133 -113
  158. package/_site/lib/storage-layout.js +162 -162
  159. package/_site/lib/structured-logger.js +574 -574
  160. package/_site/scripts/folder-picker.ps1 +156 -156
  161. package/_site/scripts/hook-trigger.js +157 -156
  162. package/_site/scripts/install-module-candidates.js +69 -0
  163. package/_site/scripts/pack-module-candidates.js +72 -0
  164. package/_site/scripts/sync-release-version.js +2 -2
  165. package/_site/scripts/vendor-modules.js +47 -0
  166. package/_site/scripts/verify-module-runtime.js +45 -0
  167. package/_site/scripts/verify-product-runtime.js +34 -0
  168. package/bin/project-knowledge-mcp.js +194 -194
  169. package/docs/README.zh-CN.md +34 -25
  170. package/docs/project-registry-schema.md +22 -22
  171. package/docs/testing-strategy.md +33 -33
  172. package/module-runtime-manifest.json +220 -0
  173. package/package.json +13 -9
  174. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  175. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  176. package/plugins/project-knowledge/.mcp.json +1 -1
  177. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  178. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  179. package/templates/project-readme.md +34 -34
  180. package/ui/favicon.svg +38 -38
  181. package/ui/index.html +51 -149
  182. package/ui/product.css +9 -0
  183. package/ui/product.js +386 -0
  184. package/vendor-manifest.json +46 -0
  185. package/_site/_test/import-ui-flow-test.js +0 -171
  186. package/_site/_test/project-control-panel-task14-test.js +0 -63
  187. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  188. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  189. package/_site/_test/ui-smoke-test.js +0 -73
  190. package/ui/app.css +0 -58
  191. package/ui/app.js +0 -607
  192. package/ui/i18n.js +0 -146
@@ -0,0 +1,7 @@
1
+ # 迁入的知识运行逻辑
2
+
3
+ 来源:project-knowledge-base/_site/lib,基线 0c62f528f66794ca5de055a137f632dfc5c57bc3。
4
+
5
+ 复用提交证据冻结、会话边界绑定、检索事实校验、提示词、安全工具策略、晋升事务及崩溃恢复。只迁入知识运行职责,没有复制外壳的项目注册表、SettingsStore、凭据或旧 LanceDB/embedding 写入能力。
6
+
7
+ 构造函数改为注入 layout 与只读项目投影/运行状态适配器;内容哈希提取为零依赖文件。项目和配置的所有权仍在外壳,引擎本地登记只是运行所需投影。向量召回接 vector-hub,不启动第二份索引。
@@ -0,0 +1,204 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { DomainError } = require('./contracts');
5
+
6
+ const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
7
+ const DEFAULT_STALE_LOCK_MS = 120_000;
8
+
9
+ function delay(ms) {
10
+ return new Promise(resolve => setTimeout(resolve, ms));
11
+ }
12
+
13
+ function isProcessAlive(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ } catch (error) {
19
+ return error && error.code === 'EPERM';
20
+ }
21
+ }
22
+
23
+ function readLockOwner(lockPath) {
24
+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch { return null; }
25
+ }
26
+
27
+ function canBreakStaleLock(lockPath, staleMs) {
28
+ let stat;
29
+ try { stat = fs.statSync(lockPath); } catch { return false; }
30
+ const owner = readLockOwner(lockPath);
31
+ // A complete owner record lets us recover immediately after a process
32
+ // crash. The age threshold is only needed for an incomplete/unreadable
33
+ // file that another process may still be creating.
34
+ if (owner && Number.isInteger(Number(owner.pid))) return !isProcessAlive(Number(owner.pid));
35
+ return (Date.now() - stat.mtimeMs) >= staleMs;
36
+ }
37
+
38
+ async function acquireFileLock(lockPath, options = {}) {
39
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_LOCK_TIMEOUT_MS;
40
+ const staleMs = Number.isFinite(options.staleMs) ? options.staleMs : DEFAULT_STALE_LOCK_MS;
41
+ const retryMs = Number.isFinite(options.retryMs) ? options.retryMs : 25;
42
+ const started = Date.now();
43
+ const nonce = crypto.randomBytes(12).toString('hex');
44
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
45
+ while (true) {
46
+ try {
47
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
48
+ const owner = { pid: process.pid, startedAt: new Date().toISOString(), nonce };
49
+ fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');
50
+ fs.fsyncSync(fd);
51
+ fs.closeSync(fd);
52
+ return async function release() {
53
+ const current = readLockOwner(lockPath);
54
+ if (!current || current.nonce !== nonce) return;
55
+ try { fs.unlinkSync(lockPath); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
56
+ };
57
+ } catch (error) {
58
+ if (!error || error.code !== 'EEXIST') throw error;
59
+ if (canBreakStaleLock(lockPath, staleMs)) {
60
+ try { fs.unlinkSync(lockPath); continue; } catch (unlinkError) {
61
+ // A competing process may recover the same stale lock first; retry through the normal wait path.
62
+ }
63
+ }
64
+ if ((Date.now() - started) >= timeoutMs) {
65
+ throw new DomainError('PROJECT_BUSY', 'Timed out waiting for a file lock.', {
66
+ status: 409,
67
+ retryable: true,
68
+ details: { lockCategory: path.basename(lockPath) },
69
+ });
70
+ }
71
+ await delay(retryMs);
72
+ }
73
+ }
74
+ }
75
+
76
+ async function withFileLock(lockPath, fn, options = {}) {
77
+ const release = await acquireFileLock(lockPath, options);
78
+ try { return await fn(); } finally { await release(); }
79
+ }
80
+
81
+ function syncDirectoryBestEffort(directory) {
82
+ let fd;
83
+ try {
84
+ fd = fs.openSync(directory, 'r');
85
+ fs.fsyncSync(fd);
86
+ } catch {
87
+ // Directory fsync is unsupported on some filesystems; the file replace is already durable.
88
+ } finally {
89
+ if (fd != null) try { fs.closeSync(fd); } catch {
90
+ // Closing a best-effort directory descriptor cannot invalidate the completed file replace.
91
+ }
92
+ }
93
+ }
94
+
95
+ function replaceWithRetry(tempPath, targetPath, options = {}) {
96
+ const retries = Number.isInteger(options.renameRetries) ? options.renameRetries : 8;
97
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
98
+ let lastError;
99
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
100
+ try {
101
+ fs.renameSync(tempPath, targetPath);
102
+ return;
103
+ } catch (error) {
104
+ lastError = error;
105
+ if (!error || !['EPERM', 'EACCES', 'EBUSY', 'EEXIST'].includes(error.code) || attempt === retries) break;
106
+ Atomics.wait(waitBuffer, 0, 0, Math.min(250, 10 * (2 ** attempt)));
107
+ }
108
+ }
109
+ throw lastError;
110
+ }
111
+
112
+ function writeFileAtomic(filePath, content, options = {}) {
113
+ const directory = path.dirname(filePath);
114
+ fs.mkdirSync(directory, { recursive: true });
115
+ const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`);
116
+ let fd;
117
+ try {
118
+ fd = fs.openSync(tempPath, 'wx', options.mode || 0o600);
119
+ fs.writeFileSync(fd, content, options.encoding || 'utf8');
120
+ fs.fsyncSync(fd);
121
+ fs.closeSync(fd);
122
+ fd = null;
123
+ if (typeof options.beforeRename === 'function') options.beforeRename(tempPath, filePath);
124
+ replaceWithRetry(tempPath, filePath, options);
125
+ syncDirectoryBestEffort(directory);
126
+ return { path: filePath };
127
+ } catch (error) {
128
+ if (fd != null) try { fs.closeSync(fd); } catch {
129
+ // Preserve the original write error.
130
+ }
131
+ try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch {
132
+ // Preserve the original write error; stale temp files are never treated as live data.
133
+ }
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ function writeJsonAtomic(filePath, value, options = {}) {
139
+ return writeFileAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`, options);
140
+ }
141
+
142
+ function readJsonStrict(filePath, options = {}) {
143
+ let raw;
144
+ try { raw = fs.readFileSync(filePath, 'utf8'); }
145
+ catch (error) {
146
+ if (error && error.code === 'ENOENT' && options.allowMissing) return options.defaultValue;
147
+ throw error;
148
+ }
149
+ try {
150
+ const parsed = JSON.parse(raw);
151
+ if (typeof options.validate === 'function') options.validate(parsed);
152
+ return parsed;
153
+ } catch (error) {
154
+ if (error instanceof DomainError) throw error;
155
+ throw new DomainError('DATA_CORRUPT', 'A JSON data file is corrupt.', {
156
+ status: 500,
157
+ cause: error,
158
+ details: { category: options.category || 'json' },
159
+ });
160
+ }
161
+ }
162
+
163
+ async function appendJsonlLocked(filePath, value, options = {}) {
164
+ const lockPath = options.lockPath || `${filePath}.lock`;
165
+ return withFileLock(lockPath, async () => {
166
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
167
+ const fd = fs.openSync(filePath, 'a', options.mode || 0o600);
168
+ try {
169
+ fs.writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8');
170
+ fs.fsyncSync(fd);
171
+ } finally {
172
+ fs.closeSync(fd);
173
+ }
174
+ return value;
175
+ }, options);
176
+ }
177
+
178
+ function cleanupStaleTemps(directory, options = {}) {
179
+ if (!fs.existsSync(directory)) return [];
180
+ const olderThanMs = Number.isFinite(options.olderThanMs) ? options.olderThanMs : 24 * 60 * 60 * 1000;
181
+ const now = Date.now();
182
+ const removed = [];
183
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
184
+ if (!entry.isFile() || !/^\..+\.\d+\.\d+\.[a-f0-9]+\.tmp$/i.test(entry.name)) continue;
185
+ const absolute = path.join(directory, entry.name);
186
+ const stat = fs.statSync(absolute);
187
+ if ((now - stat.mtimeMs) < olderThanMs) continue;
188
+ fs.unlinkSync(absolute);
189
+ removed.push(absolute);
190
+ }
191
+ return removed;
192
+ }
193
+
194
+ module.exports = {
195
+ DEFAULT_LOCK_TIMEOUT_MS,
196
+ DEFAULT_STALE_LOCK_MS,
197
+ acquireFileLock,
198
+ withFileLock,
199
+ writeFileAtomic,
200
+ writeJsonAtomic,
201
+ readJsonStrict,
202
+ appendJsonlLocked,
203
+ cleanupStaleTemps,
204
+ };
@@ -0,0 +1,140 @@
1
+ const path = require('path');
2
+
3
+ const PERMISSION_MODES = new Set(['plan', 'default', 'acceptEdits', 'auto', 'bypassPermissions']);
4
+ const PROMPT_TEMPLATE_VERSION = 2;
5
+
6
+ const DEFAULT_COMMIT_PROMPT_TEMPLATE = `你正在根据一个 Git Commit 的冻结证据维护项目知识库。
7
+
8
+ 用户需求:
9
+ {{userRequirement}}
10
+
11
+ Commit 信息:
12
+ {{commitMetadata}}
13
+
14
+ Commit 实际变更文件:
15
+ {{actualChanges}}
16
+
17
+ Commit 实际 Patch:
18
+ {{actualPatch}}
19
+
20
+ 现有相关知识:
21
+ {{existingKnowledge}}
22
+
23
+ 请完成以下判断,并只输出符合 staging manifest 合同的知识变更:
24
+ 1. 比较用户需求与实际实现是否一致;没有可靠需求时不得猜测业务目的。
25
+ 2. 只记录 Commit、Patch 和现有知识能够证明的事实。
26
+ 3. 明确需要新增、更新或删除哪些知识;删除必须有实际变更证据。
27
+ 4. 不得修改源码、最终知识目录、其他项目或派生索引。
28
+ 5. Patch 使用 chunk evidence 时,必须从只读 manifest 按序读取所需 chunk;不得从源码工作树补读或猜测。`;
29
+
30
+ const READ_TOOLS = ['Read'];
31
+ const WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit'];
32
+
33
+ function normalizePermissionMode(value) {
34
+ return PERMISSION_MODES.has(value) ? value : 'default';
35
+ }
36
+
37
+ function normalizeAutomationConfig(input) {
38
+ const source = input && typeof input === 'object' ? input : {};
39
+ const explicit = typeof source.commitPromptTemplate === 'string' && source.commitPromptTemplate.trim();
40
+ const legacy = typeof source.hookPromptTemplate === 'string' && source.hookPromptTemplate.trim();
41
+ return {
42
+ enabled: source.enabled !== false,
43
+ commitPromptTemplate: explicit || legacy || DEFAULT_COMMIT_PROMPT_TEMPLATE,
44
+ promptTemplateVersion: PROMPT_TEMPLATE_VERSION,
45
+ legacyPromptOverride: !explicit && Boolean(legacy),
46
+ };
47
+ }
48
+
49
+ function normalizeClaudeWorkbenchConfig(input) {
50
+ const source = input && typeof input === 'object' ? input : {};
51
+ return { permissionMode: normalizePermissionMode(source.permissionMode) };
52
+ }
53
+
54
+ function renderTemplate(template, vars) {
55
+ const source = typeof template === 'string' && template.trim() ? template : DEFAULT_COMMIT_PROMPT_TEMPLATE;
56
+ const safeVars = vars && typeof vars === 'object' ? vars : {};
57
+ return source.replace(/\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g, (match, name) => {
58
+ if (!Object.prototype.hasOwnProperty.call(safeVars, name)) return match;
59
+ const value = safeVars[name];
60
+ return value == null ? '' : String(value);
61
+ });
62
+ }
63
+
64
+ function normalizePathForCompare(value) {
65
+ if (!value || typeof value !== 'string') return '';
66
+ const normalized = path.resolve(value).replace(/[\\/]+$/, '');
67
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
68
+ }
69
+
70
+ function pathsReferToSameLocation(leftValue, rightValue) {
71
+ const left = normalizePathForCompare(leftValue);
72
+ const right = normalizePathForCompare(rightValue);
73
+ return Boolean(left && right && left === right);
74
+ }
75
+
76
+ function isInsidePath(root, target) {
77
+ if (!root || !target) return false;
78
+ const rootAbs = path.resolve(root);
79
+ const targetAbs = path.resolve(rootAbs, target);
80
+ const relative = path.relative(rootAbs, targetAbs);
81
+ return relative === '' || Boolean(relative && !relative.startsWith('..') && !path.isAbsolute(relative));
82
+ }
83
+
84
+ function extractToolPaths(toolName, input) {
85
+ if (!input || typeof input !== 'object') return [];
86
+ const candidates = [];
87
+ for (const key of ['file_path', 'path', 'notebook_path']) {
88
+ if (typeof input[key] === 'string') candidates.push(input[key]);
89
+ }
90
+ if (toolName === 'MultiEdit' && typeof input.file_path === 'string') candidates.push(input.file_path);
91
+ return [...new Set(candidates)];
92
+ }
93
+
94
+ function buildAutomationToolPolicy(options = {}) {
95
+ const stagingPath = options.stagingPath || options.kbPath || '';
96
+ const evidenceRoot = options.evidenceRoot || '';
97
+ return {
98
+ kind: 'knowledge-staging',
99
+ stagingPath,
100
+ evidenceRoot,
101
+ readRoots: [evidenceRoot, stagingPath].filter(Boolean),
102
+ writeRoot: stagingPath,
103
+ allowedTools: [...READ_TOOLS, ...WRITE_TOOLS],
104
+ canWriteKb: false,
105
+ canWriteStaging: true,
106
+ allowReadOnlyBash: false,
107
+ };
108
+ }
109
+
110
+ function evaluateAutomationToolUse(policy, toolName, input) {
111
+ if (!policy || policy.kind !== 'knowledge-staging') return { behavior: 'ask', reason: 'no staging policy' };
112
+ if (!policy.allowedTools.includes(toolName)) return { behavior: 'deny', reason: `tool is not allowed: ${toolName}` };
113
+ const paths = extractToolPaths(toolName, input);
114
+ if (!paths.length) return { behavior: 'deny', reason: `${toolName} has no explicit file path` };
115
+ for (const filePath of paths) {
116
+ if (toolName === 'Read') {
117
+ if (!(policy.readRoots || []).some(root => isInsidePath(root, filePath))) {
118
+ return { behavior: 'deny', reason: `path outside read-only evidence/output roots: ${filePath}` };
119
+ }
120
+ } else if (!isInsidePath(policy.writeRoot || policy.stagingPath, filePath)) {
121
+ return { behavior: 'deny', reason: `path outside writable run output: ${filePath}` };
122
+ }
123
+ }
124
+ return { behavior: 'allow', reason: toolName === 'Read' ? 'path is inside an isolated read root' : 'path is inside the isolated writable output root' };
125
+ }
126
+
127
+ module.exports = {
128
+ PERMISSION_MODES,
129
+ PROMPT_TEMPLATE_VERSION,
130
+ DEFAULT_COMMIT_PROMPT_TEMPLATE,
131
+ normalizePermissionMode,
132
+ normalizeAutomationConfig,
133
+ normalizeClaudeWorkbenchConfig,
134
+ renderTemplate,
135
+ normalizePathForCompare,
136
+ pathsReferToSameLocation,
137
+ isInsidePath,
138
+ buildAutomationToolPolicy,
139
+ evaluateAutomationToolUse,
140
+ };
@@ -0,0 +1,249 @@
1
+ const fs = require('fs');
2
+ const { DomainError, validateProjectId } = require('./contracts');
3
+ const { ConversationStore, sha256 } = require('./conversation-store');
4
+ const { readDevelopmentEvents } = require('./conversation-exclusions');
5
+
6
+ function projectEvent(event) {
7
+ return {
8
+ eventId: event.eventId,
9
+ sequence: event.sequence,
10
+ content: event.content,
11
+ contentHash: event.contentHash,
12
+ capturedAt: event.capturedAt,
13
+ };
14
+ }
15
+
16
+ class CommitConversationBinder {
17
+ constructor(options = {}) {
18
+ this.layout = options.layout;
19
+ this.projectStore = options.projectStore;
20
+ this.conversationStore = options.conversationStore || new ConversationStore({
21
+ layout: this.layout,
22
+ projectStore: this.projectStore,
23
+ logger: options.logger,
24
+ });
25
+ this.logger = options.logger || null;
26
+ }
27
+
28
+ async log(level, event, message, context) {
29
+ if (this.logger && typeof this.logger[level] === 'function') await this.logger[level](event, message, context);
30
+ }
31
+
32
+ repoMatches(left, right) {
33
+ if (!left || !right) return false;
34
+ // workspaceId is the canonical primary key (I-06). commonDir/repoId are
35
+ // read-compat fallbacks for records stored before repo-identity/v1.
36
+ if (left.workspaceId && right.workspaceId) return String(left.workspaceId) === String(right.workspaceId);
37
+ if (left.commonDir && right.commonDir) return this.layout.pathsEqual(left.commonDir, right.commonDir);
38
+ if (left.repoId && right.repoId) return String(left.repoId) === String(right.repoId);
39
+ return false;
40
+ }
41
+
42
+ boundaryOrder(boundary) {
43
+ return Number.isInteger(boundary.journalSequence) ? boundary.journalSequence : boundary.bridgeCursorAtCommit;
44
+ }
45
+
46
+ previousBoundary(projectId, boundary) {
47
+ const order = this.boundaryOrder(boundary);
48
+ return this.conversationStore.listBoundaries(projectId)
49
+ .filter(candidate => candidate.commitSha !== boundary.commitSha
50
+ && (candidate.journalId || 'global') === (boundary.journalId || 'global')
51
+ && this.repoMatches(candidate.repoIdentity, boundary.repoIdentity)
52
+ && this.boundaryOrder(candidate) < order)
53
+ .sort((left, right) => this.boundaryOrder(right) - this.boundaryOrder(left))[0] || null;
54
+ }
55
+
56
+ snapshotExists(projectId, commitSha) {
57
+ return fs.existsSync(this.layout.getProjectCommitConversationPath(projectId, commitSha));
58
+ }
59
+
60
+ async bind(input = {}) {
61
+ const projectId = validateProjectId(input.projectId);
62
+ const commitSha = this.layout.validateCommitSha(input.commitSha);
63
+ if (this.snapshotExists(projectId, commitSha)) return this.conversationStore.readSnapshot(projectId, commitSha);
64
+
65
+ if (this.projectStore) await this.conversationStore.importLegacyRequirements(projectId);
66
+ // Development Conversation reads are centralized: exclusions and Codex
67
+ // turn repair are identical here and in the query service.
68
+ let events = readDevelopmentEvents(this.conversationStore, projectId);
69
+ let boundary = null;
70
+ try { boundary = this.conversationStore.readBoundary(projectId, commitSha); }
71
+ catch (error) {
72
+ if (!error || error.code !== 'ENOENT') throw error;
73
+ }
74
+
75
+ if (boundary) events = events.filter(event => (event.journalId || 'global') === (boundary.journalId || 'global'));
76
+ const explicitEvents = events.filter(event => event.role === 'user' && event.explicitCommitSha === commitSha);
77
+ if (!boundary) {
78
+ const turns = this.buildExplicitTurns(explicitEvents);
79
+ return this.finalize(projectId, commitSha, {
80
+ repoIdentity: null,
81
+ parentSha: null,
82
+ boundaryStartCursor: null,
83
+ boundaryEndCursor: null,
84
+ status: turns.length ? 'available' : 'unavailable',
85
+ turns,
86
+ excludedFuturePromptCount: 0,
87
+ }, { reason: 'missing-commit-boundary' });
88
+ }
89
+
90
+ const previous = this.previousBoundary(projectId, boundary);
91
+ const state = this.projectStore ? this.projectStore.readState(projectId) : { conversationBaselineCursor: null };
92
+ const journalId = boundary.journalId || 'global';
93
+ const baseline = state.conversationBaselineCursors?.[journalId] ?? (journalId === 'global' ? state.conversationBaselineCursor : 0);
94
+ const startCursor = previous ? previous.bridgeCursorAtCommit : baseline;
95
+ const endCursor = boundary.bridgeCursorAtCommit;
96
+ const selected = new Map();
97
+ let ambiguousCount = 0;
98
+ let excludedFuturePromptCount = 0;
99
+
100
+ for (const event of explicitEvents) {
101
+ if (event.repoIdentity && boundary.repoIdentity && !this.repoMatches(event.repoIdentity, boundary.repoIdentity)) {
102
+ ambiguousCount += 1;
103
+ continue;
104
+ }
105
+ if (!event.turnId) { ambiguousCount += 1; continue; }
106
+ selected.set(event.turnId, 'explicit');
107
+ }
108
+
109
+ if (Number.isInteger(startCursor)) {
110
+ for (const event of events) {
111
+ if (event.role !== 'user' || event.sequence == null || event.explicitCommitSha) continue;
112
+ if (!this.repoMatches(event.repoIdentity, boundary.repoIdentity)) {
113
+ if (event.sequence > startCursor && event.sequence <= endCursor && !event.repoIdentity) ambiguousCount += 1;
114
+ continue;
115
+ }
116
+ if (event.sequence > endCursor) {
117
+ excludedFuturePromptCount += 1;
118
+ continue;
119
+ }
120
+ if (event.sequence <= startCursor) continue;
121
+ // Automatic direct evidence requires exact identity. Legacy stored
122
+ // 'high'/'trusted' translate to exact for old known data only;
123
+ // 'explicit' is the explicit-fallback tier (I-18: no synthetic).
124
+ const rawConfidence = String(event.identityConfidence || '');
125
+ const effectiveConfidence = rawConfidence === 'high' || rawConfidence === 'trusted' ? 'exact' : rawConfidence;
126
+ if (!event.turnId || !['exact', 'explicit'].includes(effectiveConfidence)) {
127
+ ambiguousCount += 1;
128
+ continue;
129
+ }
130
+ selected.set(event.turnId, 'direct');
131
+ }
132
+
133
+ for (const turnId of boundary.openTurnIdsAtCommit) {
134
+ if (selected.has(turnId)) continue;
135
+ const user = events.find(event => event.role === 'user'
136
+ && event.turnId === turnId
137
+ && event.sequence != null
138
+ && event.sequence <= startCursor
139
+ && this.repoMatches(event.repoIdentity, boundary.repoIdentity));
140
+ const closedAt = user && user.developmentTurnClosedAtSequence;
141
+ if (user && !(Number.isInteger(closedAt) && closedAt <= startCursor)) {
142
+ selected.set(turnId, 'shared-spanning');
143
+ }
144
+ }
145
+ }
146
+
147
+ const turns = [];
148
+ for (const [turnId, bindingKind] of selected) {
149
+ const turnEvents = events.filter(event => event.turnId === turnId).sort((left, right) => {
150
+ if (left.sequence == null) return 1;
151
+ if (right.sequence == null) return -1;
152
+ return left.sequence - right.sequence;
153
+ });
154
+ const userEvents = turnEvents.filter(event => event.role === 'user'
155
+ && (bindingKind === 'explicit' || (event.sequence != null && event.sequence <= endCursor)));
156
+ if (!userEvents.length) continue;
157
+ const first = userEvents[0];
158
+ // I-13: no event beyond the commit boundary may enter a frozen
159
+ // snapshot — including assistant replies that arrived after the
160
+ // boundary but before a delayed binder run.
161
+ const assistantEvents = turnEvents.filter(event => event.role === 'assistant'
162
+ && (bindingKind === 'explicit' || (event.sequence != null && event.sequence <= endCursor)));
163
+ turns.push({
164
+ turnId,
165
+ source: first.source,
166
+ sessionId: first.sessionId,
167
+ bindingKind,
168
+ userEvents: userEvents.map(projectEvent),
169
+ assistantEvents: assistantEvents.map(projectEvent),
170
+ });
171
+ }
172
+ turns.sort((left, right) => {
173
+ const a = left.userEvents[0].sequence;
174
+ const b = right.userEvents[0].sequence;
175
+ if (a == null) return 1;
176
+ if (b == null) return -1;
177
+ return a - b;
178
+ });
179
+
180
+ let status = turns.length ? 'available' : 'no-new-user-prompt';
181
+ let reason = turns.length ? 'sequence-window' : 'no-new-user-prompt';
182
+ if (!Number.isInteger(startCursor)) {
183
+ status = explicitEvents.length && turns.length ? 'available' : 'unavailable';
184
+ reason = 'conversation-baseline-unavailable';
185
+ } else if (ambiguousCount > 0 && !turns.length) {
186
+ status = 'ambiguous';
187
+ reason = 'turn-or-repo-identity-ambiguous';
188
+ }
189
+
190
+ return this.finalize(projectId, commitSha, {
191
+ repoIdentity: boundary.repoIdentity,
192
+ parentSha: boundary.parentShas[0] || null,
193
+ boundaryStartCursor: startCursor,
194
+ boundaryEndCursor: endCursor,
195
+ status,
196
+ turns,
197
+ excludedFuturePromptCount,
198
+ }, { reason, ambiguousCount, previousBoundaryCommit: previous && previous.commitSha || null });
199
+ }
200
+
201
+ buildExplicitTurns(events) {
202
+ return events.filter(event => event.turnId).map(event => ({
203
+ turnId: event.turnId,
204
+ source: event.source,
205
+ sessionId: event.sessionId,
206
+ bindingKind: 'explicit',
207
+ userEvents: [projectEvent(event)],
208
+ assistantEvents: [],
209
+ }));
210
+ }
211
+
212
+ async finalize(projectId, commitSha, snapshotInput, decision) {
213
+ const snapshot = this.conversationStore.writeSnapshot(projectId, {
214
+ commitSha,
215
+ ...snapshotInput,
216
+ finalizedAt: new Date().toISOString(),
217
+ });
218
+ await this.log(snapshot.status === 'ambiguous' || snapshot.status === 'unavailable' ? 'warn' : 'info', 'conversation.commit_snapshot_frozen', 'Commit conversation snapshot was frozen.', {
219
+ projectId,
220
+ commitSha,
221
+ component: 'commit-conversation-binder',
222
+ phase: 'snapshot-frozen',
223
+ context: {
224
+ snapshotHash: snapshot.snapshotHash,
225
+ status: snapshot.status,
226
+ turnCount: snapshot.turns.length,
227
+ userEventCount: snapshot.turns.reduce((total, turn) => total + turn.userEvents.length, 0),
228
+ assistantEventCount: snapshot.turns.reduce((total, turn) => total + turn.assistantEvents.length, 0),
229
+ decision,
230
+ },
231
+ });
232
+ return snapshot;
233
+ }
234
+ }
235
+
236
+ function snapshotRequirementRecords(snapshot) {
237
+ return snapshot.turns.flatMap(turn => turn.userEvents.map(event => ({
238
+ id: event.eventId,
239
+ client: turn.source,
240
+ sessionId: turn.sessionId,
241
+ ts: event.capturedAt,
242
+ requirement: event.content,
243
+ requirementHash: event.contentHash,
244
+ turnId: turn.turnId,
245
+ bindingKind: turn.bindingKind,
246
+ })));
247
+ }
248
+
249
+ module.exports = { CommitConversationBinder, snapshotRequirementRecords, projectEvent, sha256 };
@@ -0,0 +1,26 @@
1
+ const fs = require('fs');
2
+ const { DomainError, validateProjectId } = require('./contracts');
3
+ const { validateSha } = require('./scanner');
4
+ const AtomicFile = require('./atomic-file');
5
+
6
+ class CommitProcessingLedger {
7
+ constructor(options = {}) { this.layout = options.layout; this.atomic = options.atomic || AtomicFile; }
8
+ filePath(projectId, commitSha) { return this.layout.getRuntimePath('processed-commits', validateProjectId(projectId), `${validateSha(commitSha)}.json`); }
9
+ read(projectId, commitSha) {
10
+ const file = this.filePath(projectId, commitSha);
11
+ if (!fs.existsSync(file)) return null;
12
+ return this.atomic.readJsonStrict(file, { category: 'commit-processing-record', validate: value => {
13
+ if (!value || value.schema !== 'commit-processing-record/v1' || value.projectId !== projectId || value.commitSha !== commitSha || value.status !== 'completed') {
14
+ throw new DomainError('DATA_CORRUPT', 'Commit processing ledger record is corrupt.', { status: 500 });
15
+ }
16
+ return value;
17
+ } });
18
+ }
19
+ complete(projectId, commitSha, fields = {}) {
20
+ const record = { schema: 'commit-processing-record/v1', projectId: validateProjectId(projectId), commitSha: validateSha(commitSha), status: 'completed', ...fields, completedAt: new Date().toISOString() };
21
+ this.atomic.writeJsonAtomic(this.filePath(projectId, commitSha), record);
22
+ return record;
23
+ }
24
+ }
25
+
26
+ module.exports = { CommitProcessingLedger };