@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.
- package/.agents/plugins/marketplace.json +17 -17
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +836 -799
- package/README.md +58 -41
- package/_modules/knowledge-engine/README.md +91 -0
- package/_modules/knowledge-engine/package.json +38 -0
- package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
- package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
- package/_modules/knowledge-engine/src/bin.js +52 -0
- package/_modules/knowledge-engine/src/bridge-client.js +24 -0
- package/_modules/knowledge-engine/src/coordinator.js +263 -0
- package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
- package/_modules/knowledge-engine/src/memories.js +85 -0
- package/_modules/knowledge-engine/src/retrieval.js +116 -0
- package/_modules/knowledge-engine/src/runtime/README.md +7 -0
- package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
- package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
- package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
- package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
- package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
- package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
- package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
- package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
- package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
- package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
- package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
- package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
- package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
- package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
- package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
- package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
- package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
- package/_modules/knowledge-engine/src/server.js +154 -0
- package/_modules/knowledge-engine/src/store.js +236 -0
- package/_modules/knowledge-engine/ui/app.css +172 -0
- package/_modules/knowledge-engine/ui/app.js +297 -0
- package/_modules/knowledge-engine/ui/index.html +95 -0
- package/_site/README.md +30 -30
- package/_site/_test/ai-profile-resolver-test.js +137 -137
- package/_site/_test/automation-queue-test.js +14 -14
- package/_site/_test/automation-ui-test.js +40 -40
- package/_site/_test/background-task-registry-test.js +43 -43
- package/_site/_test/baseline-schema-test.js +91 -91
- package/_site/_test/chat-claudecodeui-match-test.js +92 -92
- package/_site/_test/claude-executable-discovery-test.js +62 -62
- package/_site/_test/claude-workbench-test.js +170 -170
- package/_site/_test/codex-conversation-projection-test.js +2 -1
- package/_site/_test/commit-conversation-binding-test.js +95 -95
- package/_site/_test/commit-evidence-test.js +110 -110
- package/_site/_test/conversation-api-test.js +109 -109
- package/_site/_test/conversation-store-test.js +136 -136
- package/_site/_test/desktop-browser-compat-test.js +28 -28
- package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
- package/_site/_test/explicit-commit-processor-test.js +37 -37
- package/_site/_test/fixtures/make-git-repos.js +12 -1
- package/_site/_test/folder-picker-output-test.js +19 -19
- package/_site/_test/fresh-hook-reimport-test.js +53 -0
- package/_site/_test/fresh-product-data-test.js +42 -0
- package/_site/_test/full-integration-e2e-test.js +165 -165
- package/_site/_test/git-validation-test.js +2 -2
- package/_site/_test/hook-runtime-endpoint-test.js +88 -88
- package/_site/_test/hook-status-repair-api-test.js +152 -152
- package/_site/_test/hook-trigger-test.js +85 -85
- package/_site/_test/import-preflight-api-test.js +234 -233
- package/_site/_test/index-writer-concurrency-test.js +135 -135
- package/_site/_test/integration-adapters-test.js +171 -171
- package/_site/_test/integration-surface-coverage-test.js +164 -164
- package/_site/_test/knowledge-language-control-test.js +170 -170
- package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
- package/_site/_test/knowledge-query-test.js +54 -54
- package/_site/_test/knowledge-retrieval-service-test.js +77 -77
- package/_site/_test/knowledge-storage-startup-test.js +52 -52
- package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
- package/_site/_test/logging-api-test.js +89 -89
- package/_site/_test/logging-sse-no-gap-test.js +88 -88
- package/_site/_test/logging-ui-test.js +106 -104
- package/_site/_test/markdown-delta-overlay-test.js +85 -85
- package/_site/_test/markdown-maintenance-api-test.js +75 -75
- package/_site/_test/mcp-server-test.js +149 -149
- package/_site/_test/module-artifact-integrity-test.js +27 -0
- package/_site/_test/module-boundary-test.js +30 -0
- package/_site/_test/module-bridge-eventbridge-test.js +7 -0
- package/_site/_test/module-model-configuration-test.js +44 -0
- package/_site/_test/module-process-lifecycle-test.js +24 -0
- package/_site/_test/module-stream-proxy-test.js +34 -0
- package/_site/_test/non-release-ci-test.js +34 -34
- package/_site/_test/offline-boundary-isolation-test.js +32 -32
- package/_site/_test/packaged-ui-smoke-test.js +11 -9
- package/_site/_test/path-consistency-test.js +151 -151
- package/_site/_test/pending-sweep-test.js +9 -9
- package/_site/_test/post-commit-automation-test.js +87 -87
- package/_site/_test/product-diagnostics-ui-test.js +75 -0
- package/_site/_test/product-import-ui-test.js +92 -0
- package/_site/_test/project-delete-recovery-test.js +64 -64
- package/_site/_test/project-goal-editor-test.js +144 -144
- package/_site/_test/project-lifecycle-transaction-test.js +106 -106
- package/_site/_test/prompt-settings-test.js +115 -115
- package/_site/_test/protected-architecture-gate-test.js +122 -122
- package/_site/_test/refactor-characterization-test.js +36 -36
- package/_site/_test/release-version-sync-test.js +1 -1
- package/_site/_test/requirement-recorder-test.js +173 -173
- package/_site/_test/run-all-tests.js +159 -156
- package/_site/_test/shared-contracts-test.js +58 -58
- package/_site/_test/startup-analysis-disabled-test.js +10 -10
- package/_site/_test/storage-foundation-test.js +78 -78
- package/_site/_test/structured-logger-test.js +101 -101
- package/_site/_test/tracking-start-test.js +109 -108
- package/_site/_test/workbench-permission-test.js +117 -117
- package/_site/_test/workspace-ui-contract-test.js +28 -43
- package/_site/lib/ai-profile-resolver.js +78 -78
- package/_site/lib/ai-workspace.js +101 -101
- package/_site/lib/automation-config.js +140 -140
- package/_site/lib/bridge-adapter.js +1 -0
- package/_site/lib/bridge-consumer-service.js +402 -402
- package/_site/lib/claude-cli-runner.js +1510 -1510
- package/_site/lib/commit-conversation-binder.js +234 -234
- package/_site/lib/commit-processing-ledger.js +27 -27
- package/_site/lib/commit-prompt.js +202 -202
- package/_site/lib/commit-reconciler.js +406 -406
- package/_site/lib/contracts.js +284 -279
- package/_site/lib/conversation-query-service.js +144 -144
- package/_site/lib/conversation-store.js +385 -385
- package/_site/lib/data-dir.js +6 -74
- package/_site/lib/engine-connection.js +67 -0
- package/_site/lib/evidence-bundle.js +228 -228
- package/_site/lib/folder-picker-output.js +21 -21
- package/_site/lib/git-runner.js +62 -62
- package/_site/lib/github-team-store.js +1172 -1172
- package/_site/lib/hook-manager.js +203 -202
- package/_site/lib/index-service.js +173 -173
- package/_site/lib/integration-installer.js +908 -907
- package/_site/lib/kb-framework.js +176 -176
- package/_site/lib/kb-validator.js +124 -124
- package/_site/lib/knowledge-promotion.js +435 -435
- package/_site/lib/knowledge-retrieval-service.js +401 -401
- package/_site/lib/knowledge-tool-runtime.js +359 -359
- package/_site/lib/llm-client.js +161 -161
- package/_site/lib/markdown-knowledge-indexer.js +230 -230
- package/_site/lib/module-bridge.js +191 -36
- package/_site/lib/post-commit-automation.js +87 -87
- package/_site/lib/product-data.js +24 -0
- package/_site/lib/project-lifecycle-service.js +535 -497
- package/_site/lib/project-store.js +268 -262
- package/_site/lib/requirement-recorder.js +278 -278
- package/_site/lib/runtime-endpoint.js +155 -155
- package/_site/lib/scanner.js +298 -298
- package/_site/lib/server-app.js +1579 -1520
- package/_site/lib/settings-store.js +133 -113
- package/_site/lib/storage-layout.js +162 -162
- package/_site/lib/structured-logger.js +574 -574
- package/_site/scripts/folder-picker.ps1 +156 -156
- package/_site/scripts/hook-trigger.js +157 -156
- package/_site/scripts/install-module-candidates.js +69 -0
- package/_site/scripts/pack-module-candidates.js +72 -0
- package/_site/scripts/sync-release-version.js +2 -2
- package/_site/scripts/vendor-modules.js +47 -0
- package/_site/scripts/verify-module-runtime.js +45 -0
- package/_site/scripts/verify-product-runtime.js +34 -0
- package/bin/project-knowledge-mcp.js +194 -194
- package/docs/README.zh-CN.md +42 -29
- package/docs/fresh-v5-start.md +28 -0
- package/docs/project-registry-schema.md +22 -22
- package/docs/testing-strategy.md +33 -33
- package/module-runtime-manifest.json +220 -0
- package/package.json +14 -9
- package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.mcp.json +1 -1
- package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
- package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
- package/templates/project-readme.md +34 -34
- package/ui/favicon.svg +38 -38
- package/ui/index.html +52 -149
- package/ui/product.css +9 -0
- package/ui/product.js +412 -0
- package/vendor-manifest.json +45 -0
- package/_site/_test/data-dir-migration-test.js +0 -77
- package/_site/_test/import-ui-flow-test.js +0 -171
- package/_site/_test/knowledge-migration-test.js +0 -75
- package/_site/_test/legacy-forward-compat-test.js +0 -257
- package/_site/_test/legacy-project-upgrade-e2e-test.js +0 -363
- package/_site/_test/p0-data-migration-characterization-test.js +0 -37
- package/_site/_test/p0-e2e-gate-test.js +0 -347
- package/_site/_test/project-control-panel-task14-test.js +0 -63
- package/_site/_test/project-layout-v2-migration-test.js +0 -127
- package/_site/_test/server-runtime-migration-safety-test.js +0 -27
- package/_site/_test/task15-20-ui-flow-test.js +0 -148
- package/_site/_test/ui-i18n-toggle-test.js +0 -114
- package/_site/_test/ui-smoke-test.js +0 -73
- package/_site/_test/v4122-upgrade-data-contract-test.js +0 -56
- package/_site/lib/data-state-classifier.js +0 -40
- package/_site/lib/legacy-data-manifest.js +0 -26
- package/_site/lib/migration-service.js +0 -442
- package/ui/app.css +0 -58
- package/ui/app.js +0 -607
- 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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
this.
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const
|
|
396
|
-
if (
|
|
397
|
-
|
|
398
|
-
}
|
|
399
|
-
if (
|
|
400
|
-
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
this.
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
journal
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
journal.
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
journal.
|
|
502
|
-
journal.
|
|
503
|
-
this.writeDeleteJournal(journal);
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
|
|
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 };
|