@sanqianx/project-knowledge 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +817 -799
  4. package/README.md +48 -36
  5. package/_modules/knowledge-engine/README.md +88 -0
  6. package/_modules/knowledge-engine/package.json +38 -0
  7. package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
  8. package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
  9. package/_modules/knowledge-engine/src/bin.js +52 -0
  10. package/_modules/knowledge-engine/src/bridge-client.js +24 -0
  11. package/_modules/knowledge-engine/src/coordinator.js +255 -0
  12. package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
  13. package/_modules/knowledge-engine/src/memories.js +85 -0
  14. package/_modules/knowledge-engine/src/migration.js +88 -0
  15. package/_modules/knowledge-engine/src/retrieval.js +116 -0
  16. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  17. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  18. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  22. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  23. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  24. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  26. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  27. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  28. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  30. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  31. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  32. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  33. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  34. package/_modules/knowledge-engine/src/server.js +155 -0
  35. package/_modules/knowledge-engine/src/store.js +239 -0
  36. package/_modules/knowledge-engine/ui/app.css +172 -0
  37. package/_modules/knowledge-engine/ui/app.js +297 -0
  38. package/_modules/knowledge-engine/ui/index.html +95 -0
  39. package/_site/README.md +30 -30
  40. package/_site/_test/ai-profile-resolver-test.js +137 -137
  41. package/_site/_test/automation-queue-test.js +14 -14
  42. package/_site/_test/automation-ui-test.js +40 -40
  43. package/_site/_test/background-task-registry-test.js +43 -43
  44. package/_site/_test/baseline-schema-test.js +91 -91
  45. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  46. package/_site/_test/claude-executable-discovery-test.js +62 -62
  47. package/_site/_test/claude-workbench-test.js +170 -170
  48. package/_site/_test/codex-conversation-projection-test.js +2 -1
  49. package/_site/_test/commit-conversation-binding-test.js +95 -95
  50. package/_site/_test/commit-evidence-test.js +110 -110
  51. package/_site/_test/conversation-api-test.js +109 -109
  52. package/_site/_test/conversation-store-test.js +136 -136
  53. package/_site/_test/data-dir-migration-test.js +57 -57
  54. package/_site/_test/desktop-browser-compat-test.js +28 -28
  55. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  56. package/_site/_test/explicit-commit-processor-test.js +37 -37
  57. package/_site/_test/fixtures/make-git-repos.js +12 -1
  58. package/_site/_test/folder-picker-output-test.js +19 -19
  59. package/_site/_test/full-integration-e2e-test.js +165 -165
  60. package/_site/_test/git-validation-test.js +2 -2
  61. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  62. package/_site/_test/hook-status-repair-api-test.js +152 -152
  63. package/_site/_test/hook-trigger-test.js +85 -85
  64. package/_site/_test/import-preflight-api-test.js +234 -233
  65. package/_site/_test/index-writer-concurrency-test.js +135 -135
  66. package/_site/_test/integration-adapters-test.js +171 -171
  67. package/_site/_test/integration-surface-coverage-test.js +164 -164
  68. package/_site/_test/knowledge-language-control-test.js +170 -170
  69. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  70. package/_site/_test/knowledge-query-test.js +54 -54
  71. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  72. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  73. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  74. package/_site/_test/legacy-forward-compat-test.js +257 -257
  75. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -363
  76. package/_site/_test/logging-api-test.js +89 -89
  77. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  78. package/_site/_test/logging-ui-test.js +106 -104
  79. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  80. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  81. package/_site/_test/mcp-server-test.js +149 -149
  82. package/_site/_test/module-artifact-integrity-test.js +27 -0
  83. package/_site/_test/module-boundary-test.js +30 -0
  84. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  85. package/_site/_test/module-model-configuration-test.js +43 -0
  86. package/_site/_test/module-process-lifecycle-test.js +24 -0
  87. package/_site/_test/module-stream-proxy-test.js +34 -0
  88. package/_site/_test/non-release-ci-test.js +34 -34
  89. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  90. package/_site/_test/p0-data-migration-characterization-test.js +37 -37
  91. package/_site/_test/p0-e2e-gate-test.js +347 -347
  92. package/_site/_test/packaged-ui-smoke-test.js +11 -9
  93. package/_site/_test/path-consistency-test.js +151 -151
  94. package/_site/_test/pending-sweep-test.js +9 -9
  95. package/_site/_test/post-commit-automation-test.js +87 -87
  96. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  97. package/_site/_test/product-import-ui-test.js +92 -0
  98. package/_site/_test/project-delete-recovery-test.js +64 -64
  99. package/_site/_test/project-goal-editor-test.js +144 -144
  100. package/_site/_test/project-layout-v2-migration-test.js +127 -127
  101. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  102. package/_site/_test/prompt-settings-test.js +115 -115
  103. package/_site/_test/protected-architecture-gate-test.js +122 -122
  104. package/_site/_test/refactor-characterization-test.js +36 -36
  105. package/_site/_test/release-version-sync-test.js +1 -1
  106. package/_site/_test/requirement-recorder-test.js +173 -173
  107. package/_site/_test/run-all-tests.js +159 -156
  108. package/_site/_test/server-runtime-migration-safety-test.js +27 -27
  109. package/_site/_test/shared-contracts-test.js +58 -58
  110. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  111. package/_site/_test/storage-foundation-test.js +78 -78
  112. package/_site/_test/structured-logger-test.js +101 -101
  113. package/_site/_test/tracking-start-test.js +108 -108
  114. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -56
  115. package/_site/_test/workbench-permission-test.js +117 -117
  116. package/_site/_test/workspace-ui-contract-test.js +28 -43
  117. package/_site/lib/ai-profile-resolver.js +78 -78
  118. package/_site/lib/ai-workspace.js +101 -101
  119. package/_site/lib/automation-config.js +140 -140
  120. package/_site/lib/bridge-adapter.js +1 -0
  121. package/_site/lib/bridge-consumer-service.js +402 -402
  122. package/_site/lib/claude-cli-runner.js +1510 -1510
  123. package/_site/lib/commit-conversation-binder.js +234 -234
  124. package/_site/lib/commit-processing-ledger.js +27 -27
  125. package/_site/lib/commit-prompt.js +202 -202
  126. package/_site/lib/commit-reconciler.js +406 -406
  127. package/_site/lib/contracts.js +284 -279
  128. package/_site/lib/conversation-query-service.js +144 -144
  129. package/_site/lib/conversation-store.js +385 -385
  130. package/_site/lib/data-dir.js +74 -74
  131. package/_site/lib/data-state-classifier.js +40 -40
  132. package/_site/lib/engine-cutover.js +97 -0
  133. package/_site/lib/evidence-bundle.js +228 -228
  134. package/_site/lib/folder-picker-output.js +21 -21
  135. package/_site/lib/git-runner.js +62 -62
  136. package/_site/lib/github-team-store.js +1172 -1172
  137. package/_site/lib/hook-manager.js +203 -202
  138. package/_site/lib/index-service.js +173 -173
  139. package/_site/lib/integration-installer.js +907 -907
  140. package/_site/lib/kb-framework.js +176 -176
  141. package/_site/lib/kb-validator.js +124 -124
  142. package/_site/lib/knowledge-promotion.js +435 -435
  143. package/_site/lib/knowledge-retrieval-service.js +401 -401
  144. package/_site/lib/knowledge-tool-runtime.js +359 -359
  145. package/_site/lib/legacy-data-manifest.js +26 -26
  146. package/_site/lib/llm-client.js +161 -161
  147. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  148. package/_site/lib/migration-service.js +442 -442
  149. package/_site/lib/module-bridge.js +198 -33
  150. package/_site/lib/post-commit-automation.js +87 -87
  151. package/_site/lib/project-lifecycle-service.js +519 -497
  152. package/_site/lib/project-store.js +268 -262
  153. package/_site/lib/requirement-recorder.js +278 -278
  154. package/_site/lib/runtime-endpoint.js +155 -155
  155. package/_site/lib/scanner.js +298 -298
  156. package/_site/lib/server-app.js +1590 -1520
  157. package/_site/lib/settings-store.js +133 -113
  158. package/_site/lib/storage-layout.js +162 -162
  159. package/_site/lib/structured-logger.js +574 -574
  160. package/_site/scripts/folder-picker.ps1 +156 -156
  161. package/_site/scripts/hook-trigger.js +157 -156
  162. package/_site/scripts/install-module-candidates.js +69 -0
  163. package/_site/scripts/pack-module-candidates.js +72 -0
  164. package/_site/scripts/sync-release-version.js +2 -2
  165. package/_site/scripts/vendor-modules.js +47 -0
  166. package/_site/scripts/verify-module-runtime.js +45 -0
  167. package/_site/scripts/verify-product-runtime.js +34 -0
  168. package/bin/project-knowledge-mcp.js +194 -194
  169. package/docs/README.zh-CN.md +34 -25
  170. package/docs/project-registry-schema.md +22 -22
  171. package/docs/testing-strategy.md +33 -33
  172. package/module-runtime-manifest.json +220 -0
  173. package/package.json +13 -9
  174. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  175. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  176. package/plugins/project-knowledge/.mcp.json +1 -1
  177. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  178. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  179. package/templates/project-readme.md +34 -34
  180. package/ui/favicon.svg +38 -38
  181. package/ui/index.html +51 -149
  182. package/ui/product.css +9 -0
  183. package/ui/product.js +386 -0
  184. package/vendor-manifest.json +46 -0
  185. package/_site/_test/import-ui-flow-test.js +0 -171
  186. package/_site/_test/project-control-panel-task14-test.js +0 -63
  187. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  188. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  189. package/_site/_test/ui-smoke-test.js +0 -73
  190. package/ui/app.css +0 -58
  191. package/ui/app.js +0 -607
  192. package/ui/i18n.js +0 -146
