@sanqianx/project-knowledge 4.7.0 → 5.0.0

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