@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.
Files changed (218) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +17 -0
  3. package/CHANGELOG.md +780 -0
  4. package/LICENSE +201 -0
  5. package/NOTICE +5 -0
  6. package/README.md +266 -0
  7. package/_site/README.md +30 -0
  8. package/_site/_test/ai-profile-resolver-test.js +137 -0
  9. package/_site/_test/ai-profile-test.js +75 -0
  10. package/_site/_test/ai-vendor-presets-test.js +91 -0
  11. package/_site/_test/automation-queue-test.js +14 -0
  12. package/_site/_test/automation-ui-test.js +40 -0
  13. package/_site/_test/background-task-registry-test.js +43 -0
  14. package/_site/_test/baseline-schema-test.js +91 -0
  15. package/_site/_test/bin-cli-test.js +218 -0
  16. package/_site/_test/bridge-adapter-test.js +95 -0
  17. package/_site/_test/bridge-consumer-service-test.js +310 -0
  18. package/_site/_test/cdp-browser-failure-test.js +100 -0
  19. package/_site/_test/chat-claudecodeui-match-test.js +92 -0
  20. package/_site/_test/claude-executable-discovery-test.js +90 -0
  21. package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -0
  22. package/_site/_test/claude-workbench-test.js +170 -0
  23. package/_site/_test/client-capture-restart-e2e-test.js +189 -0
  24. package/_site/_test/codex-conversation-projection-test.js +59 -0
  25. package/_site/_test/codex-notify-fanout-test.js +45 -0
  26. package/_site/_test/commit-boundary-freeze-test.js +147 -0
  27. package/_site/_test/commit-conversation-binding-test.js +99 -0
  28. package/_site/_test/commit-evidence-test.js +110 -0
  29. package/_site/_test/context-pack-test.js +198 -0
  30. package/_site/_test/conversation-api-test.js +119 -0
  31. package/_site/_test/conversation-store-test.js +136 -0
  32. package/_site/_test/cross-repo-isolation-e2e-test.js +187 -0
  33. package/_site/_test/data-dir-migration-test.js +77 -0
  34. package/_site/_test/desktop-browser-compat-test.js +28 -0
  35. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -0
  36. package/_site/_test/embedding-config-test.js +32 -0
  37. package/_site/_test/explicit-commit-processor-test.js +37 -0
  38. package/_site/_test/fixtures/fake-browser-exit.js +10 -0
  39. package/_site/_test/fixtures/fake-browser-hang.js +10 -0
  40. package/_site/_test/fixtures/make-git-repos.js +89 -0
  41. package/_site/_test/folder-picker-output-test.js +19 -0
  42. package/_site/_test/full-integration-e2e-test.js +165 -0
  43. package/_site/_test/git-validation-test.js +81 -0
  44. package/_site/_test/hook-runtime-endpoint-test.js +88 -0
  45. package/_site/_test/hook-status-repair-api-test.js +152 -0
  46. package/_site/_test/hook-trigger-test.js +85 -0
  47. package/_site/_test/hook-worktree-test.js +42 -0
  48. package/_site/_test/import-preflight-api-test.js +233 -0
  49. package/_site/_test/import-ui-flow-test.js +171 -0
  50. package/_site/_test/index-builder-test.js +41 -0
  51. package/_site/_test/index-writer-concurrency-test.js +135 -0
  52. package/_site/_test/integration-adapters-test.js +243 -0
  53. package/_site/_test/integration-capture-setup-test.js +108 -0
  54. package/_site/_test/integration-surface-coverage-test.js +165 -0
  55. package/_site/_test/kb-framework-test.js +57 -0
  56. package/_site/_test/kbpath-follow-test.js +63 -0
  57. package/_site/_test/knowledge-db-test.js +144 -0
  58. package/_site/_test/knowledge-language-control-test.js +170 -0
  59. package/_site/_test/knowledge-maintenance-test.js +40 -0
  60. package/_site/_test/knowledge-migration-test.js +75 -0
  61. package/_site/_test/knowledge-promotion-recovery-test.js +260 -0
  62. package/_site/_test/knowledge-query-test.js +54 -0
  63. package/_site/_test/knowledge-retrieval-service-test.js +77 -0
  64. package/_site/_test/knowledge-scopes-test.js +37 -0
  65. package/_site/_test/knowledge-storage-location-test.js +28 -0
  66. package/_site/_test/knowledge-storage-startup-test.js +52 -0
  67. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -0
  68. package/_site/_test/legacy-claude-session-alias-test.js +106 -0
  69. package/_site/_test/legacy-forward-compat-test.js +257 -0
  70. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -0
  71. package/_site/_test/legacy-routes-removed-test.js +47 -0
  72. package/_site/_test/legacy-workbench-exclusion-test.js +92 -0
  73. package/_site/_test/log-redaction-test.js +58 -0
  74. package/_site/_test/logging-api-test.js +89 -0
  75. package/_site/_test/logging-sse-no-gap-test.js +88 -0
  76. package/_site/_test/logging-ui-test.js +104 -0
  77. package/_site/_test/markdown-delta-overlay-test.js +85 -0
  78. package/_site/_test/markdown-maintenance-api-test.js +75 -0
  79. package/_site/_test/markdown-maintenance-test.js +11 -0
  80. package/_site/_test/mcp-server-test.js +149 -0
  81. package/_site/_test/model-context-windows-test.js +89 -0
  82. package/_site/_test/module-bridge-eventbridge-test.js +193 -0
  83. package/_site/_test/non-release-ci-test.js +34 -0
  84. package/_site/_test/offline-boundary-isolation-test.js +32 -0
  85. package/_site/_test/orphaned-claim-recovery-test.js +80 -0
  86. package/_site/_test/p0-data-migration-characterization-test.js +37 -0
  87. package/_site/_test/p0-e2e-gate-test.js +347 -0
  88. package/_site/_test/package-boundary-test.js +42 -0
  89. package/_site/_test/package-startup-test.js +56 -0
  90. package/_site/_test/packaged-ui-smoke-test.js +79 -0
  91. package/_site/_test/path-consistency-test.js +151 -0
  92. package/_site/_test/pending-sweep-test.js +9 -0
  93. package/_site/_test/post-commit-automation-test.js +87 -0
  94. package/_site/_test/pr-consumer-contract-test.js +55 -0
  95. package/_site/_test/project-control-panel-task14-test.js +63 -0
  96. package/_site/_test/project-delete-recovery-test.js +64 -0
  97. package/_site/_test/project-goal-editor-test.js +145 -0
  98. package/_site/_test/project-layout-v2-migration-test.js +127 -0
  99. package/_site/_test/project-lifecycle-transaction-test.js +106 -0
  100. package/_site/_test/project-remove-running-guard-test.js +79 -0
  101. package/_site/_test/project-store-test.js +90 -0
  102. package/_site/_test/prompt-settings-test.js +115 -0
  103. package/_site/_test/protected-architecture-gate-test.js +123 -0
  104. package/_site/_test/refactor-characterization-test.js +36 -0
  105. package/_site/_test/release-version-sync-test.js +98 -0
  106. package/_site/_test/requirement-binding-test.js +113 -0
  107. package/_site/_test/requirement-recorder-test.js +173 -0
  108. package/_site/_test/run-all-tests.js +156 -0
  109. package/_site/_test/runtime-endpoint-test.js +64 -0
  110. package/_site/_test/scanner-test.js +83 -0
  111. package/_site/_test/server-runtime-migration-safety-test.js +27 -0
  112. package/_site/_test/server-security-test.js +96 -0
  113. package/_site/_test/sessions-stream-test.js +92 -0
  114. package/_site/_test/shared-contracts-test.js +58 -0
  115. package/_site/_test/simple-import-test.js +97 -0
  116. package/_site/_test/startup-analysis-disabled-test.js +16 -0
  117. package/_site/_test/storage-foundation-test.js +78 -0
  118. package/_site/_test/structured-logger-test.js +101 -0
  119. package/_site/_test/task15-20-ui-flow-test.js +148 -0
  120. package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -0
  121. package/_site/_test/team-knowledge-store-test.js +131 -0
  122. package/_site/_test/tracking-start-test.js +143 -0
  123. package/_site/_test/ui-i18n-toggle-test.js +114 -0
  124. package/_site/_test/ui-smoke-test.js +73 -0
  125. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -0
  126. package/_site/_test/workbench-permission-test.js +118 -0
  127. package/_site/_test/workspace-ui-contract-test.js +43 -0
  128. package/_site/lib/ai-profile-resolver.js +78 -0
  129. package/_site/lib/ai-vendor-presets.js +83 -0
  130. package/_site/lib/ai-workspace.js +104 -0
  131. package/_site/lib/atomic-file.js +204 -0
  132. package/_site/lib/automation-config.js +140 -0
  133. package/_site/lib/bridge-adapter.js +256 -0
  134. package/_site/lib/bridge-consumer-service.js +402 -0
  135. package/_site/lib/claude-cli-runner.js +1599 -0
  136. package/_site/lib/commit-conversation-binder.js +246 -0
  137. package/_site/lib/commit-processing-ledger.js +27 -0
  138. package/_site/lib/commit-prompt.js +202 -0
  139. package/_site/lib/commit-reconciler.js +444 -0
  140. package/_site/lib/context-pack-builder.js +299 -0
  141. package/_site/lib/contracts.js +279 -0
  142. package/_site/lib/conversation-exclusions.js +204 -0
  143. package/_site/lib/conversation-query-service.js +161 -0
  144. package/_site/lib/conversation-store.js +385 -0
  145. package/_site/lib/data-dir.js +81 -0
  146. package/_site/lib/data-state-classifier.js +40 -0
  147. package/_site/lib/embedding-service.js +85 -0
  148. package/_site/lib/evidence-bundle.js +228 -0
  149. package/_site/lib/folder-picker-output.js +24 -0
  150. package/_site/lib/git-runner.js +62 -0
  151. package/_site/lib/github-team-store.js +1175 -0
  152. package/_site/lib/hook-manager.js +202 -0
  153. package/_site/lib/index-builder.js +157 -0
  154. package/_site/lib/index-service.js +173 -0
  155. package/_site/lib/integration-installer.js +907 -0
  156. package/_site/lib/kb-framework.js +191 -0
  157. package/_site/lib/kb-validator.js +124 -0
  158. package/_site/lib/knowledge-db.js +363 -0
  159. package/_site/lib/knowledge-promotion.js +435 -0
  160. package/_site/lib/knowledge-retrieval-service.js +401 -0
  161. package/_site/lib/knowledge-schema.js +121 -0
  162. package/_site/lib/knowledge-tool-runtime.js +359 -0
  163. package/_site/lib/legacy-data-manifest.js +26 -0
  164. package/_site/lib/llm-client.js +173 -0
  165. package/_site/lib/markdown-knowledge-indexer.js +230 -0
  166. package/_site/lib/migration-service.js +442 -0
  167. package/_site/lib/model-context-windows.js +82 -0
  168. package/_site/lib/module-bridge.js +496 -0
  169. package/_site/lib/post-commit-automation.js +141 -0
  170. package/_site/lib/project-lifecycle-service.js +511 -0
  171. package/_site/lib/project-registry-store.js +129 -0
  172. package/_site/lib/project-store.js +262 -0
  173. package/_site/lib/prompt-registry.js +148 -0
  174. package/_site/lib/requirement-adapters.js +10 -0
  175. package/_site/lib/requirement-binder.js +112 -0
  176. package/_site/lib/requirement-recorder.js +278 -0
  177. package/_site/lib/runtime-endpoint.js +160 -0
  178. package/_site/lib/scanner.js +298 -0
  179. package/_site/lib/server-app.js +1520 -0
  180. package/_site/lib/settings-store.js +113 -0
  181. package/_site/lib/storage-layout.js +162 -0
  182. package/_site/lib/structured-logger.js +574 -0
  183. package/_site/scripts/codex-notify-fanout.cjs +51 -0
  184. package/_site/scripts/folder-picker.ps1 +156 -0
  185. package/_site/scripts/hook-trigger.js +156 -0
  186. package/_site/scripts/sync-release-version.js +158 -0
  187. package/_site/server.js +12 -0
  188. package/_site/start.bat +26 -0
  189. package/_site/stop.bat +11 -0
  190. package/bin/project-knowledge-integrations.js +241 -0
  191. package/bin/project-knowledge-kb.js +65 -0
  192. package/bin/project-knowledge-mcp.js +195 -0
  193. package/bin/project-knowledge.js +439 -0
  194. package/claude-prompts.json +21 -0
  195. package/docs/README.zh-CN.md +175 -0
  196. package/docs/assets/architecture.svg +182 -0
  197. package/docs/assets/dashboard.png +0 -0
  198. package/docs/assets/draft-review.png +0 -0
  199. package/docs/assets/logo.svg +50 -0
  200. package/docs/assets/runs-drafts.png +0 -0
  201. package/docs/assets/settings.png +0 -0
  202. package/docs/project-registry-schema.md +33 -0
  203. package/docs/team-knowledge-mode-a-plan.md +73 -0
  204. package/docs/testing-strategy.md +33 -0
  205. package/package.json +100 -0
  206. package/plugins/project-knowledge/.claude-plugin/plugin.json +19 -0
  207. package/plugins/project-knowledge/.codex-plugin/plugin.json +38 -0
  208. package/plugins/project-knowledge/.mcp.json +14 -0
  209. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -0
  210. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -0
  211. package/plugins/project-knowledge/skills/project-knowledge/agents/openai.yaml +11 -0
  212. package/templates/change.md +30 -0
  213. package/templates/project-readme.md +52 -0
  214. package/ui/app.css +58 -0
  215. package/ui/app.js +607 -0
  216. package/ui/favicon.svg +38 -0
  217. package/ui/i18n.js +146 -0
  218. package/ui/index.html +162 -0
