Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
q2 typing: package script, joint unit U34, 64-subset and world-v1 identity tests
garrytan30717952024c
diff --git a/scripts/q2-typing-package.ts b/scripts/q2-typing-package.tsnew file mode 100644index 0000000000..4e517789bd--- /dev/null+++ b/scripts/q2-typing-package.ts@@ -0,0 +1,111 @@+#!/usr/bin/env bun+/**+ * Build a typing-unit package ref (Q2 Track C): a local branch whose single extra commit on top of `--base` sets+ * ENABLED_TYPING_UNITS in src/core/link-typing-units.ts to the given units, in the given order. Prints the commit SHA.+ *+ * bun scripts/q2-typing-package.ts --base <ref> --units U2,U1,U5 # nested package arm (order = selection order)+ * bun scripts/q2-typing-package.ts --base <ref> --arm U2 # one-unit arm (baseline + that unit; U34 = U3 with U4)+ * bun scripts/q2-typing-package.ts --base <ref> --units none # the base with no unit (equivalence checks)+ * options: --branch <name> (default q2-typing/<base-short>/<arm-U2 | U2-U1-U5 | none>), --json+ *+ * The working tree, index and current branch are never touched (git plumbing on a temporary index). An existing+ * branch is reused only when it already points at a commit with the same parent and tree; otherwise the script+ * refuses and names the branch to delete or the --branch to pass. Measure the ref with gbrain-evals+ * `--gbrain <this checkout>@<sha>`.+ */+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { JOINT_TYPING_UNITS, parseTypingUnits, type TypingUnit } from '../src/core/link-typing-units.ts';++const UNITS_FILE = 'src/core/link-typing-units.ts';+const ENABLED_RE = /export const ENABLED_TYPING_UNITS: ReadonlySet<TypingUnit> = new Set<TypingUnit>\(\[[^\]]*\]\);/;++function fail(what: string, why: string, next: string): never {+ console.error(`${what}\nWhy: ${why}\nNext: ${next}`);+ process.exit(2);+}++function arg(argv: readonly string[], flag: string): string | undefined {+ const at = argv.indexOf(flag);+ return at >= 0 ? argv[at + 1] : undefined;+}++function git(args: string[], env: Record<string, string> = {}, input?: string): string {+ return execFileSync('git', args, { encoding: 'utf8', env: { ...process.env, ...env }, input, stdio: ['pipe', 'pipe', 'pipe'] }).trim();+}++/** The units file text with ENABLED_TYPING_UNITS set to `units` (order kept). */+export function withEnabledUnits(source: string, units: readonly TypingUnit[]): string {+ if (!ENABLED_RE.test(source)) {+ throw new Error(`${UNITS_FILE} has no "export const ENABLED_TYPING_UNITS: ReadonlySet<TypingUnit> = new Set<TypingUnit>([...]);" line to rewrite.`);+ }+ return source.replace(ENABLED_RE, `export const ENABLED_TYPING_UNITS: ReadonlySet<TypingUnit> = new Set<TypingUnit>([${units.map(u => `'${u}'`).join(', ')}]);`);+}++export function packageBranchName(baseShort: string, units: readonly TypingUnit[], arm: boolean): string {+ return `q2-typing/${baseShort}/${arm ? `arm-${units.join('')}` : units.length ? units.join('-') : 'none'}`;+}++function main(argv: readonly string[]): void {+ const base = arg(argv, '--base');+ const unitsArg = arg(argv, '--units');+ const armArg = arg(argv, '--arm');+ if (!base) fail('--base is required.', 'the package is one commit on top of a base ref (the frozen build).', 'bun scripts/q2-typing-package.ts --base <ref> --units U2,U1');+ if ((unitsArg === undefined) === (armArg === undefined)) fail('Pass exactly one of --units and --arm.', '--units builds a nested package in the given order; --arm builds a one-unit arm.', 'bun scripts/q2-typing-package.ts --base <ref> --arm U2');+ let units: TypingUnit[];+ try {+ units = armArg !== undefined ? parseTypingUnits([armArg]) : unitsArg === 'none' ? [] : parseTypingUnits(unitsArg!.split(','));+ } catch (e) {+ fail(e instanceof Error ? e.message : String(e), 'only the units declared in src/core/link-typing-units.ts exist.', 'pass a comma-separated subset of U1..U6, or --units none');+ }+ if (armArg !== undefined && armArg.includes(',')) fail(`--arm takes one unit (got "${armArg}").`, 'a unit arm is the baseline plus one unit (or one joint unit such as U34).', 'use --units for several units');+ const raw = (unitsArg ?? '').split(',').map(s => s.trim().toUpperCase()).filter(s => s && s !== 'NONE');+ if (unitsArg !== undefined && parseTypingUnits(raw).length !== raw.reduce((n, u) => n + (JOINT_TYPING_UNITS[u]?.length ?? 1), 0)) {+ fail(`--units ${unitsArg} repeats a unit.`, 'a package lists each unit once, in selection order.', 'remove the repeated unit');+ }++ let baseSha: string;+ try { baseSha = git(['rev-parse', '--verify', `${base}^{commit}`]); } catch {+ fail(`Base ${base} is not a commit in this checkout.`, 'the package commit needs its parent locally.', `git fetch origin ${base} (or pass a SHA), then rerun`);+ }+ let source: string;+ try { source = git(['show', `${baseSha}:${UNITS_FILE}`]); } catch {+ fail(`Base ${base} has no ${UNITS_FILE}.`, 'only builds with the typing units can be packaged.', 'pass a base that contains the Q2 typing units');+ }+ let next: string;+ try { next = withEnabledUnits(source, units); } catch (e) {+ fail(e instanceof Error ? e.message : String(e), 'the script rewrites exactly that line.', 'restore the ENABLED_TYPING_UNITS declaration format in the base, then rerun');+ }+ const blob = git(['hash-object', '-w', '--stdin'], {}, `${next}\n`);+ const tmp = mkdtempSync(join(tmpdir(), 'q2-typing-package-'));+ const index = { GIT_INDEX_FILE: join(tmp, 'index') };+ let tree: string;+ try {+ git(['read-tree', baseSha], index);+ git(['update-index', '--cacheinfo', `100644,${blob},${UNITS_FILE}`], index);+ tree = git(['write-tree'], index);+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+ const label = armArg !== undefined ? `arm ${units.join('+')}` : units.length ? `package ${units.join(', ')}` : 'no units';+ const branch = arg(argv, '--branch') ?? packageBranchName(baseSha.slice(0, 9), units, armArg !== undefined);+ let existing: string | null = null;+ try { existing = git(['rev-parse', '--verify', `refs/heads/${branch}`]); } catch { existing = null; }+ let sha: string;+ if (existing) {+ const [parent, existingTree] = [git(['rev-parse', `${existing}^`]), git(['rev-parse', `${existing}^{tree}`])];+ if (parent !== baseSha || existingTree !== tree) {+ fail(`Branch ${branch} already exists at ${existing.slice(0, 9)} with different content.`, 'the script never moves an existing branch.', `git branch -D ${branch} (if it is yours and unpushed), or pass --branch <new name>`);+ }+ sha = existing;+ } else {+ sha = git(['commit-tree', tree, '-p', baseSha, '-m', `q2 typing ${label}: ENABLED_TYPING_UNITS = [${units.join(', ')}]\n\nBuilt by scripts/q2-typing-package.ts on ${baseSha}.`]);+ git(['branch', branch, sha]);+ }+ if (argv.includes('--json')) console.log(JSON.stringify({ sha, branch, base: baseSha, units, kind: armArg !== undefined ? 'arm' : 'package' }));+ else console.log(`${sha}\n(${label} on ${baseSha.slice(0, 9)}, branch ${branch}${existing ? ', reused' : ''}; measure with --gbrain ${process.cwd()}@${sha})`);+}++if (import.meta.main) main(process.argv.slice(2));diff --git a/src/core/link-typing-units.ts b/src/core/link-typing-units.tsindex 9f21943836..b2342b12a9 100644--- a/src/core/link-typing-units.ts+++ b/src/core/link-typing-units.ts@@ -27,13 +27,21 @@ export function activeTypingUnits(): TypingUnit[] {return TYPING_UNITS.filter(typingUnitEnabled);}+/**+ * Joint units: ids that stand for several units measured together. U34 is U3 with U4: the development trace showed+ * U4 alone loses as-of accuracy wherever board wording still types works_at (the set-F interaction), which U3 removes+ * (docs/eval/decisions/q2-parser-gaps/dev-units.md).+ */+export const JOINT_TYPING_UNITS: Readonly<Record<string, readonly TypingUnit[]>> = { U34: ['U3', 'U4'] };+export function parseTypingUnits(units: Iterable<string>): TypingUnit[] {const out: TypingUnit[] = [];for (const raw of units) {const u = raw.trim().toUpperCase();if (!u) continue;+ if (JOINT_TYPING_UNITS[u]) { for (const j of JOINT_TYPING_UNITS[u]!) if (!out.includes(j)) out.push(j); continue; }if (!(TYPING_UNITS as readonly string[]).includes(u)) {- throw new Error(`Unknown typing unit "${raw}". The units are ${TYPING_UNITS.join(', ')} (src/core/link-typing-units.ts); pass a comma-separated subset.`);+ throw new Error(`Unknown typing unit "${raw}". The units are ${TYPING_UNITS.join(', ')} and the joint ${Object.keys(JOINT_TYPING_UNITS).join(', ')} (src/core/link-typing-units.ts); pass a comma-separated subset.`);}if (!out.includes(u as TypingUnit)) out.push(u as TypingUnit);}diff --git a/test/fixtures/q2-typing-units/world-v1-master.sha256 b/test/fixtures/q2-typing-units/world-v1-master.sha256new file mode 100644index 0000000000..e1eee5e302--- /dev/null+++ b/test/fixtures/q2-typing-units/world-v1-master.sha256@@ -0,0 +1 @@+ce8f52bd1b17f443b1ec5069e247dfba341cef1f02a9372d6722b158f42bf45bdiff --git a/test/link-typing-units-subsets.test.ts b/test/link-typing-units-subsets.test.tsnew file mode 100644index 0000000000..edd468db45--- /dev/null+++ b/test/link-typing-units-subsets.test.ts@@ -0,0 +1,40 @@+/**+ * Every subset of the typing units (2^6 = 64) passes the frozen examples (test/helpers/typing-unit-examples.ts), so+ * any package the selection procedure orders is a tested build. With no unit, extraction types the world-v1 corpus+ * byte-identically to master (digest of master c5fb0201, scripts/q2-typing-dev.ts world-v1); that check needs a+ * gbrain-evals checkout (GBRAIN_TEST_TYPING_EVALS_DIR, else ../gbrain-evals) and is skipped without one.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { extractPageLinks } from '../src/core/link-extraction.ts';+import { deriveTemporalEvidence } from '../src/core/link-temporal-evidence.ts';+import { TYPING_UNITS, withTypingUnits, type TypingUnit } from '../src/core/link-typing-units.ts';+import { loadWorldV1, worldV1Edges } from '../scripts/q2-typing-dev.ts';+import { EXAMPLES, expected, observe } from './helpers/typing-unit-examples.ts';++const subsets: TypingUnit[][] = Array.from({ length: 1 << TYPING_UNITS.length }, (_, mask) => TYPING_UNITS.filter((_, i) => mask & (1 << i)));++describe('typing units: all 64 subsets pass the frozen examples', () => {+ for (const units of subsets) {+ test(`{${units.join(',')}}`, async () => {+ await withTypingUnits(units, async () => {+ for (const ex of EXAMPLES) {+ const want = expected(ex, new Set(units));+ expect({ id: ex.id, ...(await observe(ex, want)) }).toEqual({ id: ex.id, ...want });+ }+ });+ });+ }+});++const evalsDir = resolve(process.env.GBRAIN_TEST_TYPING_EVALS_DIR ?? join(import.meta.dir, '../../gbrain-evals'));+const worldDir = join(evalsDir, 'eval/data/world-v1');+const haveWorld = existsSync(worldDir);+if (!haveWorld) console.warn(`[link-typing-units-subsets] world-v1 identity skipped: no ${worldDir}. Set GBRAIN_TEST_TYPING_EVALS_DIR to a gbrain-evals checkout to run it.`);++test.skipIf(!haveWorld)('no unit: world-v1 typing is byte-identical to master', async () => {+ const master = readFileSync(join(import.meta.dir, 'fixtures/q2-typing-units/world-v1-master.sha256'), 'utf8').trim();+ const r = await withTypingUnits([], () => worldV1Edges(loadWorldV1(worldDir), extractPageLinks as never, deriveTemporalEvidence as never));+ expect(r.sha256).toBe(master);+}, 60_000);diff --git a/test/q2-typing-package.test.ts b/test/q2-typing-package.test.tsnew file mode 100644index 0000000000..f3e5bffe7e--- /dev/null+++ b/test/q2-typing-package.test.ts@@ -0,0 +1,26 @@+/** scripts/q2-typing-package.ts: the one-line rewrite of ENABLED_TYPING_UNITS and the branch names. */+import { expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { packageBranchName, withEnabledUnits } from '../scripts/q2-typing-package.ts';+import { parseTypingUnits } from '../src/core/link-typing-units.ts';++const source = readFileSync(join(import.meta.dir, '../src/core/link-typing-units.ts'), 'utf8');++test('the package commit changes exactly the ENABLED_TYPING_UNITS line, in the given order', () => {+ const next = withEnabledUnits(source, ['U2', 'U1', 'U5']);+ const changed = next.split('\n').filter((line, i) => line !== source.split('\n')[i]);+ expect(changed).toEqual([`export const ENABLED_TYPING_UNITS: ReadonlySet<TypingUnit> = new Set<TypingUnit>(['U2', 'U1', 'U5']);`]);+ expect(withEnabledUnits(next, [])).toBe(source);+});++test('a joint unit expands in place and branch names say what the ref holds', () => {+ expect(parseTypingUnits(['U2', 'U34'])).toEqual(['U2', 'U3', 'U4']);+ expect(packageBranchName('abc123def', ['U2', 'U3', 'U4'], false)).toBe('q2-typing/abc123def/U2-U3-U4');+ expect(packageBranchName('abc123def', ['U3', 'U4'], true)).toBe('q2-typing/abc123def/arm-U3U4');+ expect(packageBranchName('abc123def', [], false)).toBe('q2-typing/abc123def/none');+});++test('a units file without the declaration is refused with what to restore', () => {+ expect(() => withEnabledUnits('export const X = 1;', ['U1'])).toThrow(/has no "export const ENABLED_TYPING_UNITS/);+});