@masstensor/diagnose 0.3.2 → 0.7.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 (107) hide show
  1. package/DEVELOPMENT_PLAN.md +69 -0
  2. package/KNOWLEDGE_SECURITY.md +47 -0
  3. package/PAIRING_PROTOCOL.md +37 -0
  4. package/README.md +56 -9
  5. package/USER_GUIDE.md +460 -20
  6. package/deploy/Caddyfile +1 -1
  7. package/deploy/ecosystem.config.cjs +1 -1
  8. package/dist/agent-command.d.ts +4 -0
  9. package/dist/agent-command.js +33 -0
  10. package/dist/agent.d.ts +1 -1
  11. package/dist/agent.js +48 -8
  12. package/dist/cases.d.ts +118 -0
  13. package/dist/cases.js +115 -0
  14. package/dist/cli.js +187 -25
  15. package/dist/crypto.d.ts +7 -0
  16. package/dist/crypto.js +16 -1
  17. package/dist/discover.js +1 -1
  18. package/dist/engine.d.ts +3 -0
  19. package/dist/engine.js +49 -9
  20. package/dist/history.d.ts +13 -0
  21. package/dist/history.js +57 -0
  22. package/dist/journal.d.ts +23 -1
  23. package/dist/journal.js +82 -5
  24. package/dist/knowledge-cli.d.ts +2 -0
  25. package/dist/knowledge-cli.js +164 -0
  26. package/dist/knowledge-drafts.d.ts +47 -0
  27. package/dist/knowledge-drafts.js +76 -0
  28. package/dist/knowledge-mcp.d.ts +5 -0
  29. package/dist/knowledge-mcp.js +65 -0
  30. package/dist/maintenance.d.ts +2 -0
  31. package/dist/maintenance.js +46 -0
  32. package/dist/mcp.d.ts +1 -1
  33. package/dist/mcp.js +42 -20
  34. package/dist/operator.d.ts +4 -0
  35. package/dist/operator.js +33 -8
  36. package/dist/pairing.d.ts +40 -0
  37. package/dist/pairing.js +92 -0
  38. package/dist/peer.d.ts +13 -0
  39. package/dist/peer.js +87 -11
  40. package/dist/relay-main.js +1 -1
  41. package/dist/relay.d.ts +1 -0
  42. package/dist/relay.js +27 -4
  43. package/dist/resources.js +47 -26
  44. package/dist/schema.d.ts +2 -0
  45. package/dist/schema.js +2 -2
  46. package/dist/short-pairing.d.ts +25 -0
  47. package/dist/short-pairing.js +73 -0
  48. package/dist/skill-library.d.ts +27 -0
  49. package/dist/skill-library.js +226 -0
  50. package/dist/skill.d.ts +9 -0
  51. package/dist/skill.js +59 -0
  52. package/dist/transfers.js +28 -11
  53. package/dist/util.d.ts +2 -0
  54. package/dist/util.js +17 -3
  55. package/dist/vault-crypto.d.ts +11 -0
  56. package/dist/vault-crypto.js +30 -0
  57. package/dist/vault-server.d.ts +10 -0
  58. package/dist/vault-server.js +156 -0
  59. package/dist/vault.d.ts +19 -0
  60. package/dist/vault.js +72 -0
  61. package/examples/skills/device-troubleshooting/SKILL.md +35 -0
  62. package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
  63. package/examples/skills/owon.md +27 -0
  64. package/npm-shrinkwrap.json +209 -3
  65. package/package.json +15 -5
  66. package/scripts/setup-node.ps1 +54 -0
  67. package/scripts/setup-node.sh +52 -0
  68. package/src/agent-command.ts +25 -0
  69. package/src/agent.ts +37 -7
  70. package/src/cases.ts +74 -0
  71. package/src/cli.ts +57 -22
  72. package/src/crypto.ts +14 -1
  73. package/src/discover.ts +1 -1
  74. package/src/engine.ts +28 -7
  75. package/src/history.ts +43 -0
  76. package/src/journal.ts +41 -5
  77. package/src/knowledge-cli.ts +67 -0
  78. package/src/knowledge-drafts.ts +55 -0
  79. package/src/knowledge-mcp.ts +35 -0
  80. package/src/maintenance.ts +30 -0
  81. package/src/mcp.ts +26 -18
  82. package/src/operator.ts +25 -9
  83. package/src/pairing.ts +64 -0
  84. package/src/peer.ts +42 -14
  85. package/src/relay-main.ts +1 -1
  86. package/src/relay.ts +18 -6
  87. package/src/resources.ts +35 -13
  88. package/src/schema.ts +4 -4
  89. package/src/short-pairing.ts +57 -0
  90. package/src/skill-library.ts +162 -0
  91. package/src/skill.ts +45 -0
  92. package/src/transfers.ts +14 -3
  93. package/src/util.ts +15 -3
  94. package/src/vault-crypto.ts +25 -0
  95. package/src/vault-server.ts +72 -0
  96. package/src/vault.ts +51 -0
  97. package/test/agent.test.ts +79 -7
  98. package/test/cli.test.ts +3 -3
  99. package/test/knowledge-mcp.test.ts +37 -0
  100. package/test/knowledge.test.ts +112 -0
  101. package/test/mcp.test.ts +1 -1
  102. package/test/pairing.test.ts +124 -0
  103. package/test/review.test.ts +129 -0
  104. package/test/setup.test.ts +16 -0
  105. package/test/short-pairing.test.ts +100 -0
  106. package/test/skill-library.test.ts +62 -0
  107. package/test/skill.test.ts +25 -0
