Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
5.0 KB
Raw Blame
#!/usr/bin/env bun
/**
 * Operation manifest generator: every operation's data (name, description,
 * params, scope, flags, annotations, cliHints) without its handler.
 *
 * Output: src/core/operation-manifest.generated.ts (committed). `gbrain serve`
 * builds initialize and tools/list from it and the CLI dispatcher resolves
 * commands from it, so neither loads the ~760-module handler graph behind
 * src/core/operations.ts until a call actually runs. Freshness is pinned by
 * test/operation-manifest.test.ts; tools/list byte-identity against the eager
 * registry by test/mcp-tool-list-snapshot.test.ts.
 *
 * Second output: src/core/operation-loaders.generated.ts, each operation's
 * defining module and export, so the CLI loads only the module behind the one
 * op it runs (src/core/operation-load.ts) instead of the whole registry.
 *
 * Regenerate: bun run build:operation-manifest
 */
import { readdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { operations } from '../src/core/operations.ts';
import type { Operation } from '../src/core/ops/contract.ts';

export const OPERATION_MANIFEST_PATH = join(import.meta.dir, '..', 'src', 'core', 'operation-manifest.generated.ts');

export const OPERATION_LOADERS_PATH = join(import.meta.dir, '..', 'src', 'core', 'operation-loaders.generated.ts');

const isOperation = (v: unknown): v is Operation =>
  !!v && typeof v === 'object' && typeof (v as Operation).name === 'string' && typeof (v as Operation).handler === 'function';

/** Every module that defines operations, relative to src/core, in a stable order. */
function operationModules(): string[] {
  const opsDir = join(import.meta.dir, '..', 'src', 'core', 'ops');
  return ['verbs.ts', ...readdirSync(opsDir).filter(f => f.endsWith('.ts')).sort().map(f => `ops/${f}`)];
}

export async function renderOperationLoaders(): Promise<string> {
  const definedIn = new Map<Operation, [string, string][]>();
  for (const file of operationModules()) {
    const mod: Record<string, unknown> = await import(join(import.meta.dir, '..', 'src', 'core', file));
    for (const [exportName, value] of Object.entries(mod)) {
      const ops = Array.isArray(value) && value.length > 0 && value.every(isOperation) ? value : isOperation(value) ? [value] : [];
      for (const op of ops) definedIn.set(op, [...(definedIn.get(op) ?? []), [file, exportName]]);
    }
  }
  const used = new Set<string>();
  const entries = operations.map(op => {
    const sites = definedIn.get(op) ?? [];
    if (sites.length !== 1) {
      throw new Error(`operation ${op.name} must be exported by exactly one module under src/core (found ${sites.length}: ${sites.map(s => s.join(':')).join(', ') || 'none'})`);
    }
    const [file, exportName] = sites[0]!;
    used.add(file);
    return `  ${JSON.stringify(op.name)}: [${loaderName(file)}, ${JSON.stringify(exportName)}],`;
  });
  return [
    '// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.',
    '// Regenerate: bun run build:operation-manifest',
    '// Freshness pinned by test/operation-manifest.test.ts.',
    '//',
    '// Merge conflict here? Take either side wholesale, then re-run the command above.',
    '//',
    '// Operation name -> [loader of its defining module, export holding it].',
    '// String-literal import()s so bun --compile embeds every module.',
    '',
    ...[...used].sort().map(file => `const ${loaderName(file)} = () => import('./${file}') as Promise<Record<string, unknown>>;`),
    '',
    'export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<string, unknown>>, string]> = {',
    ...entries,
    '};',
    '',
  ].join('\n');
}

function loaderName(file: string): string {
  return `load_${file.replace(/^ops\//, '').replace(/\.ts$/, '').replace(/[^a-zA-Z0-9]/g, '_')}`;
}

export function renderOperationManifest(): string {
  const meta = operations.map(({ handler: _handler, ...rest }) => rest);
  return [
    '// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.',
    '// Regenerate: bun run build:operation-manifest',
    '// Freshness pinned by test/operation-manifest.test.ts.',
    '//',
    '// Merge conflict here? Take either side wholesale, then re-run the command above.',
    '//',
    '// Every operation in src/core/operations.ts minus its handler, in registry',
    '// order. Read by the MCP stdio server (initialize, tools/list) and the CLI',
    '// dispatcher so they stay off the handler module graph until a call runs.',
    "import type { OperationMeta } from './ops/contract.ts';",
    '',
    `export const OPERATION_MANIFEST: OperationMeta[] = ${JSON.stringify(meta, null, 2)};`,
    '',
  ].join('\n');
}

if (import.meta.main) {
  const out = renderOperationManifest();
  writeFileSync(OPERATION_MANIFEST_PATH, out, 'utf-8');
  console.log(`Wrote ${OPERATION_MANIFEST_PATH} (${operations.length} operations, ${out.length} bytes).`);
  const loaders = await renderOperationLoaders();
  writeFileSync(OPERATION_LOADERS_PATH, loaders, 'utf-8');
  console.log(`Wrote ${OPERATION_LOADERS_PATH} (${loaders.length} bytes).`);
}