Compare commits

..
Author SHA1 Message Date
97ddee0548 fix(schema-pack): narrow stats catch-all so masked errors surface, not fake 0 pages (#2466)
fetchCountRows and detectDeadPrefixes in src/core/schema-pack/stats.ts
swallowed EVERY engine error into empty results, so any real failure
printed 'Total pages: 0' + a vacuous 100% coverage on a populated brain.
Both catches now swallow only isUndefinedTableError (pre-init brain,
missing pages table) and rethrow everything else. Four regression tests:
real non-zero count on a populated PGLite brain, rethrow on non-missing-
table errors in both catch sites, and the missing-table degrade path.

Takeover of #2493.

Co-authored-by: javieraldape <javieraldape@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:41:12 -07:00
6 changed files with 102 additions and 123 deletions
+1 -5
View File
@@ -206,11 +206,7 @@ jobs:
needs: cache-check
if: needs.cache-check.outputs.hit != 'true'
runs-on: ubuntu-latest
# 20 (was 15): shard 4 runs ~14.5 min on master (dream.test.ts ~29s/test
# dominates it) and hits the 15-min ceiling on slower runners, cancelling
# mid-run with 0 test failures. Rebalancing via
# scripts/mine-shard-weights.ts is the real fix; this stops the bleeding.
timeout-minutes: 20
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
+17 -6
View File
@@ -18,6 +18,7 @@
import type { BrainEngine } from '../engine.ts';
import { loadActivePackBestEffort } from './best-effort.ts';
import type { OperationContext } from '../operations.ts';
import { isUndefinedTableError } from '../utils.ts';
export interface StatsOpts {
/** Single source scope. Omit + omit sourceIds for whole-brain aggregate. */
@@ -164,9 +165,17 @@ async function fetchCountRows(engine: BrainEngine, opts: StatsOpts): Promise<Raw
`;
try {
return await engine.executeRaw<RawCountRow>(sql, params);
} catch {
// Empty / pre-init brain: pages table may not exist yet.
return [];
} catch (err) {
// ONLY swallow the genuine "pages table doesn't exist yet" case
// (empty / pre-init brain). #2466: the old bare `catch {}` masked
// EVERY error — so any engine-level failure (connection, version
// skew, a query incompatibility) was silently converted to 0 rows,
// printing "Total pages: 0" on a populated brain and cascading into
// false "100% coverage" + a starved `schema suggest`. Surface
// everything that is not a missing-table error so the real failure
// is visible instead of hidden behind a fake zero.
if (isUndefinedTableError(err)) return [];
throw err;
}
}
@@ -204,9 +213,11 @@ async function detectDeadPrefixes(
if (cnt === 0) {
hints.push({ type: t.name, prefix });
}
} catch {
// Skip on engine error (no pages table yet, etc.).
continue;
} catch (err) {
// #2466: only skip on the genuine "no pages table yet" case;
// rethrow any other engine error so it isn't silently masked.
if (isUndefinedTableError(err)) continue;
throw err;
}
}
}
+1 -34
View File
@@ -23,15 +23,6 @@
* hold conventions and shared rule files, not skills. Files like
* `_brain-filing-rules.md` live at the root and are not considered
* skills by either loader.
*
* ClawHub-installed workspace skills (#1767): a skill dir carrying
* `.clawhub/origin.json` is an externally-managed runtime integration
* (e.g. an email or catalog skill), not a gbrain-routable skill. The
* derive path SKIPS those so `gbrain doctor` resolver_health doesn't
* hard-fail on them — UNLESS the skill's SKILL.md frontmatter declares
* `triggers:`, which is the explicit opt-in to gbrain routing (and the
* same surface that makes it reachable). An explicit manifest.json that
* lists a ClawHub skill also keeps strict checking (verbatim path).
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
@@ -69,27 +60,9 @@ function parseSkillName(skillMdPath: string): string | null {
}
}
/**
* Does the SKILL.md frontmatter declare a `triggers:` key? A ClawHub-
* installed skill that ships gbrain `triggers:` has explicitly opted in
* to gbrain routing and gets full resolver checks (#1767).
*/
function declaresTriggers(skillMdPath: string): boolean {
try {
const content = readFileSync(skillMdPath, 'utf-8');
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (!fmMatch) return false;
return /^triggers:/m.test(fmMatch[1]);
} catch {
return false;
}
}
/**
* Walk skillsDir, return every `<skillsDir>/<dir>/SKILL.md` as a
* ManifestEntry. Dotfile and underscore-prefixed dirs are skipped, as
* are ClawHub-installed external skills that haven't opted in to gbrain
* routing via `triggers:` frontmatter (#1767).
* ManifestEntry. Dotfile and underscore-prefixed dirs are skipped.
*/
function deriveManifest(skillsDir: string): ManifestEntry[] {
const out: ManifestEntry[] = [];
@@ -120,12 +93,6 @@ function deriveManifest(skillsDir: string): ManifestEntry[] {
const skillMd = join(subdirAbs, 'SKILL.md');
if (!existsSync(skillMd)) continue;
// ClawHub-installed external skill (#1767): skip unless it opts in
// to gbrain routing by declaring `triggers:` in its frontmatter.
if (existsSync(join(subdirAbs, '.clawhub', 'origin.json')) && !declaresTriggers(skillMd)) {
continue;
}
const frontmatterName = parseSkillName(skillMd);
const name = frontmatterName && frontmatterName !== '' ? frontmatterName : entry;
out.push({ name, path: `${entry}/SKILL.md` });
-29
View File
@@ -382,35 +382,6 @@ describe("DRY detection — checkResolvable", () => {
});
});
describe("#1767 — ClawHub workspace skills are not resolver-required", () => {
let dir: string;
afterEachCleanup(() => dir && rmSync(dir, { recursive: true, force: true }));
test("ClawHub skill without gbrain metadata produces no unreachable/mece_gap", () => {
dir = mkdtempSync(join(tmpdir(), "gbrain-clawhub-"));
// Native gbrain skill: routable via frontmatter triggers. No manifest.json
// (the OpenClaw derive path from the issue repro).
mkdirSync(join(dir, "query"), { recursive: true });
writeFileSync(
join(dir, "query", "SKILL.md"),
`---\nname: query\ndescription: test\ntriggers:\n - "what do we know"\n---\n\n# query\n`
);
// ClawHub-installed integration: no triggers, no resolver row.
mkdirSync(join(dir, "agentmail", ".clawhub"), { recursive: true });
writeFileSync(
join(dir, "agentmail", ".clawhub", "origin.json"),
JSON.stringify({ registry: "https://clawhub.ai", slug: "agentmail" })
);
writeFileSync(join(dir, "agentmail", "SKILL.md"), `---\nname: agentmail\ndescription: email integration\n---\n\n# agentmail\n`);
const report = checkResolvable(dir);
const agentmailIssues = report.issues.filter(i => i.skill === "agentmail");
expect(agentmailIssues).toEqual([]);
expect(report.ok).toBe(true);
expect(report.summary.total_skills).toBe(1);
});
});
describe("v0.22.4 regression — actual repo skills/ has 0 errors", () => {
test("repo skills/ pass check-resolvable cleanly (zero errors AND zero warnings)", () => {
// The v0.22.4 (Part A) contract was zero warnings AND zero errors.
+83
View File
@@ -222,6 +222,89 @@ describe('runStatsCore — JSON envelope shape', () => {
});
});
describe('runStatsCore — #2466 catch-narrowing (real count + error surfacing)', () => {
// #2466: `gbrain schema stats` reported "Total pages: 0" on a populated
// PGLite brain. The bug was a bare `catch {}` in fetchCountRows (and a
// sibling in detectDeadPrefixes) that converted ANY engine error into 0
// rows. The COUNT query itself is valid on PGLite (proven below), so the
// regression pins two things: (a) a populated brain reports the real,
// non-zero count through the full runStatsCore path; (b) a non-missing-
// table engine error is rethrown, not masked into a fake zero.
it('reports the real non-zero count on a populated PGLite brain (no false 0)', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// Seed a realistic mix: typed, untyped, multiple types — like the
// 169-page brain in the bug report (scaled down).
for (let i = 0; i < 12; i++) {
const type = i % 3 === 0 ? '' : (i % 3 === 1 ? 'person' : 'company');
await seedPage(`notes/p${i}`, { type, sourcePath: `notes/p${i}.md` });
}
const result = await runStatsCore(ctxOf());
// The core regression: NOT zero.
expect(result.aggregate.total_pages).toBe(12);
expect(result.aggregate.typed_pages).toBe(8);
expect(result.aggregate.untyped_pages).toBe(4);
// And coverage is the honest ratio, not the vacuous 1.0 a 0/0 prints.
expect(result.aggregate.coverage).not.toBe(1.0);
});
});
it('fetchCountRows rethrows a non-missing-table engine error instead of masking it as 0 pages', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// No pack → detectDeadPrefixes is skipped, isolating the throw to the
// fetchCountRows catch we narrowed. The count query (the GROUP BY one)
// throws a column-level error (SQLSTATE 42703) — the exact class the
// old bare `catch {}` swallowed into 0 rows; everything else succeeds.
__setPackLocatorForTests(() => null);
const boom = Object.assign(new Error('column "type" does not exist'), { code: '42703' });
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) throw boom; // the fetchCountRows query
return [];
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
await expect(runStatsCore(ctx)).rejects.toThrow('column "type" does not exist');
});
});
it('fetchCountRows still degrades to empty (no throw) on a genuine missing pages table', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// Pre-init brain shape: the count query hits a missing pages table
// (SQLSTATE 42P01). This is the ONLY case the narrowed catch swallows.
__setPackLocatorForTests(() => null);
const missing = Object.assign(new Error('relation "pages" does not exist'), { code: '42P01' });
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) throw missing;
return [];
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
const result = await runStatsCore(ctx);
expect(result.aggregate.total_pages).toBe(0);
expect(result.per_source).toEqual([]);
});
});
it('detectDeadPrefixes rethrows a non-missing-table error (sibling catch)', async () => {
await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: 'tiny' }, async () => {
seedTinyPack('tiny', [{ name: 'person', prefix: 'people/' }]);
// fetchCountRows (the GROUP BY query) succeeds → []; the per-prefix
// dead-prefix LIKE query then throws a non-missing-table error, which
// must surface through the narrowed sibling catch.
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) return []; // count query: empty brain, fine
throw Object.assign(new Error('division by zero'), { code: '22012' }); // the LIKE query
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
await expect(runStatsCore(ctx)).rejects.toThrow('division by zero');
});
});
});
describe('runStatsCore — type/untyped split', () => {
it('treats empty-string type as untyped (not its own bucket)', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
-49
View File
@@ -166,55 +166,6 @@ describe('loadOrDeriveManifest', () => {
expect(r.skills.map(s => s.name)).toEqual(['apple', 'mango', 'zebra']);
});
// #1767 — ClawHub-installed workspace skills are external integrations,
// not gbrain-routable skills. The derive path skips them unless they
// opt in via `triggers:` frontmatter.
it('skips ClawHub-origin skills without triggers frontmatter (#1767)', () => {
const dir = scratch();
writeSkill(dir, 'query', 'query');
writeSkill(dir, 'agentmail', 'agentmail');
mkdirSync(join(dir, 'agentmail', '.clawhub'), { recursive: true });
writeFileSync(
join(dir, 'agentmail', '.clawhub', 'origin.json'),
JSON.stringify({ registry: 'https://clawhub.ai', slug: 'agentmail' })
);
const r = loadOrDeriveManifest(dir);
expect(r.derived).toBe(true);
expect(r.skills.map(s => s.name)).toEqual(['query']);
});
it('includes ClawHub-origin skills that opt in via triggers frontmatter (#1767)', () => {
const dir = scratch();
writeSkill(dir, 'agentmail', 'agentmail');
mkdirSync(join(dir, 'agentmail', '.clawhub'), { recursive: true });
writeFileSync(
join(dir, 'agentmail', '.clawhub', 'origin.json'),
JSON.stringify({ registry: 'https://clawhub.ai', slug: 'agentmail' })
);
writeFileSync(
join(dir, 'agentmail', 'SKILL.md'),
`---\nname: agentmail\ndescription: test\ntriggers:\n - "send email"\n---\n\n# agentmail\n`
);
const r = loadOrDeriveManifest(dir);
expect(r.derived).toBe(true);
expect(r.skills.map(s => s.name)).toEqual(['agentmail']);
});
it('keeps ClawHub-origin skills listed in an explicit manifest.json (#1767)', () => {
// Explicit manifest.json is a deliberate declaration — strict checking stays.
const dir = scratch();
writeSkill(dir, 'agentmail', 'agentmail');
mkdirSync(join(dir, 'agentmail', '.clawhub'), { recursive: true });
writeFileSync(
join(dir, 'agentmail', '.clawhub', 'origin.json'),
JSON.stringify({ registry: 'https://clawhub.ai', slug: 'agentmail' })
);
writeManifest(dir, { skills: [{ name: 'agentmail', path: 'agentmail/SKILL.md' }] });
const r = loadOrDeriveManifest(dir);
expect(r.derived).toBe(false);
expect(r.skills.map(s => s.name)).toEqual(['agentmail']);
});
it('treats dirs without SKILL.md as not-a-skill', () => {
const dir = scratch();
writeSkill(dir, 'query', 'query');