Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-133 2a.4: idle wait, HEAD read and status lock read in sibling modules

garrytan0dad27859301
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9065d3c95f..a176f29ba6 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -4,7 +4,7 @@
# 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/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/autopilot.ts 1662 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); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.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)
src/commands/extract-conversation-facts.ts 2044 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left
@@ -29,7 +29,7 @@ src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred s
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
-src/core/minions/worker.ts 1782 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts)
+src/core/minions/worker.ts 1788 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts)
src/commands/sources.ts 2060 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts)
src/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index af2402e4e6..d6161aa5c8 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -22,11 +22,7 @@ import {
} from './autopilot-remediation-policy.ts';
import type { AutopilotDaemonState } from './autopilot-daemon.ts';
import { logError } from './autopilot.ts';
-import { existsSync } from 'node:fs';
-import { join } from 'node:path';
-import { execFileBounded } from '../core/bounded-child-exec.ts';
-import { gitChildEnv } from '../core/git-env.ts';
-import { GIT_OPERATION_MARKERS } from '../core/git/commit-push.ts';
+import { readCheckoutHead } from '../core/checkout-head.ts';
import { SYNC_ON_COMMIT_KEY } from '../core/sync-config-keys.ts';
import { autopilotPaused } from '../core/autopilot-paths.ts';
@@ -269,15 +265,6 @@ export interface FreshnessDecision {
job_id?: number;
}
-/** A checkout's HEAD and whether a rebase, merge, cherry-pick or revert is mid-flight there. Async and bounded; null when git cannot read it. */
-export async function readCheckoutHead(root: string): Promise<{ head: string; operation: string | null } | null> {
- const r = await execFileBounded('git', ['-C', root, 'rev-parse', '--absolute-git-dir', 'HEAD'], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
- if (r.error) return null;
- const [gitDir, head] = r.stdout.trim().split('\n');
- if (!gitDir || !head || !/^[0-9a-f]{40,64}$/.test(head)) return null;
- return { head, operation: GIT_OPERATION_MARKERS.find(marker => existsSync(join(gitDir, marker))) ?? null };
-}
-
/**
* GBRA-133 2a.4: why a checkout source is due a freshness sync. HEAD-driven first: HEAD differs from the source's last
* synced commit and this daemon has not already dispatched (or decided) for that HEAD; no ancestry assumption. The
@@ -292,10 +279,25 @@ export function freshnessTrigger(input: { head: { head: string; operation: strin
return 'head';
}
+/** Whether a checkout source is due a freshness sync: its trigger and HEAD, or why not (fresh, or a live sync job). */
+async function checkoutFreshness(engine: BrainEngine, src: SourceRow, root: string, input: { ageMs: number; intervalMs: number; decidedHead?: string }):
+ Promise<{ trigger: 'head' | 'interval'; head: { head: string; operation: string | null } | null } | { decision: FreshnessDecision }> {
+ const head = await readCheckoutHead(root);
+ const trigger = freshnessTrigger({ head, lastCommit: src.last_commit, ...input });
+ if (!trigger) return { decision: { source_id: src.id, outcome: 'fresh', head: head?.head ?? null } };
+ // #6706: a live sync job (any submitter) is already draining this source; coalescing into another submitter's row is refused.
+ if (await (await import('../core/persistence/sync-movement.ts')).liveSyncJob(engine, src.id) !== null) {
+ return { decision: { source_id: src.id, outcome: 'live_job', trigger, head: head?.head ?? null } };
+ }
+ return { trigger, head };
+}
+
/**
* v0.40 D17 freshness: runs first each tick, independent of the score gate.
* `freshnessHeads` (the daemon's per-source map of the HEAD it last dispatched or decided for) keeps a HEAD-driven
* dispatch to one per HEAD; `onlySourceIds` narrows the pass to the sources the between-tick HEAD probe saw move.
+ * A HEAD-driven job is keyed on its HEAD, never the wall-clock slot, so a new commit cannot coalesce into the slot's
+ * completed job. A source with a live sync job keeps its HEAD undecided; the next tick or probe dispatches it.
*/
export async function dispatchFreshnessSyncs(
engine: BrainEngine,
@@ -337,7 +339,8 @@ export async function dispatchFreshnessSyncs(
// reason is stated once per source and reason, and an explicit `gbrain sync --source <id>` is unaffected.
const skip = await automaticSyncSkip(engine, src, activationPending);
if (skip?.reason !== 'sync_disabled') reportAutomaticSyncSkip(src.id, skip, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'));
- if (skip) { decisions.push({ source_id: src.id, outcome: 'skipped' }); continue; }
+ if (skip) decisions.push({ source_id: src.id, outcome: 'skipped' });
+ if (skip) continue;
// A local_path this machine cannot use — relative (#3696: cwd is
// launchd's, not the registering shell's) or absent on disk and
// not a managed clone sync can re-create — would sync a phantom
@@ -354,15 +357,9 @@ export async function dispatchFreshnessSyncs(
}
const lastSyncMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0;
const ageMs = now - lastSyncMs;
- const head = await readCheckoutHead(src.local_path);
- const trigger = freshnessTrigger({ head, lastCommit: src.last_commit, ageMs, intervalMs, decidedHead: freshnessHeads.get(src.id) });
- if (!trigger) { decisions.push({ source_id: src.id, outcome: 'fresh', head: head?.head ?? null }); continue; }
- // #6706: a live sync job (any submitter) is already draining this source; coalescing into another submitter's row
- // is refused. The HEAD stays undecided, so the next tick or HEAD probe dispatches it once that job ends.
- if (await (await import('../core/persistence/sync-movement.ts')).liveSyncJob(engine, src.id) !== null) {
- decisions.push({ source_id: src.id, outcome: 'live_job', trigger, head: head?.head ?? null });
- continue;
- }
+ const due = await checkoutFreshness(engine, src, src.local_path, { ageMs, intervalMs, decidedHead: freshnessHeads.get(src.id) });
+ if ('decision' in due) { decisions.push(due.decision); continue; }
+ const { trigger, head } = due;
try {
const job = await queue.add(
'sync',
@@ -375,9 +372,7 @@ export async function dispatchFreshnessSyncs(
},
{
queue: 'default',
- // A HEAD-driven sync is keyed on the HEAD, never on the wall-clock slot: a slot key would coalesce a new commit
- // into the slot's completed job and drop it until the next slot.
- idempotency_key: trigger === 'head' ? `autopilot-sync:${src.id}:head:${head!.head}` : `autopilot-sync:${src.id}:${slot}`,
+ idempotency_key: `autopilot-sync:${src.id}:${trigger === 'head' ? `head:${head!.head}` : slot}`,
max_attempts: 2,
timeout_ms: timeoutMs,
// #6706: single-flight per source. A sync job drains until synced or its deadline, so a tick while one runs
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index d085a57c80..75279b7ce9 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -20,7 +20,7 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, unlinkSync, chmodSync, statSync } from 'fs';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { readGlobalMaintenanceVerdict } from '../core/minions/global-maintenance-stall.ts';
-import { daemonStaleAfterSeconds, readAutopilotHeartbeat } from '../core/autopilot-heartbeat.ts';
+import { readDaemonStaleAfter } from '../core/autopilot-heartbeat.ts';
import { detectExecutionEnvironment } from '../core/execution-env.ts';
import { join, dirname, isAbsolute, resolve as resolvePath } from 'path';
import { execSync } from '../core/spawn.ts';
@@ -1483,9 +1483,8 @@ export interface AutopilotStatusReport {
paused_reason: string | null;
heartbeat_age_seconds: number | null;
stale_after_seconds: number;
- /** #7003: `daemon` when the threshold comes from the running daemon's heartbeat sidecar, `flag` when from --interval. */
+ /** #7003: threshold from the running daemon's heartbeat sidecar or the --interval flag; its next tick while it sleeps. */
stale_after_source: 'daemon' | 'flag';
- /** #7003: the daemon's own next tick (its adaptive interval), when its sidecar says it is sleeping. */
next_tick_at: string | null;
last_log: string;
}
@@ -1590,13 +1589,9 @@ function showStatus(json: boolean, intervalSeconds: number) {
const pausedReason = autopilotPauseReason();
let heartbeatAgeSeconds: number | null = null;
- let lock: { mtimeMs: number; pid: number | null } | null = null;
try {
const { mtimeMs } = statSync(autopilotLockPath());
heartbeatAgeSeconds = Math.max(0, Math.floor((Date.now() - mtimeMs) / 1000));
- let pid: number | null = null;
- try { const n = parseInt(readFileSync(autopilotLockPath(), 'utf-8').trim(), 10); pid = Number.isFinite(n) ? n : null; } catch { /* unreadable: pid unknown */ }
- lock = { mtimeMs, pid };
} catch { /* never ran, or already cleaned up */ }
const jobStatus = autopilotJobStatus(job);
@@ -1608,7 +1603,7 @@ function showStatus(json: boolean, intervalSeconds: number) {
pausedReason,
heartbeatAgeSeconds,
intervalSeconds,
- daemon: daemonStaleAfterSeconds(readAutopilotHeartbeat(), lock),
+ daemon: readDaemonStaleAfter(),
lastLog: lastLine,
});
const processing = readAutopilotProcessingStatus();
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index 8283c1e2c0..9f79ee2626 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -252,7 +252,7 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
// GBRA-133 2a.4: a queued sync job wakes the idle claim loop (LISTEN on a direct session, a short poll otherwise).
const { startSyncQueueWake } = await import('../../core/minions/sync-queue-wake.ts');
- const syncQueueWake = await startSyncQueueWake(engine, worker, { queue: queueName });
+ const syncQueueWake = await startSyncQueueWake(engine, worker.idleWaiter, { queue: queueName });
startWorkerPersistenceConsumer(engine);
try {
diff --git a/src/core/autopilot-heartbeat.ts b/src/core/autopilot-heartbeat.ts
index 21ff5e8432..a51b626735 100644
--- a/src/core/autopilot-heartbeat.ts
+++ b/src/core/autopilot-heartbeat.ts
@@ -12,8 +12,8 @@
* - no sidecar, one written by another pid than the lock holder, or one older than the lock (a daemon binary that
* does not write it): the caller's flag, as before.
*/
-import { readFileSync, renameSync, writeFileSync } from 'fs';
-import { autopilotHeartbeatPath } from './autopilot-paths.ts';
+import { readFileSync, renameSync, statSync, writeFileSync } from 'fs';
+import { autopilotHeartbeatPath, autopilotLockPath } from './autopilot-paths.ts';
export interface AutopilotHeartbeat {
pid: number;
@@ -64,3 +64,11 @@ export function daemonStaleAfterSeconds(heartbeat: AutopilotHeartbeat | null, lo
if (!Number.isFinite(nextMs)) return null;
return { staleAfter: Math.max(0, Math.ceil((nextMs - lock.mtimeMs) / 1000)) + Math.max(base, 120), nextTickAt: heartbeat.next_tick_at };
}
+
+/** The live daemon's threshold for `gbrain autopilot --status`: its sidecar graded against the lock's mtime and holder pid. */
+export function readDaemonStaleAfter(lockPath = autopilotLockPath(), heartbeatPath = autopilotHeartbeatPath()): { staleAfter: number; nextTickAt: string | null } | null {
+ let lock: { mtimeMs: number; pid: number | null };
+ try { lock = { mtimeMs: statSync(lockPath).mtimeMs, pid: null }; } catch { return null; }
+ try { const n = parseInt(readFileSync(lockPath, 'utf-8').trim(), 10); lock.pid = Number.isFinite(n) ? n : null; } catch { /* unreadable: pid unknown */ }
+ return daemonStaleAfterSeconds(readAutopilotHeartbeat(heartbeatPath), lock);
+}
diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.ts
index 052865dfcc..b5172beeb0 100644
--- a/src/core/autopilot-paths.ts
+++ b/src/core/autopilot-paths.ts
@@ -37,7 +37,7 @@ export function autopilotLockPath(): string {
/**
* #7003: the daemon's heartbeat sidecar beside the lock. It records the daemon's own next tick (its adaptive interval),
- * so `--status` grades staleness from what the daemon scheduled rather than the caller's `--interval`
+ * so autopilot status grades staleness from what the daemon scheduled rather than the caller's interval flag
* (src/core/autopilot-heartbeat.ts). The lock mtime stays the liveness signal.
*/
export function autopilotHeartbeatPath(): string {
diff --git a/src/core/checkout-head.ts b/src/core/checkout-head.ts
new file mode 100644
index 0000000000..cc7bac3b9f
--- /dev/null
+++ b/src/core/checkout-head.ts
@@ -0,0 +1,21 @@
+/**
+ * GBRA-133 2a.4: a checkout's HEAD for the autopilot's HEAD-driven freshness dispatch (commands/autopilot-dispatch.ts).
+ * The git directory comes from the checkout's own `.git` entry (a directory, or a worktree/submodule `gitdir:` file),
+ * so the probe is one bounded `git rev-parse HEAD` plus a stat per in-progress-operation marker.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { execFileBounded } from './bounded-child-exec.ts';
+import { gitChildEnv } from './git-env.ts';
+import { GIT_OPERATION_MARKERS } from './git/commit-push.ts';
+import { enclosingGitMetadata } from './persistence/root-registry.ts';
+
+/** A checkout's HEAD and whether a rebase, merge, cherry-pick or revert is mid-flight there. Async and bounded; null when git cannot read it. */
+export async function readCheckoutHead(root: string): Promise<{ head: string; operation: string | null } | null> {
+ const gitDir = enclosingGitMetadata(root);
+ if (!gitDir) return null;
+ const r = await execFileBounded('git', ['-C', root, 'rev-parse', 'HEAD'], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ const head = r.error ? '' : r.stdout.trim();
+ if (!/^[0-9a-f]{40,64}$/.test(head)) return null;
+ return { head, operation: GIT_OPERATION_MARKERS.find(marker => existsSync(join(gitDir, marker))) ?? null };
+}
diff --git a/src/core/minions/idle-wait.ts b/src/core/minions/idle-wait.ts
new file mode 100644
index 0000000000..3c33a6c1f6
--- /dev/null
+++ b/src/core/minions/idle-wait.ts
@@ -0,0 +1,46 @@
+/**
+ * The MinionWorker claim loop's idle poll wait, which `wake()` ends early (GBRA-133 2a.4 sync-queue wake,
+ * src/core/minions/sync-queue-wake.ts). A wake while the loop is claiming makes the next idle wait a no-op, so a job
+ * inserted between an empty claim and the wait is never left for the full poll interval.
+ */
+
+/** One idle poll wait and how it ended (`waiting` while in progress). */
+export interface IdleWait { ms: number; ended: 'waiting' | 'timer' | 'wake' | 'skipped' | 'stop'; reason?: string }
+
+export class IdleWaiter {
+ private waiting: { entry: IdleWait; timer: ReturnType<typeof setTimeout>; resolve: () => void } | null = null;
+ private pending = false;
+ /** The newest idle waits and how each ended (bounded): the recorded decisions the sync-queue wake tests read. */
+ readonly history: IdleWait[] = [];
+
+ /** True while the claim loop waits out an idle poll (nothing claimed, nothing in flight). */
+ get idle(): boolean { return this.waiting !== null; }
+
+ /** A claim is starting: it covers every wake that arrived before it. */
+ claimStarted(): void { this.pending = false; }
+
+ wake(reason = 'wake'): void {
+ const waiting = this.waiting;
+ if (!waiting) { if (reason !== 'stop') this.pending = true; return; }
+ this.waiting = null;
+ clearTimeout(waiting.timer);
+ waiting.entry.ended = reason === 'stop' ? 'stop' : 'wake';
+ waiting.entry.reason = reason;
+ waiting.resolve();
+ }
+
+ wait(ms: number): Promise<void> {
+ if (this.history.length >= 100) this.history.shift();
+ if (this.pending) {
+ this.pending = false;
+ this.history.push({ ms, ended: 'skipped' });
+ return Promise.resolve();
+ }
+ const entry: IdleWait = { ms, ended: 'waiting' };
+ this.history.push(entry);
+ return new Promise<void>(resolve => {
+ const timer = setTimeout(() => { this.waiting = null; entry.ended = 'timer'; resolve(); }, ms);
+ this.waiting = { entry, timer, resolve };
+ });
+ }
+}
diff --git a/src/core/minions/sync-queue-wake.ts b/src/core/minions/sync-queue-wake.ts
index 8fc4b69d9c..486c8fa77e 100644
--- a/src/core/minions/sync-queue-wake.ts
+++ b/src/core/minions/sync-queue-wake.ts
@@ -17,7 +17,7 @@
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
-import type { MinionWorker } from './worker.ts';
+import type { IdleWaiter } from './idle-wait.ts';
import { consumerConnectionRoute } from '../persistence/consumer-lane.ts';
export const SYNC_WAKE_CHANNEL = 'minion_jobs';
@@ -66,8 +66,8 @@ async function listenSql(engine: BrainEngine, reason: SyncQueueWakeChoice['reaso
return routed.sql as ListenSql;
}
-/** Start the wake for one worker and log one line naming the mode. Never throws: a failed or unverified LISTEN polls instead. */
-export async function startSyncQueueWake(engine: BrainEngine, worker: Pick<MinionWorker, 'wake' | 'idle'>,
+/** Start the wake for one worker's idle waiter and log one line naming the mode. Never throws: a failed or unverified LISTEN polls instead. */
+export async function startSyncQueueWake(engine: BrainEngine, waiter: Pick<IdleWaiter, 'wake' | 'idle'>,
opts: { queue: string; env?: Record<string, string | undefined>; log?: (line: string) => void }): Promise<SyncQueueWake> {
const env = opts.env ?? process.env;
const log = opts.log ?? ((line: string) => console.log(line));
@@ -86,7 +86,7 @@ export async function startSyncQueueWake(engine: BrainEngine, worker: Pick<Minio
});
const listener = await sql.listen(SYNC_WAKE_CHANNEL, payload => {
if (payload === probe) { probed(); return; }
- if (!stopped && isSyncWakePayload(payload, opts.queue)) worker.wake('sync_queue_notify');
+ if (!stopped && isSyncWakePayload(payload, opts.queue)) waiter.wake('sync_queue_notify');
});
await engine.executeRaw('SELECT pg_notify($1, $2)', [SYNC_WAKE_CHANNEL, probe]);
if (await arrived) {
@@ -108,10 +108,10 @@ export async function startSyncQueueWake(engine: BrainEngine, worker: Pick<Minio
log(`[gbrain jobs] sync-queue wake: poll every ${pollMs} ms (${choice.reason})`);
let inflight: Promise<void> | null = null;
const timer = setInterval(() => {
- if (stopped || inflight || !worker.idle) return;
+ if (stopped || inflight || !waiter.idle) return;
inflight = engine.executeRaw<{ one: number }>(
`SELECT 1 AS one FROM minion_jobs WHERE queue = $1 AND name = 'sync' AND status = 'waiting' LIMIT 1`, [opts.queue])
- .then(rows => { if (!stopped && rows.length > 0) worker.wake('sync_queue_poll'); }, () => { /* the claim loop's own poll is the backstop */ })
+ .then(rows => { if (!stopped && rows.length > 0) waiter.wake('sync_queue_poll'); }, () => { /* the claim loop's own poll is the backstop */ })
.finally(() => { inflight = null; });
}, pollMs);
timer.unref?.();
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 2a7a763f1c..8b0e1108dd 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -88,6 +88,7 @@ import { EventEmitter } from 'events';
import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';
import { endedByShutdown, releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';
import { isWatchdogSuspect, settleWatchdogAbort } from './watchdog-attribution.ts';
+import { IdleWaiter } from './idle-wait.ts';
import { readFileSync } from 'fs';
/**
@@ -190,9 +191,6 @@ interface InFlightJob {
shared: boolean;
}
-/** One idle poll wait of the claim loop and how it ended (waiting while in progress). */
-export interface IdleWait { ms: number; ended: 'waiting' | 'timer' | 'wake' | 'skipped' | 'stop'; reason?: string }
-
export interface ConfigurationReleaseResult {
jobId: number | null;
lockToken: string;
@@ -221,12 +219,8 @@ export class MinionWorker extends EventEmitter {
private running = false;
/** Log the pause/resume transition once each, not every poll. */
private pausedByMarkerAnnounced = false;
- /** The idle poll wait in progress, which wake() ends early; null while the loop is not idle-waiting. */
- private idleWaiting: { entry: IdleWait; timer: ReturnType<typeof setTimeout>; resolve: () => void } | null = null;
- /** A wake that arrived while the loop was claiming: the next idle wait is skipped so the claim runs again at once. */
- private wakePending = false;
- /** The newest idle poll waits and how each ended (bounded): the recorded decisions the sync-queue wake tests read. */
- readonly idleWaits: IdleWait[] = [];
+ /** The idle poll wait a sync-queue wake ends early (minions/idle-wait.ts). */
+ readonly idleWaiter = new IdleWaiter();
private inFlight = new Map<number, InFlightJob>();
private executions = new Map<string, OwnedExecution>();
private pendingClaim: { lockToken: string; promise: Promise<MinionJob | null> } | null = null;
@@ -852,7 +846,7 @@ export class MinionWorker extends EventEmitter {
}
if (this.inFlight.size < this.opts.concurrency && ![...this.inFlight.values()].some(f => isWatchdogSuspect(f.job))) {
const lockToken = `${this.workerId}:${randomUUID()}`;
- this.wakePending = false;
+ this.idleWaiter.claimStarted();
let job: MinionJob | null;
try {
const claim = this.queue.claim(
@@ -924,7 +918,7 @@ export class MinionWorker extends EventEmitter {
}
} else if (this.inFlight.size === 0) {
// No jobs and nothing in flight, poll (a sync-queue wake ends the wait early)
- await this.idleWait(this.opts.pollInterval);
+ await this.idleWaiter.wait(this.opts.pollInterval);
} else {
// Jobs are running but no new ones available, brief pause before re-checking
await new Promise(resolve => setTimeout(resolve, 100));
@@ -1060,47 +1054,14 @@ export class MinionWorker extends EventEmitter {
requestShutdown(): void {
if (this.running) console.log('Minion worker shutting down...');
this.running = false;
- this.wake('stop');
+ this.idleWaiter.wake('stop');
if (!this.shutdownAbort.signal.aborted) this.shutdownAbort.abort(new Error('shutdown'));
}
- /**
- * End the idle poll wait now so the loop claims at once (GBRA-133 2a.4 sync-queue wake,
- * src/core/minions/sync-queue-wake.ts). A wake while the loop is claiming makes the next idle wait a no-op, so a job
- * inserted between an empty claim and the wait is never left for the full poll interval.
- */
- wake(reason = 'wake'): void {
- const waiting = this.idleWaiting;
- if (!waiting) { if (reason !== 'stop') this.wakePending = true; return; }
- this.idleWaiting = null;
- clearTimeout(waiting.timer);
- waiting.entry.ended = reason === 'stop' ? 'stop' : 'wake';
- waiting.entry.reason = reason;
- waiting.resolve();
- }
-
- /** True while the claim loop waits out an idle poll (nothing claimed, nothing in flight). */
- get idle(): boolean { return this.idleWaiting !== null; }
-
- private idleWait(ms: number): Promise<void> {
- if (this.idleWaits.length >= 100) this.idleWaits.shift();
- if (this.wakePending) {
- this.wakePending = false;
- this.idleWaits.push({ ms, ended: 'skipped' });
- return Promise.resolve();
- }
- const entry: IdleWait = { ms, ended: 'waiting' };
- this.idleWaits.push(entry);
- return new Promise<void>(resolve => {
- const timer = setTimeout(() => { this.idleWaiting = null; entry.ended = 'timer'; resolve(); }, ms);
- this.idleWaiting = { entry, timer, resolve };
- });
- }
-
/** Stop the worker gracefully. */
stop(): void {
this.running = false;
- this.wake('stop');
+ this.idleWaiter.wake('stop');
try { this.eldHistogram?.disable(); } catch { /* fail-open */ }
}
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index a24ed3e39a..0c7adb60c8 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -20,7 +20,8 @@ function gitMetadataDirectory(root: string): string | null {
const match = /^gitdir:\s*(.+)\s*$/m.exec(readFileSync(git, 'utf8'));
return match ? resolve(root, match[1]) : null;
}
-function enclosingGitMetadata(root: string): string | null {
+/** The git metadata directory of the checkout enclosing `root` (walks up to a `.git` directory or `gitdir:` file). */
+export function enclosingGitMetadata(root: string): string | null {
let current = root;
for (;;) {
const metadata = gitMetadataDirectory(current);
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 2e25517e17..f2ae042698 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6153,6 +6153,7 @@
"private shutdownAbort",
"private workerId",
"rawListeners: <E extends string | symbol>(eventName: string | symbol) => ((...args: any[]) => void)[]",
+ "readonly idleWaiter: IdleWaiter",
"register: (name: string, handler: MinionHandler) => void",
"registeredNames: string[]",
"removeAllListeners: <E extends string | symbol>(eventName?: string | symbol | undefined) => MinionWorker",
diff --git a/test/pathological/s-7002-worker-consumer.test.ts b/test/pathological/s-7002-worker-consumer.test.ts
index bd1c7151a3..c004434465 100644
--- a/test/pathological/s-7002-worker-consumer.test.ts
+++ b/test/pathological/s-7002-worker-consumer.test.ts
@@ -11,7 +11,7 @@
* stopped worker leaves its row. Real `gbrain jobs work` processes; asserts on the consumer rows (states), never on
* elapsed time. PGLite always, Postgres when DATABASE_URL is set.
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -50,26 +50,31 @@ async function stop(child: Subprocess): Promise<number | null> {
for (const { backend, databaseUrl } of pathologicalArms()) {
describe('#7002 a resident jobs worker joins the persistence-consumer election at boot (' + backend + ')', () => {
if (backend === 'pglite') {
- test('PGLite: jobs work drains the queue in the foreground and exits; no consumer is left behind', async () => {
- const home = brainHome({ engine: 'pglite', database_path: '' });
+ // The whole run happens in beforeAll so each PGLite open sits beside the hook that owns it; the test asserts.
+ let home = '';
+ let run: { code: number | null; text: string; rows: ConsumerRow[] } | null = null;
+ beforeAll(async () => {
+ home = brainHome({ engine: 'pglite', database_path: '' });
const path = join(home, '.gbrain', 'brain.pglite');
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: path, embedding_disabled: true }));
const engine = new PGLiteEngine();
await engine.connect({ database_path: path });
await engine.initSchema();
await engine.disconnect();
- try {
- const { child, output } = spawnWorker(home);
- const code = await stop_after_exit(child);
- const text = await output();
- expect(code, text).toBe(0);
- expect(text).toContain('drained');
- const after = new PGLiteEngine();
- await after.connect({ database_path: path });
- try { expect(await after.executeRaw<ConsumerRow>("SELECT pid, kind, mode FROM persistence_consumers WHERE kind='jobs'")).toEqual([]); }
- finally { await after.disconnect(); }
- } finally { rmSync(home, { recursive: true, force: true }); }
+ const { child, output } = spawnWorker(home);
+ const code = await stop_after_exit(child);
+ const after = new PGLiteEngine();
+ await after.connect({ database_path: path });
+ try { run = { code, text: await output(), rows: await after.executeRaw<ConsumerRow>("SELECT pid, kind, mode FROM persistence_consumers WHERE kind='jobs'") }; }
+ finally { await after.disconnect(); }
}, 180_000);
+ afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+ test('PGLite: jobs work drains the queue in the foreground and exits; no consumer is left behind', () => {
+ expect(run!.code, run!.text).toBe(0);
+ expect(run!.text).toContain('drained');
+ expect(run!.rows).toEqual([]);
+ });
return;
}
diff --git a/test/pathological/s-7003-autopilot-heartbeat.test.ts b/test/pathological/s-7003-autopilot-heartbeat.test.ts
index e9f8d06c8a..49e15b9840 100644
--- a/test/pathological/s-7003-autopilot-heartbeat.test.ts
+++ b/test/pathological/s-7003-autopilot-heartbeat.test.ts
@@ -11,7 +11,7 @@
* Fails when: --status ignores the daemon's schedule, trusts a foreign or outdated sidecar, or the daemon writes none.
* Real daemon processes for the write side (PGLite inline; Postgres dispatch with --no-worker).
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { tmpdir } from 'node:os';
@@ -79,43 +79,49 @@ function cliEnv(home: string): Record<string, string> {
}
for (const { backend, databaseUrl } of pathologicalArms()) {
- test('#7003 a running daemon writes its next tick and --status --json grades from it (' + backend + ')', async () => {
- const db = databaseUrl ? await isolatedPersistencePostgres(databaseUrl) : null;
- const { home, repo } = daemonHome(db ? { engine: 'postgres', database_url: db.databaseUrl } : { engine: 'pglite', database_path: '' });
- const dbPath = join(home, '.gbrain', 'brain.pglite');
- if (!db) {
+ describe('#7003 the daemon side (' + backend + ')', () => {
+ let db: Awaited<ReturnType<typeof isolatedPersistencePostgres>> | null = null;
+ let home = '';
+ let repo = '';
+ beforeAll(async () => {
+ db = databaseUrl ? await isolatedPersistencePostgres(databaseUrl) : null;
+ ({ home, repo } = daemonHome(db ? { engine: 'postgres', database_url: db.databaseUrl } : { engine: 'pglite', database_path: '' }));
+ if (db) return;
+ const dbPath = join(home, '.gbrain', 'brain.pglite');
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath, embedding_disabled: true, self_upgrade: { mode: 'off' } }));
const engine = new PGLiteEngine();
await engine.connect({ database_path: dbPath });
await engine.initSchema();
await engine.disconnect();
- }
- const sidecarPath = join(home, '.gbrain', 'autopilot.heartbeat.json');
- const args = ['autopilot', '--repo', repo, '--interval', '1500', ...(db ? ['--no-worker'] : ['--inline'])];
- const daemon = Bun.spawn({ cmd: [process.execPath, '--no-env-file', CLI, ...args], env: cliEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
- let output = '';
- const drain = async (s: ReadableStream<Uint8Array>) => { for await (const c of s) output += new TextDecoder().decode(c); };
- const drained = Promise.all([drain(daemon.stdout), drain(daemon.stderr)]);
- try {
- let sidecar: { pid: number; phase: string; next_tick_at: string | null; base_interval_s: number } | null = null;
- for (let i = 0; i < 2_400 && daemon.exitCode === null; i++) {
- if (existsSync(sidecarPath)) { sidecar = JSON.parse(readFileSync(sidecarPath, 'utf8')); if (sidecar?.phase === 'sleep') break; }
- await Bun.sleep(50);
+ }, 120_000);
+ afterAll(async () => { await db?.close(); if (home) rmSync(home, { recursive: true, force: true }); });
+
+ test('#7003 a running daemon writes its next tick and --status --json grades from it (' + backend + ')', async () => {
+ const sidecarPath = join(home, '.gbrain', 'autopilot.heartbeat.json');
+ const args = ['autopilot', '--repo', repo, '--interval', '1500', ...(db ? ['--no-worker'] : ['--inline'])];
+ const daemon = Bun.spawn({ cmd: [process.execPath, '--no-env-file', CLI, ...args], env: cliEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ let output = '';
+ const drain = async (s: ReadableStream<Uint8Array>) => { for await (const c of s) output += new TextDecoder().decode(c); };
+ const drained = Promise.all([drain(daemon.stdout), drain(daemon.stderr)]);
+ try {
+ let sidecar: { pid: number; phase: string; next_tick_at: string | null; base_interval_s: number } | null = null;
+ for (let i = 0; i < 2_400 && daemon.exitCode === null; i++) {
+ if (existsSync(sidecarPath)) { sidecar = JSON.parse(readFileSync(sidecarPath, 'utf8')); if (sidecar?.phase === 'sleep') break; }
+ await Bun.sleep(50);
+ }
+ expect(sidecar?.phase, output.slice(-3000)).toBe('sleep');
+ expect(sidecar!.pid).toBe(daemon.pid);
+ expect(sidecar!.base_interval_s).toBe(1500);
+ const lockMtime = statSync(join(home, '.gbrain', 'autopilot.lock')).mtimeMs;
+ const status = Bun.spawnSync({ cmd: [process.execPath, '--no-env-file', CLI, 'autopilot', '--status', '--json'], env: cliEnv(home), stdout: 'pipe', stderr: 'pipe' });
+ const report = JSON.parse(status.stdout.toString().trim().split('\n').reverse().find(l => l.startsWith('{'))!);
+ expect({ source: report.stale_after_source, next: report.next_tick_at }).toEqual({ source: 'daemon', next: sidecar!.next_tick_at });
+ expect(report.stale_after_seconds).toBe(Math.ceil((Date.parse(sidecar!.next_tick_at!) - lockMtime) / 1000) + 1500);
+ } finally {
+ daemon.kill('SIGTERM');
+ const killer = setTimeout(() => daemon.kill('SIGKILL'), 45_000);
+ await daemon.exited; clearTimeout(killer); await drained;
}
- expect(sidecar?.phase, output.slice(-3000)).toBe('sleep');
- expect(sidecar!.pid).toBe(daemon.pid);
- expect(sidecar!.base_interval_s).toBe(1500);
- const lockMtime = statSync(join(home, '.gbrain', 'autopilot.lock')).mtimeMs;
- const status = Bun.spawnSync({ cmd: [process.execPath, '--no-env-file', CLI, 'autopilot', '--status', '--json'], env: cliEnv(home), stdout: 'pipe', stderr: 'pipe' });
- const report = JSON.parse(status.stdout.toString().trim().split('\n').reverse().find(l => l.startsWith('{'))!);
- expect({ source: report.stale_after_source, next: report.next_tick_at }).toEqual({ source: 'daemon', next: sidecar!.next_tick_at });
- expect(report.stale_after_seconds).toBe(Math.ceil((Date.parse(sidecar!.next_tick_at!) - lockMtime) / 1000) + 1500);
- } finally {
- daemon.kill('SIGTERM');
- const killer = setTimeout(() => daemon.kill('SIGKILL'), 45_000);
- await daemon.exited; clearTimeout(killer); await drained;
- await db?.close();
- rmSync(home, { recursive: true, force: true });
- }
- }, 240_000);
+ }, 240_000);
+ });
}
diff --git a/test/pathological/s-autopilot-head-dispatch.test.ts b/test/pathological/s-autopilot-head-dispatch.test.ts
index 4124dedaad..11d4223f59 100644
--- a/test/pathological/s-autopilot-head-dispatch.test.ts
+++ b/test/pathological/s-autopilot-head-dispatch.test.ts
@@ -124,7 +124,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
const deps = {
env: { GBRAIN_AUTOPILOT_HEAD_PROBE_MS: '3000' }, now: () => clock,
sleep: async (ms: number) => { clock += ms; },
- readHead: async (root: string) => { reads++; return (await import('../../src/commands/autopilot-dispatch.ts')).readCheckoutHead(root); },
+ readHead: async (root: string) => { reads++; return (await import('../../src/core/checkout-head.ts')).readCheckoutHead(root); },
};
const state = { stopping: false, freshnessHeads: new Map<string, string>() };
const off = await quietly(() => sleepWatchingHeads(r.engine, state, { sleepMs: 30_000, baseInterval: 300, jsonMode: true }, deps));
diff --git a/test/pathological/s-sync-queue-wake.test.ts b/test/pathological/s-sync-queue-wake.test.ts
index b78be9af49..9aa1a6362c 100644
--- a/test/pathological/s-sync-queue-wake.test.ts
+++ b/test/pathological/s-sync-queue-wake.test.ts
@@ -12,7 +12,7 @@
* on elapsed time. PGLite always, Postgres when DATABASE_URL is set (the E2E backend matrix also runs it through
* PgBouncer: GBRAIN_TEST_BACKEND=pgbouncer).
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../../src/core/engine.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
@@ -28,12 +28,6 @@ const until = async (what: string, check: () => boolean | Promise<boolean>) => {
throw new Error('timed out waiting for ' + what);
};
-async function withEngine(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {
- const engine: BrainEngine = databaseUrl ? new PostgresEngine() : new PGLiteEngine();
- await engine.connect(databaseUrl ? { database_url: databaseUrl, poolSize: 3 } : {});
- try { await engine.initSchema(); await run(engine); } finally { await engine.disconnect(); }
-}
-
async function withIdleWorker(engine: BrainEngine, run: (w: { worker: MinionWorker; queue: MinionQueue; queueName: string; ran: number[] }) => Promise<void>) {
const queueName = 'wake-' + randomUUID().slice(0, 8);
const queue = new MinionQueue(engine);
@@ -42,7 +36,7 @@ async function withIdleWorker(engine: BrainEngine, run: (w: { worker: MinionWork
worker.register('sync', async job => { ran.push(job.id); return { ok: true }; });
const running = worker.start();
try {
- await until('the worker to go idle', () => (worker as unknown as { idle?: boolean }).idle === true);
+ await until('the worker to go idle', () => (worker as unknown as { idleWaiter?: { idle: boolean } }).idleWaiter?.idle === true);
await run({ worker, queue, queueName, ran });
} finally { worker.stop(); await running; }
}
@@ -51,48 +45,53 @@ for (const { backend, databaseUrl } of pathologicalArms()) {
/** The E2E backend matrix's PgBouncer pass hands this arm a transaction-pooler URL (it must carry prepare=false). */
const pooled = databaseUrl !== undefined && resolvePrepare(databaseUrl) === false;
describe('sync-queue wake for the jobs worker (' + (pooled ? 'pgbouncer' : backend) + ')', () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ if (databaseUrl) { const pg = new PostgresEngine(); await pg.connect({ database_url: databaseUrl, poolSize: 3 }); engine = pg; }
+ else { engine = new PGLiteEngine(); await engine.connect({}); }
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine?.disconnect(); });
+
test('a sync job queued beside an idle worker ends its idle wait and runs (no 10-minute poll)', async () => {
- await withEngine(databaseUrl, engine => withIdleWorker(engine, async ({ worker, queue, queueName, ran }) => {
+ await withIdleWorker(engine, async ({ worker, queue, queueName, ran }) => {
const { startSyncQueueWake } = await import('../../src/core/minions/sync-queue-wake.ts');
const lines: string[] = [];
- const wake = await startSyncQueueWake(engine, worker, { queue: queueName, log: line => lines.push(line) });
+ const wake = await startSyncQueueWake(engine, worker.idleWaiter, { queue: queueName, log: line => lines.push(line) });
try {
- const expected = backend === 'pglite' ? { mode: 'off', reason: 'not_postgres' }
- : pooled ? { mode: 'poll', reason: 'transaction_pooler' } : { mode: 'listen', reason: 'direct_session' };
- expect({ mode: wake.mode, reason: wake.reason }).toEqual(expected);
+ const expected = backend === 'pglite' ? 'off/not_postgres' : pooled ? 'poll/transaction_pooler' : 'listen/direct_session';
+ expect(wake.mode + '/' + wake.reason).toBe(expected);
// PGLite has no resident worker to wake; its \`jobs work\` drains in the foreground. The primitive still works there.
const job = await queue.add('sync', { sourceId: 'acme-example', noPull: true }, { queue: queueName });
- if (backend === 'pglite') worker.wake('test');
+ if (backend === 'pglite') worker.idleWaiter.wake('test');
await until('the job to run', () => ran.includes(job.id));
- const ended = worker.idleWaits.filter(w => w.ended === 'wake').map(w => w.reason);
+ const ended = worker.idleWaiter.history.filter(w => w.ended === 'wake').map(w => w.reason);
expect(ended).toContain(backend === 'pglite' ? 'test' : pooled ? 'sync_queue_poll' : 'sync_queue_notify');
- expect(worker.idleWaits.every(w => w.ms === IDLE_POLL_MS)).toBe(true);
+ expect(worker.idleWaiter.history.every(w => w.ms === IDLE_POLL_MS)).toBe(true);
if (wake.mode !== 'off') expect(lines).toEqual(['[gbrain jobs] sync-queue wake: ' + (wake.mode === 'listen' ? 'listen (direct_session)' : 'poll every 1000 ms (transaction_pooler)')]);
} finally { await wake.stop(); }
- }));
+ });
}, 120_000);
test('a wake that lands while the loop is claiming skips the next idle wait instead of being lost', async () => {
- await withEngine(databaseUrl, engine => withIdleWorker(engine, async ({ worker }) => {
+ await withIdleWorker(engine, async ({ worker }) => {
// The next claim finds nothing, and a notification arrives while it runs (after its SELECT, before the wait).
const queue = (worker as unknown as { queue: { claim: (...args: unknown[]) => Promise<unknown> } }).queue;
const claim = queue.claim.bind(queue);
let claims = 0;
- queue.claim = async (...args: unknown[]) => { const found = await claim(...args); if (claims++ === 0) worker.wake('during_claim'); return found; };
- const before = worker.idleWaits.length;
- worker.wake('first');
- await until('two more claims', () => claims >= 2 && worker.idle);
- expect(worker.idleWaits.slice(before - 1).map(w => [w.ended, w.reason ?? null])).toEqual([['wake', 'first'], ['skipped', null], ['waiting', null]]);
- }));
+ queue.claim = async (...args: unknown[]) => { const found = await claim(...args); if (claims++ === 0) worker.idleWaiter.wake('during_claim'); return found; };
+ const before = worker.idleWaiter.history.length;
+ worker.idleWaiter.wake('first');
+ await until('two more claims', () => claims >= 2 && worker.idleWaiter.idle);
+ expect(worker.idleWaiter.history.slice(before - 1).map(w => [w.ended, w.reason ?? null])).toEqual([['wake', 'first'], ['skipped', null], ['waiting', null]]);
+ });
}, 120_000);
if (backend !== 'pglite') {
test('behind a transaction pooler the wake never LISTENs; on a direct session it LISTENs (detection from the connection, not the arm)', async () => {
const { chooseSyncQueueWake } = await import('../../src/core/minions/sync-queue-wake.ts');
- await withEngine(databaseUrl, async engine => {
- expect(chooseSyncQueueWake(engine, {}).mode).toBe(pooled ? 'poll' : 'listen');
- expect(chooseSyncQueueWake(engine, { GBRAIN_WORKER_SYNC_WAKE: '0' })).toEqual({ mode: 'off', reason: 'disabled' });
- });
+ expect(chooseSyncQueueWake(engine, {}).mode).toBe(pooled ? 'poll' : 'listen');
+ expect(chooseSyncQueueWake(engine, { GBRAIN_WORKER_SYNC_WAKE: '0' })).toEqual({ mode: 'off', reason: 'disabled' });
}, 60_000);
}
});