Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

q2 track C: development mechanism trace for set H's lost current employers

garrytanc84f5f2b27e2
diff --git a/docs/eval/decisions/q2-parser-gaps/dev-trace.md b/docs/eval/decisions/q2-parser-gaps/dev-trace.md
new file mode 100644
index 0000000000..5538bb6763
--- /dev/null
+++ b/docs/eval/decisions/q2-parser-gaps/dev-trace.md
@@ -0,0 +1,128 @@
+# Q2 Track C: development mechanism trace
+
+Where did set H's current employers go? On fresh development phrasings, the build that set H measured (`583a851ee`)
+loses a current employer from the default `get_links` read in two ways, and neither is the one the published summary
+suggests. A current employer whose stint resumed after an idiomatic leave is **closed** by the new leave cue because the
+restart wording is not a start cue (5 of 7 lost edges; the edge stays typed `works_at`, so the live read shows only the
+`mentions` row). A new investor spelling on one dated timeline line **attaches** to the link on the next dated line and
+outranks `works_at` by verb precedence (2 of 7). Stated types, pack rules and role priors played no part.
+
+Development data only: temporal-edges dev seeds 3 and 5, phrasing sets A, A2 and A3, and eight new phrasing files
+written for this trace (`test/fixtures/q2-dev-phrasings/`). No custodian or sealed text was read.
+
+## Setup
+
+- Builds: gbrain master `c5fb0201` (the Track C base), `583a851ee` (set H's build) and `27b1b6af` (= `780a4fc5^`, the
+ last state before the amendment-3 removal). `583a851ee` and `27b1b6af` have identical `src/core/link-extraction.ts`
+ and `src/core/link-temporal-evidence.ts`; master differs from both by exactly the `git show 780a4fc5` diff in those
+ files, so every difference below comes from the removed rules.
+- Metrics: gbrain-evals `eval/runner/temporal-edges.ts` on branch `capy/q2-parser-gaps`, `--seeds 3,5 --e5-probe
+ --pack eval/data/p3-single-value/works-at-one-per-from.yaml --single-value-pass`, with `--phrasing A|A2|A3` or a
+ development phrasing file (`--dev-phrasing-file`, patched locally the way the harness lane adds it).
+- Edge identity: `bun scripts/q2-typing-dev.ts dump` writes the same worlds through `put_page` on each build and
+ records every person page's link rows (type, source, tense, context), its `link_transitions` rows and its default
+ `get_links` read; `compare` prints type steals and transitions by identity against the generator ledger.
+
+New development phrasings (each a full `PhrasingTemplates` file):
+
+| File | Shapes |
+|---|---|
+| `role-for` | "<role> for <company>" (current, join, move) |
+| `new-chapter` | a join described as starting a new chapter |
+| `paren-move` | a move or join with the role in parentheses; "now at [X] (<role>)" |
+| `signed-on` | "signed on with [X] as <role>"; "serves as an adviser to"; split-object leave |
+| `adviser` | "is an adviser to"; "now advising [X]" |
+| `board-investor` | "took a board seat at [X] as an investor"; observer at a board meeting; advisory board |
+| `leave-start-idioms` | quitting idioms, an exchange move, "first day at", "began working at"; "traded shares of" and "first day of the [X] summit" look-alikes |
+| `onboarding` | onboarding starts, "stepped back from", "parted company with"; an onboarding call as a look-alike |
+
+## Lost current employers, by mechanism
+
+A lost edge is a current employer (ledger) that master's default `get_links` lists as `works_at` and `583a851ee`'s
+does not. 11 phrasing sets × 2 seeds, 2,552 person pages per build (232 per phrasing set, E5 probe people included).
+
+| Mechanism | Lost | Where | Detail |
+|---|---|---|---|
+| Stated type or pack rule (`link-extraction.ts` ~708) | 0 | — | no relation lines in prose renders; every base-pack rule is `ner_only` |
+| Attachment (`attachedVerb`) + `VERB_RULES` precedence | 2 | A2 s5, board-investor s5 (same person) | "…'s Series B as an angel investor" / "…as an investor" on the line before "Was hired by [Stark] as VP engineering": the new `INVESTED_RE` alternatives match, no link sits between the match and [Stark], so the match attaches, and `invested_in` outranks the `works_at` that master found after the link ("VP engineering") |
+| Role prior | 0 | — | |
+| Temporal evidence | 5 | onboarding s3 ×2, s5 ×3 | a rejoined current stint: "Parted company with [X]" or "Stepped back from [X]" (new end cues) dates the earlier exit, the later restart "Onboarding week at [X] as …" is not a start cue on any build, so the relationship stays closed. Master recognized neither, so the edge stayed undated and live. The end transitions are correct by identity; the missing restart is missing on both builds |
+| Live-read visibility of an unchanged edge | 0 | — | |
+
+Every "lost" edge shows up in the live read of `583a851ee` as a `mentions` row only, which is how the published summary
+("typed `mentions` where master typed `works_at`") reads when seen from `get_links`. On development text, 5 of 7 are a
+temporal closure, not a typing change.
+
+## Type steals and transitions by identity (583a851ee vs master)
+
+A steal is a person→company pair where the build drops a type the ledger supports or adds one it does not.
+
+| Phrasing | Steals | Gains | New wrong transitions | Correct transitions fixed | Missing correct | Live lost / gained |
+|---|---|---|---|---|---|---|
+| A | 0 | 0 | 0 | 0 | 0 | 0 / 0 |
+| A2 | 8 | 37 | 0 | 29 | 1 | 1 / 0 |
+| A3 | 0 | 85 | 0 | 81 | 0 | 0 / 69 |
+| role-for | 0 | 0 | 0 | 0 | 0 | 0 / 0 |
+| new-chapter | 0 | 24 | 0 | 24 | 0 | 0 / 0 |
+| paren-move | 0 | 0 | 0 | 0 | 0 | 0 / 0 |
+| signed-on | 0 | 0 | 0 | 35 | 0 | 0 / 0 |
+| adviser | 0 | 52 | 0 | 0 | 0 | 0 / 0 |
+| board-investor | 23 | 0 | 0 | 0 | 1 | 1 / 0 |
+| leave-start-idioms | 0 | 0 | 0 | 300 | 0 | 0 / 0 |
+| onboarding | 0 | 24 | 0 | 198 | 0 | 5 / 0 |
+
+The 31 steals, by cause:
+
+| Cause | Pairs | Ledger relation of the pair |
+|---|---|---|
+| investor spelling ("as an angel investor", "as an investor") on another dated line attaches across the line break | 16 | advisee 10, current employer 6 |
+| observer or board wording ("…board meeting as an observer") types `invested_in` | 15 | former employer (an alumni-trap line) 15 |
+
+The three published set-H shapes did not reproduce a loss: "<role> for <company>", "(<role>)" after a move and most
+"new chapter" joins type `mentions` on **both** builds (live recall 0.640, 0.597 and 0.597 on master and `583a851ee`
+alike), because the removed `ROLE_AT_RE` reads "<role> at" and "as <role>", not "for" or parentheses. They are recall
+gaps, not regressions.
+
+Runner metrics that moved (seeds 3 and 5; master → `583a851ee`):
+
+| Phrasing | live recall | as-of exact | advisor traps | investment traps | alumni traps | E5 extra starts | E5 wrong closures |
+|---|---|---|---|---|---|---|---|
+| A | 0.871 → 0.871 | 0.933 → 0.933 | 28/28 | 26/26 | 20/20 | 48 → 0 | 24 → 0 |
+| A2 | 0.827 → 0.820 | 0.892 → 0.900 | 28/28 | 26/26 | 20/20 | 48 → 0 | 24 → 0 |
+| A3 | 0.633 → 0.827 | 0.648 → 0.790 | 28/28 | 26/26 | 20/20 | 21 → 0 | 8 → 0 |
+| signed-on | 0.583 → 0.583 | 0.579 → 0.612 | 0/28 → 0/28 | 22 → 26/26 | 18 → 20/20 | 16 → 0 | 7 → 0 |
+| adviser | 0.871 → 0.871 | 0.883 → 0.915 | 0/28 → 28/28 | 26/26 | 20/20 | 48 → 0 | 24 → 0 |
+| board-investor | 0.871 → 0.863 | 0.933 → 0.929 | 28/28 | 26/26 | 20/20 | 72 → 0 | 36 → 0 |
+| leave-start-idioms | 0.871 → 0.871 | 0.750 → 0.863 | 28/28 | 17 → 20/26 | 14 → 19/20 | 0 → 0 | 0 → 0 |
+| onboarding | 0.633 → 0.597 | 0.598 → 0.698 | 28/28 | 17 → 26/26 | 14 → 20/20 | 0 → 0 | 0 → 0 |
+
+`583a851ee` also applied 5 single-value closures on leave-start-idioms (`sv_wrong_closures` 0 → 5/160).
+
+## What the units change because of this
+
+- **U3** adds no investor or observer spelling to `INVESTED_RE`. Its only typing changes are suppressions (board,
+ observer and investor wording never types `works_at`; "board seat at" keeps `invested_in` only with an investor
+ prior), so it cannot produce the cross-line `invested_in` steal. Observer wording stays `mentions`.
+- **U5** (leave idioms and exchange moves) gets a restart guard: an end it adds is dropped when a later dated line
+ refers to the same organization in plain words that no cue reads (a possible unrecognized rejoin), outside event and
+ qualified lines. Without it, U5 reproduces the onboarding losses.
+- **U6** covers the restart framings the trace found ("onboarding week at", "onboarded at", "first day at", "began
+ working at", "kicked off a new role at", "a new chapter at").
+- **U2** targets the shapes that were recall gaps on every build ("<role> for", "(<role>)" after the link, "as <role>"
+ after a join, move, sign-on or new chapter), on the link's own line only, so a role on another timeline line never
+ attaches.
+- **U1** carries the `adviser` spelling and "advising [X]"; the signed-on and adviser sets show master at 0/28 advisor
+ traps for those spellings.
+- **U3/U4 dependency:** see `dev-units.md` (board-director development phrasing). The trace above has no board line that
+ master types `works_at`, so it cannot show the set-F interaction by itself.
+
+Reproduce (from a gbrain checkout with gbrain-evals beside it):
+
+```bash
+bun eval/runner/temporal-edges.ts --gbrain ../gbrain@583a851ee --seeds 3,5 --e5-probe \
+ --pack eval/data/p3-single-value/works-at-one-per-from.yaml --single-value-pass \
+ --dev-phrasing-file ../gbrain/test/fixtures/q2-dev-phrasings/onboarding.json --output /tmp/te # in gbrain-evals
+bun scripts/q2-typing-dev.ts dump --evals ../gbrain-evals --root ../gbrain-evals/.gbrain-overlays/583a851ee \
+ --phrasing test/fixtures/q2-dev-phrasings/onboarding.json --out /tmp/583.json # in gbrain
+bun scripts/q2-typing-dev.ts compare --base /tmp/master.json --arm /tmp/583.json
+```
diff --git a/scripts/q2-typing-dev.ts b/scripts/q2-typing-dev.ts
new file mode 100644
index 0000000000..8843018767
--- /dev/null
+++ b/scripts/q2-typing-dev.ts
@@ -0,0 +1,289 @@
+#!/usr/bin/env bun
+/**
+ * Q2 typing units: development dumps and identity tables (development data only).
+ *
+ * bun scripts/q2-typing-dev.ts dump --evals <gbrain-evals checkout> --root <gbrain tree> \
+ * --phrasing A|A2|A3|<dev phrasing JSON> [--seeds 3,5] [--units U1,U2|none] --out <dump.json>
+ * bun scripts/q2-typing-dev.ts compare --base <dump.json> --arm <dump.json> [--json]
+ * bun scripts/q2-typing-dev.ts world-v1 --evals <gbrain-evals checkout> --root <gbrain tree> [--units U1,U2|none] [--out <edges.json>]
+ *
+ * `dump` renders the temporal-edges world (gbrain-evals eval/generators/temporal-edges-gen.ts, E5 probe people
+ * included) for each development seed, writes every page through `put_page` on in-memory PGLite using the gbrain
+ * tree at `--root` (a checkout, a worktree or a gbrain-evals overlay), and records per person page: the derived link
+ * rows (type, source, tense, context), the link_transitions rows, and what a default `get_links` returns.
+ * `--units` (only for a tree that has src/core/link-typing-units.ts) runs with that typing-unit set instead of
+ * ENABLED_TYPING_UNITS.
+ *
+ * `compare` prints the type-steal and transition tables by identity (subject, target, type, kind, date) against the
+ * generator ledger: edges whose type moved away from (or toward) the ledger, new wrong transitions, fixed and missing
+ * correct transitions, and current employers lost from or added to the live read.
+ *
+ * `world-v1` types gbrain-evals' world-v1 corpus (eval/data/world-v1, rendered as the P5 H1 runner renders it) with
+ * extractPageLinks and deriveTemporalEvidence of the tree at `--root` and prints the SHA-256 of the sorted edge and
+ * transition lines; two trees (or unit sets) type the corpus identically exactly when the digests match.
+ *
+ * Hermetic: provider keys are removed from the environment and GBRAIN_HOME is a fresh temp dir; zero LLM calls.
+ * Held-out (custody) phrasing files are refused: the phrasing JSON must live inside this repository's
+ * test/fixtures/q2-dev-phrasings/.
+ */
+import { createHash } from 'node:crypto';
+import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+type Row = Record<string, unknown>;
+
+interface Ledger {
+ slug: string;
+ stints: Array<{ company: string; from: string; until: string | null; role: string }>;
+ advises: { company: string; from: string } | null;
+ invests_after_exit: { company: string; on: string } | null;
+ alumni_meeting: { company: string; on: string } | null;
+ e5?: { advisory_target: string; advisory_on: string; form: string; target: string };
+}
+
+export interface PersonDump {
+ seed: number;
+ slug: string;
+ ledger: Ledger;
+ links: Array<{ to: string; type: string; source: string | null; tense: string | null; context: string }>;
+ transitions: Array<{ from: string; to: string; type: string; kind: string; on: string; producer: string }>;
+ live: Array<{ to: string; type: string }>;
+}
+
+export interface Dump { root: string; units: string[] | null; phrasing: string; seeds: number[]; people: PersonDump[] }
+
+function arg(argv: readonly string[], flag: string): string | undefined {
+ const at = argv.indexOf(flag);
+ return at >= 0 ? argv[at + 1] : undefined;
+}
+
+function fail(what: string, why: string, next: string): never {
+ console.error(`${what}\nWhy: ${why}\nNext: ${next}`);
+ process.exit(2);
+}
+
+function hermetic(): void {
+ for (const k of Object.keys(process.env)) if (/(_API_KEY|_API_TOKEN|_BEARER_TOKEN)$|^(TYPESAFE|JEV)_/.test(k)) delete process.env[k];
+ process.env.GBRAIN_HOME = mkdtempSync(join(tmpdir(), 'q2-typing-dev-'));
+}
+
+async function dump(argv: readonly string[]): Promise<void> {
+ const evals = arg(argv, '--evals');
+ const root = arg(argv, '--root');
+ const out = arg(argv, '--out');
+ const phrasingArg = arg(argv, '--phrasing') ?? 'A';
+ if (!evals || !root || !out) fail('dump needs --evals, --root and --out.', 'the world comes from gbrain-evals and the build under test from --root.', 'bun scripts/q2-typing-dev.ts dump --evals ../gbrain-evals --root . --phrasing A --out /tmp/a.json');
+ const seeds = (arg(argv, '--seeds') ?? '3,5').split(',').map(Number);
+ if (!seeds.every(s => [3, 5].includes(s))) fail(`seeds ${seeds.join(',')} refused.`, 'only the temporal-edges development seeds 3 and 5 run here; held-out seeds belong to the custodian.', 'pass --seeds 3,5');
+ hermetic();
+ const gen = await import(join(resolve(evals!), 'eval/generators/temporal-edges-gen.ts'));
+ let phrasing: Record<string, unknown>;
+ if (['A', 'A2', 'A3'].includes(phrasingArg)) phrasing = { phrasing: phrasingArg };
+ else {
+ const file = resolve(phrasingArg);
+ if (!file.startsWith(resolve(import.meta.dir, '../test/fixtures/q2-dev-phrasings/'))) {
+ fail(`phrasing file ${phrasingArg} refused.`, 'only development phrasings under test/fixtures/q2-dev-phrasings/ run here; custody files never enter this tree.', 'pass A, A2, A3 or a file from test/fixtures/q2-dev-phrasings/');
+ }
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { id: string; templates: unknown };
+ phrasing = { sealedPhrasing: { id: `dev:${parsed.id}`, templates: gen.validatePhrasing(parsed.templates) } };
+ }
+ const rootAbs = resolve(root!);
+ const unitsArg = arg(argv, '--units');
+ let units: string[] | null = null;
+ if (unitsArg !== undefined) {
+ const mod = await import(join(rootAbs, 'src/core/link-typing-units.ts')).catch(() => null);
+ if (!mod) fail(`--units refused for ${rootAbs}.`, 'that tree has no src/core/link-typing-units.ts.', 'drop --units, or point --root at a tree with the typing units');
+ units = unitsArg === 'none' ? [] : unitsArg.split(',').map(s => s.trim()).filter(Boolean);
+ mod.setTypingUnitsForTests(units);
+ }
+ const { PGLiteEngine } = await import(join(rootAbs, 'src/core/pglite-engine.ts'));
+ const { operations } = await import(join(rootAbs, 'src/core/operations.ts'));
+ const byName = new Map((operations as Array<{ name: string; handler: (ctx: unknown, p: Row) => Promise<unknown> }>).map(o => [o.name, o]));
+ const people: PersonDump[] = [];
+ for (const seed of seeds) {
+ const world = gen.generateTemporalEdgesWorld({ seed, e5Probe: true, ...phrasing });
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const logger = { info() {}, warn() {}, error() {}, debug() {} };
+ const ctx = { engine, config: { engine: 'pglite', database_path: ':memory:' }, logger, dryRun: false, remote: false, sourceId: 'default' };
+ const op = (name: string, p: Row) => byName.get(name)!.handler(ctx, p);
+ for (const page of world.pages as Array<{ slug: string; content: string }>) {
+ const snap = await engine.readPageSnapshot(page.slug, { sourceId: 'default' });
+ await op('put_page', { slug: page.slug, content: page.content, ...(snap ? { expected_revision: snap.revision } : {}) });
+ }
+ const ledgers: Ledger[] = [...world.people, ...(world.e5_probes ?? [])];
+ for (const p of ledgers) {
+ const links = await engine.executeRaw(
+ `SELECT t.slug AS to, l.link_type AS type, l.link_source AS source, l.assertion_tense AS tense, l.context
+ FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE f.slug = $1 ORDER BY t.slug, l.link_type`, [p.slug]) as PersonDump['links'];
+ const transitions = await engine.executeRaw(
+ `SELECT f.slug AS from, t.slug AS to, lt.link_type AS type, lt.kind, lt.occurred_on::text AS on, lt.producer
+ FROM link_transitions lt JOIN pages o ON o.id = lt.origin_page_id JOIN pages f ON f.id = lt.from_page_id JOIN pages t ON t.id = lt.to_page_id
+ WHERE o.slug = $1 ORDER BY lt.occurred_on, t.slug, lt.kind`, [p.slug]) as PersonDump['transitions'];
+ const live = ((await op('get_links', { slug: p.slug })) as Row[]).map(r => ({ to: String(r.to_slug), type: String(r.link_type) }));
+ people.push({ seed, slug: p.slug, ledger: { slug: p.slug, stints: p.stints, advises: p.advises, invests_after_exit: p.invests_after_exit, alumni_meeting: p.alumni_meeting, ...(p.e5 ? { e5: p.e5 } : {}) }, links, transitions, live });
+ }
+ await engine.disconnect();
+ }
+ const result: Dump = { root: rootAbs, units, phrasing: phrasingArg, seeds, people };
+ writeFileSync(out!, JSON.stringify(result));
+ console.log(`dump: ${people.length} person pages, ${seeds.length} seed(s), units ${units ? units.join(',') || 'none' : 'build default'} -> ${out}`);
+}
+
+/** Gold relation types for a person -> target pair from the ledger alone (an E5 "other" target is also asserted as works_at). */
+export function goldTypes(l: Ledger, target: string): Set<string> {
+ const out = new Set<string>();
+ if (l.stints.some(s => s.company === target) || (l.e5?.target === 'other' && l.e5.advisory_target === target)) out.add('works_at');
+ if (l.advises?.company === target || l.e5?.advisory_target === target) out.add('advises');
+ if (l.invests_after_exit?.company === target) out.add('invested_in');
+ return out;
+}
+
+/** Gold transitions by identity (subject, target, type, kind, date). */
+export function goldTransitions(l: Ledger): Set<string> {
+ const out = new Set<string>();
+ for (const s of l.stints) {
+ out.add(tid(l.slug, s.company, 'works_at', 'start', s.from));
+ if (s.until) out.add(tid(l.slug, s.company, 'works_at', 'end', s.until));
+ }
+ if (l.advises) out.add(tid(l.slug, l.advises.company, 'advises', 'start', l.advises.from));
+ if (l.e5) out.add(tid(l.slug, l.e5.advisory_target, 'advises', 'start', l.e5.advisory_on));
+ return out;
+}
+
+const tid = (subject: string, target: string, type: string, kind: string, on: string) => [subject, target, type, kind, on.slice(0, 10)].join(' | ');
+const typesOf = (p: PersonDump, to: string) => new Set(p.links.filter(x => x.to === to && x.type !== 'mentions').map(x => x.type));
+const show = (xs: Set<string>) => [...xs].sort().join('+') || 'mentions';
+const role = (l: Ledger, to: string) => {
+ const cur = l.stints.some(s => s.company === to && s.until === null);
+ if (cur) return 'current employer';
+ if (l.stints.some(s => s.company === to)) return 'former employer';
+ if (l.advises?.company === to) return 'advisee';
+ if (l.e5?.advisory_target === to) return 'e5 advisory target';
+ return 'no ledger relation';
+};
+
+export function compareDumps(base: Dump, arm: Dump) {
+ const key = (p: PersonDump) => `${p.seed}:${p.slug}`;
+ const armBy = new Map(arm.people.map(p => [key(p), p]));
+ const steals: Array<Row> = []; const gains: Array<Row> = []; const moves: Array<Row> = [];
+ const newWrong: string[] = []; const fixed: string[] = []; const missing: string[] = [];
+ const liveLost: string[] = []; const liveGained: string[] = [];
+ for (const b of base.people) {
+ const a = armBy.get(key(b));
+ if (!a) continue;
+ const gold = goldTransitions(b.ledger);
+ const ids = (p: PersonDump) => new Set(p.transitions.filter(t => t.from === p.slug).map(t => tid(t.from, t.to, t.type, t.kind, t.on)));
+ const bt = ids(b); const at = ids(a);
+ for (const t of at) if (!bt.has(t) && !gold.has(t)) newWrong.push(`s${b.seed} ${t}`);
+ for (const t of at) if (!bt.has(t) && gold.has(t)) fixed.push(`s${b.seed} ${t}`);
+ for (const t of bt) if (!at.has(t) && gold.has(t)) missing.push(`s${b.seed} ${t}`);
+ const targets = new Set([...b.links, ...a.links].map(x => x.to));
+ for (const to of targets) {
+ const tb = typesOf(b, to); const ta = typesOf(a, to);
+ if (show(tb) === show(ta)) continue;
+ const g = goldTypes(b.ledger, to);
+ const lost = [...tb].filter(t => g.has(t) && !ta.has(t));
+ const spurious = [...ta].filter(t => !g.has(t) && !tb.has(t));
+ const won = [...ta].filter(t => g.has(t) && !tb.has(t));
+ const row = { seed: b.seed, subject: b.slug, target: to, ledger: role(b.ledger, to), gold: show(g), base: show(tb), arm: show(ta) };
+ if (lost.length || spurious.length) steals.push(row);
+ else if (won.length) gains.push(row);
+ else moves.push(row);
+ }
+ const cur = new Set(b.ledger.stints.filter(s => s.until === null).map(s => s.company));
+ const liveSet = (p: PersonDump) => new Set(p.live.filter(x => x.type === 'works_at').map(x => x.to));
+ const lb = liveSet(b); const la = liveSet(a);
+ for (const c of cur) {
+ if (lb.has(c) && !la.has(c)) liveLost.push(`s${b.seed} ${b.slug} -> ${c}`);
+ if (!lb.has(c) && la.has(c)) liveGained.push(`s${b.seed} ${b.slug} -> ${c}`);
+ }
+ }
+ return { steals, gains, moves, newWrong, fixed, missing, liveLost, liveGained };
+}
+
+function printCompare(base: Dump, arm: Dump, json: boolean): void {
+ const c = compareDumps(base, arm);
+ if (json) { console.log(JSON.stringify(c, null, 2)); return; }
+ const table = (rows: Row[]) => rows.length ? ['| seed | subject | target | ledger | gold | base | arm |', '|---|---|---|---|---|---|---|',
+ ...rows.map(r => `| ${r.seed} | ${r.subject} | ${r.target} | ${r.ledger} | ${r.gold} | ${r.base} | ${r.arm} |`)].join('\n') : '(none)';
+ const list = (xs: string[]) => xs.length ? xs.map(x => `- ${x}`).join('\n') : '(none)';
+ console.log(`base ${base.root} units ${base.units?.join(',') ?? 'default'}; arm ${arm.root} units ${arm.units?.join(',') ?? 'default'}; phrasing ${arm.phrasing}`);
+ console.log(`steals ${c.steals.length}, gains ${c.gains.length}, other moves ${c.moves.length}, new wrong transitions ${c.newWrong.length}, fixed ${c.fixed.length}, missing correct ${c.missing.length}, live lost ${c.liveLost.length}, live gained ${c.liveGained.length}`);
+ console.log(`\n### Type steals (base matched the ledger, arm does not)\n${table(c.steals)}`);
+ console.log(`\n### Type gains\n${table(c.gains)}`);
+ console.log(`\n### Other type moves\n${table(c.moves)}`);
+ console.log(`\n### New wrong transitions\n${list(c.newWrong)}`);
+ console.log(`\n### Fixed transitions\n${list(c.fixed)}`);
+ console.log(`\n### Missing correct transitions\n${list(c.missing)}`);
+ console.log(`\n### Current employers lost from the live read\n${list(c.liveLost)}`);
+ console.log(`\n### Current employers added to the live read\n${list(c.liveGained)}`);
+}
+
+interface WorldPage { slug: string; type: string; title: string; compiled_truth: string; timeline: string }
+
+/** world-v1 pages as gbrain-evals' loadCorpus reads them (arrays joined, strings coerced). */
+export function loadWorldV1(dir: string): WorldPage[] {
+ return readdirSync(dir).filter(f => f.endsWith('.json') && !f.startsWith('_')).sort().map(f => {
+ const p = JSON.parse(readFileSync(join(dir, f), 'utf8'));
+ return {
+ slug: String(p.slug), type: String(p.type), title: String(p.title ?? ''),
+ compiled_truth: String(Array.isArray(p.compiled_truth) ? p.compiled_truth.join('\n\n') : p.compiled_truth ?? ''),
+ timeline: String(Array.isArray(p.timeline) ? p.timeline.join('\n') : p.timeline ?? ''),
+ };
+ });
+}
+
+type ExtractFn = (slug: string, content: string, fm: Record<string, unknown>, pageType: string, resolver: unknown, opts?: Record<string, unknown>) => Promise<{ candidates: Array<{ targetSlug: string; linkType: string; linkSource?: string; fromSlug?: string }> }>;
+type DeriveFn = (page: { slug: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }, rows: Array<Record<string, unknown>>) => { tense: Map<string, string>; transitions: Array<Record<string, unknown>> };
+
+/** Sorted edge and transition lines for the corpus, and their SHA-256. */
+export async function worldV1Edges(pages: readonly WorldPage[], extract: ExtractFn, derive: DeriveFn): Promise<{ lines: string[]; sha256: string }> {
+ const slugs = new Set(pages.map(p => p.slug));
+ const resolver = { resolve: async (name: string) => (slugs.has(name) ? name : null) };
+ const lines: string[] = [];
+ for (const p of pages) {
+ const content = p.timeline ? `${p.compiled_truth}\n\n<!-- timeline -->\n\n${p.timeline}` : p.compiled_truth;
+ const { candidates } = await extract(p.slug, content, { type: p.type, title: p.title }, p.type, resolver, {});
+ const kept = candidates.filter(c => slugs.has(c.targetSlug));
+ for (const c of kept) lines.push(JSON.stringify(['edge', c.fromSlug ?? p.slug, c.targetSlug, c.linkType, c.linkSource ?? 'markdown']));
+ const rows = kept.map(c => ({ from_slug: c.fromSlug ?? p.slug, to_slug: c.targetSlug, link_type: c.linkType, link_source: c.linkSource ?? 'markdown' }));
+ const ev = derive({ slug: p.slug, compiled_truth: p.compiled_truth, timeline: p.timeline, frontmatter: {} }, rows);
+ for (const [k, v] of ev.tense) lines.push(JSON.stringify(['tense', p.slug, k.split('\0').join(' '), v]));
+ for (const t of ev.transitions) lines.push(JSON.stringify(['transition', t.from_slug, t.to_slug, t.link_type, t.kind, t.occurred_on, t.producer]));
+ }
+ lines.sort();
+ return { lines, sha256: createHash('sha256').update(lines.join('\n')).digest('hex') };
+}
+
+async function worldV1(argv: readonly string[]): Promise<void> {
+ const evals = arg(argv, '--evals'); const root = arg(argv, '--root');
+ if (!evals || !root) fail('world-v1 needs --evals and --root.', 'the corpus lives in gbrain-evals and the build under test is --root.', 'bun scripts/q2-typing-dev.ts world-v1 --evals ../gbrain-evals --root .');
+ hermetic();
+ const rootAbs = resolve(root!);
+ const unitsArg = arg(argv, '--units');
+ if (unitsArg !== undefined) {
+ const mod = await import(join(rootAbs, 'src/core/link-typing-units.ts'));
+ mod.setTypingUnitsForTests(unitsArg === 'none' ? [] : unitsArg.split(','));
+ }
+ const { extractPageLinks } = await import(join(rootAbs, 'src/core/link-extraction.ts'));
+ const { deriveTemporalEvidence } = await import(join(rootAbs, 'src/core/link-temporal-evidence.ts'));
+ const r = await worldV1Edges(loadWorldV1(join(resolve(evals!), 'eval/data/world-v1')), extractPageLinks, deriveTemporalEvidence);
+ const out = arg(argv, '--out');
+ if (out) writeFileSync(out, r.lines.join('\n') + '\n');
+ console.log(`world-v1: ${r.lines.length} lines, sha256 ${r.sha256} (root ${rootAbs}, units ${unitsArg ?? 'build default'})`);
+}
+
+if (import.meta.main) {
+ const [cmd, ...rest] = process.argv.slice(2);
+ if (cmd === 'dump') await dump(rest);
+ else if (cmd === 'world-v1') await worldV1(rest);
+ else if (cmd === 'compare') {
+ const b = arg(rest, '--base'); const a = arg(rest, '--arm');
+ if (!b || !a) fail('compare needs --base and --arm.', 'it compares two dumps by identity.', 'bun scripts/q2-typing-dev.ts compare --base base.json --arm arm.json');
+ printCompare(JSON.parse(readFileSync(b!, 'utf8')), JSON.parse(readFileSync(a!, 'utf8')), rest.includes('--json'));
+ } else fail(`unknown command ${cmd ?? '(none)'}.`, 'the commands are dump, compare and world-v1.', 'bun scripts/q2-typing-dev.ts dump --help is not needed: read the header of scripts/q2-typing-dev.ts');
+}
diff --git a/test/fixtures/q2-dev-phrasings/adviser.json b/test/fixtures/q2-dev-phrasings/adviser.json
new file mode 100644
index 0000000000..ff1081cdb0
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/adviser.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-adviser",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} works at {company} as {role}.",
+ "stale_summary": "{name} works at {company} as {role}.",
+ "rejoin_eu": "Previously at {company}, {name} now runs {company}'s EU team.",
+ "former": "Earlier, {name} worked at {company}.",
+ "advises": "{name} is an adviser to {company}.",
+ "tl_move": "linkedin — Left {prev} to join {company} as {role}",
+ "tl_join": "linkedin — Joined {company} as {role}",
+ "tl_leave": "linkedin — Left {company}",
+ "tl_advise": "note — Now advising {company} on hiring",
+ "tl_invest": "note — Invested in {company}'s seed extension",
+ "tl_alumni": "meeting — Met with the {company} alumni group",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/board-investor.json b/test/fixtures/q2-dev-phrasings/board-investor.json
new file mode 100644
index 0000000000..0ee74b155c
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/board-investor.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-board-investor",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} works at {company} as {role}.",
+ "stale_summary": "{name} works at {company} as {role}.",
+ "rejoin_eu": "Previously at {company}, {name} now runs {company}'s EU team.",
+ "former": "Earlier, {name} worked at {company}.",
+ "advises": "{name} sits on the advisory board of {company}.",
+ "tl_move": "linkedin — Left {prev} to join {company} as {role}",
+ "tl_join": "linkedin — Joined {company} as {role}",
+ "tl_leave": "linkedin — Left {company}",
+ "tl_advise": "note — Took an advisory role with {company}",
+ "tl_invest": "note — Took a board seat at {company} as an investor",
+ "tl_alumni": "meeting — Sat in on the {company} board meeting as an observer",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/leave-start-idioms.json b/test/fixtures/q2-dev-phrasings/leave-start-idioms.json
new file mode 100644
index 0000000000..c5b793d9f1
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/leave-start-idioms.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-leave-start-idioms",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} began working at {company} as {role} and is still there.",
+ "stale_summary": "{name} works at {company} as {role}.",
+ "rejoin_eu": "Previously at {company}, {name} now runs {company}'s EU team.",
+ "former": "Earlier, {name} worked at {company}.",
+ "advises": "{name} also advises {company}.",
+ "tl_move": "linkedin — Swapped {prev} for {company} ({role})",
+ "tl_join": "linkedin — First day at {company} as {role}",
+ "tl_leave": "linkedin — Called it a day at {company} and packed it in",
+ "tl_advise": "note — Became an advisor to {company}",
+ "tl_invest": "note — Traded shares of {company} on the secondary market",
+ "tl_alumni": "event — First day of the {company} alumni summit",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/new-chapter.json b/test/fixtures/q2-dev-phrasings/new-chapter.json
new file mode 100644
index 0000000000..fe9ce8cc63
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/new-chapter.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-new-chapter",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} started a new chapter at {company} as {role} and is still there.",
+ "stale_summary": "{name} is in a new chapter at {company} as {role}.",
+ "rejoin_eu": "Second time around, {name} is back at {company} running the EU team.",
+ "former": "{name} spent an earlier chapter at {company}.",
+ "advises": "{name} is an advisor to {company}.",
+ "tl_move": "linkedin — After {prev}, a new chapter at {company} as {role}",
+ "tl_join": "linkedin — Starting a new chapter at {company} as {role}",
+ "tl_leave": "linkedin — Closed the chapter at {company}",
+ "tl_advise": "note — Started advising {company}",
+ "tl_invest": "note — Became an angel investor in {company}",
+ "tl_alumni": "meeting — Coffee with the {company} alumni network",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/onboarding.json b/test/fixtures/q2-dev-phrasings/onboarding.json
new file mode 100644
index 0000000000..c8f0bd95c4
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/onboarding.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-onboarding",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} has been at {company} as {role} since onboarding.",
+ "stale_summary": "{name} works at {company} as {role}.",
+ "rejoin_eu": "Previously at {company}, {name} now runs {company}'s EU team.",
+ "former": "Earlier, {name} worked at {company}.",
+ "advises": "{name} also advises {company}.",
+ "tl_move": "linkedin — Stepped back from {prev}; onboarded at {company} as {role}",
+ "tl_join": "linkedin — Onboarding week at {company} as {role}",
+ "tl_leave": "linkedin — Parted company with {company}",
+ "tl_advise": "note — Started advising {company}",
+ "tl_invest": "note — Joined {company}'s bridge round",
+ "tl_alumni": "meeting — Onboarding call with the {company} alumni mentors",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/paren-move.json b/test/fixtures/q2-dev-phrasings/paren-move.json
new file mode 100644
index 0000000000..95581958d6
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/paren-move.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-paren-move",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} is now at {company} ({role}).",
+ "stale_summary": "{name}: {company} ({role}).",
+ "rejoin_eu": "{name} rejoined {company} ({role} for the EU region).",
+ "former": "Earlier: {company}.",
+ "advises": "{name} advises {company}.",
+ "tl_move": "linkedin — Moved from {prev} to {company} ({role})",
+ "tl_join": "linkedin — Joined {company} ({role})",
+ "tl_leave": "linkedin — Exit from {company}",
+ "tl_advise": "note — Became an advisor to {company}",
+ "tl_invest": "note — Invested in {company}'s Series C",
+ "tl_alumni": "meeting — Met with the {company} alumni group",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/role-for.json b/test/fixtures/q2-dev-phrasings/role-for.json
new file mode 100644
index 0000000000..b884c13db5
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/role-for.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-role-for",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} is {role} for {company} these days.",
+ "stale_summary": "{name} works as {role} for {company}.",
+ "rejoin_eu": "{name} came back to {company} and is now in charge of its EU team.",
+ "former": "Before that, {name} put in a few years at {company}.",
+ "advises": "{name} also advises {company} on pricing.",
+ "tl_move": "linkedin — Left {prev}; now {role} for {company}",
+ "tl_join": "linkedin — New role: {role} for {company}",
+ "tl_leave": "linkedin — Wrapped up at {company}",
+ "tl_advise": "note — Agreed to advise {company}",
+ "tl_invest": "note — Put money into {company}'s growth round",
+ "tl_alumni": "event — Caught up with old {company} colleagues at a reunion",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}
diff --git a/test/fixtures/q2-dev-phrasings/signed-on.json b/test/fixtures/q2-dev-phrasings/signed-on.json
new file mode 100644
index 0000000000..e2d5b8ad56
--- /dev/null
+++ b/test/fixtures/q2-dev-phrasings/signed-on.json
@@ -0,0 +1,19 @@
+{
+ "id": "q2-dev-signed-on",
+ "note": "Development-only phrasing for the Q2 typing units (gbrain test/fixtures/q2-dev-phrasings). Not held-out material.",
+ "templates": {
+ "current": "{name} signed on with {company} as {role} and remains on the team.",
+ "stale_summary": "{name} signed on with {company} as {role}.",
+ "rejoin_eu": "{name} signed back on with {company} to lead the EU team.",
+ "former": "{name} was once on staff at {company}.",
+ "advises": "{name} serves as an adviser to {company}.",
+ "tl_move": "linkedin — Left {prev} and signed on with {company} as {role}",
+ "tl_join": "linkedin — Signed on with {company} as {role}",
+ "tl_leave": "linkedin — Handed in her notice at {company}",
+ "tl_advise": "note — Signed on as an adviser to {company}",
+ "tl_invest": "note — Wrote a check into {company} after leaving",
+ "tl_alumni": "event — Spoke at a {company} alumni panel",
+ "explicit_start": "note — Started works_at [[{slug}]] as {role}",
+ "explicit_end": "note — Ended works_at [[{slug}]]"
+ }
+}