@sanqianx/project-knowledge 4.7.0 → 5.0.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 (196) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +836 -799
  4. package/README.md +58 -41
  5. package/_modules/knowledge-engine/README.md +91 -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 +263 -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/retrieval.js +116 -0
  15. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  16. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  17. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  18. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  22. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  23. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  24. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  26. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  27. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  28. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  30. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  31. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  32. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  33. package/_modules/knowledge-engine/src/server.js +154 -0
  34. package/_modules/knowledge-engine/src/store.js +236 -0
  35. package/_modules/knowledge-engine/ui/app.css +172 -0
  36. package/_modules/knowledge-engine/ui/app.js +297 -0
  37. package/_modules/knowledge-engine/ui/index.html +95 -0
  38. package/_site/README.md +30 -30
  39. package/_site/_test/ai-profile-resolver-test.js +137 -137
  40. package/_site/_test/automation-queue-test.js +14 -14
  41. package/_site/_test/automation-ui-test.js +40 -40
  42. package/_site/_test/background-task-registry-test.js +43 -43
  43. package/_site/_test/baseline-schema-test.js +91 -91
  44. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  45. package/_site/_test/claude-executable-discovery-test.js +62 -62
  46. package/_site/_test/claude-workbench-test.js +170 -170
  47. package/_site/_test/codex-conversation-projection-test.js +2 -1
  48. package/_site/_test/commit-conversation-binding-test.js +95 -95
  49. package/_site/_test/commit-evidence-test.js +110 -110
  50. package/_site/_test/conversation-api-test.js +109 -109
  51. package/_site/_test/conversation-store-test.js +136 -136
  52. package/_site/_test/desktop-browser-compat-test.js +28 -28
  53. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  54. package/_site/_test/explicit-commit-processor-test.js +37 -37
  55. package/_site/_test/fixtures/make-git-repos.js +12 -1
  56. package/_site/_test/folder-picker-output-test.js +19 -19
  57. package/_site/_test/fresh-hook-reimport-test.js +53 -0
  58. package/_site/_test/fresh-product-data-test.js +42 -0
  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/logging-api-test.js +89 -89
  75. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  76. package/_site/_test/logging-ui-test.js +106 -104
  77. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  78. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  79. package/_site/_test/mcp-server-test.js +149 -149
  80. package/_site/_test/module-artifact-integrity-test.js +27 -0
  81. package/_site/_test/module-boundary-test.js +30 -0
  82. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  83. package/_site/_test/module-model-configuration-test.js +44 -0
  84. package/_site/_test/module-process-lifecycle-test.js +24 -0
  85. package/_site/_test/module-stream-proxy-test.js +34 -0
  86. package/_site/_test/non-release-ci-test.js +34 -34
  87. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  88. package/_site/_test/packaged-ui-smoke-test.js +11 -9
  89. package/_site/_test/path-consistency-test.js +151 -151
  90. package/_site/_test/pending-sweep-test.js +9 -9
  91. package/_site/_test/post-commit-automation-test.js +87 -87
  92. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  93. package/_site/_test/product-import-ui-test.js +92 -0
  94. package/_site/_test/project-delete-recovery-test.js +64 -64
  95. package/_site/_test/project-goal-editor-test.js +144 -144
  96. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  97. package/_site/_test/prompt-settings-test.js +115 -115
  98. package/_site/_test/protected-architecture-gate-test.js +122 -122
  99. package/_site/_test/refactor-characterization-test.js +36 -36
  100. package/_site/_test/release-version-sync-test.js +1 -1
  101. package/_site/_test/requirement-recorder-test.js +173 -173
  102. package/_site/_test/run-all-tests.js +159 -156
  103. package/_site/_test/shared-contracts-test.js +58 -58
  104. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  105. package/_site/_test/storage-foundation-test.js +78 -78
  106. package/_site/_test/structured-logger-test.js +101 -101
  107. package/_site/_test/tracking-start-test.js +109 -108
  108. package/_site/_test/workbench-permission-test.js +117 -117
  109. package/_site/_test/workspace-ui-contract-test.js +28 -43
  110. package/_site/lib/ai-profile-resolver.js +78 -78
  111. package/_site/lib/ai-workspace.js +101 -101
  112. package/_site/lib/automation-config.js +140 -140
  113. package/_site/lib/bridge-adapter.js +1 -0
  114. package/_site/lib/bridge-consumer-service.js +402 -402
  115. package/_site/lib/claude-cli-runner.js +1510 -1510
  116. package/_site/lib/commit-conversation-binder.js +234 -234
  117. package/_site/lib/commit-processing-ledger.js +27 -27
  118. package/_site/lib/commit-prompt.js +202 -202
  119. package/_site/lib/commit-reconciler.js +406 -406
  120. package/_site/lib/contracts.js +284 -279
  121. package/_site/lib/conversation-query-service.js +144 -144
  122. package/_site/lib/conversation-store.js +385 -385
  123. package/_site/lib/data-dir.js +6 -74
  124. package/_site/lib/engine-connection.js +67 -0
  125. package/_site/lib/evidence-bundle.js +228 -228
  126. package/_site/lib/folder-picker-output.js +21 -21
  127. package/_site/lib/git-runner.js +62 -62
  128. package/_site/lib/github-team-store.js +1172 -1172
  129. package/_site/lib/hook-manager.js +203 -202
  130. package/_site/lib/index-service.js +173 -173
  131. package/_site/lib/integration-installer.js +908 -907
  132. package/_site/lib/kb-framework.js +176 -176
  133. package/_site/lib/kb-validator.js +124 -124
  134. package/_site/lib/knowledge-promotion.js +435 -435
  135. package/_site/lib/knowledge-retrieval-service.js +401 -401
  136. package/_site/lib/knowledge-tool-runtime.js +359 -359
  137. package/_site/lib/llm-client.js +161 -161
  138. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  139. package/_site/lib/module-bridge.js +191 -36
  140. package/_site/lib/post-commit-automation.js +87 -87
  141. package/_site/lib/product-data.js +24 -0
  142. package/_site/lib/project-lifecycle-service.js +535 -497
  143. package/_site/lib/project-store.js +268 -262
  144. package/_site/lib/requirement-recorder.js +278 -278
  145. package/_site/lib/runtime-endpoint.js +155 -155
  146. package/_site/lib/scanner.js +298 -298
  147. package/_site/lib/server-app.js +1579 -1520
  148. package/_site/lib/settings-store.js +133 -113
  149. package/_site/lib/storage-layout.js +162 -162
  150. package/_site/lib/structured-logger.js +574 -574
  151. package/_site/scripts/folder-picker.ps1 +156 -156
  152. package/_site/scripts/hook-trigger.js +157 -156
  153. package/_site/scripts/install-module-candidates.js +69 -0
  154. package/_site/scripts/pack-module-candidates.js +72 -0
  155. package/_site/scripts/sync-release-version.js +2 -2
  156. package/_site/scripts/vendor-modules.js +47 -0
  157. package/_site/scripts/verify-module-runtime.js +45 -0
  158. package/_site/scripts/verify-product-runtime.js +34 -0
  159. package/bin/project-knowledge-mcp.js +194 -194
  160. package/docs/README.zh-CN.md +42 -29
  161. package/docs/fresh-v5-start.md +28 -0
  162. package/docs/project-registry-schema.md +22 -22
  163. package/docs/testing-strategy.md +33 -33
  164. package/module-runtime-manifest.json +220 -0
  165. package/package.json +14 -9
  166. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  167. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  168. package/plugins/project-knowledge/.mcp.json +1 -1
  169. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  170. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  171. package/templates/project-readme.md +34 -34
  172. package/ui/favicon.svg +38 -38
  173. package/ui/index.html +52 -149
  174. package/ui/product.css +9 -0
  175. package/ui/product.js +412 -0
  176. package/vendor-manifest.json +45 -0
  177. package/_site/_test/data-dir-migration-test.js +0 -77
  178. package/_site/_test/import-ui-flow-test.js +0 -171
  179. package/_site/_test/knowledge-migration-test.js +0 -75
  180. package/_site/_test/legacy-forward-compat-test.js +0 -257
  181. package/_site/_test/legacy-project-upgrade-e2e-test.js +0 -363
  182. package/_site/_test/p0-data-migration-characterization-test.js +0 -37
  183. package/_site/_test/p0-e2e-gate-test.js +0 -347
  184. package/_site/_test/project-control-panel-task14-test.js +0 -63
  185. package/_site/_test/project-layout-v2-migration-test.js +0 -127
  186. package/_site/_test/server-runtime-migration-safety-test.js +0 -27
  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/_site/_test/v4122-upgrade-data-contract-test.js +0 -56
  191. package/_site/lib/data-state-classifier.js +0 -40
  192. package/_site/lib/legacy-data-manifest.js +0 -26
  193. package/_site/lib/migration-service.js +0 -442
  194. package/ui/app.css +0 -58
  195. package/ui/app.js +0 -607
  196. package/ui/i18n.js +0 -146
