Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(docs-links): LLMS_REPO_BASE must be a plain https URL (W4.12)
time-attackacc598bc0e74
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 190d749503..8c446885b1 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSpec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-contract/v1/`.- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain`/`--source` before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.-- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks. `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.+- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace; an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 8cdb4b1966..e9940b5533 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -27,4 +27,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `.github/workflows/fix-wave-gate.yml` + `scripts/fix-wave-gate.ts` — the contributor gate. `pull_request_target` on master (`opened`, `edited`, `reopened`, `synchronize`, `labeled`, `unlabeled`); sparse-checks-out only the script from the default branch and never PR code. `decide()` (pure) passes a head repository equal to `TRUSTED_HEAD_REPO` with the base repository's id, or a present `maintainer-override` label whose latest `labeled` timeline event was made by a `User` on `MAINTAINERS` (no `[bot]` login); a null head repository, a missing label or any other labeler fails. Overrides print a `notice` and step-summary line naming the actor, time and event id. `--comment` (the `welcome-comment` job, `pull-requests: write`, `opened` only) posts `gateMessage()` once per PR, keyed by `COMMENT_MARKER`. The script imports only `node:` modules. Tests: `test/scripts/fix-wave-gate.test.ts` (fixture payloads in `test/fixtures/fix-wave-gate/`). Process and the required-check settings step: `docs/RELEASING.md#fix-wave-gate`.- `.github/workflows/fix-wave-closeout.yml` + `scripts/fix-wave-closeout.ts` — closes what a merged fix wave superseded. `pull_request_target` on master (`closed`); the job runs only when the PR merged and its head repository is `garrytan/gbrain`, and sparse-checks-out only the script from the default branch. `supersededNumbers()` (pure) reads the PR numbers listed right after a line-leading `Supersedes` keyword; `runCloseout()` skips non-PRs and closed PRs, posts `closeoutMessage()` once per PR (keyed by `COMMENT_MARKER`, crediting the contributor only when the wave body says `Contributed by @handle`), closes it, caps a run at `MAX_CLOSES`, and turns a failed close into a warning. `--dry-run` reads without writing. Tests: `test/scripts/fix-wave-closeout.test.ts`. Process: `docs/RELEASING.md#fix-wave-closeout`.-- `scripts/check-skill-refs.mjs` + `scripts/portable-skill-links.ts` + `scripts/skills-commit-gate.sh` — skills-tree integrity gate (`bun run check:skill-refs`, in verify and the skills commit gate). Fails on dangling backtick `skills/` refs, `./`/`../` links, `composes:` and RESOLVER dispatcher slugs; donor-workspace paths outside the shrink-only allowlist; any `gbrain <cmd>` in a fenced line or inline code span (command position only: line/span start, after a shell separator, `nohup`/env prefixes) that is not a real command (union of `--tools-json`, `CLI_FLAG_REGISTRY`, `src/cli.ts` dispatch, the command table and op `cliHints`), plus curated known-bad subcommands (`embed refresh`); and a relative link that resolves outside the skills root, in `skills/` and in the generated `plugin/skills` and `plugin-variants/*/skills` trees (`skills/migrations/**` exempt). A tools-json load failure warns and skips the CLI lane. `portable-skill-links.ts` is that rule's fix: it points `docs/protocol/AGENT_OPERATOR_v1.md` links at the bundled `skills/conventions/agent-operator-protocol.md` and other repo files at absolute blob URLs derived from `LLMS_REPO_BASE` (raw.githubusercontent base → github.com blob base; default `garrytan/gbrain/blob/master`), retargeting default-base links for forks; `--check` reports pending rewrites. Tests: `test/check-skill-refs.test.ts`, `test/skills-portable-links.test.ts` (scaffold `--all` into a tmp host: 0 broken local links).+- `scripts/check-skill-refs.mjs` + `scripts/portable-skill-links.ts` + `scripts/skills-commit-gate.sh` — skills-tree integrity gate (`bun run check:skill-refs`, in verify and the skills commit gate). Fails on dangling backtick `skills/` refs, `./`/`../` links, `composes:` and RESOLVER dispatcher slugs; donor-workspace paths outside the shrink-only allowlist; any `gbrain <cmd>` in a fenced line or inline code span (command position only: line/span start, after a shell separator, `nohup`/env prefixes) that is not a real command (union of `--tools-json`, `CLI_FLAG_REGISTRY`, `src/cli.ts` dispatch, the command table and op `cliHints`), plus curated known-bad subcommands (`embed refresh`); and a relative link that resolves outside the skills root, in `skills/` and in the generated `plugin/skills` and `plugin-variants/*/skills` trees (`skills/migrations/**` exempt). A tools-json load failure warns and skips the CLI lane. `portable-skill-links.ts` is that rule's fix: it points `docs/protocol/AGENT_OPERATOR_v1.md` links at the bundled `skills/conventions/agent-operator-protocol.md` and other repo files at absolute blob URLs derived from `LLMS_REPO_BASE` (raw.githubusercontent base → github.com blob base; default `garrytan/gbrain/blob/master`; a non-https or credentialed value throws via `repoBaseOrThrow`, as in `scripts/llms-config.ts`), retargeting default-base links for forks; `--check` reports pending rewrites. Tests: `test/check-skill-refs.test.ts`, `test/skills-portable-links.test.ts` (scaffold `--all` into a tmp host: 0 broken local links).diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex 70f38c098b..2da8724045 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -11,6 +11,7 @@* regenerate without manual URL rewrites:* LLMS_REPO_BASE=https://raw.githubusercontent.com/fork-org/gbrain/main bun run build:llms*/+import { repoBaseOrThrow } from '../src/core/repo-base.ts';export type DocEntry = {title: string;@@ -30,9 +31,7 @@ export const PROJECT = {summary:"GBrain is a personal knowledge brain and GStack mod for agent platforms. Pluggable engines (PGLite default, Postgres+pgvector for scale), contract-first operations, fat-markdown skills, and one agent operator contract for every error and recommendation. Teaches agents brain ops, ingestion, enrichment, scheduling, identity, and access control.",repoUrl: "https://github.com/garrytan/gbrain",- rawBaseUrl:- process.env.LLMS_REPO_BASE ??- "https://raw.githubusercontent.com/garrytan/gbrain/master",+ rawBaseUrl: repoBaseOrThrow(process.env.LLMS_REPO_BASE, "https://raw.githubusercontent.com/garrytan/gbrain/master"),};export const SECTIONS: DocSection[] = [diff --git a/scripts/portable-skill-links.ts b/scripts/portable-skill-links.tsindex d14324f17f..849cdc9a4a 100644--- a/scripts/portable-skill-links.ts+++ b/scripts/portable-skill-links.ts@@ -25,6 +25,7 @@*/import { readFileSync, readdirSync, writeFileSync } from 'node:fs';import { join, posix, relative } from 'node:path';+import { repoBaseOrThrow } from '../src/core/repo-base.ts';const ROOT = join(import.meta.dir, '..');export const DEFAULT_BLOB_BASE = 'https://github.com/garrytan/gbrain/blob/master';@@ -32,8 +33,8 @@ export const PROTOCOL_SOURCE = 'docs/protocol/AGENT_OPERATOR_v1.md';export const BUNDLED_PROTOCOL = 'skills/conventions/agent-operator-protocol.md';export function repoBlobBase(env: Record<string, string | undefined> = process.env): string {- const raw = env.LLMS_REPO_BASE?.replace(/\/+$/, '');- if (!raw) return DEFAULT_BLOB_BASE;+ if (!env.LLMS_REPO_BASE?.trim()) return DEFAULT_BLOB_BASE;+ const raw = repoBaseOrThrow(env.LLMS_REPO_BASE, DEFAULT_BLOB_BASE);const m = raw.match(/^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/(.+)$/);return m ? `https://github.com/${m[1]}/${m[2]}/blob/${m[3]}` : raw;}diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex ad31d88f01..bbc795fbc1 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -20,6 +20,7 @@ import { VERB_NAMES } from './verbs.ts';import { classifyPgAccessError, formatDbAccessMarker } from './pg-access-classify.ts';import { redactConnectionInfo } from './audit/redact-connection-info.ts';import { redactUrlsInText } from './url-redact.ts';+import { parseRepoBase } from './repo-base.ts';import { recordAgentContractEvent } from './agent-contract-log.ts';import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';@@ -207,8 +208,17 @@ function docsRef(): string {export function docsUrl(anchor: string): string {if (/^https?:\/\//.test(anchor)) return anchor;const path = anchor.replace(/^\.?\//, '');- const forkBase = process.env.LLMS_REPO_BASE?.replace(/\/+$/, '');- return forkBase ? `${forkBase}/${path}` : `${REPO_BLOB}/${docsRef()}/${path}`;+ const forkBase = parseRepoBase(process.env.LLMS_REPO_BASE);+ if (forkBase !== null && typeof forkBase !== 'string') warnInvalidRepoBase(forkBase.invalid);+ return typeof forkBase === 'string' ? `${forkBase}/${path}` : `${REPO_BLOB}/${docsRef()}/${path}`;+}++let warnedRepoBase: string | null = null;+/** W4.12: an invalid `LLMS_REPO_BASE` is ignored (default links), with one stderr line per value. */+function warnInvalidRepoBase(value: string): void {+ if (warnedRepoBase === value) return;+ warnedRepoBase = value;+ process.stderr.write('[gbrain] LLMS_REPO_BASE is not a plain https URL, so documentation links use the default repository. Unset it or set an https base.\n');}// ── next + rendering ───────────────────────────────────────────────────────diff --git a/src/core/repo-base.ts b/src/core/repo-base.tsnew file mode 100644index 0000000000..7dcf5c50e8--- /dev/null+++ b/src/core/repo-base.ts@@ -0,0 +1,26 @@+/**+ * `LLMS_REPO_BASE`, the fork override for documentation links (W4.12): the+ * base URL every rendered `docs` link, `llms.txt` entry and portable skill+ * link starts with. Agents read those links as fix instructions, so only a+ * plain `https://host/path` base is accepted: no other scheme, no+ * credentials, query or fragment, and no whitespace or control characters.+ */++/** The override with trailing slashes removed; null when unset or blank; `{ invalid }` when it is not a plain https URL. */+export function parseRepoBase(raw: string | undefined): string | null | { invalid: string } {+ const value = raw?.trim().replace(/\/+$/, '');+ if (!value) return null;+ if (/[\s\x00-\x1f\x7f]/.test(value)) return { invalid: value };+ let url: URL;+ try { url = new URL(value); } catch { return { invalid: value }; }+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password || url.search || url.hash) return { invalid: value };+ return value;+}++/** Build scripts: the override, or `fallback` when unset; an invalid value throws. */+export function repoBaseOrThrow(raw: string | undefined, fallback: string): string {+ const parsed = parseRepoBase(raw);+ if (parsed === null) return fallback;+ if (typeof parsed === 'string') return parsed;+ throw new Error(`LLMS_REPO_BASE must be a plain https URL such as https://raw.githubusercontent.com/<org>/<repo>/<branch> (no credentials, query or fragment); got ${JSON.stringify(parsed.invalid)}`);+}diff --git a/test/llms-repo-base-w412.test.ts b/test/llms-repo-base-w412.test.tsnew file mode 100644index 0000000000..c27a2ff0c8--- /dev/null+++ b/test/llms-repo-base-w412.test.ts@@ -0,0 +1,49 @@+/**+ * Wave 12 W4.12: `LLMS_REPO_BASE` (the fork override for documentation links)+ * accepts only a plain https base. Agents follow rendered `docs` links as fix+ * instructions, so a `javascript:`, `http:` or credentialed value is ignored at+ * runtime (default links, one warning) and refused by the build scripts.+ */+import { describe, expect, test } from 'bun:test';+import { docsUrl } from '../src/core/agent-output.ts';+import { parseRepoBase, repoBaseOrThrow } from '../src/core/repo-base.ts';+import { repoBlobBase } from '../scripts/portable-skill-links.ts';+import { withEnv } from './helpers/with-env.ts';++const BAD = ['javascript:alert(1)//', 'http://docs.example.test', 'https://user:[email protected]', 'https://docs.example.test/x?y=1', 'https://docs.example.test/x#y', 'ftp://docs.example.test', 'https://docs.example .test'];++describe('W4.12: LLMS_REPO_BASE must be a plain https URL', () => {+ test('a valid fork base still wins', async () => {+ await withEnv({ LLMS_REPO_BASE: 'https://raw.githubusercontent.com/fork-org/gbrain/main/' }, () => {+ expect(docsUrl('docs/guides/error-codes.md#x')).toBe('https://raw.githubusercontent.com/fork-org/gbrain/main/docs/guides/error-codes.md#x');+ });+ expect(repoBlobBase({ LLMS_REPO_BASE: 'https://raw.githubusercontent.com/fork-org/gbrain/main' })).toBe('https://github.com/fork-org/gbrain/blob/main');+ });++ for (const value of BAD) {+ test(`runtime docs links ignore ${JSON.stringify(value)}`, async () => {+ const writes: string[] = [];+ const write = process.stderr.write.bind(process.stderr);+ (process.stderr.write as unknown as (c: unknown) => boolean) = (c: unknown) => { writes.push(String(c)); return true; };+ try {+ await withEnv({ LLMS_REPO_BASE: value }, () => {+ const url = docsUrl('docs/guides/error-codes.md#x');+ expect(url.startsWith('https://github.com/garrytan/gbrain/blob/')).toBe(true);+ expect(url).not.toContain(value.replace(/\/+$/, ''));+ });+ } finally { process.stderr.write = write; }+ expect(parseRepoBase(value)).toEqual({ invalid: value.trim().replace(/\/+$/, '') });+ });++ test(`build scripts refuse ${JSON.stringify(value)}`, () => {+ expect(() => repoBlobBase({ LLMS_REPO_BASE: value })).toThrow(/LLMS_REPO_BASE must be a plain https URL/);+ expect(() => repoBaseOrThrow(value, 'https://fallback.example.test')).toThrow(/plain https URL/);+ });+ }++ test('unset or blank falls back to the default', () => {+ expect(parseRepoBase(undefined)).toBeNull();+ expect(parseRepoBase(' ')).toBeNull();+ expect(repoBlobBase({})).toBe('https://github.com/garrytan/gbrain/blob/master');+ });+});