vit 0.0.1 → 0.1.3

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/src/cmd/vet.js ADDED
@@ -0,0 +1,609 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 sol pbc
3
+
4
+ import { existsSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
5
+ import { execFile } from 'node:child_process';
6
+ import { join } from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ import { requireDid } from '../lib/config.js';
9
+ import { CAP_COLLECTION, SKILL_COLLECTION } from '../lib/constants.js';
10
+ import { restoreAgent } from '../lib/oauth.js';
11
+ import { appendLog, readBeaconSet, readFollowing, vitDir } from '../lib/vit-dir.js';
12
+ import { requireNotAgent, detectCodingAgent, toSandboxName } from '../lib/agent.js';
13
+ import { resolveRef, REF_PATTERN } from '../lib/cap-ref.js';
14
+ import { isSkillRef, isValidSkillRef, nameFromSkillRef } from '../lib/skill-ref.js';
15
+ import { mark, brand, name } from '../lib/brand.js';
16
+ import { resolvePds, listRecordsFromPds, batchQuery } from '../lib/pds.js';
17
+ import { loadConfig } from '../lib/config.js';
18
+ import { jsonOk, jsonError } from '../lib/json-output.js';
19
+ import { sandboxArgs } from '../lib/sandbox.js';
20
+
21
+ const execFileAsync = promisify(execFile);
22
+
23
+ const SANDBOX_SYSTEM_PROMPT = `You are a safety reviewer. Evaluate the following software capability or skill for safety concerns.
24
+
25
+ Respond with ONLY a JSON object (no markdown, no explanation outside the JSON):
26
+ {
27
+ "safe": true or false,
28
+ "concerns": ["list of specific concerns, empty if safe"],
29
+ "summary": "one-sentence safety assessment"
30
+ }
31
+
32
+ Evaluate for: malicious code patterns, data exfiltration, unauthorized access, destructive operations, obfuscated logic, and social engineering.`;
33
+
34
+ async function runSandboxEval(agentName, contentText, opts) {
35
+ const vlog = opts.json ? (...a) => console.error(...a) : console.log;
36
+ if (opts.verbose) vlog(`[verbose] sandbox: spawning ${agentName} sub-agent`);
37
+
38
+ const { cmd, args, env } = sandboxArgs(agentName, {
39
+ prompt: contentText,
40
+ systemPrompt: SANDBOX_SYSTEM_PROMPT,
41
+ });
42
+
43
+ let stdout;
44
+ try {
45
+ const result = await execFileAsync(cmd, args, {
46
+ env: { ...process.env, ...env },
47
+ timeout: 30000,
48
+ maxBuffer: 1024 * 1024,
49
+ });
50
+ stdout = result.stdout;
51
+ } catch (err) {
52
+ if (err.killed) {
53
+ throw new Error(`sandbox: ${agentName} sub-agent timed out after 30s`);
54
+ }
55
+ throw new Error(`sandbox: ${agentName} sub-agent failed: ${err.message}`);
56
+ }
57
+
58
+ if (opts.verbose) vlog(`[verbose] sandbox: raw output length ${stdout.length}`);
59
+
60
+ // Claude wraps output in a JSON envelope with a "result" field containing the text.
61
+ // Try to extract inner text from Claude's envelope first, then parse verdict.
62
+ let text = stdout.trim();
63
+ try {
64
+ const envelope = JSON.parse(text);
65
+ if (typeof envelope.result === 'string') {
66
+ text = envelope.result.trim();
67
+ }
68
+ } catch {
69
+ // Not a JSON envelope — use raw text
70
+ }
71
+
72
+ // Extract JSON from the text (may be wrapped in markdown code fences)
73
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
74
+ if (!jsonMatch) {
75
+ throw new Error('sandbox: sub-agent returned no JSON verdict');
76
+ }
77
+
78
+ let verdict;
79
+ try {
80
+ verdict = JSON.parse(jsonMatch[0]);
81
+ } catch {
82
+ throw new Error('sandbox: sub-agent returned malformed JSON verdict');
83
+ }
84
+
85
+ if (typeof verdict.safe !== 'boolean') {
86
+ throw new Error('sandbox: verdict missing "safe" field');
87
+ }
88
+ if (!Array.isArray(verdict.concerns)) {
89
+ verdict.concerns = [];
90
+ }
91
+ if (typeof verdict.summary !== 'string') {
92
+ verdict.summary = '';
93
+ }
94
+
95
+ return { safe: verdict.safe, concerns: verdict.concerns, summary: verdict.summary };
96
+ }
97
+
98
+ function resolveSandboxAgent(opts) {
99
+ if (typeof opts.sandbox === 'string') {
100
+ // Explicit agent name — validate it
101
+ const valid = new Set(['claude', 'codex', 'gemini']);
102
+ if (!valid.has(opts.sandbox)) {
103
+ throw new Error(`unknown sandbox agent: '${opts.sandbox}'. must be one of: claude, codex, gemini`);
104
+ }
105
+ return opts.sandbox;
106
+ }
107
+ // opts.sandbox === true (flag without value) — auto-detect
108
+ const detected = detectCodingAgent();
109
+ if (!detected) {
110
+ throw new Error('could not detect agent for sandbox. specify one explicitly: --sandbox claude');
111
+ }
112
+ const mapped = toSandboxName(detected.name);
113
+ if (!mapped) {
114
+ throw new Error(`detected agent '${detected.name}' has no sandbox mapping`);
115
+ }
116
+ return mapped;
117
+ }
118
+
119
+ function ensureGitignore() {
120
+ const gitignorePath = join(vitDir(), '.gitignore');
121
+ const entry = 'dangerous-accept';
122
+ if (existsSync(gitignorePath)) {
123
+ const content = readFileSync(gitignorePath, 'utf-8');
124
+ if (content.includes(entry)) return;
125
+ }
126
+ appendFileSync(gitignorePath, entry + '\n');
127
+ }
128
+
129
+ export default function register(program) {
130
+ program
131
+ .command('vet')
132
+ .argument('[ref]', 'Cap or skill reference (e.g. fast-cache-invalidation or skill-agent-test-patterns)')
133
+ .description('Review a cap or skill before trusting it')
134
+ .option('--did <did>', 'DID to use')
135
+ .option('--trust', 'Mark the item as locally trusted')
136
+ .option('--dangerous-accept', 'Permanently disable vet gate for this project (human only)')
137
+ .option('--confirm', 'Confirm dangerous-accept, or bypass agent gate with --trust')
138
+ .option('--json', 'Output as JSON')
139
+ .option('-v, --verbose', 'Show step-by-step details')
140
+ .option('--sandbox [agent]', 'Spawn a sandboxed sub-agent to evaluate safety')
141
+ .action(async (ref, opts) => {
142
+ try {
143
+ const { verbose } = opts;
144
+ const vlog = opts.json ? (...a) => console.error(...a) : console.log;
145
+ // --- dangerous-accept flow ---
146
+ if (opts.dangerousAccept) {
147
+ const gate = requireNotAgent();
148
+ if (!gate.ok) {
149
+ if (opts.json) {
150
+ jsonError('dangerous-accept is human-only');
151
+ return;
152
+ }
153
+ console.error(`${name} vet --dangerous-accept is human-only. agents cannot set this flag.`);
154
+ process.exitCode = 1;
155
+ return;
156
+ }
157
+
158
+ if (opts.confirm) {
159
+ // Write the flag file
160
+ const dir = vitDir();
161
+ const acceptPath = join(dir, 'dangerous-accept');
162
+ writeFileSync(acceptPath, JSON.stringify({ acceptedAt: new Date().toISOString() }) + '\n');
163
+ ensureGitignore();
164
+ if (opts.json) {
165
+ jsonOk({ dangerousAccept: true });
166
+ return;
167
+ }
168
+ console.log('dangerous-accept enabled for this project.');
169
+ console.log('');
170
+ console.log('agents can now remix and learn without vetting.');
171
+ console.log('to revoke: delete .vit/dangerous-accept');
172
+ } else {
173
+ if (opts.json) {
174
+ jsonOk({ dangerousAccept: false, message: 'confirm with --confirm' });
175
+ return;
176
+ }
177
+ console.log('');
178
+ console.log(' WARNING: this permanently disables the vetting safety gate for all');
179
+ console.log(' caps and skills in this project.');
180
+ console.log('');
181
+ console.log(' any agent running in this project can remix caps and learn skills');
182
+ console.log(' without human review. only do this if you trust the agent\'s judgment');
183
+ console.log(' and the network sources you follow.');
184
+ console.log('');
185
+ console.log(' to proceed, confirm: vit vet --dangerous-accept --confirm');
186
+ }
187
+ return;
188
+ }
189
+
190
+ // --- Regular vet flow: ref is required ---
191
+ if (!ref) {
192
+ if (opts.json) {
193
+ jsonError('ref argument is required', 'usage: vit vet <ref>');
194
+ return;
195
+ }
196
+ console.error('ref argument is required for vetting. usage: vit vet <ref>');
197
+ process.exitCode = 1;
198
+ return;
199
+ }
200
+
201
+ const isSkill = isSkillRef(ref);
202
+
203
+ // Validate ref format
204
+ if (isSkill) {
205
+ if (!isValidSkillRef(ref)) {
206
+ if (opts.json) {
207
+ jsonError('invalid skill ref', 'expected format: skill-{name}');
208
+ return;
209
+ }
210
+ console.error('invalid skill ref. expected format: skill-{name} (lowercase letters, numbers, hyphens)');
211
+ process.exitCode = 1;
212
+ return;
213
+ }
214
+ } else {
215
+ if (!REF_PATTERN.test(ref)) {
216
+ if (opts.json) {
217
+ jsonError('invalid ref', 'expected three lowercase words with dashes');
218
+ return;
219
+ }
220
+ console.error('invalid ref. expected three lowercase words with dashes (e.g. fast-cache-invalidation)');
221
+ process.exitCode = 1;
222
+ return;
223
+ }
224
+ }
225
+
226
+ // --- Agent gate ---
227
+ const agent = detectCodingAgent();
228
+ if (agent) {
229
+ if ((opts.trust && opts.confirm) || opts.sandbox) {
230
+ // Sandboxed sub-agent pattern — allow it
231
+ } else {
232
+ if (opts.json) {
233
+ jsonError('vit vet is for human review', 'use --trust --confirm to bypass');
234
+ return;
235
+ }
236
+ console.error('vit vet is for human review. agents should not vet directly.');
237
+ console.error('');
238
+ console.error('if you are a sandboxed sub-agent specifically tasked with vetting,');
239
+ console.error('you can bypass this gate:');
240
+ console.error('');
241
+ console.error(` vit vet ${ref} --trust --confirm`);
242
+ console.error('');
243
+ console.error('this will trust the ref without interactive review. only use this');
244
+ console.error('if you are a dedicated vetting agent running in an isolated context.');
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ }
249
+
250
+ const sandboxAgent = opts.sandbox ? resolveSandboxAgent(opts) : null;
251
+
252
+ if (opts.json && !(opts.did || loadConfig().did)) {
253
+ jsonError('no DID configured', "run 'vit login <handle>' first");
254
+ return;
255
+ }
256
+ const did = requireDid(opts);
257
+ if (!did) return;
258
+ if (verbose) vlog(`[verbose] DID: ${did}`);
259
+
260
+ if (!isSkill) {
261
+ // Cap vet requires beacon
262
+ const beaconSet = readBeaconSet();
263
+ if (beaconSet.size === 0) {
264
+ if (opts.json) {
265
+ jsonError('no beacon set', "run 'vit init' first");
266
+ return;
267
+ }
268
+ console.error(`no beacon set. run '${name} init' in a project directory first.`);
269
+ process.exitCode = 1;
270
+ return;
271
+ }
272
+ if (verbose) vlog(`[verbose] beacons: ${[...beaconSet].join(', ')}`);
273
+
274
+ const { agent: oauthAgent } = await restoreAgent(did);
275
+ if (verbose) vlog('[verbose] session restored');
276
+
277
+ // build DID list from following + self
278
+ const following = readFollowing();
279
+ const dids = following.map(e => e.did);
280
+ dids.push(did);
281
+
282
+ // fetch caps from each DID, find matching ref
283
+ const allRecords = await batchQuery(dids, async (repoDid) => {
284
+ const pds = await resolvePds(repoDid);
285
+ if (verbose) vlog(`[verbose] ${repoDid}: resolved PDS ${pds}`);
286
+ return (await listRecordsFromPds(pds, repoDid, CAP_COLLECTION, 50)).records;
287
+ }, { verbose });
288
+
289
+ let match = null;
290
+ for (const records of allRecords) {
291
+ for (const rec of records) {
292
+ if (!beaconSet.has(rec.value.beacon)) continue;
293
+ const recRef = resolveRef(rec.value, rec.cid);
294
+ if (recRef === ref) {
295
+ if (!match || (rec.value.createdAt || '') > (match.value.createdAt || '')) {
296
+ match = rec;
297
+ }
298
+ }
299
+ }
300
+ }
301
+
302
+ if (!match) {
303
+ if (opts.json) {
304
+ jsonError(`no cap found with ref '${ref}' for this beacon`);
305
+ return;
306
+ }
307
+ console.error(`no cap found with ref '${ref}' for this beacon.`);
308
+ process.exitCode = 1;
309
+ return;
310
+ }
311
+
312
+ const record = match.value;
313
+
314
+ if (opts.sandbox) {
315
+ const contentText = [
316
+ `Type: cap`,
317
+ record.title ? `Title: ${record.title}` : '',
318
+ record.description ? `Description: ${record.description}` : '',
319
+ record.text ? `\nContent:\n${record.text}` : '',
320
+ ].filter(Boolean).join('\n');
321
+
322
+ const verdict = await runSandboxEval(sandboxAgent, contentText, opts);
323
+
324
+ if (opts.trust) {
325
+ if (verdict.safe) {
326
+ appendLog('trusted.jsonl', {
327
+ ref,
328
+ uri: match.uri,
329
+ trustedAt: new Date().toISOString(),
330
+ sandboxVerdict: verdict,
331
+ });
332
+ if (opts.json) {
333
+ jsonOk({ trusted: true, ref, uri: match.uri, sandbox: verdict });
334
+ return;
335
+ }
336
+ console.log(`${mark} trusted: ${ref} (sandbox: safe)`);
337
+ return;
338
+ } else {
339
+ // Unsafe — do NOT trust
340
+ if (opts.json) {
341
+ jsonOk({ trusted: false, ref, uri: match.uri, sandbox: verdict });
342
+ process.exitCode = 1;
343
+ return;
344
+ }
345
+ console.error(`${mark} sandbox verdict: UNSAFE`);
346
+ console.error(` summary: ${verdict.summary}`);
347
+ for (const c of verdict.concerns) {
348
+ console.error(` - ${c}`);
349
+ }
350
+ console.error('');
351
+ console.error('not trusted due to safety concerns.');
352
+ process.exitCode = 1;
353
+ return;
354
+ }
355
+ }
356
+
357
+ // --sandbox without --trust: display verdict
358
+ if (opts.json) {
359
+ const author = match.uri.split('/')[2];
360
+ jsonOk({ ref, type: 'cap', author, title: record.title || '', description: record.description || '', text: record.text || '', sandbox: verdict, trusted: false });
361
+ return;
362
+ }
363
+ console.log(`${mark} sandbox verdict: ${verdict.safe ? 'SAFE' : 'UNSAFE'}`);
364
+ console.log(` summary: ${verdict.summary}`);
365
+ if (verdict.concerns.length > 0) {
366
+ for (const c of verdict.concerns) {
367
+ console.log(` - ${c}`);
368
+ }
369
+ }
370
+ return;
371
+ }
372
+
373
+ if (opts.trust) {
374
+ appendLog('trusted.jsonl', {
375
+ ref,
376
+ uri: match.uri,
377
+ trustedAt: new Date().toISOString(),
378
+ });
379
+ if (opts.json) {
380
+ jsonOk({ trusted: true, ref, uri: match.uri });
381
+ return;
382
+ }
383
+ console.log(`${mark} trusted: ${ref}`);
384
+ return;
385
+ }
386
+
387
+ const author = match.uri.split('/')[2];
388
+ const title = record.title || '';
389
+ const description = record.description || '';
390
+ const text = record.text || '';
391
+
392
+ if (opts.json) {
393
+ jsonOk({ ref, type: 'cap', author, title, description, text });
394
+ return;
395
+ }
396
+
397
+ console.log(`=== ${brand} cap review ===`);
398
+ console.log('Review this cap carefully before trusting it.');
399
+ console.log('');
400
+ console.log(` Ref: ${ref}`);
401
+ if (title) console.log(` Title: ${title}`);
402
+ console.log(` Author: ${author}`);
403
+ if (description) {
404
+ console.log('');
405
+ console.log(` ${description}`);
406
+ }
407
+ if (text) {
408
+ console.log('');
409
+ console.log('--- Text ---');
410
+ console.log(text);
411
+ console.log('---');
412
+ }
413
+ console.log('');
414
+ console.log('To trust this cap, run:');
415
+ console.log('');
416
+ console.log(` vit vet ${ref} --trust`);
417
+ } else {
418
+ // Skill vet — no beacon required
419
+ const skillName = nameFromSkillRef(ref);
420
+
421
+ const { agent: oauthAgent } = await restoreAgent(did);
422
+ if (verbose) vlog('[verbose] session restored');
423
+
424
+ const following = readFollowing();
425
+ const dids = following.map(e => e.did);
426
+ dids.push(did);
427
+
428
+ const allRecords = await batchQuery(dids, async (repoDid) => {
429
+ const pds = await resolvePds(repoDid);
430
+ if (verbose) vlog(`[verbose] ${repoDid}: resolved PDS ${pds}`);
431
+ return (await listRecordsFromPds(pds, repoDid, SKILL_COLLECTION, 50)).records;
432
+ }, { verbose });
433
+
434
+ let match = null;
435
+ for (const records of allRecords) {
436
+ for (const rec of records) {
437
+ if (rec.value.name === skillName) {
438
+ if (!match || (rec.value.createdAt || '') > (match.value.createdAt || '')) {
439
+ match = rec;
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ if (!match) {
446
+ if (opts.json) {
447
+ jsonError(`no skill found with ref '${ref}'`);
448
+ return;
449
+ }
450
+ console.error(`no skill found with ref '${ref}' from followed accounts.`);
451
+ process.exitCode = 1;
452
+ return;
453
+ }
454
+
455
+ const record = match.value;
456
+
457
+ if (opts.sandbox) {
458
+ const parts = [
459
+ `Type: skill`,
460
+ `Name: ${record.name}`,
461
+ record.description ? `Description: ${record.description}` : '',
462
+ record.text ? `\nContent:\n${record.text}` : '',
463
+ ];
464
+ if (record.resources && record.resources.length > 0) {
465
+ parts.push('\nResources:');
466
+ for (const r of record.resources) {
467
+ parts.push(` ${r.path}${r.description ? ' — ' + r.description : ''}`);
468
+ }
469
+ }
470
+ if (record.tags && record.tags.length > 0) {
471
+ parts.push(`\nTags: ${record.tags.join(', ')}`);
472
+ }
473
+ const contentText = parts.filter(Boolean).join('\n');
474
+
475
+ const verdict = await runSandboxEval(sandboxAgent, contentText, opts);
476
+
477
+ if (opts.trust) {
478
+ if (verdict.safe) {
479
+ appendLog('trusted.jsonl', {
480
+ ref,
481
+ uri: match.uri,
482
+ trustedAt: new Date().toISOString(),
483
+ sandboxVerdict: verdict,
484
+ });
485
+ if (opts.json) {
486
+ jsonOk({ trusted: true, ref, uri: match.uri, sandbox: verdict });
487
+ return;
488
+ }
489
+ console.log(`${mark} trusted: ${ref} (sandbox: safe)`);
490
+ return;
491
+ } else {
492
+ if (opts.json) {
493
+ jsonOk({ trusted: false, ref, uri: match.uri, sandbox: verdict });
494
+ process.exitCode = 1;
495
+ return;
496
+ }
497
+ console.error(`${mark} sandbox verdict: UNSAFE`);
498
+ console.error(` summary: ${verdict.summary}`);
499
+ for (const c of verdict.concerns) {
500
+ console.error(` - ${c}`);
501
+ }
502
+ console.error('');
503
+ console.error('not trusted due to safety concerns.');
504
+ process.exitCode = 1;
505
+ return;
506
+ }
507
+ }
508
+
509
+ // --sandbox without --trust: display verdict
510
+ if (opts.json) {
511
+ const author = match.uri.split('/')[2];
512
+ jsonOk({
513
+ ref, type: 'skill', name: record.name, author,
514
+ version: record.version || null, license: record.license || null,
515
+ description: record.description || null, text: record.text || null,
516
+ sandbox: verdict, trusted: false,
517
+ });
518
+ return;
519
+ }
520
+ console.log(`${mark} sandbox verdict: ${verdict.safe ? 'SAFE' : 'UNSAFE'}`);
521
+ console.log(` summary: ${verdict.summary}`);
522
+ if (verdict.concerns.length > 0) {
523
+ for (const c of verdict.concerns) {
524
+ console.log(` - ${c}`);
525
+ }
526
+ }
527
+ return;
528
+ }
529
+
530
+ if (opts.trust) {
531
+ appendLog('trusted.jsonl', {
532
+ ref,
533
+ uri: match.uri,
534
+ trustedAt: new Date().toISOString(),
535
+ });
536
+ if (opts.json) {
537
+ jsonOk({ trusted: true, ref, uri: match.uri });
538
+ return;
539
+ }
540
+ console.log(`${mark} trusted: ${ref}`);
541
+ return;
542
+ }
543
+
544
+ const author = match.uri.split('/')[2];
545
+
546
+ if (opts.json) {
547
+ jsonOk({
548
+ ref,
549
+ type: 'skill',
550
+ name: record.name,
551
+ author,
552
+ version: record.version || null,
553
+ license: record.license || null,
554
+ description: record.description || null,
555
+ text: record.text || null,
556
+ });
557
+ return;
558
+ }
559
+
560
+ console.log(`=== ${brand} skill review ===`);
561
+ console.log('Review this skill carefully before trusting it.');
562
+ console.log('');
563
+ console.log(` Ref: ${ref}`);
564
+ console.log(` Name: ${record.name}`);
565
+ console.log(` Author: ${author}`);
566
+ if (record.version) console.log(` Version: ${record.version}`);
567
+ if (record.license) console.log(` License: ${record.license}`);
568
+ if (record.description) {
569
+ console.log('');
570
+ console.log(` ${record.description}`);
571
+ }
572
+ if (record.compatibility) {
573
+ console.log('');
574
+ console.log(` Compatibility: ${record.compatibility}`);
575
+ }
576
+ if (record.text) {
577
+ console.log('');
578
+ console.log('--- SKILL.md ---');
579
+ console.log(record.text);
580
+ console.log('---');
581
+ }
582
+ if (record.resources && record.resources.length > 0) {
583
+ console.log('');
584
+ console.log('Resources:');
585
+ for (const r of record.resources) {
586
+ const desc = r.description ? ` — ${r.description}` : '';
587
+ console.log(` ${r.path}${desc}`);
588
+ }
589
+ }
590
+ if (record.tags && record.tags.length > 0) {
591
+ console.log('');
592
+ console.log(` Tags: ${record.tags.join(', ')}`);
593
+ }
594
+ console.log('');
595
+ console.log('To trust this skill, run:');
596
+ console.log('');
597
+ console.log(` vit vet ${ref} --trust`);
598
+ }
599
+ } catch (err) {
600
+ const msg = err instanceof Error ? err.message : String(err);
601
+ if (opts.json) {
602
+ jsonError(msg);
603
+ return;
604
+ }
605
+ console.error(msg);
606
+ process.exitCode = 1;
607
+ }
608
+ });
609
+ }