@masstensor/diagnose 0.5.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT_PLAN.md +69 -0
- package/KNOWLEDGE_SECURITY.md +47 -0
- package/PAIRING_PROTOCOL.md +37 -0
- package/README.md +28 -6
- package/USER_GUIDE.md +250 -34
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +15 -5
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +61 -13
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +1 -0
- package/dist/engine.js +21 -7
- package/dist/install-skill.d.ts +2 -0
- package/dist/install-skill.js +57 -0
- package/dist/knowledge-cli.d.ts +2 -0
- package/dist/knowledge-cli.js +164 -0
- package/dist/knowledge-drafts.d.ts +47 -0
- package/dist/knowledge-drafts.js +76 -0
- package/dist/knowledge-mcp.d.ts +5 -0
- package/dist/knowledge-mcp.js +65 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +38 -9
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +18 -3
- package/dist/peer.d.ts +9 -0
- package/dist/peer.js +90 -10
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +46 -10
- package/dist/schema.d.ts +4 -1
- package/dist/schema.js +2 -2
- package/dist/session-limits.d.ts +3 -0
- package/dist/session-limits.js +3 -0
- package/dist/short-pairing.d.ts +25 -0
- package/dist/short-pairing.js +73 -0
- package/dist/skill-library.d.ts +27 -0
- package/dist/skill-library.js +226 -0
- package/dist/skill-session.d.ts +1 -0
- package/dist/skill-session.js +257 -0
- package/dist/skill.d.ts +1 -0
- package/dist/skill.js +1 -0
- package/dist/util.js +1 -0
- package/dist/vault-crypto.d.ts +11 -0
- package/dist/vault-crypto.js +30 -0
- package/dist/vault-server.d.ts +10 -0
- package/dist/vault-server.js +156 -0
- package/dist/vault.d.ts +19 -0
- package/dist/vault.js +72 -0
- package/npm-shrinkwrap.json +12 -2
- package/package.json +7 -2
- package/skills/connect/SKILL.md +60 -0
- package/skills/connect/scripts/run.mjs +37 -0
- package/src/agent.ts +12 -5
- package/src/cases.ts +74 -0
- package/src/cli.ts +51 -13
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +17 -4
- package/src/install-skill.ts +57 -0
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/mcp.ts +21 -7
- package/src/operator.ts +12 -3
- package/src/peer.ts +51 -14
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +35 -7
- package/src/schema.ts +4 -2
- package/src/session-limits.ts +3 -0
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill-session.ts +233 -0
- package/src/skill.ts +2 -1
- package/src/util.ts +1 -0
- package/src/vault-crypto.ts +25 -0
- package/src/vault-server.ts +72 -0
- package/src/vault.ts +51 -0
- package/test/agent.test.ts +26 -1
- package/test/cli.test.ts +58 -10
- package/test/install-skill.test.ts +37 -0
- package/test/knowledge-mcp.test.ts +37 -0
- package/test/knowledge.test.ts +112 -0
- package/test/mcp.test.ts +1 -1
- package/test/pairing.test.ts +8 -3
- package/test/review.test.ts +17 -0
- package/test/short-pairing.test.ts +142 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill-session.test.ts +79 -0
- package/test/skill.test.ts +1 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
4
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
5
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join, resolve } from 'node:path';
|
|
8
|
+
import { createRelay } from '../dist/relay.js';
|
|
9
|
+
import { createCode } from '../dist/crypto.js';
|
|
10
|
+
import { Peer } from '../dist/peer.js';
|
|
11
|
+
import { ProbeEngine } from '../dist/engine.js';
|
|
12
|
+
import { Audit } from '../dist/util.js';
|
|
13
|
+
|
|
14
|
+
test('real MCP case records received tasks, reports verification and proposes an unaccepted skill', async t => {
|
|
15
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-case-mcp-')); t.after(() => rm(root, { recursive: true, force: true }));
|
|
16
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createCode();
|
|
17
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
|
|
18
|
+
new ProbeEngine(host, async request => request.task.operation === 'system.inspect', new Audit(join(root, 'audit.jsonl'))); await host.open();
|
|
19
|
+
const client = new Client({ name: 'knowledge-workflow', version: '1' });
|
|
20
|
+
const transport = new StdioClientTransport({ command: process.execPath, args: [resolve('dist/cli.js'), 'mcp', url], env: { ...process.env, HOME: root, USERPROFILE: root } as Record<string, string>, stderr: 'pipe' });
|
|
21
|
+
const call = async (name: string, args: Record<string, unknown>) => { const value = await client.callTool({ name, arguments: args }); assert.ok(!value.isError, JSON.stringify(value)); return JSON.parse((value.content as { text: string }[])[0].text); };
|
|
22
|
+
try {
|
|
23
|
+
await client.connect(transport);
|
|
24
|
+
const names = (await client.listTools()).tools.map(item => item.name); assert.ok(!names.some(name => name.includes('accept') || name.includes('vault')));
|
|
25
|
+
const capabilities = await call('diagnose_capabilities', { operation: 'serial.capture' }); assert.ok(capabilities.operations[0].arguments.properties.baudRate);
|
|
26
|
+
const selected = await call('diagnose_case', { action: 'create', input: { goal: 'Verify interface inspection', host: 'workshop-laptop', target: { name: 'Gateway', model: 'SEG-X3-C', interface: 'serial' } } });
|
|
27
|
+
await call('diagnose_pair', { code, label: 'Acceptance test' });
|
|
28
|
+
for (let i = 0; i < 2; i++) { const task = await call('diagnose_start', { operation: 'system.inspect', arguments: {}, reason: 'Read-only interface inventory' }); const result = await call('diagnose_wait', { id: task.id, timeoutMs: 5000 }); assert.equal(result.result.status, 'ok'); }
|
|
29
|
+
const snapshot = await call('diagnose_case', { action: 'show' }), results = snapshot.case.evidence.filter((item: { kind: string }) => item.kind === 'task.result');
|
|
30
|
+
assert.equal(results.length, 2); assert.ok(!('data' in results[0]));
|
|
31
|
+
const status = await call('diagnose_case', { action: 'status' }); assert.equal(status.probe, 'connected'); assert.equal(status.target.model, 'SEG-X3-C');
|
|
32
|
+
const report = await call('diagnose_case', { action: 'finish', conclusion: { outcome: 'resolved', summary: 'Interface inspection works; device functionality not tested', baseline: results[0].id, verification: results[1].id } }); assert.equal(report.report.conclusion.outcome, 'resolved');
|
|
33
|
+
const draft = await call('diagnose_skill_draft', { name: 'interface-check', caseId: selected.case.id, evidence: [results[0].id], title: 'Inspect gateway interfaces', applicability: 'Gateway attached to an on-site host', prerequisites: 'User consent', identityChecks: 'Confirm model and serial number', readOnlyChecks: 'Use system.inspect; do not scan or open ports automatically', repairConditions: 'No repair authorized by this procedure', recovery: 'Stop if identity differs', verification: 'Confirm selected interface is listed', failedApproaches: 'An interface listing does not verify gateway health' });
|
|
34
|
+
assert.equal(draft.state, 'pending'); assert.deepEqual((await call('diagnose_skills', {})).references, []);
|
|
35
|
+
await call('diagnose_disconnect', {});
|
|
36
|
+
} finally { await client.close(); host.close(); await relay.close(); }
|
|
37
|
+
});
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { Cases } from '../dist/cases.js';
|
|
8
|
+
import { Drafts } from '../dist/knowledge-drafts.js';
|
|
9
|
+
import { SkillLibrary } from '../dist/skill-library.js';
|
|
10
|
+
import { Vault } from '../dist/vault.js';
|
|
11
|
+
import { newRecovery, vaultKeys, objectId, sealBundle, openBundle } from '../dist/vault-crypto.js';
|
|
12
|
+
import { createRelay } from '../dist/relay.js';
|
|
13
|
+
|
|
14
|
+
async function fixture(t: { after: (fn: () => Promise<void>) => void }) { const root = await mkdtemp(join(tmpdir(), 'diagnose-knowledge-')); t.after(() => rm(root, { recursive: true, force: true })); return root; }
|
|
15
|
+
test('case records actual evidence, excludes credentials and requires later verification', async t => {
|
|
16
|
+
const root = await fixture(t), cases = new Cases(join(root, 'cases'));
|
|
17
|
+
const value = cases.create({ goal: 'Restore readings', host: 'site-pc', target: { name: 'Gateway', model: 'SEG-X3-C', interface: 'serial', address: '/dev/private-address' } });
|
|
18
|
+
const baseline = cases.record(value.id, 'task.result', { result: { status: 'ok' }, outputs: { log: 'No readings' }, resumeToken: 'private-resume-token' }, randomUUID())!;
|
|
19
|
+
assert.throws(() => cases.finish(value.id, { outcome: 'resolved', summary: 'Fixed', baseline: baseline.id, verification: baseline.id, changes: [], remaining: [] }), /distinct/);
|
|
20
|
+
const after = cases.record(value.id, 'task.result', { result: { status: 'ok' }, outputs: { log: 'Readings received' } }, randomUUID())!;
|
|
21
|
+
cases.finish(value.id, { outcome: 'resolved', summary: 'Readings verified', baseline: baseline.id, verification: after.id, changes: ['Reconnected sensor'], remaining: [] });
|
|
22
|
+
assert.equal(cases.get(value.id).target.model, 'SEG-X3-C');
|
|
23
|
+
assert.ok(!JSON.stringify(cases.get(value.id)).includes('private-resume-token'));
|
|
24
|
+
const report = JSON.stringify(cases.report(value.id)); assert.ok(!report.includes('/dev/private-address')); assert.ok(!report.includes('Readings received')); assert.ok(report.includes(after.id));
|
|
25
|
+
const bytes = await readFile(join(root, 'cases', value.id + '.meta')); assert.ok(!bytes.includes(Buffer.from('SEG-X3-C')));
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('reviewed drafts preserve references, retain base revision and detect conflicting versions', async t => {
|
|
29
|
+
const root = await fixture(t), source = join(root, 'source'); await mkdir(join(source, 'references'), { recursive: true });
|
|
30
|
+
await writeFile(join(source, 'SKILL.md'), '# Original\n'); await writeFile(join(source, 'references/profile.md'), 'Model SEG-X3-C');
|
|
31
|
+
const library = new SkillLibrary(join(root, 'skills')), base = await library.import('owon', source), cases = new Cases(join(root, 'cases'));
|
|
32
|
+
const value = cases.create({ goal: 'Observe logs', target: { name: 'Gateway', interface: 'serial' }, skill: base });
|
|
33
|
+
const evidence = cases.record(value.id, 'task.result', { result: { status: 'ok' }, outputs: { serial: 'fixture evidence only' } })!;
|
|
34
|
+
const drafts = new Drafts(library, cases, join(root, 'drafts'));
|
|
35
|
+
const input = { name: 'owon', caseId: value.id, base, evidence: [evidence.id], title: 'OWON checks', applicability: 'SEG-X3-C', prerequisites: 'Authorized serial adapter', identityChecks: 'Confirm serial number', readOnlyChecks: 'Capture logs without writes', repairConditions: 'Only after approval', recovery: 'Stop capture', verification: 'Repeat original check', failedApproaches: 'USB power alone is not diagnostic access' };
|
|
36
|
+
const first = await drafts.create(input), conflicting = await drafts.create(input);
|
|
37
|
+
assert.match(await drafts.review(first.id), /- # Original/);
|
|
38
|
+
assert.deepEqual(await library.list(), [base]);
|
|
39
|
+
const accepted = await drafts.accept(first.id); assert.notEqual(accepted, base);
|
|
40
|
+
assert.equal(await readFile(join((await library.load(accepted)).baseDirectory, 'references/profile.md'), 'utf8'), 'Model SEG-X3-C');
|
|
41
|
+
assert.ok(!(await library.load(accepted)).instructions.includes('fixture evidence only'));
|
|
42
|
+
await assert.rejects(drafts.accept(conflicting.id), /versions changed/); assert.equal(drafts.get(conflicting.id).state, 'pending');
|
|
43
|
+
drafts.reject(conflicting.id); assert.equal(drafts.get(conflicting.id).state, 'rejected');
|
|
44
|
+
await assert.rejects(drafts.create({ ...input, evidence: [randomUUID()] }), /belong/);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('vault AEAD binds key, object and namespace; pairing codes are not recovery keys', () => {
|
|
48
|
+
const recovery = newRecovery(), id = objectId(recovery, 'reference'), bytes = Buffer.from('private skill');
|
|
49
|
+
const sealed = sealBundle(recovery, id, bytes); assert.deepEqual(openBundle(recovery, id, sealed), bytes);
|
|
50
|
+
assert.throws(() => openBundle(newRecovery(), id, sealed)); assert.throws(() => openBundle(recovery, '0'.repeat(64), sealed));
|
|
51
|
+
const altered = Buffer.from(sealed); altered[15] ^= 1; assert.throws(() => openBundle(recovery, id, altered));
|
|
52
|
+
assert.throws(() => vaultKeys('D1.' + 'a'.repeat(16) + '.' + 'b'.repeat(43)), /recovery/);
|
|
53
|
+
assert.notEqual(vaultKeys(recovery).auth, recovery.slice(3));
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('two isolated clients sync encrypted complete versions, preserve divergence, revoke and recover offline', async t => {
|
|
57
|
+
const root = await fixture(t), relay = createRelay({ port: 0, vaultPath: join(root, 'relay') }); const origin = 'http://127.0.0.1:' + await relay.listen(); t.after(() => relay.close());
|
|
58
|
+
const libraryA = new SkillLibrary(join(root, 'a-skills')), libraryB = new SkillLibrary(join(root, 'b-skills'));
|
|
59
|
+
const a = new Vault(libraryA, join(root, 'a-key'), origin), b = new Vault(libraryB, join(root, 'b-key'), origin), recovery = newRecovery(); await a.initialize(recovery); await b.initialize(recovery);
|
|
60
|
+
const source = join(root, 'source'); await mkdir(join(source, 'scripts'), { recursive: true }); await writeFile(join(source, 'SKILL.md'), '# Private device procedure'); await writeFile(join(source, 'scripts/check.sh'), 'echo safe');
|
|
61
|
+
const first = await libraryA.import('gateway', source); await a.push(first); await a.push(first);
|
|
62
|
+
assert.deepEqual(await b.pull(), [first]); assert.equal(await readFile(join((await libraryB.load(first)).baseDirectory, 'scripts/check.sh'), 'utf8'), 'echo safe');
|
|
63
|
+
await writeFile(join(source, 'SKILL.md'), '# Client A improvement'); const second = await libraryA.import('gateway', source);
|
|
64
|
+
await writeFile(join(source, 'SKILL.md'), '# Client B improvement'); const third = await libraryB.import('gateway', source);
|
|
65
|
+
await Promise.all([a.push(second), b.push(third)]); assert.deepEqual((await a.pull()).sort(), [first, second, third].sort());
|
|
66
|
+
const namespace = vaultKeys(recovery).namespace;
|
|
67
|
+
for (const name of await readdir(join(root, 'relay', namespace))) { const bytes = await readFile(join(root, 'relay', namespace, name)); assert.ok(!bytes.includes(Buffer.from('Private device'))); assert.ok(!bytes.includes(Buffer.from('gateway'))); }
|
|
68
|
+
const unauthenticated = await fetch(origin + '/v1/library'); assert.equal(unauthenticated.status, 401);
|
|
69
|
+
const backup = join(root, 'recovery-backup'); await a.backup(backup); assert.equal((await readFile(backup, 'utf8')).trim(), recovery);
|
|
70
|
+
await a.revoke(); await assert.rejects(b.list(), /403/); await assert.rejects(b.push(first), /403/);
|
|
71
|
+
assert.ok((await libraryB.load(first)).instructions.includes('Private device')); // cache survives revocation
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('vault rejects tampered ciphertext before importing and server never replaces immutable objects', async t => {
|
|
75
|
+
const root = await fixture(t), relay = createRelay({ port: 0, vaultPath: join(root, 'relay') }); const origin = 'http://127.0.0.1:' + await relay.listen(); t.after(() => relay.close());
|
|
76
|
+
const recovery = newRecovery(), keys = vaultKeys(recovery), id = 'a'.repeat(64), headers = { Authorization: 'Bearer ' + keys.auth, 'Content-Type': 'application/octet-stream' };
|
|
77
|
+
assert.equal((await fetch(origin + '/v1/library/' + id, { method: 'PUT', headers, body: Buffer.alloc(30) })).status, 201);
|
|
78
|
+
assert.equal((await fetch(origin + '/v1/library/' + id, { method: 'PUT', headers, body: Buffer.alloc(30, 1) })).status, 409);
|
|
79
|
+
const library = new SkillLibrary(join(root, 'skills')), vault = new Vault(library, join(root, 'key'), origin); await vault.initialize(recovery);
|
|
80
|
+
await assert.rejects(vault.pull(), /Invalid encrypted/); assert.deepEqual(await library.list(), []);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('relay rejects over-quota and interrupted uploads without publishing partial objects', async t => {
|
|
84
|
+
const { createServer, request } = await import('node:http');
|
|
85
|
+
const { VaultServer } = await import('../dist/vault-server.js');
|
|
86
|
+
const root = await fixture(t), store = new VaultServer(join(root, 'relay'), 40);
|
|
87
|
+
const server = createServer((req, res) => { void store.handle(req, res); });
|
|
88
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); t.after(() => new Promise<void>(resolve => server.close(() => resolve())));
|
|
89
|
+
const origin = 'http://127.0.0.1:' + (server.address() as { port: number }).port, recovery = newRecovery(), headers = { Authorization: 'Bearer ' + vaultKeys(recovery).auth };
|
|
90
|
+
const incompleteId = 'b'.repeat(64);
|
|
91
|
+
await new Promise<void>(resolve => { const req = request(origin + '/v1/library/' + incompleteId, { method: 'PUT', headers: { ...headers, 'Content-Length': '40' } }); req.on('error', () => resolve()); req.write(Buffer.alloc(30)); setTimeout(() => { req.destroy(); resolve(); }, 30); });
|
|
92
|
+
await new Promise(resolve => setTimeout(resolve, 30));
|
|
93
|
+
assert.deepEqual((await (await fetch(origin + '/v1/library', { headers })).json() as { objects: unknown[] }).objects, []);
|
|
94
|
+
assert.equal((await fetch(origin + '/v1/library/' + incompleteId, { method: 'PUT', headers, body: Buffer.alloc(30) })).status, 201);
|
|
95
|
+
assert.equal((await fetch(origin + '/v1/library/' + 'c'.repeat(64), { method: 'PUT', headers, body: Buffer.alloc(30) })).status, 507);
|
|
96
|
+
assert.equal((await (await fetch(origin + '/v1/library', { headers })).json() as { objects: unknown[] }).objects.length, 1);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('received bundles cannot traverse directories or import a forged content revision', async t => {
|
|
100
|
+
const root = await fixture(t), library = new SkillLibrary(join(root, 'skills'));
|
|
101
|
+
const reference = 'library:gateway@' + 'a'.repeat(64);
|
|
102
|
+
await assert.rejects(library.restore({ reference, files: [{ path: '../escape.md', data: Buffer.from('# bad').toString('base64') }] }), /path/);
|
|
103
|
+
await assert.rejects(library.restore({ reference, files: [{ path: 'SKILL.md', data: Buffer.from('# valid but wrong digest').toString('base64') }] }), /integrity/);
|
|
104
|
+
assert.deepEqual(await library.list(), []);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('a selected case refuses a second writer and cannot be removed while active', async t => {
|
|
108
|
+
const root = await fixture(t), first = new Cases(join(root, 'cases')), second = new Cases(join(root, 'cases'));
|
|
109
|
+
const value = first.create({ goal: 'Inspect device', target: { name: 'Gateway', interface: 'serial' } });
|
|
110
|
+
const release = first.claim(value.id); assert.throws(() => second.claim(value.id), /writer/); assert.throws(() => second.remove(value.id), /in use/); assert.throws(() => second.unlock(value.id), /still alive/);
|
|
111
|
+
release(); const releaseSecond = second.claim(value.id); releaseSecond(); second.remove(value.id); assert.deepEqual(first.list(), []);
|
|
112
|
+
});
|
package/test/mcp.test.ts
CHANGED
|
@@ -19,7 +19,7 @@ test('real stdio MCP client pairs, starts, waits and disconnects', async () => {
|
|
|
19
19
|
const client = new Client({ name: 'acceptance', version: '1.0.0' });
|
|
20
20
|
const text = (result: any) => { assert.ok(!result.isError, JSON.stringify(result)); return JSON.parse(result.content[0].text); };
|
|
21
21
|
try {
|
|
22
|
-
await client.connect(transport); assert.deepEqual((await client.listTools()).tools.map(tool => tool.name).sort(), ['diagnose_batch', 'diagnose_cancel', 'diagnose_disconnect', 'diagnose_forward', 'diagnose_pair', 'diagnose_process', 'diagnose_resource', 'diagnose_resume', 'diagnose_start', 'diagnose_transfer', 'diagnose_wait']);
|
|
22
|
+
await client.connect(transport); assert.deepEqual((await client.listTools()).tools.map(tool => tool.name).sort(), ['diagnose_batch', 'diagnose_cancel', 'diagnose_capabilities', 'diagnose_case', 'diagnose_disconnect', 'diagnose_forward', 'diagnose_pair', 'diagnose_process', 'diagnose_resource', 'diagnose_resume', 'diagnose_skill_draft', 'diagnose_skills', 'diagnose_start', 'diagnose_transfer', 'diagnose_wait']);
|
|
23
23
|
assert.equal(text(await client.callTool({ name: 'diagnose_pair', arguments: { code, label: 'MCP test' } })).connected, true);
|
|
24
24
|
const { id } = text(await client.callTool({ name: 'diagnose_start', arguments: { operation: 'system.inspect', arguments: {}, reason: 'Verify MCP execution' } }));
|
|
25
25
|
const result = text(await client.callTool({ name: 'diagnose_wait', arguments: { id, timeoutMs: 5000, release: true } }));
|
package/test/pairing.test.ts
CHANGED
|
@@ -50,14 +50,19 @@ test('actual host survives probe and relay restarts, pauses access, and revokes
|
|
|
50
50
|
let output = '', pairPrompts = 0;
|
|
51
51
|
const start = () => {
|
|
52
52
|
const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'remember-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
53
|
-
|
|
53
|
+
let startup = false;
|
|
54
|
+
child.stderr.resume(); child.stdout.on('data', bytes => {
|
|
55
|
+
output += bytes.toString();
|
|
56
|
+
if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('e\n'); }
|
|
57
|
+
if (output.includes('Remember and allow this diagnostician?') && !pairPrompts) { pairPrompts++; child.stdin.write('a\n'); }
|
|
58
|
+
}); return child;
|
|
54
59
|
};
|
|
55
60
|
let child = start(), peer: Peer | undefined;
|
|
56
61
|
const until = async (predicate: () => boolean) => { for (let i = 0; i < 300 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
|
|
57
62
|
const stop = async () => { const ended = new Promise(resolve => child.once('exit', resolve)); if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {} await ended; };
|
|
58
63
|
try {
|
|
59
|
-
await until(() =>
|
|
60
|
-
const invitation = output.match(
|
|
64
|
+
await until(() => /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.test(output));
|
|
65
|
+
const invitation = output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/)![0];
|
|
61
66
|
peer = new Peer({ role: 'join', code: invitation, relay: url, label: 'Remembered support / test AI', remember: true }); await peer.open();
|
|
62
67
|
const credential = peer.rememberedCode!; assert.ok(credential); assert.notEqual(credential, invitation);
|
|
63
68
|
peer.close(); await until(() => output.includes('Waiting for connections'));
|
package/test/review.test.ts
CHANGED
|
@@ -67,11 +67,28 @@ for (const overwrite of [false, true]) test(`download protects concurrent local
|
|
|
67
67
|
});
|
|
68
68
|
|
|
69
69
|
class FixturePeer extends EventEmitter {
|
|
70
|
+
readonly active = Promise.resolve();
|
|
70
71
|
response?: (value: WireMessage) => void;
|
|
71
72
|
async send(value: WireMessage) { this.response?.(value); }
|
|
72
73
|
close(reason: string) { this.emit('closed', reason); }
|
|
73
74
|
request(task: Task, sequence: number): Promise<WireMessage> { return new Promise(resolve => { this.response = value => { if (value.type === 'task.result') resolve(value); }; this.emit('message', { type: 'task.request', task, sequence }); }); }
|
|
74
75
|
}
|
|
76
|
+
test('probe resets its six-hour idle timeout on activity without a fixed total limit', async t => {
|
|
77
|
+
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
|
|
78
|
+
const peer = new FixturePeer(), reasons: string[] = [];
|
|
79
|
+
peer.on('closed', reason => reasons.push(reason));
|
|
80
|
+
new ProbeEngine(peer as unknown as Peer, async () => false, new Audit(join(directory(), 'audit.jsonl')));
|
|
81
|
+
await peer.active;
|
|
82
|
+
for (let round = 0; round < 3; round++) {
|
|
83
|
+
t.mock.timers.tick(5 * 60 * 60_000);
|
|
84
|
+
assert.deepEqual(reasons, []);
|
|
85
|
+
peer.emit('activity');
|
|
86
|
+
}
|
|
87
|
+
t.mock.timers.tick(6 * 60 * 60_000 - 1);
|
|
88
|
+
assert.deepEqual(reasons, []);
|
|
89
|
+
t.mock.timers.tick(1);
|
|
90
|
+
assert.deepEqual(reasons, ['Idle timeout']);
|
|
91
|
+
});
|
|
75
92
|
test('more than 1000 sequenced tasks work and replayed sequences are rejected', { timeout: 60000 }, async () => {
|
|
76
93
|
const root = directory(), peer = new FixturePeer(); let approvals = 0;
|
|
77
94
|
new ProbeEngine(peer as unknown as Peer, async () => { approvals++; return false; }, new Audit(join(root, 'audit.jsonl')), () => {}, { idleMs: 0, lifetimeMs: 0 });
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
5
|
+
import { createInvitation, parseInvitation, createCode, parseCode } from '../dist/crypto.js';
|
|
6
|
+
import { InvitationHost, InvitationJoin } from '../dist/short-pairing.js';
|
|
7
|
+
import { createRelay } from '../dist/relay.js';
|
|
8
|
+
import { Peer } from '../dist/peer.js';
|
|
9
|
+
|
|
10
|
+
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
|
11
|
+
test('nine-letter codes normalize presentation while long credentials stay separate', () => {
|
|
12
|
+
for (let i = 0; i < 20; i++) assert.match(createInvitation(), /^[a-z]{3}-[a-z]{3}-[a-z]{3}$/);
|
|
13
|
+
const parsed = parseInvitation(' ABC def-GHI '); assert.equal(parsed.room, 'S2.ab'); assert.equal(parsed.secret.toString(), 'cdefghi'); assert.equal(parsed.short, true);
|
|
14
|
+
assert.deepEqual(parseInvitation('abcdefghi'), parsed); assert.throws(() => parseCode('abc-def-ghi'));
|
|
15
|
+
for (const invalid of ['abc-def-gh', 'abc-def-ghij', 'abc-123-ghi', 'ábć-def-ghi']) assert.throws(() => parseInvitation(invalid));
|
|
16
|
+
const legacy = createCode(); assert.equal(parseInvitation(legacy).short, false); assert.equal(parseCode(legacy).secret.length, 32);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('OPAQUE yields matching strong keys, rejects wrong passwords and binds the invitation locator', () => {
|
|
20
|
+
const host = new InvitationHost('S2.ab', Buffer.from('cdefghi'));
|
|
21
|
+
const wrong = new InvitationJoin('S2.ab', Buffer.from('xxxxxxx'));
|
|
22
|
+
assert.throws(() => wrong.finish(host.start(wrong.start())), /invitation|login|authentication/i); host.reset();
|
|
23
|
+
const otherRoom = new InvitationJoin('S2.cd', Buffer.from('cdefghi'));
|
|
24
|
+
assert.throws(() => otherRoom.finish(host.start(otherRoom.start()))); host.reset();
|
|
25
|
+
const correct = new InvitationJoin('S2.ab', Buffer.from('cdefghi'));
|
|
26
|
+
const final = correct.finish(host.start(correct.start())); const secret = host.finish(final.reply);
|
|
27
|
+
assert.equal(secret.length, 32); assert.ok(secret.equals(final.secret)); assert.throws(() => host.finish(final.reply));
|
|
28
|
+
host.destroy(); correct.destroy(); wrong.destroy(); otherRoom.destroy();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('short pairing requires local approval, is one-time, and provisions a separate long reconnect credential', { timeout: 15000 }, async () => {
|
|
32
|
+
const frames: Buffer[] = [], relay = createRelay({ port: 0, observeCiphertext: bytes => frames.push(Buffer.from(bytes)) });
|
|
33
|
+
const url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation(), credential = createCode();
|
|
34
|
+
let prompts = 0;
|
|
35
|
+
const host = new Peer({ role: 'host', code, relay: url, provision: () => credential, accept: async ({ remember }) => { prompts++; assert.equal(remember, true); return true; } }); await host.open();
|
|
36
|
+
const join = new Peer({ role: 'join', code: code.toUpperCase().replaceAll('-', ' '), relay: url, remember: true });
|
|
37
|
+
try {
|
|
38
|
+
await join.open(); await host.active; assert.equal(prompts, 1); assert.equal(join.rememberedCode, credential); assert.equal(join.fingerprint, host.fingerprint);
|
|
39
|
+
const reuse = new Peer({ role: 'join', code, relay: url }); await assert.rejects(reuse.open()); reuse.close();
|
|
40
|
+
assert.ok(!Buffer.concat(frames).includes(Buffer.from(code))); assert.ok(!Buffer.concat(frames).includes(Buffer.from(credential)));
|
|
41
|
+
} finally { join.close(); host.close(); await relay.close(); }
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('wrong secret never reaches approval and a corrected code can still pair', { timeout: 15000 }, async () => {
|
|
45
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = 'abc-def-ghi'; let prompts = 0;
|
|
46
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => { prompts++; return true; } }); await host.open();
|
|
47
|
+
const wrong = new Peer({ role: 'join', code: 'abx-xxx-xxx', relay: url });
|
|
48
|
+
try { await assert.rejects(wrong.open()); assert.equal(prompts, 0); await wait(50); const correct = new Peer({ role: 'join', code, relay: url }); try { await correct.open(); assert.equal(prompts, 1); } finally { correct.close(); } }
|
|
49
|
+
finally { wrong.close(); host.close(); await relay.close(); }
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('invitation expiration is enforced by the probe even when the relay keeps the room', { timeout: 5000 }, async () => {
|
|
53
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen();
|
|
54
|
+
const host = new Peer({ role: 'host', code: createInvitation(), relay: url, invitationMs: 100 });
|
|
55
|
+
try { await host.open(); assert.match(await host.ended, /expired/); } finally { host.close(); await relay.close(); }
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('relay rejects an expired invitation before its periodic cleanup', { timeout: 5000 }, async () => {
|
|
59
|
+
const relay = createRelay({ port: 0, invitationMs: 30 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
|
|
60
|
+
const host = new Peer({ role: 'host', code, relay: url }); await host.open(); await wait(60);
|
|
61
|
+
const join = new Peer({ role: 'join', code, relay: url });
|
|
62
|
+
try { await assert.rejects(join.open()); } finally { join.close(); host.close(); await relay.close(); }
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('probe limits attempts even if a malicious relay keeps resetting the handshake', { timeout: 10000 }, async () => {
|
|
66
|
+
const server = new WebSocketServer({ port: 0, host: '127.0.0.1' }); await once(server, 'listening');
|
|
67
|
+
const url = 'ws://127.0.0.1:' + (server.address() as { port: number }).port; let rejected = 0;
|
|
68
|
+
server.on('connection', ws => {
|
|
69
|
+
const attempt = () => { ws.send(JSON.stringify({ type: 'peer' })); ws.send(Buffer.from('invalid PAKE'), { binary: true }); };
|
|
70
|
+
ws.on('message', (_data, binary) => {
|
|
71
|
+
if (binary) return;
|
|
72
|
+
const message = JSON.parse(_data.toString());
|
|
73
|
+
if (message.role) { ws.send(JSON.stringify({ type: 'registered' })); attempt(); }
|
|
74
|
+
else if (message.type === 'reject') { rejected++; attempt(); }
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
const host = new Peer({ role: 'host', code: createInvitation(), relay: url, accept: async () => { throw new Error('Must never request approval'); } });
|
|
78
|
+
try { await host.open(); assert.match(await host.ended, /attempt limit/); assert.equal(rejected, 4); }
|
|
79
|
+
finally { host.close(); for (const ws of server.clients) ws.terminate(); await new Promise<void>(resolve => server.close(() => resolve())); }
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('locator collisions are explicit and never replace the first probe', { timeout: 5000 }, async () => {
|
|
83
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen();
|
|
84
|
+
const first = new Peer({ role: 'host', code: 'abc-def-ghi', relay: url, accept: async () => true }); await first.open();
|
|
85
|
+
const second = new Peer({ role: 'host', code: 'abx-xxx-xxx', relay: url });
|
|
86
|
+
try { await assert.rejects(second.open(), /locator occupied/); const join = new Peer({ role: 'join', code: 'abc-def-ghi', relay: url }); try { await join.open(); } finally { join.close(); } }
|
|
87
|
+
finally { second.close(); first.close(); await relay.close(); }
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('session idle and lifetime clocks start after pairing, not while the code is waiting', { timeout: 5000 }, async () => {
|
|
91
|
+
const { ProbeEngine } = await import('../dist/engine.js'), { Audit } = await import('../dist/util.js');
|
|
92
|
+
const { mkdtemp, rm } = await import('node:fs/promises'), { tmpdir } = await import('node:os'), { join } = await import('node:path');
|
|
93
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-short-idle-'));
|
|
94
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
|
|
95
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
|
|
96
|
+
new ProbeEngine(host, async () => false, new Audit(join(root, 'audit')), () => {}, { idleMs: 40, lifetimeMs: 100 }); await host.open(); await wait(150);
|
|
97
|
+
const joiner = new Peer({ role: 'join', code, relay: url });
|
|
98
|
+
try { await joiner.open(); assert.equal(await host.ended, 'Idle timeout'); }
|
|
99
|
+
finally { joiner.close(); host.close(); await relay.close(); await rm(root, { recursive: true, force: true }); }
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('relay renews the locked room on encrypted traffic past six hours and expires a silent room', { timeout: 10000 }, async t => {
|
|
103
|
+
let now = Date.now();
|
|
104
|
+
t.mock.method(Date, 'now', () => now);
|
|
105
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
|
|
106
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
|
|
107
|
+
let joiner: Peer | undefined;
|
|
108
|
+
try {
|
|
109
|
+
await host.open();
|
|
110
|
+
joiner = new Peer({ role: 'join', code, relay: url });
|
|
111
|
+
await joiner.open();
|
|
112
|
+
await host.active;
|
|
113
|
+
for (let round = 0; round < 3; round++) {
|
|
114
|
+
now += 5 * 60 * 60_000;
|
|
115
|
+
const received = once(host, 'message');
|
|
116
|
+
await joiner.send({ type: 'task.cancel', id: '26155a8b-c35a-436e-948a-9797732e6259' });
|
|
117
|
+
assert.equal((await received)[0].type, 'task.cancel');
|
|
118
|
+
}
|
|
119
|
+
now += 6 * 60 * 60_000;
|
|
120
|
+
await joiner.send({ type: 'ping' });
|
|
121
|
+
assert.equal(await host.ended, 'Relay session expired');
|
|
122
|
+
assert.equal(await joiner.ended, 'Relay session expired');
|
|
123
|
+
} finally { joiner?.close(); host.close(); await relay.close(); }
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('normal heartbeat is not diagnostic activity but an explicit result poll is', { timeout: 5000 }, async () => {
|
|
127
|
+
const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
|
|
128
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
|
|
129
|
+
await host.open();
|
|
130
|
+
const joiner = new Peer({ role: 'join', code, relay: url });
|
|
131
|
+
let activity = 0;
|
|
132
|
+
host.on('activity', () => { activity++; });
|
|
133
|
+
try {
|
|
134
|
+
await joiner.open();
|
|
135
|
+
await joiner.send({ type: 'ping' });
|
|
136
|
+
assert.equal(activity, 0);
|
|
137
|
+
const touched = once(host, 'activity');
|
|
138
|
+
await joiner.send({ type: 'ping', activity: true });
|
|
139
|
+
await touched;
|
|
140
|
+
assert.equal(activity, 1);
|
|
141
|
+
} finally { joiner.close(); host.close(); await relay.close(); }
|
|
142
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { SkillLibrary } from '../dist/skill-library.js';
|
|
7
|
+
|
|
8
|
+
test('library imports complete bundles, deduplicates and keeps launchable old revisions', async t => {
|
|
9
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-library-')); t.after(() => rm(root, { recursive: true, force: true }));
|
|
10
|
+
const source = join(root, 'source'), library = new SkillLibrary(join(root, 'library'));
|
|
11
|
+
await mkdir(join(source, 'references'), { recursive: true }); await mkdir(join(source, 'scripts'));
|
|
12
|
+
await writeFile(join(source, 'SKILL.md'), '# Gateway\nRead references/profile.md.');
|
|
13
|
+
await writeFile(join(source, 'references/profile.md'), 'Model A');
|
|
14
|
+
await writeFile(join(source, 'scripts/check.sh'), 'exit 99\n');
|
|
15
|
+
const first = await library.import('gateway', source);
|
|
16
|
+
assert.equal(await library.import('gateway', source), first);
|
|
17
|
+
const loaded = await library.load(first);
|
|
18
|
+
assert.equal(loaded.libraryReference, first);
|
|
19
|
+
assert.equal(await readFile(join(loaded.baseDirectory, 'scripts/check.sh'), 'utf8'), 'exit 99\n');
|
|
20
|
+
await writeFile(join(source, 'references/profile.md'), 'Model B');
|
|
21
|
+
const second = await library.import('gateway', source); assert.notEqual(second, first);
|
|
22
|
+
assert.equal(await readFile(join((await library.load(first)).baseDirectory, 'references/profile.md'), 'utf8'), 'Model A');
|
|
23
|
+
assert.deepEqual((await library.list()).sort(), [first, second].sort());
|
|
24
|
+
await writeFile(join(loaded.baseDirectory, 'references/profile.md'), 'Tampered');
|
|
25
|
+
await assert.rejects(library.load(first), /integrity/);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('single Markdown import is isolated from adjacent files and validates references', async t => {
|
|
29
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-library-file-')); t.after(() => rm(root, { recursive: true, force: true }));
|
|
30
|
+
const library = new SkillLibrary(join(root, 'library')), file = join(root, 'task.md');
|
|
31
|
+
assert.deepEqual(await library.list(), []);
|
|
32
|
+
await writeFile(file, '# Read-only check'); await writeFile(join(root, 'secret.txt'), 'Do not import');
|
|
33
|
+
const reference = await library.import('gateway', file), loaded = await library.load(reference);
|
|
34
|
+
assert.equal(loaded.instructions, '# Read-only check');
|
|
35
|
+
await assert.rejects(readFile(join(loaded.baseDirectory, 'secret.txt')), /ENOENT/);
|
|
36
|
+
for (const name of ['../escape', 'Uppercase', '', 'con']) await assert.rejects(library.import(name, file), /name/);
|
|
37
|
+
for (const ref of ['library:../escape@' + 'a'.repeat(64), 'library:gateway@latest', 'library:gateway']) await assert.rejects(library.load(ref), /FULL_SHA256/);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('bundle import rejects symlinks, non-portable paths and oversized resources', async t => {
|
|
41
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-library-invalid-')); t.after(() => rm(root, { recursive: true, force: true }));
|
|
42
|
+
const source = join(root, 'source'), library = new SkillLibrary(join(root, 'library'));
|
|
43
|
+
await mkdir(source); await writeFile(join(source, 'SKILL.md'), '# Device');
|
|
44
|
+
await writeFile(join(source, 'has space.md'), 'invalid'); await assert.rejects(library.import('device', source), /portable/); await rm(join(source, 'has space.md'));
|
|
45
|
+
await writeFile(join(source, 'large.bin'), Buffer.alloc(8 * 1024 * 1024)); await assert.rejects(library.import('device', source), /8 MiB/); await rm(join(source, 'large.bin'));
|
|
46
|
+
if (process.platform !== 'win32') {
|
|
47
|
+
await symlink(join(source, 'SKILL.md'), join(source, 'linked.md'));
|
|
48
|
+
await assert.rejects(library.import('device', source), /symbolic/);
|
|
49
|
+
}
|
|
50
|
+
assert.deepEqual(await library.list(), []);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('library rejects excessive file counts and keeps concurrent identical imports intact', async t => {
|
|
54
|
+
const root = await mkdtemp(join(tmpdir(), 'diagnose-library-limits-')); t.after(() => rm(root, { recursive: true, force: true }));
|
|
55
|
+
const source = join(root, 'source'), library = new SkillLibrary(join(root, 'library'));
|
|
56
|
+
await mkdir(source); await writeFile(join(source, 'SKILL.md'), '# Device');
|
|
57
|
+
const refs = await Promise.all([library.import('device', source), library.import('device', source)]);
|
|
58
|
+
assert.equal(refs[0], refs[1]); await library.load(refs[0]);
|
|
59
|
+
for (let i = 0; i < 128; i++) await writeFile(join(source, `reference-${i}.md`), 'Reference');
|
|
60
|
+
await assert.rejects(library.import('device', source), /128 files/);
|
|
61
|
+
assert.deepEqual(await library.list(), [refs[0]]);
|
|
62
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { createRelay } from '../dist/relay.js';
|
|
9
|
+
import { createInvitation } from '../dist/crypto.js';
|
|
10
|
+
import { Peer } from '../dist/peer.js';
|
|
11
|
+
import { ProbeEngine } from '../dist/engine.js';
|
|
12
|
+
import { Audit } from '../dist/util.js';
|
|
13
|
+
|
|
14
|
+
function helper(action: string, input: Record<string, unknown>): Promise<Record<string, any>> {
|
|
15
|
+
const script = process.env.DIAGNOSE_TEST_SKILL ?? resolve('skills/connect/scripts/run.mjs');
|
|
16
|
+
const child = spawn(process.execPath, [script, action], { stdio: 'pipe' });
|
|
17
|
+
let out = '', err = '';
|
|
18
|
+
child.stdout.setEncoding('utf8').on('data', text => { out += text; });
|
|
19
|
+
child.stderr.setEncoding('utf8').on('data', text => { err += text; });
|
|
20
|
+
child.stdin.end(JSON.stringify(input));
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
child.on('error', reject);
|
|
23
|
+
child.on('close', status => {
|
|
24
|
+
if (status !== 0) { reject(new Error(err)); return; }
|
|
25
|
+
try { resolve(JSON.parse(out)); }
|
|
26
|
+
catch (error) { reject(error); }
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test('native Skill helper pairs once, reuses the connection for a repair and closes it', { timeout: 30000 }, async () => {
|
|
32
|
+
const scratch = await mkdtemp(join(tmpdir(), 'diagnose-skill-'));
|
|
33
|
+
const config = join(scratch, 'config.txt');
|
|
34
|
+
await writeFile(config, 'offline\n');
|
|
35
|
+
const relay = createRelay({ port: 0 });
|
|
36
|
+
const url = 'ws://127.0.0.1:' + await relay.listen();
|
|
37
|
+
const code = createInvitation();
|
|
38
|
+
let pairs = 0;
|
|
39
|
+
const approvals: Array<string> = [];
|
|
40
|
+
const host = new Peer({ role: 'host', code, relay: url, accept: async () => { pairs++; return true; } });
|
|
41
|
+
new ProbeEngine(host, async request => { approvals.push(request.stage); return true; }, new Audit(join(scratch, 'audit')));
|
|
42
|
+
let session: string | undefined;
|
|
43
|
+
try {
|
|
44
|
+
await host.open();
|
|
45
|
+
const opened = await helper('open', { code, label: 'Skill test', relay: url });
|
|
46
|
+
assert.equal(opened.connected, true);
|
|
47
|
+
assert.equal(opened.idleSeconds, 6 * 60 * 60);
|
|
48
|
+
session = opened.session;
|
|
49
|
+
assert.ok(session);
|
|
50
|
+
const call = (tool: string, args: object) => helper('call', { session, tool, arguments: args });
|
|
51
|
+
const run = async (operation: string, args: object) => {
|
|
52
|
+
const { id } = await call('diagnose_start', { operation, arguments: args, reason: 'Test an isolated demo configuration' });
|
|
53
|
+
return call('diagnose_wait', { id, timeoutMs: 5000 });
|
|
54
|
+
};
|
|
55
|
+
const forged = session.replace(/.$/, session.endsWith('0') ? '1' : '0');
|
|
56
|
+
await assert.rejects(helper('close', { session: forged }), /Invalid skill session/);
|
|
57
|
+
await assert.rejects(call('diagnose_start', { operation: 'net.forward', arguments: {} }), /Unsupported operation/);
|
|
58
|
+
const inspection = await run('system.inspect', {});
|
|
59
|
+
assert.equal(inspection.result.data.platform, process.platform);
|
|
60
|
+
assert.ok(Array.isArray(inspection.result.data.serialPorts));
|
|
61
|
+
assert.equal((await run('file.read', { path: config })).outputs.file, 'offline\n');
|
|
62
|
+
const expectedSha256 = createHash('sha256').update('offline\n').digest('hex');
|
|
63
|
+
assert.equal((await run('file.write', { path: config, content: 'online\n', expectedSha256 })).result.status, 'ok');
|
|
64
|
+
assert.equal((await run('file.read', { path: config })).outputs.file, 'online\n');
|
|
65
|
+
assert.equal(await readFile(config, 'utf8'), 'online\n');
|
|
66
|
+
assert.equal(pairs, 1);
|
|
67
|
+
assert.deepEqual(approvals, ['execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send']);
|
|
68
|
+
const handle = session;
|
|
69
|
+
assert.equal((await helper('close', { session })).disconnected, true);
|
|
70
|
+
session = undefined;
|
|
71
|
+
assert.equal(await host.ended, 'Diagnostician ended session');
|
|
72
|
+
await assert.rejects(helper('call', { session: handle, tool: 'diagnose_wait', arguments: {} }), /session unavailable/i);
|
|
73
|
+
} finally {
|
|
74
|
+
if (session) await helper('close', { session }).catch(() => {});
|
|
75
|
+
host.close();
|
|
76
|
+
await relay.close();
|
|
77
|
+
await rm(scratch, { recursive: true, force: true });
|
|
78
|
+
}
|
|
79
|
+
});
|
package/test/skill.test.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { createHash } from 'node:crypto';
|
|
|
7
7
|
import { loadSkill } from '../dist/skill.js';
|
|
8
8
|
|
|
9
9
|
test('skill loader accepts UTF-8 Markdown and preserves exact instructions and source base', async () => {
|
|
10
|
-
const root = await realpath(await mkdtemp(join(tmpdir(), 'diagnose skill '))), file = join(root, 'device "quoted".md'), source = '\uFEFF# Device\nCheck port 11500. Literal $(do-not-execute).\n';
|
|
10
|
+
const root = await realpath(await mkdtemp(join(tmpdir(), 'diagnose skill '))), file = join(root, process.platform === 'win32' ? 'device with spaces.md' : 'device "quoted".md'), source = '\uFEFF# Device\nCheck port 11500. Literal $(do-not-execute).\n';
|
|
11
11
|
await writeFile(file, source); const skill = await loadSkill(file);
|
|
12
12
|
assert.equal(skill.sourceFile, file); assert.equal(skill.baseDirectory, root); assert.equal(skill.instructions, source.slice(1)); assert.equal(skill.sha256, createHash('sha256').update(Buffer.from(source)).digest('hex'));
|
|
13
13
|
});
|