// Adapted from ego lite (MIT): package/ego-browser/src/skill-package.test.mjs import { execFileSync } from 'node:child_process'; import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import type { ApiReference } from './agent-docs/api-format.js'; import { generateApiReference } from './agent-docs/api-reference.js'; import { GUIDE_END_PREFIX, GUIDE_HEADER_PREFIX, GUIDE_MAX_CHARS, renderGuide } from './agent-docs/guide.js'; import { extractCodeBlocks, typecheckBlocks } from './agent-docs/snippets.js'; import { runCli } from './cli.js'; import { UnknownOptionError } from './errors.js'; import { assertKnownOptions } from './option-keys.js'; const root = path.resolve(import.meta.dirname, '..'); const read = (file: string): string => readFileSync(path.join(root, file), 'utf8'); const readJson = (file: string): Record => JSON.parse(read(file)) as Record; const pkg = readJson('package.json') as { version: string; repository: { url: string } }; const CANONICAL = '.claude/skills/browserclaw/SKILL.md'; const COPIES = ['.agents/skills/browserclaw/SKILL.md', 'plugins/browserclaw/skills/browserclaw/SKILL.md']; const PLUGIN_MANIFESTS = ['plugins/browserclaw/plugin.json', 'plugins/browserclaw/.claude-plugin/plugin.json']; const MARKETPLACES = [ '.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', '.cursor-plugin/marketplace.json', ]; const entry = read(CANONICAL); const guide = read('docs/agent-guide.md'); const readme = read('README.md'); interface Plugin { name: string; version?: string; source: string | { source: string; path: string }; } const pluginsOf = (file: string): Plugin[] => (readJson(file) as { plugins: Plugin[] }).plugins; function section(markdown: string, heading: string): string { const start = markdown.indexOf(`${heading}\n`); if (start === -1) throw new Error(`missing section ${heading}`); const level = /^#+/.exec(heading)?.[0] ?? '#'; const rest = markdown.slice(start + heading.length + 1); const next = new RegExp(`^#{1,${String(level.length)}} `, 'm').exec(rest); return next === null ? rest : rest.slice(0, next.index); } const firstJavascriptBlock = (markdown: string): string => /```javascript\n[\s\S]*?\n```\n/.exec(markdown)?.[0] ?? ''; const normalizeRule = (line: string): string => line.replace(/^(\d+\.|-)\s+/, '').replaceAll('**', ''); function quickStart(): string { return section(readme, '### Use it from your coding agent'); } let ref: ApiReference; let dir: string; beforeAll(() => { ref = generateApiReference(root); dir = mkdtempSync(path.join(tmpdir(), 'browserclaw-agent-docs-')); writeFileSync(path.join(dir, 'guide.md'), renderGuide(guide, pkg.version)); writeFileSync(path.join(dir, 'api.json'), JSON.stringify(ref)); }, 60_000); afterAll(() => { rmSync(dir, { recursive: true, force: true }); }); function cli(args: string[]): number { return runCli(args, { guidePath: path.join(dir, 'guide.md'), apiPath: path.join(dir, 'api.json'), version: pkg.version, stdout: () => undefined, stderr: () => undefined, }); } function npxCommands(markdown: string): string[][] { const commands: string[] = []; for (const m of markdown.matchAll(/`npx browserclaw([^`]*)`/g)) commands.push(m[1]); for (const m of markdown.matchAll(/^npx browserclaw(.*)$/gm)) commands.push(m[1]); for (const m of markdown.matchAll(/Details: npx browserclaw( help [\w.]+)/g)) commands.push(m[1]); return commands.map((c) => c .trim() .split(/\s+/) .filter((arg) => arg !== '') .map((arg) => (arg === '' || arg === '' ? 'page.click' : arg)), ); } describe('agent skill copies and plugin manifests', () => { it('generated skill copies are byte-identical to the canonical entry skill', () => { for (const copy of COPIES) expect(read(copy), copy).toBe(entry); }); it('skill copies are regular files, not symlinks', () => { for (const file of [CANONICAL, ...COPIES]) { expect(lstatSync(path.join(root, file)).isFile(), file).toBe(true); expect(lstatSync(path.join(root, file)).isSymbolicLink(), file).toBe(false); expect(lstatSync(path.dirname(path.join(root, file))).isSymbolicLink(), file).toBe(false); } }); it('tags the synchronized manifests with the release', () => { const repo = mkdtempSync(path.join(dir, 'release-')); for (const file of [ 'package.json', 'scripts/sync-agent-skills.mjs', CANONICAL, ...COPIES, ...PLUGIN_MANIFESTS, ...MARKETPLACES, ]) { mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); copyFileSync(path.join(root, file), path.join(repo, file)); } const run = (cmd: string, args: string[]) => execFileSync(cmd, args, { cwd: repo, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Test', GIT_COMMITTER_NAME: 'Test', GIT_AUTHOR_EMAIL: 'test@example.org', GIT_COMMITTER_EMAIL: 'test@example.org', }, }).trim(); run('git', ['init', '--quiet']); run('git', ['add', '.']); run('git', ['commit', '-qm', 'fixture']); const version = '99.0.0-test.1'; run('npm', ['version', version, '--git-tag-version=true', '--ignore-scripts=false']); for (const file of [...PLUGIN_MANIFESTS, MARKETPLACES[0], MARKETPLACES[2]]) { expect(run('git', ['show', `v${version}:${file}`])).toContain(`"version": "${version}"`); } expect(run('git', ['status', '--porcelain'])).toBe(''); }); it('all plugin and marketplace manifests parse and use the name browserclaw', () => { for (const file of [...PLUGIN_MANIFESTS, ...MARKETPLACES]) expect(readJson(file).name, file).toBe('browserclaw'); for (const file of MARKETPLACES) expect( pluginsOf(file).map((p) => p.name), file, ).toEqual(['browserclaw']); }); it('the four manifest version fields equal package.json version', () => { const versions = [ ...PLUGIN_MANIFESTS.map((file) => readJson(file).version), pluginsOf('.claude-plugin/marketplace.json')[0]?.version, pluginsOf('.cursor-plugin/marketplace.json')[0]?.version, ]; expect(versions).toEqual([pkg.version, pkg.version, pkg.version, pkg.version]); expect(pluginsOf('.agents/plugins/marketplace.json')[0]?.version).toBeUndefined(); }); it('every marketplace source points at plugins/browserclaw and that directory has the skill', () => { for (const file of MARKETPLACES) { const [plugin] = pluginsOf(file); const sourcePath = typeof plugin.source === 'string' ? plugin.source : plugin.source.path; expect(path.normalize(sourcePath), file).toBe(path.normalize('plugins/browserclaw')); } expect(pluginsOf('.claude-plugin/marketplace.json')[0]?.source).toBe('./plugins/browserclaw'); expect(pluginsOf('.agents/plugins/marketplace.json')[0]?.source).toEqual({ source: 'local', path: './plugins/browserclaw', }); expect(existsSync(path.join(root, 'plugins/browserclaw/skills/browserclaw/SKILL.md'))).toBe(true); }); it('the plugin directory has no package.json, hooks or bin', () => { for (const name of ['package.json', 'package-lock.json', 'hooks', 'bin', 'hooks.json']) expect(existsSync(path.join(root, 'plugins/browserclaw', name)), name).toBe(false); }); it('plugin.json declares the Agent Plugins schema and a valid name', () => { const manifest = readJson('plugins/browserclaw/plugin.json'); expect(manifest.$schema).toBe('https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'); expect(manifest.name).toMatch(/^[a-z0-9.-]{1,64}$/); }); }); describe('entry skill', () => { it('frontmatter has name browserclaw and a description of at most 1024 characters', () => { const frontmatter = /^---\nname: (.+)\ndescription: (.+)\n---\n/.exec(entry); expect(frontmatter?.[1]).toBe('browserclaw'); expect(frontmatter?.[2]?.length).toBeGreaterThan(0); expect(frontmatter?.[2]?.length).toBeLessThanOrEqual(1024); }); it('entry skill is at most 3500 characters', () => { expect(entry.length).toBeLessThanOrEqual(3500); }); it('entry skill tells the agent to run npx browserclaw skill and quotes the end-line prefix', () => { expect(entry).toContain('run `npx browserclaw skill` and read all of it'); expect(entry).toContain(`\`${GUIDE_END_PREFIX} ( lines)\``); }); it('entry skill names the --path fallback and the pre-0.21 fallback path', () => { expect(entry).toContain('`npx browserclaw skill --path`'); expect(entry).toContain('`could not determine executable to run`'); expect(entry).toContain('`node_modules/browserclaw/.claude/skills/browserclaw/SKILL.md`'); }); it('entry skill tells the agent not to upgrade an existing browserclaw dependency', () => { expect(entry).toContain('Do not upgrade an existing browserclaw dependency unless the user asks'); }); it('entry skill SSRF rule names allowedHostnames', () => { const rule = entry.split('\n').find((line) => line.startsWith('- Navigation to private')); expect(rule).toContain("allowedHostnames: ['localhost']"); expect(rule).toContain( '`dangerouslyAllowPrivateNetwork: true` only when the user asks for the whole private network', ); expect(section(guide, '## Launch options')).toContain( rule?.replace(/^- Navigation to private and loopback addresses is blocked by default\. /, '') ?? '-', ); }); it("entry refs rule is identical to the guide's Key rule 2", () => { const keyRule2 = section(guide, '## Key rules') .split('\n') .find((line) => line.startsWith('2. ')); const entryRule = section(entry, '## If you cannot run the guide') .split('\n') .find((line) => line.startsWith('- Refs ')); expect(keyRule2).toBeDefined(); expect(normalizeRule(entryRule ?? '')).toBe(normalizeRule(keyRule2 ?? '')); }); it("entry example is byte-identical to the guide's first example", () => { expect(firstJavascriptBlock(entry)).not.toBe(''); expect(firstJavascriptBlock(entry)).toBe(firstJavascriptBlock(guide)); }); }); describe('agent guide', () => { it('rendered guide is within GUIDE_MAX_CHARS and starts and ends with the sentinels', () => { const rendered = renderGuide(guide, pkg.version); const lines = rendered.trimEnd().split('\n'); expect(rendered.length).toBeLessThanOrEqual(GUIDE_MAX_CHARS); expect(lines[0]).toBe(`${GUIDE_HEADER_PREFIX}${pkg.version}`); expect(lines.at(-1)).toBe(`${GUIDE_END_PREFIX}${pkg.version} (${String(lines.length)} lines)`); expect(guide.startsWith('---')).toBe(false); }); it("the guide's UnknownOptionError example matches the real message", () => { let message = ''; try { assertKnownOptions('page.click', 'e1', { timeout: 1 }); } catch (err) { if (!(err instanceof UnknownOptionError)) throw err; message = err.message; } const quoted = /`(page\.click\(\) got unknown option [^`]+)`/.exec(section(guide, '## Look up an API'))?.[1]; expect(quoted).toBe(message); }); }); describe('APIs and commands the docs name', () => { it('every page.x(, browser.x( and BrowserClaw.x( in the entry skill and the guide is a public member', () => { const names = new Set(ref.entries.map((e) => e.name)); for (const [doc, text] of [ ['entry', entry], ['guide', guide], ] as const) { const used = [...text.matchAll(/\b(page2|page|browser|BrowserClaw)\.(\w+)\(/g)].map( (m) => `${m[1] === 'page2' ? 'page' : m[1]}.${m[2]}`, ); expect(used.length, doc).toBeGreaterThan(0); for (const name of used) { const resolved = name.startsWith('BrowserClaw.') && !names.has(name) ? `browser.${name.slice(12)}` : name; expect(names.has(resolved), `${doc}: ${name}`).toBe(true); } } }); it('every npx browserclaw command in the entry skill, the guide and the README is a CLI command', () => { for (const [doc, text] of [ ['entry', entry], ['guide', guide], ['README', readme], ] as const) { const commands = npxCommands(text); expect(commands.length, doc).toBeGreaterThan(0); for (const args of commands) expect(cli(args), `${doc}: npx browserclaw ${args.join(' ')}`).toBe(0); } }); it('README quick start names commands, APIs and install lines that exist', () => { const text = quickStart(); const commands = npxCommands(text).map((args) => args.join(' ')); expect(commands).toEqual(expect.arrayContaining(['skill', 'help page.click'])); for (const args of npxCommands(text)) expect(cli(args)).toBe(0); expect(ref.entries.some((e) => e.name === 'page.click')).toBe(true); const repo = /github\.com\/([^/]+\/[^/.]+)/.exec(pkg.repository.url)?.[1]; expect(repo).toBe('idan-rubin/browserclaw'); const marketplaces = new Set(MARKETPLACES.map((file) => readJson(file).name)); const plugins = new Set(MARKETPLACES.flatMap((file) => pluginsOf(file).map((p) => p.name))); const installs = [...text.matchAll(/(?:\/plugin install|codex plugin add) ([\w-]+)@([\w-]+)/g)]; expect(installs.length).toBe(2); for (const [, plugin, marketplace] of installs) { expect(plugins.has(plugin)).toBe(true); expect(marketplaces.has(marketplace)).toBe(true); } const sources = [...text.matchAll(/(?:marketplace add|npx skills add) ([\w-]+\/[\w-]+)/g)].map((m) => m[1]); expect(sources.length).toBe(3); for (const source of sources) expect(source).toBe(repo); }); }); describe('agent doc snippets', () => { it('every ts/js block in the entry skill and the guide type-checks against the public types', () => { const blocks = [...extractCodeBlocks(entry, CANONICAL), ...extractCodeBlocks(guide, 'docs/agent-guide.md')]; const results = typecheckBlocks(blocks, root); expect(results.length).toBeGreaterThan(15); const failures = results .filter((r) => r.errors.length > 0) .map((r) => `${r.block.source}:${String(r.block.line)} ${r.errors.join('; ')}`); expect(failures).toEqual([]); }, 60_000); }); describe('repo hygiene', () => { it('bug report form requires version, node, os, browser and reproduction', () => { const form = read('.github/ISSUE_TEMPLATE/bug_report.yml'); expect(form).toMatch(/^labels: \[bug\]$/m); const items = form.split(/\n {2}- type: /).slice(1); for (const id of ['version', 'node', 'os', 'browser', 'reproduction']) { const item = items.find((i) => new RegExp(`\\n {4}id: ${id}\\n`).test(i)); expect(item, id).toBeDefined(); expect(item, id).toMatch(/validations:\n {6}required: true/); } }); });