@sanqianx/project-knowledge 4.6.1

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 (218) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +17 -0
  3. package/CHANGELOG.md +780 -0
  4. package/LICENSE +201 -0
  5. package/NOTICE +5 -0
  6. package/README.md +266 -0
  7. package/_site/README.md +30 -0
  8. package/_site/_test/ai-profile-resolver-test.js +137 -0
  9. package/_site/_test/ai-profile-test.js +75 -0
  10. package/_site/_test/ai-vendor-presets-test.js +91 -0
  11. package/_site/_test/automation-queue-test.js +14 -0
  12. package/_site/_test/automation-ui-test.js +40 -0
  13. package/_site/_test/background-task-registry-test.js +43 -0
  14. package/_site/_test/baseline-schema-test.js +91 -0
  15. package/_site/_test/bin-cli-test.js +218 -0
  16. package/_site/_test/bridge-adapter-test.js +95 -0
  17. package/_site/_test/bridge-consumer-service-test.js +310 -0
  18. package/_site/_test/cdp-browser-failure-test.js +100 -0
  19. package/_site/_test/chat-claudecodeui-match-test.js +92 -0
  20. package/_site/_test/claude-executable-discovery-test.js +90 -0
  21. package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -0
  22. package/_site/_test/claude-workbench-test.js +170 -0
  23. package/_site/_test/client-capture-restart-e2e-test.js +189 -0
  24. package/_site/_test/codex-conversation-projection-test.js +59 -0
  25. package/_site/_test/codex-notify-fanout-test.js +45 -0
  26. package/_site/_test/commit-boundary-freeze-test.js +147 -0
  27. package/_site/_test/commit-conversation-binding-test.js +99 -0
  28. package/_site/_test/commit-evidence-test.js +110 -0
  29. package/_site/_test/context-pack-test.js +198 -0
  30. package/_site/_test/conversation-api-test.js +119 -0
  31. package/_site/_test/conversation-store-test.js +136 -0
  32. package/_site/_test/cross-repo-isolation-e2e-test.js +187 -0
  33. package/_site/_test/data-dir-migration-test.js +77 -0
  34. package/_site/_test/desktop-browser-compat-test.js +28 -0
  35. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -0
  36. package/_site/_test/embedding-config-test.js +32 -0
  37. package/_site/_test/explicit-commit-processor-test.js +37 -0
  38. package/_site/_test/fixtures/fake-browser-exit.js +10 -0
  39. package/_site/_test/fixtures/fake-browser-hang.js +10 -0
  40. package/_site/_test/fixtures/make-git-repos.js +89 -0
  41. package/_site/_test/folder-picker-output-test.js +19 -0
  42. package/_site/_test/full-integration-e2e-test.js +165 -0
  43. package/_site/_test/git-validation-test.js +81 -0
  44. package/_site/_test/hook-runtime-endpoint-test.js +88 -0
  45. package/_site/_test/hook-status-repair-api-test.js +152 -0
  46. package/_site/_test/hook-trigger-test.js +85 -0
  47. package/_site/_test/hook-worktree-test.js +42 -0
  48. package/_site/_test/import-preflight-api-test.js +233 -0
  49. package/_site/_test/import-ui-flow-test.js +171 -0
  50. package/_site/_test/index-builder-test.js +41 -0
  51. package/_site/_test/index-writer-concurrency-test.js +135 -0
  52. package/_site/_test/integration-adapters-test.js +243 -0
  53. package/_site/_test/integration-capture-setup-test.js +108 -0
  54. package/_site/_test/integration-surface-coverage-test.js +165 -0
  55. package/_site/_test/kb-framework-test.js +57 -0
  56. package/_site/_test/kbpath-follow-test.js +63 -0
  57. package/_site/_test/knowledge-db-test.js +144 -0
  58. package/_site/_test/knowledge-language-control-test.js +170 -0
  59. package/_site/_test/knowledge-maintenance-test.js +40 -0
  60. package/_site/_test/knowledge-migration-test.js +75 -0
  61. package/_site/_test/knowledge-promotion-recovery-test.js +260 -0
  62. package/_site/_test/knowledge-query-test.js +54 -0
  63. package/_site/_test/knowledge-retrieval-service-test.js +77 -0
  64. package/_site/_test/knowledge-scopes-test.js +37 -0
  65. package/_site/_test/knowledge-storage-location-test.js +28 -0
  66. package/_site/_test/knowledge-storage-startup-test.js +52 -0
  67. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -0
  68. package/_site/_test/legacy-claude-session-alias-test.js +106 -0
  69. package/_site/_test/legacy-forward-compat-test.js +257 -0
  70. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -0
  71. package/_site/_test/legacy-routes-removed-test.js +47 -0
  72. package/_site/_test/legacy-workbench-exclusion-test.js +92 -0
  73. package/_site/_test/log-redaction-test.js +58 -0
  74. package/_site/_test/logging-api-test.js +89 -0
  75. package/_site/_test/logging-sse-no-gap-test.js +88 -0
  76. package/_site/_test/logging-ui-test.js +104 -0
  77. package/_site/_test/markdown-delta-overlay-test.js +85 -0
  78. package/_site/_test/markdown-maintenance-api-test.js +75 -0
  79. package/_site/_test/markdown-maintenance-test.js +11 -0
  80. package/_site/_test/mcp-server-test.js +149 -0
  81. package/_site/_test/model-context-windows-test.js +89 -0
  82. package/_site/_test/module-bridge-eventbridge-test.js +193 -0
  83. package/_site/_test/non-release-ci-test.js +34 -0
  84. package/_site/_test/offline-boundary-isolation-test.js +32 -0
  85. package/_site/_test/orphaned-claim-recovery-test.js +80 -0
  86. package/_site/_test/p0-data-migration-characterization-test.js +37 -0
  87. package/_site/_test/p0-e2e-gate-test.js +347 -0
  88. package/_site/_test/package-boundary-test.js +42 -0
  89. package/_site/_test/package-startup-test.js +56 -0
  90. package/_site/_test/packaged-ui-smoke-test.js +79 -0
  91. package/_site/_test/path-consistency-test.js +151 -0
  92. package/_site/_test/pending-sweep-test.js +9 -0
  93. package/_site/_test/post-commit-automation-test.js +87 -0
  94. package/_site/_test/pr-consumer-contract-test.js +55 -0
  95. package/_site/_test/project-control-panel-task14-test.js +63 -0
  96. package/_site/_test/project-delete-recovery-test.js +64 -0
  97. package/_site/_test/project-goal-editor-test.js +145 -0
  98. package/_site/_test/project-layout-v2-migration-test.js +127 -0
  99. package/_site/_test/project-lifecycle-transaction-test.js +106 -0
  100. package/_site/_test/project-remove-running-guard-test.js +79 -0
  101. package/_site/_test/project-store-test.js +90 -0
  102. package/_site/_test/prompt-settings-test.js +115 -0
  103. package/_site/_test/protected-architecture-gate-test.js +123 -0
  104. package/_site/_test/refactor-characterization-test.js +36 -0
  105. package/_site/_test/release-version-sync-test.js +98 -0
  106. package/_site/_test/requirement-binding-test.js +113 -0
  107. package/_site/_test/requirement-recorder-test.js +173 -0
  108. package/_site/_test/run-all-tests.js +156 -0
  109. package/_site/_test/runtime-endpoint-test.js +64 -0
  110. package/_site/_test/scanner-test.js +83 -0
  111. package/_site/_test/server-runtime-migration-safety-test.js +27 -0
  112. package/_site/_test/server-security-test.js +96 -0
  113. package/_site/_test/sessions-stream-test.js +92 -0
  114. package/_site/_test/shared-contracts-test.js +58 -0
  115. package/_site/_test/simple-import-test.js +97 -0
  116. package/_site/_test/startup-analysis-disabled-test.js +16 -0
  117. package/_site/_test/storage-foundation-test.js +78 -0
  118. package/_site/_test/structured-logger-test.js +101 -0
  119. package/_site/_test/task15-20-ui-flow-test.js +148 -0
  120. package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -0
  121. package/_site/_test/team-knowledge-store-test.js +131 -0
  122. package/_site/_test/tracking-start-test.js +143 -0
  123. package/_site/_test/ui-i18n-toggle-test.js +114 -0
  124. package/_site/_test/ui-smoke-test.js +73 -0
  125. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -0
  126. package/_site/_test/workbench-permission-test.js +118 -0
  127. package/_site/_test/workspace-ui-contract-test.js +43 -0
  128. package/_site/lib/ai-profile-resolver.js +78 -0
  129. package/_site/lib/ai-vendor-presets.js +83 -0
  130. package/_site/lib/ai-workspace.js +104 -0
  131. package/_site/lib/atomic-file.js +204 -0
  132. package/_site/lib/automation-config.js +140 -0
  133. package/_site/lib/bridge-adapter.js +256 -0
  134. package/_site/lib/bridge-consumer-service.js +402 -0
  135. package/_site/lib/claude-cli-runner.js +1599 -0
  136. package/_site/lib/commit-conversation-binder.js +246 -0
  137. package/_site/lib/commit-processing-ledger.js +27 -0
  138. package/_site/lib/commit-prompt.js +202 -0
  139. package/_site/lib/commit-reconciler.js +444 -0
  140. package/_site/lib/context-pack-builder.js +299 -0
  141. package/_site/lib/contracts.js +279 -0
  142. package/_site/lib/conversation-exclusions.js +204 -0
  143. package/_site/lib/conversation-query-service.js +161 -0
  144. package/_site/lib/conversation-store.js +385 -0
  145. package/_site/lib/data-dir.js +81 -0
  146. package/_site/lib/data-state-classifier.js +40 -0
  147. package/_site/lib/embedding-service.js +85 -0
  148. package/_site/lib/evidence-bundle.js +228 -0
  149. package/_site/lib/folder-picker-output.js +24 -0
  150. package/_site/lib/git-runner.js +62 -0
  151. package/_site/lib/github-team-store.js +1175 -0
  152. package/_site/lib/hook-manager.js +202 -0
  153. package/_site/lib/index-builder.js +157 -0
  154. package/_site/lib/index-service.js +173 -0
  155. package/_site/lib/integration-installer.js +907 -0
  156. package/_site/lib/kb-framework.js +191 -0
  157. package/_site/lib/kb-validator.js +124 -0
  158. package/_site/lib/knowledge-db.js +363 -0
  159. package/_site/lib/knowledge-promotion.js +435 -0
  160. package/_site/lib/knowledge-retrieval-service.js +401 -0
  161. package/_site/lib/knowledge-schema.js +121 -0
  162. package/_site/lib/knowledge-tool-runtime.js +359 -0
  163. package/_site/lib/legacy-data-manifest.js +26 -0
  164. package/_site/lib/llm-client.js +173 -0
  165. package/_site/lib/markdown-knowledge-indexer.js +230 -0
  166. package/_site/lib/migration-service.js +442 -0
  167. package/_site/lib/model-context-windows.js +82 -0
  168. package/_site/lib/module-bridge.js +496 -0
  169. package/_site/lib/post-commit-automation.js +141 -0
  170. package/_site/lib/project-lifecycle-service.js +511 -0
  171. package/_site/lib/project-registry-store.js +129 -0
  172. package/_site/lib/project-store.js +262 -0
  173. package/_site/lib/prompt-registry.js +148 -0
  174. package/_site/lib/requirement-adapters.js +10 -0
  175. package/_site/lib/requirement-binder.js +112 -0
  176. package/_site/lib/requirement-recorder.js +278 -0
  177. package/_site/lib/runtime-endpoint.js +160 -0
  178. package/_site/lib/scanner.js +298 -0
  179. package/_site/lib/server-app.js +1520 -0
  180. package/_site/lib/settings-store.js +113 -0
  181. package/_site/lib/storage-layout.js +162 -0
  182. package/_site/lib/structured-logger.js +574 -0
  183. package/_site/scripts/codex-notify-fanout.cjs +51 -0
  184. package/_site/scripts/folder-picker.ps1 +156 -0
  185. package/_site/scripts/hook-trigger.js +156 -0
  186. package/_site/scripts/sync-release-version.js +158 -0
  187. package/_site/server.js +12 -0
  188. package/_site/start.bat +26 -0
  189. package/_site/stop.bat +11 -0
  190. package/bin/project-knowledge-integrations.js +241 -0
  191. package/bin/project-knowledge-kb.js +65 -0
  192. package/bin/project-knowledge-mcp.js +195 -0
  193. package/bin/project-knowledge.js +439 -0
  194. package/claude-prompts.json +21 -0
  195. package/docs/README.zh-CN.md +175 -0
  196. package/docs/assets/architecture.svg +182 -0
  197. package/docs/assets/dashboard.png +0 -0
  198. package/docs/assets/draft-review.png +0 -0
  199. package/docs/assets/logo.svg +50 -0
  200. package/docs/assets/runs-drafts.png +0 -0
  201. package/docs/assets/settings.png +0 -0
  202. package/docs/project-registry-schema.md +33 -0
  203. package/docs/team-knowledge-mode-a-plan.md +73 -0
  204. package/docs/testing-strategy.md +33 -0
  205. package/package.json +100 -0
  206. package/plugins/project-knowledge/.claude-plugin/plugin.json +19 -0
  207. package/plugins/project-knowledge/.codex-plugin/plugin.json +38 -0
  208. package/plugins/project-knowledge/.mcp.json +14 -0
  209. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -0
  210. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -0
  211. package/plugins/project-knowledge/skills/project-knowledge/agents/openai.yaml +11 -0
  212. package/templates/change.md +30 -0
  213. package/templates/project-readme.md +52 -0
  214. package/ui/app.css +58 -0
  215. package/ui/app.js +607 -0
  216. package/ui/favicon.svg +38 -0
  217. package/ui/i18n.js +146 -0
  218. package/ui/index.html +162 -0
