файл пакета→ .shtukbase/packages/code-lib/checks/lib/review.ts
checks/lib/review.ts
93 строки, 5.1 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Builds the prompt for a reviewer agent: the active norms of the named code-* packages (with the full text of
- // their judges), the hints of their measured checks on the same files, and the material — a git diff or files.
- // It prints the prompt and runs no agent. Arguments: `--diff <range>` (default: the uncommitted changes, `git diff
- // HEAD`), `--staged`, or paths of files and folders to review whole.
- import { spawnSync } from 'node:child_process';
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { posix } from 'node:path';
- import { parseYaml, splitFrontMatter } from '../../../collections/checks/lib/pages.ts';
- import { readHead } from './scan.ts';
- import { files as codeFiles, settings } from './scan.ts';
- const MAX_CHARS = 80_000;
- const PKGS = posix.join(import.meta.dir, '../../..'); // .shtukbase/packages/ in a project, packages/ in the standard
- type Action = { name: string; run: string; check?: boolean };
- function manifest(pkg: string): { title: string; actions: Action[] } | null {
- const f = posix.join(PKGS, pkg, 'package.md');
- if (!existsSync(f)) return null;
- const head = parseYaml(splitFrontMatter(readFileSync(f, 'utf8'))[0]) ?? {};
- return { title: String(head.title ?? pkg), actions: Array.isArray(head.actions) ? head.actions : [] };
- }
- function git(args: string[]): string {
- const r = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
- return r.status === 0 ? r.stdout : '';
- }
- /** The installed code-* packages that have norms (code-lib itself has none). */
- export function installedCodePackages(): string[] {
- if (!existsSync(PKGS)) return [];
- return readdirSync(PKGS).filter((d) => d.startsWith('code-') && d !== 'code-lib' && existsSync(posix.join(PKGS, d, 'package.md'))).sort();
- }
- export function review(pkgs: string[], argv: string[]): string {
- const root = process.cwd();
- let range = '';
- let staged = false;
- const paths: string[] = [];
- for (let k = 0; k < argv.length; k++) {
- if (argv[k] === '--diff') range = argv[++k] ?? '';
- else if (argv[k] === '--staged') staged = true;
- else paths.push(argv[k]);
- }
- // the material
- let material = '';
- let targets: string[] = [];
- if (paths.length) {
- const set = settings(root, 'code-lib', {});
- set.tests = true;
- targets = codeFiles(root, { ...set, exclude: [] }, paths);
- for (const p of paths) if (existsSync(p) && statSync(p).isFile() && !targets.includes(p)) targets.push(p);
- material = targets.map((f) => `=== ${f} ===\n${readFileSync(posix.join(root, f), 'utf8')}`).join('\n\n');
- } else {
- const diffArgs = staged ? ['diff', '--staged'] : ['diff', range || 'HEAD'];
- material = git([...diffArgs, '--unified=8']);
- targets = git([...diffArgs, '--name-only']).split('\n').filter((f) => f && existsSync(posix.join(root, f)));
- if (!material.trim()) material = '(the diff is empty: there are no changes or this is not a git repository — pass the files as paths)';
- }
- if (material.length > MAX_CHARS) material = material.slice(0, MAX_CHARS) + `\n… (truncated: ${material.length} characters in all; give the reviewer the files in parts)`;
- const out: string[] = [];
- out.push('You are a code reviewer. Assess the change below against the code norms of this project. The norms are a retelling of schools of thought; you judge by the meaning, not by the letter.');
- out.push('');
- out.push('How to answer: for each norm, one line `<number>: holds | violated — <file:line>: what is wrong and how to fix it | not applicable`. Then a verdict in one line: "accept" or "rework" and the main thing to fix. The findings of the checks below are hints from heuristics, they may be wrong: confirm or reject each one.');
- for (const pkg of pkgs) {
- const man = manifest(pkg);
- if (!man) continue;
- out.push('', `## ${man.title} (${pkg})`, '');
- const dir = posix.join(root, 'norms/rules', pkg);
- const rules = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.md')).sort() : [];
- for (const f of rules) {
- const h = readHead(root, posix.join('norms/rules', pkg, f));
- if (String(h.status ?? '') !== 'active') continue;
- out.push(`- ${h.ruleId} [${h.level}] ${h.title}. ${h.requirement ?? ''}`.trim());
- for (const e of Array.isArray(h.enforcers) ? h.enforcers : [h.enforcers]) {
- const p = String(e ?? '');
- if (!/\/judges\/[^/]+\.md$/.test(p)) continue;
- const jf = posix.join(PKGS, pkg, 'judges', p.split('/').pop() ?? '');
- if (existsSync(jf)) out.push('', readFileSync(jf, 'utf8').trim().replace(/^#/gm, '###'), '');
- }
- }
- const hints: string[] = [];
- if (targets.length)
- for (const a of man.actions.filter((x) => x.check)) {
- const r = spawnSync(process.execPath, [posix.join(PKGS, pkg, a.run), ...targets], { cwd: root, encoding: 'utf8' });
- hints.push(...(r.stdout ?? '').split('\n').filter((l) => l && !/findings — the check only warns/.test(l)).map((l) => ` - ${a.name}: ${l}`));
- }
- out.push('', 'Findings of the checks on these files:', ...(hints.length ? hints : [' - none']));
- }
- out.push('', '## What to review', '', '```', material, '```');
- return out.join('\n');
- }