/** Size saved benchmark methods with Perch's request and source-chunking code. */ import { createRequire } from 'node:module'; import { createInterface } from 'node:readline'; import { mkdirSync, existsSync, symlinkSync } from 'node:fs'; import { resolve, join, dirname } from 'node:path'; import { pathToFileURL } from 'node:url'; import { createHash } from 'node:crypto'; const [source, cache] = process.argv.slice(2).map(value => resolve(value)); if (!source || !cache) throw new Error('Usage: node perch-sizing.mjs PERCH_SOURCE CACHE_DIR'); mkdirSync(cache, { recursive: true }); if (!existsSync(join(cache, 'node_modules'))) symlinkSync(join(source, 'node_modules'), join(cache, 'node_modules'), 'dir'); if (!existsSync(join(dirname(cache), 'scan.yaml'))) symlinkSync(join(source, 'scan.yaml'), join(dirname(cache), 'scan.yaml')); const require = createRequire(join(source, 'package.json')); const { build } = require('esbuild'); const library = join(cache, 'perch-sizing-lib.mjs'); await build({ stdin: { contents: `export { methodSteps } from ${JSON.stringify(join(source, 'src/questions.js'))};\nexport { questionBatches, estimateTokens } from ${JSON.stringify(join(source, 'src/tokens.js'))};`, resolveDir: source, sourcefile: 'benchmark-sizing.mjs', loader: 'js', }, outfile: library, bundle: true, packages: 'external', platform: 'node', format: 'esm', logLevel: 'silent' }); const { methodSteps, questionBatches, estimateTokens } = await import(pathToFileURL(library)); function unnumber(source) { return String(source ?? '').split('\n').filter(line => !/^\.\.\. \(\d+ (?:lines above|more lines)\)$/.test(line)) .map(line => line.replace(/^L\d+\| ?/, '')).join('\n'); } function methodInput(side) { const state = side.state, method = state.method; const body = side.source ?? unnumber(method.source); const comment = method.leading_comment ?? ''; const prefix = comment ? comment.split('\n') : []; const lines = [...prefix, ...body.split('\n')]; const id = method.id ?? `${method.path}::${method.name}`; const node = { id, path: method.path, qualified_name: method.name, line: prefix.length + 1, end_line: lines.length, metrics: method.metrics }; const names = new Map([[method.name, id], [id, id]]); const neighbor = item => { const text = unnumber(item.source), firstLine = Number(String(item.source ?? '').match(/^L(\d+)\|/m)?.[1] ?? 1); const lines = text.split('\n'); const id = item.id ?? `${item.path}::${item.name}`; names.set(item.name, id); names.set(id, id); return { node: { id, path: item.path, qualified_name: item.name, line: 1, end_line: lines.length, metrics: item.metrics }, lines, ...(item.calls_method_at ? { site: Math.max(1, item.calls_method_at - firstLine + 1) } : {}), handover: item.handover ?? false }; }; const callees = (state.calls ?? []).map(neighbor), callers = (state.called_by ?? []).map(neighbor); const edges = (state.call_graph ?? []).map(edge => Array.isArray(edge) ? edge : String(edge).split(' -> ')) .filter(edge => edge.length === 2).map(edge => edge.map(name => names.get(name) ?? name)); const imports = (state.imports ?? []).map(item => { if (typeof item !== 'string') return item; const from = item.lastIndexOf(' from '); if (from < 0) throw new Error('Saved import has no module: ' + item); const target = item.slice(0, from), module = item.slice(from + 6); const as = target.lastIndexOf(' as '); const name = as < 0 ? target : target.slice(0, as); const alias = as < 0 ? name : target.slice(as + 4); return { name, alias, module }; }); return { node, lines, imports, moduleScopeText: state.module_scope ?? null, callees, callers, edges }; } function plan({ side, checks, stateBudget, requestBudget, maxQuestions }) { const target = side.source ?? unnumber(side.state.method.source); const bytes = Buffer.byteLength(target); const questions = Object.fromEntries(checks.map(check => [check.name, { type: 'choice', instructions: check.name + ': ' + check.question.instructions, criteria: check.question.criteria, }])); const limits = { state: stateBudget, single: requestBudget, request: requestBudget, questions: maxQuestions ?? Infinity, options: 2 }; let steps, leadingCommentOmitted = false; if (estimateTokens(side.state) <= stateBudget && unnumber(side.state.method.source).includes(target.trim())) steps = [{ state: side.state, covers: { start_byte: 0, end_byte: bytes } }]; else { try { steps = methodSteps({ ...methodInput(side), budget: stateBudget, asked: [] }); } catch (error) { if (error.name !== 'ContextLimitError' || !side.state.method.leading_comment) throw error; // The saved leading comment is surrounding context, outside the canonical target source. const withoutComment = { ...side, state: { ...side.state, method: { ...side.state.method, leading_comment: null } } }; steps = methodSteps({ ...methodInput(withoutComment), budget: stateBudget, asked: [] }); leadingCommentOmitted = true; } } let covered = 0; for (const step of steps) { if (step.covers.start_byte > covered) throw new Error('Source readings leave a gap in the target method'); covered = Math.max(covered, step.covers.end_byte); } if (covered !== bytes) throw new Error('Source readings do not cover the complete target method'); const readings = []; for (let index = 0; index < steps.length; index++) { const step = steps[index]; for (const batch of questionBatches(step.state, questions, limits)) readings.push({ state: step.state, question_names: Object.keys(batch), source_reading: step.state.reading ?? null, covers: step.covers ?? null, source_pass: index, source_passes: steps.length, estimated_state_tokens: estimateTokens(step.state), target_source_bytes: bytes, target_source_sha256: createHash('sha256').update(target).digest('hex'), leading_comment_omitted: leadingCommentOmitted, }); } return readings; } for await (const line of createInterface({ input: process.stdin, crlfDelay: Infinity })) { if (!line.trim()) continue; try { process.stdout.write(JSON.stringify({ readings: plan(JSON.parse(line)) }) + '\n'); } catch (error) { process.stdout.write(JSON.stringify({ error: error.message, name: error.name }) + '\n'); } }