Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: documented scripts/ and test/ paths must exist (DX-2b, T7.3)

garrytan994454daf323
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 690c69606a..92c45c4daa 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -2092,6 +2092,7 @@ Unit tests and what they cover:
### Lane-move pilot (2026-09)
+<!-- repo-paths: historical -->
The 20 heaviest PGLite-only files in `test/e2e/` (by `scripts/e2e-weights.json`)
moved out of the sequential Postgres runner into the lanes that run on every PR.
Each met the move criterion: it constructs PGLite (or spawns a PGLite CLI)
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 50ddb8753c..9ce4edfff8 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page — the page's best compiled_truth chunk is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the final output is re-sorted by score, because slice / token budget / evidence consumers assume score order. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.
-- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison). Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.
+- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Engine column routing is covered by `test/e2e/embedding-column-pglite.test.ts`, `test/e2e/embedding-column-postgres.test.ts` and `test/cosine-rescore-column.test.ts`. Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.
- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The `vector` strategy runs the production query path: `embedQuery` (query-side `input_type` on asymmetric providers) in the resolved embedding column's model, searched on that column — `embed()` is the document side and would handicap the vector baseline.
diff --git a/docs/architecture/pack-upgrade-mechanism.md b/docs/architecture/pack-upgrade-mechanism.md
index 2d9b288bd7..43ea82889f 100644
--- a/docs/architecture/pack-upgrade-mechanism.md
+++ b/docs/architecture/pack-upgrade-mechanism.md
@@ -113,7 +113,7 @@ that tuple lights up the `pack_upgrade_available` onboard check.
Implementation: `_versionRangeMatches(version, range)` in
`src/core/schema-pack/load-active.ts`. Pinned by
-`test/schema-pack-find-pack-successors.test.ts`.
+`test/schema-pack-find-pack-successors.serial.test.ts`.
## findPackSuccessors discovery
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index e7a5c8535f..d65e059606 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -237,7 +237,7 @@ Four options:
1. **Use OpenRouter** when the provider/model is available through OR's OpenAI-compatible API (covers most hosted chat models + a growing embedding catalog).
2. **Use LiteLLM proxy** (above) — the universal escape hatch. Works for 100+ providers.
3. **Open a feature request** at [github.com/garrytan/gbrain/issues](https://github.com/garrytan/gbrain/issues) with the provider's API docs URL and a setup snippet. Recipes are ~30-40 lines of TypeScript.
-4. **Submit a recipe**: clone, copy `src/core/ai/recipes/voyage.ts` as the gold-standard openai-compat template, register in `src/core/ai/recipes/index.ts`, add a per-recipe smoke test under `test/ai/recipe-<name>.test.ts`. The recipe contract test (`test/ai/recipes-contract.test.ts`) and IRON RULE regression test pin the structural invariants.
+4. **Submit a recipe**: clone, copy `src/core/ai/recipes/voyage.ts` as the gold-standard openai-compat template, register in `src/core/ai/recipes/index.ts`, add a per-recipe smoke test under `test/ai/recipe-<name>.test.ts`. The IRON RULE regression test (`test/ai/recipes-existing-regression.test.ts`) pins the shared auth contract for the existing recipes.
## Switching providers on an existing brain
diff --git a/test/docs-repo-paths.test.ts b/test/docs-repo-paths.test.ts
new file mode 100644
index 0000000000..fef9341812
--- /dev/null
+++ b/test/docs-repo-paths.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Documented repository paths exist (GBRA-47 DX-2b).
+ *
+ * Current-state docs (README, CLAUDE.md, AGENTS.md, CONTRIBUTING.md,
+ * INSTALL_FOR_AGENTS.md, docs/**, .github/**) tell agents which scripts to run
+ * and which tests own a contract. A path to a deleted or renamed `scripts/` or
+ * `test/` file sends the reader to nothing, and nothing noticed: deletions
+ * left references behind in docs, CONTRIBUTING.md and KEY_FILES. This test
+ * fails on any `scripts/...` or `test/...` file path in those docs that does
+ * not exist.
+ *
+ * Not scanned: CHANGELOG.md and TODOS.md (history and backlog), and dated
+ * records that describe the tree at the time: docs/test-audit/<date>/,
+ * docs/designs/ (plans) and docs/fix-wave-notes/.
+ *
+ * Escape hatches, in order of preference:
+ * - fix or delete the reference;
+ * - placeholder names (foo, x, your-script, ...) are skipped;
+ * - `<!-- repo-paths: historical -->` exempts the rest of its section (until
+ * the next markdown heading), for former-path tables;
+ * - ALLOWLIST for paths in an operator's own brain or another repository.
+ * It only shrinks; every entry has a reason; a stale entry fails.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+const REPO = resolve(import.meta.dir, '..');
+const ROOT_DOCS = new Set(['README.md', 'CLAUDE.md', 'AGENTS.md', 'CONTRIBUTING.md', 'INSTALL_FOR_AGENTS.md']);
+const EXEMPT_PREFIXES = ['docs/test-audit/', 'docs/designs/', 'docs/fix-wave-notes/'];
+const PATH_RE = /(?<![\w./~-])((?:scripts|test)\/[A-Za-z0-9_./-]*[A-Za-z0-9_])/g;
+const FILE_EXT = /\.(ts|mts|mjs|js|sh|tsv|txt|json|jsonl|md|yml)$/;
+const PLACEHOLDER = /^(foo|bar|baz|x|y|z|your-[\w-]+)\.[a-z.]+$/;
+const HISTORICAL = '<!-- repo-paths: historical -->';
+
+/** file -> path -> reason. Paths that live outside this repository. */
+const ALLOWLIST: Record<string, Record<string, string>> = {
+ 'docs/guides/minions-shell-jobs.md': {
+ 'scripts/x-garrytan-daily.mjs': 'example shell job running a script in the operator workspace',
+ 'scripts/fetch.mjs': 'example shell job running a script in the operator workspace',
+ },
+ 'docs/guides/quiet-hours.md': {
+ 'scripts/quiet-hours-gate.sh': 'gate script the guide has the operator create in their own workspace',
+ },
+ 'docs/guides/multi-source-brains.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/architecture/key-files/files-and-sync-1.md': {
+ 'scripts/brain-commit-push.sh': 'installed into the brain repo by `gbrain sources harden`',
+ },
+ 'docs/UPGRADING_DOWNSTREAM_AGENTS.md': {
+ 'scripts/validate-frontmatter.mjs': 'downstream agent repo script the upgrade guide tells agents to replace',
+ },
+ 'docs/mcp/HERMES-CLI-PIN.md': {
+ 'scripts/install.sh': 'the Hermes agent repository installer',
+ },
+ 'docs/architecture/key-files/skills.md': {
+ 'test/example.test.ts': 'file inside a pack scaffolded by `gbrain skillpack init`',
+ },
+};
+
+function scannedFiles(): string[] {
+ const tracked = execFileSync('git', ['ls-files', '*.md', '*.yml', '*.yaml'], { cwd: REPO, encoding: 'utf8' })
+ .split('\n')
+ .filter(Boolean);
+ return tracked.filter(f => {
+ if (EXEMPT_PREFIXES.some(p => f.startsWith(p))) return false;
+ return ROOT_DOCS.has(f) || (f.startsWith('docs/') && f.endsWith('.md')) || f.startsWith('.github/');
+ });
+}
+
+interface Ref { file: string; line: number; path: string }
+
+function documentedPaths(): Ref[] {
+ const refs: Ref[] = [];
+ for (const file of scannedFiles()) {
+ const full = join(REPO, file);
+ if (!existsSync(full)) continue;
+ let historical = false;
+ readFileSync(full, 'utf8').split('\n').forEach((text, i) => {
+ if (text.includes(HISTORICAL)) historical = true;
+ else if (/^#{1,6}\s/.test(text)) historical = false;
+ if (historical) return;
+ for (const m of text.matchAll(PATH_RE)) {
+ const path = m[1]!;
+ if (!FILE_EXT.test(path) || PLACEHOLDER.test(path.split('/').at(-1)!)) continue;
+ refs.push({ file, line: i + 1, path });
+ }
+ });
+ }
+ return refs;
+}
+
+describe('documented scripts/ and test/ paths', () => {
+ const refs = documentedPaths();
+
+ test('every documented path exists', () => {
+ const missing = refs
+ .filter(r => !existsSync(join(REPO, r.path)) && !ALLOWLIST[r.file]?.[r.path])
+ .map(r => `${r.file}:${r.line} names ${r.path}, which does not exist`);
+ if (missing.length > 0) {
+ throw new Error([
+ ...missing,
+ 'Why: a doc that names a deleted or renamed script or test sends agents to nothing.',
+ 'Fix: point the reference at the current path or delete it. A former-path table takes `<!-- repo-paths: historical -->` above it; a path in an operator brain or another repository takes a reasoned ALLOWLIST row in test/docs-repo-paths.test.ts.',
+ 'Docs: docs/TESTING.md#retiring-a-test',
+ ].join('\n'));
+ }
+ });
+
+ test('allowlist entries are still needed', () => {
+ const live = new Set(refs.map(r => `${r.file}|${r.path}`));
+ const stale = Object.entries(ALLOWLIST).flatMap(([file, paths]) =>
+ Object.keys(paths).filter(p => !live.has(`${file}|${p}`) || existsSync(join(REPO, p))).map(p => `${file} › ${p}`));
+ expect(stale).toEqual([]);
+ });
+});