ShtukbaseStandard
файл пакета→ .shtukbase/packages/code-lib/checks/lib/review.ts

checks/lib/review.ts

93 строки, 5.1 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Builds the prompt for a reviewer agent: the active norms of the named code-* packages (with the full text of
  2. // their judges), the hints of their measured checks on the same files, and the material — a git diff or files.
  3. // It prints the prompt and runs no agent. Arguments: `--diff <range>` (default: the uncommitted changes, `git diff
  4. // HEAD`), `--staged`, or paths of files and folders to review whole.
  5. import { spawnSync } from 'node:child_process';
  6. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  7. import { posix } from 'node:path';
  8. import { parseYaml, splitFrontMatter } from '../../../collections/checks/lib/pages.ts';
  9. import { readHead } from './scan.ts';
  10. import { files as codeFiles, settings } from './scan.ts';
  11. const MAX_CHARS = 80_000;
  12. const PKGS = posix.join(import.meta.dir, '../../..'); // .shtukbase/packages/ in a project, packages/ in the standard
  13. type Action = { name: string; run: string; check?: boolean };
  14. function manifest(pkg: string): { title: string; actions: Action[] } | null {
  15. const f = posix.join(PKGS, pkg, 'package.md');
  16. if (!existsSync(f)) return null;
  17. const head = parseYaml(splitFrontMatter(readFileSync(f, 'utf8'))[0]) ?? {};
  18. return { title: String(head.title ?? pkg), actions: Array.isArray(head.actions) ? head.actions : [] };
  19. }
  20. function git(args: string[]): string {
  21. const r = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
  22. return r.status === 0 ? r.stdout : '';
  23. }
  24. /** The installed code-* packages that have norms (code-lib itself has none). */
  25. export function installedCodePackages(): string[] {
  26. if (!existsSync(PKGS)) return [];
  27. return readdirSync(PKGS).filter((d) => d.startsWith('code-') && d !== 'code-lib' && existsSync(posix.join(PKGS, d, 'package.md'))).sort();
  28. }
  29. export function review(pkgs: string[], argv: string[]): string {
  30. const root = process.cwd();
  31. let range = '';
  32. let staged = false;
  33. const paths: string[] = [];
  34. for (let k = 0; k < argv.length; k++) {
  35. if (argv[k] === '--diff') range = argv[++k] ?? '';
  36. else if (argv[k] === '--staged') staged = true;
  37. else paths.push(argv[k]);
  38. }
  39. // the material
  40. let material = '';
  41. let targets: string[] = [];
  42. if (paths.length) {
  43. const set = settings(root, 'code-lib', {});
  44. set.tests = true;
  45. targets = codeFiles(root, { ...set, exclude: [] }, paths);
  46. for (const p of paths) if (existsSync(p) && statSync(p).isFile() && !targets.includes(p)) targets.push(p);
  47. material = targets.map((f) => `=== ${f} ===\n${readFileSync(posix.join(root, f), 'utf8')}`).join('\n\n');
  48. } else {
  49. const diffArgs = staged ? ['diff', '--staged'] : ['diff', range || 'HEAD'];
  50. material = git([...diffArgs, '--unified=8']);
  51. targets = git([...diffArgs, '--name-only']).split('\n').filter((f) => f && existsSync(posix.join(root, f)));
  52. if (!material.trim()) material = '(the diff is empty: there are no changes or this is not a git repository — pass the files as paths)';
  53. }
  54. 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)`;
  55. const out: string[] = [];
  56. 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.');
  57. out.push('');
  58. 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.');
  59. for (const pkg of pkgs) {
  60. const man = manifest(pkg);
  61. if (!man) continue;
  62. out.push('', `## ${man.title} (${pkg})`, '');
  63. const dir = posix.join(root, 'norms/rules', pkg);
  64. const rules = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.md')).sort() : [];
  65. for (const f of rules) {
  66. const h = readHead(root, posix.join('norms/rules', pkg, f));
  67. if (String(h.status ?? '') !== 'active') continue;
  68. out.push(`- ${h.ruleId} [${h.level}] ${h.title}. ${h.requirement ?? ''}`.trim());
  69. for (const e of Array.isArray(h.enforcers) ? h.enforcers : [h.enforcers]) {
  70. const p = String(e ?? '');
  71. if (!/\/judges\/[^/]+\.md$/.test(p)) continue;
  72. const jf = posix.join(PKGS, pkg, 'judges', p.split('/').pop() ?? '');
  73. if (existsSync(jf)) out.push('', readFileSync(jf, 'utf8').trim().replace(/^#/gm, '###'), '');
  74. }
  75. }
  76. const hints: string[] = [];
  77. if (targets.length)
  78. for (const a of man.actions.filter((x) => x.check)) {
  79. const r = spawnSync(process.execPath, [posix.join(PKGS, pkg, a.run), ...targets], { cwd: root, encoding: 'utf8' });
  80. hints.push(...(r.stdout ?? '').split('\n').filter((l) => l && !/findings — the check only warns/.test(l)).map((l) => ` - ${a.name}: ${l}`));
  81. }
  82. out.push('', 'Findings of the checks on these files:', ...(hints.length ? hints : [' - none']));
  83. }
  84. out.push('', '## What to review', '', '```', material, '```');
  85. return out.join('\n');
  86. }