Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan990e7b6e1855
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d92f884578..5a8a579824 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,15 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.+**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.### Itemized changes-- `src/core/git/range-secret-scan.ts` (new): reads one `git log -p --diff-merges=dense-combined` of the range and scans each commit's message, each file's added lines and each merge's lines neither parent has with `scanText` and the workspace allowlist (`.gbrain-scan-allow`); binary changes carry no lines, and added text over the scan cap is reported unscanned.+- `src/core/git/range-secret-scan.ts` (new): reads the range with plumbing only (`rev-list`, `git cat-file commit` per message, one `git diff-tree --stdin -p --root --cc` streamed to a private temporary file and read in chunks), so no log, diff or encoding setting and no replace ref changes what is scanned, and memory stays bounded however large the binaries in the range are. It scans each commit's message, each file's added lines and each merge's lines no parent has with `scanText` and the workspace allowlist (`.gbrain-scan-allow`). Binary is git's own rule (a NUL in the first 8000 bytes) with attributes read from the empty tree; a file git still calls binary is checked by its own bytes when its old side was not empty or an attribute could apply, and scanned whole when it is text. Added text over the scan cap is reported unscanned, and output it does not recognise, a git failure or its 300 s budget make the result unreadable.- `src/core/persistence/worktree-refresh.ts`: an unset `sources.refresh_publish_diverged` publishes only when `gitDurabilityPolicy` says durable (otherwise `refresh_diverged` names the durability and the `--enable` command); the publish child runs with `--scan-secrets`.-- `src/core/git/commit-push.ts`, `src/commands/git.ts`: `scanSecrets` / `--scan-secrets` (push-only) scans `trackingRef..target` inside the publish lock, right before the push, and refuses `publish_secret_found` (new error code) on a finding, an over-cap file or a range git cannot list; its fix lists the commits and asks the user to remove the value or allowlist a false positive, never to push anyway.+- `src/core/git/commit-push.ts`, `src/commands/git.ts`: `scanSecrets` / `--scan-secrets` (push-only) scans `trackingRef..target` inside the publish lock, right before the push, and refuses `publish_secret_found` (new error code) on a finding or an over-cap file, and `publish_scan_unreadable` (new error code: no secret was reported, check the checkout with `git fsck`) when the scan could not read the range in full; the secret refusal's fix lists the commits and asks the user to remove the value or allowlist a false positive, never to push anyway.- Docs: `docs/guides/shared-checkout-git.md` (`publish_secret_found` row), `docs/guides/write-refusals.md` (`refresh_diverged`), `docs/guides/live-sync.md`, `docs/guides/shared-checkout-git.md`, `docs/guides/troubleshooting.md`, `docs/architecture/canonical-writers.md`.-- Tests: `test/guarded-publish.test.ts` (a secret added then removed, one in a commit message and one in a merge resolution each refuse with nothing pushed and no value printed; an allowlisted fingerprint and a binary file are skipped; a clean range publishes); `test/refresh-publish-diverged-7686.test.ts` (unset with durability off refuses naming `--enable`, unset with durability on publishes, a secret in the local commits refuses `publish_secret_found` with nothing pushed or fenced).+- Tests: `test/guarded-publish.test.ts` (a secret added then removed, one in a commit message and one in a merge resolution each refuse with nothing pushed and no value printed; an allowlisted fingerprint and a binary file are skipped; a clean range publishes; a NUL past a text file's first 8000 bytes, a repository log encoding and `log.showRoot=false` with a merged root commit never hide a secret; a range the scan cannot read refuses `publish_scan_unreadable`); `test/refresh-publish-diverged-7686.test.ts` (unset with durability off refuses naming `--enable`, unset with durability on publishes, a secret in the local commits refuses `publish_secret_found` with nothing pushed or fenced).## [0.60.619.0] - 2026-11-08**`gbrain git commit-push` on a managed checkout no longer reports commits the remote lacks as already pushed.** On a managed canonical worktree, commit-push commits only the named paths and leaves publishing to the persistence owner. When the commit already existed (a script's bare commit, or one an earlier call made), it printed `nothing to commit; origin/main at -`, exited 0 and logged `[push] ok-already-on-remote`, which the push-log reader behind `put_page`'s `lastPushStatus` and doctor counts as a push that landed, while the branch sat ahead of (or diverged from) its upstream. It now says nothing was pushed, reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`), names the command that publishes them, and writes no push-log line. Nothing is pushed or moved; exit codes are unchanged.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 3c70425887..917a8556ba 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3652,6 +3652,16 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair|---|---|---|---|---|---|---|| The catalog adoption is accepted but not fully committed. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### publish_scan_unreadable++<a id="publish_scan_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An automatic publish could not read its local commits in full to scan them for secrets (a missing or corrupt object, git output the scan does not recognise, or the 300 s budget); no secret was reported and nothing was pushed. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | user | `gbrain doctor --json` | 1 | no |++More: [docs/guides/shared-checkout-git.md#publish_scan_unreadable](../../docs/guides/shared-checkout-git.md#publish_scan_unreadable)+### publish_secret_found<a id="publish_secret_found"></a>diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex 6f9e273c0e..36e8520cb5 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -186,6 +186,7 @@ Follow the error's `fix.next` as the| `git_operation_in_progress` | 1 | A rebase, merge, cherry-pick or revert is unfinished in the checkout. gbrain never aborts it for you. Follow [stuck rebase](#stuck-rebase). || `git_detached_head` | 1 | The checkout is on a detached HEAD or an unborn branch. Check out the branch the remote tracks (`git switch <branch>`), or make the first commit, then rerun. || <a id="publish_secret_found"></a>`publish_secret_found` | 1 | Only with `--scan-secrets` (the publish `gbrain sources refresh` runs on its own): a commit about to be pushed adds a value that looks like a secret, in its message, an added line (even one a later commit removed) or a merge resolution, adds text too large to scan, or changes `.gbrain-scan-allow` or a `.gitattributes` (files that decide what the scan sees); nothing was pushed. The message names each file, line, rule and commit, never the value. Ask the user: remove the value from those unpushed commits, or add a false positive's fingerprint to `.gbrain-scan-allow`, then retry. Never publish them with a command that skips the scan. |+| <a id="publish_scan_unreadable"></a>`publish_scan_unreadable` | 1 | Only with `--scan-secrets`: the scan could not read the commits about to be pushed in full (a missing or corrupt object, git output it does not recognise, or its 300 s budget), so it reported no secret and nothing was pushed. Run `git fsck` in the checkout, fix what it names, then retry. Never publish with a command that skips the scan. || `integrate_conflict` | 1 | Local and remote commits changed the same file; nothing was merged and the checkout is unchanged. Stop, relay the question to the user, then [resolve](#conflicts). || `push_unconfirmed` | 4 | The commit is durable locally but no push destination confirmed it (network, credentials, branch protection, a remote that kept moving, or another push that held the push lock for the whole wait). Fix what the message names, then run `gbrain git commit-push --push-only`. Never force-push. || `writer_coordinator_required` | 1 | This is a managed worktree. Stop using git for pages; save them through `put_page` and the other gbrain write tools. |diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5d2d158761..af6d21fed8 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -578,6 +578,7 @@ export const CODES = {serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },publish_secret_found: { class: 'consent', summary: "An automatic publish found values that look like secrets (or text too large to scan) in the commits it was about to push; nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_secret_found', actor: 'user' },+ publish_scan_unreadable: { class: 'host_only', summary: "An automatic publish could not read its local commits in full to scan them for secrets (a missing or corrupt object, git output the scan does not recognise, or the 300 s budget); no secret was reported and nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable', actor: 'user' },push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },pg_connection_recovery_failed: { class: 'retryable', summary: "A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error.", why: "The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own.", docs: 'docs/ENGINES.md#pg-connection-recovery-failed', suggestion: 'Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--only', 'pool_reap_health', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the recent stuck, desync and recovery events serve recorded.', requires_exclusive: false } },diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.tsindex f93ee83f32..66ccfa80df 100644--- a/src/core/git/commit-push.ts+++ b/src/core/git/commit-push.ts@@ -27,7 +27,7 @@*/import { appendFileSync, existsSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { findingsInLog, rangeScanArgs } from './range-secret-scan.ts';+import { scanRange } from './range-secret-scan.ts';import { isAbsolute, join, relative, resolve } from 'node:path';import { execFileSync } from '../spawn.ts';import { gitChildEnv, literalPathspecs } from '../git-env.ts';@@ -1031,16 +1031,23 @@ function assertLocalCommitsInsideRoots(ctx: Ctx, target: string, roots: string[]/** The automatic-publish secret gate: scan what the commits in trackingRef..target add (the exact range this publish pushes, under its lock). */function assertNoSecretsInRange(ctx: Ctx, target: string): void {- const log = git(ctx.root, rangeScanArgs(ctx.trackingRef, target), { timeoutMs: 300_000, maxBuffer: 1024 * 1024 * 1024 });- const scan = log.code === 0 ? findingsInLog(ctx.root, log.stdout) : null;- if (scan && !scan.findings.length && !scan.unscanned.length && !scan.gate_changes.length) return;- const named = scan ? [...scan.findings.map(f => `${f.path}:${f.line} (${f.pattern}, ${f.commit.slice(0, 7)})`), ...scan.unscanned.map(u => `${u.path} (too large to scan, ${u.commit.slice(0, 7)})`),- ...scan.gate_changes.map(g => `${g.path} (changes what the scan sees, ${g.commit.slice(0, 7)})`)] : [];- throw opError('publish_secret_found', scan- ? `${named.length} item(s) in the local commits ${ctx.trackingRef}..${target.slice(0, 12)} look like secrets or could not be scanned: ${named.slice(0, 10).join(', ')}${named.length > 10 ? ', ...' : ''}. Nothing was pushed.`- : `git could not list the local commits ${ctx.trackingRef}..${target.slice(0, 12)} to scan them for secrets (${log.stderr.trim().slice(0, 200) || `exit ${log.code}`}). Nothing was pushed.`,+ const scan = scanRange(ctx.root, ctx.trackingRef, target);+ if (scan.unreadable !== undefined) {+ throw opError('publish_scan_unreadable', `The secret scan could not read the local commits ${ctx.trackingRef}..${target.slice(0, 12)} (${scan.unreadable}). No secret was reported. Nothing was pushed.`,+ `The publish pushes only commits it has read in full. Check the checkout with git fsck in ${ctx.root} (a missing or corrupt object, a full disk, or a git too slow for the 300 s budget), fix what it reports, then retry. Never publish with a command that skips this scan.`,+ { detail: JSON.stringify({ unreadable: scan.unreadable }), fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,+ argv: ['git', '-C', ctx.root, 'fsck'],+ why: 'Read-only: names missing or corrupt objects in the unpublished commits, the usual reason the scan cannot read them.',+ user_message: `The secret scan could not read the unpublished commits in ${ctx.root}, so nothing was pushed. Check the checkout with git fsck and fix what it reports?`,+ docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable' } });+ }+ if (!scan.findings.length && !scan.unscanned.length && !scan.gate_changes.length) return;+ const named = [...scan.findings.map(f => `${f.path}:${f.line} (${f.pattern}, ${f.commit.slice(0, 7)})`), ...scan.unscanned.map(u => `${u.path} (too large to scan, ${u.commit.slice(0, 7)})`),+ ...scan.gate_changes.map(g => `${g.path} (changes what the scan sees, ${g.commit.slice(0, 7)})`)];+ throw opError('publish_secret_found',+ `${named.length} item(s) in the local commits ${ctx.trackingRef}..${target.slice(0, 12)} look like secrets or could not be scanned: ${named.slice(0, 10).join(', ')}${named.length > 10 ? ', ...' : ''}. Nothing was pushed.`,'Remove the value from those commits (rewriting unpushed local commits is the user\'s call), or add a false positive\'s fingerprint to .gbrain-scan-allow, then retry. Never publish them with a command that skips this scan.',- { detail: JSON.stringify(scan ?? { error: 'unreadable' }),+ { detail: JSON.stringify(scan),fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,argv: ['git', '-C', ctx.root, 'log', '--stat', `${ctx.trackingRef}..${target}`],why: 'Lists the unpublished commits the scan refused; read-only. A secret pushed to the remote stays in its history.',diff --git a/src/core/git/range-secret-scan.ts b/src/core/git/range-secret-scan.tsindex 220b22ab7a..8c9e02bccd 100644--- a/src/core/git/range-secret-scan.ts+++ b/src/core/git/range-secret-scan.ts@@ -2,71 +2,217 @@* Secret scan over the commits an automatic publish pushes. A commit gbrain did not write (a script's plain* `git commit`) never passed the write path's scan, so the publish scans, under its publish lock and for the exact* commit it pushes, what each commit in `base..head` adds: its message, the lines it adds file by file (a value a later- * commit removed is still in the pushed history), and for a merge commit the lines it adds that neither parent has+ * commit removed is still in the pushed history), and for a merge commit the lines it adds that no parent has* (a conflict resolution). The workspace allowlist (`.gbrain-scan-allow`: path globs and fingerprints) applies.- * Findings carry the path, line, rule, fingerprint and commit, never the matched value. The diff is forced to text and- * its prefixes and size threshold are pinned, so no attribute or user setting decides what is scanned; added text that- * holds a NUL byte is binary by content and carries no lines. A file whose added text is over the scan cap cannot be scanned and is reported as such, so callers refuse. A commit- * in the range that changes a file deciding what the scan sees (`.gbrain-scan-allow`, a `.gitattributes`) is reported- * too, so callers refuse rather than let the published commits widen their own gate.+ * Findings carry the path, line, rule, fingerprint and commit, never the matched value.+ *+ * Only plumbing reads the commits (`rev-list`, `cat-file commit`, one `diff-tree --stdin --root --cc`), so no log, diff or+ * encoding setting changes what is read, and replace refs are off. The diff streams to a private temporary file and is+ * read in chunks, so memory stays bounded. Binary detection is git's own (a NUL in a blob's first 8000 bytes), with+ * attributes read from the empty tree: a file git still calls binary is checked by its own bytes when its old side was+ * not empty or attributes could still apply, and a text file is then scanned whole. Added text over the scan cap is+ * reported as unscanned, and a commit that changes a file deciding what the scan sees (`.gbrain-scan-allow`, a+ * `.gitattributes`) as a gate change, so callers refuse. Output the parser does not recognise, a git failure or a run+ * past the time budget sets `unreadable` instead of returning a partial result.*/+import { spawnSync } from 'node:child_process';+import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, readSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { isAbsolute, join } from 'node:path';+import { GIT_READ_ENV, gitChildEnv } from '../git-env.ts';+import { GIT_ENV } from '../git-transport.ts';import { loadWorkspaceAllowlist, pathAllowlisted, SCAN_ALLOW_FILENAME } from '../secret-scan-allowlist.ts';import { scanText, SCAN_MAX_FILE_BYTES } from '../secret-scan.ts';export interface RangeSecretFinding { path: string; commit: string; line: number; pattern: string; fingerprint: string }-export interface RangeScan { findings: RangeSecretFinding[]; unscanned: Array<{ path: string; commit: string }>; gate_changes: Array<{ path: string; commit: string }> }--/** The `git log` arguments whose output findingsInLog reads. */-export function rangeScanArgs(base: string, head: string): string[] {- return ['-c', 'core.quotePath=false', '-c', 'core.attributesFile=/dev/null', '-c', 'core.bigFileThreshold=2g', 'log', '--no-renames', '--no-ext-diff', '--no-textconv', '--no-color',- '--diff-merges=dense-combined', '--text', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '-p', '--format=commit %H%n%B%n%x00', `${base}..${head}`, '--'];+export interface RangeScan {+ findings: RangeSecretFinding[]; unscanned: Array<{ path: string; commit: string }>; gate_changes: Array<{ path: string; commit: string }>;+ /** Set when the commits could not be read completely; the other lists are then partial. */+ unreadable?: string;}/** The commit message as `path` in a finding. */export const MESSAGE_PATH = '(commit message)';-export function findingsInLog(root: string, log: string): RangeScan {- const allowlist = loadWorkspaceAllowlist(root);+const SNIFF_BYTES = 8000;+const BIG_FILE_THRESHOLD = 512 * 1024 * 1024;+const CONFIG = ['-c', 'core.quotePath=false', '-c', 'core.attributesFile=/dev/null', '-c', `core.bigFileThreshold=${BIG_FILE_THRESHOLD}`];+const DIFF = ['diff-tree', '--stdin', '-r', '-p', '--root', '--cc', '--no-renames', '--no-ext-diff', '--no-textconv', '--no-color',+ '--full-index', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0'];++class Unreadable extends Error {}++type Run = ReturnType<typeof spawnSync>;+function run(root: string, args: string[], deadline: number, opts: { input?: string; out?: number; maxBuffer?: number } = {}): Run {+ const timeout = deadline - Date.now();+ if (timeout <= 0) throw new Unreadable('the scan ran past its time budget');+ return spawnSync('git', ['-C', root, ...args], { input: opts.input ?? '', stdio: ['pipe', opts.out ?? 'pipe', 'pipe'], timeout,+ maxBuffer: opts.maxBuffer ?? 64 * 1024 * 1024, env: gitChildEnv({ ...GIT_ENV, ...GIT_READ_ENV, LC_ALL: 'C', GIT_NO_REPLACE_OBJECTS: '1' }) });+}+function must(r: Run, what: string): Buffer {+ if (r.error || r.status !== 0) {+ const why = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT' ? 'timed out' : String(r.stderr ?? '').trim() || r.error?.message || `exit ${r.status}`;+ throw new Unreadable(`git ${what} failed: ${why.slice(0, 300)}`);+ }+ return r.stdout as Buffer;+}++/** Lines of an open file read in 1 MiB chunks; a line longer than `limit` bytes keeps its first `limit` bytes and is marked long. */+function* fileLines(fd: number, limit: number): Generator<{ text: string; long: boolean }> {+ const chunk = Buffer.alloc(1 << 20);+ let pending: Buffer[] = [], size = 0, position = 0;+ const take = (piece: Buffer) => { if (size < limit) pending.push(Buffer.from(piece.subarray(0, limit - size))); size += piece.length; };+ const line = () => { const out = { text: Buffer.concat(pending).toString('utf8'), long: size > limit }; pending = []; size = 0; return out; };+ for (let n; (n = readSync(fd, chunk, 0, chunk.length, position)) > 0; position += n) {+ const view = chunk.subarray(0, n);+ let start = 0;+ for (let nl; (nl = view.indexOf(10, start)) !== -1; start = nl + 1) { take(view.subarray(start, nl)); yield line(); }+ if (start < n) take(view.subarray(start));+ }+ if (size) yield line();+}++const C_ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 };+/** A path as git prints it: bare, or C-quoted when it holds a special character. Null when the quoting is malformed. */+function unquote(text: string): string | null {+ if (!text.startsWith('"')) return text;+ if (text.length < 2 || !text.endsWith('"')) return null;+ const bytes: number[] = [];+ for (let i = 1; i < text.length - 1; i++) {+ if (text[i] !== '\\') { bytes.push(...Buffer.from(text[i]!)); continue; }+ const octal = /^[0-7]{3}/.exec(text.slice(i + 1));+ if (octal) { bytes.push(parseInt(octal[0], 8)); i += 3; continue; }+ const escaped = C_ESCAPES[text[++i] ?? ''];+ if (escaped === undefined) return null;+ bytes.push(escaped);+ }+ return Buffer.from(bytes).toString('utf8');+}++/** True when git's attribute lookup, pointed at the empty tree, cannot apply any attribute (git 2.42+, no info/attributes rule). */+function attributesNeutral(root: string, deadline: number): boolean {+ const version = /git version (\d+)\.(\d+)/.exec(must(run(root, ['version'], deadline), 'version').toString());+ if (!version || Number(version[1]) < 2 || (Number(version[1]) === 2 && Number(version[2]) < 42)) return false;+ const rel = must(run(root, ['rev-parse', '--git-path', 'info/attributes'], deadline), 'rev-parse').toString().trim();+ const file = isAbsolute(rel) ? rel : join(root, rel);+ return !existsSync(file) || readFileSync(file, 'utf8').split('\n').every(line => !line.trim() || line.trim().startsWith('#'));+}++export function scanRange(root: string, base: string, head: string, timeoutMs = 300_000): RangeScan {+ const deadline = Date.now() + timeoutMs;const scan: RangeScan = { findings: [], unscanned: [], gate_changes: [] };- let commit = '', path: string | null = null, next = 0, combined = false, inMessage = false, header = false;- let added: string[] = [], at: number[] = [];- const flush = () => {- if (path && added.length && (path === MESSAGE_PATH || !pathAllowlisted(path, allowlist))) {- const text = added.join('\n');- if (path !== MESSAGE_PATH && text.includes('\0')) { /* binary by content */ }- else if (Buffer.byteLength(text) > SCAN_MAX_FILE_BYTES) scan.unscanned.push({ path, commit });- else for (const f of scanText(text, { allowlist })) scan.findings.push({ path, commit, line: at[f.line - 1] ?? f.line, pattern: f.pattern, fingerprint: f.fingerprint });- }- added = []; at = [];+ const allowlist = loadWorkspaceAllowlist(root);+ const scanned = (path: string, commit: string, text: string, lineAt: (line: number) => number = line => line) => {+ if (Buffer.byteLength(text) > SCAN_MAX_FILE_BYTES) { scan.unscanned.push({ path, commit }); return; }+ for (const f of scanText(text, { allowlist })) scan.findings.push({ path, commit, line: lineAt(f.line), pattern: f.pattern, fingerprint: f.fingerprint });};- for (const line of log.split('\n')) {- if (inMessage) {- if (line === '\0') { flush(); inMessage = false; path = null; continue; }- added.push(line); at.push(added.length);- continue;+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-range-scan-'));+ try {+ const commits = must(run(root, ['rev-list', `${base}..${head}`, '--'], deadline), 'rev-list').toString().split('\n').filter(Boolean);+ if (!commits.length) return scan;++ for (const commit of commits) {+ const raw = run(root, ['cat-file', 'commit', commit], deadline, { maxBuffer: SCAN_MAX_FILE_BYTES + 1024 * 1024 });+ if ((raw.error as NodeJS.ErrnoException | undefined)?.code === 'ENOBUFS') { scan.unscanned.push({ path: MESSAGE_PATH, commit }); continue; }+ const object = must(raw, 'cat-file commit');+ const split = object.indexOf('\n\n');+ const encoding = /^encoding (.+)$/m.exec(object.subarray(0, split < 0 ? object.length : split).toString('latin1'))?.[1]?.trim() ?? 'utf-8';+ let message: string;+ try { message = new TextDecoder(encoding).decode(split < 0 ? Buffer.alloc(0) : object.subarray(split + 2)); } catch {+ scan.unscanned.push({ path: MESSAGE_PATH, commit }); continue;+ }+ scanned(MESSAGE_PATH, commit, message);}- if (line.startsWith('commit ') && /^commit [0-9a-f]{40,64}$/.test(line)) { flush(); commit = line.slice(7); path = MESSAGE_PATH; inMessage = true; continue; }- if (line.startsWith('diff --git ') || line.startsWith('diff --cc ') || line.startsWith('diff --combined ')) {- flush(); path = null; header = true; combined = !line.startsWith('diff --git ');- const named = (combined ? line.replace(/^diff --(?:cc|combined) /, '') : line.replace(/^diff --git "?a\/.*? "?b\//, '')).replace(/"$/, '');- if (named === SCAN_ALLOW_FILENAME || named === '.gitattributes' || named.endsWith('/.gitattributes')) scan.gate_changes.push({ path: named, commit });- continue;++ const neutral = attributesNeutral(root, deadline);+ const attrSource = neutral ? [`--attr-source=${must(run(root, ['hash-object', '-t', 'tree', '--stdin'], deadline), 'hash-object').toString().trim()}`] : [];+ const out = join(dir, 'diff');+ const fd = openSync(out, 'w+', 0o600);+ const binaries: Array<{ commit: string; path: string; blob: string; added: boolean }> = [];+ try {+ must(run(root, [...attrSource, ...CONFIG, ...DIFF], deadline, { input: commits.join('\n') + '\n', out: fd }), 'diff-tree');+ let commit = '', path: string | null = null, header = false, parents = 1, next = 0, bytes = 0, oversized = false;+ let olds: string[] = [], blob = '', added: string[] = [], at: number[] = [];+ const flush = () => {+ if (path && (oversized || added.length) && !pathAllowlisted(path, allowlist)) {+ if (oversized) scan.unscanned.push({ path, commit });+ else scanned(path, commit, added.join('\n'), line => at[line - 1] ?? line);+ }+ added = []; at = []; bytes = 0; oversized = false;+ };+ const unexpected = (line: string) => new Unreadable(`git diff-tree printed a line the scan does not recognise in ${commit.slice(0, 12) || 'the range'}: ${JSON.stringify(line.slice(0, 80))}`);+ for (const { text: line, long } of fileLines(fd, SCAN_MAX_FILE_BYTES + 1)) {+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(line)) { flush(); commit = line; path = null; header = false; continue; }+ if (line.startsWith('diff --git ') || line.startsWith('diff --cc ') || line.startsWith('diff --combined ')) {+ flush();+ if (!commit || long) throw unexpected(line);+ if (line.startsWith('diff --git ')) {+ const pair = line.slice('diff --git '.length), half = (pair.length - 1) / 2;+ const left = Number.isInteger(half) && pair[half] === ' ' ? unquote(pair.slice(0, half)) : null;+ const right = left === null ? null : unquote(pair.slice(half + 1));+ path = left?.startsWith('a/') && right?.startsWith('b/') && left.slice(2) === right.slice(2) ? right.slice(2) : null;+ } else path = unquote(line.replace(/^diff --(?:cc|combined) /, ''));+ if (path === null) throw unexpected(line);+ if (path === SCAN_ALLOW_FILENAME || path === '.gitattributes' || path.endsWith('/.gitattributes')) scan.gate_changes.push({ path, commit });+ header = true; olds = []; blob = '';+ continue;+ }+ const hunk = /^(@{2,}) ((?:-\d+(?:,\d+)? )+)\+(\d+)(?:,\d+)? \1(?: |$)/.exec(line);+ if (hunk && path && !long) {+ parents = hunk[1]!.length - 1;+ if (hunk[2]!.trim().split(' ').length !== parents) throw unexpected(line);+ header = false; next = Number(hunk[3]);+ continue;+ }+ if (header && path && !long) {+ const index = /^index ((?:[0-9a-f]+,)*[0-9a-f]+)\.\.([0-9a-f]+)(?: [0-7]+)?$/.exec(line);+ if (index) { olds = index[1]!.split(','); blob = index[2]!; continue; }+ if (/^(?:old mode|new mode|deleted file mode|new file mode|mode) [0-7,.]+$/.test(line) || line.startsWith('--- ') || line.startsWith('+++ ')) continue;+ if (line === 'Binary files differ' || /^Binary files .+ differ$/.test(line)) {+ if (blob && !/^0+$/.test(blob)) binaries.push({ commit, path, blob, added: olds.every(old => /^0+$/.test(old)) });+ path = null;+ continue;+ }+ throw unexpected(line);+ }+ if (!path || header) throw unexpected(line);+ if (line.startsWith('\\')) continue;+ const prefix = line.slice(0, parents);+ if (prefix.length < parents || /[^ +-]/.test(prefix)) throw unexpected(line);+ if (prefix.includes('-')) continue;+ if (prefix === '+'.repeat(parents)) {+ bytes += Buffer.byteLength(line) - parents + 1;+ if (long || bytes > SCAN_MAX_FILE_BYTES) { oversized = true; added = []; at = []; }+ else { added.push(line.slice(parents)); at.push(next); }+ }+ next++;+ }+ flush();+ } finally {+ closeSync(fd);+ }++ const sizes = new Map<string, number>();+ const fresh = binaries.filter(b => neutral && b.added);+ if (fresh.length) {+ const check = must(run(root, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], deadline, { input: fresh.map(b => b.blob).join('\n') + '\n' }), 'cat-file --batch-check');+ for (const row of check.toString().split('\n')) { const [name, size] = row.split(' '); if (name && size) sizes.set(name, Number(size)); }}- const hunk = /^@@@? -\d+(?:,\d+)? (?:-\d+(?:,\d+)? )?\+(\d+)(?:,\d+)? @@@?/.exec(line);- if (hunk) { header = false; next = Number(hunk[1]); continue; }- if (header) {- if (!line.startsWith('+++ ')) continue;- path = line === '+++ /dev/null' ? null : line.slice(4).replace(/^"?b\//, '').replace(/"$/, '');- continue;+ for (const b of binaries) {+ if (pathAllowlisted(b.path, allowlist)) continue;+ if (neutral && b.added && (sizes.get(b.blob) ?? Infinity) <= BIG_FILE_THRESHOLD) continue;+ const sniff = run(root, ['cat-file', 'blob', b.blob], deadline, { maxBuffer: SNIFF_BYTES });+ if ((sniff.error as NodeJS.ErrnoException | undefined)?.code !== 'ENOBUFS') must(sniff, 'cat-file blob');+ if ((sniff.stdout as Buffer).subarray(0, SNIFF_BYTES).includes(0)) continue;+ const whole = run(root, ['cat-file', 'blob', b.blob], deadline, { maxBuffer: SCAN_MAX_FILE_BYTES });+ if ((whole.error as NodeJS.ErrnoException | undefined)?.code === 'ENOBUFS') { scan.unscanned.push({ path: b.path, commit: b.commit }); continue; }+ scanned(b.path, b.commit, must(whole, 'cat-file blob').toString('utf8'));}- if (!path) continue;- if (combined) {- const prefix = line.slice(0, 2);- if (prefix.includes('-') || prefix.length < 2) continue;- if (prefix === '++') { added.push(line.slice(2)); at.push(next); }- next++;- } else if (line.startsWith('+')) { added.push(line.slice(1)); at.push(next++); }+ return scan;+ } catch (e) {+ if (e instanceof Unreadable) return { ...scan, unreadable: e.message };+ throw e;+ } finally {+ rmSync(dir, { recursive: true, force: true });}- flush();- return scan;}diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex a6627b6bd5..7503061a5a 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -406,6 +406,7 @@ describe('#7619 split rules', () => {'src/core/git-head.ts': 'git child argv','src/core/git-remote.ts': 'git child argv','src/core/git/commit-push.ts': 'git child argv',+ 'src/core/git/range-secret-scan.ts': 'git child argv','src/core/hardened-git.ts': 'git child argv (the reason-trailer log options)','src/core/persistence/checkout-state.ts': 'git child argv','src/core/persistence/effect-git.ts': 'git child argv',diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 16daec3912..6007fb64ca 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6840,7 +6840,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/guarded-publish.test.ts b/test/guarded-publish.test.tsindex bccc46a7dd..5d1b42c65b 100644--- a/test/guarded-publish.test.ts+++ b/test/guarded-publish.test.ts@@ -145,3 +145,45 @@ test('attributes outside the range and diff settings never hide a secret or a gaexpect(widened.message).toContain('.gbrain-scan-allow (changes what the scan sees, ');expect(remoteTip(noprefix)).toBe(noprefix.base);});++test('a NUL byte past the first 8000 bytes of a text file never hides a secret in it', () => {+ const r = repo('late-nul');+ commit(r.root, 'notes.md', `Deploy token ${token}\n${'x'.repeat(10_000)}\0tail\n`);+ const error = refused(() => publish(r.root));+ expect(error.code).toBe('publish_secret_found');+ expect(error.message).toContain('notes.md:1 (');+ expect(remoteTip(r)).toBe(r.base);+});++test('a repository log encoding never hides a secret in a commit message', () => {+ const r = repo('encoding');+ git(r.root, 'config', 'i18n.logOutputEncoding', 'UTF-16LE');+ commit(r.root, 'page.md', 'a page\n', `rotate ${token}`);+ expect(refused(() => publish(r.root)).message).toContain('(commit message):1 (');+ expect(remoteTip(r)).toBe(r.base);+});++test('a root commit merged in from unrelated history is scanned whatever log.showRoot says', () => {+ const r = repo('showroot');+ git(r.root, 'config', 'log.showRoot', 'false');+ git(r.root, 'checkout', '-q', '--orphan', 'imported');+ git(r.root, 'rm', '-rqf', '.');+ commit(r.root, 'imported.md', `Deploy token ${token}\n`);+ git(r.root, 'checkout', '-q', 'main');+ git(r.root, 'merge', '-q', '--allow-unrelated-histories', '--no-edit', 'imported');+ expect(refused(() => publish(r.root)).message).toContain('imported.md:1 (');+ expect(remoteTip(r)).toBe(r.base);+});++test('commits the scan cannot read refuse with their own code, not as secrets to remove', () => {+ const r = repo('unreadable');+ commit(r.root, 'notes.md', 'plain text\n');+ const blob = git(r.root, 'rev-parse', 'HEAD:notes.md');+ git(r.root, 'rm', '-q', 'notes.md'); git(r.root, 'commit', '-qm', 'drop notes');+ rmSync(join(r.root, '.git', 'objects', blob.slice(0, 2), blob.slice(2)));+ const error = refused(() => publish(r.root));+ expect(error.code).toBe('publish_scan_unreadable');+ expect(error.message).toContain('Nothing was pushed.');+ expect(error.message).not.toContain('look like secrets');+ expect(remoteTip(r)).toBe(r.base);+});