Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* Template-repo generator [D4, G7, A1, CX2-14].
*
* Builds the "Use this template" GitHub template-repo tree: the exact file set
* `gbrain bootstrap render` produces, with every interview value still a
* `{{TOKEN}}` placeholder. There is ONE rendering code path with two consumers
* [D4]: this generator calls the same `renderWorkspace()` engine the desktop
* bootstrap uses, in minimal/deterministic mode, then adds the two
* template-only artifacts:
*
* - `agent.json` from `TEMPLATE_PLACEHOLDER_MANIFEST` (`initialized: false` —
* the template/attach discriminator [CX2-1]).
* - A template `README.md` ("Use this template" instructions) stamped with
* the gbrain VERSION it was generated from; `bootstrap status` compares
* that stamp to the installed binary (adopter-skew check [CX-P1.11]).
*
* Byte-determinism [CX2-14]: two independent renders of the same commit are
* byte-identical. No wall-clock timestamps anywhere — the only date in the
* tree is the canonical epoch placeholder inside
* `TEMPLATE_PLACEHOLDER_MANIFEST`. CI relies on this: the release workflow
* publishes ONLY after a `diff -r` of fresh generator output against the
* vendored tree at `templates/bootstrap/template-repo/` passes, and
* `scripts/check-bootstrap-templates.sh` runs the same byte-diff OFFLINE [A1].
*
* Repo-only tooling: invoked via `scripts/generate-template-repo.ts` (CI +
* guard script). Deliberately NOT wired into src/cli.ts and NOT bundled into
* the compiled binary's command surface.
*/
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { TEMPLATE_PLACEHOLDER_MANIFEST, writeManifest } from './format.ts';
import { renderWorkspace } from './render.ts';
import { INSTALL_PIN, INSTALL_RAW_BASE } from '../install-ref.ts';
/** Stamp line contract shared with scripts/check-bootstrap-templates.sh and
* the release workflow. `{{VERSION}}` is replaced at generation time from the
* VERSION file. */
export const TEMPLATE_STAMP_PLACEHOLDER = '<!-- gbrain-template-stamp: {{VERSION}} -->';
/**
* Template-repo README, authored here (not a .template file) because it is a
* generated release artifact, not an identity file the interview fills.
* Assembled from a line array so the nested paste-block fences stay readable.
* MUST stay deterministic: no dates, no environment reads.
*/
const TEMPLATE_README_LINES: readonly string[] = [
'# gbrain agent workspace — template',
'',
TEMPLATE_STAMP_PLACEHOLDER,
'',
'This repository is the **"Use this template"** distribution artifact for a',
'[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same',
'file set `gbrain bootstrap render` produces, with every value still a',
'`{{TOKEN}}` placeholder. Nothing in this tree is real data: your agent fills the',
'placeholders from YOUR interview answers, on your machine.',
'',
'## Use this template',
'',
'1. Click **Use this template → Create a new repository**, and make the new',
' repository **Private**. The bootstrap flow refuses to put identity files in',
' a public repository.',
'2. Clone your new repository, then open Claude Code or Codex (desktop app or',
' CLI) in that folder.',
'3. Paste this into your agent:',
'',
' ```',
' Read and follow every step of:',
` ${INSTALL_RAW_BASE}/BOOTSTRAP_FOR_AGENTS.md`,
' Goal: finish setting up this cloned template as my persistent personal',
' agent, with gbrain as your memory. Interview me before writing any',
' identity file — never invent answers. You are not done until',
' `gbrain bootstrap verify` exits 0.',
' ```',
'',
' Already running the gbrain CLI',
` (\`bun install -g ${INSTALL_PIN}\`)? Then the first`,
' step is always:',
'',
' ```',
' gbrain bootstrap status',
' ```',
'',
" `bootstrap status` hard-fails while this repository's `origin` is public,",
' before any identity file lands.',
'',
"## What's in this tree",
'',
'- `agent.json` — workspace manifest with `initialized: false`; `gbrain',
' bootstrap render` flips it to `true` on your machine. That flag (never the',
" file's mere presence) is what distinguishes a fresh template clone from a",
' machine-two clone of a live workspace.',
'- Identity files (`SOUL.md`, `USER.md`, `MEMORY.md`, …) and operating',
' contracts (`AGENTS.md`, `HEARTBEAT.md`, `ACCESS_POLICY.md`, `GITHUB.md`) —',
' placeholder-only until your interview.',
'- `.gitignore` — pre-configured so the local brain database, env files, and',
' machine-local state never reach this repository.',
'',
"This README is generated by gbrain's release pipeline; edits made here are",
'overwritten on the next gbrain release. The stamp at the top records the',
'gbrain version that generated this tree — `gbrain bootstrap status` compares',
'it to your installed binary and warns on skew.',
];
/** Render the template-repo README with the version stamp filled in. Pure. */
export function renderTemplateReadme(version: string): string {
const v = version.trim();
if (!v) throw new Error('renderTemplateReadme: version must be non-empty');
return `${TEMPLATE_README_LINES.join('\n').replaceAll('{{VERSION}}', v)}\n`;
}
export interface GenerateTemplateTreeOptions {
/** Version stamp; defaults to the repo VERSION file (repo-only tooling). */
version?: string;
/** Repo root override (tests); default resolves from this module's location. */
repoRoot?: string;
}
export interface GenerateTemplateTreeResult {
outDir: string;
version: string;
/** Sorted repo-relative paths of every file written (determinism receipt). */
files: string[];
}
function readRepoVersion(repoRoot?: string): string {
const root = repoRoot ?? resolve(import.meta.dir, '..', '..', '..');
const p = join(root, 'VERSION');
if (!existsSync(p)) {
throw new Error(
`VERSION file not found at ${p} — pass opts.version explicitly (the generator is repo-only tooling)`,
);
}
return readFileSync(p, 'utf8').trim();
}
/** Recursive, sorted (LC_ALL=C-equivalent byte order), '/'-joined relative
* file listing. Exported for the determinism test's tree walk. */
export function listTreeFiles(dir: string, prefix = ''): string[] {
const out: string[] = [];
const entries = readdirSync(dir, { withFileTypes: true });
for (const e of entries) {
const rel = prefix ? `${prefix}/${e.name}` : e.name;
if (e.isDirectory()) {
if (e.name === '.git') continue; // never traverse a checkout's metadata
out.push(...listTreeFiles(join(dir, e.name), rel));
} else {
out.push(rel);
}
}
return out.sort();
}
/** Generate the full template-repo tree into `outDir`. */
export async function generateTemplateTree(
outDir: string,
opts: GenerateTemplateTreeOptions = {},
): Promise<GenerateTemplateTreeResult> {
const version = (opts.version ?? readRepoVersion(opts.repoRoot)).trim();
if (!version) throw new Error('generateTemplateTree: resolved version is empty');
mkdirSync(outDir, { recursive: true });
// 1. The shared render engine, minimal/deterministic mode: placeholder
// tokens retained, canonical provenance, no runtime state [CX2-14].
await renderWorkspace(outDir, { minimal: true });
// 2. Template manifest: initialized:false + frozen-epoch created_at.
writeManifest(outDir, TEMPLATE_PLACEHOLDER_MANIFEST);
// 3. Template README with the VERSION stamp.
writeFileSync(join(outDir, 'README.md'), renderTemplateReadme(version), 'utf8');
return { outDir, version, files: listTreeFiles(outDir) };
}