Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): grade type_proliferation per source against each source's own pack (#6289)

time-attack86ed5b96f735
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index a99a87c513..69d7d3ab93 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -10,6 +10,7 @@ Key files:
- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.
- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.
- `src/core/schema-pack/unify-types-handler.ts` + `src/core/onboard/checks.ts` (`checkPackUpgradeAvailable`) — pack-upgrade retype (`runUnifyTypes`, the `unify-types` job). #6196: on a managed brain apply runs the dry run first (`applyOnManagedBrain`): with nothing to retype, link or alias it only switches the active pack (`flipActivePack`, DB + file plane); otherwise it refuses `writer_coordinator_required` with the counts and a read-only `gbrain onboard --check --explain` fix before any lock or write, and the dry run warns that apply waits for coordinated retype. `pack_upgrade_available` on a managed brain is an info row (`readiness_state: degraded`) with that preview as its fix and no `unify-types` apply remediation it could not run. Coordinated retype (D2) is deferred.
+- `src/core/onboard/checks.ts` (`checkTypeProliferation`) — doctor/onboard `type_proliferation` (#6289): one `SELECT DISTINCT source_id, type` read; each source resolves its own pack through `loadActivePackForLocalEngine(engine, { sourceId })` (per-source DB config included); sources sharing a pack pool their labels, an alias counts as its canonical type (`classifyStoredType`), and each pool is graded with the unchanged thresholds (warn above declared + 5, fail above declared × 2). The message names the worst pool's sources, pack and up to five undeclared labels. A source whose pack does not resolve, or a failed query, warns "not verified", never ok. Pinned by `test/onboard-pack-upgrade-checks.test.ts`.
- `src/core/schema-pack/pack-lock.ts` — Atomic `O_CREAT|O_EXCL` per-pack lock. DELIBERATELY NOT the `existsSync + writeFileSync` TOCTOU shape from `src/core/page-lock.ts`. Default 60s TTL, refresh every 10s while `withPackLock(fn)` runs, `--force` semantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.
- `src/core/schema-pack/write-vocabulary.ts` — write-time pack-vocabulary enforcement shared by the write surfaces (capture op, `add_link` op, `gbrain capture` CLI). `loadActivePackForWriteVocabulary(ctx)` pairs the engine's DB-plane `schema_pack` key with FILE-ONLY config (the `loadActivePackForLocalEngine` posture) while threading `remote` (fail-closed: anything not strictly false is remote) + `sourceId`; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before). `packDeclaresPageType`/`packDeclaresLinkType` + message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without a `gbrain schema explain` round-trip. The DEFAULT `note` path is never checked here — callers validate EXPLICIT names only, so bare `gbrain capture` works under a pack that doesn't declare `note`. `loadActivePackForWriteVocabulary` also swallows a rejecting `getConfig`; `previewNames` bounds the vocabulary preview in the error (the first 12 names + `(N total)`). Pinned by `test/write-vocabulary.test.ts`.
- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so a future `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.
diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.ts
index 2daba9a506..280c4e1f20 100644
--- a/src/core/onboard/checks.ts
+++ b/src/core/onboard/checks.ts
@@ -630,61 +630,67 @@ export async function checkPackUpgradeAvailable(
* pages exceed pack-declared types + 5; fails at declared × 2. No false
* positives on custom packs (compares to actual pack declaration count,
* not a hardcoded threshold).
+ *
+ * #6289: each source is graded against its own resolved pack (per-source
+ * DB config included); sources sharing a pack pool their labels, and an
+ * alias counts as its canonical type. A source whose pack does not resolve,
+ * or a failed query, is "not verified" (warn), never ok.
*/
export async function checkTypeProliferation(
engine: BrainEngine,
): Promise<OnboardCheckResult> {
- let declared = 15; // fallback to gbrain-base-v2 default if pack unavailable
+ const result = (status: 'ok' | 'warn' | 'fail', message: string): OnboardCheckResult =>
+ ({ check: { name: 'type_proliferation', status, message }, remediations: [] });
+ let rows: Array<{ source_id: string; type: string }>;
try {
- const { loadActivePack } = await import('../schema-pack/load-active.ts');
- const { loadConfigFileOnly } = await import('../config.ts');
- let dbConfig: string | undefined;
- try {
- dbConfig = (await engine.getConfig('schema_pack')) ?? undefined;
- } catch { /* tolerate pre-config brains */ }
- const active = await loadActivePack({ cfg: loadConfigFileOnly(), remote: false, dbConfig })
- .catch(() => null);
- if (active) declared = active.manifest.page_types.length;
- } catch {
- // Use fallback.
- }
- const n = await safeCount(
- engine,
- `SELECT COUNT(DISTINCT type) AS count FROM pages WHERE deleted_at IS NULL AND type IS NOT NULL`,
- );
- const warn = declared + 5;
- const fail = declared * 2;
- if (n > fail) {
- return {
- check: {
- name: 'type_proliferation',
- status: 'fail',
- message:
- `${n} distinct page types (pack declares ${declared}). ` +
- `Run \`gbrain onboard --check --explain\` to preview a pack upgrade ` +
- `or define a custom pack with mapping_rules.`,
- },
- remediations: [], // pack_upgrade_available check emits the actionable step
- };
+ rows = await engine.executeRaw<{ source_id: string; type: string }>(
+ `SELECT DISTINCT source_id, type FROM pages WHERE deleted_at IS NULL AND type IS NOT NULL ORDER BY source_id, type`);
+ } catch (e) {
+ return result('warn', `type_proliferation not verified: the page type query failed (${(e as Error).message}).`);
}
- if (n > warn) {
- return {
- check: {
- name: 'type_proliferation',
- status: 'warn',
- message: `${n} distinct page types vs ${declared} declared in pack — consider unification.`,
- },
- remediations: [],
- };
+ const { loadActivePackForLocalEngine } = await import('../schema-pack/best-effort.ts');
+ const { classifyStoredType } = await import('../schema-pack/type-usage.ts');
+ const pools = new Map<string, { pack: NonNullable<Awaited<ReturnType<typeof loadActivePackForLocalEngine>>>; sources: Set<string>; labels: Set<string>; undeclared: Set<string> }>();
+ const unresolved = new Set<string>();
+ for (const sourceId of new Set(rows.map(r => r.source_id))) {
+ const pack = await loadActivePackForLocalEngine(engine, { sourceId });
+ if (!pack) { unresolved.add(sourceId); continue; }
+ const pool = pools.get(pack.identity) ?? { pack, sources: new Set<string>(), labels: new Set<string>(), undeclared: new Set<string>() };
+ pool.sources.add(sourceId);
+ for (const { type } of rows.filter(r => r.source_id === sourceId)) {
+ const cls = classifyStoredType(type, pack.manifest);
+ pool.labels.add(cls.kind === 'alias_of' ? cls.canonical : type);
+ if (cls.kind === 'undeclared') pool.undeclared.add(type);
+ }
+ pools.set(pack.identity, pool);
}
- return {
- check: {
- name: 'type_proliferation',
- status: 'ok',
- message: `${n} distinct typed values (pack declares ${declared})`,
- },
- remediations: [],
+ const graded = [...pools.values()].map(pool => {
+ const declared = pool.pack.manifest.page_types.length;
+ const n = pool.labels.size;
+ return { pool, declared, n, status: n > declared * 2 ? 'fail' as const : n > declared + 5 ? 'warn' as const : 'ok' as const };
+ });
+ const rank = { ok: 0, warn: 1, fail: 2 };
+ const worst = graded.sort((a, b) => rank[b.status] - rank[a.status] || b.n - b.declared - (a.n - a.declared))[0];
+ const where = (g: typeof graded[number]) => {
+ const undeclared = [...g.pool.undeclared].sort();
+ const names = undeclared.slice(0, 5).join(', ') + (undeclared.length > 5 ? `, +${undeclared.length - 5} more` : '');
+ return ` (source${g.pool.sources.size > 1 ? 's' : ''} ${[...g.pool.sources].sort().join(', ')}, pack ${g.pool.pack.manifest.name}${names ? `; undeclared: ${names}` : ''})`;
};
+ const notVerified = unresolved.size
+ ? ` Not verified: the schema pack for source${unresolved.size > 1 ? 's' : ''} ${[...unresolved].sort().join(', ')} does not resolve (run \`gbrain schema active --source <id>\`).`
+ : '';
+ if (worst?.status === 'fail') {
+ return result('fail',
+ `${worst.n} distinct page types (pack declares ${worst.declared})${where(worst)}. ` +
+ `Run \`gbrain onboard --check --explain\` to preview a pack upgrade ` +
+ `or define a custom pack with mapping_rules.${notVerified}`);
+ }
+ if (worst?.status === 'warn') {
+ return result('warn', `${worst.n} distinct page types vs ${worst.declared} declared in pack — consider unification${where(worst)}.${notVerified}`);
+ }
+ if (notVerified) return result('warn', `type_proliferation${notVerified.trimEnd()}`);
+ if (!worst) return result('ok', 'no typed pages');
+ return result('ok', graded.map(g => `${g.n} distinct typed values (pack ${g.pool.pack.manifest.name} declares ${g.declared})`).join('; '));
}
/**
diff --git a/test/onboard-pack-upgrade-checks.test.ts b/test/onboard-pack-upgrade-checks.test.ts
index f1367ac81f..e8af91218d 100644
--- a/test/onboard-pack-upgrade-checks.test.ts
+++ b/test/onboard-pack-upgrade-checks.test.ts
@@ -151,6 +151,54 @@ describe('checkTypeProliferation (D16 pack-aware ratio)', () => {
});
});
+describe('checkTypeProliferation per-source packs (#6289)', () => {
+ async function seedSource(sourceId: string, types: string[]) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ for (const [i, type] of types.entries()) {
+ await engine.putPage(`${sourceId}-p${i}`, { title: `${sourceId}-p${i}`, type: type as never, compiled_truth: 'body', timeline: '', frontmatter: {} }, { sourceId });
+ }
+ }
+ const env = { GBRAIN_HOME: emptyHome(), GBRAIN_SCHEMA_PACK: undefined };
+
+ it('grades each source against its own pack', async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await engine.setConfig('schema_pack.source.side-example', 'gbrain-everything');
+ await withEnv(env, async () => {
+ const { loadActivePack } = await import('../src/core/schema-pack/load-active.ts');
+ const everything = await loadActivePack({ cfg: null, remote: false, dbConfig: 'gbrain-everything' });
+ await seedPages(['note']);
+ await seedSource('side-example', everything.manifest.page_types.map(t => t.name));
+ const result = await checkTypeProliferation(engine);
+ expect(result.check.status).toBe('ok');
+ });
+ });
+
+ it('a source over its pack threshold warns naming the source, pack and undeclared labels', async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await withEnv(env, async () => {
+ const { loadActivePack } = await import('../src/core/schema-pack/load-active.ts');
+ const declared = (await loadActivePack({ cfg: null, remote: false, dbConfig: 'gbrain-base-v2' })).manifest.page_types.length;
+ await seedSource('side-example', Array.from({ length: declared + 6 }, (_, i) => `custom-type-${String(i).padStart(2, '0')}`));
+ const result = await checkTypeProliferation(engine);
+ expect(result.check.status).toBe('warn');
+ expect(result.check.message).toContain('source side-example');
+ expect(result.check.message).toContain('pack gbrain-base-v2');
+ expect(result.check.message).toContain('undeclared: custom-type-00');
+ });
+ });
+
+ it('a source whose pack does not resolve warns "not verified", never ok', async () => {
+ await engine.setConfig('schema_pack.source.side-example', 'no-such-pack-example');
+ await withEnv(env, async () => {
+ await seedSource('side-example', ['note']);
+ const result = await checkTypeProliferation(engine);
+ expect(result.check.status).toBe('warn');
+ expect(result.check.message).toContain('Not verified');
+ expect(result.check.message).toContain('side-example');
+ });
+ });
+});
+
describe('checkDanglingAliases (F12 source-scoped JOIN)', () => {
it('returns ok when no aliases exist', async () => {
const result = await checkDanglingAliases(engine);