Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): poll_command is the envelope's receipt command with --brain, and write-request --help names its states (#6255)

time-attack4ce48c4ef76f
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 4c4ade9123..545d6a3a97 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -40,6 +40,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|claim|transfer` and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.
-- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`.
+- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`. #6255: a pending receipt's envelope carries the receipt fix, and `poll_command` plus the `Poll:` line are that same argv.
- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 1cd94426fa..dc0b5f8e0e 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -41,7 +41,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/page-input.ts` — freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomes `note` with `legacy_type` retained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract. `test/brain-allowlist.test.ts` pins changed-pack replay, raw-size refusal, and private parse-error redaction. `undeclaredPageTypeWarning` covers every other `put_page` (not managed file imports): a type the write source's pack neither declares nor aliases is stored as written and the committed result carries `type_warning` (`code: page_type_undeclared`, cause, fix, docs), also logged; pinned by `test/put-page-type-warning.test.ts`.
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`.
+- `src/core/persistence/write-wait.ts` — the CLI write-wait and exit contract (#5232). `resolveCliWriteWaitMs` (`--wait` seconds > `GBRAIN_WRITE_WAIT_MS` > file-plane `persistence.write_wait_ms` > 30 s; agents keep `AGENT_WRITE_WAIT_MS`); `writeExchangeBudget` (transport deadline = wait + 15 s admission headroom; an explicit `--timeout` shortens the requested owner wait instead); `replayWhilePending` (replays the identical request ID while an older owner, a remote server or a subagent tool's own bounded wait reports pending; the caller-supplied `sleep` decides how each pause ends, which is how subagent tool writes stop on abort); `writeErrorExitCode` keys on an admitted non-terminal receipt (`admittedPendingReceipt` in `types.ts`): pending → `PENDING_WRITE_EXIT_CODE` (0 with `--accept-pending`/`GBRAIN_ACCEPT_PENDING=1`), anything else → 1. Pinned by `test/pending-write-exit.serial.test.ts` and `test/pending-write-exit-owner.test.ts`. `pollCommand` (#6255) renders the envelope's receipt `fix.argv` (`gbrain write-request --brain <id> -- <request_id>`), else pins that argv to the CLI routing.
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB. Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.
diff --git a/src/cli.ts b/src/cli.ts
index 6a699b0f64..d371d32f7e 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -2920,6 +2920,8 @@ const OP_HELP_EXAMPLES: Record<string, string[]> = {
'gbrain backlinks companies/acme-example --source-id business',
'gbrain backlinks companies/acme-example --all-sources --json',
],
+ // #6255: the receipt command's routing flags and states.
+ get_write_request: ['gbrain write-request --brain host -- <request_id> [--json] # queued/running: pending, read again after retry_after_ms; committed/conflict/failed/cancelled: final'],
traverse_graph: [
'gbrain graph people/alice-example --depth 2',
'gbrain graph people/alice-example --source business --direction both',
diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.ts
index b5e0e2cd6e..9d9d30f34b 100644
--- a/src/commands/persistence-delegate.ts
+++ b/src/commands/persistence-delegate.ts
@@ -21,12 +21,15 @@ export async function reportPersistenceCliError(error: unknown, json = false,
// PENDING_WRITE_EXIT_CODE (0 with --accept-pending) and names how to poll.
const pending = pendingReceiptOf(error);
const acceptPending = acceptPendingRequested(getCliOptions().acceptPending);
+ const render = cliRenderContext();
+ const envelope = toAgentError(error, { transport: 'cli', command: cliCommandOf(), render, ...(pending ? { mutating: true, outcome: 'pending' as const } : {}) });
+ // #6255: one source for the poll command: the envelope's receipt fix, pinned like every CLI fix.
+ const poll = pending ? pollCommand(pending.request_id, envelope.fix, render.routing) : undefined;
if (json) {
// Legacy keys lead and keep their values; the v1 envelope fields (code, fix, docs_cmd, class, retryable,
// notices, contract_version) come from the shared renderer, as renderCliError writes them (cli-error.ts pattern).
const legacy: Record<string, unknown> = pending ? { ...detail, request_id: pending.request_id, state: pending.state,
- poll_command: pollCommand(pending.request_id) } : { ...detail };
- const envelope = toAgentError(error, { transport: 'cli', command: cliCommandOf(), render: cliRenderContext() });
+ poll_command: poll } : { ...detail };
noteRenderedErrorCode(envelope.code);
const doc = { ...legacy, ...Object.fromEntries(Object.entries(envelope).filter(([, v]) => v !== undefined)), ...legacy };
await out(JSON.stringify(doc, null, 2) + '\n');
@@ -39,7 +42,7 @@ export async function reportPersistenceCliError(error: unknown, json = false,
const requestId = receipt?.request_id ?? ('request_id' in detail ? detail.request_id : undefined);
if (requestId) console.error(`Request: ${requestId}${receipt ? ` (${receipt.state})` : ''}`);
if (pending) {
- console.error(`Poll: ${pollCommand(pending.request_id)}`);
+ console.error(`Poll: ${poll}`);
if (!acceptPending) console.error(`Exit ${PENDING_WRITE_EXIT_CODE}: accepted, not yet committed. Wait longer with --wait <seconds>, or pass --accept-pending to exit 0 (${WRITE_EXIT_DOCS}).`);
}
setCliExitVerdict(writeErrorExitCode(error, acceptPending));
diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.ts
index ea7d602583..81c4da34c9 100644
--- a/src/core/persistence/write-wait.ts
+++ b/src/core/persistence/write-wait.ts
@@ -8,6 +8,7 @@ import { loadConfig, type GBrainConfig } from '../config.ts';
import { getCliOptions } from '../cli-options.ts';
import { PENDING_WRITE_EXIT_CODE } from '../exit-codes.ts';
import { OperationError } from '../ops/contract.ts';
+import { pinRouting, type FixRouting } from '../fix-routing.ts';
import { admittedPendingReceipt, type WriteReceipt } from './types.ts';
import { WIRE_WRITE_WAIT_MAX_MS } from './params.ts';
@@ -120,9 +121,16 @@ export function writeErrorExitCode(error: unknown, acceptPending: boolean): numb
return acceptPending ? 0 : PENDING_WRITE_EXIT_CODE;
}
-/** The copy-paste poll command for a pending receipt. */
-export function pollCommand(requestId: string): string {
- return `gbrain call get_write_request '${JSON.stringify({ request_id: requestId })}'`;
+/**
+ * The copy-paste poll command for a pending receipt (#6255): the same
+ * `gbrain write-request [--brain <id>] -- <request_id>` argv the error
+ * envelope's `fix` carries. A `fix.argv` that reads this receipt wins, so the
+ * two never disagree; otherwise the receipt command is pinned to `routing`.
+ */
+export function pollCommand(requestId: string, fix?: { argv?: readonly string[] }, routing?: FixRouting): string {
+ const argv = fix?.argv?.[0] === 'gbrain' && fix.argv[1] === 'write-request' && fix.argv.includes(requestId)
+ ? fix.argv : pinRouting(['gbrain', 'write-request', '--', requestId], routing);
+ return argv.join(' ');
}
/**
diff --git a/test/pending-write-exit.serial.test.ts b/test/pending-write-exit.serial.test.ts
index 225be07894..f100bea64b 100644
--- a/test/pending-write-exit.serial.test.ts
+++ b/test/pending-write-exit.serial.test.ts
@@ -112,7 +112,10 @@ describe('resident owner: pending-write exit codes', () => {
const body = JSON.parse(result.stdout);
expect(body.write_request).toMatchObject({ request_id: ID, state: 'running' });
expect(body).toMatchObject({ request_id: ID, state: 'running' });
- expect(body.poll_command).toBe(`gbrain call get_write_request '{"request_id":"${ID}"}'`);
+ // #6255: the poll command is the envelope's receipt fix, pinned to the brain it ran against.
+ expect(body.poll_command).toBe(`gbrain write-request --brain host -- ${ID}`);
+ expect(body.poll_command).toBe(body.fix.argv.join(' '));
+ expect(result.stderr).toContain(`Poll: gbrain write-request --brain host -- ${ID}`);
}
});
}
@@ -175,7 +178,7 @@ describe('resident owner: pending-write exit codes', () => {
const result = await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID }), '--wait', '0']);
expect(result.code).toBe(PENDING_WRITE_EXIT_CODE);
expect(result.stderr).toContain(`Request: ${ID} (running)`);
- expect(result.stderr).toContain(`Poll: gbrain call get_write_request '{"request_id":"${ID}"}'`);
+ expect(result.stderr).toContain(`Poll: gbrain write-request --brain host -- ${ID}`);
expect(result.stderr).toContain('#cli-exit-status-for-writes');
});
}, 30_000);
diff --git a/test/write-request-help.test.ts b/test/write-request-help.test.ts
new file mode 100644
index 0000000000..2404f7586f
--- /dev/null
+++ b/test/write-request-help.test.ts
@@ -0,0 +1,16 @@
+/** #6255 (fix wave 12, W1.4): `gbrain write-request --help` names its routing flags and the receipt states. */
+import { expect, test } from 'bun:test';
+import { printOpHelp } from '../src/cli.ts';
+import { operationsByName } from '../src/core/operations.ts';
+
+test('write-request help shows --brain, --json and the pending versus final states', () => {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { printOpHelp(operationsByName.get_write_request!, 'write-request'); } finally { console.log = log; }
+ const help = lines.join('\n');
+ expect(help).toContain('gbrain write-request --brain host -- <request_id>');
+ expect(help).toContain('--json');
+ expect(help).toContain('retry_after_ms');
+ for (const state of ['queued', 'running', 'committed', 'conflict', 'failed', 'cancelled']) expect(help).toContain(state);
+});