@sanqianx/project-knowledge 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plugins/marketplace.json +20 -0
- package/.claude-plugin/marketplace.json +17 -0
- package/CHANGELOG.md +780 -0
- package/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +266 -0
- package/_site/README.md +30 -0
- package/_site/_test/ai-profile-resolver-test.js +137 -0
- package/_site/_test/ai-profile-test.js +75 -0
- package/_site/_test/ai-vendor-presets-test.js +91 -0
- package/_site/_test/automation-queue-test.js +14 -0
- package/_site/_test/automation-ui-test.js +40 -0
- package/_site/_test/background-task-registry-test.js +43 -0
- package/_site/_test/baseline-schema-test.js +91 -0
- package/_site/_test/bin-cli-test.js +218 -0
- package/_site/_test/bridge-adapter-test.js +95 -0
- package/_site/_test/bridge-consumer-service-test.js +310 -0
- package/_site/_test/cdp-browser-failure-test.js +100 -0
- package/_site/_test/chat-claudecodeui-match-test.js +92 -0
- package/_site/_test/claude-executable-discovery-test.js +90 -0
- package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -0
- package/_site/_test/claude-workbench-test.js +170 -0
- package/_site/_test/client-capture-restart-e2e-test.js +189 -0
- package/_site/_test/codex-conversation-projection-test.js +59 -0
- package/_site/_test/codex-notify-fanout-test.js +45 -0
- package/_site/_test/commit-boundary-freeze-test.js +147 -0
- package/_site/_test/commit-conversation-binding-test.js +99 -0
- package/_site/_test/commit-evidence-test.js +110 -0
- package/_site/_test/context-pack-test.js +198 -0
- package/_site/_test/conversation-api-test.js +119 -0
- package/_site/_test/conversation-store-test.js +136 -0
- package/_site/_test/cross-repo-isolation-e2e-test.js +187 -0
- package/_site/_test/data-dir-migration-test.js +77 -0
- package/_site/_test/desktop-browser-compat-test.js +28 -0
- package/_site/_test/desktop-hook-runtime-regression-test.js +204 -0
- package/_site/_test/embedding-config-test.js +32 -0
- package/_site/_test/explicit-commit-processor-test.js +37 -0
- package/_site/_test/fixtures/fake-browser-exit.js +10 -0
- package/_site/_test/fixtures/fake-browser-hang.js +10 -0
- package/_site/_test/fixtures/make-git-repos.js +89 -0
- package/_site/_test/folder-picker-output-test.js +19 -0
- package/_site/_test/full-integration-e2e-test.js +165 -0
- package/_site/_test/git-validation-test.js +81 -0
- package/_site/_test/hook-runtime-endpoint-test.js +88 -0
- package/_site/_test/hook-status-repair-api-test.js +152 -0
- package/_site/_test/hook-trigger-test.js +85 -0
- package/_site/_test/hook-worktree-test.js +42 -0
- package/_site/_test/import-preflight-api-test.js +233 -0
- package/_site/_test/import-ui-flow-test.js +171 -0
- package/_site/_test/index-builder-test.js +41 -0
- package/_site/_test/index-writer-concurrency-test.js +135 -0
- package/_site/_test/integration-adapters-test.js +243 -0
- package/_site/_test/integration-capture-setup-test.js +108 -0
- package/_site/_test/integration-surface-coverage-test.js +165 -0
- package/_site/_test/kb-framework-test.js +57 -0
- package/_site/_test/kbpath-follow-test.js +63 -0
- package/_site/_test/knowledge-db-test.js +144 -0
- package/_site/_test/knowledge-language-control-test.js +170 -0
- package/_site/_test/knowledge-maintenance-test.js +40 -0
- package/_site/_test/knowledge-migration-test.js +75 -0
- package/_site/_test/knowledge-promotion-recovery-test.js +260 -0
- package/_site/_test/knowledge-query-test.js +54 -0
- package/_site/_test/knowledge-retrieval-service-test.js +77 -0
- package/_site/_test/knowledge-scopes-test.js +37 -0
- package/_site/_test/knowledge-storage-location-test.js +28 -0
- package/_site/_test/knowledge-storage-startup-test.js +52 -0
- package/_site/_test/knowledge-store-logs-supervision-test.js +89 -0
- package/_site/_test/legacy-claude-session-alias-test.js +106 -0
- package/_site/_test/legacy-forward-compat-test.js +257 -0
- package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -0
- package/_site/_test/legacy-routes-removed-test.js +47 -0
- package/_site/_test/legacy-workbench-exclusion-test.js +92 -0
- package/_site/_test/log-redaction-test.js +58 -0
- package/_site/_test/logging-api-test.js +89 -0
- package/_site/_test/logging-sse-no-gap-test.js +88 -0
- package/_site/_test/logging-ui-test.js +104 -0
- package/_site/_test/markdown-delta-overlay-test.js +85 -0
- package/_site/_test/markdown-maintenance-api-test.js +75 -0
- package/_site/_test/markdown-maintenance-test.js +11 -0
- package/_site/_test/mcp-server-test.js +149 -0
- package/_site/_test/model-context-windows-test.js +89 -0
- package/_site/_test/module-bridge-eventbridge-test.js +193 -0
- package/_site/_test/non-release-ci-test.js +34 -0
- package/_site/_test/offline-boundary-isolation-test.js +32 -0
- package/_site/_test/orphaned-claim-recovery-test.js +80 -0
- package/_site/_test/p0-data-migration-characterization-test.js +37 -0
- package/_site/_test/p0-e2e-gate-test.js +347 -0
- package/_site/_test/package-boundary-test.js +42 -0
- package/_site/_test/package-startup-test.js +56 -0
- package/_site/_test/packaged-ui-smoke-test.js +79 -0
- package/_site/_test/path-consistency-test.js +151 -0
- package/_site/_test/pending-sweep-test.js +9 -0
- package/_site/_test/post-commit-automation-test.js +87 -0
- package/_site/_test/pr-consumer-contract-test.js +55 -0
- package/_site/_test/project-control-panel-task14-test.js +63 -0
- package/_site/_test/project-delete-recovery-test.js +64 -0
- package/_site/_test/project-goal-editor-test.js +145 -0
- package/_site/_test/project-layout-v2-migration-test.js +127 -0
- package/_site/_test/project-lifecycle-transaction-test.js +106 -0
- package/_site/_test/project-remove-running-guard-test.js +79 -0
- package/_site/_test/project-store-test.js +90 -0
- package/_site/_test/prompt-settings-test.js +115 -0
- package/_site/_test/protected-architecture-gate-test.js +123 -0
- package/_site/_test/refactor-characterization-test.js +36 -0
- package/_site/_test/release-version-sync-test.js +98 -0
- package/_site/_test/requirement-binding-test.js +113 -0
- package/_site/_test/requirement-recorder-test.js +173 -0
- package/_site/_test/run-all-tests.js +156 -0
- package/_site/_test/runtime-endpoint-test.js +64 -0
- package/_site/_test/scanner-test.js +83 -0
- package/_site/_test/server-runtime-migration-safety-test.js +27 -0
- package/_site/_test/server-security-test.js +96 -0
- package/_site/_test/sessions-stream-test.js +92 -0
- package/_site/_test/shared-contracts-test.js +58 -0
- package/_site/_test/simple-import-test.js +97 -0
- package/_site/_test/startup-analysis-disabled-test.js +16 -0
- package/_site/_test/storage-foundation-test.js +78 -0
- package/_site/_test/structured-logger-test.js +101 -0
- package/_site/_test/task15-20-ui-flow-test.js +148 -0
- package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -0
- package/_site/_test/team-knowledge-store-test.js +131 -0
- package/_site/_test/tracking-start-test.js +143 -0
- package/_site/_test/ui-i18n-toggle-test.js +114 -0
- package/_site/_test/ui-smoke-test.js +73 -0
- package/_site/_test/v4122-upgrade-data-contract-test.js +56 -0
- package/_site/_test/workbench-permission-test.js +118 -0
- package/_site/_test/workspace-ui-contract-test.js +43 -0
- package/_site/lib/ai-profile-resolver.js +78 -0
- package/_site/lib/ai-vendor-presets.js +83 -0
- package/_site/lib/ai-workspace.js +104 -0
- package/_site/lib/atomic-file.js +204 -0
- package/_site/lib/automation-config.js +140 -0
- package/_site/lib/bridge-adapter.js +256 -0
- package/_site/lib/bridge-consumer-service.js +402 -0
- package/_site/lib/claude-cli-runner.js +1599 -0
- package/_site/lib/commit-conversation-binder.js +246 -0
- package/_site/lib/commit-processing-ledger.js +27 -0
- package/_site/lib/commit-prompt.js +202 -0
- package/_site/lib/commit-reconciler.js +444 -0
- package/_site/lib/context-pack-builder.js +299 -0
- package/_site/lib/contracts.js +279 -0
- package/_site/lib/conversation-exclusions.js +204 -0
- package/_site/lib/conversation-query-service.js +161 -0
- package/_site/lib/conversation-store.js +385 -0
- package/_site/lib/data-dir.js +81 -0
- package/_site/lib/data-state-classifier.js +40 -0
- package/_site/lib/embedding-service.js +85 -0
- package/_site/lib/evidence-bundle.js +228 -0
- package/_site/lib/folder-picker-output.js +24 -0
- package/_site/lib/git-runner.js +62 -0
- package/_site/lib/github-team-store.js +1175 -0
- package/_site/lib/hook-manager.js +202 -0
- package/_site/lib/index-builder.js +157 -0
- package/_site/lib/index-service.js +173 -0
- package/_site/lib/integration-installer.js +907 -0
- package/_site/lib/kb-framework.js +191 -0
- package/_site/lib/kb-validator.js +124 -0
- package/_site/lib/knowledge-db.js +363 -0
- package/_site/lib/knowledge-promotion.js +435 -0
- package/_site/lib/knowledge-retrieval-service.js +401 -0
- package/_site/lib/knowledge-schema.js +121 -0
- package/_site/lib/knowledge-tool-runtime.js +359 -0
- package/_site/lib/legacy-data-manifest.js +26 -0
- package/_site/lib/llm-client.js +173 -0
- package/_site/lib/markdown-knowledge-indexer.js +230 -0
- package/_site/lib/migration-service.js +442 -0
- package/_site/lib/model-context-windows.js +82 -0
- package/_site/lib/module-bridge.js +496 -0
- package/_site/lib/post-commit-automation.js +141 -0
- package/_site/lib/project-lifecycle-service.js +511 -0
- package/_site/lib/project-registry-store.js +129 -0
- package/_site/lib/project-store.js +262 -0
- package/_site/lib/prompt-registry.js +148 -0
- package/_site/lib/requirement-adapters.js +10 -0
- package/_site/lib/requirement-binder.js +112 -0
- package/_site/lib/requirement-recorder.js +278 -0
- package/_site/lib/runtime-endpoint.js +160 -0
- package/_site/lib/scanner.js +298 -0
- package/_site/lib/server-app.js +1520 -0
- package/_site/lib/settings-store.js +113 -0
- package/_site/lib/storage-layout.js +162 -0
- package/_site/lib/structured-logger.js +574 -0
- package/_site/scripts/codex-notify-fanout.cjs +51 -0
- package/_site/scripts/folder-picker.ps1 +156 -0
- package/_site/scripts/hook-trigger.js +156 -0
- package/_site/scripts/sync-release-version.js +158 -0
- package/_site/server.js +12 -0
- package/_site/start.bat +26 -0
- package/_site/stop.bat +11 -0
- package/bin/project-knowledge-integrations.js +241 -0
- package/bin/project-knowledge-kb.js +65 -0
- package/bin/project-knowledge-mcp.js +195 -0
- package/bin/project-knowledge.js +439 -0
- package/claude-prompts.json +21 -0
- package/docs/README.zh-CN.md +175 -0
- package/docs/assets/architecture.svg +182 -0
- package/docs/assets/dashboard.png +0 -0
- package/docs/assets/draft-review.png +0 -0
- package/docs/assets/logo.svg +50 -0
- package/docs/assets/runs-drafts.png +0 -0
- package/docs/assets/settings.png +0 -0
- package/docs/project-registry-schema.md +33 -0
- package/docs/team-knowledge-mode-a-plan.md +73 -0
- package/docs/testing-strategy.md +33 -0
- package/package.json +100 -0
- package/plugins/project-knowledge/.claude-plugin/plugin.json +19 -0
- package/plugins/project-knowledge/.codex-plugin/plugin.json +38 -0
- package/plugins/project-knowledge/.mcp.json +14 -0
- package/plugins/project-knowledge/opencode/project-knowledge.md +3 -0
- package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -0
- package/plugins/project-knowledge/skills/project-knowledge/agents/openai.yaml +11 -0
- package/templates/change.md +30 -0
- package/templates/project-readme.md +52 -0
- package/ui/app.css +58 -0
- package/ui/app.js +607 -0
- package/ui/favicon.svg +38 -0
- package/ui/i18n.js +146 -0
- package/ui/index.html +162 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { SCHEMAS, DomainError, validateProjectId } = require('./contracts');
|
|
4
|
+
const { StorageLayout } = require('./storage-layout');
|
|
5
|
+
const { ProjectRegistryStore } = require('./project-registry-store');
|
|
6
|
+
const { ProjectStore } = require('./project-store');
|
|
7
|
+
const { runGit } = require('./project-lifecycle-service');
|
|
8
|
+
const { CommitReconciler, reconcileProjectCommits } = require('./commit-reconciler');
|
|
9
|
+
const { validateSha } = require('./scanner');
|
|
10
|
+
const { renderCommitPrompt } = require('./commit-prompt');
|
|
11
|
+
|
|
12
|
+
function stores(deps = {}) {
|
|
13
|
+
const layout = deps.layout || new StorageLayout(deps);
|
|
14
|
+
return {
|
|
15
|
+
layout,
|
|
16
|
+
registryStore: deps.registryStore || new ProjectRegistryStore({ layout }),
|
|
17
|
+
projectStore: deps.projectStore || new ProjectStore({ layout }),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function handlePostCommitEvent(event = {}, deps = {}) {
|
|
22
|
+
if (event.schema !== SCHEMAS.hookEvent) throw new DomainError('SCHEMA_UNSUPPORTED', 'Hook event must use hook-event/v2.', { status: 409 });
|
|
23
|
+
const projectId = validateProjectId(event.projectId);
|
|
24
|
+
const commitSha = validateSha(event.head, 'Hook event head');
|
|
25
|
+
if (!event.repoRoot) throw new DomainError('INVALID_ARGUMENT', 'Hook event repoRoot is required.');
|
|
26
|
+
const resolved = stores(deps);
|
|
27
|
+
if (!resolved.registryStore.readDisplaySnapshot(projectId)) throw new DomainError('PROJECT_NOT_FOUND', 'Hook projectId is not registered.', { status: 404 });
|
|
28
|
+
const config = resolved.projectStore.readConfig(projectId);
|
|
29
|
+
const runtimeRoot = path.resolve(runGit(path.resolve(event.repoRoot), ['rev-parse', '--show-toplevel']).stdout);
|
|
30
|
+
const commonDir = path.resolve(runGit(runtimeRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir']).stdout);
|
|
31
|
+
if (config.repoIdentity && config.repoIdentity.commonDir
|
|
32
|
+
&& !resolved.layout.pathsEqual(config.repoIdentity.commonDir, commonDir)) {
|
|
33
|
+
if (fs.existsSync(config.repoPath)) {
|
|
34
|
+
throw new DomainError('PROJECT_NOT_FOUND', 'Hook Git identity does not match projectId.', { status: 404 });
|
|
35
|
+
}
|
|
36
|
+
const state = resolved.projectStore.readState(projectId);
|
|
37
|
+
const baseline = state.lastAnalyzedCommit || state.trackingStartCommit;
|
|
38
|
+
if (baseline) {
|
|
39
|
+
const reachable = runGit(runtimeRoot, ['merge-base', '--is-ancestor', baseline, commitSha], { allowFailure: true });
|
|
40
|
+
if (!reachable.ok) throw new DomainError('PROJECT_NOT_FOUND', 'Moved Hook repository does not contain the project baseline.', { status: 404 });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (!resolved.layout.pathsEqual(config.repoPath, runtimeRoot)) {
|
|
44
|
+
// Only the versioned Hook path reaches this update, after projectId and Git identity checks above.
|
|
45
|
+
await resolved.projectStore.updateConfig(projectId, { repoPath: runtimeRoot }, { allowRepoPath: true });
|
|
46
|
+
}
|
|
47
|
+
if (event.boundary && event.boundary.status === 'captured' && event.boundary.boundary) {
|
|
48
|
+
const boundary = event.boundary.boundary;
|
|
49
|
+
if (boundary.projectId !== projectId || boundary.commitSha !== commitSha) {
|
|
50
|
+
throw new DomainError('INVALID_ARGUMENT', 'Hook boundary identity does not match the Hook event.');
|
|
51
|
+
}
|
|
52
|
+
const commitExists = runGit(runtimeRoot, ['cat-file', '-e', `${boundary.commitSha}^{commit}`], { allowFailure: true });
|
|
53
|
+
if (!commitExists.ok) throw new DomainError('INVALID_ARGUMENT', 'Hook boundary commit does not exist in the repository.');
|
|
54
|
+
// Ordering (T13): the boundary was appended before the Hook notified us;
|
|
55
|
+
// drain the journal THROUGH the boundary sequence before any snapshot is
|
|
56
|
+
// bound, so every same-workspace event <= boundaryEndCursor is already in
|
|
57
|
+
// the ConversationStore (or deterministically handled) at freeze time.
|
|
58
|
+
if (deps.bridgeConsumerService && typeof deps.bridgeConsumerService.drainThrough === 'function') {
|
|
59
|
+
await deps.bridgeConsumerService.drainThrough(Number(boundary.journalSequence), 'commit-boundary');
|
|
60
|
+
}
|
|
61
|
+
if (deps.conversationStore && typeof deps.conversationStore.writeBoundary === 'function') {
|
|
62
|
+
deps.conversationStore.writeBoundary(projectId, boundary);
|
|
63
|
+
}
|
|
64
|
+
} else if (event.boundary && event.boundary.status === 'unavailable' && deps.logger && typeof deps.logger.warn === 'function') {
|
|
65
|
+
await deps.logger.warn('conversation.boundary_gap', 'Conversation boundary capture gap was reported by the Git Hook.', {
|
|
66
|
+
projectId,
|
|
67
|
+
operationId: deps.operationId || event.operationId || '',
|
|
68
|
+
commitSha: event.head || '',
|
|
69
|
+
phase: 'boundary',
|
|
70
|
+
context: {
|
|
71
|
+
gapId: event.boundary.gap && event.boundary.gap.gapId || '',
|
|
72
|
+
reason: event.boundary.gap && event.boundary.gap.reason || 'unavailable',
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const reconciler = deps.reconciler instanceof CommitReconciler ? deps.reconciler : new CommitReconciler({ ...deps, ...resolved });
|
|
77
|
+
return reconciler.processCommitEvent({ projectId, commitSha, branch: event.branch || '', operationId: deps.operationId || event.operationId || '' });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function cleanupOrphanedRuns(_projects, deps = {}) {
|
|
81
|
+
if (!deps.projectStore && !deps.registryStore && !deps.layout) {
|
|
82
|
+
return { activeClaims: 0, recoveredFromFrozenClaims: 0, legacyStoreSkipped: true };
|
|
83
|
+
}
|
|
84
|
+
const resolved = stores(deps);
|
|
85
|
+
let activeClaims = 0;
|
|
86
|
+
for (const projectId of resolved.registryStore.listIds()) {
|
|
87
|
+
if (resolved.projectStore.readState(projectId).analysis.activeClaim) activeClaims += 1;
|
|
88
|
+
}
|
|
89
|
+
return { activeClaims, recoveredFromFrozenClaims: activeClaims };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function recoverOrphanedClaims(deps = {}) {
|
|
93
|
+
const resolved = stores(deps);
|
|
94
|
+
const recovered = [];
|
|
95
|
+
for (const projectId of resolved.registryStore.listIds()) {
|
|
96
|
+
const state = resolved.projectStore.readState(projectId);
|
|
97
|
+
const orphaned = state.analysis.activeClaim;
|
|
98
|
+
if (!orphaned) continue;
|
|
99
|
+
if (orphaned.phase === 'failed' && orphaned.error && orphaned.error.code === 'ORPHANED_CLAIM') continue;
|
|
100
|
+
const recoveredAt = typeof deps.now === 'function' ? deps.now() : new Date().toISOString();
|
|
101
|
+
const error = {
|
|
102
|
+
code: 'ORPHANED_CLAIM',
|
|
103
|
+
message: 'Commit analysis was interrupted by a previous process exit.',
|
|
104
|
+
phase: String(orphaned.phase || state.analysis.status || 'unknown'),
|
|
105
|
+
retryable: false,
|
|
106
|
+
ts: recoveredAt,
|
|
107
|
+
};
|
|
108
|
+
await resolved.projectStore.updateState(projectId, draft => {
|
|
109
|
+
if (!draft.analysis.activeClaim) return;
|
|
110
|
+
draft.analysis.activeClaim.phase = 'failed';
|
|
111
|
+
draft.analysis.activeClaim.error = error;
|
|
112
|
+
draft.analysis.status = 'failed';
|
|
113
|
+
draft.analysis.lastError = error;
|
|
114
|
+
}, { expectedRevision: state.revision });
|
|
115
|
+
recovered.push({
|
|
116
|
+
projectId,
|
|
117
|
+
commitSha: String(orphaned.commitSha || ''),
|
|
118
|
+
runId: String(orphaned.runId || ''),
|
|
119
|
+
previousPhase: error.phase,
|
|
120
|
+
});
|
|
121
|
+
if (deps.logger && typeof deps.logger.warn === 'function') {
|
|
122
|
+
await deps.logger.warn('reconcile.orphaned_claim_recovered', 'An interrupted commit claim was made terminal without retrying analysis.', {
|
|
123
|
+
projectId,
|
|
124
|
+
commitSha: String(orphaned.commitSha || ''),
|
|
125
|
+
runId: String(orphaned.runId || ''),
|
|
126
|
+
phase: 'recovery',
|
|
127
|
+
context: { previousPhase: error.phase },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return recovered;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = {
|
|
135
|
+
CommitReconciler,
|
|
136
|
+
cleanupOrphanedRuns,
|
|
137
|
+
handlePostCommitEvent,
|
|
138
|
+
recoverOrphanedClaims,
|
|
139
|
+
reconcileProjectCommits,
|
|
140
|
+
renderCommitPrompt,
|
|
141
|
+
};
|
|
@@ -0,0 +1,511 @@
|
|
|
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
|
+
let repoInspection = null;
|
|
76
|
+
let plannedGitInit = false;
|
|
77
|
+
if (checks.path.ok) {
|
|
78
|
+
const inside = runGit(localPath, ['rev-parse', '--is-inside-work-tree'], { allowFailure: true });
|
|
79
|
+
const top = inside.ok ? runGit(localPath, ['rev-parse', '--show-toplevel'], { allowFailure: true }) : null;
|
|
80
|
+
// A folder merely nested below another repository is not itself an
|
|
81
|
+
// importable Git project. This matters on CI workspaces and prevents a
|
|
82
|
+
// selected plain folder from silently inheriting its parent's history.
|
|
83
|
+
const isRepoRoot = Boolean(top && top.ok && path.resolve(top.stdout) === path.resolve(localPath));
|
|
84
|
+
if (!inside.ok || !isRepoRoot) {
|
|
85
|
+
plannedGitInit = true;
|
|
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
|
+
} else {
|
|
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 };
|