@sanqianx/project-knowledge 4.6.1 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +817 -780
  4. package/README.md +48 -36
  5. package/_modules/knowledge-engine/README.md +88 -0
  6. package/_modules/knowledge-engine/package.json +38 -0
  7. package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
  8. package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
  9. package/_modules/knowledge-engine/src/bin.js +52 -0
  10. package/_modules/knowledge-engine/src/bridge-client.js +24 -0
  11. package/_modules/knowledge-engine/src/coordinator.js +255 -0
  12. package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
  13. package/_modules/knowledge-engine/src/memories.js +85 -0
  14. package/_modules/knowledge-engine/src/migration.js +88 -0
  15. package/_modules/knowledge-engine/src/retrieval.js +116 -0
  16. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  17. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  18. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  22. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  23. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  24. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  26. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  27. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  28. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  30. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  31. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  32. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  33. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  34. package/_modules/knowledge-engine/src/server.js +155 -0
  35. package/_modules/knowledge-engine/src/store.js +239 -0
  36. package/_modules/knowledge-engine/ui/app.css +172 -0
  37. package/_modules/knowledge-engine/ui/app.js +297 -0
  38. package/_modules/knowledge-engine/ui/index.html +95 -0
  39. package/_site/README.md +30 -30
  40. package/_site/_test/ai-profile-resolver-test.js +137 -137
  41. package/_site/_test/automation-queue-test.js +14 -14
  42. package/_site/_test/automation-ui-test.js +40 -40
  43. package/_site/_test/background-task-registry-test.js +43 -43
  44. package/_site/_test/baseline-schema-test.js +91 -91
  45. package/_site/_test/bridge-adapter-test.js +1 -1
  46. package/_site/_test/bridge-consumer-service-test.js +1 -1
  47. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  48. package/_site/_test/claude-executable-discovery-test.js +62 -62
  49. package/_site/_test/claude-workbench-test.js +170 -170
  50. package/_site/_test/client-capture-restart-e2e-test.js +4 -4
  51. package/_site/_test/codex-conversation-projection-test.js +2 -1
  52. package/_site/_test/commit-boundary-freeze-test.js +1 -1
  53. package/_site/_test/commit-conversation-binding-test.js +95 -95
  54. package/_site/_test/commit-evidence-test.js +110 -110
  55. package/_site/_test/conversation-api-test.js +109 -109
  56. package/_site/_test/conversation-store-test.js +136 -136
  57. package/_site/_test/cross-repo-isolation-e2e-test.js +2 -2
  58. package/_site/_test/data-dir-migration-test.js +57 -57
  59. package/_site/_test/desktop-browser-compat-test.js +28 -28
  60. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  61. package/_site/_test/explicit-commit-processor-test.js +37 -37
  62. package/_site/_test/fixtures/make-git-repos.js +12 -1
  63. package/_site/_test/folder-picker-output-test.js +19 -19
  64. package/_site/_test/full-integration-e2e-test.js +165 -165
  65. package/_site/_test/git-validation-test.js +2 -2
  66. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  67. package/_site/_test/hook-status-repair-api-test.js +152 -152
  68. package/_site/_test/hook-trigger-test.js +85 -85
  69. package/_site/_test/import-preflight-api-test.js +234 -233
  70. package/_site/_test/index-writer-concurrency-test.js +135 -135
  71. package/_site/_test/integration-adapters-test.js +171 -171
  72. package/_site/_test/integration-capture-setup-test.js +1 -1
  73. package/_site/_test/integration-surface-coverage-test.js +164 -164
  74. package/_site/_test/knowledge-language-control-test.js +170 -170
  75. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  76. package/_site/_test/knowledge-query-test.js +54 -54
  77. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  78. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  79. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  80. package/_site/_test/legacy-forward-compat-test.js +257 -257
  81. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -363
  82. package/_site/_test/logging-api-test.js +89 -89
  83. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  84. package/_site/_test/logging-ui-test.js +106 -104
  85. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  86. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  87. package/_site/_test/mcp-server-test.js +149 -149
  88. package/_site/_test/module-artifact-integrity-test.js +27 -0
  89. package/_site/_test/module-boundary-test.js +30 -0
  90. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  91. package/_site/_test/module-model-configuration-test.js +43 -0
  92. package/_site/_test/module-process-lifecycle-test.js +24 -0
  93. package/_site/_test/module-stream-proxy-test.js +34 -0
  94. package/_site/_test/non-release-ci-test.js +34 -34
  95. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  96. package/_site/_test/p0-data-migration-characterization-test.js +37 -37
  97. package/_site/_test/p0-e2e-gate-test.js +347 -347
  98. package/_site/_test/packaged-ui-smoke-test.js +19 -10
  99. package/_site/_test/path-consistency-test.js +151 -151
  100. package/_site/_test/pending-sweep-test.js +9 -9
  101. package/_site/_test/post-commit-automation-test.js +87 -87
  102. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  103. package/_site/_test/product-import-ui-test.js +92 -0
  104. package/_site/_test/project-delete-recovery-test.js +64 -64
  105. package/_site/_test/project-goal-editor-test.js +144 -144
  106. package/_site/_test/project-layout-v2-migration-test.js +127 -127
  107. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  108. package/_site/_test/prompt-settings-test.js +115 -115
  109. package/_site/_test/protected-architecture-gate-test.js +122 -122
  110. package/_site/_test/refactor-characterization-test.js +36 -36
  111. package/_site/_test/release-version-sync-test.js +1 -1
  112. package/_site/_test/requirement-recorder-test.js +173 -173
  113. package/_site/_test/run-all-tests.js +159 -156
  114. package/_site/_test/server-runtime-migration-safety-test.js +27 -27
  115. package/_site/_test/shared-contracts-test.js +58 -58
  116. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  117. package/_site/_test/storage-foundation-test.js +78 -78
  118. package/_site/_test/structured-logger-test.js +101 -101
  119. package/_site/_test/tracking-start-test.js +108 -108
  120. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -56
  121. package/_site/_test/workbench-permission-test.js +117 -117
  122. package/_site/_test/workspace-ui-contract-test.js +28 -43
  123. package/_site/lib/ai-profile-resolver.js +78 -78
  124. package/_site/lib/ai-workspace.js +101 -101
  125. package/_site/lib/automation-config.js +140 -140
  126. package/_site/lib/bridge-adapter.js +5 -1
  127. package/_site/lib/bridge-consumer-service.js +402 -402
  128. package/_site/lib/claude-cli-runner.js +1510 -1510
  129. package/_site/lib/commit-conversation-binder.js +234 -234
  130. package/_site/lib/commit-processing-ledger.js +27 -27
  131. package/_site/lib/commit-prompt.js +202 -202
  132. package/_site/lib/commit-reconciler.js +406 -406
  133. package/_site/lib/contracts.js +284 -279
  134. package/_site/lib/conversation-query-service.js +144 -144
  135. package/_site/lib/conversation-store.js +385 -385
  136. package/_site/lib/data-dir.js +74 -74
  137. package/_site/lib/data-state-classifier.js +40 -40
  138. package/_site/lib/engine-cutover.js +97 -0
  139. package/_site/lib/evidence-bundle.js +228 -228
  140. package/_site/lib/folder-picker-output.js +21 -21
  141. package/_site/lib/git-runner.js +62 -62
  142. package/_site/lib/github-team-store.js +1172 -1172
  143. package/_site/lib/hook-manager.js +203 -202
  144. package/_site/lib/index-service.js +173 -173
  145. package/_site/lib/integration-installer.js +907 -907
  146. package/_site/lib/kb-framework.js +176 -176
  147. package/_site/lib/kb-validator.js +124 -124
  148. package/_site/lib/knowledge-promotion.js +435 -435
  149. package/_site/lib/knowledge-retrieval-service.js +401 -401
  150. package/_site/lib/knowledge-tool-runtime.js +359 -359
  151. package/_site/lib/legacy-data-manifest.js +26 -26
  152. package/_site/lib/llm-client.js +161 -161
  153. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  154. package/_site/lib/migration-service.js +442 -442
  155. package/_site/lib/module-bridge.js +198 -33
  156. package/_site/lib/post-commit-automation.js +87 -87
  157. package/_site/lib/project-lifecycle-service.js +519 -497
  158. package/_site/lib/project-store.js +268 -262
  159. package/_site/lib/requirement-recorder.js +278 -278
  160. package/_site/lib/runtime-endpoint.js +155 -155
  161. package/_site/lib/scanner.js +298 -298
  162. package/_site/lib/server-app.js +1590 -1520
  163. package/_site/lib/settings-store.js +133 -113
  164. package/_site/lib/storage-layout.js +162 -162
  165. package/_site/lib/structured-logger.js +574 -574
  166. package/_site/scripts/folder-picker.ps1 +156 -156
  167. package/_site/scripts/hook-trigger.js +157 -156
  168. package/_site/scripts/install-module-candidates.js +69 -0
  169. package/_site/scripts/pack-module-candidates.js +72 -0
  170. package/_site/scripts/sync-release-version.js +2 -2
  171. package/_site/scripts/vendor-modules.js +47 -0
  172. package/_site/scripts/verify-module-runtime.js +45 -0
  173. package/_site/scripts/verify-product-runtime.js +34 -0
  174. package/bin/project-knowledge-mcp.js +194 -194
  175. package/docs/README.zh-CN.md +34 -25
  176. package/docs/project-registry-schema.md +22 -22
  177. package/docs/testing-strategy.md +33 -33
  178. package/module-runtime-manifest.json +220 -0
  179. package/package.json +13 -10
  180. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  181. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  182. package/plugins/project-knowledge/.mcp.json +1 -1
  183. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  184. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  185. package/templates/project-readme.md +34 -34
  186. package/ui/favicon.svg +38 -38
  187. package/ui/index.html +51 -149
  188. package/ui/product.css +9 -0
  189. package/ui/product.js +386 -0
  190. package/vendor-manifest.json +46 -0
  191. package/_site/_test/import-ui-flow-test.js +0 -171
  192. package/_site/_test/project-control-panel-task14-test.js +0 -63
  193. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  194. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  195. package/_site/_test/ui-smoke-test.js +0 -73
  196. package/ui/app.css +0 -58
  197. package/ui/app.js +0 -607
  198. package/ui/i18n.js +0 -146
