@masstensor/diagnose 0.3.0 → 0.5.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/README.md +77 -111
- package/USER_GUIDE.md +567 -0
- package/deploy/Caddyfile +15 -1
- package/dist/agent-command.d.ts +4 -0
- package/dist/agent-command.js +33 -0
- package/dist/agent.d.ts +2 -0
- package/dist/agent.js +115 -0
- package/dist/cli.js +178 -22
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +2 -0
- package/dist/engine.js +37 -4
- package/dist/history.d.ts +13 -0
- package/dist/history.js +57 -0
- package/dist/journal.d.ts +23 -1
- package/dist/journal.js +82 -5
- package/dist/maintenance.d.ts +2 -0
- package/dist/maintenance.js +46 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +21 -18
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +17 -5
- package/dist/pairing.d.ts +40 -0
- package/dist/pairing.js +92 -0
- package/dist/peer.d.ts +4 -0
- package/dist/peer.js +10 -3
- package/dist/resources.js +47 -26
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +2 -2
- package/dist/skill.d.ts +8 -0
- package/dist/skill.js +58 -0
- package/dist/transfers.js +28 -11
- package/dist/util.d.ts +2 -0
- package/dist/util.js +16 -3
- package/examples/skills/device-troubleshooting/SKILL.md +35 -0
- package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
- package/examples/skills/owon.md +27 -0
- package/npm-shrinkwrap.json +215 -5
- package/package.json +23 -5
- package/scripts/setup-node.ps1 +54 -0
- package/scripts/setup-node.sh +52 -0
- package/src/agent-command.ts +25 -0
- package/src/agent.ts +79 -0
- package/src/cli.ts +53 -20
- package/src/discover.ts +1 -1
- package/src/engine.ts +19 -4
- package/src/history.ts +43 -0
- package/src/journal.ts +41 -5
- package/src/maintenance.ts +30 -0
- package/src/mcp.ts +18 -16
- package/src/operator.ts +15 -6
- package/src/pairing.ts +64 -0
- package/src/peer.ts +6 -4
- package/src/resources.ts +35 -13
- package/src/schema.ts +4 -4
- package/src/skill.ts +44 -0
- package/src/transfers.ts +14 -3
- package/src/util.ts +14 -3
- package/test/agent.test.ts +104 -0
- package/test/pairing.test.ts +124 -0
- package/test/review.test.ts +128 -0
- package/test/setup.test.ts +16 -0
- package/test/skill.test.ts +25 -0
|
@@ -0,0 +1,128 @@
|
|
|
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
|
+
response?: (value: WireMessage) => void;
|
|
71
|
+
async send(value: WireMessage) { this.response?.(value); }
|
|
72
|
+
close(reason: string) { this.emit('closed', reason); }
|
|
73
|
+
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
|
+
test('more than 1000 sequenced tasks work and replayed sequences are rejected', { timeout: 60000 }, async () => {
|
|
76
|
+
const root = directory(), peer = new FixturePeer(); let approvals = 0;
|
|
77
|
+
new ProbeEngine(peer as unknown as Peer, async () => { approvals++; return false; }, new Audit(join(root, 'audit.jsonl')), () => {}, { idleMs: 0, lifetimeMs: 0 });
|
|
78
|
+
try {
|
|
79
|
+
for (let sequence = 1; sequence <= 1005; sequence++) {
|
|
80
|
+
const result = await peer.request(task('system.inspect', {}), sequence);
|
|
81
|
+
assert.equal(result.type === 'task.result' && result.result.status, 'denied');
|
|
82
|
+
}
|
|
83
|
+
assert.equal(approvals, 1005);
|
|
84
|
+
const repeated = await peer.request(task('system.inspect', {}), 1005);
|
|
85
|
+
assert.equal(repeated.type === 'task.result' && repeated.result.status, 'duplicate'); assert.equal(approvals, 1005);
|
|
86
|
+
} finally { peer.close('Done'); }
|
|
87
|
+
});
|
|
88
|
+
test('operator bounds completed result storage without limiting lifetime task count', async () => {
|
|
89
|
+
const peer = new FixturePeer(), operator = new Operator(peer as unknown as Peer);
|
|
90
|
+
peer.send = async value => { if (value.type === 'task.request') peer.emit('message', { type: 'task.result', id: value.task.id, result: { status: 'ok' } }); };
|
|
91
|
+
let first = '';
|
|
92
|
+
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))); }
|
|
93
|
+
await assert.rejects(operator.wait(first), /expired/); peer.close('Done');
|
|
94
|
+
});
|
|
95
|
+
test('local history retains exact task and collected results even when transfer is refused, encrypted on disk', async () => {
|
|
96
|
+
const root = directory(), peer = new FixturePeer(), audit = new Audit(join(root, 'audit.jsonl'));
|
|
97
|
+
new ProbeEngine(peer as unknown as Peer, async request => request.stage === 'execute', audit, () => {}, { idleMs: 0, lifetimeMs: 0 });
|
|
98
|
+
const request = task('process.script', { interpreter: process.execPath, script: 'console.log("PRIVATE_HISTORY_EVIDENCE")' });
|
|
99
|
+
try {
|
|
100
|
+
await peer.request(request, 1); await wait(10);
|
|
101
|
+
const value = audit.history.show(request.id) as { request: Task; outputs: Record<string, { data: string }>; events: { event: string }[] };
|
|
102
|
+
assert.deepEqual(value.request, request); assert.match(value.outputs.stdout.data, /PRIVATE_HISTORY_EVIDENCE/);
|
|
103
|
+
assert.ok(value.events.some(event => event.event === 'task.send-denied'));
|
|
104
|
+
for (const name of readdirSync(join(root, 'history'))) assert.equal(readFileSync(join(root, 'history', name)).includes(Buffer.from('PRIVATE_HISTORY_EVIDENCE')), false);
|
|
105
|
+
assert.equal(readFileSync(audit.path, 'utf8').includes('PRIVATE_HISTORY_EVIDENCE'), false);
|
|
106
|
+
assert.equal(new History(join(root, 'history')).list().length, 1);
|
|
107
|
+
cleanupLocal(0, root); assert.equal(new History(join(root, 'history')).list().length, 0);
|
|
108
|
+
} finally { peer.close('Done'); }
|
|
109
|
+
});
|
|
110
|
+
test('journal budgets prune inactive records, protect live jobs, and reject unbounded output', () => {
|
|
111
|
+
const root = directory(), limits = { maxBytes: 5000, maxEntries: 2, maxAgeMs: 86400000 }, journal = new Journal(root, limits);
|
|
112
|
+
const meta = (state: string) => ({ id: randomUUID(), kind: 'process' as const, state, createdAt: new Date().toISOString(), updatedAt: '', ownerPid: process.pid, tokenHash: '', retainOnDisconnect: false });
|
|
113
|
+
const active = meta('running'), old = meta('completed'); journal.save(active); journal.save(old); journal.append(old.id, 'stdout', Buffer.alloc(1500));
|
|
114
|
+
const next = meta('completed'); journal.save(next); assert.equal(journal.exists(old.id), false); assert.equal(journal.exists(active.id), true);
|
|
115
|
+
assert.throws(() => journal.append(active.id, 'stdout', Buffer.alloc(6000)), /quota/);
|
|
116
|
+
journal.cleanup({ ...limits, maxAgeMs: 0 }); assert.equal(journal.exists(active.id), true); assert.equal(journal.exists(next.id), false);
|
|
117
|
+
});
|
|
118
|
+
test('Windows npm command resolution preserves literal arguments without a shell', async () => {
|
|
119
|
+
const root = directory(), entry = join(root, 'node_modules', 'example', 'bin.js'); mkdirSync(join(root, 'node_modules', 'example'), { recursive: true });
|
|
120
|
+
writeFileSync(entry, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))');
|
|
121
|
+
writeFileSync(join(root, 'codex.cmd'), '@ECHO off\n"%_prog%" "%dp0%\\node_modules\\example\\bin.js" %*\n');
|
|
122
|
+
const args = ['space value', '"quoted"', '%PATH%', '!VAR!', '$(no)', '& echo NO', '{"path":"C:\\Folder name"}'];
|
|
123
|
+
const resolved = await agentCommand('codex', args, { PATH: root }, 'win32');
|
|
124
|
+
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}`))); });
|
|
125
|
+
assert.deepEqual(JSON.parse(captured), args);
|
|
126
|
+
writeFileSync(join(root, 'claude.cmd'), '@echo off\necho unsupported');
|
|
127
|
+
await assert.rejects(agentCommand('claude', [], { Path: root }, 'win32'), /Unsupported/);
|
|
128
|
+
});
|
|
@@ -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,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, '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
|
+
});
|