包文件→ .shtukbase/packages/hooks/lib/hooklib.ts
lib/hooklib.ts
153 行, 7.0 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The shared part of the hook packages: the payload Claude Code sends on stdin, the project root, the installed
- // packages with their front matter, and a run of all check actions (what `shtuk check` runs) for hooks that need it.
- // Contract of a hook script (the same as Claude Code's own command hooks): the JSON payload on stdin; exit 0 lets the
- // action through (stdout of a SessionStart hook is added to the agent's context); exit 2 blocks it, and stderr is
- // what the agent reads; any other code is a broken hook, reported and not blocking.
- import { spawnSync } from 'node:child_process';
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { extname, join, posix, relative, resolve, sep } from 'node:path';
- import { type Head, parseYaml, readPage, splitFrontMatter } from '../../collections/checks/lib/pages.ts';
- export const BUN = process.versions.bun ? process.execPath : 'bun';
- export const BLOCK = 2;
- export type Payload = Record<string, any>;
- export type Pkg = { id: string; dir: string; head: Head };
- /** The payload on stdin; null when it is not JSON (then a hook lets everything through). */
- export function readPayload(): { raw: string; p: Payload | null } {
- let raw = '';
- try {
- raw = readFileSync(0, 'utf8');
- } catch {
- return { raw, p: null };
- }
- try {
- const p = JSON.parse(raw);
- return { raw, p: p && typeof p === 'object' ? p : null };
- } catch {
- return { raw, p: null };
- }
- }
- /** The project root: CLAUDE_PROJECT_DIR, else the payload's cwd, else the working directory. */
- export function projectRoot(p: Payload | null): string {
- return resolve(process.env.CLAUDE_PROJECT_DIR || (p && typeof p.cwd === 'string' ? p.cwd : '') || process.cwd());
- }
- /** A path of the payload as an address from the project root with forward slashes; null when it is outside. */
- export function projectPath(root: string, file: unknown): string | null {
- if (typeof file !== 'string' || !file) return null;
- const rel = relative(root, resolve(root, file));
- if (!rel || rel.startsWith('..') || resolve(rel) === rel) return null;
- return rel.split(sep).join('/');
- }
- /** Installed packages: folders of .shtukbase/packages with a package.md, by id. */
- export function installedPackages(root: string): Pkg[] {
- const base = join(root, '.shtukbase', 'packages');
- if (!existsSync(base)) return [];
- const out: Pkg[] = [];
- for (const id of readdirSync(base).sort()) {
- const dir = join(base, id);
- const man = join(dir, 'package.md');
- if (!statSync(dir).isDirectory() || !existsSync(man)) continue;
- out.push({ id, dir, head: parseYaml(splitFrontMatter(readFileSync(man, 'utf8'))[0]) });
- }
- return out;
- }
- export const list = (v: unknown): any[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
- /** How a package file runs: .ts/.js/.mjs with bun, .py with python3, anything else by itself. */
- export function command(file: string): [string, string[]] {
- const ext = extname(file);
- if (['.ts', '.js', '.mjs'].includes(ext)) return [BUN, [file]];
- if (ext === '.py') return ['python3', [file]];
- return [file, []];
- }
- /** A file inside a package folder; null when the path leaves it. */
- export function inside(dir: string, rel: unknown): string | null {
- if (typeof rel !== 'string' || !rel) return null;
- const full = resolve(dir, rel);
- return full.startsWith(dir + sep) ? full : null;
- }
- /** Norm addresses in manifests are relative to the project, with an optional leading slash. */
- export function normHead(root: string, address: unknown): Head {
- const file = typeof address === 'string' ? inside(root, address.replace(/^\//, '')) : null;
- return file && existsSync(file) ? readPage(file).fm : {};
- }
- export function fileOwners(): Record<string, string | null> {
- return JSON.parse(process.env.SHTUK_OWNERS ?? '{}');
- }
- export type CheckResult = { key: string; ok: boolean; lines: string[] };
- /** Every check action of every installed package (what `shtuk check` runs), from the project root. */
- export function runChecks(root: string): CheckResult[] {
- const out: CheckResult[] = [];
- for (const pkg of installedPackages(root))
- for (const a of list(pkg.head.actions)) {
- if (!a || a.check !== true) continue;
- const key = `${pkg.id}/${a.name}`;
- const file = inside(pkg.dir, a.run);
- if (!file || !existsSync(file)) {
- out.push({ key, ok: false, lines: [`no file ${a.run}`] });
- continue;
- }
- const [exe, args] = command(file);
- const r = spawnSync(exe, args, { cwd: root, encoding: 'utf8', timeout: 60_000, stdio: ['ignore', 'pipe', 'pipe'] });
- const lines = (r.stdout ?? '').split('\n').map((l) => l.trimEnd()).filter(Boolean);
- if (r.error) lines.push(`did not start: ${r.error.message}`);
- const ok = !r.error && r.status === 0;
- if (!ok && !lines.length) lines.push(`code ${r.status}${r.stderr?.trim() ? `: ${r.stderr.trim().split('\n')[0]}` : ''}`);
- out.push({ key, ok, lines });
- }
- return out;
- }
- /** Findings of failed checks, one line each: `<package>/<action>: <line>`. */
- export function findings(results: CheckResult[]): string[] {
- return results.filter((r) => !r.ok).flatMap((r) => r.lines.map((l) => `${r.key}: ${l}`));
- }
- /** A folder for a package's runtime state (baselines and the like), outside the package's own files. */
- export function stateDir(root: string, pkg: string): string {
- return join(root, '.shtukbase', 'state', pkg);
- }
- /** The collection a project file belongs to (`/work/tasks` for `work/tasks/x.md`): the page beside its folder has
- * `type: Collection` and lies at most one folder deep — the same rule as the schema checks. Null otherwise. */
- export function collectionOf(root: string, rel: string): string | null {
- if (!rel.endsWith('.md')) return null;
- const dir = posix.dirname(rel);
- if (dir === '.' || dir.split('/').length > 2) return null;
- const page = join(root, dir + '.md');
- if (!existsSync(page)) return null;
- const head = parseYaml(splitFrontMatter(readFileSync(page, 'utf8'))[0]);
- return String(head.type ?? '').trim() === 'Collection' ? '/' + dir : null;
- }
- /** The file content a Write, Edit or MultiEdit would leave; null when it cannot be told (the tool will fail itself). */
- export function contentAfter(root: string, tool: string, input: Payload): string | null {
- const file = typeof input.file_path === 'string' ? resolve(root, input.file_path) : null;
- if (!file) return null;
- if (tool === 'Write') return typeof input.content === 'string' ? input.content : null;
- const before = existsSync(file) ? readFileSync(file, 'utf8') : '';
- const edits = tool === 'Edit' ? [input] : tool === 'MultiEdit' ? list(input.edits) : [];
- if (!edits.length) return null;
- let text = before;
- for (const e of edits) {
- if (typeof e?.old_string !== 'string' || typeof e?.new_string !== 'string') return null;
- if (e.old_string === '') {
- if (text !== '') return null;
- text = e.new_string;
- continue;
- }
- if (!text.includes(e.old_string)) return null;
- text = e.replace_all ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string);
- }
- return text;
- }