Files
gbrain/test/e2e/type-unification-full-flow.test.ts
T
5d42f3295e v0.41.22.0 feat: type-unification cathedral — 94 types → 15 canonical (closes #1479) (#1542)
* Merge branch 'master' into garrytan/type-taxonomy-unification

Resolve VERSION, package.json, CHANGELOG conflicts with v0.41.22.0
on top, preserving master's v0.41.19.0 entry below.

* feat: v0.41.22.0 type-unification cathedral — collapse 94 types to 15 (closes #1479)

Ships gbrain-base-v2 as the new install default (15 canonical types: 14
+ note catch-all) and the unify-types PROTECTED Minion handler that
runs the gbrain-base→v2 migration end-to-end on existing brains.

What this delivers:
- gbrain-base-v2.yaml standalone schema pack (no extends:) with 14
  canonical page_types + 9 cluster mapping_rules + catch-all sentinel
- 3 new schema-pack primitives: runRetypeCore (chunked UPDATE with
  legacy_type stamping), runPageToLinkCore (edge-shaped pages →
  link rows), runPageToAliasCore (concept-redirect → slug_aliases)
- rewriteLinksBatch for N-pair atomic FK rewrite
- Migration v104 slug_aliases table (forward-bootstrap probed on both
  engines for safe upgrade chain)
- New engine method resolveSlugWithAlias(slug, sourceOrSources) on
  both Postgres + PGLite with multi-source ambiguity warning
- inferTypeAndSubtypeFromPack overload + subtypes: + mapping_rules:
  + migration_from: schema-pack manifest extensions
- findPackSuccessors version-range walker (1.x / 1.0.x / exact match)
- expandTypeFilter for --type back-compat (D14): legacy aliases route
  through mapping_rules → canonical+subtype before the SQL filter fires
- 3 new onboard checks: pack_upgrade_available, type_proliferation,
  dangling_aliases (source-scoped per F12)
- unify-types Minion handler (PROTECTED, manual_only via render.ts
  allowlist per D17): retype-explicit → retype-catch-all →
  page-to-link → page-to-alias → final sync → active-pack flip
- alias_resolved 1.05x post-fusion search boost stage; KNOBS_HASH_VERSION
  bumped 5→6 (one-time cache miss on upgrade, self-healing in TTL)
- ELIGIBLE_TYPES for facts extraction extended with v2 canonicals
  (codex F-ELIGIBLE: blocker not v0.43 follow-up)

Tests: 79 new unit/integration cases + 3 E2E cases covering all 9
production clusters end-to-end. 124-case verification on the cache-key
+ build-llms fixes. KNOBS_HASH_VERSION assertions updated in 3 tests.

Plan: ~/.claude/plans/system-instruction-you-are-working-transient-elephant.md
(16 locked decisions D1-D17, 12 baseline fixes F7-F21 absorbed from
codex outside voice).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: CI verify failures — system-of-record allow-comment + schema-unify manifest registration

Two CI failures on PR #1542:

1. check:system-of-record flagged page-to-link.ts:207 addLinksBatch as
   a direct write to a derived table. The call IS the reconcile surface
   for page_to_link mapping_rules — it converts edge-shaped pages into
   canonical link rows under the PROTECTED unify-types Minion handler,
   source-scoped, atomic per-rule. Added the canonical
   `// gbrain-allow-direct-insert: <reason>` comment on the same line.

2. check:resolver emitted 11 orphan_trigger warnings for `schema-unify`
   because the skill was added to skills/RESOLVER.md without a
   corresponding entry in skills/manifest.json. Added the registration
   under the existing skills[] array.

bun run verify: 28/28 checks pass locally.

* fix: CI test failures — schema-unify conformance + eligibility regression

Six test failures across shards 2 + 10 on PR #1542:

1. resolver.test.ts: round-trip parser requires frontmatter triggers to
   be quoted (`- "..."` or `- '...'`). schema-unify shipped with bare
   YAML strings; quoted the 10 triggers to round-trip correctly.

2. skills-conformance.test.ts (×3): schema-unify SKILL.md was missing
   the required Contract, Anti-Patterns, and Output Format sections
   that every conformant skill must declare. Added all three:
   - Contract: inputs / outputs / side effects / failure modes
   - Anti-Patterns: 5 DON'Ts including the autopilot trust boundary
   - Output Format: per-phase stderr lines + celebration summary +
     JSON envelope shape

3. facts-eligibility.test.ts (×2): the v0.41.22 ELIGIBLE_TYPES
   expansion added `concept` to the eligible list, but the existing
   test suite pins concept as rejected (it's `extractable: true` in
   the schema pack but the v0.41.11 contract documented this as
   "cosmetic on the backstop path because backstop uses hardcoded
   ELIGIBLE_TYPES"). Removed `concept` from the expansion; other v2
   canonicals (media, tweet, atom, analysis) stay. Comment updated
   to document the deliberate omission.

All 6 failing tests now pass locally (370/370 across the 3 affected
files). bun run verify: 28/28 checks green.

* fix: harden findPackSuccessors test against shard pollution

CI shard 8 reported 1 fail (1.00ms — too fast for any real loadActivePack
file I/O) on `finds gbrain-base-v2 as successor of gbrain-base@1.0.0`.
Local triple-run passes 9/9 in isolation.

Root cause: the existing afterEach reset clears the module-level pack
cache AFTER each test, but the FIRST test in the file inherits whatever
state sibling files in the same bun shard process left behind. With
24+ schema-pack tests in shard 8 (mutate, mutate-audit, best-effort,
registry-reload, manifest-v041_2, etc.) running before this file, the
first test can read a poisoned cache.

Fix: add `beforeEach(_resetPackCacheForTests)`. Two-sided reset
guarantees clean state regardless of file ordering within the shard.

bun run verify: 28/28 checks pass.

* fix: quarantine two flaky tests to serial runner

CI shard 1 + shard 8 each surfaced one intermittent failure:

shard 1: buildBrainTools > execute() on put_page with valid namespace
shard 8: findPackSuccessors > finds gbrain-base-v2 as successor

Both pass cleanly in isolation. Both are concurrency races against
shared in-shard state:

- brain-allowlist.test.ts shares a singleton PGLiteEngine across 18
  tests with a beforeEach DELETE FROM pages. With max-concurrency=4,
  two put_page tests can interleave their TRUNCATE + write phases,
  so the auto-link/extract sub-steps inside put_page race against
  the sibling test's DELETE.
- schema-pack-find-pack-successors.test.ts reads bundled YAML packs
  via loadActivePack. The module-level pack cache is shared across
  parallel tests in the same shard; the previous beforeEach reset
  helped but didn't fully isolate against concurrent file reads
  under CI load.

Fix per CLAUDE.md test-isolation lint rule R2 (concurrency-fragile
files belong in the .serial.test.ts quarantine): rename both files
to *.serial.test.ts. Serial runner picks them up at max-concurrency=1.
49/49 serial files pass locally. 28/28 verify checks pass.

* fix: quarantine embed-stale test to serial runner

CI shard 9 reported 6 failures, all from the embedStaleForSource describe
block, all ~120-150ms each — classic shared-engine concurrency race shape.
Passes 7/7 locally in isolation.

Root cause: embed-stale.test.ts shares a singleton PGLiteEngine across 7
tests with beforeEach resetPgliteState. Under bun's max-concurrency=4 in
the parallel shard, two tests can interleave their TRUNCATE + seedPage +
upsertChunks + embedStaleForSource flow, so one test's stale-chunk count
sees another test's mid-flight writes.

Same fix as brain-allowlist.serial.test.ts and
schema-pack-find-pack-successors.serial.test.ts: rename to *.serial.test.ts
so the serial runner picks it up at max-concurrency=1.

bun run verify: 28/28 checks pass. 7/7 embed-stale tests pass via serial.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 07:01:28 -07:00

232 lines
9.6 KiB
TypeScript

// v0.42 Type Unification (T34) — IRON RULE E2E test.
//
// Seeds a synthetic brain with all 9 clusters from issue #1479 (~30 pages
// covering tweets / articles / companies / atoms / media / analysis /
// concept-redirect / one-offs / symlinks), runs the full unify-types
// pipeline against gbrain-base-v2, and asserts:
// - distinct types drops from ~25 to ≤16 (15 canonical + residual)
// - alias rows created for concept-redirect pages
// - canonical pages survive
// - source pages soft-deleted for page-to-link + page-to-alias clusters
// - active pack flipped
// - wikilink resolution via slug_aliases works
// - re-running is idempotent (total_applied: 0)
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { runUnifyTypes } from '../../src/core/schema-pack/unify-types-handler.ts';
import { runAllOnboardChecks } from '../../src/core/onboard/checks.ts';
import { _resetPackCacheForTests } from '../../src/core/schema-pack/registry.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
});
beforeEach(async () => {
await resetPgliteState(engine);
_resetPackCacheForTests();
});
function ctxOf() {
return {
engine,
config: {},
logger: { info: () => {}, warn: () => {}, error: () => {} },
dryRun: false,
remote: false,
} as never;
}
async function seedAll9Clusters() {
const seeds: Array<{ slug: string; type: string; body?: string; fm?: Record<string, unknown> }> = [
// Cluster 1: tweet family (5 types)
{ slug: 'tweets/a', type: 'tweet-single' },
{ slug: 'tweets/b', type: 'tweet-thread' },
{ slug: 'tweets/c', type: 'tweet-bundle' },
{ slug: 'tweets/d', type: 'tweet-stub' },
{ slug: 'tweets/e', type: 'media/x-tweet/bundle' },
// Cluster 2: articles (3 types → 1 with subtype + 1 → source)
{ slug: 'articles/x', type: 'article' },
{ slug: 'articles/y', type: 'media/article' },
{ slug: 'sources/z', type: 'sources/article' },
// Cluster 3: companies (3 types → 1 with subtype)
{ slug: 'companies/x', type: 'company' },
{ slug: 'companies/y', type: 'yc-company' },
{ slug: 'companies/z', type: 'product' },
// Cluster 4: atoms (3 types → 1 with subtype + 1 page→link)
{ slug: 'atoms/a', type: 'atom-extraction' },
{ slug: 'atoms/b', type: 'content-atom' },
{ slug: 'atoms/c', type: 'lore' },
// Cluster 5: media (3 types → 1 with subtype)
{ slug: 'videos/x', type: 'video' },
{ slug: 'youtube/y', type: 'youtube-video' },
{ slug: 'books/z', type: 'book' },
// Cluster 6: analysis (2 types → 1)
{ slug: 'analysis/x', type: 'media/analysis' },
{ slug: 'analysis/y', type: 'competitive-intel' },
// Cluster 7: concept-redirect (canonical + 2 redirects)
{ slug: 'wiki/concepts/canonical', type: 'concept' },
{ slug: 'wiki/concepts/redirect-1', type: 'concept-redirect',
body: '[[wiki/concepts/canonical]] redirect body that is long enough to pass any min-char gates' },
{ slug: 'wiki/concepts/redirect-2', type: 'concept-redirect',
body: '[[wiki/concepts/canonical]] another redirect to the same canonical with sufficient length' },
// Cluster 8: one-offs (4 types → all note with legacy_type)
{ slug: 'note/civic-1', type: 'civic' },
{ slug: 'note/framework-1', type: 'framework' },
{ slug: 'note/insight-1', type: 'insight' },
{ slug: 'note/memo-1', type: 'memo' },
// Cluster 9: symlinks (already handled by page_to_link rule; need target + source)
{ slug: 'people/alice', type: 'person' },
{ slug: 'companies/acme', type: 'company' },
{ slug: 'atoms/partner-1', type: 'atom-partner-link',
fm: { source: 'people/alice', target: 'companies/acme' } },
];
for (const s of seeds) {
await engine.putPage(s.slug, {
title: s.slug,
type: s.type as never,
compiled_truth: s.body ?? 'page body that is sufficiently long to pass any minimum-length backstop guards in the codebase',
timeline: '',
frontmatter: s.fm ?? {},
source_path: `${s.slug}.md`,
});
}
return seeds.length;
}
describe('v0.42 type-unification E2E (IRON RULE)', () => {
it('runs the full pipeline against a synthetic 9-cluster brain', async () => {
const seedCount = await seedAll9Clusters();
expect(seedCount).toBeGreaterThan(25);
// Pre-state: many distinct types
const preTypes = await engine.executeRaw<{ cnt: string }>(
`SELECT COUNT(DISTINCT type)::text AS cnt FROM pages WHERE deleted_at IS NULL`,
);
const preDistinct = parseInt(preTypes[0].cnt, 10);
expect(preDistinct).toBeGreaterThanOrEqual(20);
// Onboard surfaces pack_upgrade_available
const checks = await runAllOnboardChecks(engine);
const packUpgrade = checks.find(c => c.check.name === 'pack_upgrade_available');
expect(packUpgrade?.check.status).toBe('warn');
expect(packUpgrade?.remediations[0]?.job).toBe('unify-types');
// Dry-run
const dryResult = await runUnifyTypes(ctxOf(), {
target_pack: 'gbrain-base-v2',
apply: false,
});
expect(dryResult.apply).toBe(false);
expect(dryResult.per_phase.retype_explicit.would_apply).toBeGreaterThan(10);
// Apply
const applyResult = await runUnifyTypes(ctxOf(), {
target_pack: 'gbrain-base-v2',
apply: true,
});
expect(applyResult.apply).toBe(true);
expect(applyResult.active_pack_flipped).toBe(true);
expect(applyResult.pack_identity_after).toContain('gbrain-base-v2');
// Post-state: ≤16 distinct types (15 canonical + maybe residual)
const postTypes = await engine.executeRaw<{ cnt: string }>(
`SELECT COUNT(DISTINCT type)::text AS cnt FROM pages WHERE deleted_at IS NULL`,
);
const postDistinct = parseInt(postTypes[0].cnt, 10);
expect(postDistinct).toBeLessThanOrEqual(16);
expect(postDistinct).toBeLessThan(preDistinct);
// Concept-redirect pages soft-deleted
const aliasedRedirects = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM pages WHERE slug LIKE 'wiki/concepts/redirect-%' AND deleted_at IS NULL`,
);
expect(aliasedRedirects.length).toBe(0);
// slug_aliases rows created
const aliasRows = await engine.executeRaw<{ alias_slug: string; canonical_slug: string }>(
`SELECT alias_slug, canonical_slug FROM slug_aliases ORDER BY alias_slug`,
);
expect(aliasRows.length).toBe(2);
expect(aliasRows[0].canonical_slug).toBe('wiki/concepts/canonical');
// resolveSlugWithAlias short-circuits old slug to canonical
const resolved = await engine.resolveSlugWithAlias('wiki/concepts/redirect-1', 'default');
expect(resolved).toBe('wiki/concepts/canonical');
// atom-partner-link converted to real link row
const linkRows = await engine.executeRaw<{ link_type: string }>(
`SELECT l.link_type FROM links l
JOIN pages p1 ON l.from_page_id = p1.id
JOIN pages p2 ON l.to_page_id = p2.id
WHERE p1.slug = 'people/alice' AND p2.slug = 'companies/acme'
AND l.link_source = 'manual'`,
);
expect(linkRows.length).toBe(1);
expect(linkRows[0].link_type).toBe('partner_of');
// Onboard checks clear post-unify
const checksAfter = await runAllOnboardChecks(engine);
const packUpgradeAfter = checksAfter.find(c => c.check.name === 'pack_upgrade_available');
expect(packUpgradeAfter?.check.status).toBe('ok');
const typeProlifAfter = checksAfter.find(c => c.check.name === 'type_proliferation');
expect(typeProlifAfter?.check.status).toBe('ok');
// Idempotency: re-running is no-op
const idempResult = await runUnifyTypes(ctxOf(), {
target_pack: 'gbrain-base-v2',
apply: true,
});
expect(idempResult.per_phase.retype_explicit.applied).toBe(0);
expect(idempResult.per_phase.page_to_alias.aliased).toBe(0);
expect(idempResult.per_phase.page_to_link.converted).toBe(0);
});
it('canonical pages preserve their type identity', async () => {
// After unify, key reference pages keep their canonical types.
await seedAll9Clusters();
await runUnifyTypes(ctxOf(), {
target_pack: 'gbrain-base-v2',
apply: true,
});
const ppl = await engine.executeRaw<{ type: string }>(
`SELECT type FROM pages WHERE slug = 'people/alice' AND deleted_at IS NULL`,
);
expect(ppl[0].type).toBe('person');
const co = await engine.executeRaw<{ type: string }>(
`SELECT type FROM pages WHERE slug = 'companies/acme' AND deleted_at IS NULL`,
);
expect(co[0].type).toBe('company');
const conc = await engine.executeRaw<{ type: string }>(
`SELECT type FROM pages WHERE slug = 'wiki/concepts/canonical' AND deleted_at IS NULL`,
);
expect(conc[0].type).toBe('concept');
});
it('legacy_type frontmatter enables per-page rollback (D8)', async () => {
await seedAll9Clusters();
await runUnifyTypes(ctxOf(), {
target_pack: 'gbrain-base-v2',
apply: true,
});
// Pick one retyped page and verify legacy_type
const rows = await engine.executeRaw<{ slug: string; type: string; frontmatter: Record<string, unknown> }>(
`SELECT slug, type, frontmatter FROM pages
WHERE slug = 'tweets/a' AND deleted_at IS NULL`,
);
expect(rows[0].type).toBe('tweet');
expect(rows[0].frontmatter.legacy_type).toBe('tweet-single');
// Rollback would be: UPDATE pages SET type = frontmatter->>'legacy_type'
// — this is verified semantically by the value being preserved.
});
});