@@ -1,278 +1,278 @@
1
- const crypto = require('crypto');
2
- const fs = require('fs');
3
- const path = require('path');
4
- const { spawnSync } = require('child_process');
5
- const {
6
- SCHEMAS,
7
- FIELD_LIMITS,
8
- DomainError,
9
- createId,
10
- validateProjectId,
11
- } = require('./contracts');
12
- const { StorageLayout } = require('./storage-layout');
13
- const { ProjectRegistryStore } = require('./project-registry-store');
14
- const { ProjectStore } = require('./project-store');
15
- const { ConversationStore } = require('./conversation-store');
16
-
17
- const REQUIREMENT_CLIENTS = Object.freeze(['claude', 'codex', 'opencode']);
18
- const CLIENT_ALIASES = Object.freeze({
19
- 'claude-code': 'claude',
20
- claudecode: 'claude',
21
- 'codex-cli': 'codex',
22
- });
23
-
24
- function requiredMetadata(value, name, maxLength = 512) {
25
- const normalized = String(value || '').trim();
26
- if (!normalized || normalized.length > maxLength || /[\u0000-\u001f\u007f]/.test(normalized)) {
27
- throw new DomainError('INVALID_ARGUMENT', `${name} must be a non-empty identifier no longer than ${maxLength} characters.`);
28
- }
29
- return normalized;
30
- }
31
-
32
- function optionalMetadata(value, name, maxLength = 512) {
33
- if (value == null || value === '') return null;
34
- return requiredMetadata(value, name, maxLength);
35
- }
36
-
37
- function normalizeClient(client) {
38
- const raw = String(client || '').trim().toLowerCase();
39
- const normalized = CLIENT_ALIASES[raw] || raw;
40
- if (!REQUIREMENT_CLIENTS.includes(normalized)) {
41
- throw new DomainError('INVALID_ARGUMENT', `client must be one of: ${REQUIREMENT_CLIENTS.join(', ')}.`);
42
- }
43
- return normalized;
44
- }
45
-
46
- function normalizeCommit(value, name = 'commit') {
47
- if (value == null || value === '') return null;
48
- const normalized = String(value).trim().toLowerCase();
49
- if (!/^[0-9a-f]{7,64}$/.test(normalized)) {
50
- throw new DomainError('INVALID_ARGUMENT', `${name} must be a Git object id.`);
51
- }
52
- return normalized;
53
- }
54
-
55
- function requirementHash(text) {
56
- return `sha256:${crypto.createHash('sha256').update(text, 'utf8').digest('hex')}`;
57
- }
58
-
59
- // Canonical repo-identity/v1 builder from the Bridge package (synchronous
60
- // helpers only). Missing module degrades to null identity, never a guess.
61
- let bridgeIdentityModule = null;
62
- try {
63
- const bridgeModule = require('@sanqianx/ai-coding-event-bridge-console/src/bridge');
64
- if (bridgeModule && typeof bridgeModule.buildRepoIdentityV1 === 'function') bridgeIdentityModule = bridgeModule;
65
- } catch (_) {
66
- bridgeIdentityModule = null;
67
- }
68
-
69
- class GitReader {
70
- run(repoPath, args) {
71
- return spawnSync('git', ['-C', path.resolve(repoPath), ...args], {
72
- encoding: 'utf8',
73
- windowsHide: true,
74
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
75
- });
76
- }
77
-
78
- resolveRoot(candidate) {
79
- const resolved = path.resolve(candidate || process.cwd());
80
- const gitCwd = fs.existsSync(resolved) && fs.statSync(resolved).isFile() ? path.dirname(resolved) : resolved;
81
- const result = this.run(gitCwd, ['rev-parse', '--show-toplevel']);
82
- const root = String(result.stdout || '').trim();
83
- if (result.status !== 0 || !root) {
84
- throw new DomainError('INVALID_ARGUMENT', 'repoPath must resolve to a Git worktree.');
85
- }
86
- return path.resolve(root);
87
- }
88
-
89
- currentContext(repoPath) {
90
- try {
91
- const headResult = this.run(repoPath, ['rev-parse', '--verify', 'HEAD']);
92
- const head = headResult.status === 0 ? normalizeCommit(String(headResult.stdout || '').trim(), 'HEAD') : null;
93
- const branchResult = this.run(repoPath, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
94
- const branch = branchResult.status === 0
95
- ? optionalMetadata(String(branchResult.stdout || '').trim(), 'branch', 1024)
96
- : null;
97
- const topResult = this.run(repoPath, ['rev-parse', '--show-toplevel']);
98
- const top = topResult.status === 0 && String(topResult.stdout || '').trim()
99
- ? path.resolve(String(topResult.stdout).trim())
100
- : null;
101
- const commonResult = this.run(repoPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
102
- const commonDir = commonResult.status === 0 && String(commonResult.stdout || '').trim()
103
- ? path.resolve(String(commonResult.stdout).trim())
104
- : null;
105
- let repoIdentity = null;
106
- if (top && bridgeIdentityModule) {
107
- let workspaceRoot = top;
108
- try { workspaceRoot = fs.realpathSync.native(top) || top; } catch (_) { workspaceRoot = top; }
109
- const remoteResult = this.run(repoPath, ['config', '--get', 'remote.origin.url']);
110
- const remote = remoteResult.status === 0 && String(remoteResult.stdout || '').trim()
111
- ? bridgeIdentityModule.normalizeGitUrl(String(remoteResult.stdout).trim())
112
- : null;
113
- repoIdentity = bridgeIdentityModule.buildRepoIdentityV1({ workspaceRoot, commonDir, remote });
114
- }
115
- return { headAtRecord: head, branch, repoIdentity };
116
- } catch {
117
- return { headAtRecord: null, branch: null, repoIdentity: null };
118
- }
119
- }
120
-
121
- isAncestor(repoPath, ancestor, commit) {
122
- const left = normalizeCommit(ancestor, 'ancestor');
123
- const right = normalizeCommit(commit, 'commit');
124
- if (!left || !right) return false;
125
- return this.run(repoPath, ['merge-base', '--is-ancestor', left, right]).status === 0;
126
- }
127
- }
128
-
129
- class ProjectRequirementResolver {
130
- constructor(options = {}) {
131
- this.layout = options.layout || new StorageLayout(options);
132
- this.registryStore = options.registryStore || new ProjectRegistryStore({ layout: this.layout });
133
- this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
134
- this.gitReader = options.gitReader || new GitReader();
135
- }
136
-
137
- resolve(input = {}) {
138
- const explicitProjectId = input.projectId ? validateProjectId(input.projectId) : '';
139
- const registry = this.registryStore.read({ allowMissing: true });
140
- if (explicitProjectId) {
141
- if (!registry.projects[explicitProjectId]) {
142
- throw new DomainError('PROJECT_NOT_FOUND', 'The explicit projectId is not registered.', { status: 404 });
143
- }
144
- const config = this.projectStore.readConfig(explicitProjectId);
145
- if (config.enabled === false) throw new DomainError('PROJECT_NOT_FOUND', 'The explicit project is disabled.', { status: 404 });
146
- if (input.repoPath) {
147
- const root = this.gitReader.resolveRoot(input.repoPath);
148
- if (!this.layout.pathsEqual(root, config.repoPath)) {
149
- throw new DomainError('PROJECT_NOT_FOUND', 'repoPath does not match the explicit projectId.', { status: 404 });
150
- }
151
- }
152
- return { projectId: explicitProjectId, config };
153
- }
154
-
155
- const root = this.gitReader.resolveRoot(input.repoPath || process.cwd());
156
- const matches = registry.projectOrder.filter(projectId => {
157
- const config = this.projectStore.readConfig(projectId);
158
- return config.enabled !== false && this.layout.pathsEqual(config.repoPath, root);
159
- });
160
- if (matches.length === 0) {
161
- throw new DomainError('PROJECT_NOT_FOUND', 'No enabled project is registered for the current Git root.', { status: 404 });
162
- }
163
- if (matches.length > 1) {
164
- throw new DomainError('PROJECT_AMBIGUOUS', 'Multiple projects are registered for the current Git root.', { status: 409 });
165
- }
166
- const projectId = matches[0];
167
- return { projectId, config: this.projectStore.readConfig(projectId) };
168
- }
169
- }
170
-
171
- class RequirementRecorder {
172
- constructor(options = {}) {
173
- this.layout = options.layout || new StorageLayout(options);
174
- this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
175
- this.gitReader = options.gitReader || new GitReader();
176
- this.resolver = options.resolver || new ProjectRequirementResolver({
177
- layout: this.layout,
178
- projectStore: this.projectStore,
179
- registryStore: options.registryStore,
180
- gitReader: this.gitReader,
181
- });
182
- this.logger = options.logger || null;
183
- this.conversationStore = options.conversationStore || new ConversationStore({
184
- layout: this.layout,
185
- projectStore: this.projectStore,
186
- logger: this.logger,
187
- });
188
- this.now = options.now || (() => new Date().toISOString());
189
- this.createRequirementId = options.createRequirementId || (() => createId('req'));
190
- }
191
-
192
- async recordRequirement(input = {}) {
193
- const operationId = input.operationId || createId('op');
194
- try {
195
- const text = typeof input.text === 'string'
196
- ? input.text
197
- : typeof input.requirement === 'string' ? input.requirement : '';
198
- if (!text.trim()) throw new DomainError('INVALID_ARGUMENT', 'Requirement text must be non-empty.', { operationId });
199
- if (text.length > FIELD_LIMITS.requirement) {
200
- throw new DomainError('INVALID_ARGUMENT', `Requirement text exceeds ${FIELD_LIMITS.requirement} characters.`, { operationId });
201
- }
202
- const client = normalizeClient(input.client);
203
- const sessionId = requiredMetadata(input.sessionId, 'sessionId');
204
- const conversationId = optionalMetadata(input.conversationId, 'conversationId');
205
- const explicitCommit = normalizeCommit(input.explicitCommit, 'explicitCommit');
206
- const resolved = this.resolver.resolve(input);
207
- const gitContext = this.gitReader.currentContext(resolved.config.repoPath);
208
- const record = {
209
- schema: SCHEMAS.requirement,
210
- id: this.createRequirementId(),
211
- ts: this.now(),
212
- projectId: resolved.projectId,
213
- client,
214
- sessionId,
215
- conversationId,
216
- branch: gitContext.branch || null,
217
- headAtRecord: gitContext.headAtRecord || null,
218
- requirement: text,
219
- requirementHash: requirementHash(text),
220
- explicitCommit,
221
- };
222
- const source = client === 'claude' ? 'claude-code' : client;
223
- const turnId = optionalMetadata(input.turnId, 'turnId') || `explicit-${record.id}`;
224
- await this.conversationStore.appendEvent(resolved.projectId, {
225
- eventId: `explicit-${record.id}`,
226
- sequence: null,
227
- source,
228
- eventType: 'user_prompt',
229
- role: 'user',
230
- content: text,
231
- sessionId,
232
- turnId,
233
- projectPath: resolved.config.repoPath,
234
- repoIdentity: gitContext.repoIdentity,
235
- branch: record.branch,
236
- headAtCapture: record.headAtRecord,
237
- capturedAt: record.ts,
238
- rawEventType: 'explicit-requirement-adapter',
239
- identityConfidence: explicitCommit ? 'explicit' : 'high',
240
- captureStatus: 'explicit-supplement',
241
- explicitCommitSha: explicitCommit,
242
- legacyRequirementId: record.id,
243
- });
244
- if (this.logger && typeof this.logger.info === 'function') {
245
- await this.logger.info('requirement.recorded', 'User requirement recorded.', {
246
- operationId,
247
- projectId: resolved.projectId,
248
- requirementId: record.id,
249
- client,
250
- sessionId,
251
- requirementHash: record.requirementHash,
252
- });
253
- }
254
- return { ...record, turnId };
255
- } catch (error) {
256
- if (error instanceof DomainError) {
257
- if (!error.operationId) error.operationId = operationId;
258
- throw error;
259
- }
260
- throw new DomainError('INVALID_ARGUMENT', 'Requirement could not be recorded durably.', {
261
- status: 500,
262
- retryable: true,
263
- operationId,
264
- cause: error,
265
- });
266
- }
267
- }
268
- }
269
-
270
- module.exports = {
271
- REQUIREMENT_CLIENTS,
272
- GitReader,
273
- ProjectRequirementResolver,
274
- RequirementRecorder,
275
- normalizeClient,
276
- normalizeCommit,
277
- requirementHash,
278
- };
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { spawnSync } = require('child_process');
5
+ const {
6
+ SCHEMAS,
7
+ FIELD_LIMITS,
8
+ DomainError,
9
+ createId,
10
+ validateProjectId,
11
+ } = require('./contracts');
12
+ const { StorageLayout } = require('./storage-layout');
13
+ const { ProjectRegistryStore } = require('./project-registry-store');
14
+ const { ProjectStore } = require('./project-store');
15
+ const { ConversationStore } = require('./conversation-store');
16
+
17
+ const REQUIREMENT_CLIENTS = Object.freeze(['claude', 'codex', 'opencode']);
18
+ const CLIENT_ALIASES = Object.freeze({
19
+ 'claude-code': 'claude',
20
+ claudecode: 'claude',
21
+ 'codex-cli': 'codex',
22
+ });
23
+
24
+ function requiredMetadata(value, name, maxLength = 512) {
25
+ const normalized = String(value || '').trim();
26
+ if (!normalized || normalized.length > maxLength || /[\u0000-\u001f\u007f]/.test(normalized)) {
27
+ throw new DomainError('INVALID_ARGUMENT', `${name} must be a non-empty identifier no longer than ${maxLength} characters.`);
28
+ }
29
+ return normalized;
30
+ }
31
+
32
+ function optionalMetadata(value, name, maxLength = 512) {
33
+ if (value == null || value === '') return null;
34
+ return requiredMetadata(value, name, maxLength);
35
+ }
36
+
37
+ function normalizeClient(client) {
38
+ const raw = String(client || '').trim().toLowerCase();
39
+ const normalized = CLIENT_ALIASES[raw] || raw;
40
+ if (!REQUIREMENT_CLIENTS.includes(normalized)) {
41
+ throw new DomainError('INVALID_ARGUMENT', `client must be one of: ${REQUIREMENT_CLIENTS.join(', ')}.`);
42
+ }
43
+ return normalized;
44
+ }
45
+
46
+ function normalizeCommit(value, name = 'commit') {
47
+ if (value == null || value === '') return null;
48
+ const normalized = String(value).trim().toLowerCase();
49
+ if (!/^[0-9a-f]{7,64}$/.test(normalized)) {
50
+ throw new DomainError('INVALID_ARGUMENT', `${name} must be a Git object id.`);
51
+ }
52
+ return normalized;
53
+ }
54
+
55
+ function requirementHash(text) {
56
+ return `sha256:${crypto.createHash('sha256').update(text, 'utf8').digest('hex')}`;
57
+ }
58
+
59
+ // Canonical repo-identity/v1 builder from the Bridge package (synchronous
60
+ // helpers only). Missing module degrades to null identity, never a guess.
61
+ let bridgeIdentityModule = null;
62
+ try {
63
+ const bridgeModule = require('@sanqianx/ai-coding-event-bridge-console/src/bridge');
64
+ if (bridgeModule && typeof bridgeModule.buildRepoIdentityV1 === 'function') bridgeIdentityModule = bridgeModule;
65
+ } catch (_) {
66
+ bridgeIdentityModule = null;
67
+ }
68
+
69
+ class GitReader {
70
+ run(repoPath, args) {
71
+ return spawnSync('git', ['-C', path.resolve(repoPath), ...args], {
72
+ encoding: 'utf8',
73
+ windowsHide: true,
74
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
75
+ });
76
+ }
77
+
78
+ resolveRoot(candidate) {
79
+ const resolved = path.resolve(candidate || process.cwd());
80
+ const gitCwd = fs.existsSync(resolved) && fs.statSync(resolved).isFile() ? path.dirname(resolved) : resolved;
81
+ const result = this.run(gitCwd, ['rev-parse', '--show-toplevel']);
82
+ const root = String(result.stdout || '').trim();
83
+ if (result.status !== 0 || !root) {
84
+ throw new DomainError('INVALID_ARGUMENT', 'repoPath must resolve to a Git worktree.');
85
+ }
86
+ return path.resolve(root);
87
+ }
88
+
89
+ currentContext(repoPath) {
90
+ try {
91
+ const headResult = this.run(repoPath, ['rev-parse', '--verify', 'HEAD']);
92
+ const head = headResult.status === 0 ? normalizeCommit(String(headResult.stdout || '').trim(), 'HEAD') : null;
93
+ const branchResult = this.run(repoPath, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
94
+ const branch = branchResult.status === 0
95
+ ? optionalMetadata(String(branchResult.stdout || '').trim(), 'branch', 1024)
96
+ : null;
97
+ const topResult = this.run(repoPath, ['rev-parse', '--show-toplevel']);
98
+ const top = topResult.status === 0 && String(topResult.stdout || '').trim()
99
+ ? path.resolve(String(topResult.stdout).trim())
100
+ : null;
101
+ const commonResult = this.run(repoPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
102
+ const commonDir = commonResult.status === 0 && String(commonResult.stdout || '').trim()
103
+ ? path.resolve(String(commonResult.stdout).trim())
104
+ : null;
105
+ let repoIdentity = null;
106
+ if (top && bridgeIdentityModule) {
107
+ let workspaceRoot = top;
108
+ try { workspaceRoot = fs.realpathSync.native(top) || top; } catch (_) { workspaceRoot = top; }
109
+ const remoteResult = this.run(repoPath, ['config', '--get', 'remote.origin.url']);
110
+ const remote = remoteResult.status === 0 && String(remoteResult.stdout || '').trim()
111
+ ? bridgeIdentityModule.normalizeGitUrl(String(remoteResult.stdout).trim())
112
+ : null;
113
+ repoIdentity = bridgeIdentityModule.buildRepoIdentityV1({ workspaceRoot, commonDir, remote });
114
+ }
115
+ return { headAtRecord: head, branch, repoIdentity };
116
+ } catch {
117
+ return { headAtRecord: null, branch: null, repoIdentity: null };
118
+ }
119
+ }
120
+
121
+ isAncestor(repoPath, ancestor, commit) {
122
+ const left = normalizeCommit(ancestor, 'ancestor');
123
+ const right = normalizeCommit(commit, 'commit');
124
+ if (!left || !right) return false;
125
+ return this.run(repoPath, ['merge-base', '--is-ancestor', left, right]).status === 0;
126
+ }
127
+ }
128
+
129
+ class ProjectRequirementResolver {
130
+ constructor(options = {}) {
131
+ this.layout = options.layout || new StorageLayout(options);
132
+ this.registryStore = options.registryStore || new ProjectRegistryStore({ layout: this.layout });
133
+ this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
134
+ this.gitReader = options.gitReader || new GitReader();
135
+ }
136
+
137
+ resolve(input = {}) {
138
+ const explicitProjectId = input.projectId ? validateProjectId(input.projectId) : '';
139
+ const registry = this.registryStore.read({ allowMissing: true });
140
+ if (explicitProjectId) {
141
+ if (!registry.projects[explicitProjectId]) {
142
+ throw new DomainError('PROJECT_NOT_FOUND', 'The explicit projectId is not registered.', { status: 404 });
143
+ }
144
+ const config = this.projectStore.readConfig(explicitProjectId);
145
+ if (config.enabled === false) throw new DomainError('PROJECT_NOT_FOUND', 'The explicit project is disabled.', { status: 404 });
146
+ if (input.repoPath) {
147
+ const root = this.gitReader.resolveRoot(input.repoPath);
148
+ if (!this.layout.pathsEqual(root, config.repoPath)) {
149
+ throw new DomainError('PROJECT_NOT_FOUND', 'repoPath does not match the explicit projectId.', { status: 404 });
150
+ }
151
+ }
152
+ return { projectId: explicitProjectId, config };
153
+ }
154
+
155
+ const root = this.gitReader.resolveRoot(input.repoPath || process.cwd());
156
+ const matches = registry.projectOrder.filter(projectId => {
157
+ const config = this.projectStore.readConfig(projectId);
158
+ return config.enabled !== false && this.layout.pathsEqual(config.repoPath, root);
159
+ });
160
+ if (matches.length === 0) {
161
+ throw new DomainError('PROJECT_NOT_FOUND', 'No enabled project is registered for the current Git root.', { status: 404 });
162
+ }
163
+ if (matches.length > 1) {
164
+ throw new DomainError('PROJECT_AMBIGUOUS', 'Multiple projects are registered for the current Git root.', { status: 409 });
165
+ }
166
+ const projectId = matches[0];
167
+ return { projectId, config: this.projectStore.readConfig(projectId) };
168
+ }
169
+ }
170
+
171
+ class RequirementRecorder {
172
+ constructor(options = {}) {
173
+ this.layout = options.layout || new StorageLayout(options);
174
+ this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
175
+ this.gitReader = options.gitReader || new GitReader();
176
+ this.resolver = options.resolver || new ProjectRequirementResolver({
177
+ layout: this.layout,
178
+ projectStore: this.projectStore,
179
+ registryStore: options.registryStore,
180
+ gitReader: this.gitReader,
181
+ });
182
+ this.logger = options.logger || null;
183
+ this.conversationStore = options.conversationStore || new ConversationStore({
184
+ layout: this.layout,
185
+ projectStore: this.projectStore,
186
+ logger: this.logger,
187
+ });
188
+ this.now = options.now || (() => new Date().toISOString());
189
+ this.createRequirementId = options.createRequirementId || (() => createId('req'));
190
+ }
191
+
192
+ async recordRequirement(input = {}) {
193
+ const operationId = input.operationId || createId('op');
194
+ try {
195
+ const text = typeof input.text === 'string'
196
+ ? input.text
197
+ : typeof input.requirement === 'string' ? input.requirement : '';
198
+ if (!text.trim()) throw new DomainError('INVALID_ARGUMENT', 'Requirement text must be non-empty.', { operationId });
199
+ if (text.length > FIELD_LIMITS.requirement) {
200
+ throw new DomainError('INVALID_ARGUMENT', `Requirement text exceeds ${FIELD_LIMITS.requirement} characters.`, { operationId });
201
+ }
202
+ const client = normalizeClient(input.client);
203
+ const sessionId = requiredMetadata(input.sessionId, 'sessionId');
204
+ const conversationId = optionalMetadata(input.conversationId, 'conversationId');
205
+ const explicitCommit = normalizeCommit(input.explicitCommit, 'explicitCommit');
206
+ const resolved = this.resolver.resolve(input);
207
+ const gitContext = this.gitReader.currentContext(resolved.config.repoPath);
208
+ const record = {
209
+ schema: SCHEMAS.requirement,
210
+ id: this.createRequirementId(),
211
+ ts: this.now(),
212
+ projectId: resolved.projectId,
213
+ client,
214
+ sessionId,
215
+ conversationId,
216
+ branch: gitContext.branch || null,
217
+ headAtRecord: gitContext.headAtRecord || null,
218
+ requirement: text,
219
+ requirementHash: requirementHash(text),
220
+ explicitCommit,
221
+ };
222
+ const source = client === 'claude' ? 'claude-code' : client;
223
+ const turnId = optionalMetadata(input.turnId, 'turnId') || `explicit-${record.id}`;
224
+ await this.conversationStore.appendEvent(resolved.projectId, {
225
+ eventId: `explicit-${record.id}`,
226
+ sequence: null,
227
+ source,
228
+ eventType: 'user_prompt',
229
+ role: 'user',
230
+ content: text,
231
+ sessionId,
232
+ turnId,
233
+ projectPath: resolved.config.repoPath,
234
+ repoIdentity: gitContext.repoIdentity,
235
+ branch: record.branch,
236
+ headAtCapture: record.headAtRecord,
237
+ capturedAt: record.ts,
238
+ rawEventType: 'explicit-requirement-adapter',
239
+ identityConfidence: explicitCommit ? 'explicit' : 'high',
240
+ captureStatus: 'explicit-supplement',
241
+ explicitCommitSha: explicitCommit,
242
+ legacyRequirementId: record.id,
243
+ });
244
+ if (this.logger && typeof this.logger.info === 'function') {
245
+ await this.logger.info('requirement.recorded', 'User requirement recorded.', {
246
+ operationId,
247
+ projectId: resolved.projectId,
248
+ requirementId: record.id,
249
+ client,
250
+ sessionId,
251
+ requirementHash: record.requirementHash,
252
+ });
253
+ }
254
+ return { ...record, turnId };
255
+ } catch (error) {
256
+ if (error instanceof DomainError) {
257
+ if (!error.operationId) error.operationId = operationId;
258
+ throw error;
259
+ }
260
+ throw new DomainError('INVALID_ARGUMENT', 'Requirement could not be recorded durably.', {
261
+ status: 500,
262
+ retryable: true,
263
+ operationId,
264
+ cause: error,
265
+ });
266
+ }
267
+ }
268
+ }
269
+
270
+ module.exports = {
271
+ REQUIREMENT_CLIENTS,
272
+ GitReader,
273
+ ProjectRequirementResolver,
274
+ RequirementRecorder,
275
+ normalizeClient,
276
+ normalizeCommit,
277
+ requirementHash,
278
+ };