@@ -1,77 +1,77 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const { spawnSync } = require('child_process');
5
- const { DomainError, createId } = require('./contracts');
6
- const AtomicFile = require('./atomic-file');
7
- const hookManagerDefault = require('./hook-manager');
8
- const { resolveEffectiveAiProfile } = require('./ai-profile-resolver');
9
-
10
- function slugify(value) {
11
- const slug = String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
12
- return slug || 'project';
13
- }
14
-
15
- function runGit(repoPath, args, options = {}) {
16
- const result = spawnSync('git', ['-C', repoPath, ...args], {
17
- encoding: 'utf8', windowsHide: true,
18
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
19
- });
20
- if (result.status !== 0 && !options.allowFailure) {
21
- throw new DomainError('INVALID_ARGUMENT', 'Git operation failed.', { status: 400, details: { args: args.join(' '), exitCode: result.status, gitError: String(result.stderr || '').trim().slice(0, 1000) } });
22
- }
23
- return { ok: result.status === 0, stdout: String(result.stdout || '').trim(), stderr: String(result.stderr || '').trim(), status: result.status };
24
- }
25
-
26
- class ProjectLifecycleService {
27
- constructor(options = {}) {
28
- this.layout = options.layout;
29
- this.settingsStore = options.settingsStore;
30
- this.registryStore = options.registryStore;
31
- this.projectStore = options.projectStore;
32
- this.hookManager = options.hookManager || hookManagerDefault;
33
- this.triggerScriptPath = options.triggerScriptPath;
34
- this.logger = options.logger || { child() { return this; }, info() {}, warn() {}, error() {} };
35
- this.isProjectBusy = options.isProjectBusy || (() => false);
36
- this.bridgeAdapter = options.bridgeAdapter || null;
37
- this.fault = options.fault || (() => {});
38
- }
39
-
40
- // T06: pure preflight — does NOT mutate any state. Reports every
41
- // prerequisite the UI must show before the user clicks Import. Any
42
- // missing prerequisite is surfaced as a `problems[]` entry with an
43
- // actionable message and an `action` the UI can offer (e.g. a
44
- // "Configure knowledge root" link). The shape is intentionally flat so
45
- // the UI can render it directly without per-field branching.
46
- async preflightImport(input = {}) {
47
- const localPath = String(input.localPath || '').trim();
48
- const settings = this.settingsStore.read();
49
- const problems = [];
50
- const checks = {};
51
- let knowledgeRoot = '';
52
- try {
53
- knowledgeRoot = this.layout.getKnowledgeRootPath(settings);
54
- } catch (error) {
55
- if (error && error.code === 'INVALID_ARGUMENT') {
56
- problems.push({ code: 'KNOWLEDGE_ROOT_MISSING', message: 'Knowledge root is not configured.', action: 'CONFIGURE_KNOWLEDGE_ROOT' });
57
- checks.knowledgeRoot = { ok: false, reason: 'unconfigured' };
58
- } else {
59
- throw error;
60
- }
61
- }
62
-
63
- // Check 1: path exists and is a directory.
64
- if (!localPath) {
65
- problems.push({ code: 'PATH_REQUIRED', message: 'A local repository path is required.', action: 'CHOOSE_PATH' });
66
- checks.path = { ok: false, reason: 'missing' };
67
- } else if (!fs.existsSync(localPath) || !fs.statSync(localPath).isDirectory()) {
68
- problems.push({ code: 'PATH_MISSING', message: 'The selected path does not exist or is not a directory.', action: 'CHOOSE_PATH' });
69
- checks.path = { ok: false, reason: 'not-a-directory' };
70
- } else {
71
- checks.path = { ok: true };
72
- }
73
-
74
- // Check 2: git repository or can be initialized.
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { spawnSync } = require('child_process');
5
+ const { DomainError, createId } = require('./contracts');
6
+ const AtomicFile = require('./atomic-file');
7
+ const hookManagerDefault = require('./hook-manager');
8
+ const { resolveEffectiveAiProfile } = require('./ai-profile-resolver');
9
+
10
+ function slugify(value) {
11
+ const slug = String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
12
+ return slug || 'project';
13
+ }
14
+
15
+ function runGit(repoPath, args, options = {}) {
16
+ const result = spawnSync('git', ['-C', repoPath, ...args], {
17
+ encoding: 'utf8', windowsHide: true,
18
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
19
+ });
20
+ if (result.status !== 0 && !options.allowFailure) {
21
+ throw new DomainError('INVALID_ARGUMENT', 'Git operation failed.', { status: 400, details: { args: args.join(' '), exitCode: result.status, gitError: String(result.stderr || '').trim().slice(0, 1000) } });
22
+ }
23
+ return { ok: result.status === 0, stdout: String(result.stdout || '').trim(), stderr: String(result.stderr || '').trim(), status: result.status };
24
+ }
25
+
26
+ class ProjectLifecycleService {
27
+ constructor(options = {}) {
28
+ this.layout = options.layout;
29
+ this.settingsStore = options.settingsStore;
30
+ this.registryStore = options.registryStore;
31
+ this.projectStore = options.projectStore;
32
+ this.hookManager = options.hookManager || hookManagerDefault;
33
+ this.triggerScriptPath = options.triggerScriptPath;
34
+ this.logger = options.logger || { child() { return this; }, info() {}, warn() {}, error() {} };
35
+ this.isProjectBusy = options.isProjectBusy || (() => false);
36
+ this.bridgeAdapter = options.bridgeAdapter || null;
37
+ this.fault = options.fault || (() => {});
38
+ }
39
+
40
+ // T06: pure preflight — does NOT mutate any state. Reports every
41
+ // prerequisite the UI must show before the user clicks Import. Any
42
+ // missing prerequisite is surfaced as a `problems[]` entry with an
43
+ // actionable message and an `action` the UI can offer (e.g. a
44
+ // "Configure knowledge root" link). The shape is intentionally flat so
45
+ // the UI can render it directly without per-field branching.
46
+ async preflightImport(input = {}) {
47
+ const localPath = String(input.localPath || '').trim();
48
+ const settings = this.settingsStore.read();
49
+ const problems = [];
50
+ const checks = {};
51
+ let knowledgeRoot = '';
52
+ try {
53
+ knowledgeRoot = this.layout.getKnowledgeRootPath(settings);
54
+ } catch (error) {
55
+ if (error && error.code === 'INVALID_ARGUMENT') {
56
+ problems.push({ code: 'KNOWLEDGE_ROOT_MISSING', message: 'Knowledge root is not configured.', action: 'CONFIGURE_KNOWLEDGE_ROOT' });
57
+ checks.knowledgeRoot = { ok: false, reason: 'unconfigured' };
58
+ } else {
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ // Check 1: path exists and is a directory.
64
+ if (!localPath) {
65
+ problems.push({ code: 'PATH_REQUIRED', message: 'A local repository path is required.', action: 'CHOOSE_PATH' });
66
+ checks.path = { ok: false, reason: 'missing' };
67
+ } else if (!fs.existsSync(localPath) || !fs.statSync(localPath).isDirectory()) {
68
+ problems.push({ code: 'PATH_MISSING', message: 'The selected path does not exist or is not a directory.', action: 'CHOOSE_PATH' });
69
+ checks.path = { ok: false, reason: 'not-a-directory' };
70
+ } else {
71
+ checks.path = { ok: true };
72
+ }
73
+
74
+ // Check 2: git repository or can be initialized.
75
75
  let repoInspection = null;
76
76
  let plannedGitInit = false;
77
77
  if (checks.path.ok) {
@@ -86,426 +86,448 @@ class ProjectLifecycleService {
86
86
  checks.git = { ok: false, status: 'non-git', plannedInit: true, message: 'Directory is not a Git repository. Import will run `git init` before proceeding.' };
87
87
  } else {
88
88
  const head = runGit(localPath, ['rev-parse', '--verify', 'HEAD'], { allowFailure: true });
89
- const commonDir = runGit(localPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
90
- const branch = runGit(localPath, ['branch', '--show-current'], { allowFailure: true });
91
- repoInspection = {
92
- ok: true,
93
- repoPath: top.ok ? path.resolve(top.stdout) : path.resolve(localPath),
94
- commonDir: commonDir.ok ? path.resolve(commonDir.stdout) : '',
95
- headCommit: head.ok ? head.stdout : null,
96
- branch: branch.ok ? branch.stdout : '',
97
- emptyRepo: !head.ok,
98
- };
99
- checks.git = { ok: true, status: repoInspection.emptyRepo ? 'empty' : 'ok', repoPath: repoInspection.repoPath, commonDir: repoInspection.commonDir, headCommit: repoInspection.headCommit, branch: repoInspection.branch };
100
- }
101
- }
102
-
103
- // Check 3: knowledge root configured + writable.
104
- if (!knowledgeRoot) {
105
- problems.push({ code: 'KNOWLEDGE_ROOT_MISSING', message: 'Knowledge root is not configured.', action: 'CONFIGURE_KNOWLEDGE_ROOT' });
106
- checks.knowledgeRoot = { ok: false, reason: 'unconfigured' };
107
- } else if (!fs.existsSync(knowledgeRoot)) {
108
- try {
109
- fs.mkdirSync(knowledgeRoot, { recursive: true });
110
- } catch (error) {
111
- problems.push({ code: 'KNOWLEDGE_ROOT_NOT_WRITABLE', message: `Knowledge root is not writable: ${error.message}`, action: 'CONFIGURE_KNOWLEDGE_ROOT' });
112
- checks.knowledgeRoot = { ok: false, reason: 'not-writable', path: knowledgeRoot };
113
- }
114
- checks.knowledgeRoot = checks.knowledgeRoot || { ok: true, path: knowledgeRoot, created: true };
115
- } else {
116
- try {
117
- fs.accessSync(knowledgeRoot, fs.constants.W_OK);
118
- checks.knowledgeRoot = { ok: true, path: knowledgeRoot };
119
- } catch (error) {
120
- problems.push({ code: 'KNOWLEDGE_ROOT_NOT_WRITABLE', message: `Knowledge root is not writable: ${error.message}`, action: 'CONFIGURE_KNOWLEDGE_ROOT' });
121
- checks.knowledgeRoot = { ok: false, reason: 'not-writable', path: knowledgeRoot };
122
- }
123
- }
124
-
125
- // Check 4: effective AI profile availability.
126
- let aiProfile = null;
127
- try {
128
- const resolved = resolveEffectiveAiProfile(settings, { aiProfileId: input.aiProfileId || null });
129
- aiProfile = { id: resolved.profileId, source: resolved.source };
130
- checks.aiProfile = { ok: true, ...aiProfile };
131
- } catch (error) {
132
- if (error && error.code === 'AI_PROFILE_REQUIRED') {
133
- problems.push({ code: 'AI_PROFILE_REQUIRED', message: 'No usable AI profile is configured. Configure one before importing.', action: 'CONFIGURE_AI_PROFILE' });
134
- checks.aiProfile = { ok: false };
135
- } else {
136
- throw error;
137
- }
138
- }
139
-
140
- // Check 5: duplicate / already-managed project.
141
- if (repoInspection && repoInspection.ok) {
142
- for (const config of this.listConfigs()) {
143
- if (this.layout.pathsEqual(config.repoPath, repoInspection.repoPath)
144
- || (config.repoIdentity && config.repoIdentity.commonDir && repoInspection.commonDir
145
- && this.layout.pathsEqual(config.repoIdentity.commonDir, repoInspection.commonDir))) {
146
- problems.push({ code: 'DUPLICATE_PROJECT', message: 'This Git repository is already managed by another project.', action: 'OPEN_EXISTING_PROJECT', existingProjectId: config.projectId });
147
- checks.duplicate = { ok: false, existingProjectId: config.projectId };
148
- break;
149
- }
150
- }
151
- if (!checks.duplicate) checks.duplicate = { ok: true };
152
- }
153
-
154
- // Check 6: existing non-managed hook conflict.
155
- if (repoInspection && repoInspection.ok) {
156
- try {
157
- const hookStatus = this.hookManager.readHookStatus({ repoPath: repoInspection.repoPath });
158
- if (!hookStatus.kbManaged && hookStatus.reason && /third-party/i.test(hookStatus.reason)) {
159
- problems.push({ code: 'HOOK_CONFLICT', message: 'A third-party post-commit hook is installed. Project-Knowledge will not overwrite it.', action: 'INSPECT_HOOK' });
160
- checks.hook = { ok: false, reason: 'third-party' };
161
- } else if (!hookStatus.kbManaged && hookStatus.reason && /legacy managed hook/i.test(hookStatus.reason)) {
162
- // Legacy v1 hook: import will replace it; that's the migration
163
- // path (T03 case 2), not a conflict.
164
- checks.hook = { ok: true, reason: 'legacy-v1' };
165
- } else {
166
- checks.hook = { ok: true };
167
- }
168
- } catch (error) {
169
- checks.hook = { ok: true, reason: 'no-hooks-dir' };
170
- }
171
- }
172
-
173
- // Check 7: knowledge language selection (zh-CN / en-US).
174
- const requestedLanguage = input.knowledgeLanguage || 'zh-CN';
175
- if (!['zh-CN', 'en-US'].includes(requestedLanguage)) {
176
- problems.push({ code: 'KNOWLEDGE_LANGUAGE_INVALID', message: `knowledgeLanguage must be 'zh-CN' or 'en-US'; got '${requestedLanguage}'.`, action: 'CHOOSE_LANGUAGE' });
177
- checks.knowledgeLanguage = { ok: false, requested: requestedLanguage };
178
- } else {
179
- checks.knowledgeLanguage = { ok: true, value: requestedLanguage };
180
- }
181
-
182
- // Check 8: optional team binding compatibility.
183
- let teamBinding = null;
184
- if (input.teamBinding) {
185
- try {
186
- teamBinding = this.normalizeTeamBinding(input.teamBinding);
187
- if (!fs.existsSync(teamBinding.knowledgePath) || !fs.statSync(teamBinding.knowledgePath).isDirectory()) {
188
- problems.push({ code: 'TEAM_KB_MISSING', message: 'The selected team knowledge directory does not exist.', action: 'CHOOSE_TEAM_STORE' });
189
- checks.teamBinding = { ok: false, reason: 'missing' };
190
- } else {
191
- checks.teamBinding = { ok: true };
192
- }
193
- } catch (error) {
194
- problems.push({ code: 'TEAM_BINDING_INVALID', message: error.message, action: 'CHOOSE_TEAM_STORE' });
195
- checks.teamBinding = { ok: false };
196
- }
197
- }
198
-
199
- const ready = problems.length === 0;
200
- return {
201
- ok: ready,
202
- ready,
203
- plannedGitInit,
204
- problems,
205
- checks,
206
- effective: {
207
- aiProfile,
208
- knowledgeRoot: checks.knowledgeRoot && checks.knowledgeRoot.path || null,
209
- knowledgeLanguage: checks.knowledgeLanguage && checks.knowledgeLanguage.value || null,
210
- teamBinding: !!teamBinding,
211
- },
212
- };
213
- }
214
-
215
- transactionPath(operationId) { return this.layout.getRuntimePath('transactions', `${operationId}.json`); }
216
- deleteTransactionPath(projectId) { return this.layout.getRuntimePath('deletions', `${projectId}.json`); }
217
-
218
- readDeleteJournal(projectId) {
219
- return AtomicFile.readJsonStrict(this.deleteTransactionPath(projectId), {
220
- allowMissing: true,
221
- defaultValue: null,
222
- category: 'project-delete-transaction',
223
- validate: journal => {
224
- if (!journal || journal.schema !== 'project-delete-transaction/v1' || journal.projectId !== projectId || !journal.config || !journal.steps) {
225
- throw new DomainError('DATA_CORRUPT', 'Project delete transaction is corrupt.', { status: 500 });
226
- }
227
- return journal;
228
- },
229
- });
230
- }
231
-
232
- hasPendingDeletion(projectId) {
233
- const journal = this.readDeleteJournal(projectId);
234
- return Boolean(journal && journal.phase !== 'completed');
235
- }
236
-
237
- writeDeleteJournal(journal) {
238
- journal.updatedAt = new Date().toISOString();
239
- AtomicFile.writeJsonAtomic(this.deleteTransactionPath(journal.projectId), journal);
240
- }
241
-
242
- writeJournal(journal) {
243
- journal.updatedAt = new Date().toISOString();
244
- AtomicFile.writeJsonAtomic(this.transactionPath(journal.operationId), journal);
245
- }
246
-
247
- listConfigs() {
248
- const configs = [];
249
- for (const projectId of this.registryStore.listIds()) configs.push(this.projectStore.readConfig(projectId));
250
- return configs;
251
- }
252
-
253
- inspectOrInitializeGit(repoPath, journal) {
254
- const inside = runGit(repoPath, ['rev-parse', '--is-inside-work-tree'], { allowFailure: true });
255
- if (!inside.ok) {
256
- const initialized = runGit(repoPath, ['init']);
257
- journal.gitInitialized = initialized.ok;
258
- }
259
- const top = runGit(repoPath, ['rev-parse', '--show-toplevel']).stdout;
260
- const commonDir = runGit(repoPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']).stdout;
261
- const head = runGit(repoPath, ['rev-parse', '--verify', 'HEAD'], { allowFailure: true });
262
- return { repoPath: path.resolve(top), commonDir: path.resolve(commonDir), head: head.ok ? head.stdout : null };
263
- }
264
-
265
- async importProject(input = {}) {
266
- const operationId = input.operationId || createId('op');
267
- const log = this.logger.child ? this.logger.child({ component: 'project-lifecycle', operationId }) : this.logger;
268
- const journal = { schema: 'project-import-transaction/v1', operationId, phase: 'started', created: {}, startedAt: new Date().toISOString() };
269
- this.writeJournal(journal);
270
- await log.info?.('project.import.started', 'Project import started.', { phase: 'validate' });
271
- try {
272
- const localPath = path.resolve(String(input.localPath || '').trim());
273
- if (!input.localPath || !fs.existsSync(localPath) || !fs.statSync(localPath).isDirectory()) throw new DomainError('INVALID_ARGUMENT', 'localPath must be an existing directory.', { status: 400, operationId });
274
- const settings = this.settingsStore.read();
275
- const knowledgeRoot = this.layout.getKnowledgeRootPath(settings);
276
- this.layout.validateKnowledgeRoot(knowledgeRoot);
277
- const git = this.inspectOrInitializeGit(localPath, journal);
278
- for (const config of this.listConfigs()) {
279
- if (this.layout.pathsEqual(config.repoPath, git.repoPath) || (config.repoIdentity && this.layout.pathsEqual(config.repoIdentity.commonDir, git.commonDir))) {
280
- throw new DomainError('INVALID_ARGUMENT', 'This Git repository is already imported.', { status: 409, operationId });
281
- }
282
- }
283
- const projectId = input.projectId || `project-${crypto.randomUUID()}`;
284
- const displayName = String(input.displayName || path.basename(git.repoPath));
285
- const storageName = input.storageName || `${slugify(displayName)}-${projectId.replace(/[^a-z0-9]/gi, '').slice(-6).toLowerCase()}`;
286
- const team = this.normalizeTeamBinding(input.teamBinding || input.teamKnowledgeBase);
287
- const knowledgePath = team ? team.knowledgePath : this.layout.resolveNewProjectKnowledgePath(storageName, settings);
288
- if (team) {
289
- if (!fs.existsSync(knowledgePath) || !fs.statSync(knowledgePath).isDirectory()) {
290
- throw new DomainError('INVALID_ARGUMENT', 'The selected team knowledge directory does not exist.', { status: 400, operationId });
291
- }
292
- } else {
293
- if (fs.existsSync(knowledgePath) && fs.readdirSync(knowledgePath).length > 0) throw new DomainError('MIGRATION_TARGET_CONFLICT', 'The project knowledge directory is not empty.', { status: 409, operationId });
294
- if (!fs.existsSync(knowledgePath)) {
295
- fs.mkdirSync(knowledgePath, { recursive: true });
296
- journal.created.knowledgeDirectory = knowledgePath;
297
- }
298
- }
299
- journal.phase = 'paths-prepared';
300
- journal.projectId = projectId;
301
- journal.repoPath = git.repoPath;
302
- journal.knowledgePath = knowledgePath;
303
- this.writeJournal(journal);
304
- // Canonical workspace identity comes from the Bridge package; the old
305
- // PK-only { commonDir } shape is never written for new imports.
306
- const identityResult = this.bridgeAdapter && typeof this.bridgeAdapter.resolveRepoIdentity === 'function'
307
- ? await this.bridgeAdapter.resolveRepoIdentity(git.repoPath)
308
- : { status: 'unavailable', repoIdentity: null, reason: 'bridge-adapter-unavailable' };
309
- const repoIdentityV1 = identityResult.status === 'ok' ? identityResult.repoIdentity : null;
310
- const conversationBaseline = this.bridgeAdapter && typeof this.bridgeAdapter.getHighWatermark === 'function'
311
- ? await this.bridgeAdapter.getHighWatermark({ projectId, repoIdentity: repoIdentityV1, repoPath: git.repoPath })
312
- : { status: 'unavailable', cursor: null, reason: 'bridge-adapter-unavailable' };
313
- const stateInput = git.head
314
- ? { trackingStartCommit: git.head, trackingMode: 'normal' }
315
- : { trackingStartCommit: null, trackingMode: 'empty-repo' };
316
- stateInput.conversationBaselineCursor = conversationBaseline.cursor;
317
- stateInput.conversation = {
318
- lastConsumedCursor: conversationBaseline.cursor,
319
- captureStatus: conversationBaseline.status,
320
- lastError: conversationBaseline.status === 'captured' ? null : { reason: conversationBaseline.reason || 'unavailable' },
321
- };
322
- if (!repoIdentityV1) {
323
- stateInput.conversation.repoIdentityStatus = identityResult.reason || 'repo-identity-unavailable';
324
- }
325
- const created = await this.projectStore.create(projectId, {
326
- displayName, storageName, repoPath: git.repoPath, knowledgePath,
327
- enabled: true, aiProfileId: input.aiProfileId || null,
328
- knowledgeLanguage: input.knowledgeLanguage || 'zh-CN',
329
- teamBinding: team ? team.binding : null,
330
- repoIdentity: repoIdentityV1 || null,
331
- }, stateInput);
332
- journal.created.metadata = this.layout.getProjectMetadataDir(projectId);
333
- journal.phase = 'metadata-created';
334
- this.writeJournal(journal);
335
- const hook = this.hookManager.installHook({ repoPath: git.repoPath, projectId, triggerScriptPath: this.triggerScriptPath });
336
- journal.created.hookPath = hook.hookPath;
337
- journal.phase = 'hook-verified';
338
- this.writeJournal(journal);
339
- await this.registryStore.add(projectId, { createdAt: created.config.createdAt, displayNameSnapshot: displayName });
340
- journal.created.registry = true;
341
- journal.phase = 'completed';
342
- journal.completedAt = new Date().toISOString();
343
- this.writeJournal(journal);
344
- await log.info?.('project.import.completed', 'Project import completed.', { projectId, phase: 'registry-commit', durationMs: Date.now() - Date.parse(journal.startedAt) });
345
- return { ok: true, operationId, projectId, config: created.config, state: created.state, hook, gitInitialized: journal.gitInitialized === true };
346
- } catch (error) {
347
- const rollbackWarnings = await this.rollbackImport(journal);
348
- journal.phase = 'failed';
349
- journal.failedAt = new Date().toISOString();
350
- journal.error = { code: error.code || '', message: String(error.message || error) };
351
- journal.rollbackWarnings = rollbackWarnings;
352
- this.writeJournal(journal);
353
- await log.error?.('project.import.failed', 'Project import failed.', { projectId: journal.projectId || '', phase: journal.phase, error, context: { rollbackWarnings } });
354
- if (error instanceof DomainError) throw error;
355
- throw new DomainError('INVALID_ARGUMENT', 'Project import failed.', { status: 500, operationId, cause: error, details: { rollbackWarnings } });
356
- }
357
- }
358
-
359
- normalizeTeamBinding(input) {
360
- if (!input) return null;
361
- if (typeof input !== 'object' || Array.isArray(input)) throw new DomainError('INVALID_ARGUMENT', 'teamBinding must be an object.');
362
- const storePath = path.resolve(String(input.storePath || input.storeLocalPath || input.kbStorePath || '').trim());
363
- const rawSubdir = String(input.kbSubdir || input.path || '').trim().replace(/\\/g, '/');
364
- if (!String(input.storePath || input.storeLocalPath || input.kbStorePath || '').trim() || !rawSubdir) {
365
- throw new DomainError('INVALID_ARGUMENT', 'Team knowledge requires storePath and kbSubdir.');
366
- }
367
- if (path.isAbsolute(rawSubdir) || rawSubdir.split('/').some(part => !part || part === '.' || part === '..')) {
368
- throw new DomainError('PATH_OUTSIDE_ROOT', 'Team knowledge kbSubdir is invalid.', { status: 403 });
369
- }
370
- const knowledgePath = path.resolve(storePath, ...rawSubdir.split('/'));
371
- if (!this.layout.isPathInside(storePath, knowledgePath)) {
372
- throw new DomainError('PATH_OUTSIDE_ROOT', 'Team knowledge must stay inside the selected store.', { status: 403 });
373
- }
374
- const provider = String(input.provider || input.teamProvider || 'github').trim().toLowerCase();
375
- if (!['github', 'gitea'].includes(provider)) throw new DomainError('INVALID_ARGUMENT', 'Unsupported team knowledge provider.');
376
- return {
377
- knowledgePath,
378
- binding: {
379
- schema: 'team-binding/v1',
380
- provider,
381
- storePath,
382
- storeRemoteUrl: String(input.storeRemoteUrl || input.kbStoreRemoteUrl || input.cloneUrl || ''),
383
- storeId: String(input.storeId || input.kbStoreId || ''),
384
- storeFullName: String(input.storeFullName || input.kbStoreFullName || ''),
385
- branch: String(input.branch || input.defaultBranch || 'main'),
386
- kbId: String(input.kbId || path.basename(knowledgePath)),
387
- kbSlug: String(input.kbSlug || input.slug || path.basename(knowledgePath)),
388
- kbSubdir: rawSubdir,
389
- displayName: String(input.displayName || input.kbDisplayName || path.basename(knowledgePath)),
390
- },
391
- };
392
- }
393
-
394
- async rollbackImport(journal) {
395
- const warnings = [];
396
- if (journal.created.registry && journal.projectId) {
397
- try { await this.registryStore.remove(journal.projectId); } catch (error) { warnings.push(`registry:${error.message}`); }
398
- }
399
- if (journal.created.hookPath && journal.projectId && journal.repoPath) {
400
- try { this.hookManager.uninstallHook({ repoPath: journal.repoPath, projectId: journal.projectId }); } catch (error) { warnings.push(`hook:${error.message}`); }
401
- }
402
- if (journal.created.metadata && fs.existsSync(journal.created.metadata)) {
403
- try { fs.rmSync(journal.created.metadata, { recursive: true, force: true }); } catch (error) { warnings.push(`metadata:${error.message}`); }
404
- }
405
- if (journal.created.knowledgeDirectory && fs.existsSync(journal.created.knowledgeDirectory)) {
406
- try {
407
- if (fs.readdirSync(journal.created.knowledgeDirectory).length === 0) fs.rmdirSync(journal.created.knowledgeDirectory);
408
- else warnings.push('knowledge:ROLLBACK_ASSET_PRESERVED');
409
- } catch (error) { warnings.push(`knowledge:${error.message}`); }
410
- }
411
- if (journal.gitInitialized) warnings.push('git:ROLLBACK_ASSET_PRESERVED');
412
- return warnings;
413
- }
414
-
415
- async deleteProject(projectId, options = {}) {
416
- let journal = this.readDeleteJournal(projectId);
417
- const operationId = journal && journal.operationId || options.operationId || createId('op');
418
- const log = this.logger.child ? this.logger.child({ component: 'project-lifecycle', operationId, projectId }) : this.logger;
419
- if (!journal) {
420
- if (await this.isProjectBusy(projectId)) throw new DomainError('PROJECT_BUSY', 'Project has an active reconciliation or AI run.', { status: 409, retryable: true, operationId });
421
- const config = this.projectStore.readConfig(projectId);
422
- if (options.deleteKnowledge === true && options.confirmationToken !== projectId) {
423
- throw new DomainError('INVALID_ARGUMENT', 'Explicit projectId confirmation is required to delete knowledge.', { status: 409, operationId });
424
- }
425
- journal = {
426
- schema: 'project-delete-transaction/v1',
427
- operationId,
428
- projectId,
429
- phase: 'tombstoned',
430
- requested: { deleteKnowledge: options.deleteKnowledge === true },
431
- config,
432
- steps: {
433
- hook: { completed: false },
434
- registry: { completed: false },
435
- metadata: { completed: false },
436
- knowledge: { completed: false },
437
- },
438
- startedAt: new Date().toISOString(),
439
- };
440
- this.writeDeleteJournal(journal);
441
- this.fault('delete-tombstoned', journal);
442
- await log.info?.('project.delete.started', 'Project delete transaction started.', { phase: 'tombstoned', context: { deleteKnowledge: journal.requested.deleteKnowledge } });
443
- } else {
444
- if (journal.phase === 'completed') {
445
- return { ok: true, operationId, projectId, ...journal.result, recovered: true };
446
- }
447
- if (Boolean(options.deleteKnowledge) !== Boolean(journal.requested.deleteKnowledge)) {
448
- throw new DomainError('IMMUTABLE_FIELD', 'A pending delete transaction cannot change deleteKnowledge.', { status: 409, operationId });
449
- }
450
- if (journal.requested.deleteKnowledge && options.confirmationToken !== projectId) {
451
- throw new DomainError('INVALID_ARGUMENT', 'Explicit projectId confirmation is required to resume knowledge deletion.', { status: 409, operationId });
452
- }
453
- }
454
- const config = journal.config;
455
- const perform = async (stepName, action) => {
456
- if (journal.steps[stepName].completed) return journal.steps[stepName].result;
457
- journal.phase = `${stepName}.running`;
458
- journal.failedStep = null;
459
- this.writeDeleteJournal(journal);
460
- this.fault(`delete-before-${stepName}`, journal);
461
- const result = await action();
462
- this.fault(`delete-after-${stepName}`, journal);
463
- journal.steps[stepName] = { completed: true, completedAt: new Date().toISOString(), result };
464
- journal.phase = `${stepName}.completed`;
465
- this.writeDeleteJournal(journal);
466
- return result;
467
- };
468
- try {
469
- const hook = await perform('hook', async () => {
470
- if (!fs.existsSync(config.repoPath)) return { ok: true, removed: false, reason: 'repository-missing' };
471
- return this.hookManager.uninstallHook({ repoPath: config.repoPath, projectId });
472
- });
473
- await perform('registry', async () => ({ removed: await this.registryStore.remove(projectId) }));
474
- await perform('metadata', async () => {
475
- const metadataDir = this.layout.getProjectMetadataDir(projectId);
476
- if (!fs.existsSync(metadataDir)) return { removed: false };
477
- fs.rmSync(metadataDir, { recursive: true, force: true });
478
- return { removed: true };
479
- });
480
- const knowledge = await perform('knowledge', async () => {
481
- if (!journal.requested.deleteKnowledge || config.teamBinding) return { removed: false, preserved: true };
482
- if (!fs.existsSync(config.knowledgePath)) return { removed: false, preserved: false };
483
- fs.rmSync(config.knowledgePath, { recursive: true, force: true });
484
- return { removed: true, preserved: false };
485
- });
486
- this.fault('delete-before-completed', journal);
487
- journal.phase = 'completed';
488
- journal.completedAt = new Date().toISOString();
489
- journal.result = {
490
- hook,
491
- removedKnowledge: knowledge.removed === true,
492
- knowledgePath: config.knowledgePath,
493
- externalKnowledgePreserved: knowledge.removed !== true,
494
- };
495
- this.writeDeleteJournal(journal);
496
- await log.info?.('project.delete.completed', 'Project delete transaction completed.', { phase: 'completed', context: { hook, externalKnowledgePreserved: journal.result.externalKnowledgePreserved } });
497
- return { ok: true, operationId, projectId, ...journal.result };
498
- } catch (error) {
499
- journal.failedStep = journal.phase;
500
- journal.phase = 'failed';
501
- journal.failedAt = new Date().toISOString();
502
- journal.error = { code: error.code || 'INVALID_ARGUMENT', message: String(error.message || error) };
503
- this.writeDeleteJournal(journal);
504
- await log.error?.('project.delete.failed', 'Project delete transaction stopped and can be retried.', { phase: journal.failedStep, error });
505
- if (error instanceof DomainError) throw error;
506
- throw new DomainError('MIGRATION_FAILED', 'Project delete transaction failed and can be retried.', { status: 500, operationId, retryable: true, cause: error });
507
- }
508
- }
509
- }
510
-
511
- module.exports = { ProjectLifecycleService, slugify, runGit };
89
+ const commonDir = runGit(localPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
90
+ const branch = runGit(localPath, ['branch', '--show-current'], { allowFailure: true });
91
+ repoInspection = {
92
+ ok: true,
93
+ repoPath: top.ok ? path.resolve(top.stdout) : path.resolve(localPath),
94
+ commonDir: commonDir.ok ? path.resolve(commonDir.stdout) : '',
95
+ headCommit: head.ok ? head.stdout : null,
96
+ branch: branch.ok ? branch.stdout : '',
97
+ emptyRepo: !head.ok,
98
+ };
99
+ checks.git = { ok: true, status: repoInspection.emptyRepo ? 'empty' : 'ok', repoPath: repoInspection.repoPath, commonDir: repoInspection.commonDir, headCommit: repoInspection.headCommit, branch: repoInspection.branch };
100
+ }
101
+ }
102
+
103
+ // Check 3: knowledge root configured + writable.
104
+ if (!knowledgeRoot) {
105
+ problems.push({ code: 'KNOWLEDGE_ROOT_MISSING', message: 'Knowledge root is not configured.', action: 'CONFIGURE_KNOWLEDGE_ROOT' });
106
+ checks.knowledgeRoot = { ok: false, reason: 'unconfigured' };
107
+ } else if (!fs.existsSync(knowledgeRoot)) {
108
+ try {
109
+ let parent = path.dirname(knowledgeRoot);
110
+ while (!fs.existsSync(parent) && path.dirname(parent) !== parent) parent = path.dirname(parent);
111
+ fs.accessSync(parent, fs.constants.W_OK);
112
+ } catch (error) {
113
+ problems.push({ code: 'KNOWLEDGE_ROOT_NOT_WRITABLE', message: `Knowledge root is not writable: ${error.message}`, action: 'CONFIGURE_KNOWLEDGE_ROOT' });
114
+ checks.knowledgeRoot = { ok: false, reason: 'not-writable', path: knowledgeRoot };
115
+ }
116
+ checks.knowledgeRoot = checks.knowledgeRoot || { ok: true, path: knowledgeRoot, plannedCreate: true };
117
+ } else {
118
+ try {
119
+ fs.accessSync(knowledgeRoot, fs.constants.W_OK);
120
+ checks.knowledgeRoot = { ok: true, path: knowledgeRoot };
121
+ } catch (error) {
122
+ problems.push({ code: 'KNOWLEDGE_ROOT_NOT_WRITABLE', message: `Knowledge root is not writable: ${error.message}`, action: 'CONFIGURE_KNOWLEDGE_ROOT' });
123
+ checks.knowledgeRoot = { ok: false, reason: 'not-writable', path: knowledgeRoot };
124
+ }
125
+ }
126
+
127
+ // Check 4: effective AI profile availability.
128
+ let aiProfile = null;
129
+ try {
130
+ const resolved = resolveEffectiveAiProfile(settings, { aiProfileId: input.aiProfileId || null });
131
+ aiProfile = { id: resolved.profileId, source: resolved.source };
132
+ checks.aiProfile = { ok: true, ...aiProfile };
133
+ } catch (error) {
134
+ if (error && error.code === 'AI_PROFILE_REQUIRED') {
135
+ checks.aiProfile = { ok: false, required: false, message: '后台模型尚未配置;项目仍可导入,不会自动分析历史。' };
136
+ } else {
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ // Check 5: duplicate / already-managed project.
142
+ if (repoInspection && repoInspection.ok) {
143
+ for (const config of this.listConfigs()) {
144
+ if (this.layout.pathsEqual(config.repoPath, repoInspection.repoPath)
145
+ || (config.repoIdentity && config.repoIdentity.commonDir && repoInspection.commonDir
146
+ && this.layout.pathsEqual(config.repoIdentity.commonDir, repoInspection.commonDir))) {
147
+ problems.push({ code: 'DUPLICATE_PROJECT', message: 'This Git repository is already managed by another project.', action: 'OPEN_EXISTING_PROJECT', existingProjectId: config.projectId });
148
+ checks.duplicate = { ok: false, existingProjectId: config.projectId };
149
+ break;
150
+ }
151
+ }
152
+ if (!checks.duplicate) checks.duplicate = { ok: true };
153
+ }
154
+
155
+ // Check 6: existing non-managed hook conflict.
156
+ if (repoInspection && repoInspection.ok) {
157
+ try {
158
+ const hookStatus = this.hookManager.readHookStatus({ repoPath: repoInspection.repoPath });
159
+ if (!hookStatus.kbManaged && hookStatus.reason && /third-party/i.test(hookStatus.reason)) {
160
+ problems.push({ code: 'HOOK_CONFLICT', message: 'A third-party post-commit hook is installed. Project-Knowledge will not overwrite it.', action: 'INSPECT_HOOK' });
161
+ checks.hook = { ok: false, reason: 'third-party' };
162
+ } else if (!hookStatus.kbManaged && hookStatus.reason && /legacy managed hook/i.test(hookStatus.reason)) {
163
+ // Legacy v1 hook: import will replace it; that's the migration
164
+ // path (T03 case 2), not a conflict.
165
+ checks.hook = { ok: true, reason: 'legacy-v1' };
166
+ } else {
167
+ checks.hook = { ok: true };
168
+ }
169
+ } catch (error) {
170
+ checks.hook = { ok: true, reason: 'no-hooks-dir' };
171
+ }
172
+ }
173
+
174
+ // Check 7: knowledge language selection (zh-CN / en-US).
175
+ const requestedLanguage = input.knowledgeLanguage || 'zh-CN';
176
+ if (!['zh-CN', 'en-US'].includes(requestedLanguage)) {
177
+ problems.push({ code: 'KNOWLEDGE_LANGUAGE_INVALID', message: `knowledgeLanguage must be 'zh-CN' or 'en-US'; got '${requestedLanguage}'.`, action: 'CHOOSE_LANGUAGE' });
178
+ checks.knowledgeLanguage = { ok: false, requested: requestedLanguage };
179
+ } else {
180
+ checks.knowledgeLanguage = { ok: true, value: requestedLanguage };
181
+ }
182
+
183
+ // Check 8: optional team binding compatibility.
184
+ let teamBinding = null;
185
+ if (input.teamBinding) {
186
+ try {
187
+ teamBinding = this.normalizeTeamBinding(input.teamBinding);
188
+ if (!fs.existsSync(teamBinding.knowledgePath) || !fs.statSync(teamBinding.knowledgePath).isDirectory()) {
189
+ problems.push({ code: 'TEAM_KB_MISSING', message: 'The selected team knowledge directory does not exist.', action: 'CHOOSE_TEAM_STORE' });
190
+ checks.teamBinding = { ok: false, reason: 'missing' };
191
+ } else {
192
+ checks.teamBinding = { ok: true };
193
+ }
194
+ } catch (error) {
195
+ problems.push({ code: 'TEAM_BINDING_INVALID', message: error.message, action: 'CHOOSE_TEAM_STORE' });
196
+ checks.teamBinding = { ok: false };
197
+ }
198
+ }
199
+
200
+ const ready = problems.length === 0;
201
+ if (input.domainId && !(settings.brain?.domains || []).some(d => d.id === input.domainId)) problems.push({ code: 'DOMAIN_MISSING', message: '所选领域不存在。' });
202
+ if (input.knowledgePath) {
203
+ const target = path.resolve(input.knowledgePath);
204
+ const overlap = (a, b) => this.layout.isPathInside(a, b, { realpath: true }) || this.layout.isPathInside(b, a, { realpath: true });
205
+ if (!path.isAbsolute(input.knowledgePath)) problems.push({ code: 'KNOWLEDGE_PATH_INVALID', message: '知识目录必须是绝对路径。' });
206
+ else if (overlap(target, localPath) || knowledgeRoot && overlap(target, path.join(knowledgeRoot, '_shared')) || this.listConfigs().some(c => overlap(c.knowledgePath, target))) problems.push({ code: 'KNOWLEDGE_PATH_CONFLICT', message: '知识目录与代码、共享目录或其他项目冲突。' });
207
+ else if (!input.teamBinding && fs.existsSync(target) && (!fs.statSync(target).isDirectory() || fs.readdirSync(target).length)) problems.push({ code: 'KNOWLEDGE_PATH_NOT_EMPTY', message: '新项目的知识目录必须为空;已有文件会保留。' });
208
+ }
209
+ return {
210
+ ok: problems.length === 0,
211
+ ready: problems.length === 0,
212
+ plannedGitInit,
213
+ problems,
214
+ checks,
215
+ effective: {
216
+ aiProfile,
217
+ knowledgeRoot: checks.knowledgeRoot && checks.knowledgeRoot.path || null,
218
+ knowledgeLanguage: checks.knowledgeLanguage && checks.knowledgeLanguage.value || null,
219
+ teamBinding: !!teamBinding,
220
+ },
221
+ };
222
+ }
223
+
224
+ transactionPath(operationId) { return this.layout.getRuntimePath('transactions', `${operationId}.json`); }
225
+ deleteTransactionPath(projectId) { return this.layout.getRuntimePath('deletions', `${projectId}.json`); }
226
+
227
+ readDeleteJournal(projectId) {
228
+ return AtomicFile.readJsonStrict(this.deleteTransactionPath(projectId), {
229
+ allowMissing: true,
230
+ defaultValue: null,
231
+ category: 'project-delete-transaction',
232
+ validate: journal => {
233
+ if (!journal || journal.schema !== 'project-delete-transaction/v1' || journal.projectId !== projectId || !journal.config || !journal.steps) {
234
+ throw new DomainError('DATA_CORRUPT', 'Project delete transaction is corrupt.', { status: 500 });
235
+ }
236
+ return journal;
237
+ },
238
+ });
239
+ }
240
+
241
+ hasPendingDeletion(projectId) {
242
+ const journal = this.readDeleteJournal(projectId);
243
+ return Boolean(journal && journal.phase !== 'completed');
244
+ }
245
+
246
+ writeDeleteJournal(journal) {
247
+ journal.updatedAt = new Date().toISOString();
248
+ AtomicFile.writeJsonAtomic(this.deleteTransactionPath(journal.projectId), journal);
249
+ }
250
+
251
+ writeJournal(journal) {
252
+ journal.updatedAt = new Date().toISOString();
253
+ AtomicFile.writeJsonAtomic(this.transactionPath(journal.operationId), journal);
254
+ }
255
+
256
+ listConfigs() {
257
+ const configs = [];
258
+ for (const projectId of this.registryStore.listIds()) configs.push(this.projectStore.readConfig(projectId));
259
+ return configs;
260
+ }
261
+
262
+ inspectOrInitializeGit(repoPath, journal, options = {}) {
263
+ const inside = runGit(repoPath, ['rev-parse', '--is-inside-work-tree'], { allowFailure: true });
264
+ const topBefore = inside.ok ? runGit(repoPath, ['rev-parse', '--show-toplevel']) : null;
265
+ if (!inside.ok || !this.layout.pathsEqual(topBefore.stdout, repoPath)) {
266
+ if (options.confirmGitInit !== true) throw new DomainError('INVALID_ARGUMENT', '请明确确认后再初始化非 Git 目录。');
267
+ const initialized = runGit(repoPath, ['init']);
268
+ journal.gitInitialized = initialized.ok;
269
+ }
270
+ const top = runGit(repoPath, ['rev-parse', '--show-toplevel']).stdout;
271
+ const commonDir = runGit(repoPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']).stdout;
272
+ const head = runGit(repoPath, ['rev-parse', '--verify', 'HEAD'], { allowFailure: true });
273
+ return { repoPath: path.resolve(top), commonDir: path.resolve(commonDir), head: head.ok ? head.stdout : null };
274
+ }
275
+
276
+ async importProject(input = {}) {
277
+ const operationId = input.operationId || createId('op');
278
+ const log = this.logger.child ? this.logger.child({ component: 'project-lifecycle', operationId }) : this.logger;
279
+ const journal = { schema: 'project-import-transaction/v1', operationId, phase: 'started', created: {}, startedAt: new Date().toISOString() };
280
+ this.writeJournal(journal);
281
+ await log.info?.('project.import.started', 'Project import started.', { phase: 'validate' });
282
+ try {
283
+ const localPath = path.resolve(String(input.localPath || '').trim());
284
+ if (!input.localPath || !fs.existsSync(localPath) || !fs.statSync(localPath).isDirectory()) throw new DomainError('INVALID_ARGUMENT', 'localPath must be an existing directory.', { status: 400, operationId });
285
+ const settings = this.settingsStore.read();
286
+ const knowledgeRoot = this.layout.getKnowledgeRootPath(settings);
287
+ this.layout.validateKnowledgeRoot(knowledgeRoot);
288
+ const brain = settings.brain || { id: 'brain-default', domains: [] };
289
+ if (input.brainId && input.brainId !== brain.id) throw new DomainError('INVALID_ARGUMENT', '智脑不存在。');
290
+ if (input.domainId && !brain.domains.some(domain => domain.id === input.domainId)) throw new DomainError('INVALID_ARGUMENT', '领域不存在。');
291
+ const git = this.inspectOrInitializeGit(localPath, journal, input);
292
+ for (const config of this.listConfigs()) {
293
+ if (this.layout.pathsEqual(config.repoPath, git.repoPath) || (config.repoIdentity && this.layout.pathsEqual(config.repoIdentity.commonDir, git.commonDir))) {
294
+ throw new DomainError('INVALID_ARGUMENT', 'This Git repository is already imported.', { status: 409, operationId });
295
+ }
296
+ }
297
+ const projectId = input.projectId || `project-${crypto.randomUUID()}`;
298
+ const displayName = String(input.displayName || path.basename(git.repoPath));
299
+ const storageName = input.storageName || `${slugify(displayName)}-${projectId.replace(/[^a-z0-9]/gi, '').slice(-6).toLowerCase()}`;
300
+ const team = this.normalizeTeamBinding(input.teamBinding || input.teamKnowledgeBase);
301
+ const knowledgePath = team ? team.knowledgePath : input.knowledgePath ? path.resolve(input.knowledgePath) : this.layout.resolveNewProjectKnowledgePath(storageName, settings);
302
+ if (input.knowledgePath && !path.isAbsolute(input.knowledgePath)) throw new DomainError('INVALID_ARGUMENT', '知识目录必须是绝对路径。');
303
+ if (this.layout.isPathInside(git.repoPath, knowledgePath, { realpath: true }) || this.layout.isPathInside(knowledgePath, git.repoPath, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', '代码目录和知识目录不能相互嵌套。', { status: 409 });
304
+ const sharedRoot = path.join(knowledgeRoot, '_shared');
305
+ if (this.layout.isPathInside(sharedRoot, knowledgePath, { realpath: true }) || this.layout.isPathInside(knowledgePath, sharedRoot, { realpath: true })) throw new DomainError('PATH_OUTSIDE_ROOT', '项目知识目录不能占用智脑共享目录。', { status: 409 });
306
+ for (const config of this.listConfigs()) {
307
+ if (this.layout.isPathInside(config.knowledgePath, knowledgePath, { realpath: true }) || this.layout.isPathInside(knowledgePath, config.knowledgePath, { realpath: true })) throw new DomainError('MIGRATION_TARGET_CONFLICT', '知识目录与已登记项目冲突。', { status: 409 });
308
+ }
309
+ if (team) {
310
+ if (!fs.existsSync(knowledgePath) || !fs.statSync(knowledgePath).isDirectory()) {
311
+ throw new DomainError('INVALID_ARGUMENT', 'The selected team knowledge directory does not exist.', { status: 400, operationId });
312
+ }
313
+ } else {
314
+ if (fs.existsSync(knowledgePath) && fs.readdirSync(knowledgePath).length > 0) throw new DomainError('MIGRATION_TARGET_CONFLICT', 'The project knowledge directory is not empty.', { status: 409, operationId });
315
+ if (!fs.existsSync(knowledgePath)) {
316
+ fs.mkdirSync(knowledgePath, { recursive: true });
317
+ journal.created.knowledgeDirectory = knowledgePath;
318
+ }
319
+ }
320
+ journal.phase = 'paths-prepared';
321
+ journal.projectId = projectId;
322
+ journal.repoPath = git.repoPath;
323
+ journal.knowledgePath = knowledgePath;
324
+ this.writeJournal(journal);
325
+ // Canonical workspace identity comes from the Bridge package; the old
326
+ // PK-only { commonDir } shape is never written for new imports.
327
+ const identityResult = this.bridgeAdapter && typeof this.bridgeAdapter.resolveRepoIdentity === 'function'
328
+ ? await this.bridgeAdapter.resolveRepoIdentity(git.repoPath)
329
+ : { status: 'unavailable', repoIdentity: null, reason: 'bridge-adapter-unavailable' };
330
+ const repoIdentityV1 = identityResult.status === 'ok' ? identityResult.repoIdentity : null;
331
+ const conversationBaseline = this.bridgeAdapter && typeof this.bridgeAdapter.getHighWatermark === 'function'
332
+ ? await this.bridgeAdapter.getHighWatermark({ projectId, repoIdentity: repoIdentityV1, repoPath: git.repoPath })
333
+ : { status: 'unavailable', cursor: null, reason: 'bridge-adapter-unavailable' };
334
+ const stateInput = git.head
335
+ ? { trackingStartCommit: git.head, trackingMode: 'normal' }
336
+ : { trackingStartCommit: null, trackingMode: 'empty-repo' };
337
+ stateInput.conversationBaselineCursor = conversationBaseline.cursor;
338
+ stateInput.conversation = {
339
+ lastConsumedCursor: conversationBaseline.cursor,
340
+ captureStatus: conversationBaseline.status,
341
+ lastError: conversationBaseline.status === 'captured' ? null : { reason: conversationBaseline.reason || 'unavailable' },
342
+ };
343
+ if (!repoIdentityV1) {
344
+ stateInput.conversation.repoIdentityStatus = identityResult.reason || 'repo-identity-unavailable';
345
+ }
346
+ const created = await this.projectStore.create(projectId, {
347
+ displayName, storageName, repoPath: git.repoPath, knowledgePath,
348
+ enabled: true, aiProfileId: input.aiProfileId || null,
349
+ knowledgeLanguage: input.knowledgeLanguage || 'zh-CN',
350
+ brainId: brain.id, domainId: input.domainId || null,
351
+ teamBinding: team ? team.binding : null,
352
+ repoIdentity: repoIdentityV1 || null,
353
+ }, stateInput);
354
+ journal.created.metadata = this.layout.getProjectMetadataDir(projectId);
355
+ journal.phase = 'metadata-created';
356
+ this.writeJournal(journal);
357
+ const hook = this.hookManager.installHook({ repoPath: git.repoPath, projectId, triggerScriptPath: this.triggerScriptPath, dataDir: this.layout.getDataDir(), ...this.bridgeAdapter?.hookBinding?.() });
358
+ journal.created.hookPath = hook.hookPath;
359
+ journal.phase = 'hook-verified';
360
+ this.writeJournal(journal);
361
+ await this.registryStore.add(projectId, { createdAt: created.config.createdAt, displayNameSnapshot: displayName });
362
+ journal.created.registry = true;
363
+ journal.phase = 'completed';
364
+ journal.completedAt = new Date().toISOString();
365
+ this.writeJournal(journal);
366
+ await log.info?.('project.import.completed', 'Project import completed.', { projectId, phase: 'registry-commit', durationMs: Date.now() - Date.parse(journal.startedAt) });
367
+ return { ok: true, operationId, projectId, config: created.config, state: created.state, hook, gitInitialized: journal.gitInitialized === true };
368
+ } catch (error) {
369
+ const rollbackWarnings = await this.rollbackImport(journal);
370
+ journal.phase = 'failed';
371
+ journal.failedAt = new Date().toISOString();
372
+ journal.error = { code: error.code || '', message: String(error.message || error) };
373
+ journal.rollbackWarnings = rollbackWarnings;
374
+ this.writeJournal(journal);
375
+ await log.error?.('project.import.failed', 'Project import failed.', { projectId: journal.projectId || '', phase: journal.phase, error, context: { rollbackWarnings } });
376
+ if (error instanceof DomainError) throw error;
377
+ throw new DomainError('INVALID_ARGUMENT', 'Project import failed.', { status: 500, operationId, cause: error, details: { rollbackWarnings } });
378
+ }
379
+ }
380
+
381
+ normalizeTeamBinding(input) {
382
+ if (!input) return null;
383
+ if (typeof input !== 'object' || Array.isArray(input)) throw new DomainError('INVALID_ARGUMENT', 'teamBinding must be an object.');
384
+ const storePath = path.resolve(String(input.storePath || input.storeLocalPath || input.kbStorePath || '').trim());
385
+ const rawSubdir = String(input.kbSubdir || input.path || '').trim().replace(/\\/g, '/');
386
+ if (!String(input.storePath || input.storeLocalPath || input.kbStorePath || '').trim() || !rawSubdir) {
387
+ throw new DomainError('INVALID_ARGUMENT', 'Team knowledge requires storePath and kbSubdir.');
388
+ }
389
+ if (path.isAbsolute(rawSubdir) || rawSubdir.split('/').some(part => !part || part === '.' || part === '..')) {
390
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Team knowledge kbSubdir is invalid.', { status: 403 });
391
+ }
392
+ const knowledgePath = path.resolve(storePath, ...rawSubdir.split('/'));
393
+ if (!this.layout.isPathInside(storePath, knowledgePath)) {
394
+ throw new DomainError('PATH_OUTSIDE_ROOT', 'Team knowledge must stay inside the selected store.', { status: 403 });
395
+ }
396
+ const provider = String(input.provider || input.teamProvider || 'github').trim().toLowerCase();
397
+ if (!['github', 'gitea'].includes(provider)) throw new DomainError('INVALID_ARGUMENT', 'Unsupported team knowledge provider.');
398
+ return {
399
+ knowledgePath,
400
+ binding: {
401
+ schema: 'team-binding/v1',
402
+ provider,
403
+ storePath,
404
+ storeRemoteUrl: String(input.storeRemoteUrl || input.kbStoreRemoteUrl || input.cloneUrl || ''),
405
+ storeId: String(input.storeId || input.kbStoreId || ''),
406
+ storeFullName: String(input.storeFullName || input.kbStoreFullName || ''),
407
+ branch: String(input.branch || input.defaultBranch || 'main'),
408
+ kbId: String(input.kbId || path.basename(knowledgePath)),
409
+ kbSlug: String(input.kbSlug || input.slug || path.basename(knowledgePath)),
410
+ kbSubdir: rawSubdir,
411
+ displayName: String(input.displayName || input.kbDisplayName || path.basename(knowledgePath)),
412
+ },
413
+ };
414
+ }
415
+
416
+ async rollbackImport(journal) {
417
+ const warnings = [];
418
+ if (journal.created.registry && journal.projectId) {
419
+ try { await this.registryStore.remove(journal.projectId); } catch (error) { warnings.push(`registry:${error.message}`); }
420
+ }
421
+ if (journal.created.hookPath && journal.projectId && journal.repoPath) {
422
+ try { this.hookManager.uninstallHook({ repoPath: journal.repoPath, projectId: journal.projectId }); } catch (error) { warnings.push(`hook:${error.message}`); }
423
+ }
424
+ if (journal.created.metadata && fs.existsSync(journal.created.metadata)) {
425
+ try { fs.rmSync(journal.created.metadata, { recursive: true, force: true }); } catch (error) { warnings.push(`metadata:${error.message}`); }
426
+ }
427
+ if (journal.created.knowledgeDirectory && fs.existsSync(journal.created.knowledgeDirectory)) {
428
+ try {
429
+ if (fs.readdirSync(journal.created.knowledgeDirectory).length === 0) fs.rmdirSync(journal.created.knowledgeDirectory);
430
+ else warnings.push('knowledge:ROLLBACK_ASSET_PRESERVED');
431
+ } catch (error) { warnings.push(`knowledge:${error.message}`); }
432
+ }
433
+ if (journal.gitInitialized) warnings.push('git:ROLLBACK_ASSET_PRESERVED');
434
+ return warnings;
435
+ }
436
+
437
+ async deleteProject(projectId, options = {}) {
438
+ let journal = this.readDeleteJournal(projectId);
439
+ const operationId = journal && journal.operationId || options.operationId || createId('op');
440
+ const log = this.logger.child ? this.logger.child({ component: 'project-lifecycle', operationId, projectId }) : this.logger;
441
+ if (!journal) {
442
+ if (await this.isProjectBusy(projectId)) throw new DomainError('PROJECT_BUSY', 'Project has an active reconciliation or AI run.', { status: 409, retryable: true, operationId });
443
+ const config = this.projectStore.readConfig(projectId);
444
+ if (options.deleteKnowledge === true && options.confirmationToken !== projectId) {
445
+ throw new DomainError('INVALID_ARGUMENT', 'Explicit projectId confirmation is required to delete knowledge.', { status: 409, operationId });
446
+ }
447
+ journal = {
448
+ schema: 'project-delete-transaction/v1',
449
+ operationId,
450
+ projectId,
451
+ phase: 'tombstoned',
452
+ requested: { deleteKnowledge: options.deleteKnowledge === true },
453
+ config,
454
+ steps: {
455
+ hook: { completed: false },
456
+ registry: { completed: false },
457
+ metadata: { completed: false },
458
+ knowledge: { completed: false },
459
+ },
460
+ startedAt: new Date().toISOString(),
461
+ };
462
+ this.writeDeleteJournal(journal);
463
+ this.fault('delete-tombstoned', journal);
464
+ await log.info?.('project.delete.started', 'Project delete transaction started.', { phase: 'tombstoned', context: { deleteKnowledge: journal.requested.deleteKnowledge } });
465
+ } else {
466
+ if (journal.phase === 'completed') {
467
+ return { ok: true, operationId, projectId, ...journal.result, recovered: true };
468
+ }
469
+ if (Boolean(options.deleteKnowledge) !== Boolean(journal.requested.deleteKnowledge)) {
470
+ throw new DomainError('IMMUTABLE_FIELD', 'A pending delete transaction cannot change deleteKnowledge.', { status: 409, operationId });
471
+ }
472
+ if (journal.requested.deleteKnowledge && options.confirmationToken !== projectId) {
473
+ throw new DomainError('INVALID_ARGUMENT', 'Explicit projectId confirmation is required to resume knowledge deletion.', { status: 409, operationId });
474
+ }
475
+ }
476
+ const config = journal.config;
477
+ const perform = async (stepName, action) => {
478
+ if (journal.steps[stepName].completed) return journal.steps[stepName].result;
479
+ journal.phase = `${stepName}.running`;
480
+ journal.failedStep = null;
481
+ this.writeDeleteJournal(journal);
482
+ this.fault(`delete-before-${stepName}`, journal);
483
+ const result = await action();
484
+ this.fault(`delete-after-${stepName}`, journal);
485
+ journal.steps[stepName] = { completed: true, completedAt: new Date().toISOString(), result };
486
+ journal.phase = `${stepName}.completed`;
487
+ this.writeDeleteJournal(journal);
488
+ return result;
489
+ };
490
+ try {
491
+ const hook = await perform('hook', async () => {
492
+ if (!fs.existsSync(config.repoPath)) return { ok: true, removed: false, reason: 'repository-missing' };
493
+ return this.hookManager.uninstallHook({ repoPath: config.repoPath, projectId });
494
+ });
495
+ await perform('registry', async () => ({ removed: await this.registryStore.remove(projectId) }));
496
+ await perform('metadata', async () => {
497
+ const metadataDir = this.layout.getProjectMetadataDir(projectId);
498
+ if (!fs.existsSync(metadataDir)) return { removed: false };
499
+ fs.rmSync(metadataDir, { recursive: true, force: true });
500
+ return { removed: true };
501
+ });
502
+ const knowledge = await perform('knowledge', async () => {
503
+ if (!journal.requested.deleteKnowledge || config.teamBinding) return { removed: false, preserved: true };
504
+ if (!fs.existsSync(config.knowledgePath)) return { removed: false, preserved: false };
505
+ fs.rmSync(config.knowledgePath, { recursive: true, force: true });
506
+ return { removed: true, preserved: false };
507
+ });
508
+ this.fault('delete-before-completed', journal);
509
+ journal.phase = 'completed';
510
+ journal.completedAt = new Date().toISOString();
511
+ journal.result = {
512
+ hook,
513
+ removedKnowledge: knowledge.removed === true,
514
+ knowledgePath: config.knowledgePath,
515
+ externalKnowledgePreserved: knowledge.removed !== true,
516
+ };
517
+ this.writeDeleteJournal(journal);
518
+ await log.info?.('project.delete.completed', 'Project delete transaction completed.', { phase: 'completed', context: { hook, externalKnowledgePreserved: journal.result.externalKnowledgePreserved } });
519
+ return { ok: true, operationId, projectId, ...journal.result };
520
+ } catch (error) {
521
+ journal.failedStep = journal.phase;
522
+ journal.phase = 'failed';
523
+ journal.failedAt = new Date().toISOString();
524
+ journal.error = { code: error.code || 'INVALID_ARGUMENT', message: String(error.message || error) };
525
+ this.writeDeleteJournal(journal);
526
+ await log.error?.('project.delete.failed', 'Project delete transaction stopped and can be retried.', { phase: journal.failedStep, error });
527
+ if (error instanceof DomainError) throw error;
528
+ throw new DomainError('MIGRATION_FAILED', 'Project delete transaction failed and can be retried.', { status: 500, operationId, retryable: true, cause: error });
529
+ }
530
+ }
531
+ }
532
+
533
+ module.exports = { ProjectLifecycleService, slugify, runGit };