Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

notifier: wanted markers, so a sync request is never dropped (2a.3)

garrytan89d0546d83a1
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index ad421fe5cd..1a140ba9de 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2394,6 +2394,16 @@ More: [docs/guides/write-refusals.md#no_pricing](../../docs/guides/write-refusal
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### no_resident
+
+<a id="no_resident"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A sync request (gbrain sync trigger) was recorded as a wanted marker, but no resident process (gbrain serve, gbrain jobs work or the autopilot daemon) runs on this brain to sync it. | On PGLite only the process that holds the database can sync, and none does; the marker is kept, so the next resident or sync drains it and nothing is lost. | Run gbrain sync --source <id> --no-pull now, or start gbrain serve (no service is installed for you); the recorded request is drained by the next resident. | agent | `gbrain doctor --json` | 3 | no |
+
+More: [docs/guides/on-commit-sync.md#no-resident](../../docs/guides/on-commit-sync.md#no-resident)
+
### no_routing_eval
<a id="no_routing_eval"></a>
@@ -2464,6 +2474,16 @@ Reasons: `not_owner_host`, `not_applicable`.
More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-pages)
+### notifier_stalled
+
+<a id="notifier_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The commit notifier kept a source due through every retry tier (5 s, 15 s, 1 min, 5 min) without the sync making progress; it keeps retrying every 5 minutes. | A commit-triggered sync failed or was refused the same way on every attempt, so the commit is still not searchable; the notifier block in gbrain sync status names the last error and the trace file with every attempt. | Run gbrain sync --source <id> --no-pull in the foreground to see the error, fix its cause, then read gbrain sync status --source <id> --json (the notifier block) to confirm the source is current. | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/guides/on-commit-sync.md#notifier-stalled](../../docs/guides/on-commit-sync.md#notifier-stalled)
+
### origin_twin_mass_merge_refused
<a id="origin_twin_mass_merge_refused"></a>
@@ -3092,6 +3112,16 @@ More: [docs/guides/write-refusals.md#refresh_not_managed](../../docs/guides/writ
More: [docs/guides/write-refusals.md#refresh_not_owner](../../docs/guides/write-refusals.md#refresh_not_owner)
+### refresh_required
+
+<a id="refresh_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A GitHub push arrived for a managed source: a managed source never pulls, so the pushed commit is recorded as wanted and waits for a refresh. | Managed sync imports the checkout's own HEAD; remote commits come in through gbrain sources refresh, which updates the worktree under the writer lock. The push's commit is kept as a wanted marker until the source reaches it. | Run gbrain sources refresh <id> on the brain host, then gbrain sync --source <id> --no-pull (a resident notifier runs the sync on its own). | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/on-commit-sync.md#refresh-required](../../docs/guides/on-commit-sync.md#refresh-required)
+
### refresh_source_changed
<a id="refresh_source_changed"></a>
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9065d3c95f..283f943139 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3014 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move)
+src/cli/main.ts 3015 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe)
src/commands/autopilot.ts 1650 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 7900b3f3ee..e149325ef3 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2467,7 +2467,8 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
// LiveServeLockError — instead the sync runs INSIDE the serve over its IPC
// socket (commands/sync-delegate.ts). Handled === delegated or politely
// refused (exit verdict set inside); false falls through unchanged.
- if (command === 'sync' && !syncOperator) {
+ if (command === 'sync' && args[0] === 'trigger' && await (await import('../commands/sync-delegate.ts')).maybeTriggerThroughServe(loadConfig(), args.slice(1))) return null;
+ if (command === 'sync' && !syncOperator && args[0] !== 'trigger') {
const cfgSync = loadConfig();
if (await (await import('../commands/sync-persistence-delegate.ts')).maybeDelegateSyncToPersistence(cfgSync, args)) return null;
if (cfgSync?.engine === 'pglite' && cfgSync.database_path && !cfgSync.database_url) {
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index ac04f5a6b4..bfffe68c7a 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -709,24 +709,8 @@ function mountGitHubWebhook(app: Express, ctx: ServeHttpContext): void {
return;
}
- // Submit sync job with priority -10 (above autopilot's 0).
try {
- const queue = new MinionQueue(engine);
- const job = await queue.add(
- 'sync',
- {
- sourceId: source.id,
- noExtract: false,
- auto_embed_backfill: true,
- embed_reason: 'webhook',
- },
- {
- priority: -10,
- idempotency_key: `webhook:sync:${source.id}:${Math.floor(Date.now() / 30_000)}`,
- maxWaiting: 1,
- },
- );
- res.status(202).json({ job_id: job.id, source_id: source.id });
+ await submitGitHubPush(engine, source.id, (parsed as { after?: unknown }).after, res);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error('webhook: queue submission error:', msg);
@@ -735,3 +719,48 @@ function mountGitHubWebhook(app: Express, ctx: ServeHttpContext): void {
},
);
}
+
+const PUSHED_SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
+
+/** The part of an Express response the push answer writes. */
+export interface PushAnswerSink { status(code: number): { json(body: unknown): unknown } }
+
+/**
+ * GBRA-133 PR 2a.3: a verified push for a tracked branch. The pushed commit is recorded as a wanted marker first, so
+ * it is never lost to coalescing: a classic source queues one sync (priority -10, single flight per source through
+ * maxPending 1; this replaced the 30 s idempotency bucket, which dropped a second push inside the bucket while the
+ * first job ran) and a later run re-checks the marker. A managed source never pulls, so instead of a 202 for a job
+ * that cannot import the push it answers refresh_required (409) with the gbrain sources refresh fix, keeping the
+ * marker until the source reaches that commit.
+ */
+export async function submitGitHubPush(engine: BrainEngine, sourceId: string, after: unknown, res: PushAnswerSink): Promise<void> {
+ const wantedHead = typeof after === 'string' && PUSHED_SHA.test(after) && !/^0+$/.test(after) ? after : null;
+ const { recordTriggerMarker } = await import('../core/notifier/nudge.ts');
+ const recorded = await recordTriggerMarker(engine, { sourceId, intent: 'pull', wantedHead, requestedBy: 'webhook' });
+ if (!recorded) { res.status(404).json({ error: 'unknown_source', source_id: sourceId }); return; }
+ const { marker, managed } = recorded;
+ const base = { source_id: sourceId, wanted_head: marker.wanted_head, marker_generation: marker.generation };
+ if (managed) {
+ const { opError } = await import('../core/ops/contract.ts');
+ const error = opError('refresh_required', `A push arrived for managed source ${sourceId}; a managed source never pulls, so the pushed commit waits for a refresh.`,
+ `Run gbrain sources refresh ${sourceId} on the brain host; the resident notifier then syncs the refreshed checkout.`,
+ { fix: { argv: ['gbrain', 'sources', 'refresh', sourceId], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Fast-forwards the managed checkout to its upstream under the writer lock and runs the managed --no-pull sync.' } });
+ res.status(409).json({ ...error.toJSON(), ...base, status: 'refresh_required' });
+ return;
+ }
+ const queue = new MinionQueue(engine);
+ const job = await queue.add(
+ 'sync',
+ {
+ sourceId,
+ noExtract: false,
+ auto_embed_backfill: true,
+ embed_reason: 'webhook',
+ },
+ { priority: -10, maxPending: 1 },
+ );
+ const { attachMarkerJob } = await import('../core/notifier/store.ts');
+ await attachMarkerJob(engine, sourceId, marker.intent, marker.generation, job.id);
+ res.status(202).json({ job_id: job.id, ...base, action: job.coalesced ? 'coalesced' : 'queued' });
+}
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index e8d76cda86..6579d04548 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -54,6 +54,7 @@ import {
readIpcSecret,
readIpcSecretForConfig,
requestSyncAbort,
+ requestSyncNudge,
requestSyncStart,
requestSyncStatus,
resolveSocketPath,
@@ -62,7 +63,9 @@ import {
} from '../core/context/resolve-ipc.ts';
import {
DELEGATED_SYNC_LANES_MAX,
+ SYNC_NUDGE_VERSION,
type DelegatedSyncOptions,
+ type SyncNudgeResponse,
type SyncStartRegistration,
type SyncStatusResponse,
type WireSyncResult,
@@ -271,6 +274,21 @@ export async function maybeDelegateSyncToServe(dataDir: string, args: string[]):
return true;
}
const startResp = start as Exclude<SyncStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;
+ // GBRA-133 PR 2a: a serve already syncing records this request as a wanted marker (never for --dry-run, which stays
+ // read-only); its notifier runs it once the running sync ends, so the request is not dropped.
+ if (!startResp.ok && startResp.error === 'busy' && !options.dryRun) {
+ const nudged = await requestSyncNudge(sock, { secret, version: SYNC_NUDGE_VERSION, sourceId: sourceId ?? 'default', requestedBy: 'delegated_sync',
+ ...(options.full ? { intent: 'full' as const } : options.noPull ? { intent: 'freshness' as const } : {}) });
+ const ack = nudged === IPC_UNAVAILABLE || 'degraded' in (nudged as object) ? null : nudged as SyncNudgeResponse;
+ if (ack?.ok && ack.marker) {
+ const m = ack.marker;
+ serr(`[sync] the serve (PID ${holder.pid}) is already syncing (job ${startResp.jobId ?? '?'}); recorded this request as wanted (${m.intent}`
+ + `${m.wanted_head ? ` ${m.wanted_head.slice(0, 8)}` : ''}, generation ${m.generation}); ${ack.notifier ? 'its notifier runs it when that sync ends' : 'the next resident with a notifier runs it'}.`);
+ if (args.includes('--json')) await (await import('../core/cli-force-exit.ts')).writeStdoutFinal(JSON.stringify({ action: 'nudged', source_id: m.source_id, intent: m.intent, wanted_head: m.wanted_head, marker_generation: m.generation, running_job_id: startResp.jobId ?? null }) + '\n');
+ await setVerdict(0);
+ return true;
+ }
+ }
if (!startResp.ok) {
serr(`[sync] ${startRefusalText(startResp)} ${remediation(holder.pid, '')}`);
await setVerdict(1);
@@ -624,3 +642,37 @@ function pick<T extends object, K extends keyof T>(source: T, keys: readonly K[]
for (const key of keys) if (source[key] !== undefined) out[key] = source[key];
return out;
}
+
+/**
+ * GBRA-133 PR 2a: `gbrain sync trigger` while a live serve holds the PGLite brain. The request is recorded as a wanted
+ * marker through the serve (sync_nudge, acknowledged) and its notifier starts the sync: action nudged, exit 0. A serve
+ * running without a notifier (GBRAIN_NOTIFIER=0) records it too and answers no_resident (exit 3 with the fix).
+ * Returns false off PGLite or when no serve holds the brain (the engine path records the marker: queued or no_resident).
+ * The owner-delegated sync paths in cli/main.ts skip `sync trigger`, which they would refuse as an unknown sync option.
+ */
+export async function maybeTriggerThroughServe(config: { engine?: string; database_path?: string; database_url?: string } | null, args: string[]): Promise<boolean> {
+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url || args.includes('--help') || args.includes('-h')) return false;
+ const dataDir = config.database_path;
+ const sourceId = args.find((a, i) => args[i - 1] === '--source');
+ if (!sourceId) return false;
+ const holder = probeLivePgliteHolder(dataDir);
+ if (!holder || !holder.serve) return false;
+ const json = args.includes('--json');
+ const sock = resolveSocketPath(dataDir);
+ const secret = readIpcSecret(dataDir);
+ const refuse = async (why: string) => { serr(`[sync trigger] a live gbrain serve (PID ${holder.pid}) holds this PGLite brain and ${why} ` + remediation(holder.pid, '')); await setVerdict(1); return true; };
+ if (!existsSync(sock) || !secret) return refuse('exposes no sync IPC (older gbrain, serve --http, or GBRAIN_SERVE_SYNC_IPC=0).');
+ const r = await requestSyncNudge(sock, { secret, version: SYNC_NUDGE_VERSION, sourceId, requestedBy: 'sync_trigger' });
+ if (r === IPC_UNAVAILABLE) return refuse('is not answering its IPC socket.');
+ if ('degraded' in (r as object)) return refuse('predates sync_nudge; restart it on this gbrain version.');
+ const resp = r as SyncNudgeResponse;
+ if (!resp.ok || !resp.marker) {
+ if (resp.error === 'unknown_source') { serr(`Source "${sourceId}" not found. List with: gbrain sources list`); await setVerdict(1); return true; }
+ return refuse(`refused the request (${resp.error ?? 'unknown error'}).`);
+ }
+ const { finishTrigger } = await import('./sync/trigger.ts');
+ const m = resp.marker;
+ await finishTrigger({ action: resp.notifier ? 'nudged' : 'no_resident', source_id: m.source_id, intent: m.intent, wanted_head: m.wanted_head, marker_generation: m.generation }, json);
+ if (resp.notifier) await setVerdict(0);
+ return true;
+}
diff --git a/src/commands/sync/trigger.ts b/src/commands/sync/trigger.ts
index 5457f16ef4..d122251872 100644
--- a/src/commands/sync/trigger.ts
+++ b/src/commands/sync/trigger.ts
@@ -1,47 +1,73 @@
-/** `gbrain sync trigger`: queue a push-triggered sync job. */
+/** `gbrain sync trigger`: ask for a sync of one source without waiting for it (GBRA-133 PR 2a). */
import type { BrainEngine } from '../../core/engine.ts';
-/**
- * v0.40 Federated Sync v2: `gbrain sync trigger --source <id> [--priority high|normal|low]`
- *
- * Push-trigger entry point. Wraps `queue.add('sync', ...)` with priority -10
- * (above autopilot's 0) so push-triggered syncs preempt scheduled ones.
- * Use cases: GitHub webhook handler (POST /webhooks/github), CLI nudge after
- * a manual git pull, scripted dispatch from `gbrain sources federate`.
- *
- * Sets `auto_embed_backfill: true` so the extended sync handler (T6/T7)
- * auto-enqueues an embed-backfill job after the sync settles.
- *
- * Output: prints `job_id=N` to stdout for shell composition. Errors exit 1.
- */
-export async function runSyncTrigger(engine: BrainEngine, args: string[]): Promise<void> {
- if (args.includes('--help') || args.includes('-h')) {
- console.log(`Usage: gbrain sync trigger --source <id> [--priority high|normal|low]
+export type TriggerAction = 'queued' | 'nudged' | 'coalesced' | 'no_resident';
+
+export interface TriggerOutcome {
+ action: TriggerAction;
+ source_id: string;
+ intent: 'freshness' | 'pull' | 'full';
+ wanted_head: string | null;
+ marker_generation: number;
+ job_id?: number;
+}
-Queue a push-triggered sync job for one source. Prints the resulting job id
-on stdout. The autopilot worker picks it up and runs performSync against the
-named source; if the sync added/modified pages, an embed-backfill job is
-auto-enqueued (subject to D6 budget cap + D19 source-level cooldown).
+const USAGE = 'Usage: gbrain sync trigger --source <id> [--priority high|normal|low] [--json]';
-Use cases:
- - GitHub webhook → 'gbrain sync trigger --source <repo>'
- - Manual nudge after 'git pull' inside a federated source
- - Programmatic triggers from CI / shell automation
+export function printSyncTriggerHelp(): void {
+ console.log(`${USAGE}
+
+Ask for a sync of one source without waiting for it. The request is recorded
+as a wanted marker (one per source and intent: freshness for a managed source,
+its checkout's HEAD; pull for a classic source), so it is never lost while
+another sync runs: whoever drains the source re-checks the marker afterwards.
+
+Outcomes (stdout keeps job_id=N whenever a job is queued; --json prints
+{action, job_id?, wanted_head, ...}):
+ queued a sync job was queued (Postgres; a jobs worker or autopilot runs it)
+ coalesced a sync job for this source is already waiting or running; the
+ marker makes it (or the notifier) run once more if needed
+ nudged the running gbrain serve recorded the request and its notifier
+ starts the sync (PGLite)
+ no_resident the request is recorded, but nothing on this brain will sync it
+ until a resident starts; exit 3 with the fix
+ gbrain sync --source <id> --no-pull
+
+Exit 0 for queued, coalesced and nudged; 3 for no_resident.
See also:
gbrain sources webhook set <id> Set up GitHub-signed push webhook
- gbrain sources status Per-source sync + embed coverage
+ gbrain sync status --source <id> The notifier block: who syncs it, its state
`);
- return;
- }
+}
+export function printTriggerOutcome(o: TriggerOutcome, json: boolean): void {
+ if (json) { console.log(JSON.stringify(o)); return; }
+ const head = o.wanted_head ? o.wanted_head.slice(0, 8) : 'upstream';
+ if (o.job_id !== undefined) console.log(`job_id=${o.job_id}`);
+ else console.log(`action=${o.action}`);
+ const line: Record<TriggerAction, string> = {
+ queued: `queued sync job ${o.job_id} for ${o.source_id} (${o.intent}, wanted ${head})`,
+ coalesced: `a sync job for ${o.source_id} is already waiting or running (job ${o.job_id}); the request is recorded and runs once more if that job does not reach ${head}`,
+ nudged: `the running serve recorded the request for ${o.source_id} (${o.intent}, wanted ${head}) and its notifier starts the sync`,
+ no_resident: `recorded the request for ${o.source_id} (${o.intent}, wanted ${head}), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) runs on this brain to sync it. Run: gbrain sync --source ${o.source_id} --no-pull`,
+ };
+ console.error(`[sync trigger] ${line[o.action]}`);
+}
+
+/**
+ * The engine path: Postgres queues a job (single flight per source through maxPending 1; the wanted marker replaces
+ * the old 30 s idempotency bucket), PGLite records the marker and reports no_resident (a live serve would have taken
+ * the request over its IPC socket before this process could open the brain, commands/sync-delegate.ts).
+ */
+export async function runSyncTrigger(engine: BrainEngine, args: string[]): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) return printSyncTriggerHelp();
const sourceIdArg = args.find((a, i) => args[i - 1] === '--source') ?? null;
if (!sourceIdArg) {
console.error('Error: --source <id> is required');
- console.error("Usage: gbrain sync trigger --source <id> [--priority high|normal|low]");
+ console.error(USAGE);
process.exit(2);
}
-
const priorityArg = args.find((a, i) => args[i - 1] === '--priority') ?? 'high';
const priorityMap: Record<string, number> = { high: -10, normal: 0, low: 5 };
const priority = priorityMap[priorityArg];
@@ -49,33 +75,40 @@ See also:
console.error(`Invalid --priority value: "${priorityArg}". Must be high|normal|low.`);
process.exit(2);
}
-
- // Verify source exists before submitting
- const { fetchSource } = await import('../../core/sources-load.ts');
- const source = await fetchSource(engine, sourceIdArg);
- if (!source) {
+ const json = args.includes('--json');
+ const { recordTriggerMarker } = await import('../../core/notifier/nudge.ts');
+ const recorded = await recordTriggerMarker(engine, { sourceId: sourceIdArg, requestedBy: 'sync_trigger' });
+ if (!recorded) {
console.error(`Source "${sourceIdArg}" not found. List with: gbrain sources list`);
process.exit(1);
}
-
+ const { marker, managed } = recorded;
+ const base = { source_id: marker.source_id, intent: marker.intent, wanted_head: marker.wanted_head, marker_generation: marker.generation };
+ if (engine.kind === 'pglite') return finishTrigger({ action: 'no_resident', ...base }, json);
const { MinionQueue } = await import('../../core/minions/queue.ts');
- const queue = new MinionQueue(engine);
- const job = await queue.add(
- 'sync',
- {
- sourceId: sourceIdArg,
- repoPath: source.local_path,
- noExtract: false,
- auto_embed_backfill: true,
- embed_reason: 'sync_trigger',
- },
- {
- priority,
- idempotency_key: `sync-trigger:${sourceIdArg}:${Math.floor(Date.now() / 30_000)}`,
- maxWaiting: 1,
- },
- );
+ const job = await new MinionQueue(engine).add('sync', {
+ sourceId: marker.source_id,
+ ...(managed || marker.intent === 'freshness' ? { noPull: true } : {}),
+ noExtract: false,
+ auto_embed_backfill: true,
+ embed_reason: 'sync_trigger',
+ }, { priority, maxPending: 1 });
+ const { attachMarkerJob } = await import('../../core/notifier/store.ts');
+ await attachMarkerJob(engine, marker.source_id, marker.intent, marker.generation, job.id);
+ await finishTrigger({ action: job.coalesced ? 'coalesced' : 'queued', ...base, job_id: job.id }, json);
+}
- // --json: stdout is JSON lines (the same contract runSync keeps).
- console.log(args.includes('--json') ? JSON.stringify({ job_id: job.id }) : `job_id=${job.id}`);
+/** Prints the outcome; no_resident also carries the error envelope (--json) and exits 3 with the fix. */
+export async function finishTrigger(o: TriggerOutcome, json: boolean): Promise<void> {
+ if (o.action !== 'no_resident') return printTriggerOutcome(o, json);
+ if (json) {
+ const { opError } = await import('../../core/ops/contract.ts');
+ const error = opError('no_resident', `No resident process syncs source ${o.source_id}; the request is recorded and waits for one.`,
+ `Run gbrain sync --source ${o.source_id} --no-pull now, or start gbrain serve; the recorded request is drained by the next resident.`,
+ { fix: { argv: ['gbrain', 'sync', '--source', o.source_id, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Syncs the checkout HEAD now; the recorded marker clears once last_commit reaches it.' } });
+ console.log(JSON.stringify({ ...o, error: error.toJSON() }));
+ } else printTriggerOutcome(o, false);
+ const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');
+ setCliExitVerdict(3);
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 96e71f1659..ff25e360c3 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -118,7 +118,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
- 'serve': ['--absolute-git-dir', '--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--verify', '--yes'],
+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.ts
index 3f7727e3ec..98f28338e1 100644
--- a/src/core/context/resolve-ipc.ts
+++ b/src/core/context/resolve-ipc.ts
@@ -37,6 +37,10 @@
* response, and an old serve answers `unknown_kind:sync_start` so the
* client degrades to the documented stop-the-serve refusal.
*
+ * sync_nudge (secret-gated, protocol:2, versioned) — GBRA-133 PR 2a: record a
+ * wanted marker (sync trigger, a busy delegated sync) and nudge the serve's
+ * commit notifier; acknowledged with the marker. Wire shapes in sync-ipc.ts.
+ *
* sweep_start / sweep_status (secret-gated, protocol:2) — #677:
* serve-delegated maintenance sweep, the same start+poll shape as the
* sync kinds (no abort — a sweep is a bounded run). Wire shapes in
@@ -67,6 +71,8 @@ import type { TurnContextResult } from './turn-context.ts';
import type {
SyncAbortRequest,
SyncAbortResponse,
+ SyncNudgeRequest,
+ SyncNudgeResponse,
SyncStartRequest,
SyncStartResponse,
SyncStatusRequest,
@@ -241,6 +247,7 @@ export type IpcRequest =
| SyncStartRequest
| SyncStatusRequest
| SyncAbortRequest
+ | SyncNudgeRequest
| SweepStartRequest
| SweepStatusRequest;
@@ -279,6 +286,7 @@ export type ContextPackHandler = (req: ContextPackRequest, progress?: { assemble
export type SyncStartIpcHandler = (req: SyncStartRequest) => SyncStartResponse | Promise<SyncStartResponse>;
export type SyncStatusIpcHandler = (req: SyncStatusRequest) => SyncStatusResponse | Promise<SyncStatusResponse>;
export type SyncAbortIpcHandler = (req: SyncAbortRequest) => SyncAbortResponse | Promise<SyncAbortResponse>;
+export type SyncNudgeIpcHandler = (req: SyncNudgeRequest) => SyncNudgeResponse | Promise<SyncNudgeResponse>;
export type SweepStartIpcHandler = (req: SweepStartRequest) => SweepStartResponse | Promise<SweepStartResponse>;
export type SweepStatusIpcHandler = (req: SweepStatusRequest) => SweepStatusResponse | Promise<SweepStatusResponse>;
@@ -290,6 +298,7 @@ export interface IpcHandlers {
sync_start?: SyncStartIpcHandler;
sync_status?: SyncStatusIpcHandler;
sync_abort?: SyncAbortIpcHandler;
+ sync_nudge?: SyncNudgeIpcHandler;
sweep_start?: SweepStartIpcHandler;
sweep_status?: SweepStatusIpcHandler;
}
@@ -635,6 +644,8 @@ export type SyncAbortClientRequest = Omit<SyncAbortRequest, 'kind' | 'protocol'>
export type SyncStartIpcResult = SyncStartResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
export type SyncStatusIpcResult = SyncStatusResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
export type SyncAbortIpcResult = SyncAbortResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
+export type SyncNudgeClientRequest = Omit<SyncNudgeRequest, 'kind' | 'protocol'>;
+export type SyncNudgeIpcResult = SyncNudgeResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
/**
* Delegated-sync clients: same fail-soft ladder as requestTurnContext —
@@ -671,6 +682,16 @@ export async function requestSyncAbort(
return syncRoundTrip<SyncAbortResponse>(socketPath, line, opts.timeoutMs ?? SYNC_ABORT_CLIENT_TIMEOUT_MS);
}
+/** GBRA-133 PR 2a: record a wanted marker through the serve (same fail-soft ladder; an older serve reads stale_serve). */
+export async function requestSyncNudge(
+ socketPath: string,
+ req: SyncNudgeClientRequest,
+ opts: { timeoutMs?: number } = {},
+): Promise<SyncNudgeIpcResult> {
+ const line = JSON.stringify({ kind: 'sync_nudge', protocol: 2, ...req } satisfies SyncNudgeRequest);
+ return syncRoundTrip<SyncNudgeResponse>(socketPath, line, opts.timeoutMs ?? SYNC_START_CLIENT_TIMEOUT_MS);
+}
+
// ── Delegated-sweep clients (#677) — same fail-soft ladder as sync ─────────
export type SweepStartClientRequest = Omit<SweepStartRequest, 'kind' | 'protocol'>;
@@ -888,6 +909,10 @@ export async function startResolveIpcServer(
resp = JSON.stringify(
await handleSyncKind(parsed as SyncAbortRequest, handlers.sync_abort, opts),
);
+ } else if (kind === 'sync_nudge') {
+ resp = JSON.stringify(
+ await handleSyncKind(parsed as SyncNudgeRequest, handlers.sync_nudge, opts),
+ );
} else if (kind === 'sweep_start') {
resp = JSON.stringify(
await handleSyncKind(parsed as SweepStartRequest, handlers.sweep_start, opts),
diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.ts
index 9fb250d506..dc1c261cc6 100644
--- a/src/core/context/sync-ipc.ts
+++ b/src/core/context/sync-ipc.ts
@@ -296,3 +296,35 @@ export interface SyncAbortResponse {
state?: DelegatedSyncState;
error?: string;
}
+
+/**
+ * GBRA-133 PR 2a: sync_nudge (secret-gated, protocol 2, versioned by `version`). A client that cannot sync now (
+ * `gbrain sync trigger`, or a delegated sync the serve answered `busy`) records what it wants as a wanted marker
+ * through the serve that holds the PGLite brain, which acknowledges with the marker and nudges its notifier. An
+ * absent `intent` lets the serve pick (managed: freshness, classic: pull); a freshness marker with no `wantedHead`
+ * takes the checkout's HEAD as the serve reads it. An older serve answers unknown_kind:sync_nudge.
+ */
+export const SYNC_NUDGE_VERSION = 1;
+
+export interface SyncNudgeRequest {
+ kind: 'sync_nudge';
+ protocol: 2;
+ version: number;
+ secret: string;
+ sourceId: string;
+ intent?: 'freshness' | 'pull' | 'full';
+ wantedHead?: string | null;
+ requestedBy: 'sync_trigger' | 'delegated_sync';
+}
+
+export interface SyncNudgeResponse {
+ ok: boolean;
+ protocol: 2;
+ version?: number;
+ acked?: boolean;
+ marker?: { source_id: string; intent: 'freshness' | 'pull' | 'full'; generation: number; wanted_head: string | null; first_due_at: string };
+ /** Whether a notifier runs in that serve (false: GBRAIN_NOTIFIER=0 there; the marker waits for a resident). */
+ notifier?: boolean;
+ resident?: string | null;
+ error?: string;
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 23a3c77796..de677848df 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -283,6 +283,8 @@ export const CODES = {
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
ghost_mass_delete_refused: { class: 'consent', summary: "gbrain repair ghost-pages refused to soft-delete more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to ghost pages: that many missing canonical files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted.", docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Check the source checkout on its owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is removed.", requires_exclusive: false } },
+ no_resident: { class: 'unavailable', actor: 'agent', exit: 3, summary: "A sync request (gbrain sync trigger) was recorded as a wanted marker, but no resident process (gbrain serve, gbrain jobs work or the autopilot daemon) runs on this brain to sync it.", why: "On PGLite only the process that holds the database can sync, and none does; the marker is kept, so the next resident or sync drains it and nothing is lost.", docs: 'docs/guides/on-commit-sync.md#no-resident', suggestion: 'Run gbrain sync --source <id> --no-pull now, or start gbrain serve (no service is installed for you); the recorded request is drained by the next resident.' },
+ notifier_stalled: { class: 'retryable', actor: 'agent', summary: "The commit notifier kept a source due through every retry tier (5 s, 15 s, 1 min, 5 min) without the sync making progress; it keeps retrying every 5 minutes.", why: "A commit-triggered sync failed or was refused the same way on every attempt, so the commit is still not searchable; the notifier block in gbrain sync status names the last error and the trace file with every attempt.", docs: 'docs/guides/on-commit-sync.md#notifier-stalled', suggestion: 'Run gbrain sync --source <id> --no-pull in the foreground to see the error, fix its cause, then read gbrain sync status --source <id> --json (the notifier block) to confirm the source is current.' },
origin_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair origin-twins refused to merge duplicate-origin twins amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to origin twins (#6948): that many twins at once almost always means a re-import under other slugs or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#origin-twins', suggestion: 'Check the source and its checkout first. If merging these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },
ghost_storage_unknown: { class: 'unavailable', summary: "Ghost pages of a source cannot be classified because its canonical checkout cannot be read reliably; nothing was listed or changed.", why: "A page is never reported or removed as a ghost while its file may only be unreadable: a missing or non-directory root (storage_unavailable), or a stat error, an invalid gbrain.yml or an inconclusive page check (ambiguous_storage), fails closed.", reasons: ['storage_unavailable', 'ambiguous_storage'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair ghost-pages --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },
git_branch_unborn: { class: 'host_only', summary: "The canonical checkout's branch has no commit yet, so Git durability has nothing to build on.", why: "A Git effect commits on top of HEAD and pushes the branch; on an unborn branch (a fresh `init --git` root) there is no HEAD to commit on and no ref to push, so enabling durability would park every effect. The database is unaffected.", suggestion: 'Make the first commit on the branch on the brain host (git add -A && git commit -m "Initial brain"), then rerun gbrain sources writer git-durability <source> --enable.' },
@@ -452,6 +454,7 @@ export const CODES = {
persistence_restart_required: { class: 'host_only', summary: "This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code.", why: "A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit).", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart the serve process (for the installed service: systemctl --user restart gbrain-serve; otherwise stop and start it in the foreground); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json.' },
pool_inflight_over_budget: { class: 'host_only', summary: "A pooled statement of this gbrain serve has run longer than its in-flight budget (the read pool's statement_timeout plus grace, or the longer statement_timeout its operation declared); `/health?deep=1` answers 503 with this code.", why: "Since #6543 the in-flight watchdog retires a statement past its budget whether or not bytes keep arriving (reason=age), so this code means the watchdog is off (GBRAIN_PG_STUCK_GRACE_MS=off), the serve runs a driver without per-statement budgets, or the retirement is still in progress; a transaction that declared a longer statement_timeout, or an index build that declared 0, is measured against its own budget and not reported. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check.' },
deep_health_probe_failed: { class: 'retryable', summary: "The pooled `SELECT 1` of `/health?deep=1` did not answer: an earlier probe is still pending, it timed out, or it failed.", reasons: ['pending', 'timeout', 'error'], why: "The deep probe runs through the ordinary pooled dispatch, where handler statements wait, so a saturated or wedged pool fails it while plain /health (a reserved idle connection) may still answer 200. One deep probe runs per engine at a time.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Retry in a few seconds; if it keeps failing, run gbrain doctor --json from a fresh process to check the database and pooler, then restart this gbrain serve.' },
+ refresh_required: { class: 'caller', actor: 'agent', summary: "A GitHub push arrived for a managed source: a managed source never pulls, so the pushed commit is recorded as wanted and waits for a refresh.", why: "Managed sync imports the checkout's own HEAD; remote commits come in through gbrain sources refresh, which updates the worktree under the writer lock. The push's commit is kept as a wanted marker until the source reaches it.", docs: 'docs/guides/on-commit-sync.md#refresh-required', suggestion: 'Run gbrain sources refresh <id> on the brain host, then gbrain sync --source <id> --no-pull (a resident notifier runs the sync on its own).' },
serve_self_exit_suppressed: { class: 'host_only', summary: "gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed.", why: "The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand.' },
serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },
persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index 2046c90d9c..10b9eccaa3 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -108,6 +108,10 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
next: { command: `gbrain jobs get ${live.id} --json`, safe_to_loop: true, retry_after_ms: 30_000, why: `Sync job #${live.id} is draining source ${sourceId ?? 'default'}; it resumes the cursor, so nothing else needs to run.` } };
}
}
+ // GBRA-133 PR 2a: the wanted markers this run can satisfy, read before it starts; after the run each is cleared
+ // only if nobody re-recorded it meanwhile (generation), and anything still due gets one follow-up job.
+ const { readMarkersForRun, settleRunMarkers, recordBusyMarker } = await import('../../notifier/handoff.ts');
+ const markersRead = await readMarkersForRun(engine, sourceId ?? 'default');
let result;
try {
result = await performSync(engine, {
@@ -135,6 +139,8 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
const holder = read && read.kind !== 'unknown' ? read : null;
const runningJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;
console.error(`[sync] skipped: sync already in progress for ${id} (lock ${err.lockKey} held${holder ? ` by a ${holder.kind} drainer` : ''}).`);
+ // GBRA-133 PR 2a: the newer commit this job was for is recorded as wanted; the holder's run re-checks it.
+ await recordBusyMarker(engine, id, { pull: !noPull });
// A job result is readable by remote callers (get_job), so it carries the public holder: kind and times only.
return { skipped: true, reason: 'sync_in_progress', source_id: id, ...(holder ? { holder: publicDrainHolder(holder) } : {}),
...(runningJob !== null ? { running_job_id: runningJob, next: { command: `gbrain jobs get ${runningJob} --json`, safe_to_loop: true, retry_after_ms: 30_000,
@@ -212,6 +218,8 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
throw new UnrecoverableError(`Managed sync of source ${sourceId ?? 'default'} is ${result.status === 'blocked_by_failures' ? 'blocked' : 'stopped'}`
+ ` (${drain?.stop_reason ?? result.status}${drain?.remaining != null ? `, ${drain.remaining} entries left` : ''}). ${next?.why ?? ''}${next?.command ? ` Next: ${next.command}` : ''}`.trim());
}
- return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason, ...(embedNotice ? { notice: embedNotice } : {}) };
+ const followUp = drained.incomplete === true ? null : await settleRunMarkers(engine, sourceId ?? 'default', markersRead, { pulled: !noPull, full: false });
+ return { ...result, ...drained, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason, ...(embedNotice ? { notice: embedNotice } : {}),
+ ...(followUp ? { marker_follow_up: followUp } : {}) };
};
}
diff --git a/src/core/notifier/handoff.ts b/src/core/notifier/handoff.ts
new file mode 100644
index 0000000000..bdd035353e
--- /dev/null
+++ b/src/core/notifier/handoff.ts
@@ -0,0 +1,45 @@
+/**
+ * GBRA-133 PR 2a: the wanted-marker handoff for a drainer that is not the notifier (the `sync` job handler, the serve's
+ * delegated runner). Read the markers before the run, settle them after it (generation-checked, store.ts), and start
+ * at most one follow-up for whatever is still due: a queued job (maxWaiting 1, so it never coalesces into the job that
+ * is finishing) where a queue drains jobs, else a nudge to this process's notifier. A run that finds the source busy
+ * records a marker instead of dropping its commit. Every step is best effort: the run's own result never depends on it,
+ * and the residents' durable marker scan drains anything left behind (a marker that lands after this re-check).
+ */
+import type { BrainEngine } from '../engine.ts';
+import { attachMarkerJob, missingTable, readDueMarkers, settleMarkers, type WantedMarker } from './store.ts';
+
+export async function readMarkersForRun(engine: BrainEngine, sourceId: string): Promise<WantedMarker[]> {
+ try { return await readDueMarkers(engine, [sourceId]); } catch (error) { if (!missingTable(error)) console.error(`[sync] reading wanted markers of ${sourceId} failed: ${error instanceof Error ? error.message : String(error)}`); return []; }
+}
+
+/** After a completed run: clears what it satisfied; queues one follow-up job when something is still due. Returns that job. */
+export async function settleRunMarkers(engine: BrainEngine, sourceId: string, read: WantedMarker[], run: { pulled: boolean; full: boolean }, opts: { queue?: boolean } = {}): Promise<{ job_id: number | null; markers: number } | null> {
+ try {
+ const remaining = await settleMarkers(engine, sourceId, read, run);
+ if (!remaining.length) return null;
+ if (opts.queue === false || engine.kind === 'pglite') {
+ (await import('./resident.ts')).nudgeResidentNotifier();
+ return { job_id: null, markers: remaining.length };
+ }
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const pull = remaining.some(m => m.intent === 'pull');
+ const job = await new MinionQueue(engine).add('sync', { sourceId, ...(pull ? {} : { noPull: true }), noExtract: false, auto_embed_backfill: true, embed_reason: 'marker_follow_up' },
+ { priority: -10, maxWaiting: 1 });
+ for (const m of remaining) await attachMarkerJob(engine, sourceId, m.intent, m.generation, job.id);
+ return { job_id: job.id, markers: remaining.length };
+ } catch (error) {
+ if (!missingTable(error)) console.error(`[sync] settling wanted markers of ${sourceId} failed: ${error instanceof Error ? error.message : String(error)}`);
+ return null;
+ }
+}
+
+/** A run that found another sync draining the source records what it wanted; the holder's re-check (or a resident) runs it. */
+export async function recordBusyMarker(engine: BrainEngine, sourceId: string, opts: { pull: boolean }): Promise<void> {
+ try {
+ const { recordTriggerMarker } = await import('./nudge.ts');
+ await recordTriggerMarker(engine, { sourceId, intent: opts.pull ? undefined : 'freshness', requestedBy: 'lock_busy' });
+ } catch (error) {
+ if (!missingTable(error)) console.error(`[sync] recording a wanted marker for ${sourceId} failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
diff --git a/src/core/notifier/nudge.ts b/src/core/notifier/nudge.ts
new file mode 100644
index 0000000000..6d51c9ce8e
--- /dev/null
+++ b/src/core/notifier/nudge.ts
@@ -0,0 +1,55 @@
+/**
+ * GBRA-133 PR 2a: the serve side of `sync_nudge` and the marker a trigger records. One rule for every submitter:
+ * a managed source asks for freshness (its checkout's HEAD; it never pulls), a classic source asks for a pull unless
+ * the caller named an intent, and a freshness marker with no head takes the checkout's HEAD now.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { SYNC_NUDGE_VERSION, type SyncNudgeRequest, type SyncNudgeResponse } from '../context/sync-ipc.ts';
+import { MARKER_INTENTS, upsertMarker, type MarkerIntent, type MarkerRequester, type WantedMarker } from './store.ts';
+import { revParseHead } from './detect.ts';
+import { nudgeResidentNotifier, residentNotifier } from './resident.ts';
+
+const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
+
+/** Whether the source is a managed one (bound to a worktree on an activated brain), and its checkout root. */
+export async function sourceSyncShape(engine: BrainEngine, sourceId: string): Promise<{ exists: boolean; managed: boolean; root: string | null }> {
+ const [row] = await engine.executeRaw<{ local_path: string | null; root: string | null; bound: unknown; enabled: unknown }>(
+ `SELECT s.local_path, h.local_path AS root, (b.source_id IS NOT NULL) AS bound,
+ COALESCE((SELECT enabled FROM persistence_brain WHERE singleton = 1), false) AS enabled
+ FROM sources s
+ LEFT JOIN persistence_source_bindings b ON b.source_id = s.id AND b.source_incarnation = s.incarnation
+ LEFT JOIN persistence_worktrees w ON w.id = b.worktree_id
+ LEFT JOIN persistence_host_bindings h ON h.worktree_id = w.id AND h.host_id = w.owner_host_id
+ WHERE s.id = $1 AND NOT s.archived LIMIT 1`, [sourceId]);
+ if (!row) return { exists: false, managed: false, root: null };
+ const managed = (row.bound === true || row.bound === 't') && (row.enabled === true || row.enabled === 't');
+ return { exists: true, managed, root: (managed ? row.root : null) ?? row.local_path };
+}
+
+/** Records the marker a trigger asks for; resolves the intent and, for freshness, the checkout's HEAD. */
+export async function recordTriggerMarker(engine: BrainEngine, req: { sourceId: string; intent?: MarkerIntent; wantedHead?: string | null; requestedBy: MarkerRequester; jobId?: number | null }):
+ Promise<{ marker: WantedMarker; managed: boolean } | null> {
+ const shape = await sourceSyncShape(engine, req.sourceId);
+ if (!shape.exists) return null;
+ const intent: MarkerIntent = req.intent ?? (shape.managed ? 'freshness' : 'pull');
+ let wantedHead = req.wantedHead ?? null;
+ if (intent === 'freshness' && !wantedHead && shape.root) wantedHead = await revParseHead(shape.root).catch(() => null);
+ return { marker: await upsertMarker(engine, { sourceId: req.sourceId, intent, wantedHead, requestedBy: req.requestedBy, jobId: req.jobId ?? null }), managed: shape.managed };
+}
+
+export async function recordSyncNudge(engine: BrainEngine, req: SyncNudgeRequest): Promise<SyncNudgeResponse> {
+ if (typeof req.version !== 'number' || req.version < 1) return { ok: false, protocol: 2, version: SYNC_NUDGE_VERSION, error: 'unsupported_version' };
+ if (typeof req.sourceId !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,62}$/i.test(req.sourceId)) return { ok: false, protocol: 2, version: SYNC_NUDGE_VERSION, error: 'invalid_options:sourceId' };
+ if (req.intent !== undefined && !(MARKER_INTENTS as readonly string[]).includes(req.intent)) return { ok: false, protocol: 2, version: SYNC_NUDGE_VERSION, error: 'invalid_options:intent' };
+ if (req.wantedHead !== undefined && req.wantedHead !== null && !(typeof req.wantedHead === 'string' && SHA.test(req.wantedHead))) {
+ return { ok: false, protocol: 2, version: SYNC_NUDGE_VERSION, error: 'invalid_options:wantedHead' };
+ }
+ const requestedBy: MarkerRequester = req.requestedBy === 'delegated_sync' ? 'delegated_sync' : 'sync_nudge';
+ const recorded = await recordTriggerMarker(engine, { sourceId: req.sourceId, intent: req.intent, wantedHead: req.wantedHead ?? null, requestedBy });
+ if (!recorded) return { ok: false, protocol: 2, version: SYNC_NUDGE_VERSION, error: 'unknown_source' };
+ const resident = residentNotifier();
+ nudgeResidentNotifier();
+ const m = recorded.marker;
+ return { ok: true, protocol: 2, version: SYNC_NUDGE_VERSION, acked: true, notifier: resident !== null, resident: resident?.resident ?? null,
+ marker: { source_id: m.source_id, intent: m.intent, generation: m.generation, wanted_head: m.wanted_head, first_due_at: m.first_due_at } };
+}
diff --git a/src/core/notifier/store.ts b/src/core/notifier/store.ts
index 6694980757..320f2cceb2 100644
--- a/src/core/notifier/store.ts
+++ b/src/core/notifier/store.ts
@@ -280,8 +280,10 @@ export async function recordSyncerHost(engine: Exec, sourceId: string, hostId: s
/**
* Called where a sync advances a source's last_commit (sync-anchor.ts writeSyncAnchor): records this host as the
- * source's syncer, so this host's resident notifier watches it. Best effort: a sync never fails on it.
+ * source's syncer, so this host's resident notifier watches it, and clears the markers that head satisfies. Best effort: a sync never fails on it.
*/
export async function recordLocalSyncer(engine: Exec, sourceId: string): Promise<void> {
try { await recordSyncerHost(engine, sourceId, localHostId()); } catch { /* the notifier reports the source as unrecorded */ }
+ // The CLI's re-check (GBRA-133 PR 2a.3): a run that reached a marker's head clears it, whoever ran it.
+ try { await pruneSatisfiedMarkers(engine, [sourceId]); } catch { /* the residents' marker scan prunes it */ }
}
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index 96f03da56c..1100bd58ab 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -54,6 +54,7 @@
* CLI's effective flags (the managed cursor owns processing options).
*/
+import { readMarkersForRun, settleRunMarkers } from './notifier/handoff.ts';
import { isAdmissionOrigin, withAdmissionOrigin } from './persistence/admission-origin.ts';
import { randomUUID } from 'node:crypto';
import { withLegacySyncDelegation } from './persistence/sync-authority.ts';
@@ -260,6 +261,7 @@ function startDelegatedSyncScoped(
`start job=${job.id} source=${sourceId ?? 'default'} ` +
`opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,
);
+ const markers = options.dryRun ? [] : await readMarkersForRun(engine, sourceId ?? 'default');
const r = await performSync(engine, {
...classicSyncOpts(options, sourceId),
// ALWAYS deferred — see module header. Drained by maybeDrainDeferredEmbeds.
@@ -276,6 +278,7 @@ function startDelegatedSyncScoped(
`done job=${job.id} status=${r.status} added=${r.added} modified=${r.modified} ` +
`deleted=${r.deleted} in=${Math.round((Date.now() - job.startedAt) / 1000)}s`,
);
+ if (!options.dryRun) await settleRunMarkers(engine, sourceId ?? 'default', markers, { pulled: !options.noPull, full: options.full === true }, { queue: false });
// Wire noEmbed means the USER declined embeds — honor it by skipping
// the drain too (performSync above always ran noEmbed regardless).
if (!options.dryRun && !options.noEmbed && r.added + r.modified > 0) {
@@ -350,6 +353,7 @@ async function startVerifiedDelegatedSync(
const { performSync } = await import('../commands/sync.ts');
const sourceId = await resolveJobSource(engine, job);
const managed = await readManagedMode(engine);
+ const markers = options.dryRun ? [] : await readMarkersForRun(engine, sourceId ?? 'default');
log(
`start job=${job.id} source=${sourceId ?? 'default'} writer=${verified.principal.id} managed=${managed} ` +
`opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,
@@ -382,6 +386,8 @@ async function startVerifiedDelegatedSync(
`done job=${job.id} status=${r.status} added=${r.added} modified=${r.modified} ` +
`deleted=${r.deleted}${r.drain ? ` drain=${r.drain.outcome}` : ''} in=${Math.round((Date.now() - job.startedAt) / 1000)}s`,
);
+ // GBRA-133 PR 2a.3: the post-run re-check (generation-checked); whatever is still due goes to this serve's notifier.
+ if (!options.dryRun) await settleRunMarkers(engine, sourceId ?? 'default', markers, { pulled: !managed && !options.noPull, full: options.full === true }, { queue: false });
if (!managed && !options.dryRun && !options.noEmbed && r.added + r.modified > 0) {
scheduleDeferredSyncEmbeds(engine, sourceId);
}
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index 655857f60a..e4f0f919be 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -189,7 +189,7 @@ export async function bindResolveIpcForServe(
// catch would otherwise swallow the error and start NO listener).
// Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not
// registered and clients get 'unsupported_kind' (the polite refusal).
- let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort'> = {};
+ let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort' | 'sync_nudge'> = {};
if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {
try {
const runner = await import('../core/serve-sync-runner.ts');
@@ -202,6 +202,8 @@ export async function bindResolveIpcForServe(
}),
sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId, typeof req.afterLine === 'number' ? req.afterLine : 0),
sync_abort: (req) => runner.abortDelegatedSync(req.jobId),
+ // GBRA-133 PR 2a: a wanted marker recorded through this serve, acknowledged, and a nudge to its notifier.
+ sync_nudge: async (req) => (await import('../core/notifier/nudge.ts')).recordSyncNudge(engine, req),
};
} catch (e) {
process.stderr.write(
diff --git a/test/e2e/s-notifier-marker-handoff-postgres.test.ts b/test/e2e/s-notifier-marker-handoff-postgres.test.ts
new file mode 100644
index 0000000000..2976483f79
--- /dev/null
+++ b/test/e2e/s-notifier-marker-handoff-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../pathological/s-notifier-marker-handoff.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 2e25517e17..9ebc41aa99 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6403,7 +6403,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"no_resident\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/pathological/s-notifier-marker-handoff.test.ts b/test/pathological/s-notifier-marker-handoff.test.ts
new file mode 100644
index 0000000000..7b8d97c3da
--- /dev/null
+++ b/test/pathological/s-notifier-marker-handoff.test.ts
@@ -0,0 +1,226 @@
+/**
+ * GBRA-133 PR 2a.3: a request to sync a source is never dropped. Every submitter (sync trigger, the GitHub push
+ * webhook, sync_nudge, a busy delegated sync) records a wanted marker per source and intent; a drainer clears only the
+ * generation it read, and the residents' durable marker scan drains anything left behind, with sync.on_commit off.
+ *
+ * Protects (each case fails on v0.60.309.0, where none of this exists: a push inside the webhook's 30 s idempotency
+ * bucket, or a trigger that coalesced into a finishing job, left its commit unsynced until something else synced):
+ * - a marker re-recorded while a run was in flight survives that run's settle (generation check) and gets a follow-up;
+ * - a marker recorded after the handler's last check but before its job completed is drained by a resident's scan
+ * with sync.on_commit off and no later commits;
+ * - a submitter that crashed after its upsert (no job queued) is drained the same way after a resident starts;
+ * - a dry run stays read-only (no marker read, cleared or written);
+ * - the push webhook coalesces a second push into the waiting job and keeps the newer sha; a managed push answers
+ * refresh_required (409) with the gbrain sources refresh fix and queues nothing;
+ * - sync trigger --json reports queued / coalesced (Postgres) and no_resident with exit 3 (PGLite, no serve).
+ * Real git, real store, real handler, real delegated runner. PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { performSync } from '../../src/commands/sync.ts';
+import { makeSyncHandler } from '../../src/core/minions/handlers/sync.ts';
+import { startServeHeadWatcher } from '../../src/core/serve-head-watcher.ts';
+import { __resetDelegatedSyncForTests, getDelegatedSyncStatus, isDelegatedSyncRunning, startDelegatedSync } from '../../src/core/serve-sync-runner.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { readMarkers, upsertMarker } from '../../src/core/notifier/store.ts';
+import { recordTriggerMarker } from '../../src/core/notifier/nudge.ts';
+import { settleRunMarkers } from '../../src/core/notifier/handoff.ts';
+import { submitGitHubPush as submitPush } from '../../src/commands/serve-http-webhooks.ts';
+import { runSyncTrigger } from '../../src/commands/sync/trigger.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { managedBrain, pathologicalArms } from './harness.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+function commit(root: string, file: string, body: string): string {
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, file), body);
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', `add ${file}`);
+ return git(root, 'rev-parse', 'HEAD');
+}
+async function until(what: string, fn: () => Promise<boolean>, lines: string[] = [], timeoutMs = 90_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await fn())) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}; log: ${JSON.stringify(lines)}`);
+ await Bun.sleep(100);
+ }
+}
+const searchable = async (engine: BrainEngine, word: string, slug: string) => (await engine.searchKeyword(word, { limit: 20 })).some(r => r.slug === slug);
+const lastCommit = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]?.last_commit ?? null;
+const SOURCE = 'acme-example';
+
+/** The push route's answer, captured from the response sink it writes. */
+async function submitGitHubPush(engine: BrainEngine, sourceId: string, after: unknown): Promise<{ status: number; body: Record<string, unknown> }> {
+ let answer: { status: number; body: Record<string, unknown> } | null = null;
+ await submitPush(engine, sourceId, after, { status: (status: number) => ({ json: (body: unknown) => { answer = { status, body: body as Record<string, unknown> }; } }) });
+ if (!answer) throw new Error('the push route wrote no answer');
+ return answer;
+}
+
+async function classicBrain(databaseUrl: string | undefined, run: (b: { engine: BrainEngine; root: string }) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-marker-handoff-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_NOTIFIER: undefined, GBRAIN_NOTIFIER_CLASSIC_SOURCES: undefined }, async () => {
+ __resetDelegatedSyncForTests();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, SOURCE); mkdirSync(root); git(root, 'init', '-q');
+ commit(root, 'notes/alice-example.md', '---\ntitle: Alice Example\n---\nAlice Example keeps the acme-example ledger.\n');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3)", [SOURCE, root, JSON.stringify({ github_repo: 'acme-example/notes' })]);
+ await performSync(engine, { sourceId: SOURCE, repoPath: root, noPull: true, noEmbed: true });
+ await engine.setConfig('sync.on_commit', 'false');
+ await run({ engine, root });
+ } finally {
+ await until('the runner to idle', async () => !isDelegatedSyncRunning(), [], 60_000).catch(() => undefined);
+ __resetDelegatedSyncForTests();
+ await disposePersistenceConsumer(engine).catch(() => undefined);
+ await close();
+ }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function quietly<T>(fn: () => Promise<T>): Promise<{ value: T; out: string[]; err: string[] }> {
+ const out: string[] = []; const err: string[] = [];
+ const [log, error] = [console.log, console.error];
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ try { return { value: await fn(), out, err }; } finally { console.log = log; console.error = error; }
+}
+
+/** A resident started with sync.on_commit off drains the recorded marker; returns its recorded decisions. */
+async function drainWithResident(engine: BrainEngine, word: string, slug: string, head: string) {
+ const lines: string[] = [];
+ const watcher = startServeHeadWatcher(engine, { log: line => lines.push(line), pollMs: 1000, debounceMs: 100 });
+ try {
+ await until(`${slug} to become searchable`, async () => searchable(engine, word, slug), lines);
+ await until('last_commit to reach the marker head', async () => (await lastCommit(engine, SOURCE)) === head && !isDelegatedSyncRunning(), lines);
+ await until('the marker to clear', async () => (await readMarkers(engine, [SOURCE])).length === 0, lines);
+ return { decisions: [...watcher.decisions], snapshot: watcher.snapshot(), lines };
+ } finally { await watcher.stop(); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`wanted markers never drop a request (${backend})`, () => {
+ test('a marker re-recorded while a run was in flight survives that run and gets one follow-up', async () => {
+ await classicBrain(databaseUrl, async ({ engine, root }) => {
+ const first = await upsertMarker(engine, { sourceId: SOURCE, intent: 'freshness', wantedHead: git(root, 'rev-parse', 'HEAD'), requestedBy: 'sync_trigger' });
+ const read = [first];
+ const newer = commit(root, 'notes/bob-example.md', '---\ntitle: Bob Example\n---\nBob Example files the quarterly heliotrope memo.\n');
+ const second = await upsertMarker(engine, { sourceId: SOURCE, intent: 'freshness', wantedHead: newer, requestedBy: 'sync_trigger' });
+ expect(second.generation).toBe(first.generation + 1);
+ const followUp = await settleRunMarkers(engine, SOURCE, read, { pulled: false, full: false });
+ const left = await readMarkers(engine, [SOURCE]);
+ expect(left.map(m => [m.intent, m.generation, m.wanted_head])).toEqual([['freshness', second.generation, newer]]);
+ expect(followUp?.markers).toBe(1);
+ if (engine.kind === 'pglite') expect(followUp?.job_id).toBeNull();
+ else {
+ expect(typeof followUp?.job_id).toBe('number');
+ expect(left[0]!.job_id).toBe(followUp!.job_id);
+ const again = await settleRunMarkers(engine, SOURCE, [], { pulled: false, full: false });
+ expect(again?.job_id).toBe(followUp!.job_id);
+ }
+ });
+ }, 120_000);
+
+ test('a marker recorded after the job handler\'s last check, before completion, is drained by a resident with sync.on_commit off', async () => {
+ await classicBrain(databaseUrl, async ({ engine, root }) => {
+ const head = commit(root, 'notes/carol-example.md', '---\ntitle: Carol Example\n---\nCarol Example audits the marmalade ledger.\n');
+ const result = await quietly(() => makeSyncHandler(engine)({ id: 1, name: 'sync', data: { sourceId: SOURCE, repoPath: root, pull: false, auto_embed_backfill: false },
+ signal: new AbortController().signal, updateProgress: async () => {}, log: async () => {} } as never));
+ expect((result.value as { status?: string }).status).not.toBe('blocked_by_failures');
+ expect(await lastCommit(engine, SOURCE)).toBe(head);
+ const later = commit(root, 'notes/dave-example.md', '---\ntitle: Dave Example\n---\nDave Example tracks the cobalt shipment.\n');
+ const recorded = await recordTriggerMarker(engine, { sourceId: SOURCE, intent: 'freshness', requestedBy: 'sync_trigger' });
+ expect(recorded?.marker.wanted_head).toBe(later);
+ const drained = await drainWithResident(engine, 'cobalt', 'notes/dave-example', later);
+ expect(drained.snapshot.enabled).toBe(false);
+ expect(drained.decisions.some(d => d.source === SOURCE && d.decision === 'start')).toBe(true);
+ });
+ }, 180_000);
+
+ test('a submitter that crashed after its upsert (no job queued) is drained once a resident starts', async () => {
+ await classicBrain(databaseUrl, async ({ engine, root }) => {
+ const head = commit(root, 'notes/erin-example.md', '---\ntitle: Erin Example\n---\nErin Example signs the tangerine lease.\n');
+ await upsertMarker(engine, { sourceId: SOURCE, intent: 'freshness', wantedHead: head, requestedBy: 'webhook' });
+ expect(Number((await engine.executeRaw<{ n: unknown }>("SELECT count(*) AS n FROM minion_jobs WHERE name='sync'"))[0]!.n)).toBe(0);
+ const drained = await drainWithResident(engine, 'tangerine', 'notes/erin-example', head);
+ expect(drained.decisions.some(d => d.source === SOURCE && d.decision === 'start')).toBe(true);
+ });
+ }, 180_000);
+
+ test('a dry run stays read-only: a pending pull marker is neither read for clearing nor changed', async () => {
+ await classicBrain(databaseUrl, async ({ engine }) => {
+ const marker = await upsertMarker(engine, { sourceId: SOURCE, intent: 'pull', wantedHead: null, requestedBy: 'sync_trigger' });
+ const start = await startDelegatedSync(engine, { sourceId: SOURCE, noPull: false, dryRun: true, timeoutSeconds: 60 }, `test-${randomUUID()}`);
+ expect(start.ok).toBe(true);
+ await until('the dry run to finish', async () => !isDelegatedSyncRunning());
+ expect(getDelegatedSyncStatus(String((start as { jobId: string }).jobId)).state).toBe('done');
+ expect((await readMarkers(engine, [SOURCE])).map(m => [m.intent, m.generation])).toEqual([['pull', marker.generation]]);
+ });
+ }, 120_000);
+
+ test('the push webhook records the pushed sha and coalesces a second push into the waiting job', async () => {
+ await classicBrain(databaseUrl, async ({ engine }) => {
+ const sha1 = 'a'.repeat(40); const sha2 = 'b'.repeat(40);
+ const first = await submitGitHubPush(engine, SOURCE, sha1);
+ const second = await submitGitHubPush(engine, SOURCE, sha2);
+ expect(first.status).toBe(202); expect(second.status).toBe(202);
+ expect(first.body).toMatchObject({ action: 'queued', source_id: SOURCE, wanted_head: sha1 });
+ expect(second.body).toMatchObject({ action: 'coalesced', job_id: first.body.job_id, wanted_head: sha2 });
+ const markers = await readMarkers(engine, [SOURCE]);
+ expect(markers.map(m => [m.intent, m.wanted_head, m.generation, m.job_id])).toEqual([['pull', sha2, 2, first.body.job_id as number]]);
+ const deleted = await submitGitHubPush(engine, SOURCE, '0'.repeat(40));
+ expect(deleted.body).toMatchObject({ wanted_head: null });
+ });
+ }, 120_000);
+
+ test('sync trigger --json: queued then coalesced on Postgres; no_resident with exit 3 on PGLite without a serve', async () => {
+ await classicBrain(databaseUrl, async ({ engine }) => {
+ _resetCliExitVerdictForTests();
+ try {
+ const one = await quietly(() => runSyncTrigger(engine, ['--source', SOURCE, '--json']));
+ const a = JSON.parse(one.out.at(-1)!);
+ if (engine.kind === 'pglite') {
+ expect(a).toMatchObject({ action: 'no_resident', source_id: SOURCE, intent: 'pull' });
+ expect(a.error.fix).toBeDefined();
+ expect(JSON.stringify(a.error)).toContain('--no-pull');
+ expect(currentExitCode()).toBe(3);
+ expect((await readMarkers(engine, [SOURCE])).map(m => m.intent)).toEqual(['pull']);
+ return;
+ }
+ const two = await quietly(() => runSyncTrigger(engine, ['--source', SOURCE, '--json']));
+ const b = JSON.parse(two.out.at(-1)!);
+ expect(a).toMatchObject({ action: 'queued', source_id: SOURCE, intent: 'pull' });
+ expect(typeof a.job_id).toBe('number');
+ expect(b).toMatchObject({ action: 'coalesced', job_id: a.job_id, marker_generation: a.marker_generation + 1 });
+ expect(currentExitCode()).toBe(0);
+ const text = await quietly(() => runSyncTrigger(engine, ['--source', SOURCE]));
+ expect(text.out).toContain(`job_id=${a.job_id}`);
+ } finally { _resetCliExitVerdictForTests(); }
+ });
+ }, 120_000);
+
+ test('a managed push answers refresh_required with the sources refresh fix and queues nothing', async () => {
+ await managedBrain(async ({ engine }) => {
+ await engine.executeRaw("UPDATE sources SET config = config || $1::jsonb WHERE id='default'", [JSON.stringify({ github_repo: 'acme-example/managed' })]);
+ const sha = 'c'.repeat(40);
+ const answer = await submitGitHubPush(engine, 'default', sha);
+ expect(answer.status).toBe(409);
+ expect(answer.body).toMatchObject({ status: 'refresh_required', source_id: 'default', wanted_head: sha });
+ expect(JSON.stringify(answer.body)).toContain('"refresh_required"');
+ expect(JSON.stringify(answer.body)).toContain('"sources","refresh","default"');
+ expect((await readMarkers(engine, ['default'])).map(m => [m.intent, m.wanted_head])).toEqual([['pull', sha]]);
+ const jobs = await engine.executeRaw<{ n: unknown }>("SELECT count(*) AS n FROM minion_jobs WHERE name='sync'");
+ expect(Number(jobs[0]!.n)).toBe(0);
+ }, { databaseUrl });
+ }, 120_000);
+ });
+}