Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Retry and import hints print commands that work, quiet hours keep a cancel reason, PGLite edge filter binds every arm, particle-1 gets thinking headroom

garrytanbc0d64d522f2
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 917a8556ba..ebcac4c2a1 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3298,7 +3298,7 @@ More: [docs/guides/windowed-reads.md#page_body_segmented](../../docs/guides/wind
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| The page was deleted or replaced while the operation ran. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
+| The page was deleted or replaced while the operation ran. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --include-content --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
### page_not_found
@@ -4260,7 +4260,7 @@ More: [docs/guides/windowed-reads.md#revision_changed](../../docs/guides/windowe
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| The target changed since it was read; the expected revision no longer matches. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
+| The target changed since it was read; the expected revision no longer matches. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --include-content --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
### revision_required
@@ -4268,7 +4268,7 @@ More: [docs/guides/windowed-reads.md#revision_changed](../../docs/guides/windowe
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it. | Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
+| The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it. | Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --include-content --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |
### revision_unavailable
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index cc48ea8298..8c77bbefd4 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -571,7 +571,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_drain_timeout"></a>`refresh_drain_timeout` | `refresh_drain_timeout` | Queued writes or Git effects on the checkout did not finish within `--wait-drain` (default 60 s; `sources.refresh_drain_wait_ms`; `GBRAIN_REFRESH_DRAIN_WAIT_MS`). The counts are in the message. The fence was lifted and HEAD did not move. | Retry, or wait longer with `--wait-drain <seconds>`. Inspect what is queued with `gbrain sources writer status <source> --json`. |
| <a id="refresh_lock_timeout"></a>`refresh_lock_timeout` | `refresh_lock_timeout` | The refresh fence locks the brain, worktree, source and refresh rows with a 5 s lock timeout, and another database transaction held one of them longer. `why` lists the five oldest open transactions in this database holding locks on those tables (pid, application, state, how long the transaction has been open). They are candidates: the blocker may not be among them, because Postgres does not show which row each one holds. It never repeats their SQL, and says so when that lookup failed or took longer than 3 s. HEAD did not move: no fence was set, or the draining refresh was aborted. When the same holder also blocked that abort, the refusal says the row stays `draining`, and the next `gbrain sources refresh <source>` resumes it. | Retry `gbrain sources refresh <source>`. If it repeats, a transaction holding one of those rows is stuck: `why` lists the oldest candidates, so confirm the blocker on the brain host before ending any transaction. |
| <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. |
-| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout, or gbrain's own commits the upstream does not hold yet), the upstream branch changed while the refresh waited, or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. When HEAD moved or work reached the checkout after the drain check, the run already retried once from a fresh precheck, and the message names why that retry was refused too. | Retry `gbrain sources refresh <source>`. |
+| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout, gbrain's own commits the upstream does not hold yet, or gbrain's own commits under an upstream branch that changed while the refresh waited; the upstream is compared only when HEAD moved), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. When HEAD moved or work reached the checkout after the drain check, the run already retried once from a fresh precheck, and the message names why that retry was refused too. | Retry `gbrain sources refresh <source>`. |
| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. (A commit that lands on the upstream commit right after the refresh's own merge is not this case: the refresh records the merge and syncs it. Nor is one that lands on the start commit right before the merge: git refuses the fast-forward and the refresh ends `refresh_source_changed`; if its process dies before that, recovery aborts the refresh the same way when the checkout's reflog shows HEAD never reached the upstream commit.) Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. Writer status reads HEAD and names the one step left when HEAD already sits at one of those commits: `--resume` at the upstream commit, `--abandon` at the start commit when no member source has synced past it. When one has (its `last_commit` is set and is neither the start commit nor an ancestor of it; a commit git cannot find counts too), `--abandon` refuses with this code and changes nothing, because the next sync would roll that member's pages back; `--resume` refuses too, and both name the one way out that keeps those pages: the fix (`next: ask_user`) previews with `git -C <checkout> status --short`, fast-forwards the checkout with `git merge --ff-only` to the commit the members synced (the upstream commit, or a later one a member already synced; it keeps uncommitted edits and refuses if one overlaps an incoming file), then runs `--resume`. When git refuses, the fix names a hard reset to that commit instead (destructive: it discards local commits and uncommitted edits not in that commit). `--resume` finishes a `recovery_required` refresh whose HEAD is the upstream commit or descends from it, unless a member synced a commit on this refresh's line (or one git cannot place) that HEAD does not contain; then it refuses with the same fast-forward fix. |
| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not saved. `detail` is `retry_after_ms=<n>`, estimated from the refresh itself: the median duration of the worktree's last completed refreshes minus how long this one has run, never below 15 s while it syncs or 2 s in its other phases (so a refresh of several minutes is never answered with a 1 s retry). The message names the phase, how long the refresh has run and typically takes, and the CLI's human output ends with one line, `Nothing was saved; retry the same command in about <n> s (retry_after_ms=<n>).`, which survives `| tail -1`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. With `persistence.refresh_barrier` on, a single page or memory write waits behind the refresh instead ([deferred writes](#deferred-writes)). | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
diff --git a/src/cli/page-render.ts b/src/cli/page-render.ts
index 79105b27c3..ce0ea6398a 100644
--- a/src/cli/page-render.ts
+++ b/src/cli/page-render.ts
@@ -140,6 +140,7 @@ export function formatGetPage(r: GetPageResult): string {
return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
}
if (typeof r.body !== 'string') {
+ if (typeof r.content === 'string' && r.revision) process.stderr.write(`[gbrain] revision ${r.revision}: put or delete this page with --expected-revision ${r.revision}.\n`);
return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', { type: r.type, title: r.title, tags: r.tags || [] });
}
if (r.section || r.grep) return renderSlice(r);
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 17c0437880..3f040699ea 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1310,7 +1310,7 @@ export async function initPGLite(opts: {
writeCliNotices(await firstRunBundle(engine, searchMode, registrationSurface));
// The single primary action, last-on-screen.
- printMemoryVerbsQuickstart({ emptyBrain: stats.page_count === 0, onPglite: true });
+ printMemoryVerbsQuickstart({ emptyBrain: stats.page_count === 0, onPglite: true, keyless: config.embedding_disabled === true });
}
} finally {
try { await engine.disconnect(); } catch { /* best-effort */ }
@@ -1330,7 +1330,7 @@ const INIT_EMBEDDING_HINT = 'Pick an embedding model whose dimensions match (`gb
*/
let registrationSurface: McpSurface | undefined;
let searchModeChoice: import('./init-mode-picker.ts').SearchModeChoice = {};
-function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boolean } = {}): void {
+function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boolean; keyless?: boolean } = {}): void {
const register = harnessRegistrationCommand(registrationSurface);
console.log('');
console.log(`→ Do this next — give your agent memory (copy these ${register ? 'three' : 'two'} commands):`);
@@ -1348,7 +1348,7 @@ function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boo
console.log('');
console.log(
'More: ' +
- (opts.emptyBrain ? 'bulk-load notes `gbrain import <dir>` · ' : '') +
+ (opts.emptyBrain ? `bulk-load notes \`gbrain import <dir>${opts.keyless ? ' --no-embed' : ''}\` · ` : '') +
(opts.onPglite ? 'scale up `gbrain migrate --to postgres --plan` · ' : '') +
'health `gbrain doctor`',
);
diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.ts
index 46f4e6a991..97e671b89d 100644
--- a/src/core/ai/recipes/openrouter.ts
+++ b/src/core/ai/recipes/openrouter.ts
@@ -57,10 +57,12 @@ export function openrouterRequiresExplicitPromptCache(modelId: string): boolean
* the same headroom on the OR route (#4758). Z.ai's GLM-4.5+/5.x think by
* default too (zhipu recipe, gbrain#4727) and OR bills their reasoning as
* completion tokens — same cutoff, same headroom under the `z-ai/` prefix.
+ * Particle (`particle-ai/`) reasons by default as well and OR bills it as
+ * completion tokens, so a thinking:'off' call needs the same headroom (GST-1977).
*/
export function openrouterThinkingByDefault(modelId: string): boolean {
const normalized = modelId.trim().toLowerCase();
- if (normalized.startsWith('deepseek/')) return true;
+ if (normalized.startsWith('deepseek/') || normalized.startsWith('particle-ai/')) return true;
return normalized.startsWith('z-ai/') && GLM_THINKING_BY_DEFAULT_RE.test(normalized);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 2e82668a4c..fa58dec3a7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1486,7 +1486,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.614.0', id: 'refresh_barrier_aborted_refresh_sync_gst1853', text: 'While a checkout\'s last `gbrain sources refresh` ended without completing (aborted, abandoned, or rolled back after its process died), every refresh run on the owner host, including one refused `refresh_diverged`, now ends by running the managed `--no-pull` sync of each source behind the checkout HEAD, listed in its `synced` (a refusal\'s message names them). With `persistence.refresh_barrier` on, a write held behind that refresh for a commit sync had not imported is therefore decided in that run instead of waiting for a later refresh: a `put_page` with `expected_revision` ends `revision_conflict`, a blind one lands and names what it replaced in `supersedes`, and a `remember` or `add_timeline_entry` applies on top.' },
{ since: '0.60.608.0', id: 'refresh_barrier_later_write_gst1623', text: 'With `persistence.refresh_barrier` on, a write that waited behind a refresh or an import (other than a `remember` or `add_timeline_entry`, which still applies on top) now ends `revision_conflict` instead of applying when a later write to the same page committed first, which a consumer from an older release can cause; read the page again and resubmit with a new `request_id`. A write held again and again behind imports now expires once it has waited four wait limits (at least 4 hours) since its admission, even when each hold is shorter than one wait limit. With the barrier on or off, a plain-git commit that lands on the start commit right before a refresh merges makes git refuse the fast-forward, and the refresh now ends `refresh_source_changed` with the fence lifted and the commit kept, instead of leaving the checkout `recovery_required`; one that lands right after the merge is recorded and synced.' },
{ since: '0.60.617.0', id: 'url_source_origin', text: 'New doctor check `url_source_origin` (warn) lists URL sources in the default clone directory with no record of who added them, which is every URL source added before that record existed: gbrain cannot tell whether a remote caller or the local operator added each one, so their reclones use the clone settings of a local add. `gbrain sources record-origin <id>... --remote|--local` records the answer the user gives, as a preview until `--apply`, on the brain host only. `--remote` gives the source the clone settings a remote add gets (git-lfs downloads and hooks off on every later reclone) and refuses a checkout that tracks git-lfs files or cannot be inspected. Nothing changes on upgrade.' },
- { since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },
+ { since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch the precheck recorded is still the branch\'s `@{upstream}` and holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, gbrain\'s commits the upstream does not hold yet, or gbrain\'s commits under an `@{upstream}` other than the one the precheck recorded still refuses as before.' },
{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },
{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },
];
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index af6d21fed8..1bb86974d4 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -549,7 +549,7 @@ export const CODES = {
reasons: ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'binding_missing', 'incarnation_changed', 'coordination_path_missing', 'local_path_missing', 'not_sent', 'outcome_unknown'],
docs: 'docs/guides/troubleshooting.md#owner-unavailable',
suggestion: 'Read gbrain sources writer status --source <id> --json on the brain host. A transfer or clone in progress: wait and retry. host_mismatch: run the step on the owner host, or give the worker and the shell one GBRAIN_HOME; never copy or regenerate host.json. Nothing claims or transfers ownership to run maintenance.' },
- page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
+ page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },
page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
page_body_rows_unreadable: { class: 'server', summary: "This large page's segment rows readable on this connection do not cover its body, so the read returned nothing rather than a short or empty body.", why: "A segmented page keeps its body in manifest rows that must tile the stored body from its first byte to body_bytes; a role that sees the page row but not its manifest rows (a row-level security policy or grant that covers pages only), or rows missing from the database, would otherwise read as an empty or truncated page with nothing to say so.", docs: 'docs/guides/windowed-reads.md#page_body_rows_unreadable', suggestion: "Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages (the brain host's operator), then read again; run gbrain doctor --json to check the segment tables. When doctor segmented_tiling lists the page, its rows are missing: preview gbrain repair segmented-tiling --source <id>, which republishes it from Git." },
@@ -695,8 +695,8 @@ export const CODES = {
result_too_large: { class: 'caller', summary: "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.", why: "Results are measured as the complete encoded JSON-RPC frame (every block, notice and escape). A frame over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be rejected or silently cut by the client.", docs: 'docs/guides/windowed-reads.md#result_too_large', legacy_error: 'invalid_params', suggestion: "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size and outline, which name the windows to read.", requires_exclusive: false } },
revision_changed: { class: 'caller', summary: "The page changed since the cursor or chunk id was issued, so that position no longer names the same text.", why: "Cursors and chunk positions are bound to one page revision; reading on from them after an edit could skip or repeat text without saying so.", docs: 'docs/guides/windowed-reads.md#revision_changed', legacy_error: 'invalid_params', suggestion: "Read again from the position in fix (the same byte offset at the current revision), or start over with body: 'outline'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and size.", requires_exclusive: false } },
revision_backfill_pending: { class: 'caller', summary: "The page was written before page revisions existed and the revision backfill has not reached it, so it has no revision a write or preview can bind to.", fix: { argv: ['gbrain', 'apply-migrations', '--force-schema'], consent: [], actor: 'agent', why: "Re-runs the schema migration pass on the brain host, which resumes the page revision backfill and prints its progress; it changes no page content.", requires_exclusive: true }, docs: 'docs/guides/write-refusals.md#revision-backfill' },
- revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },
- revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },
+ revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },
+ revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },
revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },
schema_owner_required: { class: 'caller', summary: "The database role this command connects as may not create schema objects (Postgres 42501), so the schema repair created nothing.", why: "On a brain whose tables belong to a separate owner role, the application role cannot run DDL; only the owner can recreate a missing table.", docs: 'docs/guides/repair.md#missing-tables', suggestion: 'Run the same apply connected as the role that owns the brain tables (the one apply-migrations uses).' },
scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index a0ee43215b..ab3ffafed9 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -1013,7 +1013,7 @@ export class MinionWorker extends EventEmitter {
await this.engine.executeRaw(
`UPDATE minion_jobs
SET status = 'cancelled', error_text = 'skipped_quiet_hours', updated_at = now()
- WHERE id = $1 AND status NOT IN ('completed','failed','dead')`,
+ WHERE id = $1 AND status NOT IN ('completed','failed','dead','cancelled')`,
[job.id],
);
}
diff --git a/src/core/pglite-engine/code-edges.ts b/src/core/pglite-engine/code-edges.ts
index d8774416ff..103b6daad8 100644
--- a/src/core/pglite-engine/code-edges.ts
+++ b/src/core/pglite-engine/code-edges.ts
@@ -1,11 +1,9 @@
/**
* PGLite-only code-edge read (refactor wave 1 C13). The rest of the domain
* lives once in src/core/engine-sql/code-edges.ts. `getEdgesByChunk` stays
- * dialect-specific because its PGLite SQL behaves differently from Postgres's
- * on master: one UNION ALL under a single shared LIMIT, and an edge-type
- * filter that binds only to the `to_chunk_id` arm for direction 'both'
- * (operator precedence). Unifying it would change PGLite results, so it is
- * listed in docs/designs/refactor-wave-1/w1-inventory.md and left as is.
+ * dialect-specific because it runs on the PGLite query API, but it applies the
+ * same filters as the shared Postgres read: the edge-type filter covers every
+ * direction arm and is bound, and each table gets its own LIMIT.
*/
import type { PGlite } from '@electric-sql/pglite';
import { rowToCodeEdge } from '../engine-sql/code-edges.ts';
@@ -23,37 +21,34 @@ export async function getEdgesByChunk(
): Promise<import('../types.ts').CodeEdgeResult[]> {
const direction = opts?.direction ?? 'both';
const limit = Math.min(opts?.limit ?? 50, 200);
- const edgeTypeClause = opts?.edgeType ? `AND edge_type = '${opts.edgeType.replace(/'/g, "''")}'` : '';
- // Build the chunk-table filter based on direction. Unresolved edges
- // (code_edges_symbol) only carry from_chunk_id — there's no inbound
- // direction into them from a chunk ID, so we include them only when
- // direction is 'out' or 'both'.
- let chunkFilter = '';
- if (direction === 'in') chunkFilter = `WHERE to_chunk_id = $1`;
- else if (direction === 'out') chunkFilter = `WHERE from_chunk_id = $1`;
- else chunkFilter = `WHERE from_chunk_id = $1 OR to_chunk_id = $1`;
-
- let symbolFilter = '';
- if (direction === 'out' || direction === 'both') {
- symbolFilter = `WHERE from_chunk_id = $1`;
+ const params: unknown[] = [chunkId, limit];
+ let typeClause = '';
+ if (opts?.edgeType) {
+ params.push(opts.edgeType);
+ typeClause = 'AND edge_type = $3';
}
-
- const unionClause = symbolFilter ? `
- UNION ALL
- SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- ${symbolFilter} ${edgeTypeClause}
- ` : '';
-
- const { rows } = await deps.db.query(
+ const chunkFilter = direction === 'in' ? 'to_chunk_id = $1'
+ : direction === 'out' ? 'from_chunk_id = $1'
+ : '(from_chunk_id = $1 OR to_chunk_id = $1)';
+ const { rows: chunkRows } = await deps.db.query(
`SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
- ${chunkFilter} ${edgeTypeClause}
- ${unionClause}
- LIMIT $2`,
- [chunkId, limit],
+ WHERE ${chunkFilter} ${typeClause}
+ LIMIT $2`,
+ params,
);
- return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ let symbolRows: unknown[] = [];
+ if (direction !== 'in') {
+ const { rows } = await deps.db.query(
+ `SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE from_chunk_id = $1 ${typeClause}
+ LIMIT $2`,
+ params,
+ );
+ symbolRows = rows;
+ }
+ return [...chunkRows, ...symbolRows].map(r => rowToCodeEdge(r as Record<string, unknown>));
}
diff --git a/test/ai/recipe-openrouter.test.ts b/test/ai/recipe-openrouter.test.ts
index 56b96c3896..25a587121a 100644
--- a/test/ai/recipe-openrouter.test.ts
+++ b/test/ai/recipe-openrouter.test.ts
@@ -604,3 +604,15 @@ describe('recipe: openrouter thinking-by-default — z-ai GLM (#4727)', () => {
expect(getProviderCapabilities(model).supportsThinking).toBe(false);
});
});
+
+// GST-1977: Particle's particle-1 reasons by default and OpenRouter bills the
+// reasoning against max_tokens, so a thinking:'off' call (the dream-triage
+// judge) needs the thinking-model headroom or it truncates at the 2,048 cap.
+describe('recipe: openrouter thinking-by-default — particle-ai (GST-1977)', () => {
+ test.each([
+ 'openrouter:particle-ai/particle-1',
+ 'openrouter:Particle-AI/particle-1',
+ ])('%s is thinking-by-default', (model) => {
+ expect(getProviderCapabilities(model).supportsThinking).toBe(true);
+ });
+});
diff --git a/test/code-edges.test.ts b/test/code-edges.test.ts
index 21ac32976f..d6274b938e 100644
--- a/test/code-edges.test.ts
+++ b/test/code-edges.test.ts
@@ -126,6 +126,26 @@ describe('Layer 5 (A1) — code-edges engine methods', () => {
expect(incoming.length).toBeGreaterThanOrEqual(1);
});
+ test('getEdgesByChunk both: the edge-type filter covers every arm and each table keeps its own limit (Postgres parity)', async () => {
+ await engine.addCodeEdges([{
+ from_chunk_id: chunkA,
+ to_chunk_id: chunkB,
+ from_symbol_qualified: 'run',
+ to_symbol_qualified: 'helper',
+ edge_type: 'imports',
+ }]);
+ const typed = await engine.getEdgesByChunk(chunkA, { direction: 'both', edgeType: 'imports' });
+ expect(typed.length).toBe(1);
+ expect(typed.every(e => e.edge_type === 'imports')).toBe(true);
+
+ const capped = await engine.getEdgesByChunk(chunkA, { direction: 'both', limit: 1 });
+ expect(capped.filter(e => e.resolved && e.to_chunk_id === chunkB).length).toBe(1);
+ expect(capped.filter(e => e.to_chunk_id === null).length).toBe(1);
+
+ const quoted = await engine.getEdgesByChunk(chunkA, { direction: 'both', edgeType: "calls' OR '1'='1" });
+ expect(quoted).toEqual([]);
+ });
+
test('deleteCodeEdgesForChunks removes rows in both directions', async () => {
await engine.deleteCodeEdgesForChunks([chunkA]);
const after = await engine.getEdgesByChunk(chunkA, { direction: 'both' });
diff --git a/test/init-keyless-import-hint.test.ts b/test/init-keyless-import-hint.test.ts
new file mode 100644
index 0000000000..53d260fd21
--- /dev/null
+++ b/test/init-keyless-import-hint.test.ts
@@ -0,0 +1,44 @@
+/**
+ * A keyless PGLite init ends with "More: bulk-load notes \`gbrain import <dir>\`".
+ * On a brain initialized with --no-embedding that printed command must work as
+ * written instead of refusing with embedding_disabled.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const CLI = join(import.meta.dir, '../src/cli.ts');
+let home: string;
+
+async function cli(args: string[]) {
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], {
+ cwd: home, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore',
+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_DISABLE_UPDATE_CHECK: '1', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' },
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+}
+
+let initOut = '';
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-init-keyless-hint-'));
+ const init = await cli(['init', '--pglite', '--no-embedding']);
+ expect(init.code, init.stderr).toBe(0);
+ initOut = init.stdout;
+}, 120_000);
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+describe('keyless init bulk-load hint', () => {
+ test('the printed import command succeeds on the keyless brain', async () => {
+ const hint = initOut.match(/bulk-load notes \`([^\`]+)\`/);
+ expect(hint, initOut).not.toBeNull();
+ const notes = join(home, 'notes');
+ mkdirSync(notes);
+ writeFileSync(join(notes, 'alice.md'), '---\ntitle: Alice\ntype: person\n---\nAlice is an engineer.\n');
+ const argv = hint![1].split(/\s+/).map(a => (a === '<dir>' ? notes : a));
+ expect(argv[0]).toBe('gbrain');
+ const run = await cli(argv.slice(1));
+ expect(run.code, run.stdout + run.stderr).toBe(0);
+ }, 120_000);
+});
diff --git a/test/revision-fix-command-shows-revision.test.ts b/test/revision-fix-command-shows-revision.test.ts
new file mode 100644
index 0000000000..cff4cea229
--- /dev/null
+++ b/test/revision-fix-command-shows-revision.test.ts
@@ -0,0 +1,54 @@
+/**
+ * revision_required / revision_conflict: the envelope's fix command says it
+ * "reads the current page and its revision". Running that exact command must
+ * print the revision, so the caller can resubmit with --expected-revision.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const CLI = join(import.meta.dir, '../src/cli.ts');
+let home: string;
+
+async function cli(args: string[]) {
+ const child = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], {
+ cwd: home, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore',
+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_DISABLE_UPDATE_CHECK: '1', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' },
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-revision-fix-'));
+ const init = await cli(['init', '--pglite', '--no-embedding']);
+ expect(init.code, init.stderr).toBe(0);
+}, 120_000);
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+describe('revision_required fix command', () => {
+ test('the fix command prints the revision a retry needs, and the retry succeeds', async () => {
+ writeFileSync(join(home, 'v1.md'), '---\ntitle: Bob\n---\nBob v1\n');
+ writeFileSync(join(home, 'v2.md'), '---\ntitle: Bob\n---\nBob v2\n');
+ expect((await cli(['put', 'notes/bob', '--file', join(home, 'v1.md')])).code).toBe(0);
+
+ const refused = await cli(['put', 'notes/bob', '--file', join(home, 'v2.md'), '--json']);
+ expect(refused.code).not.toBe(0);
+ const envelope = JSON.parse(refused.stdout);
+ expect(envelope.code).toBe('revision_required');
+ const argv: string[] = envelope.fix.argv;
+ expect(argv[0]).toBe('gbrain');
+
+ const read = await cli(['get', 'notes/bob', '--json']);
+ const revision: string = JSON.parse(read.stdout).revision;
+ expect(typeof revision).toBe('string');
+
+ const fix = await cli(argv.slice(1));
+ expect(fix.code, fix.stderr).toBe(0);
+ expect(fix.stdout + fix.stderr).toContain(revision);
+
+ const retry = await cli(['put', 'notes/bob', '--file', join(home, 'v2.md'), '--expected-revision', revision]);
+ expect(retry.code, retry.stderr).toBe(0);
+ }, 120_000);
+});
diff --git a/test/worker-quiet-hours-skip-keeps-cancelled.test.ts b/test/worker-quiet-hours-skip-keeps-cancelled.test.ts
new file mode 100644
index 0000000000..0acc53eda0
--- /dev/null
+++ b/test/worker-quiet-hours-skip-keeps-cancelled.test.ts
@@ -0,0 +1,47 @@
+/**
+ * Quiet-hours skip fallback: when MinionQueue.cancelJob throws, the worker's
+ * direct UPDATE must not touch a job that is already cancelled. Otherwise an
+ * operator's cancel reason is overwritten with 'skipped_quiet_hours'.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+
+describe('quiet-hours skip fallback', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('a job already cancelled keeps its cancel reason when cancelJob throws', async () => {
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('quiet-hours-probe', {});
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = 'cancelled', error_text = 'cancelled by operator' WHERE id = $1`,
+ [job.id],
+ );
+ const worker = new MinionWorker(engine, { concurrency: 1 });
+ const internals = worker as unknown as {
+ queue: MinionQueue;
+ handleQuietHoursDefer(job: unknown, lockToken: string, verdict: 'skip' | 'defer'): Promise<void>;
+ };
+ internals.queue.cancelJob = async () => { throw new Error('transient cancel failure'); };
+ const log = console.log;
+ console.log = () => {};
+ try {
+ await internals.handleQuietHoursDefer(job, 'no-lock', 'skip');
+ } finally {
+ console.log = log;
+ }
+ const [row] = await engine.executeRaw<{ status: string; error_text: string | null }>(
+ 'SELECT status, error_text FROM minion_jobs WHERE id = $1', [job.id],
+ );
+ expect(row!.status).toBe('cancelled');
+ expect(row!.error_text).toBe('cancelled by operator');
+ });
+});
diff --git a/test/write-receipt-remediation.test.ts b/test/write-receipt-remediation.test.ts
index 44113e6248..123b7d0423 100644
--- a/test/write-receipt-remediation.test.ts
+++ b/test/write-receipt-remediation.test.ts
@@ -52,12 +52,12 @@ describe('replayed receipts (B4)', () => {
test('a replaced page keeps code page_identity_changed', () => {
const e = replay(oldStyleRow({ error_message: 'The accepted page identity changed.' }));
- expect(envelope(e, 'cli')).toMatchObject({ error: 'page_identity_changed', code: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', 'notes', '--', 'people/alice-example'] } });
+ expect(envelope(e, 'cli')).toMatchObject({ error: 'page_identity_changed', code: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--include-content', '--source', 'notes', '--', 'people/alice-example'] } });
});
test('revision_conflict fills the same read from receipt fields', () => {
const e = replay(oldStyleRow({ state: 'conflict', error_code: 'revision_conflict', error_message: 'The page changed during preparation.' }));
- expect(envelope(e, 'cli').fix?.command).toBe('gbrain get --source notes -- people/alice-example');
+ expect(envelope(e, 'cli').fix?.command).toBe('gbrain get --include-content --source notes -- people/alice-example');
});
test('an unsafe slug drops the template; the fix falls back to the receipt read', () => {