@@ -1,279 +1,284 @@
1
- const crypto = require('crypto');
2
-
3
- const SCHEMAS = Object.freeze({
4
- settings: 'settings/v2',
5
- projectRegistry: 'project-registry/v2',
6
- projectConfig: 'project-config/v2',
7
- projectState: 'project-state/v2',
8
- requirement: 'requirement/v1',
9
- aiCodingEvent: 'ai-coding-event/v1',
10
- gitCommitBoundary: 'git-commit-boundary/v1',
11
- commitConversationSnapshot: 'commit-conversation-snapshot/v1',
12
- commitClaim: 'commit-claim/v1',
13
- promotionJournal: 'promotion-journal/v1',
14
- migrationJournal: 'migration-journal/v1',
15
- log: 'log/v2',
16
- hookEvent: 'hook-event/v2',
17
- });
18
-
19
- const SCHEMA_VERSIONS = Object.freeze({
20
- settings: 2,
21
- projectRegistry: 2,
22
- projectConfig: 2,
23
- projectState: 2,
24
- hookManaged: 2,
25
- layoutMigration: 'layout-v2',
26
- });
27
-
28
- const TRIGGERS = Object.freeze(['git-hook']);
29
- const TRIGGER_SET = new Set(TRIGGERS);
30
- const LOG_LEVELS = Object.freeze(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
31
- const LOG_LEVEL_SET = new Set(LOG_LEVELS);
32
- const ANALYSIS_PHASES = Object.freeze([
33
- 'idle',
34
- 'scanning',
35
- 'claim.created',
36
- 'requirement.bound',
37
- 'evidence.prepared',
38
- 'ai.running',
39
- 'output.validated',
40
- 'promotion.prepared',
41
- 'markdown.promoted',
42
- 'state.advanced',
43
- 'index.queued',
44
- 'index.applied',
45
- 'history-diverged',
46
- 'failed',
47
- ]);
48
-
49
- const ERROR_CODES = Object.freeze([
50
- 'INVALID_ARGUMENT',
51
- 'INVALID_TRIGGER',
52
- 'SCHEMA_UNSUPPORTED',
53
- 'DATA_CORRUPT',
54
- 'IMMUTABLE_FIELD',
55
- 'PROJECT_BUSY',
56
- 'PROJECT_NOT_FOUND',
57
- 'PROJECT_AMBIGUOUS',
58
- 'HOOK_CONFLICT',
59
- 'HOOK_INVALID',
60
- 'HISTORY_DIVERGED',
61
- 'MIGRATION_SOURCE_CHANGED',
62
- 'MIGRATION_TARGET_CONFLICT',
63
- 'MIGRATION_FAILED',
64
- 'PATH_OUTSIDE_ROOT',
65
- 'AUTH_REQUIRED',
66
- 'ORIGIN_FORBIDDEN',
67
- 'LOGGER_UNAVAILABLE',
68
- 'LOG_CURSOR_EXPIRED',
69
- 'EVIDENCE_INTEGRITY_FAILED',
70
- 'AI_PROFILE_REQUIRED',
71
- ]);
72
-
73
- const IMMUTABLE_PROJECT_FIELDS = Object.freeze([
74
- 'schema',
75
- 'schemaVersion',
76
- 'projectId',
77
- 'storageName',
78
- 'createdAt',
79
- 'knowledgePath',
80
- ]);
81
- const MUTABLE_PROJECT_FIELDS = Object.freeze([
82
- 'displayName',
83
- 'enabled',
84
- 'aiProfileId',
85
- 'knowledgeLanguage',
86
- 'relatedProjectIds',
87
- ]);
88
-
89
- const REDACTED_VALUE = '[REDACTED]';
90
- const REDACTION_KEY_PATTERN = /(?:api[-_]?key|auth(?:orization|token)?|access[-_]?token|refresh[-_]?token|bearer|password|passwd|secret|client[-_]?secret|private[-_]?key|cookie|set-cookie)/i;
91
- const FIELD_LIMITS = Object.freeze({
92
- message: 4096,
93
- stack: 16384,
94
- path: 4096,
95
- contextString: 8192,
96
- requirement: 131072,
97
- });
98
-
99
- class DomainError extends Error {
100
- constructor(code, message, options = {}) {
101
- super(String(message || code || 'Domain error'), options.cause ? { cause: options.cause } : undefined);
102
- this.name = 'DomainError';
103
- this.code = ERROR_CODES.includes(code) ? code : 'INVALID_ARGUMENT';
104
- this.status = Number.isInteger(options.status) ? options.status : 400;
105
- this.retryable = options.retryable === true;
106
- this.operationId = options.operationId || '';
107
- this.details = sanitizePublicDetails(options.details);
108
- }
109
- }
110
-
111
- function createId(prefix) {
112
- const base = typeof crypto.randomUUID === 'function'
113
- ? crypto.randomUUID().replace(/-/g, '')
114
- : crypto.randomBytes(16).toString('hex');
115
- return `${prefix}-${base}`;
116
- }
117
-
118
- function assertSchema(actual, expected, category = 'data') {
119
- if (actual !== expected) {
120
- throw new DomainError('SCHEMA_UNSUPPORTED', `Unsupported ${category} schema.`, {
121
- status: 409,
122
- details: { category, expected, actual: String(actual || '') },
123
- });
124
- }
125
- return true;
126
- }
127
-
128
- function validateTrigger(trigger) {
129
- if (!TRIGGER_SET.has(trigger)) {
130
- throw new DomainError('INVALID_TRIGGER', 'Trigger must be git-hook.', {
131
- details: { trigger: String(trigger || '') },
132
- });
133
- }
134
- return trigger;
135
- }
136
-
137
- function validateLogLevel(level) {
138
- if (!LOG_LEVEL_SET.has(level)) {
139
- throw new DomainError('INVALID_ARGUMENT', 'Invalid log level.', {
140
- details: { level: String(level || '') },
141
- });
142
- }
143
- return level;
144
- }
145
-
146
- function validateProjectId(projectId) {
147
- const value = String(projectId || '');
148
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$/.test(value)) {
149
- throw new DomainError('INVALID_ARGUMENT', 'Invalid projectId.');
150
- }
151
- return value;
152
- }
153
-
154
- function validateStateTransition(from, to) {
155
- if (!ANALYSIS_PHASES.includes(from) || !ANALYSIS_PHASES.includes(to)) {
156
- throw new DomainError('INVALID_ARGUMENT', 'Unknown analysis phase.', { details: { from, to } });
157
- }
158
- if (from === to) return true;
159
- const allowed = {
160
- idle: ['scanning', 'index.queued', 'failed'],
161
- scanning: ['claim.created', 'idle', 'history-diverged', 'failed'],
162
- 'claim.created': ['requirement.bound', 'failed'],
163
- 'requirement.bound': ['evidence.prepared', 'failed'],
164
- 'evidence.prepared': ['ai.running', 'failed'],
165
- 'ai.running': ['output.validated', 'failed'],
166
- 'output.validated': ['promotion.prepared', 'failed'],
167
- 'promotion.prepared': ['markdown.promoted', 'failed'],
168
- 'markdown.promoted': ['state.advanced', 'failed'],
169
- 'state.advanced': ['index.queued', 'scanning', 'idle', 'failed'],
170
- 'index.queued': ['index.applied', 'failed'],
171
- 'index.applied': ['idle', 'scanning'],
172
- 'history-diverged': ['scanning', 'idle'],
173
- failed: ['scanning', 'ai.running', 'promotion.prepared', 'index.queued', 'idle'],
174
- };
175
- if (!(allowed[from] || []).includes(to)) {
176
- throw new DomainError('INVALID_ARGUMENT', `Invalid analysis transition: ${from} -> ${to}.`, {
177
- details: { from, to },
178
- });
179
- }
180
- return true;
181
- }
182
-
183
- function sanitizePublicDetails(value, seen = new WeakSet()) {
184
- if (value == null || typeof value === 'boolean' || typeof value === 'number') return value;
185
- if (typeof value === 'string') return value.slice(0, FIELD_LIMITS.contextString);
186
- if (value instanceof Error) return { name: value.name, code: value.code || '', message: String(value.message || '').slice(0, FIELD_LIMITS.message) };
187
- if (typeof value !== 'object') return String(value).slice(0, FIELD_LIMITS.contextString);
188
- if (seen.has(value)) return '[Circular]';
189
- seen.add(value);
190
- if (Array.isArray(value)) return value.slice(0, 100).map(item => sanitizePublicDetails(item, seen));
191
- const out = {};
192
- for (const [key, child] of Object.entries(value)) {
193
- if (REDACTION_KEY_PATTERN.test(key) || /stack/i.test(key) || /prompt|diff|header/i.test(key)) {
194
- continue;
195
- } else {
196
- out[key] = sanitizePublicDetails(child, seen);
197
- }
198
- }
199
- return out;
200
- }
201
-
202
- function serializeErrorEnvelope(error, operationId = '') {
203
- const source = error instanceof DomainError
204
- ? error
205
- : new DomainError('INVALID_ARGUMENT', 'The operation failed.', { status: 500, operationId });
206
- return {
207
- ok: false,
208
- error: {
209
- code: source.code,
210
- message: source.message,
211
- operationId: source.operationId || operationId || '',
212
- retryable: source.retryable === true,
213
- details: sanitizePublicDetails(source.details || {}),
214
- },
215
- };
216
- }
217
-
218
- function publicAiProfileView(profile) {
219
- const source = profile && typeof profile === 'object' ? profile : {};
220
- const secret = source.apiKey || source.authToken || source.anthropicAuthToken || '';
221
- const publicView = {};
222
- for (const [key, value] of Object.entries(source)) {
223
- if (REDACTION_KEY_PATTERN.test(key)) continue;
224
- publicView[key] = value;
225
- }
226
- publicView.hasApiKey = Boolean(secret);
227
- publicView.apiKeyMasked = secret ? `****${String(secret).slice(-4)}` : '';
228
- return publicView;
229
- }
230
-
231
- function publicAiProfilesConfig(config) {
232
- const source = config && typeof config === 'object' ? config : {};
233
- return {
234
- ...source,
235
- profiles: Array.isArray(source.profiles) ? source.profiles.map(publicAiProfileView) : [],
236
- };
237
- }
238
-
239
- function assertMutableProjectPatch(patch, options = {}) {
240
- const allowKnowledgePath = options.allowKnowledgePath === true;
241
- const allowRepoPath = options.allowRepoPath === true;
242
- for (const key of Object.keys(patch && typeof patch === 'object' ? patch : {})) {
243
- if (IMMUTABLE_PROJECT_FIELDS.includes(key) && !(allowKnowledgePath && key === 'knowledgePath')) {
244
- throw new DomainError('IMMUTABLE_FIELD', `Project field is immutable: ${key}.`, { status: 409, details: { field: key } });
245
- }
246
- if (!MUTABLE_PROJECT_FIELDS.includes(key)
247
- && !(allowKnowledgePath && key === 'knowledgePath')
248
- && !(allowRepoPath && key === 'repoPath')) {
249
- throw new DomainError('INVALID_ARGUMENT', `Unknown project field: ${key}.`, { details: { field: key } });
250
- }
251
- }
252
- return true;
253
- }
254
-
255
- module.exports = {
256
- SCHEMAS,
257
- SCHEMA_VERSIONS,
258
- TRIGGERS,
259
- LOG_LEVELS,
260
- ANALYSIS_PHASES,
261
- ERROR_CODES,
262
- IMMUTABLE_PROJECT_FIELDS,
263
- MUTABLE_PROJECT_FIELDS,
264
- REDACTED_VALUE,
265
- REDACTION_KEY_PATTERN,
266
- FIELD_LIMITS,
267
- DomainError,
268
- createId,
269
- assertSchema,
270
- validateTrigger,
271
- validateLogLevel,
272
- validateProjectId,
273
- validateStateTransition,
274
- sanitizePublicDetails,
275
- serializeErrorEnvelope,
276
- publicAiProfileView,
277
- publicAiProfilesConfig,
278
- assertMutableProjectPatch,
279
- };
1
+ const crypto = require('crypto');
2
+
3
+ const SCHEMAS = Object.freeze({
4
+ settings: 'settings/v2',
5
+ projectRegistry: 'project-registry/v2',
6
+ projectConfig: 'project-config/v2',
7
+ projectState: 'project-state/v2',
8
+ requirement: 'requirement/v1',
9
+ aiCodingEvent: 'ai-coding-event/v1',
10
+ gitCommitBoundary: 'git-commit-boundary/v1',
11
+ commitConversationSnapshot: 'commit-conversation-snapshot/v1',
12
+ commitClaim: 'commit-claim/v1',
13
+ promotionJournal: 'promotion-journal/v1',
14
+ migrationJournal: 'migration-journal/v1',
15
+ log: 'log/v2',
16
+ hookEvent: 'hook-event/v2',
17
+ });
18
+
19
+ const SCHEMA_VERSIONS = Object.freeze({
20
+ settings: 2,
21
+ projectRegistry: 2,
22
+ projectConfig: 2,
23
+ projectState: 2,
24
+ hookManaged: 2,
25
+ layoutMigration: 'layout-v2',
26
+ });
27
+
28
+ const TRIGGERS = Object.freeze(['git-hook']);
29
+ const TRIGGER_SET = new Set(TRIGGERS);
30
+ const LOG_LEVELS = Object.freeze(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
31
+ const LOG_LEVEL_SET = new Set(LOG_LEVELS);
32
+ const ANALYSIS_PHASES = Object.freeze([
33
+ 'idle',
34
+ 'scanning',
35
+ 'claim.created',
36
+ 'requirement.bound',
37
+ 'evidence.prepared',
38
+ 'ai.running',
39
+ 'output.validated',
40
+ 'promotion.prepared',
41
+ 'markdown.promoted',
42
+ 'state.advanced',
43
+ 'index.queued',
44
+ 'index.applied',
45
+ 'history-diverged',
46
+ 'failed',
47
+ ]);
48
+
49
+ const ERROR_CODES = Object.freeze([
50
+ 'INVALID_ARGUMENT',
51
+ 'INVALID_TRIGGER',
52
+ 'SCHEMA_UNSUPPORTED',
53
+ 'DATA_CORRUPT',
54
+ 'IMMUTABLE_FIELD',
55
+ 'PROJECT_BUSY',
56
+ 'PROJECT_NOT_FOUND',
57
+ 'PROJECT_AMBIGUOUS',
58
+ 'HOOK_CONFLICT',
59
+ 'HOOK_INVALID',
60
+ 'HISTORY_DIVERGED',
61
+ 'MIGRATION_SOURCE_CHANGED',
62
+ 'MIGRATION_TARGET_CONFLICT',
63
+ 'MIGRATION_FAILED',
64
+ 'PATH_OUTSIDE_ROOT',
65
+ 'AUTH_REQUIRED',
66
+ 'ORIGIN_FORBIDDEN',
67
+ 'LOGGER_UNAVAILABLE',
68
+ 'LOG_CURSOR_EXPIRED',
69
+ 'EVIDENCE_INTEGRITY_FAILED',
70
+ 'AI_PROFILE_REQUIRED',
71
+ 'KNOWLEDGE_WRITE_MOVED',
72
+ 'MODEL_CONFIG_MOVED',
73
+ 'MODULE_UNREACHABLE',
74
+ ]);
75
+
76
+ const IMMUTABLE_PROJECT_FIELDS = Object.freeze([
77
+ 'schema',
78
+ 'schemaVersion',
79
+ 'projectId',
80
+ 'storageName',
81
+ 'createdAt',
82
+ 'knowledgePath',
83
+ ]);
84
+ const MUTABLE_PROJECT_FIELDS = Object.freeze([
85
+ 'displayName',
86
+ 'enabled',
87
+ 'aiProfileId',
88
+ 'knowledgeLanguage',
89
+ 'relatedProjectIds',
90
+ 'brainId',
91
+ 'domainId',
92
+ ]);
93
+
94
+ const REDACTED_VALUE = '[REDACTED]';
95
+ const REDACTION_KEY_PATTERN = /(?:api[-_]?key|auth(?:orization|token)?|access[-_]?token|refresh[-_]?token|bearer|password|passwd|secret|client[-_]?secret|private[-_]?key|cookie|set-cookie)/i;
96
+ const FIELD_LIMITS = Object.freeze({
97
+ message: 4096,
98
+ stack: 16384,
99
+ path: 4096,
100
+ contextString: 8192,
101
+ requirement: 131072,
102
+ });
103
+
104
+ class DomainError extends Error {
105
+ constructor(code, message, options = {}) {
106
+ super(String(message || code || 'Domain error'), options.cause ? { cause: options.cause } : undefined);
107
+ this.name = 'DomainError';
108
+ this.code = ERROR_CODES.includes(code) ? code : 'INVALID_ARGUMENT';
109
+ this.status = Number.isInteger(options.status) ? options.status : 400;
110
+ this.retryable = options.retryable === true;
111
+ this.operationId = options.operationId || '';
112
+ this.details = sanitizePublicDetails(options.details);
113
+ }
114
+ }
115
+
116
+ function createId(prefix) {
117
+ const base = typeof crypto.randomUUID === 'function'
118
+ ? crypto.randomUUID().replace(/-/g, '')
119
+ : crypto.randomBytes(16).toString('hex');
120
+ return `${prefix}-${base}`;
121
+ }
122
+
123
+ function assertSchema(actual, expected, category = 'data') {
124
+ if (actual !== expected) {
125
+ throw new DomainError('SCHEMA_UNSUPPORTED', `Unsupported ${category} schema.`, {
126
+ status: 409,
127
+ details: { category, expected, actual: String(actual || '') },
128
+ });
129
+ }
130
+ return true;
131
+ }
132
+
133
+ function validateTrigger(trigger) {
134
+ if (!TRIGGER_SET.has(trigger)) {
135
+ throw new DomainError('INVALID_TRIGGER', 'Trigger must be git-hook.', {
136
+ details: { trigger: String(trigger || '') },
137
+ });
138
+ }
139
+ return trigger;
140
+ }
141
+
142
+ function validateLogLevel(level) {
143
+ if (!LOG_LEVEL_SET.has(level)) {
144
+ throw new DomainError('INVALID_ARGUMENT', 'Invalid log level.', {
145
+ details: { level: String(level || '') },
146
+ });
147
+ }
148
+ return level;
149
+ }
150
+
151
+ function validateProjectId(projectId) {
152
+ const value = String(projectId || '');
153
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$/.test(value)) {
154
+ throw new DomainError('INVALID_ARGUMENT', 'Invalid projectId.');
155
+ }
156
+ return value;
157
+ }
158
+
159
+ function validateStateTransition(from, to) {
160
+ if (!ANALYSIS_PHASES.includes(from) || !ANALYSIS_PHASES.includes(to)) {
161
+ throw new DomainError('INVALID_ARGUMENT', 'Unknown analysis phase.', { details: { from, to } });
162
+ }
163
+ if (from === to) return true;
164
+ const allowed = {
165
+ idle: ['scanning', 'index.queued', 'failed'],
166
+ scanning: ['claim.created', 'idle', 'history-diverged', 'failed'],
167
+ 'claim.created': ['requirement.bound', 'failed'],
168
+ 'requirement.bound': ['evidence.prepared', 'failed'],
169
+ 'evidence.prepared': ['ai.running', 'failed'],
170
+ 'ai.running': ['output.validated', 'failed'],
171
+ 'output.validated': ['promotion.prepared', 'failed'],
172
+ 'promotion.prepared': ['markdown.promoted', 'failed'],
173
+ 'markdown.promoted': ['state.advanced', 'failed'],
174
+ 'state.advanced': ['index.queued', 'scanning', 'idle', 'failed'],
175
+ 'index.queued': ['index.applied', 'failed'],
176
+ 'index.applied': ['idle', 'scanning'],
177
+ 'history-diverged': ['scanning', 'idle'],
178
+ failed: ['scanning', 'ai.running', 'promotion.prepared', 'index.queued', 'idle'],
179
+ };
180
+ if (!(allowed[from] || []).includes(to)) {
181
+ throw new DomainError('INVALID_ARGUMENT', `Invalid analysis transition: ${from} -> ${to}.`, {
182
+ details: { from, to },
183
+ });
184
+ }
185
+ return true;
186
+ }
187
+
188
+ function sanitizePublicDetails(value, seen = new WeakSet()) {
189
+ if (value == null || typeof value === 'boolean' || typeof value === 'number') return value;
190
+ if (typeof value === 'string') return value.slice(0, FIELD_LIMITS.contextString);
191
+ if (value instanceof Error) return { name: value.name, code: value.code || '', message: String(value.message || '').slice(0, FIELD_LIMITS.message) };
192
+ if (typeof value !== 'object') return String(value).slice(0, FIELD_LIMITS.contextString);
193
+ if (seen.has(value)) return '[Circular]';
194
+ seen.add(value);
195
+ if (Array.isArray(value)) return value.slice(0, 100).map(item => sanitizePublicDetails(item, seen));
196
+ const out = {};
197
+ for (const [key, child] of Object.entries(value)) {
198
+ if (REDACTION_KEY_PATTERN.test(key) || /stack/i.test(key) || /prompt|diff|header/i.test(key)) {
199
+ continue;
200
+ } else {
201
+ out[key] = sanitizePublicDetails(child, seen);
202
+ }
203
+ }
204
+ return out;
205
+ }
206
+
207
+ function serializeErrorEnvelope(error, operationId = '') {
208
+ const source = error instanceof DomainError
209
+ ? error
210
+ : new DomainError('INVALID_ARGUMENT', 'The operation failed.', { status: 500, operationId });
211
+ return {
212
+ ok: false,
213
+ error: {
214
+ code: source.code,
215
+ message: source.message,
216
+ operationId: source.operationId || operationId || '',
217
+ retryable: source.retryable === true,
218
+ details: sanitizePublicDetails(source.details || {}),
219
+ },
220
+ };
221
+ }
222
+
223
+ function publicAiProfileView(profile) {
224
+ const source = profile && typeof profile === 'object' ? profile : {};
225
+ const secret = source.apiKey || source.authToken || source.anthropicAuthToken || '';
226
+ const publicView = {};
227
+ for (const [key, value] of Object.entries(source)) {
228
+ if (REDACTION_KEY_PATTERN.test(key)) continue;
229
+ publicView[key] = value;
230
+ }
231
+ publicView.hasApiKey = Boolean(secret);
232
+ publicView.apiKeyMasked = secret ? `****${String(secret).slice(-4)}` : '';
233
+ return publicView;
234
+ }
235
+
236
+ function publicAiProfilesConfig(config) {
237
+ const source = config && typeof config === 'object' ? config : {};
238
+ return {
239
+ ...source,
240
+ profiles: Array.isArray(source.profiles) ? source.profiles.map(publicAiProfileView) : [],
241
+ };
242
+ }
243
+
244
+ function assertMutableProjectPatch(patch, options = {}) {
245
+ const allowKnowledgePath = options.allowKnowledgePath === true;
246
+ const allowRepoPath = options.allowRepoPath === true;
247
+ for (const key of Object.keys(patch && typeof patch === 'object' ? patch : {})) {
248
+ if (IMMUTABLE_PROJECT_FIELDS.includes(key) && !(allowKnowledgePath && key === 'knowledgePath')) {
249
+ throw new DomainError('IMMUTABLE_FIELD', `Project field is immutable: ${key}.`, { status: 409, details: { field: key } });
250
+ }
251
+ if (!MUTABLE_PROJECT_FIELDS.includes(key)
252
+ && !(allowKnowledgePath && key === 'knowledgePath')
253
+ && !(allowRepoPath && key === 'repoPath')) {
254
+ throw new DomainError('INVALID_ARGUMENT', `Unknown project field: ${key}.`, { details: { field: key } });
255
+ }
256
+ }
257
+ return true;
258
+ }
259
+
260
+ module.exports = {
261
+ SCHEMAS,
262
+ SCHEMA_VERSIONS,
263
+ TRIGGERS,
264
+ LOG_LEVELS,
265
+ ANALYSIS_PHASES,
266
+ ERROR_CODES,
267
+ IMMUTABLE_PROJECT_FIELDS,
268
+ MUTABLE_PROJECT_FIELDS,
269
+ REDACTED_VALUE,
270
+ REDACTION_KEY_PATTERN,
271
+ FIELD_LIMITS,
272
+ DomainError,
273
+ createId,
274
+ assertSchema,
275
+ validateTrigger,
276
+ validateLogLevel,
277
+ validateProjectId,
278
+ validateStateTransition,
279
+ sanitizePublicDetails,
280
+ serializeErrorEnvelope,
281
+ publicAiProfileView,
282
+ publicAiProfilesConfig,
283
+ assertMutableProjectPatch,
284
+ };