@@ -0,0 +1,104 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getDataDir } = require('./data-dir');
4
+
5
+ const APP_ROOT = getDataDir();
6
+ const SITE_ROOT = path.resolve(__dirname, '..');
7
+ const AI_ROOT = path.join(APP_ROOT, '_ai');
8
+ const STANDARD_SUBDIRS = ['runs', 'context-packs', 'backups', 'claude-workbench'];
9
+
10
+ function safeSlug(slug) {
11
+ return typeof slug === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(slug);
12
+ }
13
+
14
+ function projectAIPath(slug) {
15
+ if (!safeSlug(slug)) throw new Error(`invalid slug for AI workspace: ${slug}`);
16
+ return path.join(AI_ROOT, slug);
17
+ }
18
+
19
+ function ensureProjectAIPath(slug) {
20
+ const root = projectAIPath(slug);
21
+ for (const sub of STANDARD_SUBDIRS) {
22
+ fs.mkdirSync(path.join(root, sub), { recursive: true });
23
+ }
24
+ return root;
25
+ }
26
+
27
+ function legacyAIPath(kbPath) {
28
+ return path.join(kbPath, '_ai');
29
+ }
30
+
31
+ function copyDir(src, dest) {
32
+ fs.mkdirSync(dest, { recursive: true });
33
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
34
+ const from = path.join(src, entry.name);
35
+ const to = path.join(dest, entry.name);
36
+ if (entry.isDirectory()) copyDir(from, to);
37
+ else if (entry.isFile()) fs.copyFileSync(from, to);
38
+ }
39
+ }
40
+
41
+ function migrateAIWorkspace({ slug, kbPath, preserveOriginal = true }) {
42
+ const legacy = legacyAIPath(kbPath);
43
+ const target = ensureProjectAIPath(slug);
44
+ const result = {
45
+ ok: true,
46
+ slug,
47
+ legacyPath: legacy,
48
+ targetPath: target,
49
+ copied: false,
50
+ preservedOriginal: preserveOriginal,
51
+ };
52
+ if (!fs.existsSync(legacy)) return result;
53
+ copyDir(legacy, target);
54
+ result.copied = true;
55
+ if (!preserveOriginal) {
56
+ fs.rmSync(legacy, { recursive: true, force: true });
57
+ result.preservedOriginal = false;
58
+ }
59
+ return result;
60
+ }
61
+
62
+ function runPath(slug, runId) {
63
+ return path.join(projectAIPath(slug), 'runs', `${runId}.json`);
64
+ }
65
+
66
+ function contextPackDir(slug, runId) {
67
+ return path.join(projectAIPath(slug), 'context-packs', runId);
68
+ }
69
+
70
+ function findExistingRunPath({ slug, kbPath, runId }) {
71
+ const primary = path.join(projectAIPath(slug), 'runs', `${runId}.json`);
72
+ return primary;
73
+ }
74
+
75
+ function listProjectDirs(projectSlug = null, projects = null) {
76
+ if (projectSlug) return [projectAIPath(projectSlug)];
77
+ const dirs = [];
78
+ if (fs.existsSync(AI_ROOT)) {
79
+ for (const entry of fs.readdirSync(AI_ROOT, { withFileTypes: true })) {
80
+ if (entry.isDirectory() && safeSlug(entry.name)) dirs.push(path.join(AI_ROOT, entry.name));
81
+ }
82
+ }
83
+ if (projects) {
84
+ for (const [slug] of Object.entries(projects)) {
85
+ if (safeSlug(slug)) dirs.push(projectAIPath(slug));
86
+ }
87
+ }
88
+ return [...new Set(dirs.map(d => path.resolve(d)))];
89
+ }
90
+
91
+ module.exports = {
92
+ APP_ROOT,
93
+ SITE_ROOT,
94
+ AI_ROOT,
95
+ STANDARD_SUBDIRS,
96
+ projectAIPath,
97
+ ensureProjectAIPath,
98
+ legacyAIPath,
99
+ migrateAIWorkspace,
100
+ runPath,
101
+ contextPackDir,
102
+ findExistingRunPath,
103
+ listProjectDirs,
104
+ };
@@ -0,0 +1,204 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { DomainError } = require('./contracts');
5
+
6
+ const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
7
+ const DEFAULT_STALE_LOCK_MS = 120_000;
8
+
9
+ function delay(ms) {
10
+ return new Promise(resolve => setTimeout(resolve, ms));
11
+ }
12
+
13
+ function isProcessAlive(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ } catch (error) {
19
+ return error && error.code === 'EPERM';
20
+ }
21
+ }
22
+
23
+ function readLockOwner(lockPath) {
24
+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch { return null; }
25
+ }
26
+
27
+ function canBreakStaleLock(lockPath, staleMs) {
28
+ let stat;
29
+ try { stat = fs.statSync(lockPath); } catch { return false; }
30
+ const owner = readLockOwner(lockPath);
31
+ // A complete owner record lets us recover immediately after a process
32
+ // crash. The age threshold is only needed for an incomplete/unreadable
33
+ // file that another process may still be creating.
34
+ if (owner && Number.isInteger(Number(owner.pid))) return !isProcessAlive(Number(owner.pid));
35
+ return (Date.now() - stat.mtimeMs) >= staleMs;
36
+ }
37
+
38
+ async function acquireFileLock(lockPath, options = {}) {
39
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_LOCK_TIMEOUT_MS;
40
+ const staleMs = Number.isFinite(options.staleMs) ? options.staleMs : DEFAULT_STALE_LOCK_MS;
41
+ const retryMs = Number.isFinite(options.retryMs) ? options.retryMs : 25;
42
+ const started = Date.now();
43
+ const nonce = crypto.randomBytes(12).toString('hex');
44
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
45
+ while (true) {
46
+ try {
47
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
48
+ const owner = { pid: process.pid, startedAt: new Date().toISOString(), nonce };
49
+ fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');
50
+ fs.fsyncSync(fd);
51
+ fs.closeSync(fd);
52
+ return async function release() {
53
+ const current = readLockOwner(lockPath);
54
+ if (!current || current.nonce !== nonce) return;
55
+ try { fs.unlinkSync(lockPath); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
56
+ };
57
+ } catch (error) {
58
+ if (!error || error.code !== 'EEXIST') throw error;
59
+ if (canBreakStaleLock(lockPath, staleMs)) {
60
+ try { fs.unlinkSync(lockPath); continue; } catch (unlinkError) {
61
+ // A competing process may recover the same stale lock first; retry through the normal wait path.
62
+ }
63
+ }
64
+ if ((Date.now() - started) >= timeoutMs) {
65
+ throw new DomainError('PROJECT_BUSY', 'Timed out waiting for a file lock.', {
66
+ status: 409,
67
+ retryable: true,
68
+ details: { lockCategory: path.basename(lockPath) },
69
+ });
70
+ }
71
+ await delay(retryMs);
72
+ }
73
+ }
74
+ }
75
+
76
+ async function withFileLock(lockPath, fn, options = {}) {
77
+ const release = await acquireFileLock(lockPath, options);
78
+ try { return await fn(); } finally { await release(); }
79
+ }
80
+
81
+ function syncDirectoryBestEffort(directory) {
82
+ let fd;
83
+ try {
84
+ fd = fs.openSync(directory, 'r');
85
+ fs.fsyncSync(fd);
86
+ } catch {
87
+ // Directory fsync is unsupported on some filesystems; the file replace is already durable.
88
+ } finally {
89
+ if (fd != null) try { fs.closeSync(fd); } catch {
90
+ // Closing a best-effort directory descriptor cannot invalidate the completed file replace.
91
+ }
92
+ }
93
+ }
94
+
95
+ function replaceWithRetry(tempPath, targetPath, options = {}) {
96
+ const retries = Number.isInteger(options.renameRetries) ? options.renameRetries : 8;
97
+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));
98
+ let lastError;
99
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
100
+ try {
101
+ fs.renameSync(tempPath, targetPath);
102
+ return;
103
+ } catch (error) {
104
+ lastError = error;
105
+ if (!error || !['EPERM', 'EACCES', 'EBUSY', 'EEXIST'].includes(error.code) || attempt === retries) break;
106
+ Atomics.wait(waitBuffer, 0, 0, Math.min(250, 10 * (2 ** attempt)));
107
+ }
108
+ }
109
+ throw lastError;
110
+ }
111
+
112
+ function writeFileAtomic(filePath, content, options = {}) {
113
+ const directory = path.dirname(filePath);
114
+ fs.mkdirSync(directory, { recursive: true });
115
+ const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`);
116
+ let fd;
117
+ try {
118
+ fd = fs.openSync(tempPath, 'wx', options.mode || 0o600);
119
+ fs.writeFileSync(fd, content, options.encoding || 'utf8');
120
+ fs.fsyncSync(fd);
121
+ fs.closeSync(fd);
122
+ fd = null;
123
+ if (typeof options.beforeRename === 'function') options.beforeRename(tempPath, filePath);
124
+ replaceWithRetry(tempPath, filePath, options);
125
+ syncDirectoryBestEffort(directory);
126
+ return { path: filePath };
127
+ } catch (error) {
128
+ if (fd != null) try { fs.closeSync(fd); } catch {
129
+ // Preserve the original write error.
130
+ }
131
+ try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch {
132
+ // Preserve the original write error; stale temp files are never treated as live data.
133
+ }
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ function writeJsonAtomic(filePath, value, options = {}) {
139
+ return writeFileAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`, options);
140
+ }
141
+
142
+ function readJsonStrict(filePath, options = {}) {
143
+ let raw;
144
+ try { raw = fs.readFileSync(filePath, 'utf8'); }
145
+ catch (error) {
146
+ if (error && error.code === 'ENOENT' && options.allowMissing) return options.defaultValue;
147
+ throw error;
148
+ }
149
+ try {
150
+ const parsed = JSON.parse(raw);
151
+ if (typeof options.validate === 'function') options.validate(parsed);
152
+ return parsed;
153
+ } catch (error) {
154
+ if (error instanceof DomainError) throw error;
155
+ throw new DomainError('DATA_CORRUPT', 'A JSON data file is corrupt.', {
156
+ status: 500,
157
+ cause: error,
158
+ details: { category: options.category || 'json' },
159
+ });
160
+ }
161
+ }
162
+
163
+ async function appendJsonlLocked(filePath, value, options = {}) {
164
+ const lockPath = options.lockPath || `${filePath}.lock`;
165
+ return withFileLock(lockPath, async () => {
166
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
167
+ const fd = fs.openSync(filePath, 'a', options.mode || 0o600);
168
+ try {
169
+ fs.writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8');
170
+ fs.fsyncSync(fd);
171
+ } finally {
172
+ fs.closeSync(fd);
173
+ }
174
+ return value;
175
+ }, options);
176
+ }
177
+
178
+ function cleanupStaleTemps(directory, options = {}) {
179
+ if (!fs.existsSync(directory)) return [];
180
+ const olderThanMs = Number.isFinite(options.olderThanMs) ? options.olderThanMs : 24 * 60 * 60 * 1000;
181
+ const now = Date.now();
182
+ const removed = [];
183
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
184
+ if (!entry.isFile() || !/^\..+\.\d+\.\d+\.[a-f0-9]+\.tmp$/i.test(entry.name)) continue;
185
+ const absolute = path.join(directory, entry.name);
186
+ const stat = fs.statSync(absolute);
187
+ if ((now - stat.mtimeMs) < olderThanMs) continue;
188
+ fs.unlinkSync(absolute);
189
+ removed.push(absolute);
190
+ }
191
+ return removed;
192
+ }
193
+
194
+ module.exports = {
195
+ DEFAULT_LOCK_TIMEOUT_MS,
196
+ DEFAULT_STALE_LOCK_MS,
197
+ acquireFileLock,
198
+ withFileLock,
199
+ writeFileAtomic,
200
+ writeJsonAtomic,
201
+ readJsonStrict,
202
+ appendJsonlLocked,
203
+ cleanupStaleTemps,
204
+ };
@@ -0,0 +1,140 @@
1
+ const path = require('path');
2
+
3
+ const PERMISSION_MODES = new Set(['plan', 'default', 'acceptEdits', 'auto', 'bypassPermissions']);
4
+ const PROMPT_TEMPLATE_VERSION = 2;
5
+
6
+ const DEFAULT_COMMIT_PROMPT_TEMPLATE = `你正在根据一个 Git Commit 的冻结证据维护项目知识库。
7
+
8
+ 用户需求:
9
+ {{userRequirement}}
10
+
11
+ Commit 信息:
12
+ {{commitMetadata}}
13
+
14
+ Commit 实际变更文件:
15
+ {{actualChanges}}
16
+
17
+ Commit 实际 Patch:
18
+ {{actualPatch}}
19
+
20
+ 现有相关知识:
21
+ {{existingKnowledge}}
22
+
23
+ 请完成以下判断,并只输出符合 staging manifest 合同的知识变更:
24
+ 1. 比较用户需求与实际实现是否一致;没有可靠需求时不得猜测业务目的。
25
+ 2. 只记录 Commit、Patch 和现有知识能够证明的事实。
26
+ 3. 明确需要新增、更新或删除哪些知识;删除必须有实际变更证据。
27
+ 4. 不得修改源码、最终知识目录、其他项目或派生索引。
28
+ 5. Patch 使用 chunk evidence 时,必须从只读 manifest 按序读取所需 chunk;不得从源码工作树补读或猜测。`;
29
+
30
+ const READ_TOOLS = ['Read'];
31
+ const WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit'];
32
+
33
+ function normalizePermissionMode(value) {
34
+ return PERMISSION_MODES.has(value) ? value : 'default';
35
+ }
36
+
37
+ function normalizeAutomationConfig(input) {
38
+ const source = input && typeof input === 'object' ? input : {};
39
+ const explicit = typeof source.commitPromptTemplate === 'string' && source.commitPromptTemplate.trim();
40
+ const legacy = typeof source.hookPromptTemplate === 'string' && source.hookPromptTemplate.trim();
41
+ return {
42
+ enabled: source.enabled !== false,
43
+ commitPromptTemplate: explicit || legacy || DEFAULT_COMMIT_PROMPT_TEMPLATE,
44
+ promptTemplateVersion: PROMPT_TEMPLATE_VERSION,
45
+ legacyPromptOverride: !explicit && Boolean(legacy),
46
+ };
47
+ }
48
+
49
+ function normalizeClaudeWorkbenchConfig(input) {
50
+ const source = input && typeof input === 'object' ? input : {};
51
+ return { permissionMode: normalizePermissionMode(source.permissionMode) };
52
+ }
53
+
54
+ function renderTemplate(template, vars) {
55
+ const source = typeof template === 'string' && template.trim() ? template : DEFAULT_COMMIT_PROMPT_TEMPLATE;
56
+ const safeVars = vars && typeof vars === 'object' ? vars : {};
57
+ return source.replace(/\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g, (match, name) => {
58
+ if (!Object.prototype.hasOwnProperty.call(safeVars, name)) return match;
59
+ const value = safeVars[name];
60
+ return value == null ? '' : String(value);
61
+ });
62
+ }
63
+
64
+ function normalizePathForCompare(value) {
65
+ if (!value || typeof value !== 'string') return '';
66
+ const normalized = path.resolve(value).replace(/[\\/]+$/, '');
67
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
68
+ }
69
+
70
+ function pathsReferToSameLocation(leftValue, rightValue) {
71
+ const left = normalizePathForCompare(leftValue);
72
+ const right = normalizePathForCompare(rightValue);
73
+ return Boolean(left && right && left === right);
74
+ }
75
+
76
+ function isInsidePath(root, target) {
77
+ if (!root || !target) return false;
78
+ const rootAbs = path.resolve(root);
79
+ const targetAbs = path.resolve(rootAbs, target);
80
+ const relative = path.relative(rootAbs, targetAbs);
81
+ return relative === '' || Boolean(relative && !relative.startsWith('..') && !path.isAbsolute(relative));
82
+ }
83
+
84
+ function extractToolPaths(toolName, input) {
85
+ if (!input || typeof input !== 'object') return [];
86
+ const candidates = [];
87
+ for (const key of ['file_path', 'path', 'notebook_path']) {
88
+ if (typeof input[key] === 'string') candidates.push(input[key]);
89
+ }
90
+ if (toolName === 'MultiEdit' && typeof input.file_path === 'string') candidates.push(input.file_path);
91
+ return [...new Set(candidates)];
92
+ }
93
+
94
+ function buildAutomationToolPolicy(options = {}) {
95
+ const stagingPath = options.stagingPath || options.kbPath || '';
96
+ const evidenceRoot = options.evidenceRoot || '';
97
+ return {
98
+ kind: 'knowledge-staging',
99
+ stagingPath,
100
+ evidenceRoot,
101
+ readRoots: [evidenceRoot, stagingPath].filter(Boolean),
102
+ writeRoot: stagingPath,
103
+ allowedTools: [...READ_TOOLS, ...WRITE_TOOLS],
104
+ canWriteKb: false,
105
+ canWriteStaging: true,
106
+ allowReadOnlyBash: false,
107
+ };
108
+ }
109
+
110
+ function evaluateAutomationToolUse(policy, toolName, input) {
111
+ if (!policy || policy.kind !== 'knowledge-staging') return { behavior: 'ask', reason: 'no staging policy' };
112
+ if (!policy.allowedTools.includes(toolName)) return { behavior: 'deny', reason: `tool is not allowed: ${toolName}` };
113
+ const paths = extractToolPaths(toolName, input);
114
+ if (!paths.length) return { behavior: 'deny', reason: `${toolName} has no explicit file path` };
115
+ for (const filePath of paths) {
116
+ if (toolName === 'Read') {
117
+ if (!(policy.readRoots || []).some(root => isInsidePath(root, filePath))) {
118
+ return { behavior: 'deny', reason: `path outside read-only evidence/output roots: ${filePath}` };
119
+ }
120
+ } else if (!isInsidePath(policy.writeRoot || policy.stagingPath, filePath)) {
121
+ return { behavior: 'deny', reason: `path outside writable run output: ${filePath}` };
122
+ }
123
+ }
124
+ return { behavior: 'allow', reason: toolName === 'Read' ? 'path is inside an isolated read root' : 'path is inside the isolated writable output root' };
125
+ }
126
+
127
+ module.exports = {
128
+ PERMISSION_MODES,
129
+ PROMPT_TEMPLATE_VERSION,
130
+ DEFAULT_COMMIT_PROMPT_TEMPLATE,
131
+ normalizePermissionMode,
132
+ normalizeAutomationConfig,
133
+ normalizeClaudeWorkbenchConfig,
134
+ renderTemplate,
135
+ normalizePathForCompare,
136
+ pathsReferToSameLocation,
137
+ isInsidePath,
138
+ buildAutomationToolPolicy,
139
+ evaluateAutomationToolUse,
140
+ };