Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (voices round)
garrytan98308e0a5aa7
diff --git a/docs/designs/REFRESH_WRITE_BARRIER.md b/docs/designs/REFRESH_WRITE_BARRIER.mdindex ae2d198800..43dad5ccde 100644--- a/docs/designs/REFRESH_WRITE_BARRIER.md+++ b/docs/designs/REFRESH_WRITE_BARRIER.md@@ -229,8 +229,10 @@ Deferred rows are durable rows; nothing about them lives in process memory.operationally on a clean deploy watch and on every routed producer of that brain having its threeproofs (pending to committed, pending to conflict, restart), reported by the box lane. Turning itoff stops new deferrals; existing deferred rows still drain.-- **Downgrade order:** turn the flag off → wait until no row is `deferred` → downgrade.- `gbrain upgrade --check-downgrade` (read-only, new) exits 0 when no deferred row remains and exits+- **Downgrade order:** turn the flag off → wait until every write admitted deferred has finished → downgrade.+ `gbrain upgrade --check-downgrade` (read-only, new) exits 0 when none remains (a released row that+ a consumer claimed counts until it commits or fails, because an older consumer that recovers it+ skips the refresh-change check) and exits3 with `downgrade_blocked_deferred_writes` (count, oldest age) otherwise; the box's automaticbinary restore calls it and refuses to restore an older binary on exit 3. Safety does not rest onthat gate (an older binary cannot claim the rows); liveness does: after a downgrade they would wait@@ -371,8 +373,9 @@ its owner host, under the worktree's native writer lock (the owner check `source(and honours a global `core.hooksPath`), so installing there would also guard a person's ownlinked checkout. The owner path installs into a hooks directory private to that worktree(`<worktree git dir>/gbrain-hooks`) and points that worktree's `core.hooksPath` at it with- `git config --worktree` (enabling `extensions.worktreeConfig` only when the repository has linked- worktrees). It refuses, changing nothing, when another tool's hook already lives at the effective+ `git config --worktree`, enabling `extensions.worktreeConfig` first so the setting never lands in the+ shared config; the enforce hook also lets through any worktree whose git dir is not its own, so a+ worktree that inherits the hooks path is not guarded. It refuses, changing nothing, when another tool's hook already lives at the effectivepath, and `--status` reports the effective hooks path.- **Enforce mode** refuses plain commits, `--amend`, `--no-verify` commits, and, unlike the opt-inguard, also cherry-pick, revert, rebase and sequencer commits: in a managed worktree only the ownerdiff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.mdindex 6ca4764213..ce913ee7b7 100644--- a/docs/guides/shared-checkout-git.md+++ b/docs/guides/shared-checkout-git.md@@ -588,7 +588,11 @@ writes through the door and the in-memory merges are plumbing that runs nocommit hook, sync's auto-init turns hooks off, `commit-push` names the commitlock it holds, and a refresh fast-forward runs no commit hook.`gbrain sources guard <source> --status` prints whether it is installed, its-mode and the effective hooks path; `--uninstall` removes it.+mode and the effective hooks path; `--uninstall` removes it. A worktree added+later with `git worktree add` inherits the hooks path (git copies+`config.worktree`); the guard lets its commits through, and+`git config --worktree --unset core.hooksPath` in that worktree restores its+own hooks.A writer that turns hooks off itself (`git -c core.hooksPath=/dev/null commit`)is not stopped by any hook. The [commit ledger](#commit-ledger) names it.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 1e98e4da63..01af859b4e 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -622,8 +622,8 @@ syncing it is accepted and waits for the refresh instead of being refused `workteach active refresh.- <a id="downgrade_blocked_deferred_writes"></a>Before installing an older release, turn the barrieroff and wait for `gbrain upgrade --check-downgrade` to exit 0. It exits 3 with- `downgrade_blocked_deferred_writes` (count and oldest age) while deferred writes remain, because an- older release never drains them.+ `downgrade_blocked_deferred_writes` (count and oldest age) while any write admitted deferred has not+ finished, waiting or already claimed, because an older release never drains them safely.## Managed sync drain stopsdiff --git a/src/commands/doctor/checks/foreign-writers.ts b/src/commands/doctor/checks/foreign-writers.tsindex 033006d2e7..bc3e620388 100644--- a/src/commands/doctor/checks/foreign-writers.ts+++ b/src/commands/doctor/checks/foreign-writers.ts@@ -205,12 +205,17 @@ interface RepoReport {function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial: boolean } {const ledger = readLedger(repo.common);const ledgered = new Set<string>();- const intents: { head_before: string | null; msg: string; t: number }[] = [];+ const intents: { head_before: string | null; msg: string; t: number; who: string; resolved: boolean }[] = [];let start: number | null = null;for (const r of ledger) {if (r.e === 'start') start = Date.parse(r.t);- else if (r.e === 'commit') ledgered.add(r.sha);- else intents.push({ head_before: r.head_before, msg: r.msg_sha256, t: Date.parse(r.t) });+ else if (r.e === 'commit') {+ ledgered.add(r.sha);+ // The intent this commit line completes: the same process's newest open one. Only an intent left open can explain a commit.+ const who = `${r.host}\0${r.pid}\0${r.writer}`;+ const open = intents.findLast(i => !i.resolved && i.who === who);+ if (open) open.resolved = true;+ } else intents.push({ head_before: r.head_before, msg: r.msg_sha256, t: Date.parse(r.t), who: `${r.host}\0${r.pid}\0${r.writer}`, resolved: false });}if (start === null && ledger.length) start = Date.parse(ledger[0]!.t);const startSec = start === null ? null : Math.floor(start / 1000);@@ -256,7 +261,10 @@ function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial:if (Date.now() > deadline) { partial = true; break; }const batch = open.slice(i, i + 200);const out = git(anyTop, ['log', '--no-walk', '--ignore-missing', '--stdin', '--format=%H%x00%P%x00%ct%x00%cn <%ce>%x00%s%x00%B%x1e'], batch.map(c => c.sha).join('\n') + '\n');- if (out === null) { partial = true; break; }+ if (out === null) {+ for (const c of batch) report.unknown.push({ ref: c.ref, old: '', new: c.sha, time: new Date(c.time * 1000).toISOString() });+ continue;+ }const meta = new Map<string, string[]>();for (const rec of out.split('\x1e')) {const f = rec.replace(/^\n/, '').split('\0');@@ -271,7 +279,7 @@ function scanRepo(repo: Repo, deadline: number): { report: RepoReport; partial:const guard = c.kind === 'plain' ? enforceGuardSince(c.gitDir) : null;const commit: ForeignCommit = { sha: c.sha, kind: c.kind, guard_bypassed: guard !== null && guard <= ct * 1000, ref: c.ref, time: new Date(ct * 1000).toISOString(), subject: f[4]!, committer: f[3]!, checkout: c.checkout };const digest = messageDigest(f[5]!);- const matched = intents.some(t => t.head_before === (parents[0] ?? null) && t.msg === digest && ct * 1000 >= t.t - 1000 && ct * 1000 - t.t <= UNCONFIRMED_WINDOW_MS);+ const matched = intents.some(t => !t.resolved && t.head_before === (parents[0] ?? null) && t.msg === digest && ct * 1000 >= t.t - 1000 && ct * 1000 - t.t <= UNCONFIRMED_WINDOW_MS);(matched ? report.unconfirmed : report.foreign).push(commit);}}@@ -318,7 +326,7 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {window: reports.map(r => ({ common: r.common, from: r.window_from, to: new Date(now).toISOString(), ledger_start: r.ledger_start, oldest_reflog: r.oldest_reflog, uncovered: r.uncovered, ledger: r.ledger })),foreign, unconfirmed, unknown, dirty: dirty.slice(0, MAX_LISTED), dirty_count: dirty.length, dirty_warn_after_minutes: FOREIGN_DIRTY_WARN_MS / 60_000, partial,};- const scope = `${repos.length} repositor${repos.length === 1 ? 'y' : 'ies'}${partial ? ' (partial: the scan stopped at doctor\'s budget)' : ''}`;+ const scope = `${repos.length} repositor${repos.length === 1 ? 'y' : 'ies'}${partial ? ' (partial)' : ''}`;if (foreign.length) {const newest = foreign[0]!;const line = `Commit ${newest.sha.slice(0, 12)} (${label(newest)}, "${newest.subject}", ${newest.time}) in ${newest.checkout} was not made by gbrain; route that writer through gbrain git commit-push or a page write`;@@ -330,8 +338,9 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {verify: doctorVerify('foreign_writers') } });return checks;}- if (unconfirmed.length || unknown.length || old.length) {+ if (unconfirmed.length || unknown.length || old.length || partial) {const parts = [+ partial ? 'the scan did not finish (doctor\'s time budget, or a git status that failed), so part of the window is unchecked' : '',unconfirmed.length ? `${unconfirmed.length} commit(s) match a gbrain intent whose commit line is missing (a crash between git commit and the ledger append): ${unconfirmed.slice(0, 5).map(c => c.sha.slice(0, 12)).join(', ')}; they are not written back to the ledger` : '',unknown.length ? `${unknown.length} ref move(s) whose commits could not be read: ${unknown.slice(0, 5).map(u => `${u.ref} -> ${u.new.slice(0, 12)}`).join(', ')}` : '',old.length ? `${old.length} page file(s) have been untracked or modified for more than ${FOREIGN_DIRTY_WARN_MS / 60_000} minutes with no gbrain commit pending: ${old.slice(0, 5).map(d => `${d.path} (${d.state}, ${ago(d.age_ms)})`).join(', ')}${old.length > 5 ? ', ...' : ''}` : '',diff --git a/src/commands/git.ts b/src/commands/git.tsindex 1d0b561b03..51702ed3d6 100644--- a/src/commands/git.ts+++ b/src/commands/git.ts@@ -11,7 +11,8 @@* gbrain git commit-push --pending [--path <dir>] [-m <msg>]* gbrain git guard [--install | --uninstall] [--path <dir>] [--json]*/-import { realpathSync } from 'node:fs';+import { existsSync, realpathSync } from 'node:fs';+import { join } from 'node:path';import { commitAndPush, checkoutRoot, pullShared, scopePaths, COMMIT_LOCK_NAME, SOURCE_ROOT_CONFIG, type Resolution } from '../core/git/commit-push.ts';import { guardStatus, installGuard, uninstallGuard } from '../core/git/commit-guard.ts';import { appendPushLog } from '../core/brain-repo-durability.ts';@@ -138,14 +139,17 @@ function parseResolutions(specs: string[]): Map<string, Resolution> {/*** #8662: on a host whose brain records its source checkouts, a checkout resolved from the working directory that is none of- * them and carries no gbrain.sourceRoot marker is refused before anything is staged (a wrapper that changed into another- * repository). An explicit --path names its checkout and is not checked here (a legacy source is not in that record).+ * them and carries no mark of a gbrain brain checkout is refused before anything is staged (a wrapper that changed into+ * another repository). A legacy source is not in that record, so `gbrain sources harden`'s marks admit it: a+ * gbrain.sourceRoot or gbrain.cliPath entry, or the committed scripts/brain-commit-push.sh (whose own calls pass no --path).+ * An explicit --path names its checkout and is not checked here.*/function assertSourceCheckout(repo: string): void {const registered = registeredManagedRootRecords();if (!registered.length || managedFilesystemRootFor(repo)) return;+ if (existsSync(join(repo, 'scripts', 'brain-commit-push.sh'))) return;try {- execFileSync('git', ['-C', repo, 'config', '--local', '--get-all', SOURCE_ROOT_CONFIG], { env: gitChildEnv({ ...GIT_ENV }), stdio: ['ignore', 'pipe', 'ignore'] });+ execFileSync('git', ['-C', repo, 'config', '--local', '--get-regexp', `^(${SOURCE_ROOT_CONFIG}|gbrain.clipath)$`.replace(/\./g, '\\.').toLowerCase()], { env: gitChildEnv({ ...GIT_ENV }), stdio: ['ignore', 'pipe', 'ignore'] });return;} catch { /* no marker */ }const first = registered[0]!.root;@@ -196,7 +200,7 @@ export async function runGit(args: string[]): Promise<number> {if (p.dryRun) {const lock = execFileSync('git', ['-C', repo, 'rev-parse', '--git-path', COMMIT_LOCK_NAME], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();const branch = execFileSync('git', ['-C', repo, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { env: gitChildEnv({ ...GIT_ENV }) }).toString().trim();- const paths = p.pull || p.pushOnly ? [] : scopePaths(repo, p.paths, cwd);+ const paths = p.pull || p.pushOnly || !p.paths.length ? [] : scopePaths(repo, p.paths, cwd);emit(json, { dry_run: true, repo, branch, lock, paths, mode: p.pull ? 'pull' : p.pushOnly ? 'push-only' : 'commit-push' },`dry run: ${p.pull ? 'pull' : p.pushOnly ? 'push-only' : `commit ${paths.join(' ')}`} on ${branch} in ${repo} (lock ${lock}); nothing written`);return 0;diff --git a/src/core/git/commit-guard.ts b/src/core/git/commit-guard.tsindex f2ea7beced..2724f3e629 100644--- a/src/core/git/commit-guard.ts+++ b/src/core/git/commit-guard.ts@@ -40,7 +40,9 @@ ${enforce ? `${GUARD_ENFORCE_MARKER}# A person can bypass it for one command: ${GUARD_BYPASS_ENV}=off git <command>[ "\${${GUARD_BYPASS_ENV}:-}" = off ] && exit 0[ "\${2:-}" = merge ] && exit 0-for _op in ${enforce ? 'MERGE_HEAD' : 'MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer'}; do+${enforce ? `# git worktree add copies config.worktree, so a worktree added after the install inherits this hooks path: only the owner worktree is guarded.+[ "$(cd "$(git rev-parse --absolute-git-dir)" && pwd -P)" = "$(cd "$(dirname "$0")/.." && pwd -P)" ] || exit 0+` : ''}for _op in ${enforce ? 'MERGE_HEAD' : 'MERGE_HEAD CHERRY_PICK_HEAD REVERT_HEAD rebase-merge rebase-apply sequencer'}; do[ -e "$(git rev-parse --git-path "$_op")" ] && exit 0done_lock="$(git rev-parse --path-format=absolute --git-path ${COMMIT_LOCK_NAME} 2>/dev/null || true)"@@ -190,8 +192,7 @@ export function installOwnerGuard(worktree: string, mode: GuardMode): OwnerGuardchanged = true;}if (p.effective !== p.own) {- const linked = gitMust(p.root, ['worktree', 'list', '--porcelain']).split('\n').filter(l => l.startsWith('worktree ')).length > 1;- if (linked && !before.worktree_config) enableWorktreeConfig(p.root, p.common);+ if (!before.worktree_config) enableWorktreeConfig(p.root, p.common);gitMust(p.root, ['config', '--worktree', 'core.hooksPath', p.own]);changed = true;}diff --git a/src/core/persistence/refresh-barrier.ts b/src/core/persistence/refresh-barrier.tsindex db0ba668f2..6a442ee95a 100644--- a/src/core/persistence/refresh-barrier.ts+++ b/src/core/persistence/refresh-barrier.ts@@ -106,10 +106,11 @@ export async function refreshReleased(engine: SqlEngine, refreshId: string | nulreturn row?.released === true;}-/** Deferred writes still waiting, for `gbrain upgrade --check-downgrade` and writer status. */+/** Writes admitted deferred that have not finished (waiting, or claimed and still publishing), for `gbrain upgrade --check-downgrade`. */export async function deferredBacklog(engine: SqlEngine): Promise<{ count: number; oldest_age_ms: number }> {const [row] = await engine.executeRaw<{ count: number; oldest_age_ms: number | null }>(`SELECT count(*)::int AS count,- (EXTRACT(EPOCH FROM now()-min(created_at))*1000)::bigint AS oldest_age_ms FROM persistence_requests WHERE state='deferred'`);+ (EXTRACT(EPOCH FROM now()-min(created_at))*1000)::bigint AS oldest_age_ms FROM persistence_requests+ WHERE deferred_refresh_id IS NOT NULL AND state IN ('deferred','queued','running','recovering')`);return { count: Number(row?.count ?? 0), oldest_age_ms: Number(row?.oldest_age_ms ?? 0) };}diff --git a/src/core/schema-migrations/v290-refresh-write-barrier.ts b/src/core/schema-migrations/v290-refresh-write-barrier.tsindex a46627f738..b44460641c 100644--- a/src/core/schema-migrations/v290-refresh-write-barrier.ts+++ b/src/core/schema-migrations/v290-refresh-write-barrier.ts@@ -1,5 +1,5 @@import type { Migration } from './types.ts';-import { buildIndexOnline, migrationNotice } from './helpers.ts';+import { buildIndexOnline, migrationNotice, runMigrationStatement } from './helpers.ts';const PERSISTENCE_DEFERRED_INDEX = { name: 'persistence_requests_deferred', table: 'persistence_requests',sql: `CREATE INDEX IF NOT EXISTS persistence_requests_deferred ON persistence_requests(worktree_id, sequence) WHERE state='deferred'` } as const;@@ -19,10 +19,11 @@ const PERSISTENCE_DEFERRED_INDEX = { name: 'persistence_requests_deferred', tabl// barrier-aware claim of a released refresh), conflict, failed or cancelled.// - persistence_consumers.capabilities: what a live consumer can drain; admission// defers only when every live consumer of the owner host can.-// Postgres swaps the state CHECK and adds the deferred_refresh_id foreign key with-// ADD ... NOT VALID then VALIDATE (no long ACCESS EXCLUSIVE scan of the permanent-// receipts), outside a transaction like v114, and builds the deferred index-// CONCURRENTLY like v223; PGLite does each in one shot. The number is a placeholder+// Postgres swaps the state CHECK and adds the deferred_refresh_id foreign key NOT+// VALID in the SQL batch, then validates each in its own statement from the handler+// (SHARE UPDATE EXCLUSIVE, after the batch's ACCESS EXCLUSIVE is released, so the+// scan of the permanent receipts blocks no reader or writer), and builds the+// deferred index CONCURRENTLY like v223; PGLite does each in one shot. The number is a placeholder// restamped at the merge slot.export const v290: Migration = {version: 290,@@ -42,7 +43,6 @@ export const v290: Migration = {FOREIGN KEY (deferred_refresh_id) REFERENCES persistence_worktree_refreshes(id) NOT VALID;END IF;END $$;- ALTER TABLE persistence_requests VALIDATE CONSTRAINT persistence_requests_deferred_refresh_id_fkey;ALTER TABLE persistence_consumers ADD COLUMN IF NOT EXISTS capabilities text[] NOT NULL DEFAULT '{}';CREATE OR REPLACE FUNCTION gbrain_release_refresh_barrier() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$BEGIN@@ -73,7 +73,6 @@ export const v290: Migration = {ALTER TABLE persistence_requests DROP CONSTRAINT IF EXISTS persistence_requests_state_check;ALTER TABLE persistence_requests ADD CONSTRAINT persistence_requests_state_checkCHECK (state IN ('queued','deferred','running','recovering','committed','conflict','failed','cancelled')) NOT VALID;- ALTER TABLE persistence_requests VALIDATE CONSTRAINT persistence_requests_state_check;`,pglite: `ALTER TABLE persistence_worktree_refreshes ADD COLUMN IF NOT EXISTS barrier_sequence bigint;@@ -112,5 +111,12 @@ export const v290: Migration = {CHECK (state IN ('queued','deferred','running','recovering','committed','conflict','failed','cancelled'));`,},- handler: async engine => { await buildIndexOnline(engine, 290, PERSISTENCE_DEFERRED_INDEX, { notice: migrationNotice }); },+ handler: async engine => {+ if (engine.kind === 'postgres') {+ for (const name of ['persistence_requests_deferred_refresh_id_fkey', 'persistence_requests_state_check']) {+ await runMigrationStatement(engine, 290, `ALTER TABLE persistence_requests VALIDATE CONSTRAINT ${name}`);+ }+ }+ await buildIndexOnline(engine, 290, PERSISTENCE_DEFERRED_INDEX, { notice: migrationNotice });+ },};diff --git a/test/doctor-foreign-writers.test.ts b/test/doctor-foreign-writers.test.tsindex 26f6d66a95..832a52ad23 100644--- a/test/doctor-foreign-writers.test.ts+++ b/test/doctor-foreign-writers.test.ts@@ -219,6 +219,37 @@ test('an open intent matching a commit is unconfirmed (warn) and never written bexpect((await run()).status).toBe('fail');}, 60_000);+test('an intent its own commit line completed never covers a later commit with the same parent and message', async () => {+ const { work } = checkout();+ await register('reused', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ const parent = head(work);+ write(work, 'notes/b.md', 'b\n');+ commitPathsLocked(work, ['notes/b.md'], 'same message', { lockWaitMs: 1000 });+ git(work, ['reset', '-q', '--hard', parent]);+ write(work, 'notes/c.md', 'c\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'same message']);+ const sha = head(work);+ const check = await run();+ expect(check.status).toBe('fail');+ expect((check.details!.foreign as ForeignCommit[]).map(c => c.sha)).toContain(sha);+ expect(check.details!.unconfirmed).toEqual([]);+}, 60_000);++test('a git status that fails leaves the scan partial, which warns instead of reading ok', async () => {+ const { work } = checkout();+ await register('unreadable', join(work, 'notes'));+ write(work, 'notes/a.md', 'a\n');+ commitPathsLocked(work, ['notes/a.md'], 'start the ledger', { lockWaitMs: 1000 });+ expect((await run()).status).toBe('ok');+ writeFileSync(join(work, '.git', 'index'), 'not an index');+ const check = await run();+ expect(check.details!.partial).toBe(true);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('the scan did not finish');+}, 60_000);+test('after rotation the ledgered commits in commit-ledger.1.jsonl still count', async () => {const { work } = checkout();await register('rotated', join(work, 'notes'));diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex b8ac3d4589..1f09d5e509 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -4702,10 +4702,13 @@"dropInvalidConcurrentIndex","lockTableForAnalyze","migrationNotice",+ "migrationStatementTimeoutMs","quietMigrationNotices",- "tableRows"+ "runMigrationStatement",+ "tableRows",+ "withSchemaLockTimeout"],- "sha256": "69eea77482e935be165caf0d2daa8f24128a2a5f252e28d7408ac4ed0f2ac2c9"+ "sha256": "471e0c6ef19acc300cc08d1d86d75713788b121ff04430246bab823c05ca6c19"},"idempotent": true,"name": "refresh_write_barrier",@@ -4719,8 +4722,8 @@"sha256": "042e36e067f6244954b6d5cd895b944ed5a0e3aa3de52b56e1f774f6720e9d7b"},"postgres": {- "length": 3251,- "sha256": "69a8e657a89483837176501f038ca709ef6bb45e1f810ca1f4c11cc3daf699c2"+ "length": 3056,+ "sha256": "e1546db362bf52ca97c2e1d0068c1a7cad3ca5d53763352d7322f2160c97f61e"}},"transaction": false,diff --git a/test/git-commit-push-not-a-source-8662.test.ts b/test/git-commit-push-not-a-source-8662.test.tsindex eb4bea05ec..db19c973e5 100644--- a/test/git-commit-push-not-a-source-8662.test.ts+++ b/test/git-commit-push-not-a-source-8662.test.ts@@ -64,6 +64,10 @@ test('a checkout that is not a registered source is refused checkout_not_a_sourc}expect(git(other, 'rev-parse', 'HEAD')).toBe(before);expect(git(other, 'status', '--porcelain')).toBe('?? notes/');+ // The fix and verify it prescribes run as given: a dry run of the named checkout, with no paths, writes nothing.+ const dry = await runCli(['git', 'commit-push', '--json', '--dry-run', '--path', canonicalFilesystemPath(brain)], { cwd: other, home, env: identity });+ expect(dry.exitCode).toBe(0);+ expect(JSON.parse(dry.stdout)).toMatchObject({ dry_run: true, paths: [] });}, 60_000);test('the registered checkout still commits, a gbrain source marker admits its checkout, and an explicit --path is not checked', async () => {@@ -77,6 +81,15 @@ test('the registered checkout still commits, a gbrain source marker admits its cconst published = await commitPush(marked, home, '--', 'notes/a.md');expect(published.exitCode).toBe(0);expect(JSON.parse(published.stdout)).toMatchObject({ outcome: 'pushed', paths: ['notes/a.md'] });+ // A legacy source checkout hardened by gbrain (its committed helper calls commit-push from the checkout with no --path).+ for (const [name, mark] of [['admitted-clipath', (root: string) => git(root, 'config', '--local', 'gbrain.cliPath', '/usr/local/bin/gbrain')],+ ['admitted-helper', (root: string) => { mkdirSync(join(root, 'scripts')); writeFileSync(join(root, 'scripts', 'brain-commit-push.sh'), '#!/bin/sh\n'); }]] as const) {+ const hardened = otherRepo(name);+ mark(hardened);+ const committed = await commitPush(hardened, home, '--', 'notes/a.md');+ expect(committed.exitCode).toBe(0);+ expect(JSON.parse(committed.stdout)).toMatchObject({ outcome: 'pushed', paths: ['notes/a.md'] });+ }// An explicit --path names its checkout: a legacy source the managed-root record does not list still commits.const legacy = otherRepo('admitted-legacy');const named = await commitPush(dir, home, '--path', legacy, '--', 'notes/a.md');diff --git a/test/refresh-barrier-state-audit.test.ts b/test/refresh-barrier-state-audit.test.tsindex 8d63b1df2b..6275eaf9a1 100644--- a/test/refresh-barrier-state-audit.test.ts+++ b/test/refresh-barrier-state-audit.test.ts@@ -29,6 +29,7 @@ const DECIDED: Record<string, { count: number; why: string }> = {'src/core/persistence/checkpoint-validation.ts': { count: 2, why: 'managed sync' },'src/core/persistence/journal.ts': { count: 8, why: 'claim and head selectors pair the list with RELEASED_DEFERRED (EARLIER_HEAD with its own EARLIER_DEFERRED probe); the two named-sync lists match sync rows, never deferred; the rest are recovery rules' },'src/core/persistence/managed-sync-orphans.ts': { count: 4, why: 'managed sync' },+ 'src/core/persistence/refresh-barrier.ts': { count: 1, why: 'the downgrade backlog names deferred ahead of the open states: a released deferred row that is still queued or running has not published' },'src/core/persistence/page-batch.ts': { count: 1, why: 'batches are never deferred' },'src/core/persistence/schema.ts': { count: 3, why: 'the original state CHECK and partial indexes; deferred rows have their own index' },'src/core/persistence/sync-admission.ts': { count: 1, why: 'managed sync' },diff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.tsindex 7e8b1b0eb8..7a43927edf 100644--- a/test/refresh-write-barrier.test.ts+++ b/test/refresh-write-barrier.test.ts@@ -249,6 +249,13 @@ test('gbrain upgrade --check-downgrade exits 3 downgrade_blocked_deferred_writesexpect(blocked.out).toContain('downgrade_blocked_deferred_writes');});expect((await refresh).status).toBe('completed');+ const rollback = new Error('rollback');+ await expect(f.engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.refresh_barrier','1',true)");+ await tx.executeRaw("UPDATE persistence_requests SET state='running' WHERE id=$1::uuid", [deferred.id]);+ expect((await deferredBacklog(tx)).count).toBe(1);+ throw rollback;+ })).rejects.toBe(rollback);expect((await settle(f, deferred)).state).toBe('committed');const clear = await check();expect(clear.code).toBe(0);diff --git a/test/sources-guard.test.ts b/test/sources-guard.test.tsindex a7bdc1f8c0..ddbdb5c92e 100644--- a/test/sources-guard.test.ts+++ b/test/sources-guard.test.ts@@ -65,6 +65,11 @@ test('owner host only; enforce refuses a plain commit; refresh, effect and doorexpect(installed).toMatchObject({ installed: true, mode: 'enforce', changed: true, source_id: f.alpha });expect(installed.hooks_path).toBe(join(git(f.root, 'rev-parse', '--absolute-git-dir'), 'gbrain-hooks'));expect((await sourcesGuard(f.engine, { sourceId: f.alpha, action: 'install', mode: 'enforce' })).changed).toBe(false);+ const later = join(f.dir, 'later');+ git(f.root, 'worktree', 'add', '-q', '-b', 'later', later);+ writeFileSync(join(later, 'alpha', 'later.md'), page('Later', 'A worktree added after the install commits freely.'));+ git(later, 'add', 'alpha/later.md');+ git(later, 'commit', '-q', '-m', 'commit in a worktree added after the install');writeFileSync(join(f.root, 'alpha', 'stray.md'), page('Stray', 'A plain commit.'));git(f.root, 'add', 'alpha/stray.md');