@masstensor/diagnose 0.5.0 → 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 (78) 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 +12 -4
  5. package/USER_GUIDE.md +178 -31
  6. package/deploy/Caddyfile +1 -1
  7. package/deploy/ecosystem.config.cjs +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +15 -5
  10. package/dist/cases.d.ts +118 -0
  11. package/dist/cases.js +115 -0
  12. package/dist/cli.js +19 -8
  13. package/dist/crypto.d.ts +7 -0
  14. package/dist/crypto.js +16 -1
  15. package/dist/discover.js +1 -1
  16. package/dist/engine.d.ts +1 -0
  17. package/dist/engine.js +12 -5
  18. package/dist/knowledge-cli.d.ts +2 -0
  19. package/dist/knowledge-cli.js +164 -0
  20. package/dist/knowledge-drafts.d.ts +47 -0
  21. package/dist/knowledge-drafts.js +76 -0
  22. package/dist/knowledge-mcp.d.ts +5 -0
  23. package/dist/knowledge-mcp.js +65 -0
  24. package/dist/mcp.d.ts +1 -1
  25. package/dist/mcp.js +27 -8
  26. package/dist/operator.d.ts +2 -0
  27. package/dist/operator.js +16 -3
  28. package/dist/peer.d.ts +9 -0
  29. package/dist/peer.js +78 -9
  30. package/dist/relay-main.js +1 -1
  31. package/dist/relay.d.ts +1 -0
  32. package/dist/relay.js +27 -4
  33. package/dist/short-pairing.d.ts +25 -0
  34. package/dist/short-pairing.js +73 -0
  35. package/dist/skill-library.d.ts +27 -0
  36. package/dist/skill-library.js +226 -0
  37. package/dist/skill.d.ts +1 -0
  38. package/dist/skill.js +1 -0
  39. package/dist/util.js +1 -0
  40. package/dist/vault-crypto.d.ts +11 -0
  41. package/dist/vault-crypto.js +30 -0
  42. package/dist/vault-server.d.ts +10 -0
  43. package/dist/vault-server.js +156 -0
  44. package/dist/vault.d.ts +19 -0
  45. package/dist/vault.js +72 -0
  46. package/npm-shrinkwrap.json +12 -2
  47. package/package.json +6 -2
  48. package/src/agent.ts +12 -5
  49. package/src/cases.ts +74 -0
  50. package/src/cli.ts +11 -7
  51. package/src/crypto.ts +14 -1
  52. package/src/discover.ts +1 -1
  53. package/src/engine.ts +9 -3
  54. package/src/knowledge-cli.ts +67 -0
  55. package/src/knowledge-drafts.ts +55 -0
  56. package/src/knowledge-mcp.ts +35 -0
  57. package/src/mcp.ts +12 -6
  58. package/src/operator.ts +10 -3
  59. package/src/peer.ts +38 -12
  60. package/src/relay-main.ts +1 -1
  61. package/src/relay.ts +18 -6
  62. package/src/short-pairing.ts +57 -0
  63. package/src/skill-library.ts +162 -0
  64. package/src/skill.ts +2 -1
  65. package/src/util.ts +1 -0
  66. package/src/vault-crypto.ts +25 -0
  67. package/src/vault-server.ts +72 -0
  68. package/src/vault.ts +51 -0
  69. package/test/agent.test.ts +26 -1
  70. package/test/cli.test.ts +3 -3
  71. package/test/knowledge-mcp.test.ts +37 -0
  72. package/test/knowledge.test.ts +112 -0
  73. package/test/mcp.test.ts +1 -1
  74. package/test/pairing.test.ts +2 -2
  75. package/test/review.test.ts +1 -0
  76. package/test/short-pairing.test.ts +100 -0
  77. package/test/skill-library.test.ts +62 -0
  78. package/test/skill.test.ts +1 -1
@@ -41,7 +41,7 @@ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} loads re
41
41
  const f = fixture(), before = readFileSync(f.settings, 'utf8');
42
42
  const result = await run(['agent', agent, '--relay', 'https://relay.example.test', '--', '--model', 'a model with spaces', 'literal $(do-not-execute)'], { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture, TEST_EXIT: '7' });
