@sanqianx/project-knowledge 4.7.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +836 -799
  4. package/README.md +58 -41
  5. package/_modules/knowledge-engine/README.md +91 -0
  6. package/_modules/knowledge-engine/package.json +38 -0
  7. package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
  8. package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
  9. package/_modules/knowledge-engine/src/bin.js +52 -0
  10. package/_modules/knowledge-engine/src/bridge-client.js +24 -0
  11. package/_modules/knowledge-engine/src/coordinator.js +263 -0
  12. package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
  13. package/_modules/knowledge-engine/src/memories.js +85 -0
  14. package/_modules/knowledge-engine/src/retrieval.js +116 -0
  15. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  16. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  17. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  18. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  22. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  23. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  24. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  26. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  27. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  28. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  30. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  31. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  32. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  33. package/_modules/knowledge-engine/src/server.js +154 -0
  34. package/_modules/knowledge-engine/src/store.js +236 -0
  35. package/_modules/knowledge-engine/ui/app.css +172 -0
  36. package/_modules/knowledge-engine/ui/app.js +297 -0
  37. package/_modules/knowledge-engine/ui/index.html +95 -0
  38. package/_site/README.md +30 -30
  39. package/_site/_test/ai-profile-resolver-test.js +137 -137
  40. package/_site/_test/automation-queue-test.js +14 -14
  41. package/_site/_test/automation-ui-test.js +40 -40
  42. package/_site/_test/background-task-registry-test.js +43 -43
  43. package/_site/_test/baseline-schema-test.js +91 -91
  44. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  45. package/_site/_test/claude-executable-discovery-test.js +62 -62
  46. package/_site/_test/claude-workbench-test.js +170 -170
  47. package/_site/_test/codex-conversation-projection-test.js +2 -1
  48. package/_site/_test/commit-conversation-binding-test.js +95 -95
  49. package/_site/_test/commit-evidence-test.js +110 -110
  50. package/_site/_test/conversation-api-test.js +109 -109
  51. package/_site/_test/conversation-store-test.js +136 -136
  52. package/_site/_test/desktop-browser-compat-test.js +28 -28
  53. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  54. package/_site/_test/explicit-commit-processor-test.js +37 -37
  55. package/_site/_test/fixtures/make-git-repos.js +12 -1
  56. package/_site/_test/folder-picker-output-test.js +19 -19
  57. package/_site/_test/fresh-hook-reimport-test.js +53 -0
  58. package/_site/_test/fresh-product-data-test.js +42 -0
  59. package/_site/_test/full-integration-e2e-test.js +165 -165
  60. package/_site/_test/git-validation-test.js +2 -2
  61. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  62. package/_site/_test/hook-status-repair-api-test.js +152 -152
  63. package/_site/_test/hook-trigger-test.js +85 -85
  64. package/_site/_test/import-preflight-api-test.js +234 -233
  65. package/_site/_test/index-writer-concurrency-test.js +135 -135
  66. package/_site/_test/integration-adapters-test.js +171 -171
  67. package/_site/_test/integration-surface-coverage-test.js +164 -164
  68. package/_site/_test/knowledge-language-control-test.js +170 -170
  69. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  70. package/_site/_test/knowledge-query-test.js +54 -54
  71. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  72. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  73. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  74. package/_site/_test/logging-api-test.js +89 -89
  75. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  76. package/_site/_test/logging-ui-test.js +106 -104
  77. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  78. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  79. package/_site/_test/mcp-server-test.js +149 -149
  80. package/_site/_test/module-artifact-integrity-test.js +27 -0
  81. package/_site/_test/module-boundary-test.js +30 -0
  82. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  83. package/_site/_test/module-model-configuration-test.js +44 -0
  84. package/_site/_test/module-process-lifecycle-test.js +24 -0
  85. package/_site/_test/module-stream-proxy-test.js +34 -0
  86. package/_site/_test/non-release-ci-test.js +34 -34
  87. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  88. package/_site/_test/packaged-ui-smoke-test.js +11 -9
  89. package/_site/_test/path-consistency-test.js +151 -151
  90. package/_site/_test/pending-sweep-test.js +9 -9
  91. package/_site/_test/post-commit-automation-test.js +87 -87
  92. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  93. package/_site/_test/product-import-ui-test.js +92 -0
  94. package/_site/_test/project-delete-recovery-test.js +64 -64
  95. package/_site/_test/project-goal-editor-test.js +144 -144
  96. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  97. package/_site/_test/prompt-settings-test.js +115 -115
  98. package/_site/_test/protected-architecture-gate-test.js +122 -122
  99. package/_site/_test/refactor-characterization-test.js +36 -36
  100. package/_site/_test/release-version-sync-test.js +1 -1
  101. package/_site/_test/requirement-recorder-test.js +173 -173
  102. package/_site/_test/run-all-tests.js +159 -156
  103. package/_site/_test/shared-contracts-test.js +58 -58
  104. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  105. package/_site/_test/storage-foundation-test.js +78 -78
  106. package/_site/_test/structured-logger-test.js +101 -101
  107. package/_site/_test/tracking-start-test.js +109 -108
  108. package/_site/_test/workbench-permission-test.js +117 -117
  109. package/_site/_test/workspace-ui-contract-test.js +28 -43
  110. package/_site/lib/ai-profile-resolver.js +78 -78
  111. package/_site/lib/ai-workspace.js +101 -101
  112. package/_site/lib/automation-config.js +140 -140
  113. package/_site/lib/bridge-adapter.js +1 -0
  114. package/_site/lib/bridge-consumer-service.js +402 -402
  115. package/_site/lib/claude-cli-runner.js +1510 -1510
  116. package/_site/lib/commit-conversation-binder.js +234 -234
  117. package/_site/lib/commit-processing-ledger.js +27 -27
  118. package/_site/lib/commit-prompt.js +202 -202
  119. package/_site/lib/commit-reconciler.js +406 -406
  120. package/_site/lib/contracts.js +284 -279
  121. package/_site/lib/conversation-query-service.js +144 -144
  122. package/_site/lib/conversation-store.js +385 -385
  123. package/_site/lib/data-dir.js +6 -74
  124. package/_site/lib/engine-connection.js +67 -0
  125. package/_site/lib/evidence-bundle.js +228 -228
  126. package/_site/lib/folder-picker-output.js +21 -21
  127. package/_site/lib/git-runner.js +62 -62
  128. package/_site/lib/github-team-store.js +1172 -1172
  129. package/_site/lib/hook-manager.js +203 -202
  130. package/_site/lib/index-service.js +173 -173
  131. package/_site/lib/integration-installer.js +908 -907
  132. package/_site/lib/kb-framework.js +176 -176
  133. package/_site/lib/kb-validator.js +124 -124
  134. package/_site/lib/knowledge-promotion.js +435 -435
  135. package/_site/lib/knowledge-retrieval-service.js +401 -401
  136. package/_site/lib/knowledge-tool-runtime.js +359 -359
  137. package/_site/lib/llm-client.js +161 -161
  138. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  139. package/_site/lib/module-bridge.js +191 -36
  140. package/_site/lib/post-commit-automation.js +87 -87
  141. package/_site/lib/product-data.js +24 -0
  142. package/_site/lib/project-lifecycle-service.js +535 -497
  143. package/_site/lib/project-store.js +268 -262
  144. package/_site/lib/requirement-recorder.js +278 -278
  145. package/_site/lib/runtime-endpoint.js +155 -155
  146. package/_site/lib/scanner.js +298 -298
  147. package/_site/lib/server-app.js +1579 -1520
  148. package/_site/lib/settings-store.js +133 -113
  149. package/_site/lib/storage-layout.js +162 -162
  150. package/_site/lib/structured-logger.js +574 -574
  151. package/_site/scripts/folder-picker.ps1 +156 -156
  152. package/_site/scripts/hook-trigger.js +157 -156
  153. package/_site/scripts/install-module-candidates.js +69 -0
  154. package/_site/scripts/pack-module-candidates.js +72 -0
  155. package/_site/scripts/sync-release-version.js +2 -2
  156. package/_site/scripts/vendor-modules.js +47 -0
  157. package/_site/scripts/verify-module-runtime.js +45 -0
  158. package/_site/scripts/verify-product-runtime.js +34 -0
  159. package/bin/project-knowledge-mcp.js +194 -194
  160. package/docs/README.zh-CN.md +42 -29
  161. package/docs/fresh-v5-start.md +28 -0
  162. package/docs/project-registry-schema.md +22 -22
  163. package/docs/testing-strategy.md +33 -33
  164. package/module-runtime-manifest.json +220 -0
  165. package/package.json +14 -9
  166. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  167. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  168. package/plugins/project-knowledge/.mcp.json +1 -1
  169. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  170. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  171. package/templates/project-readme.md +34 -34
  172. package/ui/favicon.svg +38 -38
  173. package/ui/index.html +52 -149
  174. package/ui/product.css +9 -0
  175. package/ui/product.js +412 -0
  176. package/vendor-manifest.json +45 -0
  177. package/_site/_test/data-dir-migration-test.js +0 -77
  178. package/_site/_test/import-ui-flow-test.js +0 -171
  179. package/_site/_test/knowledge-migration-test.js +0 -75
  180. package/_site/_test/legacy-forward-compat-test.js +0 -257
  181. package/_site/_test/legacy-project-upgrade-e2e-test.js +0 -363
  182. package/_site/_test/p0-data-migration-characterization-test.js +0 -37
  183. package/_site/_test/p0-e2e-gate-test.js +0 -347
  184. package/_site/_test/project-control-panel-task14-test.js +0 -63
  185. package/_site/_test/project-layout-v2-migration-test.js +0 -127
  186. package/_site/_test/server-runtime-migration-safety-test.js +0 -27
  187. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  188. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  189. package/_site/_test/ui-smoke-test.js +0 -73
  190. package/_site/_test/v4122-upgrade-data-contract-test.js +0 -56
  191. package/_site/lib/data-state-classifier.js +0 -40
  192. package/_site/lib/legacy-data-manifest.js +0 -26
  193. package/_site/lib/migration-service.js +0 -442
  194. package/ui/app.css +0 -58
  195. package/ui/app.js +0 -607
  196. package/ui/i18n.js +0 -146
