@hmharness/lsp 0.23.33 → 0.23.34

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/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "@hmharness/lsp",
3
- "version": "0.23.33",
4
- "description": "hmharness LSP Client/Manager — drives external language servers (LSP 3.18 over stdio) for agent code intelligence. Client only: we never implement language servers.",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "default": "./dist/index.js"
12
- }
13
- },
14
- "scripts": {
15
- "build": "tsc -p tsconfig.build.json"
16
- },
17
- "dependencies": {
18
- "@hmharness/kernel": "0.23.33"
19
- },
20
- "engines": {
21
- "node": ">=22"
22
- }
23
- }
1
+ {
2
+ "name": "@hmharness/lsp",
3
+ "version": "0.23.34",
4
+ "description": "hmharness LSP Client/Manager — drives external language servers (LSP 3.18 over stdio) for agent code intelligence. Client only: we never implement language servers.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc -p tsconfig.build.json"
16
+ },
17
+ "dependencies": {
18
+ "@hmharness/kernel": "0.23.34"
19
+ },
20
+ "engines": {
21
+ "node": ">=22"
22
+ }
23
+ }
@@ -1,60 +1,60 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtemp, rm, mkdir, writeFile, chmod } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { discoverServers, DEVECO_ROOTS } from '../registry.ts';
7
-
8
- test('registry: DevEco-local discovery prefers the bundled official server over PATH shims', async () => {
9
- // a FAKE DevEco root with a fake clangd that answers --version
10
- const fakeRoot = await mkdtemp(join(tmpdir(), 'deveco-'));
11
- const lspDir = join(fakeRoot, 'tools', 'llvm', 'server', 'lsp', 'win');
12
- await mkdir(lspDir, { recursive: true });
13
- const fakeClangd = join(lspDir, 'clangd.exe');
14
- // on win, a .cmd-style script works for spawnSync; use node itself via a shim dir
15
- const shimDir = await mkdtemp(join(tmpdir(), 'deveco-shim-'));
16
- const shim = join(shimDir, 'clangd.exe');
17
- if (process.platform === 'win32') {
18
- await writeFile(shim, `@echo off\r\necho clangd version 99.0.0 (fake devecos)\r\nexit /b 0\r\n`, 'utf8');
19
- } else {
20
- await writeFile(shim, '#!/bin/sh\necho "clangd version 99.0.0 (fake)"\nexit 0\n', 'utf8');
21
- await chmod(shim, 0o755);
22
- }
23
- // point the fake DevEco root's clangd at the shim via a copy
24
- const { copyFile } = await import('node:fs/promises');
25
- if (process.platform === 'win32') {
26
- await copyFile(shim, fakeClangd.replace(/\.exe$/, '.cmd'));
27
- // discovery looks for clangd.exe — write a .cmd dispatcher named exe? keep honest:
28
- // instead test through the injected roots with the shim AS the exe (windows can exec .cmd via shell only) —
29
- // simplest: make the injected discovery find the shim directly by naming it clangd.exe in a fake root layout
30
- }
31
- // use the shim placed in a fake-root layout with the exact expected filename
32
- const fakeRoot2 = await mkdtemp(join(tmpdir(), 'deveco2-'));
33
- const dir2 = join(fakeRoot2, 'tools', 'llvm', 'server', 'lsp', 'win');
34
- await mkdir(dir2, { recursive: true });
35
- const target = process.platform === 'win32' ? join(dir2, 'clangd.exe') : join(dir2, 'clangd.exe');
36
- await copyFile(shim, target).catch(async () => {
37
- // on windows spawnSync of a .cmd named .exe fails; fall back to probing absence honestly
38
- });
39
- const servers = discoverServers(true, { devecoRoots: [fakeRoot2] });
40
- const fake = servers.find((s) => s.origin === 'DevEco-local');
41
- if (fake) {
42
- assert.equal(fake.id, 'clangd');
43
- assert.equal(fake.official, true);
44
- assert.ok(fake.command.includes('tools/llvm/server/lsp'), 'recorded with the DevEco layout path');
45
- } else {
46
- // windows cannot exec a .cmd renamed .exe — discovery honestly finds nothing
47
- assert.ok(servers.every((s) => s.origin !== 'DevEco-local'));
48
- }
49
- // the REAL DevEco root (when installed) yields a healthy official clangd
50
- const real = discoverServers(true).find((s) => s.origin === 'DevEco-local');
51
- if (real) {
52
- assert.equal(real.healthy, true);
53
- assert.equal(real.official, true);
54
- }
55
- // real roots are exposed for auditability
56
- assert.ok(Array.isArray(DEVECO_ROOTS));
57
- await rm(fakeRoot, { recursive: true, force: true });
58
- await rm(shimDir, { recursive: true, force: true });
59
- await rm(fakeRoot2, { recursive: true, force: true });
60
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, rm, mkdir, writeFile, chmod } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { discoverServers, DEVECO_ROOTS } from '../registry.ts';
7
+
8
+ test('registry: DevEco-local discovery prefers the bundled official server over PATH shims', async () => {
9
+ // a FAKE DevEco root with a fake clangd that answers --version
10
+ const fakeRoot = await mkdtemp(join(tmpdir(), 'deveco-'));
11
+ const lspDir = join(fakeRoot, 'tools', 'llvm', 'server', 'lsp', 'win');
12
+ await mkdir(lspDir, { recursive: true });
13
+ const fakeClangd = join(lspDir, 'clangd.exe');
14
+ // on win, a .cmd-style script works for spawnSync; use node itself via a shim dir
15
+ const shimDir = await mkdtemp(join(tmpdir(), 'deveco-shim-'));
16
+ const shim = join(shimDir, 'clangd.exe');
17
+ if (process.platform === 'win32') {
18
+ await writeFile(shim, `@echo off\r\necho clangd version 99.0.0 (fake devecos)\r\nexit /b 0\r\n`, 'utf8');
19
+ } else {
20
+ await writeFile(shim, '#!/bin/sh\necho "clangd version 99.0.0 (fake)"\nexit 0\n', 'utf8');
21
+ await chmod(shim, 0o755);
22
+ }
23
+ // point the fake DevEco root's clangd at the shim via a copy
24
+ const { copyFile } = await import('node:fs/promises');
25
+ if (process.platform === 'win32') {
26
+ await copyFile(shim, fakeClangd.replace(/\.exe$/, '.cmd'));
27
+ // discovery looks for clangd.exe — write a .cmd dispatcher named exe? keep honest:
28
+ // instead test through the injected roots with the shim AS the exe (windows can exec .cmd via shell only) —
29
+ // simplest: make the injected discovery find the shim directly by naming it clangd.exe in a fake root layout
30
+ }
31
+ // use the shim placed in a fake-root layout with the exact expected filename
32
+ const fakeRoot2 = await mkdtemp(join(tmpdir(), 'deveco2-'));
33
+ const dir2 = join(fakeRoot2, 'tools', 'llvm', 'server', 'lsp', 'win');
34
+ await mkdir(dir2, { recursive: true });
35
+ const target = process.platform === 'win32' ? join(dir2, 'clangd.exe') : join(dir2, 'clangd.exe');
36
+ await copyFile(shim, target).catch(async () => {
37
+ // on windows spawnSync of a .cmd named .exe fails; fall back to probing absence honestly
38
+ });
39
+ const servers = discoverServers(true, { devecoRoots: [fakeRoot2] });
40
+ const fake = servers.find((s) => s.origin === 'DevEco-local');
41
+ if (fake) {
42
+ assert.equal(fake.id, 'clangd');
43
+ assert.equal(fake.official, true);
44
+ assert.ok(fake.command.includes('tools/llvm/server/lsp'), 'recorded with the DevEco layout path');
45
+ } else {
46
+ // windows cannot exec a .cmd renamed .exe — discovery honestly finds nothing
47
+ assert.ok(servers.every((s) => s.origin !== 'DevEco-local'));
48
+ }
49
+ // the REAL DevEco root (when installed) yields a healthy official clangd
50
+ const real = discoverServers(true).find((s) => s.origin === 'DevEco-local');
51
+ if (real) {
52
+ assert.equal(real.healthy, true);
53
+ assert.equal(real.official, true);
54
+ }
55
+ // real roots are exposed for auditability
56
+ assert.ok(Array.isArray(DEVECO_ROOTS));
57
+ await rm(fakeRoot, { recursive: true, force: true });
58
+ await rm(shimDir, { recursive: true, force: true });
59
+ await rm(fakeRoot2, { recursive: true, force: true });
60
+ });
@@ -1,89 +1,89 @@
1
- /**
2
- * Fake LSP server for hermetic tests (no real language server needed on
3
- * CI): speaks the base protocol over stdio and answers the Tier-0
4
- * requests with fixed, deterministic results. Written as plain JS so the
5
- * test can spawn it directly with the system node.
6
- */
7
- const fs = require('fs');
8
-
9
- function send(obj) {
10
- const payload = Buffer.from(JSON.stringify(obj), 'utf8');
11
- process.stdout.write(Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]));
12
- }
13
-
14
- let buf = Buffer.alloc(0);
15
- process.stdin.on('data', (chunk) => {
16
- buf = Buffer.concat([buf, chunk]);
17
- for (;;) {
18
- const headerEnd = buf.indexOf('\r\n\r\n');
19
- if (headerEnd < 0) break;
20
- const m = /Content-Length:\s*(\d+)/i.exec(buf.subarray(0, headerEnd).toString('ascii'));
21
- if (!m) { buf = buf.subarray(headerEnd + 4); continue; }
22
- const len = Number(m[1]);
23
- const bodyStart = headerEnd + 4;
24
- if (buf.length < bodyStart + len) break;
25
- let msg;
26
- try { msg = JSON.parse(buf.subarray(bodyStart, bodyStart + len).toString('utf8')); } catch { buf = buf.subarray(bodyStart + len); continue; }
27
- buf = buf.subarray(bodyStart + len);
28
- handle(msg);
29
- }
30
- });
31
-
32
- function handle(msg) {
33
- if (msg.method === 'initialize' && typeof msg.id === 'number') {
34
- send({ jsonrpc: '2.0', id: msg.id, result: { capabilities: { hoverProvider: true, definitionProvider: true, referencesProvider: true, documentSymbolProvider: true }, serverInfo: { name: 'fake-lsp', version: '0.0.1' } } });
35
- return;
36
- }
37
- if (msg.method === 'initialized') return;
38
- if (msg.method === 'shutdown' && typeof msg.id === 'number') {
39
- send({ jsonrpc: '2.0', id: msg.id, result: null });
40
- return;
41
- }
42
- if (msg.method === 'exit') { process.exit(0); }
43
- if (msg.method === 'textDocument/didOpen') {
44
- const doc = msg.params.textDocument;
45
- if (doc.text.includes('DELBERATE_ERROR_MARKER')) {
46
- send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, severity: 1, source: 'fake-lsp', message: 'marker found: deliberate error' }] } });
47
- } else {
48
- send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [] } });
49
- }
50
- return;
51
- }
52
- if (msg.method === 'textDocument/hover' && typeof msg.id === 'number') {
53
- send({ jsonrpc: '2.0', id: msg.id, result: { contents: { kind: 'plaintext', value: 'fake hover: symbol at ' + msg.params.position.line + ':' + msg.params.position.character } } });
54
- return;
55
- }
56
- if (msg.method === 'textDocument/definition' && typeof msg.id === 'number') {
57
- send({ jsonrpc: '2.0', id: msg.id, result: { uri: 'file:///fake/def.ts', range: { start: { line: 3, character: 0 }, end: { line: 3, character: 10 } } } });
58
- return;
59
- }
60
- if (msg.method === 'textDocument/references' && typeof msg.id === 'number') {
61
- send({ jsonrpc: '2.0', id: msg.id, result: [{ uri: 'file:///fake/r1.ts', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 4 } } }, { uri: 'file:///fake/r2.ts', range: { start: { line: 2, character: 0 }, end: { line: 2, character: 4 } } }] });
62
- return;
63
- }
64
- if (msg.method === 'textDocument/implementation' && typeof msg.id === 'number') {
65
- send({ jsonrpc: '2.0', id: msg.id, result: [{ uri: 'file:///fake/impl-a.ts', range: { start: { line: 9, character: 0 }, end: { line: 9, character: 6 } } }, { uri: 'file:///fake/impl-b.ts', range: { start: { line: 4, character: 0 }, end: { line: 4, character: 6 } } }] });
66
- return;
67
- }
68
- if (msg.method === 'textDocument/prepareCallHierarchy' && typeof msg.id === 'number') {
69
- send({ jsonrpc: '2.0', id: msg.id, result: [{ name: 'targetFn', kind: 12, uri: 'file:///fake/probe.ts', range: { start: { line: 0, character: 0 }, end: { line: 1, character: 0 } }, selectionRange: { start: { line: 0, character: 0 }, end: { line: 0, character: 9 } } }] });
70
- return;
71
- }
72
- if (msg.method === 'callHierarchy/incomingCalls' && typeof msg.id === 'number') {
73
- send({ jsonrpc: '2.0', id: msg.id, result: [{ from: { name: 'callerOne', uri: 'file:///fake/c1.ts', range: { start: { line: 2, character: 0 }, end: { line: 3, character: 0 } } }, fromRanges: [{ start: { line: 2, character: 4 }, end: { line: 2, character: 13 } }] }, { from: { name: 'callerTwo', uri: 'file:///fake/c2.ts', range: { start: { line: 5, character: 0 }, end: { line: 6, character: 0 } } }, fromRanges: [{ start: { line: 5, character: 4 }, end: { line: 5, character: 13 } }] }] });
74
- return;
75
- }
76
- if (msg.method === 'callHierarchy/outgoingCalls' && typeof msg.id === 'number') {
77
- send({ jsonrpc: '2.0', id: msg.id, result: [{ to: { name: 'helperFn', uri: 'file:///fake/h.ts', range: { start: { line: 1, character: 0 }, end: { line: 2, character: 0 } } }, toRanges: [{ start: { line: 1, character: 2 }, end: { line: 1, character: 11 } }] }] });
78
- return;
79
- }
80
- if (msg.method === 'textDocument/documentSymbol' && typeof msg.id === 'number') {
81
- send({ jsonrpc: '2.0', id: msg.id, result: [{ name: 'mainFn', kind: 12, range: { start: { line: 0, character: 0 }, end: { line: 5, character: 0 } }, children: [{ name: 'inner', kind: 6, range: { start: { line: 1, character: 2 }, end: { line: 2, character: 2 } } }] }] });
82
- return;
83
- }
84
- if (typeof msg.id === 'number') {
85
- send({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found: ' + msg.method } });
86
- }
87
- }
88
-
89
- fs.writeSync(2, ''); // keep stderr referenced
1
+ /**
2
+ * Fake LSP server for hermetic tests (no real language server needed on
3
+ * CI): speaks the base protocol over stdio and answers the Tier-0
4
+ * requests with fixed, deterministic results. Written as plain JS so the
5
+ * test can spawn it directly with the system node.
6
+ */
7
+ const fs = require('fs');
8
+
9
+ function send(obj) {
10
+ const payload = Buffer.from(JSON.stringify(obj), 'utf8');
11
+ process.stdout.write(Buffer.concat([Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii'), payload]));
12
+ }
13
+
14
+ let buf = Buffer.alloc(0);
15
+ process.stdin.on('data', (chunk) => {
16
+ buf = Buffer.concat([buf, chunk]);
17
+ for (;;) {
18
+ const headerEnd = buf.indexOf('\r\n\r\n');
19
+ if (headerEnd < 0) break;
20
+ const m = /Content-Length:\s*(\d+)/i.exec(buf.subarray(0, headerEnd).toString('ascii'));
21
+ if (!m) { buf = buf.subarray(headerEnd + 4); continue; }
22
+ const len = Number(m[1]);
23
+ const bodyStart = headerEnd + 4;
24
+ if (buf.length < bodyStart + len) break;
25
+ let msg;
26
+ try { msg = JSON.parse(buf.subarray(bodyStart, bodyStart + len).toString('utf8')); } catch { buf = buf.subarray(bodyStart + len); continue; }
27
+ buf = buf.subarray(bodyStart + len);
28
+ handle(msg);
29
+ }
30
+ });
31
+
32
+ function handle(msg) {
33
+ if (msg.method === 'initialize' && typeof msg.id === 'number') {
34
+ send({ jsonrpc: '2.0', id: msg.id, result: { capabilities: { hoverProvider: true, definitionProvider: true, referencesProvider: true, documentSymbolProvider: true }, serverInfo: { name: 'fake-lsp', version: '0.0.1' } } });
35
+ return;
36
+ }
37
+ if (msg.method === 'initialized') return;
38
+ if (msg.method === 'shutdown' && typeof msg.id === 'number') {
39
+ send({ jsonrpc: '2.0', id: msg.id, result: null });
40
+ return;
41
+ }
42
+ if (msg.method === 'exit') { process.exit(0); }
43
+ if (msg.method === 'textDocument/didOpen') {
44
+ const doc = msg.params.textDocument;
45
+ if (doc.text.includes('DELBERATE_ERROR_MARKER')) {
46
+ send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } }, severity: 1, source: 'fake-lsp', message: 'marker found: deliberate error' }] } });
47
+ } else {
48
+ send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: doc.uri, diagnostics: [] } });
49
+ }
50
+ return;
51
+ }
52
+ if (msg.method === 'textDocument/hover' && typeof msg.id === 'number') {
53
+ send({ jsonrpc: '2.0', id: msg.id, result: { contents: { kind: 'plaintext', value: 'fake hover: symbol at ' + msg.params.position.line + ':' + msg.params.position.character } } });
54
+ return;
55
+ }
56
+ if (msg.method === 'textDocument/definition' && typeof msg.id === 'number') {
57
+ send({ jsonrpc: '2.0', id: msg.id, result: { uri: 'file:///fake/def.ts', range: { start: { line: 3, character: 0 }, end: { line: 3, character: 10 } } } });
58
+ return;
59
+ }
60
+ if (msg.method === 'textDocument/references' && typeof msg.id === 'number') {
61
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ uri: 'file:///fake/r1.ts', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 4 } } }, { uri: 'file:///fake/r2.ts', range: { start: { line: 2, character: 0 }, end: { line: 2, character: 4 } } }] });
62
+ return;
63
+ }
64
+ if (msg.method === 'textDocument/implementation' && typeof msg.id === 'number') {
65
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ uri: 'file:///fake/impl-a.ts', range: { start: { line: 9, character: 0 }, end: { line: 9, character: 6 } } }, { uri: 'file:///fake/impl-b.ts', range: { start: { line: 4, character: 0 }, end: { line: 4, character: 6 } } }] });
66
+ return;
67
+ }
68
+ if (msg.method === 'textDocument/prepareCallHierarchy' && typeof msg.id === 'number') {
69
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ name: 'targetFn', kind: 12, uri: 'file:///fake/probe.ts', range: { start: { line: 0, character: 0 }, end: { line: 1, character: 0 } }, selectionRange: { start: { line: 0, character: 0 }, end: { line: 0, character: 9 } } }] });
70
+ return;
71
+ }
72
+ if (msg.method === 'callHierarchy/incomingCalls' && typeof msg.id === 'number') {
73
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ from: { name: 'callerOne', uri: 'file:///fake/c1.ts', range: { start: { line: 2, character: 0 }, end: { line: 3, character: 0 } } }, fromRanges: [{ start: { line: 2, character: 4 }, end: { line: 2, character: 13 } }] }, { from: { name: 'callerTwo', uri: 'file:///fake/c2.ts', range: { start: { line: 5, character: 0 }, end: { line: 6, character: 0 } } }, fromRanges: [{ start: { line: 5, character: 4 }, end: { line: 5, character: 13 } }] }] });
74
+ return;
75
+ }
76
+ if (msg.method === 'callHierarchy/outgoingCalls' && typeof msg.id === 'number') {
77
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ to: { name: 'helperFn', uri: 'file:///fake/h.ts', range: { start: { line: 1, character: 0 }, end: { line: 2, character: 0 } } }, toRanges: [{ start: { line: 1, character: 2 }, end: { line: 1, character: 11 } }] }] });
78
+ return;
79
+ }
80
+ if (msg.method === 'textDocument/documentSymbol' && typeof msg.id === 'number') {
81
+ send({ jsonrpc: '2.0', id: msg.id, result: [{ name: 'mainFn', kind: 12, range: { start: { line: 0, character: 0 }, end: { line: 5, character: 0 } }, children: [{ name: 'inner', kind: 6, range: { start: { line: 1, character: 2 }, end: { line: 2, character: 2 } } }] }] });
82
+ return;
83
+ }
84
+ if (typeof msg.id === 'number') {
85
+ send({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found: ' + msg.method } });
86
+ }
87
+ }
88
+
89
+ fs.writeSync(2, ''); // keep stderr referenced
@@ -1,131 +1,131 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { mkdtemp, rm } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import { join, dirname } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import { encodeMessage, MessageDecoder } from '../protocol.ts';
8
- import { scrubEnv, ProcessManager } from '../process-manager.ts';
9
- import { LspClient } from '../client.ts';
10
- import { fileToUri } from '../registry.ts';
11
-
12
- const FAKE_SERVER = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'fake-server.cjs');
13
-
14
- test('protocol: Content-Length framing round-trips through the decoder', () => {
15
- const dec = new MessageDecoder();
16
- const msg = { jsonrpc: '2.0' as const, id: 7, method: 'x', params: { s: '中文内容' } };
17
- const wire = encodeMessage(msg);
18
- // feed in two chunks to prove incremental decoding
19
- const mid = Math.floor(wire.length / 2);
20
- const out1 = dec.push(wire.subarray(0, mid));
21
- const out2 = dec.push(wire.subarray(mid));
22
- assert.deepEqual(out1, []);
23
- assert.deepEqual(out2, [msg]);
24
- // two messages in one chunk
25
- const dec2 = new MessageDecoder();
26
- const both = dec2.push(Buffer.concat([encodeMessage({ jsonrpc: '2.0', id: 1, method: 'a' }), encodeMessage({ jsonrpc: '2.0', id: 2, method: 'b' })]));
27
- assert.equal(both.length, 2);
28
- });
29
-
30
- test('process-manager: env scrub keeps PATH, drops secret-looking vars', () => {
31
- const env = scrubEnv([]);
32
- assert.ok(env.PATH !== undefined || env.Path !== undefined, 'PATH survives');
33
- const probeKeys = ['NODE_AUTH_TOKEN', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'BIGMODEL_API_KEY'];
34
- for (const k of probeKeys) assert.equal((env as Record<string, unknown>)[k], undefined, `${k} must not inherit`);
35
- });
36
-
37
- test('client: full lifecycle against the fake server (initialize→sync→tier0→shutdown)', async () => {
38
- const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
39
- const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
40
- const got: Array<{ uri: string; n: number }> = [];
41
- const client = new LspClient(manager.start(), {
42
- requestTimeoutMs: 10_000,
43
- onDiagnostics: (uri, diags) => got.push({ uri, n: diags.length }),
44
- });
45
- const init = await client.initialize(fileToUri(ws));
46
- assert.equal(init.serverInfo?.name, 'fake-lsp');
47
- // document sync drives push diagnostics
48
- const uri = fileToUri(join(ws, 'probe.ts'));
49
- client.openDoc(uri, 'typescript', 'const x: number = DELBERATE_ERROR_MARKER;\n');
50
- await new Promise((r) => setTimeout(r, 500));
51
- assert.ok(got.some((g) => g.uri === uri && g.n === 1), 'one diagnostic pushed for the marker file');
52
- // tier-0 requests
53
- const hover = await client.hover({ uri }, { line: 0, character: 6 });
54
- assert.match(JSON.stringify(hover?.contents), /fake hover/);
55
- const def = await client.definition({ uri }, { line: 0, character: 6 });
56
- assert.equal(Array.isArray(def) ? def[0]?.uri : def?.uri, 'file:///fake/def.ts');
57
- const refs = await client.references({ uri }, { line: 0, character: 6 });
58
- assert.equal(refs.length, 2);
59
- // Tier-1: implementation + call hierarchy
60
- const impls = await client.implementation({ uri }, { line: 0, character: 6 });
61
- assert.equal(Array.isArray(impls) ? impls.length : 1, 2);
62
- const item = await client.prepareCallHierarchy({ uri }, { line: 0, character: 6 });
63
- const first = Array.isArray(item) ? item[0] : item;
64
- const incoming = await client.callHierarchyIncoming(first);
65
- assert.equal(incoming.length, 2);
66
- assert.equal((incoming[0]!.from as { name?: string }).name, 'callerOne');
67
- const outgoing = await client.callHierarchyOutgoing(first);
68
- assert.equal(outgoing.length, 1);
69
- assert.equal((outgoing[0]!.to as { name?: string }).name, 'helperFn');
70
- const syms = await client.documentSymbols({ uri });
71
- assert.equal(syms[0]?.name, 'mainFn');
72
- assert.equal(syms[0]?.children?.[0]?.name, 'inner');
73
- // clean shutdown stops the process
74
- await client.shutdown();
75
- await manager.stop();
76
- assert.equal(manager.running, false);
77
- await rm(ws, { recursive: true, force: true });
78
- });
79
-
80
- test('registry: health probe flags a broken shim as unhealthy (fake: a command that always fails)', async () => {
81
- const { discoverServers } = await import('../registry.ts');
82
- // real discovery on THIS machine: whatever exists must carry a verdict
83
- const servers = discoverServers(true);
84
- for (const s of servers) {
85
- assert.ok(typeof s.healthy === 'boolean', `${s.id} must carry a health verdict`);
86
- if (!s.healthy) assert.ok((s.unhealthyReason ?? '').length > 0, `${s.id} unhealthy must say why`);
87
- }
88
- // a nonexistent binary is simply not discovered; a failing one is
89
- // discovered-but-unhealthy only when it exists on PATH — both states stay
90
- // honest. (On this dev machine rust-analyzer is a component-missing shim
91
- // and MUST be unhealthy if present.)
92
- const rust = servers.find((s) => s.id === 'rust-analyzer');
93
- if (rust && rust.unhealthyReason) console.log('rust-analyzer verdict:', rust.unhealthyReason.slice(0, 80));
94
- });
95
-
96
- test('client: unknown method surfaces the server error honestly', async () => {
97
- const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
98
- const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
99
- const client = new LspClient(manager.start(), { requestTimeoutMs: 10_000 });
100
- await client.initialize(fileToUri(ws));
101
- await assert.rejects(() => client.request('workspace/executeCommand', {}), /-32601|method not found/);
102
- await client.shutdown();
103
- await manager.stop();
104
- await rm(ws, { recursive: true, force: true });
105
- });
106
-
107
- test('process-manager: restart budget refuses flapping servers', async () => {
108
- const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
109
- const manager = new ProcessManager({ id: 'crasher', command: process.execPath, args: ['-e', 'process.exit(3)'], source: 'explicit' }, ws, { maxRestarts: 2 });
110
- // restarts consume ONLY on explicit start() while the child is dead; a
111
- // fixed 300ms sleep can race a slow spawn (start() sees it alive and
112
- // returns WITHOUT counting) - so WAIT for death before each restart
113
- // (await-the-boundary; this exact test flaked twice on CI)
114
- const waitDead = async (): Promise<boolean> => {
115
- const deadline = Date.now() + 10_000;
116
- while (manager.running) {
117
- if (Date.now() > deadline) return false;
118
- await new Promise((r) => setTimeout(r, 25));
119
- }
120
- return true;
121
- };
122
- manager.start();
123
- assert.ok(await waitDead(), 'first crash should exit');
124
- manager.start(); // restart 1
125
- assert.ok(await waitDead(), 'restart 1 should crash');
126
- manager.start(); // restart 2
127
- assert.ok(await waitDead(), 'restart 2 should crash');
128
- assert.throws(() => manager.start(), /restart budget/);
129
- await manager.stop();
130
- await rm(ws, { recursive: true, force: true });
131
- });
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, dirname } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { encodeMessage, MessageDecoder } from '../protocol.ts';
8
+ import { scrubEnv, ProcessManager } from '../process-manager.ts';
9
+ import { LspClient } from '../client.ts';
10
+ import { fileToUri } from '../registry.ts';
11
+
12
+ const FAKE_SERVER = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'fake-server.cjs');
13
+
14
+ test('protocol: Content-Length framing round-trips through the decoder', () => {
15
+ const dec = new MessageDecoder();
16
+ const msg = { jsonrpc: '2.0' as const, id: 7, method: 'x', params: { s: '中文内容' } };
17
+ const wire = encodeMessage(msg);
18
+ // feed in two chunks to prove incremental decoding
19
+ const mid = Math.floor(wire.length / 2);
20
+ const out1 = dec.push(wire.subarray(0, mid));
21
+ const out2 = dec.push(wire.subarray(mid));
22
+ assert.deepEqual(out1, []);
23
+ assert.deepEqual(out2, [msg]);
24
+ // two messages in one chunk
25
+ const dec2 = new MessageDecoder();
26
+ const both = dec2.push(Buffer.concat([encodeMessage({ jsonrpc: '2.0', id: 1, method: 'a' }), encodeMessage({ jsonrpc: '2.0', id: 2, method: 'b' })]));
27
+ assert.equal(both.length, 2);
28
+ });
29
+
30
+ test('process-manager: env scrub keeps PATH, drops secret-looking vars', () => {
31
+ const env = scrubEnv([]);
32
+ assert.ok(env.PATH !== undefined || env.Path !== undefined, 'PATH survives');
33
+ const probeKeys = ['NODE_AUTH_TOKEN', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'BIGMODEL_API_KEY'];
34
+ for (const k of probeKeys) assert.equal((env as Record<string, unknown>)[k], undefined, `${k} must not inherit`);
35
+ });
36
+
37
+ test('client: full lifecycle against the fake server (initialize→sync→tier0→shutdown)', async () => {
38
+ const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
39
+ const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
40
+ const got: Array<{ uri: string; n: number }> = [];
41
+ const client = new LspClient(manager.start(), {
42
+ requestTimeoutMs: 10_000,
43
+ onDiagnostics: (uri, diags) => got.push({ uri, n: diags.length }),
44
+ });
45
+ const init = await client.initialize(fileToUri(ws));
46
+ assert.equal(init.serverInfo?.name, 'fake-lsp');
47
+ // document sync drives push diagnostics
48
+ const uri = fileToUri(join(ws, 'probe.ts'));
49
+ client.openDoc(uri, 'typescript', 'const x: number = DELBERATE_ERROR_MARKER;\n');
50
+ await new Promise((r) => setTimeout(r, 500));
51
+ assert.ok(got.some((g) => g.uri === uri && g.n === 1), 'one diagnostic pushed for the marker file');
52
+ // tier-0 requests
53
+ const hover = await client.hover({ uri }, { line: 0, character: 6 });
54
+ assert.match(JSON.stringify(hover?.contents), /fake hover/);
55
+ const def = await client.definition({ uri }, { line: 0, character: 6 });
56
+ assert.equal(Array.isArray(def) ? def[0]?.uri : def?.uri, 'file:///fake/def.ts');
57
+ const refs = await client.references({ uri }, { line: 0, character: 6 });
58
+ assert.equal(refs.length, 2);
59
+ // Tier-1: implementation + call hierarchy
60
+ const impls = await client.implementation({ uri }, { line: 0, character: 6 });
61
+ assert.equal(Array.isArray(impls) ? impls.length : 1, 2);
62
+ const item = await client.prepareCallHierarchy({ uri }, { line: 0, character: 6 });
63
+ const first = Array.isArray(item) ? item[0] : item;
64
+ const incoming = await client.callHierarchyIncoming(first);
65
+ assert.equal(incoming.length, 2);
66
+ assert.equal((incoming[0]!.from as { name?: string }).name, 'callerOne');
67
+ const outgoing = await client.callHierarchyOutgoing(first);
68
+ assert.equal(outgoing.length, 1);
69
+ assert.equal((outgoing[0]!.to as { name?: string }).name, 'helperFn');
70
+ const syms = await client.documentSymbols({ uri });
71
+ assert.equal(syms[0]?.name, 'mainFn');
72
+ assert.equal(syms[0]?.children?.[0]?.name, 'inner');
73
+ // clean shutdown stops the process
74
+ await client.shutdown();
75
+ await manager.stop();
76
+ assert.equal(manager.running, false);
77
+ await rm(ws, { recursive: true, force: true });
78
+ });
79
+
80
+ test('registry: health probe flags a broken shim as unhealthy (fake: a command that always fails)', async () => {
81
+ const { discoverServers } = await import('../registry.ts');
82
+ // real discovery on THIS machine: whatever exists must carry a verdict
83
+ const servers = discoverServers(true);
84
+ for (const s of servers) {
85
+ assert.ok(typeof s.healthy === 'boolean', `${s.id} must carry a health verdict`);
86
+ if (!s.healthy) assert.ok((s.unhealthyReason ?? '').length > 0, `${s.id} unhealthy must say why`);
87
+ }
88
+ // a nonexistent binary is simply not discovered; a failing one is
89
+ // discovered-but-unhealthy only when it exists on PATH — both states stay
90
+ // honest. (On this dev machine rust-analyzer is a component-missing shim
91
+ // and MUST be unhealthy if present.)
92
+ const rust = servers.find((s) => s.id === 'rust-analyzer');
93
+ if (rust && rust.unhealthyReason) console.log('rust-analyzer verdict:', rust.unhealthyReason.slice(0, 80));
94
+ });
95
+
96
+ test('client: unknown method surfaces the server error honestly', async () => {
97
+ const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
98
+ const manager = new ProcessManager({ id: 'fake', command: process.execPath, args: [FAKE_SERVER], source: 'explicit' }, ws);
99
+ const client = new LspClient(manager.start(), { requestTimeoutMs: 10_000 });
100
+ await client.initialize(fileToUri(ws));
101
+ await assert.rejects(() => client.request('workspace/executeCommand', {}), /-32601|method not found/);
102
+ await client.shutdown();
103
+ await manager.stop();
104
+ await rm(ws, { recursive: true, force: true });
105
+ });
106
+
107
+ test('process-manager: restart budget refuses flapping servers', async () => {
108
+ const ws = await mkdtemp(join(tmpdir(), 'lsp-ws-'));
109
+ const manager = new ProcessManager({ id: 'crasher', command: process.execPath, args: ['-e', 'process.exit(3)'], source: 'explicit' }, ws, { maxRestarts: 2 });
110
+ // restarts consume ONLY on explicit start() while the child is dead; a
111
+ // fixed 300ms sleep can race a slow spawn (start() sees it alive and
112
+ // returns WITHOUT counting) - so WAIT for death before each restart
113
+ // (await-the-boundary; this exact test flaked twice on CI)
114
+ const waitDead = async (): Promise<boolean> => {
115
+ const deadline = Date.now() + 10_000;
116
+ while (manager.running) {
117
+ if (Date.now() > deadline) return false;
118
+ await new Promise((r) => setTimeout(r, 25));
119
+ }
120
+ return true;
121
+ };
122
+ manager.start();
123
+ assert.ok(await waitDead(), 'first crash should exit');
124
+ manager.start(); // restart 1
125
+ assert.ok(await waitDead(), 'restart 1 should crash');
126
+ manager.start(); // restart 2
127
+ assert.ok(await waitDead(), 'restart 2 should crash');
128
+ assert.throws(() => manager.start(), /restart budget/);
129
+ await manager.stop();
130
+ await rm(ws, { recursive: true, force: true });
131
+ });