@@ -0,0 +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');
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
+ };
@@ -0,0 +1,160 @@
1
+ // Stable discovery record for the one local project-knowledge backend.
2
+ //
3
+ // Git hooks and the desktop shell must not bake in a port: the CLI can fall
4
+ // back from 5757 when that port is occupied. This small file lives in the
5
+ // version-independent data directory and is replaced atomically whenever a
6
+ // backend starts.
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ const SCHEMA = 'project-knowledge/runtime-endpoint/v1';
12
+ const FILENAME = 'runtime-endpoint.json';
13
+
14
+ function endpointPath(dataDir) {
15
+ return path.join(path.resolve(dataDir), FILENAME);
16
+ }
17
+
18
+ function isLoopbackHost(host) {
19
+ const value = String(host || '').trim().toLowerCase();
20
+ return value === '127.0.0.1' || value === 'localhost' || value === '::1';
21
+ }
22
+
23
+ function normalizeEndpoint(value) {
24
+ if (!value || typeof value !== 'object') return null;
25
+ const pid = Number(value.pid);
26
+ const port = Number(value.port);
27
+ const host = String(value.host || '127.0.0.1').trim();
28
+ if (!Number.isInteger(pid) || pid <= 0) return null;
29
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
30
+ // Runtime discovery is intentionally local-only. Never let a modified
31
+ // endpoint file make hooks send repository metadata to a remote host.
32
+ if (!isLoopbackHost(host)) return null;
33
+ return {
34
+ schema: SCHEMA,
35
+ pid,
36
+ host,
37
+ port,
38
+ mode: String(value.mode || 'cli'),
39
+ startedAt: String(value.startedAt || ''),
40
+ };
41
+ }
42
+
43
+ function readEndpoint(dataDir) {
44
+ try {
45
+ const parsed = JSON.parse(fs.readFileSync(endpointPath(dataDir), 'utf-8'));
46
+ if (parsed.schema !== SCHEMA) return null;
47
+ return normalizeEndpoint(parsed);
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function isProcessAlive(pid) {
54
+ try {
55
+ process.kill(Number(pid), 0);
56
+ return true;
57
+ } catch (error) {
58
+ // EPERM means the process exists but we lack permission to signal it
59
+ // (common on Windows when the daemon and this process run at different
60
+ // privilege levels). Treat that as alive — only ESRCH/ENOENT mean dead.
61
+ // Misjudging a live process as dead would delete a running backend's
62
+ // endpoint file (see readLiveEndpoint) and spawn a duplicate.
63
+ if (error && error.code === 'EPERM') return true;
64
+ return false;
65
+ }
66
+ }
67
+
68
+ function readLiveEndpoint(dataDir, { removeStale = true } = {}) {
69
+ const endpoint = readEndpoint(dataDir);
70
+ if (!endpoint) return null;
71
+ if (isProcessAlive(endpoint.pid)) return endpoint;
72
+ if (removeStale) clearEndpoint(dataDir, { pid: endpoint.pid });
73
+ return null;
74
+ }
75
+
76
+ function writeEndpoint(dataDir, value) {
77
+ const endpoint = normalizeEndpoint({
78
+ ...value,
79
+ startedAt: value && value.startedAt || new Date().toISOString(),
80
+ });
81
+ if (!endpoint) throw new Error('invalid runtime endpoint');
82
+ const target = endpointPath(dataDir);
83
+ const temp = `${target}.${process.pid}.tmp`;
84
+ fs.mkdirSync(path.dirname(target), { recursive: true });
85
+ fs.writeFileSync(temp, JSON.stringify(endpoint, null, 2) + '\n', 'utf-8');
86
+ try {
87
+ fs.renameSync(temp, target);
88
+ } catch (error) {
89
+ // Windows cannot always replace an existing file with renameSync.
90
+ try { fs.rmSync(target, { force: true }); } catch {
91
+ // The following rename is authoritative and reports endpoint replacement failure.
92
+ }
93
+ fs.renameSync(temp, target);
94
+ }
95
+ return endpoint;
96
+ }
97
+
98
+ function claimEndpoint(dataDir, value) {
99
+ const endpoint = normalizeEndpoint({
100
+ ...value,
101
+ startedAt: value && value.startedAt || new Date().toISOString(),
102
+ });
103
+ if (!endpoint) throw new Error('invalid runtime endpoint');
104
+ const target = endpointPath(dataDir);
105
+ fs.mkdirSync(path.dirname(target), { recursive: true });
106
+
107
+ for (let attempt = 0; attempt < 2; attempt++) {
108
+ try {
109
+ fs.writeFileSync(target, JSON.stringify(endpoint, null, 2) + '\n', {
110
+ encoding: 'utf-8',
111
+ flag: 'wx',
112
+ });
113
+ return { claimed: true, endpoint };
114
+ } catch (error) {
115
+ if (!error || error.code !== 'EEXIST') throw error;
116
+ const existing = readEndpoint(dataDir);
117
+ if (existing && isProcessAlive(existing.pid)) {
118
+ return { claimed: false, endpoint: existing };
119
+ }
120
+ // A just-created file can briefly be unreadable while another process
121
+ // writes it. Treat it as busy rather than deleting a concurrent claim.
122
+ try {
123
+ const ageMs = Date.now() - fs.statSync(target).mtimeMs;
124
+ if (!existing && ageMs < 2000) return { claimed: false, endpoint: null };
125
+ } catch {
126
+ // clearEndpoint performs the ownership-safe final check when stat is unavailable.
127
+ }
128
+ clearEndpoint(dataDir, existing ? { pid: existing.pid } : {});
129
+ }
130
+ }
131
+ return { claimed: false, endpoint: readLiveEndpoint(dataDir) };
132
+ }
133
+
134
+ function clearEndpoint(dataDir, { pid } = {}) {
135
+ const target = endpointPath(dataDir);
136
+ if (pid != null) {
137
+ const current = readEndpoint(dataDir);
138
+ if (current && current.pid !== Number(pid)) return false;
139
+ }
140
+ try {
141
+ fs.rmSync(target, { force: true });
142
+ return true;
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ module.exports = {
149
+ SCHEMA,
150
+ FILENAME,
151
+ endpointPath,
152
+ isLoopbackHost,
153
+ normalizeEndpoint,
154
+ readEndpoint,
155
+ readLiveEndpoint,
156
+ writeEndpoint,
157
+ claimEndpoint,
158
+ clearEndpoint,
159
+ isProcessAlive,
160
+ };