@@ -1,204 +1,204 @@
1
- // _site/_test/desktop-hook-runtime-regression-test.js
2
- //
3
- // Characterization harness for the post-commit hook runtime contract.
4
- // The current regression (RC-01) is that buildHookBody defaults
5
- // nodeExecutable to process.execPath, which in Desktop mode points at the
6
- // Electron executable rather than a real Node binary. When Git invokes the
7
- // hook from a normal shell, the script therefore launches Electron instead
8
- // of executing hook-trigger.js.
9
- //
10
- // These tests must:
11
- // - PASS for healthy CLI installs with an explicit Node executable;
12
- // - EXPOSE the regression when the default is left to process.execPath in a
13
- // simulated Desktop environment.
14
-
15
- const assert = require('assert');
16
- const fs = require('fs');
17
- const os = require('os');
18
- const path = require('path');
19
- const { spawnSync } = require('child_process');
20
-
21
- const {
22
- buildHookBody,
23
- installHook,
24
- readHookStatus,
25
- parseManagedMarker,
26
- HOOK_MARKER,
27
- } = require('../lib/hook-manager');
28
-
29
- const ROOT = path.resolve(__dirname, '..', '..');
30
- const TRIGGER = path.join(ROOT, '_site', 'scripts', 'hook-trigger.js');
31
-
32
- function git(repo, args) {
33
- const result = spawnSync('git', ['-C', repo, ...args], {
34
- encoding: 'utf8',
35
- windowsHide: true,
36
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
37
- });
38
- if (result.status !== 0) throw new Error(result.stderr || `git ${args.join(' ')} failed: ${result.status}`);
39
- return String(result.stdout || '').trim();
40
- }
41
-
42
- function makeRepo() {
43
- const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-desktop-hook-'));
44
- git(repo, ['init', '-q', '-b', 'main']);
45
- git(repo, ['config', 'user.email', 'desktop-hook@example.local']);
46
- git(repo, ['config', 'user.name', 'Desktop Hook Test']);
47
- fs.writeFileSync(path.join(repo, 'README.md'), '# desktop hook\n');
48
- git(repo, ['add', 'README.md']);
49
- git(repo, ['commit', '-q', '-m', 'initial']);
50
- return repo;
51
- }
52
-
53
- (async () => {
54
- // ---- Case 1: explicit real Node executable must be persisted verbatim ----
55
- {
56
- const repo = makeRepo();
57
- const projectId = 'project-desktop-hook';
58
- const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
59
- const body = buildHookBody({
60
- projectId,
61
- triggerScriptPath: TRIGGER,
62
- nodeExecutable: fakeNode,
63
- });
64
- assert(body.includes(fakeNode.replace(/\\/g, '/')), 'explicit Node executable must be embedded in hook body');
65
- assert(body.includes('ELECTRON_RUN_AS_NODE=1'), 'T02 contract: hook body must prefix ELECTRON_RUN_AS_NODE=1 so Desktop packaging runs as Node');
66
- fs.rmSync(repo, { recursive: true, force: true });
67
- }
68
-
69
- // ---- Case 2: installHook must accept an explicit nodeExecutable ----
70
- {
71
- const repo = makeRepo();
72
- const projectId = 'project-desktop-hook-install';
73
- const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
74
- const installed = installHook({
75
- repoPath: repo,
76
- projectId,
77
- triggerScriptPath: TRIGGER,
78
- nodeExecutable: fakeNode,
79
- });
80
- assert.strictEqual(installed.ok, true);
81
- const hookBody = fs.readFileSync(installed.hookPath, 'utf8');
82
- assert(hookBody.includes(fakeNode.replace(/\\/g, '/')), 'installed hook body must embed the explicit Node executable');
83
- assert.strictEqual(parseManagedMarker(hookBody).projectId, projectId);
84
- fs.rmSync(repo, { recursive: true, force: true });
85
- }
86
-
87
- // ---- Case 3: CHARACTERIZATION — Desktop executable prefix ----
88
- // The Desktop backend launches the core CLI through the Electron executable
89
- // with ELECTRON_RUN_AS_NODE=1 in the backend child environment. A Git
90
- // post-commit hook does NOT inherit that env var, so the hook body must
91
- // explicitly set ELECTRON_RUN_AS_NODE=1 before invoking the executable,
92
- // even when the executable is Electron (Desktop packaging).
93
- {
94
- const fakeElectron = path.join(os.tmpdir(), `fake-electron-${process.pid}.exe`);
95
- const body = buildHookBody({
96
- projectId: 'project-desktop-hook-default',
97
- triggerScriptPath: TRIGGER,
98
- nodeExecutable: fakeElectron,
99
- });
100
- assert(body.includes('ELECTRON_RUN_AS_NODE=1'),
101
- 'T02 contract: hook body must prefix ELECTRON_RUN_AS_NODE=1 so a Desktop Electron binary executes as Node');
102
- assert(body.includes(fakeElectron.replace(/\\/g, '/')),
103
- 'hook body must embed the resolved executable verbatim');
104
- assert(typeof body === 'string' && body.length > 0, 'hook body must be non-empty');
105
- }
106
-
107
- // ---- Case 4: hook runtime contract — trigger must run even with weird paths ----
108
- // The hook body must work when the project path contains spaces. We install
109
- // into a path that includes a literal space and confirm installHook + readback
110
- // round-trip without escaping failures.
111
- {
112
- const base = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-desktop-hook-spaces-'));
113
- const repo = path.join(base, 'project with spaces');
114
- fs.mkdirSync(repo, { recursive: true });
115
- git(repo, ['init', '-q', '-b', 'main']);
116
- git(repo, ['config', 'user.email', 'spaces@example.local']);
117
- git(repo, ['config', 'user.name', 'Spaces Test']);
118
- fs.writeFileSync(path.join(repo, 'README.md'), '# spaces\n');
119
- git(repo, ['add', 'README.md']);
120
- git(repo, ['commit', '-q', '-m', 'initial']);
121
- const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
122
- const installed = installHook({
123
- repoPath: repo,
124
- projectId: 'project-spaces',
125
- triggerScriptPath: TRIGGER,
126
- nodeExecutable: fakeNode,
127
- });
128
- assert.strictEqual(installed.ok, true);
129
- const status = readHookStatus({ repoPath: repo, projectId: 'project-spaces' });
130
- assert.strictEqual(status.kbManaged, true);
131
- fs.rmSync(base, { recursive: true, force: true });
132
- }
133
-
134
- // ---- Case 5: missing required args must still produce a valid hook body ----
135
- // This guards the "fail-open" property required by I-12 (Git commit must
136
- // never fail because Project-Knowledge is unavailable).
137
- {
138
- let threw = false;
139
- try {
140
- buildHookBody({ projectId: '', triggerScriptPath: TRIGGER, nodeExecutable: process.execPath });
141
- } catch (error) { threw = true; }
142
- assert.strictEqual(threw, true, 'empty projectId must be rejected by buildHookBody');
143
- }
144
-
145
- // ---- Case 6: end-to-end execution — hook body actually runs the trigger ----
146
- // Build a tiny "trigger" that records its argv + ELECTRON_RUN_AS_NODE env
147
- // to a journal, install the hook pointing at it, then exec the installed
148
- // hook via sh and assert the journal was written. This proves the hook
149
- // body resolves the executable correctly and that ELECTRON_RUN_AS_NODE=1
150
- // is set before the trigger runs (so a Desktop Electron binary would
151
- // execute as Node instead of launching as a GUI).
152
- {
153
- const repo = makeRepo();
154
- const journal = path.join(os.tmpdir(), `pk-desktop-hook-journal-${process.pid}.json`);
155
- const triggerBody = `#!/usr/bin/env node
156
- const fs = require('fs');
157
- fs.writeFileSync(${JSON.stringify(journal)}, JSON.stringify({
158
- argv: process.argv.slice(2),
159
- electronRunAsNode: process.env.ELECTRON_RUN_AS_NODE || null,
160
- execPath: process.execPath,
161
- }, null, 2));
162
- process.exit(0);
163
- `;
164
- const fakeTrigger = path.join(os.tmpdir(), `pk-fake-trigger-${process.pid}.js`);
165
- fs.writeFileSync(fakeTrigger, triggerBody);
166
- const projectId = 'project-hook-exec';
167
- const fakeNode = process.execPath; // real Node in the test env
168
- const installed = installHook({
169
- repoPath: repo,
170
- projectId,
171
- triggerScriptPath: fakeTrigger,
172
- nodeExecutable: fakeNode,
173
- });
174
- assert.strictEqual(installed.ok, true);
175
- // Execute with Git for Windows' own POSIX shell. A bare `bash` can resolve
176
- // to WSL, which cannot consume a Windows hook path.
177
- let sh = 'sh';
178
- if (process.platform === 'win32') {
179
- const where = spawnSync('where.exe', ['git'], { encoding: 'utf8', windowsHide: true });
180
- const gitPath = String(where.stdout || '').split(/\r?\n/).find(Boolean);
181
- const candidate = gitPath && path.join(path.dirname(path.dirname(gitPath)), 'bin', 'sh.exe');
182
- sh = candidate && fs.existsSync(candidate) ? candidate : 'bash';
183
- }
184
- const result = spawnSync(sh, [installed.hookPath], {
185
- encoding: 'utf8',
186
- windowsHide: true,
187
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
188
- });
189
- assert.strictEqual(result.status, 0, `hook must exit 0 even when Project-Knowledge is unavailable; got ${result.status}\n${result.stderr || ''}`);
190
- assert(fs.existsSync(journal), 'fake trigger must be executed by the hook body');
191
- const recorded = JSON.parse(fs.readFileSync(journal, 'utf8'));
192
- assert.strictEqual(recorded.electronRunAsNode, '1', 'ELECTRON_RUN_AS_NODE=1 must be set before the trigger runs');
193
- assert(recorded.argv.includes('--project-id'), 'trigger argv must include --project-id');
194
- assert(recorded.argv.includes(projectId), 'trigger argv must include the project id');
195
- fs.rmSync(repo, { recursive: true, force: true });
196
- fs.rmSync(fakeTrigger, { force: true });
197
- fs.rmSync(journal, { force: true });
198
- }
199
-
200
- console.log('desktop-hook-runtime-regression-test PASS');
201
- })().catch(error => {
202
- console.error(error.stack || error.message);
203
- process.exit(1);
204
- });
1
+ // _site/_test/desktop-hook-runtime-regression-test.js
2
+ //
3
+ // Characterization harness for the post-commit hook runtime contract.
4
+ // The current regression (RC-01) is that buildHookBody defaults
5
+ // nodeExecutable to process.execPath, which in Desktop mode points at the
6
+ // Electron executable rather than a real Node binary. When Git invokes the
7
+ // hook from a normal shell, the script therefore launches Electron instead
8
+ // of executing hook-trigger.js.
9
+ //
10
+ // These tests must:
11
+ // - PASS for healthy CLI installs with an explicit Node executable;
12
+ // - EXPOSE the regression when the default is left to process.execPath in a
13
+ // simulated Desktop environment.
14
+
15
+ const assert = require('assert');
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+ const { spawnSync } = require('child_process');
20
+
21
+ const {
22
+ buildHookBody,
23
+ installHook,
24
+ readHookStatus,
25
+ parseManagedMarker,
26
+ HOOK_MARKER,
27
+ } = require('../lib/hook-manager');
28
+
29
+ const ROOT = path.resolve(__dirname, '..', '..');
30
+ const TRIGGER = path.join(ROOT, '_site', 'scripts', 'hook-trigger.js');
31
+
32
+ function git(repo, args) {
33
+ const result = spawnSync('git', ['-C', repo, ...args], {
34
+ encoding: 'utf8',
35
+ windowsHide: true,
36
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
37
+ });
38
+ if (result.status !== 0) throw new Error(result.stderr || `git ${args.join(' ')} failed: ${result.status}`);
39
+ return String(result.stdout || '').trim();
40
+ }
41
+
42
+ function makeRepo() {
43
+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-desktop-hook-'));
44
+ git(repo, ['init', '-q', '-b', 'main']);
45
+ git(repo, ['config', 'user.email', 'desktop-hook@example.local']);
46
+ git(repo, ['config', 'user.name', 'Desktop Hook Test']);
47
+ fs.writeFileSync(path.join(repo, 'README.md'), '# desktop hook\n');
48
+ git(repo, ['add', 'README.md']);
49
+ git(repo, ['commit', '-q', '-m', 'initial']);
50
+ return repo;
51
+ }
52
+
53
+ (async () => {
54
+ // ---- Case 1: explicit real Node executable must be persisted verbatim ----
55
+ {
56
+ const repo = makeRepo();
57
+ const projectId = 'project-desktop-hook';
58
+ const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
59
+ const body = buildHookBody({
60
+ projectId,
61
+ triggerScriptPath: TRIGGER,
62
+ nodeExecutable: fakeNode,
63
+ });
64
+ assert(body.includes(fakeNode.replace(/\\/g, '/')), 'explicit Node executable must be embedded in hook body');
65
+ assert(body.includes('ELECTRON_RUN_AS_NODE=1'), 'T02 contract: hook body must prefix ELECTRON_RUN_AS_NODE=1 so Desktop packaging runs as Node');
66
+ fs.rmSync(repo, { recursive: true, force: true });
67
+ }
68
+
69
+ // ---- Case 2: installHook must accept an explicit nodeExecutable ----
70
+ {
71
+ const repo = makeRepo();
72
+ const projectId = 'project-desktop-hook-install';
73
+ const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
74
+ const installed = installHook({
75
+ repoPath: repo,
76
+ projectId,
77
+ triggerScriptPath: TRIGGER,
78
+ nodeExecutable: fakeNode,
79
+ });
80
+ assert.strictEqual(installed.ok, true);
81
+ const hookBody = fs.readFileSync(installed.hookPath, 'utf8');
82
+ assert(hookBody.includes(fakeNode.replace(/\\/g, '/')), 'installed hook body must embed the explicit Node executable');
83
+ assert.strictEqual(parseManagedMarker(hookBody).projectId, projectId);
84
+ fs.rmSync(repo, { recursive: true, force: true });
85
+ }
86
+
87
+ // ---- Case 3: CHARACTERIZATION — Desktop executable prefix ----
88
+ // The Desktop backend launches the core CLI through the Electron executable
89
+ // with ELECTRON_RUN_AS_NODE=1 in the backend child environment. A Git
90
+ // post-commit hook does NOT inherit that env var, so the hook body must
91
+ // explicitly set ELECTRON_RUN_AS_NODE=1 before invoking the executable,
92
+ // even when the executable is Electron (Desktop packaging).
93
+ {
94
+ const fakeElectron = path.join(os.tmpdir(), `fake-electron-${process.pid}.exe`);
95
+ const body = buildHookBody({
96
+ projectId: 'project-desktop-hook-default',
97
+ triggerScriptPath: TRIGGER,
98
+ nodeExecutable: fakeElectron,
99
+ });
100
+ assert(body.includes('ELECTRON_RUN_AS_NODE=1'),
101
+ 'T02 contract: hook body must prefix ELECTRON_RUN_AS_NODE=1 so a Desktop Electron binary executes as Node');
102
+ assert(body.includes(fakeElectron.replace(/\\/g, '/')),
103
+ 'hook body must embed the resolved executable verbatim');
104
+ assert(typeof body === 'string' && body.length > 0, 'hook body must be non-empty');
105
+ }
106
+
107
+ // ---- Case 4: hook runtime contract — trigger must run even with weird paths ----
108
+ // The hook body must work when the project path contains spaces. We install
109
+ // into a path that includes a literal space and confirm installHook + readback
110
+ // round-trip without escaping failures.
111
+ {
112
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-desktop-hook-spaces-'));
113
+ const repo = path.join(base, 'project with spaces');
114
+ fs.mkdirSync(repo, { recursive: true });
115
+ git(repo, ['init', '-q', '-b', 'main']);
116
+ git(repo, ['config', 'user.email', 'spaces@example.local']);
117
+ git(repo, ['config', 'user.name', 'Spaces Test']);
118
+ fs.writeFileSync(path.join(repo, 'README.md'), '# spaces\n');
119
+ git(repo, ['add', 'README.md']);
120
+ git(repo, ['commit', '-q', '-m', 'initial']);
121
+ const fakeNode = path.join(ROOT, '_site', '_test', 'fixtures', 'fake-browser-exit.js');
122
+ const installed = installHook({
123
+ repoPath: repo,
124
+ projectId: 'project-spaces',
125
+ triggerScriptPath: TRIGGER,
126
+ nodeExecutable: fakeNode,
127
+ });
128
+ assert.strictEqual(installed.ok, true);
129
+ const status = readHookStatus({ repoPath: repo, projectId: 'project-spaces' });
130
+ assert.strictEqual(status.kbManaged, true);
131
+ fs.rmSync(base, { recursive: true, force: true });
132
+ }
133
+
134
+ // ---- Case 5: missing required args must still produce a valid hook body ----
135
+ // This guards the "fail-open" property required by I-12 (Git commit must
136
+ // never fail because Project-Knowledge is unavailable).
137
+ {
138
+ let threw = false;
139
+ try {
140
+ buildHookBody({ projectId: '', triggerScriptPath: TRIGGER, nodeExecutable: process.execPath });
141
+ } catch (error) { threw = true; }
142
+ assert.strictEqual(threw, true, 'empty projectId must be rejected by buildHookBody');
143
+ }
144
+
145
+ // ---- Case 6: end-to-end execution — hook body actually runs the trigger ----
146
+ // Build a tiny "trigger" that records its argv + ELECTRON_RUN_AS_NODE env
147
+ // to a journal, install the hook pointing at it, then exec the installed
148
+ // hook via sh and assert the journal was written. This proves the hook
149
+ // body resolves the executable correctly and that ELECTRON_RUN_AS_NODE=1
150
+ // is set before the trigger runs (so a Desktop Electron binary would
151
+ // execute as Node instead of launching as a GUI).
152
+ {
153
+ const repo = makeRepo();
154
+ const journal = path.join(os.tmpdir(), `pk-desktop-hook-journal-${process.pid}.json`);
155
+ const triggerBody = `#!/usr/bin/env node
156
+ const fs = require('fs');
157
+ fs.writeFileSync(${JSON.stringify(journal)}, JSON.stringify({
158
+ argv: process.argv.slice(2),
159
+ electronRunAsNode: process.env.ELECTRON_RUN_AS_NODE || null,
160
+ execPath: process.execPath,
161
+ }, null, 2));
162
+ process.exit(0);
163
+ `;
164
+ const fakeTrigger = path.join(os.tmpdir(), `pk-fake-trigger-${process.pid}.js`);
165
+ fs.writeFileSync(fakeTrigger, triggerBody);
166
+ const projectId = 'project-hook-exec';
167
+ const fakeNode = process.execPath; // real Node in the test env
168
+ const installed = installHook({
169
+ repoPath: repo,
170
+ projectId,
171
+ triggerScriptPath: fakeTrigger,
172
+ nodeExecutable: fakeNode,
173
+ });
174
+ assert.strictEqual(installed.ok, true);
175
+ // Execute with Git for Windows' own POSIX shell. A bare `bash` can resolve
176
+ // to WSL, which cannot consume a Windows hook path.
177
+ let sh = 'sh';
178
+ if (process.platform === 'win32') {
179
+ const where = spawnSync('where.exe', ['git'], { encoding: 'utf8', windowsHide: true });
180
+ const gitPath = String(where.stdout || '').split(/\r?\n/).find(Boolean);
181
+ const candidate = gitPath && path.join(path.dirname(path.dirname(gitPath)), 'bin', 'sh.exe');
182
+ sh = candidate && fs.existsSync(candidate) ? candidate : 'bash';
183
+ }
184
+ const result = spawnSync(sh, [installed.hookPath], {
185
+ encoding: 'utf8',
186
+ windowsHide: true,
187
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
188
+ });
189
+ assert.strictEqual(result.status, 0, `hook must exit 0 even when Project-Knowledge is unavailable; got ${result.status}\n${result.stderr || ''}`);
190
+ assert(fs.existsSync(journal), 'fake trigger must be executed by the hook body');
191
+ const recorded = JSON.parse(fs.readFileSync(journal, 'utf8'));
192
+ assert.strictEqual(recorded.electronRunAsNode, '1', 'ELECTRON_RUN_AS_NODE=1 must be set before the trigger runs');
193
+ assert(recorded.argv.includes('--project-id'), 'trigger argv must include --project-id');
194
+ assert(recorded.argv.includes(projectId), 'trigger argv must include the project id');
195
+ fs.rmSync(repo, { recursive: true, force: true });
196
+ fs.rmSync(fakeTrigger, { force: true });
197
+ fs.rmSync(journal, { force: true });
198
+ }
199
+
200
+ console.log('desktop-hook-runtime-regression-test PASS');
201
+ })().catch(error => {
202
+ console.error(error.stack || error.message);
203
+ process.exit(1);
204
+ });
@@ -1,37 +1,37 @@
1
- const assert = require('assert');
2
- const { CommitReconciler } = require('../lib/commit-reconciler');
3
-
4
- const sha = suffix => `${'a'.repeat(39)}${suffix}`;
5
- const calls = [];
6
- let active = 0;
7
- let maxActive = 0;
8
- const completed = new Set();
9
- const projectStore = { readConfig: id => ({ projectId: id, enabled: true, repoPath: 'C:/fixture', knowledgePath: 'C:/knowledge' }) };
10
- const reconciler = new CommitReconciler({ projectStore, registryStore: {}, requireAiProfile: false });
11
- reconciler.processingLedger = {
12
- read: (projectId, commitSha) => completed.has(`${projectId}:${commitSha}`) ? { status: 'completed' } : null,
13
- complete: (projectId, commitSha) => { completed.add(`${projectId}:${commitSha}`); return { status: 'completed' }; },
14
- };
15
- reconciler.processCommit = async (projectId, _trigger, _operationId, _config, _branch, commitSha) => {
16
- active += 1; maxActive = Math.max(maxActive, active); calls.push(`${projectId}:${commitSha}`);
17
- await new Promise(resolve => setTimeout(resolve, 20));
18
- active -= 1;
19
- return { ok: true, commitSha, runId: `run-${commitSha.slice(-1)}`, claimFingerprint: `fp-${commitSha.slice(-1)}` };
20
- };
21
-
22
- (async () => {
23
- const d = sha('d'); const e = sha('e'); const f = sha('f');
24
- const duplicateA = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
25
- const duplicateB = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
26
- const next = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: e, branch: 'main' });
27
- const other = reconciler.processCommitEvent({ projectId: 'project-b', commitSha: f, branch: 'main' });
28
- const [first, second, third, fourth] = await Promise.all([duplicateA, duplicateB, next, other]);
29
- assert.equal(first.status, 'completed'); assert.equal(second.status, 'completed');
30
- assert.equal(third.status, 'completed'); assert.equal(fourth.status, 'completed');
31
- assert.deepEqual(calls.filter(value => value.startsWith('project-a:')), [`project-a:${d}`, `project-a:${e}`]);
32
- assert.equal(calls.filter(value => value === `project-a:${d}`).length, 1, 'duplicate explicit Hook event must join');
33
- assert(maxActive >= 2, 'different projects may process in parallel');
34
- const repeated = await reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
35
- assert.equal(repeated.status, 'already-completed');
36
- console.log('explicit-commit-processor-test PASS');
37
- })().catch(error => { console.error(error.stack || error.message); process.exit(1); });
1
+ const assert = require('assert');
2
+ const { CommitReconciler } = require('../lib/commit-reconciler');
3
+
4
+ const sha = suffix => `${'a'.repeat(39)}${suffix}`;
5
+ const calls = [];
6
+ let active = 0;
7
+ let maxActive = 0;
8
+ const completed = new Set();
9
+ const projectStore = { readConfig: id => ({ projectId: id, enabled: true, repoPath: 'C:/fixture', knowledgePath: 'C:/knowledge' }) };
10
+ const reconciler = new CommitReconciler({ projectStore, registryStore: {}, requireAiProfile: false });
11
+ reconciler.processingLedger = {
12
+ read: (projectId, commitSha) => completed.has(`${projectId}:${commitSha}`) ? { status: 'completed' } : null,
13
+ complete: (projectId, commitSha) => { completed.add(`${projectId}:${commitSha}`); return { status: 'completed' }; },
14
+ };
15
+ reconciler.processCommit = async (projectId, _trigger, _operationId, _config, _branch, commitSha) => {
16
+ active += 1; maxActive = Math.max(maxActive, active); calls.push(`${projectId}:${commitSha}`);
17
+ await new Promise(resolve => setTimeout(resolve, 20));
18
+ active -= 1;
19
+ return { ok: true, commitSha, runId: `run-${commitSha.slice(-1)}`, claimFingerprint: `fp-${commitSha.slice(-1)}` };
20
+ };
21
+
22
+ (async () => {
23
+ const d = sha('d'); const e = sha('e'); const f = sha('f');
24
+ const duplicateA = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
25
+ const duplicateB = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
26
+ const next = reconciler.processCommitEvent({ projectId: 'project-a', commitSha: e, branch: 'main' });
27
+ const other = reconciler.processCommitEvent({ projectId: 'project-b', commitSha: f, branch: 'main' });
28
+ const [first, second, third, fourth] = await Promise.all([duplicateA, duplicateB, next, other]);
29
+ assert.equal(first.status, 'completed'); assert.equal(second.status, 'completed');
30
+ assert.equal(third.status, 'completed'); assert.equal(fourth.status, 'completed');
31
+ assert.deepEqual(calls.filter(value => value.startsWith('project-a:')), [`project-a:${d}`, `project-a:${e}`]);
32
+ assert.equal(calls.filter(value => value === `project-a:${d}`).length, 1, 'duplicate explicit Hook event must join');
33
+ assert(maxActive >= 2, 'different projects may process in parallel');
34
+ const repeated = await reconciler.processCommitEvent({ projectId: 'project-a', commitSha: d, branch: 'main' });
35
+ assert.equal(repeated.status, 'already-completed');
36
+ console.log('explicit-commit-processor-test PASS');
37
+ })().catch(error => { console.error(error.stack || error.message); process.exit(1); });
@@ -47,7 +47,18 @@ function initRepo(repoPath) {
47
47
  function makeRepo({ kind = 'one-commit' } = {}) {
48
48
  const repoPath = fs.mkdtempSync(path.join(os.tmpdir(), `kb-fixture-${kind}-${process.pid}-`));
49
49
  const commits = [];
50
- const cleanup = () => fs.rmSync(repoPath, { recursive: true, force: true });
50
+ const cleanup = () => {
51
+ if (path.dirname(repoPath) !== path.resolve(os.tmpdir()) || !path.basename(repoPath).startsWith(`kb-fixture-${kind}-${process.pid}-`)) throw new Error('Unsafe fixture cleanup');
52
+ function remove(directory) {
53
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
54
+ const file = path.join(directory, entry.name);
55
+ if (entry.isDirectory() && !entry.isSymbolicLink()) remove(file);
56
+ else { try { fs.unlinkSync(file); } catch (error) { if (error.code !== 'EPERM') throw error; fs.chmodSync(file, 0o600); fs.unlinkSync(file); } }
57
+ }
58
+ fs.rmdirSync(directory);
59
+ }
60
+ if (fs.existsSync(repoPath)) remove(repoPath);
61
+ };
51
62
 
52
63
  if (kind === 'not-git') {
53
64
  write(path.join(repoPath, 'README.md'), '# not git\n');
@@ -1,19 +1,19 @@
1
- const assert = require('assert');
2
- const { selectedDirectoryFromOutput } = require('../lib/folder-picker-output');
3
-
4
- const banner = '������µĿ�ƽ̨ PowerShell https://aka.ms/pscore6';
5
- assert.equal(selectedDirectoryFromOutput(banner, { exists: () => false }), '',
6
- 'PowerShell banner text must never be accepted as a selected folder');
7
-
8
- const folder = 'D:\\work\\project';
9
- assert.equal(selectedDirectoryFromOutput(`${banner}\r\n${folder}\r\n`, {
10
- exists: candidate => candidate === folder,
11
- stat: () => ({ isDirectory: () => true }),
12
- }), folder, 'the existing absolute directory should be selected from mixed output');
13
-
14
- assert.equal(selectedDirectoryFromOutput('relative-folder', {
15
- exists: () => true,
16
- stat: () => ({ isDirectory: () => true }),
17
- }), '', 'relative output must not be accepted');
18
-
19
- console.log('folder-picker-output-test PASS');
1
+ const assert = require('assert');
2
+ const { selectedDirectoryFromOutput } = require('../lib/folder-picker-output');
3
+
4
+ const banner = '������µĿ�ƽ̨ PowerShell https://aka.ms/pscore6';
5
+ assert.equal(selectedDirectoryFromOutput(banner, { exists: () => false }), '',
6
+ 'PowerShell banner text must never be accepted as a selected folder');
7
+
8
+ const folder = 'D:\\work\\project';
9
+ assert.equal(selectedDirectoryFromOutput(`${banner}\r\n${folder}\r\n`, {
10
+ exists: candidate => candidate === folder,
11
+ stat: () => ({ isDirectory: () => true }),
12
+ }), folder, 'the existing absolute directory should be selected from mixed output');
13
+
14
+ assert.equal(selectedDirectoryFromOutput('relative-folder', {
15
+ exists: () => true,
16
+ stat: () => ({ isDirectory: () => true }),
17
+ }), '', 'relative output must not be accepted');
18
+
19
+ console.log('folder-picker-output-test PASS');
@@ -0,0 +1,53 @@
1
+ const assert = require('assert/strict');
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const { execFileSync } = require('child_process');
6
+ const { StorageLayout } = require('../lib/storage-layout');
7
+ const { SettingsStore } = require('../lib/settings-store');
8
+ const { ProjectRegistryStore } = require('../lib/project-registry-store');
9
+ const { ProjectStore } = require('../lib/project-store');
10
+ const { ProjectLifecycleService } = require('../lib/project-lifecycle-service');
11
+ const hooks = require('../lib/hook-manager');
12
+
13
+ (async () => {
14
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-fresh-hook-'));
15
+ const layout = new StorageLayout({ dataDir: path.join(root, 'fresh') });
16
+ const settingsStore = new SettingsStore({ layout });
17
+ const registryStore = new ProjectRegistryStore({ layout });
18
+ const projectStore = new ProjectStore({ layout });
19
+ const triggerScriptPath = path.resolve(__dirname, '../scripts/hook-trigger.js');
20
+ await settingsStore.initialize({ knowledge: { rootPath: path.join(root, 'knowledge') } });
21
+ await registryStore.initialize();
22
+ const options = { layout, settingsStore, registryStore, projectStore, triggerScriptPath };
23
+ const lifecycle = new ProjectLifecycleService(options);
24
+ const repo = path.join(root, '中文 项目'); fs.mkdirSync(repo);
25
+ const git = args => execFileSync('git', args, { cwd: repo, windowsHide: true, encoding: 'utf8' }).trim();
26
+ git(['init', '-q']); git(['config', 'user.name', 'Fresh Test']); git(['config', 'user.email', 'fresh@example.invalid']);
27
+ fs.writeFileSync(path.join(repo, 'user-code.txt'), 'unchanged'); git(['add', '.']); git(['commit', '-qm', 'baseline']);
28
+ const old = hooks.installHook({ repoPath: repo, projectId: 'project-old', triggerScriptPath, dataDir: path.join(root, 'old') });
29
+ const oldBytes = fs.readFileSync(old.hookPath, 'utf8');
30
+ const input = { localPath: repo, projectId: 'project-new', storageName: 'new' };
31
+ const preflight = await lifecycle.preflightImport(input);
32
+ assert.equal(preflight.checks.hook.replacementProjectId, 'project-old');
33
+ for (const confirmation of [undefined, 'project-wrong']) {
34
+ await assert.rejects(lifecycle.importProject({ ...input, replaceManagedHookProjectId: confirmation }), { code: 'HOOK_CONFLICT' });
35
+ assert.equal(fs.readFileSync(old.hookPath, 'utf8'), oldBytes);
36
+ assert.equal(registryStore.listIds().length, 0);
37
+ }
38
+ const brokenRegistry = Object.create(registryStore);
39
+ brokenRegistry.add = async () => { throw new Error('registry write failed'); };
40
+ await assert.rejects(new ProjectLifecycleService({ ...options, registryStore: brokenRegistry }).importProject({ ...input, replaceManagedHookProjectId: 'project-old' }));
41
+ assert.equal(fs.readFileSync(old.hookPath, 'utf8'), oldBytes, 'failed import restores the old managed hook');
42
+ const result = await lifecycle.importProject({ ...input, replaceManagedHookProjectId: 'project-old' });
43
+ assert.equal(hooks.readHookStatus({ repoPath: repo }).projectId, 'project-new');
44
+ assert.equal(result.state.lastAnalyzedCommit, null);
45
+ assert.equal(result.state.trackingStartCommit, git(['rev-parse', 'HEAD']));
46
+ assert.deepEqual(fs.readdirSync(result.config.knowledgePath), []);
47
+ assert.equal(fs.readFileSync(path.join(repo, 'user-code.txt'), 'utf8'), 'unchanged');
48
+ await lifecycle.deleteProject('project-new');
49
+ const thirdParty = '#!/bin/sh\necho third-party\n'; fs.writeFileSync(old.hookPath, thirdParty);
50
+ await assert.rejects(lifecycle.importProject({ ...input, replaceManagedHookProjectId: 'project-old' }), { code: 'HOOK_CONFLICT' });
51
+ assert.equal(fs.readFileSync(old.hookPath, 'utf8'), thirdParty);
52
+ console.log('PASS explicit fresh Hook replacement, rollback, baseline, third-party protection');
53
+ })().catch(error => { console.error(error); process.exitCode = 1; });