@@ -0,0 +1,129 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, writeFileSync, readFileSync, statSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { randomUUID, createHash } from 'node:crypto';
7
+ import { EventEmitter } from 'node:events';
8
+ import { spawn } from 'node:child_process';
9
+ import { SessionResources } from '../dist/resources.js';
10
+ import { Audit } from '../dist/util.js';
11
+ import { atomicTaskSchema, resourceRequestSchema, type Task, type WireMessage } from '../dist/schema.js';
12
+ import { download } from '../dist/transfers.js';
13
+ import { Operator } from '../dist/operator.js';
14
+ import { ProbeEngine } from '../dist/engine.js';
15
+ import type { Peer } from '../dist/peer.js';
16
+ import { Journal } from '../dist/journal.js';
17
+ import { History } from '../dist/history.js';
18
+ import { cleanupLocal } from '../dist/maintenance.js';
19
+ import { agentCommand } from '../dist/agent-command.js';
20
+ const directory = () => mkdtempSync(join(tmpdir(), 'diagnose-review-'));
21
+ const task = (operation: string, args: object) => atomicTaskSchema.parse({ id: randomUUID(), operation, arguments: args, reason: 'Review regression' });
22
+ const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
23
+
24
+ test('process leader exit and local revocation both remove ordinary descendants', { skip: process.platform === 'win32' }, async () => {
25
+ for (const parentExits of [true, false]) {
26
+ const root = directory(), manager = new SessionResources(join(root, 'resources'), new Audit(join(root, 'audit.jsonl'))), marker = join(root, 'pid');
27
+ let pid: number | undefined;
28
+ try {
29
+ const script = `const c=require('child_process').spawn(process.execPath,['-e','process.on("SIGTERM",()=>{});setInterval(()=>{},1000)'],{stdio:'ignore'});require('fs').writeFileSync(${JSON.stringify(marker)},String(c.pid));c.unref();${parentExits ? '' : 'setInterval(()=>{},1000);'}`;
30
+ await manager.open(task('process.open', { executable: process.execPath, args: ['-e', script] }), 'owner');
31
+ for (let i = 0; i < 100 && !existsSync(marker); i++) await wait(20);
32
+ pid = Number(readFileSync(marker, 'utf8'));
33
+ if (!parentExits) await manager.revoke();
34
+ let alive = true;
35
+ for (let i = 0; i < 100; i++) { try { process.kill(pid, 0); if (process.platform === 'linux' && /^State:\s+Z/m.test(readFileSync(`/proc/${pid}/status`, 'utf8'))) { alive = false; break; } } catch { alive = false; break; } await wait(20); }
36
+ assert.equal(alive, false, 'Descendant must be stopped even after its leader exits');
37
+ } finally { if (pid) try { process.kill(pid, 'SIGKILL'); } catch {} await manager.revoke(); }
38
+ }
39
+ });
40
+
41
+ test('upload preserves executable permissions and refuses newly created targets', { skip: process.platform === 'win32' }, async () => {
42
+ const root = directory(), manager = new SessionResources(join(root, 'resources'), new Audit(join(root, 'audit.jsonl'))), target = join(root, 'program');
43
+ const bytes = Buffer.from('replacement'), sha256 = createHash('sha256').update(bytes).digest('hex');
44
+ const control = (id: string, action: string, extra = {}) => manager.control('owner', resourceRequestSchema.parse({ id, action, ...extra }));
45
+ try {
46
+ writeFileSync(target, 'original', { mode: 0o755 });
47
+ const result = await manager.open(task('file.transfer', { direction: 'upload', path: target, overwrite: true, size: bytes.length, sha256 }), 'owner') as { id: string };
48
+ await control(result.id, 'input', { data: bytes.toString('base64') }); await control(result.id, 'commit');
49
+ assert.equal(statSync(target).mode & 0o777, 0o755);
50
+ const fresh = join(root, 'new');
51
+ const second = await manager.open(task('file.transfer', { direction: 'upload', path: fresh, size: bytes.length, sha256 }), 'owner') as { id: string };
52
+ await control(second.id, 'input', { data: bytes.toString('base64') }); writeFileSync(fresh, 'local data');
53
+ await assert.rejects(control(second.id, 'commit'), /changed|exists/i); assert.equal(readFileSync(fresh, 'utf8'), 'local data');
54
+ } finally { await manager.revoke(); }
55
+ });
56
+
57
+ for (const overwrite of [false, true]) test(`download protects concurrent local edits (overwrite=${overwrite})`, async () => {
58
+ const root = directory(), target = join(root, 'result'), bytes = Buffer.from('remote'), id = randomUUID();
59
+ if (overwrite) writeFileSync(target, 'original');
60
+ const operator = {
61
+ async start() { writeFileSync(target, 'local edit while awaiting authorization'); return id; },
62
+ async wait() { return { id, result: { status: 'ok', data: { id, size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), offset: 0 } } }; }, release() {},
63
+ async resource(request: { action: string }) { return request.action === 'read' ? { data: bytes.toString('base64'), nextOffset: bytes.length } : {}; },
64
+ } as unknown as Operator;
65
+ await assert.rejects(download(operator, 'remote', target, 'Regression', { overwrite }), /exist|changed/i);
66
+ assert.equal(readFileSync(target, 'utf8'), 'local edit while awaiting authorization');
67
+ });
68
+
69
+ class FixturePeer extends EventEmitter {
70
+ readonly active = Promise.resolve();
71
+ response?: (value: WireMessage) => void;
72
+ async send(value: WireMessage) { this.response?.(value); }
73
+ close(reason: string) { this.emit('closed', reason); }
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 }); }); }
75
+ }
76
+ test('more than 1000 sequenced tasks work and replayed sequences are rejected', { timeout: 60000 }, async () => {
77
+ const root = directory(), peer = new FixturePeer(); let approvals = 0;
78
+ new ProbeEngine(peer as unknown as Peer, async () => { approvals++; return false; }, new Audit(join(root, 'audit.jsonl')), () => {}, { idleMs: 0, lifetimeMs: 0 });
79
+ try {
80
+ for (let sequence = 1; sequence <= 1005; sequence++) {
81
+ const result = await peer.request(task('system.inspect', {}), sequence);
82
+ assert.equal(result.type === 'task.result' && result.result.status, 'denied');
83
+ }
84
+ assert.equal(approvals, 1005);
85
+ const repeated = await peer.request(task('system.inspect', {}), 1005);
86
+ assert.equal(repeated.type === 'task.result' && repeated.result.status, 'duplicate'); assert.equal(approvals, 1005);
87
+ } finally { peer.close('Done'); }
88
+ });
89
+ test('operator bounds completed result storage without limiting lifetime task count', async () => {
90
+ const peer = new FixturePeer(), operator = new Operator(peer as unknown as Peer);
91
+ peer.send = async value => { if (value.type === 'task.request') peer.emit('message', { type: 'task.result', id: value.task.id, result: { status: 'ok' } }); };
92
+ let first = '';
93
+ for (let i = 0; i < 1005; i++) { const id = await operator.start({ operation: 'system.inspect', arguments: {}, reason: 'Long session' }); first ||= id; assert.ok(!('pending' in await operator.wait(id))); }
94
+ await assert.rejects(operator.wait(first), /expired/); peer.close('Done');
95
+ });
96
+ test('local history retains exact task and collected results even when transfer is refused, encrypted on disk', async () => {
97
+ const root = directory(), peer = new FixturePeer(), audit = new Audit(join(root, 'audit.jsonl'));
98
+ new ProbeEngine(peer as unknown as Peer, async request => request.stage === 'execute', audit, () => {}, { idleMs: 0, lifetimeMs: 0 });
99
+ const request = task('process.script', { interpreter: process.execPath, script: 'console.log("PRIVATE_HISTORY_EVIDENCE")' });
100
+ try {
101
+ await peer.request(request, 1); await wait(10);
102
+ const value = audit.history.show(request.id) as { request: Task; outputs: Record<string, { data: string }>; events: { event: string }[] };
103
+ assert.deepEqual(value.request, request); assert.match(value.outputs.stdout.data, /PRIVATE_HISTORY_EVIDENCE/);
104
+ assert.ok(value.events.some(event => event.event === 'task.send-denied'));
105
+ for (const name of readdirSync(join(root, 'history'))) assert.equal(readFileSync(join(root, 'history', name)).includes(Buffer.from('PRIVATE_HISTORY_EVIDENCE')), false);
106
+ assert.equal(readFileSync(audit.path, 'utf8').includes('PRIVATE_HISTORY_EVIDENCE'), false);
107
+ assert.equal(new History(join(root, 'history')).list().length, 1);
108
+ cleanupLocal(0, root); assert.equal(new History(join(root, 'history')).list().length, 0);
109
+ } finally { peer.close('Done'); }
110
+ });
111
+ test('journal budgets prune inactive records, protect live jobs, and reject unbounded output', () => {
112
+ const root = directory(), limits = { maxBytes: 5000, maxEntries: 2, maxAgeMs: 86400000 }, journal = new Journal(root, limits);
113
+ const meta = (state: string) => ({ id: randomUUID(), kind: 'process' as const, state, createdAt: new Date().toISOString(), updatedAt: '', ownerPid: process.pid, tokenHash: '', retainOnDisconnect: false });
114
+ const active = meta('running'), old = meta('completed'); journal.save(active); journal.save(old); journal.append(old.id, 'stdout', Buffer.alloc(1500));
115
+ const next = meta('completed'); journal.save(next); assert.equal(journal.exists(old.id), false); assert.equal(journal.exists(active.id), true);
116
+ assert.throws(() => journal.append(active.id, 'stdout', Buffer.alloc(6000)), /quota/);
117
+ journal.cleanup({ ...limits, maxAgeMs: 0 }); assert.equal(journal.exists(active.id), true); assert.equal(journal.exists(next.id), false);
118
+ });
119
+ test('Windows npm command resolution preserves literal arguments without a shell', async () => {
120
+ const root = directory(), entry = join(root, 'node_modules', 'example', 'bin.js'); mkdirSync(join(root, 'node_modules', 'example'), { recursive: true });
121
+ writeFileSync(entry, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))');
122
+ writeFileSync(join(root, 'codex.cmd'), '@ECHO off\n"%_prog%" "%dp0%\\node_modules\\example\\bin.js" %*\n');
123
+ const args = ['space value', '"quoted"', '%PATH%', '!VAR!', '$(no)', '& echo NO', '{"path":"C:\\Folder name"}'];
124
+ const resolved = await agentCommand('codex', args, { PATH: root }, 'win32');
125
+ const captured = await new Promise<string>((resolve, reject) => { const child = spawn(resolved.command, resolved.args, { shell: false }); let out = ''; child.stdout.on('data', b => out += b); child.on('error', reject); child.on('close', code => code === 0 ? resolve(out) : reject(new Error(`Exit ${code}`))); });
126
+ assert.deepEqual(JSON.parse(captured), args);
127
+ writeFileSync(join(root, 'claude.cmd'), '@echo off\necho unsupported');
128
+ await assert.rejects(agentCommand('claude', [], { Path: root }, 'win32'), /Unsupported/);
129
+ });
@@ -0,0 +1,16 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, mkdirSync, writeFileSync, readdirSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { spawnSync } from 'node:child_process';
7
+
8
+ for (const [version, npmPresent, expected] of [['18.20.0', true, 1], ['20.9.0', true, 1], ['20.10.0', true, 0], ['22.18.0', false, 1]] as const) {
9
+ test(`setup preserves existing Node ${version} and user files (npm present: ${npmPresent})`, { skip: process.platform === 'win32' }, () => {
10
+ const root = mkdtempSync(join(tmpdir(), 'diagnose-setup-test-')), home = join(root, 'home'), bin = join(root, 'bin'); mkdirSync(home); mkdirSync(bin);
11
+ writeFileSync(join(bin, 'node'), `#!${process.execPath}\nif(process.argv[2]==='--version')console.log('v${version}');else {Object.defineProperty(process.versions,'node',{value:'${version}'});eval(process.argv[3]);}\n`, { mode: 0o700 });
12
+ if (npmPresent) for (const name of ['npm', 'npx']) writeFileSync(join(bin, name), '#!/bin/sh\necho 10.0.0\n', { mode: 0o700 });
13
+ const result = spawnSync('/bin/bash', [resolve('scripts/setup-node.sh')], { env: { ...process.env, HOME: home, PATH: bin + ':/usr/bin:/bin' }, encoding: 'utf8' });
14
+ assert.equal(result.status, expected, result.stderr); assert.match(result.stdout, /will NOT be updated/); assert.deepEqual(readdirSync(home), [], 'Existing installations must not create a runtime, environment file, or profile entries');
15
+ });
16
+ }
@@ -0,0 +1,100 @@
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
+ });
@@ -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,25 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, mkdir, writeFile, realpath } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { loadSkill } from '../dist/skill.js';
8
+
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, process.platform === 'win32' ? 'device with spaces.md' : 'device "quoted".md'), source = '\uFEFF# Device\nCheck port 11500. Literal $(do-not-execute).\n';
11
+ await writeFile(file, source); const skill = await loadSkill(file);
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
+ });
14
+
15
+ test('skill directory resolves SKILL.md without loading unrelated files or executing scripts', async () => {
16
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'diagnose-skill-directory-'))); await mkdir(join(root, 'references')); await writeFile(join(root, 'SKILL.md'), '# Device task\nRead references/profile.md.'); await writeFile(join(root, 'references/profile.md'), 'Reference only');
17
+ const skill = await loadSkill(root); assert.equal(skill.sourceFile, join(root, 'SKILL.md')); assert.equal(skill.baseDirectory, root); assert.ok(!skill.instructions.includes('Reference only'));
18
+ });
19
+
20
+ test('skill loader rejects missing, empty, non-Markdown, non-UTF8, and oversized inputs', async () => {
21
+ await assert.rejects(loadSkill(''), /non-empty path/);
22
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'diagnose-skill-invalid-')));
23
+ await assert.rejects(loadSkill(join(root, 'missing.md')), /ENOENT/); await assert.rejects(loadSkill(root), /SKILL.md/);
24
+ for (const [name, content, error] of [['empty.md', ' \n', /empty/i], ['data.json', '{}', /Markdown/], ['binary.md', Buffer.from([255, 254, 0]), /UTF-8/], ['huge.md', Buffer.alloc(256 * 1024 + 1, 65), /256 KiB/]] as const) { const file = join(root, name); await writeFile(file, content); await assert.rejects(loadSkill(file), error); }
25
+ });