ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/hooks/lib/hooklib.ts

lib/hooklib.ts

153 líneas, 7.0 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // The shared part of the hook packages: the payload Claude Code sends on stdin, the project root, the installed
  2. // packages with their front matter, and a run of all check actions (what `shtuk check` runs) for hooks that need it.
  3. // Contract of a hook script (the same as Claude Code's own command hooks): the JSON payload on stdin; exit 0 lets the
  4. // action through (stdout of a SessionStart hook is added to the agent's context); exit 2 blocks it, and stderr is
  5. // what the agent reads; any other code is a broken hook, reported and not blocking.
  6. import { spawnSync } from 'node:child_process';
  7. import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
  8. import { extname, join, posix, relative, resolve, sep } from 'node:path';
  9. import { type Head, parseYaml, readPage, splitFrontMatter } from '../../collections/checks/lib/pages.ts';
  10. export const BUN = process.versions.bun ? process.execPath : 'bun';
  11. export const BLOCK = 2;
  12. export type Payload = Record<string, any>;
  13. export type Pkg = { id: string; dir: string; head: Head };
  14. /** The payload on stdin; null when it is not JSON (then a hook lets everything through). */
  15. export function readPayload(): { raw: string; p: Payload | null } {
  16. let raw = '';
  17. try {
  18. raw = readFileSync(0, 'utf8');
  19. } catch {
  20. return { raw, p: null };
  21. }
  22. try {
  23. const p = JSON.parse(raw);
  24. return { raw, p: p && typeof p === 'object' ? p : null };
  25. } catch {
  26. return { raw, p: null };
  27. }
  28. }
  29. /** The project root: CLAUDE_PROJECT_DIR, else the payload's cwd, else the working directory. */
  30. export function projectRoot(p: Payload | null): string {
  31. return resolve(process.env.CLAUDE_PROJECT_DIR || (p && typeof p.cwd === 'string' ? p.cwd : '') || process.cwd());
  32. }
  33. /** A path of the payload as an address from the project root with forward slashes; null when it is outside. */
  34. export function projectPath(root: string, file: unknown): string | null {
  35. if (typeof file !== 'string' || !file) return null;
  36. const rel = relative(root, resolve(root, file));
  37. if (!rel || rel.startsWith('..') || resolve(rel) === rel) return null;
  38. return rel.split(sep).join('/');
  39. }
  40. /** Installed packages: folders of .shtukbase/packages with a package.md, by id. */
  41. export function installedPackages(root: string): Pkg[] {
  42. const base = join(root, '.shtukbase', 'packages');
  43. if (!existsSync(base)) return [];
  44. const out: Pkg[] = [];
  45. for (const id of readdirSync(base).sort()) {
  46. const dir = join(base, id);
  47. const man = join(dir, 'package.md');
  48. if (!statSync(dir).isDirectory() || !existsSync(man)) continue;
  49. out.push({ id, dir, head: parseYaml(splitFrontMatter(readFileSync(man, 'utf8'))[0]) });
  50. }
  51. return out;
  52. }
  53. export const list = (v: unknown): any[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
  54. /** How a package file runs: .ts/.js/.mjs with bun, .py with python3, anything else by itself. */
  55. export function command(file: string): [string, string[]] {
  56. const ext = extname(file);
  57. if (['.ts', '.js', '.mjs'].includes(ext)) return [BUN, [file]];
  58. if (ext === '.py') return ['python3', [file]];
  59. return [file, []];
  60. }
  61. /** A file inside a package folder; null when the path leaves it. */
  62. export function inside(dir: string, rel: unknown): string | null {
  63. if (typeof rel !== 'string' || !rel) return null;
  64. const full = resolve(dir, rel);
  65. return full.startsWith(dir + sep) ? full : null;
  66. }
  67. /** Norm addresses in manifests are relative to the project, with an optional leading slash. */
  68. export function normHead(root: string, address: unknown): Head {
  69. const file = typeof address === 'string' ? inside(root, address.replace(/^\//, '')) : null;
  70. return file && existsSync(file) ? readPage(file).fm : {};
  71. }
  72. export function fileOwners(): Record<string, string | null> {
  73. return JSON.parse(process.env.SHTUK_OWNERS ?? '{}');
  74. }
  75. export type CheckResult = { key: string; ok: boolean; lines: string[] };
  76. /** Every check action of every installed package (what `shtuk check` runs), from the project root. */
  77. export function runChecks(root: string): CheckResult[] {
  78. const out: CheckResult[] = [];
  79. for (const pkg of installedPackages(root))
  80. for (const a of list(pkg.head.actions)) {
  81. if (!a || a.check !== true) continue;
  82. const key = `${pkg.id}/${a.name}`;
  83. const file = inside(pkg.dir, a.run);
  84. if (!file || !existsSync(file)) {
  85. out.push({ key, ok: false, lines: [`no file ${a.run}`] });
  86. continue;
  87. }
  88. const [exe, args] = command(file);
  89. const r = spawnSync(exe, args, { cwd: root, encoding: 'utf8', timeout: 60_000, stdio: ['ignore', 'pipe', 'pipe'] });
  90. const lines = (r.stdout ?? '').split('\n').map((l) => l.trimEnd()).filter(Boolean);
  91. if (r.error) lines.push(`did not start: ${r.error.message}`);
  92. const ok = !r.error && r.status === 0;
  93. if (!ok && !lines.length) lines.push(`code ${r.status}${r.stderr?.trim() ? `: ${r.stderr.trim().split('\n')[0]}` : ''}`);
  94. out.push({ key, ok, lines });
  95. }
  96. return out;
  97. }
  98. /** Findings of failed checks, one line each: `<package>/<action>: <line>`. */
  99. export function findings(results: CheckResult[]): string[] {
  100. return results.filter((r) => !r.ok).flatMap((r) => r.lines.map((l) => `${r.key}: ${l}`));
  101. }
  102. /** A folder for a package's runtime state (baselines and the like), outside the package's own files. */
  103. export function stateDir(root: string, pkg: string): string {
  104. return join(root, '.shtukbase', 'state', pkg);
  105. }
  106. /** The collection a project file belongs to (`/work/tasks` for `work/tasks/x.md`): the page beside its folder has
  107. * `type: Collection` and lies at most one folder deep — the same rule as the schema checks. Null otherwise. */
  108. export function collectionOf(root: string, rel: string): string | null {
  109. if (!rel.endsWith('.md')) return null;
  110. const dir = posix.dirname(rel);
  111. if (dir === '.' || dir.split('/').length > 2) return null;
  112. const page = join(root, dir + '.md');
  113. if (!existsSync(page)) return null;
  114. const head = parseYaml(splitFrontMatter(readFileSync(page, 'utf8'))[0]);
  115. return String(head.type ?? '').trim() === 'Collection' ? '/' + dir : null;
  116. }
  117. /** The file content a Write, Edit or MultiEdit would leave; null when it cannot be told (the tool will fail itself). */
  118. export function contentAfter(root: string, tool: string, input: Payload): string | null {
  119. const file = typeof input.file_path === 'string' ? resolve(root, input.file_path) : null;
  120. if (!file) return null;
  121. if (tool === 'Write') return typeof input.content === 'string' ? input.content : null;
  122. const before = existsSync(file) ? readFileSync(file, 'utf8') : '';
  123. const edits = tool === 'Edit' ? [input] : tool === 'MultiEdit' ? list(input.edits) : [];
  124. if (!edits.length) return null;
  125. let text = before;
  126. for (const e of edits) {
  127. if (typeof e?.old_string !== 'string' || typeof e?.new_string !== 'string') return null;
  128. if (e.old_string === '') {
  129. if (text !== '') return null;
  130. text = e.new_string;
  131. continue;
  132. }
  133. if (!text.includes(e.old_string)) return null;
  134. text = e.replace_all ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string);
  135. }
  136. return text;
  137. }