43
43
  assert.equal(result.code, 7, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
44
- assert.equal(captured.server.command, process.execPath); assert.deepEqual(captured.server.args, [cli, 'mcp', 'https://relay.example.test']); assert.equal(captured.tools.length, 11); assert.ok(captured.tools.includes('diagnose_pair')); assert.ok(captured.tools.includes('diagnose_process'));
44
+ assert.equal(captured.server.command, process.execPath); assert.deepEqual(captured.server.args, [cli, 'mcp', 'https://relay.example.test']); assert.equal(captured.tools.length, 15); assert.ok(captured.tools.includes('diagnose_pair')); assert.ok(captured.tools.includes('diagnose_process'));
45
45
  assert.deepEqual(captured.args.slice(-3), ['--model', 'a model with spaces', 'literal $(do-not-execute)']);
46
46
  assert.equal(readFileSync(f.settings, 'utf8'), before); for (const name of ['.codex', '.claude', '.gemini']) assert.equal(readFileSync(join(f.root, name, 'sentinel'), 'utf8'), 'unchanged');
47
47
  if (agent === 'gemini') { assert.equal(captured.admin.marker, 'preserve-admin-policy'); assert.equal(existsSync(captured.settingsPath), false); }
@@ -85,6 +85,20 @@ test('skill directory is accepted, and invalid skills fail before launching an a
85
85
  const conflict = await run(['agent', 'gemini', '--skill', skill, '--', '--prompt', 'another task'], env); assert.equal(conflict.code, 1); assert.match(conflict.output, /initial task/);
86
86
  });
87
87
 
88
+ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} launches a pinned library bundle through the CLI`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
89
+ const f = fixture(), source = join(f.root, 'source'); mkdirSync(source); mkdirSync(join(source, 'references'));
90
+ writeFileSync(join(source, 'SKILL.md'), '# Library task\nRead references/profile.md.'); writeFileSync(join(source, 'references/profile.md'), 'Model A');
91
+ const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
92
+ const imported = await run(['skills', 'import', 'gateway', source], env); assert.equal(imported.code, 0, imported.output);
93
+ const reference = imported.output.trim(); assert.match(reference, /^library:gateway@[a-f0-9]{64}$/);
94
+ const listed = await run(['skills', 'list'], env); assert.deepEqual(JSON.parse(listed.output), [reference]);
95
+ const launched = await run(['agent', agent, '--skill', reference], env); assert.equal(launched.code, 0, launched.output);
96
+ const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
97
+ assert.equal(captured.task.instructions, '# Library task\nRead references/profile.md.');
98
+ assert.equal(readFileSync(join(captured.task.baseDirectory, 'references/profile.md'), 'utf8'), 'Model A');
99
+ assert.ok(captured.task.baseDirectory.includes(reference.split('@')[1]));
100
+ });
101
+
88
102
  test('termination also removes the skill snapshot', { skip: process.platform === 'win32', timeout: 10000 }, async () => {
89
103
  const f = fixture(), source = join(f.root, 'task.md'); writeFileSync(source, '# Test task');
90
104
  const child = spawn(process.execPath, [cli, 'agent', 'codex', '--skill', source], { env: { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, TEST_CAPTURE: f.capture, TEST_WAIT: '1' }, stdio: 'ignore' }); const exit = new Promise<number | null>(resolveExit => child.once('close', resolveExit));
@@ -102,3 +116,14 @@ for (const agent of ['codex', 'claude', 'gemini']) test(`selected startup task r
102
116
  assert.equal(result.code, 0, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8')); assert.equal(captured.workflow.result.status, 'ok'); assert.equal(captured.workflow.outputs['1.file'], 'fixed'); assert.equal(readFileSync(target, 'utf8'), 'fixed'); assert.deepEqual(stages, ['execute', 'send']); assert.ok(!captured.args.join(' ').includes(code));
103
117
  } finally { engine.cancelAll(); host.close(); await relay.close(); }
104
118
  });
