Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

PR B: /ship review fixes, deterministic foreign_writers listing, routing table

garrytan4cee5bd8eb4f
diff --git a/docs/designs/REFRESH_WRITE_BARRIER.md b/docs/designs/REFRESH_WRITE_BARRIER.md
index 0161bec928..ae2d198800 100644
--- a/docs/designs/REFRESH_WRITE_BARRIER.md
+++ b/docs/designs/REFRESH_WRITE_BARRIER.md
@@ -21,7 +21,8 @@ Two problems keep a shared brain checkout from converging:
PR B turns (1) into a deferred write that commits after the refresh, and makes (2) visible with an
append-only ledger of every commit gbrain makes plus a doctor check that names every other commit.
It also lets the owner install the commit guard on a managed worktree, adds a per-path base check
-to `gbrain git commit-push`, and folds four small bugs (#8615, #8616, #8617, #8662).
+to `gbrain git commit-push`, and folds three small bugs (#8615, #8617, #8662); #8616 is left out
+(below).
Out of scope: who routes the box's writers (lane L2), when the flag is turned on (an operations
decision with stated preconditions, below), and the soak cell (lane L5).
@@ -217,8 +218,9 @@ Deferred rows are durable rows; nothing about them lives in process memory.
`refresh_barrier_1` in `capabilities`; otherwise it refuses as today. A consumer started later by
an older binary still cannot claim a deferred row; what it could do is claim a queued row of the
same worktree ahead of a released deferred one, which is why the upgrade order below requires
- quiescence of older binaries before the flag goes on, and doctor reports a live consumer without
- the capability on a brain with the flag on.
+ quiescence of older binaries before the flag goes on. A doctor check that reports a live consumer
+ without the capability on a brain with the flag on, and a gate on older refreshers, are follow-ups
+ (#8688); until they land the upgrade order below is the only guard.
- **Upgrade order:** apply the migration (harmless with the flag off) → upgrade every binary on the
owner host → restart resident consumers so their heartbeats carry the capability (quiescence) →
watch a clean deploy → turn the flag on per brain.
@@ -310,7 +312,7 @@ commits are plumbing whose ref move happens later, so the line belongs where the
`max(ledger start or oldest retained line, oldest reflog entry)` to now, and doctor prints it.
- **Crash reconciliation (porcelain sites only).** The intent line records `head_before`, the commit
message's sha256 and the writer. A crash between `git commit` and the commit line leaves an open
- intent. doctor lists an unledgered commit as `gbrain_unconfirmed` only when its parent is the
+ intent. doctor lists an unledgered commit under `unconfirmed` only when its parent is the
intent's `head_before`, its message digest matches and it was created within 60 s of the intent;
that is a `warn`, never a `fail`, and it is **never written back into the ledger** automatically,
so an ambiguous outcome cannot certify a foreign commit. A failed ledger append never fails the
@@ -392,9 +394,8 @@ its owner host, under the worktree's native writer lock (the owner check `source
line; the outside branch is read as text only. The file belongs to PR A's planned set, so the hunk
is agreed with that lane first.
- **#8616** (an impossible calendar date such as 2026-09-31 aborted a whole preview window with
- `internal_error` from a `::date` cast): the timeline parser rejects dates that are not real
- calendar dates, so sync and repair agree, and the projection guards its cast so a residual bad
- row refuses its own page (`invalid_timeline_date`, naming the line) while the window continues.
+ `internal_error` from a `::date` cast): left out of this PR. It does not reproduce on current master,
+ where the timeline date guard from #8049 already refuses the bad date; nothing changed here.
- **#8617** (`refresh_source_changed` lost a whole tick): exactly one same-tick retry when the cause
is HEAD moving or work arriving after the drain check, after waiting (bounded by the commit-lock
wait) for the committing writer to finish. Ownership or membership changes are not retried. A
@@ -430,7 +431,7 @@ its owner host, under the worktree's native writer lock (the owner check `source
capacity and age bounds; flag off unchanged; repo-less never defers; MCP `isError: false` pending;
the two refusals non-zero on both surfaces; `--check-downgrade` exit 3 while rows remain.
- **Base check:** a moved blob refuses `commit_base_moved` and leaves the index untouched; `absent`.
-- **Bug folds:** one red-first test each.
+- **Bug folds:** one red-first test each (#8615, #8617, #8662).
## Docs and skills
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 153eb06209..fcd69b24a5 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -455,6 +455,21 @@ file's working copy (`Dp`) only when the path would otherwise be admitted, so
`dirty` counts only those, and a file whose page already matches its commit
reads `matched` even when its working copy is edited.
+## Writes deferred behind a refresh
+
+With `persistence.refresh_barrier` on (off by default), a page write that
+arrives while `gbrain sources refresh` holds its worktree is not refused
+`worktree_refreshing`: it waits in state `deferred` and the caller gets a
+pending receipt. `gbrain sources writer status <id> --json` lists those rows
+with `state: "deferred"` in `requests`, and the `queue` entry for
+`deferred` carries their count and `oldest_age_ms`. They are not stuck while
+the refresh runs: once it completes or aborts they publish in order, and one
+whose file the refresh changed ends `revision_conflict`. A write still waiting
+after `persistence.refresh_barrier_max_wait_ms` ends
+[`refresh_barrier_expired`](write-refusals.md#refresh_barrier_expired) with
+nothing applied: check the refresh, then submit it again with a new request id.
+Before downgrading gbrain, `gbrain upgrade --check-downgrade` must exit 0.
+
## See also
- [`write-refusals.md`](write-refusals.md#held-files-and-content-refusals): every hold code with its recovery.
diff --git a/src/commands/doctor/checks/foreign-writers.ts b/src/commands/doctor/checks/foreign-writers.ts
index 3eb000a3d8..033006d2e7 100644
--- a/src/commands/doctor/checks/foreign-writers.ts
+++ b/src/commands/doctor/checks/foreign-writers.ts
@@ -308,11 +308,12 @@ async function runForeignWriters(ctx: DoctorContext): Promise<Check[]> {
if (found === null) partial = true; else dirty.push(...found);
}
}
- dirty.sort((a, b) => b.age_ms - a.age_ms || a.checkout.localeCompare(b.checkout) || a.path.localeCompare(b.path));
+ const isOld = (d: Dirty) => d.age_ms > FOREIGN_DIRTY_WARN_MS;
+ dirty.sort((a, b) => Number(isOld(b)) - Number(isOld(a)) || a.checkout.localeCompare(b.checkout) || a.path.localeCompare(b.path));
const foreign = reports.flatMap(r => r.foreign).sort((a, b) => b.time.localeCompare(a.time) || a.sha.localeCompare(b.sha));
const unconfirmed = reports.flatMap(r => r.unconfirmed);
const unknown = reports.flatMap(r => r.unknown);
- const old = dirty.filter(d => d.age_ms > FOREIGN_DIRTY_WARN_MS);
+ const old = dirty.filter(isOld).sort((a, b) => b.age_ms - a.age_ms);
const details = {
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,
diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.ts
index ef95f02985..24059d201b 100644
--- a/src/commands/doctor/checks/git-convergence.ts
+++ b/src/commands/doctor/checks/git-convergence.ts
@@ -191,7 +191,7 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
.filter(Boolean).join('; '));
// #5808 (#5606 residue): a managed canonical worktree has no bulk push; its owner pushes page writes and the operator pushes the rest.
const remedy = bad.some(r => isManagedFilesystemPath(r.root))
- ? 'Commit and push them: on a managed canonical worktree the persistence owner commits and pushes page writes (gbrain sources writer status <source> --json shows parked pushes; gbrain sources writer git-durability <source> --enable turns them on), and files that are not pages are committed and pushed with plain git in the checkout, never pulled or rebased; elsewhere gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout'
+ ? 'Commit and push them: on a managed canonical worktree the persistence owner commits and pushes page writes (gbrain sources writer status <source> --json shows parked pushes; gbrain sources writer git-durability <source> --enable turns them on), and files that are not pages are committed with gbrain git commit-push -m <msg> -- <paths> in the checkout, never pulled or rebased; elsewhere gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout'
: 'Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout)';
const stranded = bad.filter(r => r.stranded);
const status = bad.some(r => r.status === 'fail') ? 'fail' : 'warn';
@@ -201,8 +201,8 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())
const push: Action = { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', uncommitted.root], consent: [], actor: 'agent', requires_exclusive: false,
why: 'Publishes the commit just made without moving the checkout.', verify: doctorVerify('git_convergence') };
return { name: 'git_convergence', status, details,
- message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${uncommitted.root} is a managed checkout with Git durability on, ${pages.length} tracked file(s) modified under its source root (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}) and no Git effect queued, running or parked, so no effect will commit them (#7091: earlier releases committed no edits to tracked pages when the source root sits below the repository top). Review and commit them with plain git, then push with the keep-checkout publish. ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}`,
- fix: { ask_user: true, argv: ['git', '-C', uncommitted.root, 'commit', '-m', 'gbrain: persist canonical memory update', '--', ...pages], consent: [], actor: 'user', requires_exclusive: false,
+ message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. ${uncommitted.root} is a managed checkout with Git durability on, ${pages.length} tracked file(s) modified under its source root (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}) and no Git effect queued, running or parked, so no effect will commit them (#7091: earlier releases committed no edits to tracked pages when the source root sits below the repository top). Review them and commit them with gbrain git commit-push, then push with the keep-checkout publish. ${remedy}; this compares with the last fetched upstream and does not fetch.${boundNote}`,
+ fix: { ask_user: true, argv: ['gbrain', 'git', 'commit-push', '--path', uncommitted.root, '-m', 'gbrain: persist canonical memory update', '--', ...pages], consent: [], actor: 'user', requires_exclusive: false,
why: `These tracked files under a durable managed source root differ from the last commit and no Git effect will commit them; committing writes them to the checkout's history, so the user reviews them first.${stranded.length > 1 ? ` ${stranded.length - 1} other checkout(s) are stranded too, see details.roots (stranded).` : ''}`,
user_message: `${pages.length} page file(s) in ${uncommitted.root} were edited but never committed (${pages.slice(0, 5).join(', ')}${pages.length > 5 ? ', ...' : ''}), so they are not on the remote. Commit them and push?`,
verify: doctorVerify('git_convergence'), then: push } };
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 25d6fa1cfb..51e6dbde25 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -232,6 +232,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'think': ['--brain', '--source'],
'transcripts': ['--brain', '--source'],
'trust': ['--brain'],
+ 'upgrade': ['--brain'],
'waiting': ['--brain', '--source'],
'watch': ['--brain', '--source'],
'whoknows': ['--brain'],
diff --git a/src/core/schema-migrations/v290-refresh-write-barrier.ts b/src/core/schema-migrations/v290-refresh-write-barrier.ts
index b8d0be07d4..a46627f738 100644
--- a/src/core/schema-migrations/v290-refresh-write-barrier.ts
+++ b/src/core/schema-migrations/v290-refresh-write-barrier.ts
@@ -1,4 +1,8 @@
import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } 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;
// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
@@ -15,9 +19,11 @@ import type { Migration } from './types.ts';
// 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 with ADD ... NOT VALID then VALIDATE (no long
-// ACCESS EXCLUSIVE scan), outside a transaction like v114; PGLite does it in one
-// shot. The number is a placeholder restamped at the merge slot.
+// 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
+// restamped at the merge slot.
export const v290: Migration = {
version: 290,
name: 'refresh_write_barrier',
@@ -29,9 +35,15 @@ export const v290: Migration = {
ALTER TABLE persistence_worktree_refreshes ADD COLUMN IF NOT EXISTS barrier_sequence bigint;
ALTER TABLE persistence_worktree_refreshes ADD COLUMN IF NOT EXISTS released_at timestamptz;
UPDATE persistence_worktree_refreshes SET released_at=COALESCE(completed_at,updated_at) WHERE state IN ('completed','aborted') AND released_at IS NULL;
- ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS deferred_refresh_id uuid REFERENCES persistence_worktree_refreshes(id);
+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS deferred_refresh_id uuid;
+ DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='persistence_requests_deferred_refresh_id_fkey' AND conrelid='persistence_requests'::regclass) THEN
+ ALTER TABLE persistence_requests ADD CONSTRAINT persistence_requests_deferred_refresh_id_fkey
+ 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 INDEX IF NOT EXISTS persistence_requests_deferred ON persistence_requests(worktree_id, sequence) WHERE state='deferred';
CREATE OR REPLACE FUNCTION gbrain_release_refresh_barrier() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
BEGIN
NEW.released_at := COALESCE(NEW.released_at, now());
@@ -69,7 +81,6 @@ export const v290: Migration = {
UPDATE persistence_worktree_refreshes SET released_at=COALESCE(completed_at,updated_at) WHERE state IN ('completed','aborted') AND released_at IS NULL;
ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS deferred_refresh_id uuid REFERENCES persistence_worktree_refreshes(id);
ALTER TABLE persistence_consumers ADD COLUMN IF NOT EXISTS capabilities text[] NOT NULL DEFAULT '{}';
- CREATE INDEX IF NOT EXISTS persistence_requests_deferred ON persistence_requests(worktree_id, sequence) WHERE state='deferred';
CREATE OR REPLACE FUNCTION gbrain_release_refresh_barrier() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $$
BEGIN
NEW.released_at := COALESCE(NEW.released_at, now());
@@ -101,4 +112,5 @@ 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 }); },
};
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 1003523f8e..814b03c419 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -545,8 +545,10 @@ export type RequestLogStatus = 'success' | 'success_with_warnings' | 'accepted_p
/** #5249: the receipt of a write the dispatcher returned as accepted but not yet committed. */
export function acceptedPendingReceipt(result: ToolResult): WriteReceipt | null {
+ const text = result.content[0]?.text ?? '{}';
+ if (!result.isError && !/^\s*\{\s*"status"\s*:\s*"pending"/.test(text.slice(0, 64))) return null;
try {
- const parsed: unknown = JSON.parse(result.content[0]?.text ?? '{}');
+ const parsed: unknown = JSON.parse(text);
return result.isError ? admittedPendingReceipt(parsed) : deferredPendingReceipt(parsed);
} catch { return null; }
}
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 5af4462e01..acaa292ff5 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -8014,43 +8014,43 @@
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fm/image.png",
+ "path": "fences/late.md",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fm/null-bytes.md",
+ "path": "fences/untracked.md",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fm/null-in-frontmatter.md",
+ "path": "fm/image.png",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fm/untracked-yaml.md",
+ "path": "fm/late-broken.md",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fences/late.md",
+ "path": "fm/null-bytes.md",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fences/untracked.md",
+ "path": "fm/null-in-frontmatter.md",
"state": "untracked"
},
{
"age_ms": "<volatile>",
"checkout": "<home>/notes-src",
- "path": "fm/late-broken.md",
+ "path": "fm/untracked-yaml.md",
"state": "untracked"
}
],
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 6985e146c1..b8ac3d4589 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -41,6 +41,7 @@
"PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533",
"PERSISTENCE_COMPACTABLE_INDEX": "25ee657878efb41ba9ea3a7624464ddcf66407d861659456c230366e57f230a0",
"PERSISTENCE_DATABASE_PENDING_INDEX_SQL": "6e0f618be33d037454933ea4dea11438413d45aef35d3bd4f33e89624d6e199e",
+ "PERSISTENCE_DEFERRED_INDEX": "197c708370699aa5e8362b329abc47135ad6fc9c78ab751bd82bdb39d020c3c7",
"PERSISTENCE_EFFECT_PARKED_INDEX_SQL": "0107863883415378d7c0dce7a0cbd5311c2c5a59fc0f81917cc8b767fd235cf2",
"PERSISTENCE_FOREGROUND_COMMITTED_INDEX": "cb6bb9f8e9bcfd2524a04d05e5da865e92c69442bbcd438d8191d311f76d0663",
"PERSISTENCE_REQUEST_ID_INDEX": "2c5325e86cf395f617d93a39a45593931639cd8b14fd513b6d9e7d125f16c78f",
@@ -4689,7 +4690,23 @@
"version": 289
},
{
- "handler": "absent",
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "PERSISTENCE_DEFERRED_INDEX",
+ "PLANNER_REPAIR_TABLES",
+ "analyzeAfterIndexBuild",
+ "analyzeDeferred",
+ "analyzeYieldingToVacuum",
+ "buildIndexOnline",
+ "dropInvalidConcurrentIndex",
+ "lockTableForAnalyze",
+ "migrationNotice",
+ "quietMigrationNotices",
+ "tableRows"
+ ],
+ "sha256": "69eea77482e935be165caf0d2daa8f24128a2a5f252e28d7408ac4ed0f2ac2c9"
+ },
"idempotent": true,
"name": "refresh_write_barrier",
"sql": {
@@ -4698,12 +4715,12 @@
},
"sqlFor": {
"pglite": {
- "length": 2816,
- "sha256": "7051b03885dc4e0c97f900549a29ace6f7112815ea54bd2d5c1144ef1ea0bea8"
+ "length": 2684,
+ "sha256": "042e36e067f6244954b6d5cd895b944ed5a0e3aa3de52b56e1f774f6720e9d7b"
},
"postgres": {
- "length": 2917,
- "sha256": "30b59966ee2b45c1eb33199dd83eaa0b771b8b494e107b0f3147764c19728662"
+ "length": 3251,
+ "sha256": "69a8e657a89483837176501f038ca709ef6bb45e1f810ca1f4c11cc3daf699c2"
}
},
"transaction": false,
diff --git a/test/persistence-git-subdir-root-7091.test.ts b/test/persistence-git-subdir-root-7091.test.ts
index 217713da51..6aa8dd4386 100644
--- a/test/persistence-git-subdir-root-7091.test.ts
+++ b/test/persistence-git-subdir-root-7091.test.ts
@@ -19,6 +19,8 @@ import { activateSharedSkillPersistence } from '../src/core/persistence/skill-ac
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { commitGitTargets } from '../src/core/persistence/effect-git.ts';
import { gitConvergenceCheck } from '../src/commands/doctor/checks/git-convergence.ts';
+import { commitAndPush } from '../src/core/git/commit-push.ts';
+import { ledgerLocation, readLedger } from '../src/core/git/commit-ledger.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { testBackends } from './helpers/test-backends.ts';
import { type Repo, bindSource, createGitCoalescingFixture, git, harden, pageSlug, pass, pauseGitEffects, putPage, release } from './helpers/git-coalescing-fixture.ts';
@@ -143,9 +145,13 @@ for (const kind of testBackends()) describe(`#7091 a source root below the Git t
const page = `${SUBDIR}/${pageSlug(1)}.md`;
writeFileSync(join(top.root, page), edited(1));
const dirty = await gitConvergenceCheck(engine);
- expect(dirty).toMatchObject({ status: 'warn', fix: { ask_user: true, actor: 'user', argv: ['git', '-C', top.root, 'commit', '-m', 'gbrain: persist canonical memory update', '--', page],
+ expect(dirty).toMatchObject({ status: 'warn', fix: { ask_user: true, actor: 'user', argv: ['gbrain', 'git', 'commit-push', '--path', top.root, '-m', 'gbrain: persist canonical memory update', '--', page],
then: { argv: ['gbrain', 'git', 'commit-push', '--push-only', '--keep-checkout', '--path', top.root] } } });
expect((dirty!.details as { roots: unknown[] }).roots).toEqual([expect.objectContaining({ root: top.root, stranded: true, uncommitted_pages: [page] })]);
+
+ const fixed = commitAndPush({ repo: top.root, cwd: top.root, paths: [page], message: 'gbrain: persist canonical memory update' });
+ expect(fixed.committed).toBe(git(top.root, 'rev-parse', 'HEAD').trim());
+ expect(readLedger(ledgerLocation(top.root)!.common).some(r => r.e === 'commit' && r.sha === fixed.committed)).toBe(true);
}), 300_000);
});
diff --git a/test/refresh-write-barrier.test.ts b/test/refresh-write-barrier.test.ts
index 388d220010..7e8b1b0eb8 100644
--- a/test/refresh-write-barrier.test.ts
+++ b/test/refresh-write-barrier.test.ts
@@ -12,6 +12,8 @@
*/
import { afterAll, afterEach, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
+import { rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
import { run as runUpgradeCommand } from '../src/cli/commands/upgrade.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
@@ -272,6 +274,54 @@ test('a deferred write whose token is revoked while it waits ends permission_den
expect(Number(n)).toBe(0);
}), 180_000);
+test('a write admitted after the release waits behind the released deferred write on its worktree', () => each(async f => {
+ let first!: WriteRequest;
+ const refresh = await duringRefresh(f, async () => {
+ const out = await call(f, 'put_page', { slug: 'notes/order', content: page('Order', 'the deferred version') });
+ first = await requestRow(f, out.body.request_id);
+ expect(first.state).toBe('deferred');
+ });
+ expect((await refresh).status).toBe('completed');
+ expect((await requestRow(f, first.request_id)).state).toBe('deferred');
+ const later = await call(f, 'put_page', { slug: 'notes/order', content: page('Order', 'the later version') });
+ expect(later).toMatchObject({ isError: true, body: { code: 'revision_required' } });
+ expect((await settle(f, first)).state).toBe('committed');
+ const [stored] = await f.engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [f.alpha, 'notes/order']);
+ expect(stored?.compiled_truth ?? '').toContain('the deferred version');
+}), 180_000);
+
+test('a write deferred behind a refresh that aborts commits once the refresh is released', () => each(async f => {
+ let deferred!: WriteRequest;
+ await expect(duringRefresh(f, async () => {
+ const out = await call(f, 'put_page', { slug: 'notes/after-abort', content: page('After abort', 'body') });
+ deferred = await requestRow(f, out.body.request_id);
+ expect(deferred.state).toBe('deferred');
+ writeFileSync(join(f.root, 'alpha', 'two.md'), page('Alpha two', 'A local edit the merge would overwrite.'));
+ })).rejects.toMatchObject({ code: 'refresh_dirty' });
+ rmSync(join(f.root, 'alpha', 'two.md'), { force: true });
+ const [{ state }] = await f.engine.executeRaw<{ state: string }>('SELECT state FROM persistence_worktree_refreshes WHERE id=$1::uuid', [deferred.deferred_refresh_id]);
+ expect(state).toBe('aborted');
+ expect((await settle(f, deferred)).state).toBe('committed');
+}), 180_000);
+
+test('a deferred write cancelled while its refresh runs ends cancelled with nothing applied and its counters released', () => each(async f => {
+ let deferred!: WriteRequest;
+ const before = await outstanding(f);
+ const refresh = await duringRefresh(f, async () => {
+ const out = await call(f, 'put_page', { slug: 'notes/cancelled', content: page('Cancelled', 'body') });
+ deferred = await requestRow(f, out.body.request_id);
+ expect(deferred.state).toBe('deferred');
+ const cancelled = await call(f, 'cancel_write_request', { request_id: deferred.request_id });
+ expect(cancelled.isError).toBe(false);
+ expect((await requestRow(f, deferred.request_id)).state).toBe('cancelled');
+ });
+ expect((await refresh).status).toBe('completed');
+ expect(await outstanding(f)).toBe(before);
+ const [{ n }] = await f.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [f.alpha, 'notes/cancelled']);
+ expect(Number(n)).toBe(0);
+ expect((await deferredBacklog(f.engine)).count).toBe(0);
+}), 180_000);
+
test('with the barrier off a write during a refresh is still refused worktree_refreshing', () => each(async f => {
await withEnv({ GBRAIN_REFRESH_BARRIER: '0' }, async () => {
resetWriteSwitches();