119
+
120
+ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} starts the selected case with its pinned skill`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
121
+ const { Cases } = await import('../dist/cases.js'), { SkillLibrary } = await import('../dist/skill-library.js');
122
+ const f = fixture(), source = join(f.root, 'task.md'); writeFileSync(source, '# Case procedure');
123
+ const reference = await new SkillLibrary(join(f.root, '.diagnose', 'skills')).import('gateway', source);
124
+ const selected = new Cases(join(f.root, '.diagnose', 'cases')).create({ goal: 'Check device logs', target: { name: 'Gateway', interface: 'serial' }, skill: reference });
125
+ const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
126
+ const result = await run(['agent', agent, '--case', selected.id], env); assert.equal(result.code, 0, result.output);
127
+ const captured = JSON.parse(readFileSync(f.capture, 'utf8')); assert.equal(captured.task.libraryReference, reference); assert.deepEqual(captured.server.args.slice(-2), ['--case', selected.id]);
128
+ const conflict = await run(['agent', agent, '--case', selected.id, '--skill', source], env); assert.equal(conflict.code, 1); assert.match(conflict.output, /revision differs/);
129
+ });
package/test/cli.test.ts CHANGED
@@ -17,7 +17,7 @@ test('actual host CLI displays and enforces pairing, execution and transfer prom
17
17
  let codeResolve!: (value: string) => void;
18
18
  const code = new Promise<string>(resolve => { codeResolve = resolve; });
19
19
  child.stdout.on('data', bytes => {
20
- text += bytes.toString(); const match = /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.exec(text); if (match) codeResolve(match[0]);
20
+ text += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(text); if (match) codeResolve(match[0]);
21
21
  if (!pairing && text.includes('Allow this temporary diagnostic session?')) { pairing = true; child.stdin.write('y\n'); }
22
22
  if (!executing && text.includes('Allow exactly this operation?')) { executing = true; child.stdin.write('y\n'); }
23
23
  if (!sending && text.includes('Send these results (')) { sending = true; child.stdin.write('y\n'); }
@@ -39,7 +39,7 @@ test('host CLI auto selection skips task prompts, can revoke, and requires local
39
39
  const code = new Promise<string>(resolve => { resolveCode = resolve; });
40
40
  child.stderr.resume();
41
41
  child.stdout.on('data', bytes => {
42
- output += bytes.toString(); const match = /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.exec(output); if (match) resolveCode(match[0]);
42
+ output += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(output); if (match) resolveCode(match[0]);
43
43
  if (!paired && output.includes('Allow this temporary diagnostic session?')) { paired = true; child.stdin.write('a\n'); }
44
44
  const executionCount = output.split('Allow exactly this operation?').length - 1;
45
45
  if (executionCount > executionPrompts) { executionPrompts = executionCount; child.stdin.write('n\n'); }
@@ -75,7 +75,7 @@ test('host CLI re-pairs after disconnect and resumes retained process without re
75
75
  const childHome = mkdtempSync(join(tmpdir(), 'diagnose-repair-')), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`;
76
76
  const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'repair-test', process.execPath, 'dist/cli.js', 'start', url], { detached: true, env: { ...process.env, HOME: childHome }, stdio: ['pipe', 'pipe', 'pipe'] });
77
77
  let output = '', approvals = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); const count = output.split('Allow this temporary diagnostic session?').length - 1; if (count > approvals) { approvals = count; child.stdin.write('a\n'); } });
78
- const codes = () => [...new Set(output.match(/D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/g) ?? [])];
78
+ const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
79
79
  const until = async (predicate: () => boolean) => { for (let n = 0; n < 200 && !predicate(); n++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
80
80
  let peer: Peer | undefined;
81
81
  try {
@@ -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 } }));
@@ -56,8 +56,8 @@ test('actual host survives probe and relay restarts, pauses access, and revokes
56
56
  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
57
  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
58
  try {
59
- await until(() => /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.test(output));
60
- const invitation = output.match(/D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/)![0];
59
+ await until(() => /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.test(output));
60
+ const invitation = output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/)![0];
61
61
  peer = new Peer({ role: 'join', code: invitation, relay: url, label: 'Remembered support / test AI', remember: true }); await peer.open();
62
62
  const credential = peer.rememberedCode!; assert.ok(credential); assert.notEqual(credential, invitation);
63
63
  peer.close(); await until(() => output.includes('Waiting for connections'));
@@ -67,6 +67,7 @@ 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); }
@@ -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
+ });
@@ -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
  });