Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR3 lane 3c: local put/capture --file stream through the import reader; main.ts back under its ceiling

garrytanabf8269dae06
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 718196ed63..7bd5195d64 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3019 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 #6876: links --help paging example (limit/cursor/all; the paging lives in core/ops/link-paging.ts); +4 Wave B PR 3: put --file (flag validator, --file= parse, dispatch line; logic in cli/commands/append.ts runPutFile) and its help example
+src/cli/main.ts 3015 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 #6876: links --help paging example (limit/cursor/all; the paging lives in core/ops/link-paging.ts)
src/commands/autopilot.ts 1650 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
diff --git a/src/cli/commands/append.ts b/src/cli/commands/append.ts
index d75a248b94..482a7c3155 100644
--- a/src/cli/commands/append.ts
+++ b/src/cli/commands/append.ts
@@ -7,25 +7,31 @@
* `append` calls append_page with a generated request_id (`--request-id`
* replays one); text whose append_page request would not fit the smallest
* transport cap goes through an upload session with mode `append`.
- * `put --file` sends put_page while the page fits one request (the trusted
- * local CLI: the page ceiling; a thin client: the smallest transport cap) and
- * otherwise streams the file through an upload session, never holding it as
- * one string. Every call goes where any other CLI write goes: the remote
- * brain on a thin client, the resident owner when a serve holds the brain,
- * else this process's engine.
+ * `put --file` (and `capture --file`) send one request while the page fits
+ * it (the trusted local CLI: the page ceiling; a thin client: the smallest
+ * transport cap). A larger file on the trusted local CLI streams through the
+ * import's two-pass reader into this process's engine (spec 3.1); a thin
+ * client, a managed brain or one a serve holds takes it through an upload
+ * session. Neither holds the file as one string. Every other call goes where
+ * any CLI write goes: the remote brain on a thin client, the resident owner
+ * when a serve holds the brain, else this process's engine.
*/
import { createReadStream, readFileSync, statSync } from 'node:fs';
import { open } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
+import { resolve } from 'node:path';
import type { BrainEngine } from '../../core/engine.ts';
import type { CliDispatchContext } from '../command-table.ts';
import { loadConfig, isThinClient } from '../../core/config.ts';
import { getCliOptions } from '../../core/cli-options.ts';
import { currentCliWriteWait } from '../../core/persistence/write-wait.ts';
-import { maybeDelegateLocalOperation } from '../../core/persistence/local-client.ts';
import { RemoteMcpError } from '../../core/remote-mcp-error.ts';
import { OperationError, opError } from '../../core/ops/contract.ts';
import { PAGE_MAX_BYTES } from '../../core/page-size-policy.ts';
+import type { ImportResult } from '../../core/import-file.ts';
+import { FRONTMATTER_HEAD_MAX_BYTES } from '../../core/page-body/limits.ts';
+import { maybeDelegateLocalOperation, residentPersistenceConfig } from '../../core/persistence/local-client.ts';
+import { inspectLockHolder } from '../../core/pglite-lock.ts';
import { detectBinaryNullByte, detectBinarySignature } from '../../core/capture-content.ts';
import { readStdinPayload } from '../../core/stdin-read.ts';
import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';
@@ -279,41 +285,76 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
}
}
+/** `--file PATH` / `--file=PATH` taken out of put's argv (before a bare `--`), and the args left. */
+function takeFileArg(args: string[]): { path: string | undefined; rest: string[] } {
+ const rest = [...args];
+ for (let i = 0; i < rest.length && rest[i] !== '--'; i++) {
+ if (rest[i] === '--file') return { path: rest[i + 1]?.startsWith('--') ? undefined : rest[i + 1], rest: [...rest.slice(0, i), ...rest.slice(i + 2)] };
+ if (rest[i]!.startsWith('--file=')) return { path: rest[i]!.slice('--file='.length) || undefined, rest: [...rest.slice(0, i), ...rest.slice(i + 1)] };
+ }
+ return { path: undefined, rest };
+}
+
+/** Flags whose put_page semantics need the whole page as one request (or, for dry_run, write nothing). */
+const ONE_REQUEST_ONLY = ['allow_empty', 'allow_shrink', 'drop_timeline', 'dry_run'] as const;
+
/**
- * `gbrain put <slug> --file PATH`: `params` are put's parsed CLI params with
- * `file`. Returns false after filling `content` from the file when the page
- * fits one put_page request, so the ordinary put dispatch sends it; returns
- * true after uploading a larger file through an upload session and printing
- * the receipt with `format`.
+ * `gbrain put <slug> --file PATH` (main.ts runs it before parsing put's args).
+ * A page that fits one put_page request (the page ceiling locally, the
+ * smallest transport cap on a thin client) returns false with `args` now
+ * carrying `--content=<file>`, so the ordinary put dispatch sends it. A larger
+ * file returns true after writing: on the trusted local CLI it streams through
+ * the import's two-pass reader into this process's engine (spec 3.1), never
+ * held as one string, when the brain is unmanaged; a thin client, a managed
+ * brain (its coordinator admits a file only from the source root) or one a
+ * serve holds takes it through an upload session, still streamed in parts.
+ * Failures are rendered here, so true also means "done".
*/
-export async function runPutFile(params: Record<string, unknown>, opts: {
+export async function runPutFile(op: { name: string }, args: string[], opts: {
+ parse: (op: never, args: string[]) => Record<string, unknown>;
connect: () => Promise<BrainEngine>;
format: (op: string, result: unknown, params: Record<string, unknown>) => string;
}): Promise<boolean> {
- const path = String(params.file);
- delete params.file;
- let size: number;
- try { size = statSync(path).size; } catch (error) {
- throw usageError(`Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`, 'Pass --file a readable text file.');
- }
- const thin = isThinClient(loadConfig());
- if (size <= PAGE_MAX_BYTES) {
- const content = decodeTextInput(readFileSync(path), path);
- const fitsOneRequest = !thin || toolCallFrameBytes('put_page', { ...params, content }) <= DIRECT_FRAME_MAX_BYTES;
- if (fitsOneRequest) { params.content = content; return false; }
- }
- const json = params.json === true;
- const requestId = typeof params.request_id === 'string' ? params.request_id : randomUUID();
- const source = typeof params.source === 'string' ? params.source : typeof params.source_id === 'string' ? params.source_id : null;
- const caller = pageWriteCaller(opts.connect, source);
+ const { path, rest } = takeFileArg(args);
+ let params: Record<string, unknown> = {};
+ let caller: PageWriteCaller | undefined;
+ let engine: Promise<BrainEngine> | undefined;
+ const connect = () => engine ??= opts.connect();
try {
- const oneRequestOnly = ['allow_empty', 'allow_shrink', 'drop_timeline', 'force', 'dry_run'].filter(key => params[key] !== undefined && params[key] !== false);
- if (oneRequestOnly.length) {
- throw usageError(`${oneRequestOnly.map(key => `--${key.replace(/_/g, '-')}`).join(', ')} apply only to a page that fits one put_page request.`,
- `${path} is larger than one request, so it goes through an upload session, which replaces a page only with --expected-revision. Drop those flags.`);
+ if (!path) throw usageError('--file requires a value.', 'Pass --file a readable text file.');
+ params = opts.parse(op as never, rest);
+ let size: number;
+ try { size = statSync(path).size; } catch (error) {
+ throw usageError(`Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`, 'Pass --file a readable text file.');
+ }
+ const thin = isThinClient(loadConfig());
+ if (size <= PAGE_MAX_BYTES) {
+ const content = decodeTextInput(readFileSync(path), path);
+ if (!thin || toolCallFrameBytes('put_page', { ...params, content }) <= DIRECT_FRAME_MAX_BYTES) {
+ args.splice(0, args.length, `--content=${content}`, ...rest);
+ return false;
+ }
+ }
+ const flags = ONE_REQUEST_ONLY.filter(key => params[key] !== undefined && params[key] !== false);
+ if (flags.length) {
+ throw usageError(`${flags.map(key => `--${key.replace(/_/g, '-')}`).join(', ')} apply only to a page that fits one put_page request.`, `${path} is larger than one request. Drop those flags.`);
}
+ const source = typeof params.source === 'string' ? params.source : typeof params.source_id === 'string' ? params.source_id : null;
+ if (!thin) {
+ const streamed = await streamLocalPage(connect, path, String(params.slug), source, params);
+ if (streamed) {
+ const output = opts.format('put_page', streamed, params);
+ if (output) await writeStdoutFinal(output);
+ return true;
+ }
+ }
+ if (params.force === true && typeof params.expected_revision !== 'string') {
+ throw usageError('--force applies only to a page that fits one put_page request or streams locally.', `${path} goes through an upload session, which replaces a page only with --expected-revision. Pass the page's revision (gbrain get --json).`);
+ }
+ caller = pageWriteCaller(connect, source, { teardown: false });
const result = await uploadPageBody(caller.call, {
- slug: params.slug, mode: typeof params.expected_revision === 'string' ? 'replace' : 'create', request_id: requestId,
+ slug: params.slug, mode: typeof params.expected_revision === 'string' ? 'replace' : 'create',
+ request_id: typeof params.request_id === 'string' ? params.request_id : (params.request_id = randomUUID()),
...(typeof params.expected_revision === 'string' ? { expected_revision: params.expected_revision } : {}),
}, await fileUploadBody(path), {
transient: caller.transient,
@@ -322,13 +363,126 @@ export async function runPutFile(params: Record<string, unknown>, opts: {
const output = opts.format('put_page', result, params);
if (output) await writeStdoutFinal(output);
} catch (error) {
- await reportFailure(error, 'put', json, requestId);
+ await reportFailure(error, 'put', params.json === true, typeof params.request_id === 'string' ? params.request_id : undefined);
} finally {
- await caller.close();
+ await caller?.close();
+ if (engine) await finishCliTeardown({ engine: await engine, drainTimeoutMs: 1000 });
}
return true;
}
+/**
+ * A local file over the page ceiling written as page `slug` by the import's
+ * two-pass streamed reader (spec 3.1) in this process's engine, with put's
+ * revision precondition (`expected_revision` / `force` in `params`; a new
+ * page needs neither). `head` replaces the file's first `skip` bytes
+ * (capture's merged frontmatter). Returns null when this process cannot be the
+ * writer: a serve holds the PGLite brain, or the brain is managed (its
+ * coordinator takes a file outside the source root only through an upload
+ * session).
+ */
+async function streamLocalPage(connect: () => Promise<BrainEngine>, path: string, slug: string, source: string | null, params: Record<string, unknown>,
+ content: { head?: { skip: number; bytes: Uint8Array }; provenance?: { source_kind: string | null; source_uri: string | null; ingested_via: string | null } } = {}): Promise<ImportResult | null> {
+ const resident = residentPersistenceConfig(loadConfig());
+ if (resident?.engine === 'pglite' && resident.database_path && !resident.database_url) {
+ const holder = inspectLockHolder(resident.database_path);
+ if (holder.held && holder.pid !== process.pid) return null;
+ }
+ const engine = await connect();
+ const [{ readManagedMode }, { readPageBodyPolicy }, { slugifyPath }, { resolveSourceWithTier }, { assertPageRevision }, { engineMutationPrecondition, parseMutationPrecondition }, { importStreamedMarkdownFile }] = await Promise.all([
+ import('../../core/persistence/managed-mode.ts'), import('../../core/page-body/limits.ts'), import('../../core/sync.ts'), import('../../core/source-resolver.ts'),
+ import('../../core/page-state/types.ts'), import('../../core/persistence/preconditions.ts'), import('../../core/page-body/streamed-import.ts')]);
+ if (await readManagedMode(engine)) return null;
+ const policy = await readPageBodyPolicy(engine);
+ const stat = statSync(path);
+ if (!policy.segmented || stat.size > policy.maxBytes) {
+ throw opError('invalid_params', `File too large (${stat.size} bytes, max ${policy.segmented ? policy.maxBytes : PAGE_MAX_BYTES}).`,
+ `${path} is over the single-string page ceiling and ${policy.segmented ? 'over pages.max_bytes' : 'segmented page storage (pages.segmented_storage) is off'}, so nothing was written. Split the file into smaller pages.`);
+ }
+ const relativePath = `${slug}.md`;
+ if (!slug || slugifyPath(relativePath) !== slug) {
+ throw usageError(`'${slug}' is not a canonical page slug.`, `A page over the single-string ceiling is written under its canonical slug; use '${slugifyPath(relativePath)}'.`);
+ }
+ const { source_id: sourceId } = await resolveSourceWithTier(engine, source);
+ assertPageRevision(await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }), engineMutationPrecondition(parseMutationPrecondition(params)));
+ const result = await importStreamedMarkdownFile(engine, resolve(path), relativePath, { sourceId, inferFrontmatter: false, content }, stat, policy);
+ if (result.status === 'skipped' && result.error) {
+ throw opError(result.refusal?.code === 'invalid_frontmatter' ? 'invalid_frontmatter' : 'invalid_params', result.error,
+ `${path} was not written as ${slug}: fix what the message names (or split the file into smaller pages) and run the command again.`);
+ }
+ return result;
+}
+
+/**
+ * `computeContentHash(normalizeForHash(text))` of a UTF-8 file without holding
+ * it: the BOM and surrounding whitespace dropped, CRLF folded, NFKC applied per
+ * run of whole lines (a newline is a normalization boundary). Null when the
+ * normalized text is empty.
+ */
+export async function normalizedFileHash(path: string): Promise<string | null> {
+ const hasher = createHash('sha256');
+ const decoder = utf8();
+ let pending = '';
+ let started = false;
+ const take = (final: boolean) => {
+ pending = pending.replace(/\r\n/g, '\n');
+ if (!started) { pending = pending.replace(/^\s+/, ''); if (!pending) return; started = true; }
+ const end = pending.search(/\s*$/);
+ const cut = final ? end : pending.lastIndexOf('\n', end - 1) + 1;
+ if (cut > 0) hasher.update(pending.slice(0, cut).normalize('NFKC'));
+ pending = final ? '' : pending.slice(cut);
+ };
+ try {
+ for await (const chunk of createReadStream(path)) { pending += decoder.decode(chunk as Buffer, { stream: true }); take(false); }
+ pending += decoder.decode();
+ } catch (error) {
+ if (error instanceof TypeError) throw notUtf8(path);
+ throw error;
+ }
+ take(true);
+ return started ? hasher.digest('hex') : null;
+}
+
+/** A capture's receipt fields, for capture.ts printReceipt. */
+export interface StreamedCapture { slug: string; status?: string; chunks?: number; content_hash: string }
+
+/**
+ * `gbrain capture --file` over the page ceiling on the trusted local CLI:
+ * the capture op's slug (from the normalized content hash) and frontmatter
+ * merge are computed from a streamed hash and the file head, and the body
+ * streams through the import's reader (spec 3.1). Null when this process
+ * cannot be the writer (a serve holds the brain, or it is managed): the caller
+ * reads the file and takes the upload path.
+ */
+export async function streamLocalCapture(path: string, input: CaptureUploadInput & { request_id?: string }, connect: () => Promise<BrainEngine>): Promise<StreamedCapture | null> {
+ const handle = await open(path, 'r');
+ let head: Buffer;
+ try {
+ head = Buffer.alloc(Math.min(FRONTMATTER_HEAD_MAX_BYTES, (await handle.stat()).size));
+ head = head.subarray(0, (await handle.read(head, 0, head.length, 0)).bytesRead);
+ } finally { await handle.close(); }
+ assertTextHead(head.subarray(0, 8192), path);
+ const bom = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0;
+ const lineEnd = head.lastIndexOf(0x0a);
+ if (lineEnd < bom) throw opError('invalid_params', `${path} has no line break in its first ${FRONTMATTER_HEAD_MAX_BYTES} bytes.`, 'A capture this large is written by its head and its streamed body; add line breaks to the file and capture it again.');
+ let headText: string;
+ try { headText = utf8().decode(head.subarray(bom, lineEnd + 1)); } catch { throw notUtf8(path); }
+ if (/^---\r?\n/.test(headText) && !/\n---\r?\n/.test(headText)) {
+ throw opError('invalid_frontmatter', `${path}'s frontmatter does not close within its first ${FRONTMATTER_HEAD_MAX_BYTES} bytes.`, 'Close the frontmatter block with a --- line near the top of the file, then capture it again.');
+ }
+ const contentHash = await normalizedFileHash(path);
+ if (!contentHash) throw opError('invalid_params', 'Capture requires nonempty text.', `${path} is empty or whitespace, so nothing was captured.`);
+ const { explicitCaptureType, mergeCaptureFrontmatter, slugPrefixForType } = await import('../../core/capture-content.ts');
+ const type = explicitCaptureType(headText, input.type) ?? 'note';
+ const slug = input.slug?.toLowerCase() ?? `${slugPrefixForType(type)}/${new Date().toISOString().slice(0, 10)}-${contentHash.slice(0, 8)}`;
+ const merged = mergeCaptureFrontmatter(headText, { type, capturedVia: 'capture-cli',
+ ...Object.fromEntries((['who', 'what', 'where', 'kind', 'depth'] as const).filter(key => input[key] !== undefined).map(key => [key, input[key]])) });
+ const result = await streamLocalPage(connect, path, slug, input.source ?? null,
+ { ...(input.expected_revision ? { expected_revision: input.expected_revision } : {}), ...(input.force ? { force: true } : {}) },
+ { head: { skip: lineEnd + 1 - bom, bytes: Buffer.from(merged, 'utf8') }, provenance: { source_kind: null, source_uri: 'cli-file', ingested_via: null } });
+ return result && { slug: result.slug, status: result.status, chunks: result.chunks, content_hash: contentHash };
+}
+
/** The capture options an upload of a large capture honors (capture.ts RunOpts). */
export interface CaptureUploadInput {
slug?: string; type?: string; who?: string; what?: string; where?: string; kind?: string; depth?: string;
diff --git a/src/cli/main.ts b/src/cli/main.ts
index e87a0efa91..c412c58888 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -529,12 +529,11 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
// the routing seam below can decide local-vs-remote without paying a
- // PGLite migration replay on thin-client installs. The arg parser, image
- // transform, and required-param check are all engine-free; refactoring
- // them out of the engine try/catch is safe and unlocks routing.
+ // PGLite migration replay on thin-client installs. The arg parser, image transform and required-param
+ // check are engine-free, so they run outside the engine try/catch. Wave B: put --file runs first (cli/commands/append.ts).
+ if (op.name === 'put_page' && subArgs.some(a => /^--file(=|$)/.test(a)) && await (await import('./commands/append.ts')).runPutFile(op, subArgs, { parse: parseOpArgs, connect: () => connectEngine(), format: formatResult })) return;
const params = parseOpArgs(op, subArgs);
- if (op.name === 'put_page' && typeof params.file === 'string' && await (await import('./commands/append.ts')).runPutFile(params, { connect: () => connectEngine(), format: formatResult }).catch((e: unknown) => exitCliError(e, command))) return; // Wave B: content from the file, or an upload over one request
// #3513: stdin fill moved out of parseOpArgs so a non-TTY stdin with no
// piped input can't block the parse forever — the bounded read leaves the
// param unset on timeout and the required-param check below fails fast.
@@ -1061,7 +1060,6 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
params[key] = arg.slice(eq + 1) !== 'false';
continue;
}
- if (key === 'file' && op.name === 'put_page') { params.file = arg.slice(eq + 1); continue; }
const def = op.params[key];
if (def) {
const raw = arg.slice(eq + 1);
@@ -1307,7 +1305,7 @@ export function validateCommandFlags(command: string, subArgs: string[]): string
return findUnknownFlag(subArgs, new Set(legal));
}
const op = cliOps.get(command) ?? cliAliases.get(command);
- if (op) return findUnknownOpFlag(op, subArgs);
+ if (op) return findUnknownOpFlag(op, op.name === 'put_page' ? subArgs.filter((a, i) => !/^--file(=|$)/.test(a) && subArgs[i - 1] !== '--file') : subArgs); // put --file: cli/commands/append.ts
return null; // unknown command — the dispatcher's own error handles it
}
@@ -1368,7 +1366,6 @@ export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | n
const positive = rawKey.slice(3).replace(/-/g, '_');
if (op.params[positive]?.type === 'boolean') continue;
}
- if (rawKey === 'file' && op.name === 'put_page') { if (m[2] === undefined) i++; continue; } // Wave B: put --file (cli/commands/append.ts runPutFile), never a wire param
const key = rawKey.replace(/-/g, '_');
const paramDef = op.params[key];
if (paramDef) {
@@ -2932,7 +2929,6 @@ async function completeEngineStartup(engine: BrainEngine): Promise<void> {
/** CLI-only usage examples appended to `gbrain <command> --help`. */
const OP_HELP_EXAMPLES: Record<string, string[]> = {
- put_page: ['gbrain put notes/acme-example --file notes.md # from a file (one over a request uploads in parts); to add to a page: gbrain append'],
get_links: [
'gbrain links people/alice-example # resolved source (every federated source when unpinned)',
'gbrain links people/alice-example --source business # one source',
diff --git a/src/commands/capture.ts b/src/commands/capture.ts
index 4c73031942..c324adb75d 100644
--- a/src/commands/capture.ts
+++ b/src/commands/capture.ts
@@ -30,7 +30,7 @@
* - --json: structured response for agents.
*/
-import { readFileSync } from 'node:fs';
+import { readFileSync, statSync } from 'node:fs';
import { readStdinPayload } from '../core/stdin-read.ts';
import { resolve } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
@@ -59,6 +59,7 @@ import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
+import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
export { detectBinaryNullByte, normalizeForHash, mergeCaptureFrontmatter } from '../core/capture-content.ts';
@@ -324,6 +325,18 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opt
inputLabel = 'stdin';
} else if (parsed.filePath) {
inputLabel = parsed.filePath;
+ // Wave B: a trusted local file over the page ceiling streams (src/cli/commands/append.ts streamLocalCapture).
+ if (!isThinClient(cfg) && (statSync(parsed.filePath, { throwIfNoEntry: false })?.size ?? 0) > PAGE_MAX_BYTES) {
+ try {
+ const streamed = await (await import('../cli/commands/append.ts')).streamLocalCapture(parsed.filePath, parsed, async () => engine ??= await options.getEngine!());
+ if (streamed) return printReceipt({ ...streamed, written: false, source_kind: 'capture-cli', captured_at: new Date().toISOString() }, parsed.quiet ?? false, parsed.json ?? false);
+ } catch (error) {
+ if (await reportPersistenceCliError(error, parsed.json ?? false)) return;
+ console.error(`gbrain capture: ${error instanceof Error ? error.message : String(error)}`);
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ return setCliExitVerdict(1);
+ }
+ }
try {
// No encoding => returns Buffer; binary guard sees raw bytes.
rawBuffer = readFileSync(parsed.filePath);
@@ -404,7 +417,7 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opt
// Wave B: a file larger than one request goes through an upload session (src/cli/commands/append.ts).
const upload = parsed.filePath ? await import('../cli/commands/append.ts') : null;
if (upload?.captureNeedsUpload(params, isThinClient(cfg))) {
- result = await upload.uploadCapture(rawBody, parsed, requestId, async () => engine ?? await options.getEngine!());
+ result = await upload.uploadCapture(rawBody, parsed, requestId, async () => engine ??= await options.getEngine!());
} else if (isThinClient(cfg)) {
const raw = await callRemoteTool(cfg!, 'capture', params, { timeoutMs: getCliOptions().timeoutMs ?? 30_000, writeWaitMs: currentCliWriteWait().waitMs });
result = unpackToolResult<Record<string, unknown>>(raw);
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index 5af17f0101..e2f7ffd5c3 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -95,6 +95,13 @@ type StreamedImportOptions = {
forceRechunk?: boolean;
activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
firstCommitAt?: Date;
+ /**
+ * A page write of the file's content (`gbrain put|capture --file` on the trusted local CLI), not a file import: the
+ * file records no origin (no source_path or file source_uri), no other file's slug claim applies, the staging is a
+ * `put`, and `head` replaces the file's first `skip` bytes after its BOM (capture's merged frontmatter). The
+ * caller passes `<slug>.md` as the relative path.
+ */
+ content?: { head?: { skip: number; bytes: Uint8Array }; provenance?: { source_kind: string | null; source_uri: string | null; ingested_via: string | null } };
/**
* A managed import's preparation (import-prepare.ts): the file must hash to
* `sha256` (the admitted bytes), the page base is the caller's snapshot, and
@@ -303,8 +310,8 @@ export async function importStreamedMarkdownFile(engine: BrainEngine, filePath:
const size = opened.size;
const bomBytes = Buffer.alloc(3);
await file.read(bomBytes, 0, 3, 0);
- const bom = bomBytes[0] === 0xef && bomBytes[1] === 0xbb && bomBytes[2] === 0xbf ? 3 : 0;
- const prefix = opts.inferFrontmatter !== false ? await inferredPrefix(file, bom, size, relativePath) : new Uint8Array(0);
+ const bom = (bomBytes[0] === 0xef && bomBytes[1] === 0xbb && bomBytes[2] === 0xbf ? 3 : 0) + (opts.content?.head?.skip ?? 0);
+ const prefix = opts.content?.head ? opts.content.head.bytes : opts.inferFrontmatter !== false ? await inferredPrefix(file, bom, size, relativePath) : new Uint8Array(0);
if (!prefix) return hold(expectedSlug, size, 'frontmatter inference reads the first 20 lines, and they are not within the file head');
const hash = opts.coordinated ? createHash('sha256').update(bomBytes.subarray(0, bom)) : null;
const blocks = new BlockDigests();
@@ -363,7 +370,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
if (existing?.deleted_at) return hold(slug, size, 'restoring a deleted page rewrites its body through the inline writer');
if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);
const sourceRoot = resolve(input.filePath, ...relativePath.split(/[\\/]/).map(() => '..'));
- const collisionOwner = collidingSlugOwner(existing, slug, sourceRoot, relativePath);
+ const collisionOwner = opts.content ? null : collidingSlugOwner(existing, slug, sourceRoot, relativePath);
if (collisionOwner) {
process.stderr.write(`[import] slug collision: ${relativePath} and ${collisionOwner} both map to ${slug} in source ${sourceId}; keeping ${collisionOwner}. Rename one file to import both.\n`);
return { slug, status: 'skipped', chunks: 0, skip_reason: 'slug_collision' };
@@ -385,7 +392,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
if (opts.coordinated) owner = opts.coordinated.owner;
else {
const { principal } = await maintenanceAttribution(engine);
- owner = { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null };
+ owner = { kind: opts.content ? 'put' : 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null };
}
const live = existing ? await segmentedLivePage(engine, Number(existing.id)) : null;
let fenced = false;
@@ -418,18 +425,19 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
return opts.coordinated ? opts.coordinated.prepare({ slug, observedRevision: opts.coordinated.snapshot?.revision ?? null, noop: true, result: skipped, frontmatter: parsed.frontmatter,
validate: async () => {}, apply: async () => {} }) : skipped;
}
- const identity = opts.coordinated?.moved ? { kind: 'none' as const }
+ const identity = opts.coordinated?.moved || opts.content ? { kind: 'none' as const }
: await decideImportIdentity(engine, { sourceId, slug, hash, frontmatterId: null, sourcePath: relativePath, sourceRoot, body: { title: parsed.title, compiled_truth: '', timeline: '' } });
if (identity.kind === 'shared_hash') process.stderr.write(`[import] WARNING: ${relativePath} shares content_hash with ${identity.dupSlug} in source ${sourceId}. Indexing both.\n`);
const nowDate = new Date();
const { loadBrainTimeZone } = await import('../import-file.ts');
- const filename = basename(relativePath, '.md');
+ const filename = opts.content ? slug.split('/').pop() ?? slug : basename(relativePath, '.md');
const { date: effectiveDate, source: effectiveDateSource } = computeEffectiveDate({ slug, frontmatter: parsed.frontmatter, filename, timeZone: await loadBrainTimeZone(engine),
updatedAt: existing?.updated_at ?? nowDate,
createdAt: fallbackCreatedAt({ existing, fileTimes: { birthtime: input.stat.birthtime, mtime: input.stat.mtime, firstCommit: opts.firstCommitAt }, now: nowDate }) });
const meta = { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter as JsonObject, page_kind: 'markdown' as const,
- effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filename, source_path: relativePath,
- source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null };
+ effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filename,
+ ...(opts.content ? { source_path: null, source_kind: null, source_uri: null, ingested_via: null, ...opts.content.provenance }
+ : { source_path: relativePath, source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null }) };
const refs = prepared.body.body_flags.has_protected ? [] : [...codeRefs.refs.values()];
const apply = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
if (existing) await tx.createVersion(slug, preimage ? { sourceId, preimage } : { sourceId });
diff --git a/test/cli-page-writes.test.ts b/test/cli-page-writes.test.ts
index 81bf6d4799..13eb51c48b 100644
--- a/test/cli-page-writes.test.ts
+++ b/test/cli-page-writes.test.ts
@@ -1,26 +1,42 @@
/**
- * Wave B write operations from the local CLI (spec 6.1, 6.2, 6.5):
- * `gbrain put <slug> --file` reads the page from a file (no stdin), and over
- * one request uploads it in parts; `gbrain append` adds text with
- * append_page, idempotent by --request-id, through an upload session when the
- * text is over one request. Runs the real CLI on PGLite and on Postgres.
+ * Wave B write operations from the local CLI (spec 3.1, 6.1, 6.2, 6.5):
+ * `gbrain put <slug> --file` and `gbrain capture --file` read the page from a
+ * file (no stdin); over the page ceiling the trusted local CLI streams it
+ * through the import's two-pass reader, with no upload session.
+ * `gbrain append` adds text with append_page, idempotent by --request-id,
+ * through an upload session when the text is over one request. Runs the real
+ * CLI on PGLite and on Postgres.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
+import { normalizeForHash } from '../src/core/capture-content.ts';
const CLI = join(import.meta.dir, '../src/cli.ts');
/** Quotes, backslashes, tabs and other control characters, multi-byte and astral text. */
const ESCAPE_HEAVY = 'said "hi" \\ path\\to\\x \t tab \u0007 bell é 中文 😀 🧠';
+const sha = (text: string) => createHash('sha256').update(text).digest('hex');
+/** The body `gbrain get` prints after the page's frontmatter block. */
+const printedBody = (stdout: string) => stdout.slice(stdout.indexOf('\n---\n\n') + 6);
+/** A page just over the single-string ceiling. */
+const hugeBody = (title: string) => {
+ const line = `- ${ESCAPE_HEAVY} row\n`;
+ return `# ${title}\n\n` + line.repeat(Math.ceil((PAGE_MAX_BYTES + 1024 * 1024) / Buffer.byteLength(line)));
+};
for (const backend of testBackends()) {
describe(`CLI page writes (${backend})`, () => {
let home: string;
let close: (() => Promise<void>) | undefined;
+ let pg: BrainEngine | undefined;
+ let pglite: PGLiteEngine | undefined;
async function cli(args: string[], stdin?: string) {
const child = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], {
@@ -35,19 +51,30 @@ for (const backend of testBackends()) {
expect(read.code, read.stderr).toBe(0);
return JSON.parse(read.stdout);
}
+ /** Reads the brain directly between CLI runs (the PGLite lock is free once the CLI exits). */
+ async function sql<T>(text: string, params: unknown[] = []): Promise<T[]> {
+ if (pg) return pg.executeRaw<T>(text, params);
+ const { database_path } = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));
+ await pglite!.connect({ database_path });
+ try { return await pglite!.executeRaw<T>(text, params); } finally { await pglite!.disconnect(); }
+ }
+ const uploads = async () => (await sql<{ n: number }>("SELECT count(*)::int AS n FROM page_body_stagings WHERE kind = 'upload'"))[0]!.n;
+ const stored = async (slug: string) => (await sql<{ body_storage: string; source_path: string | null; source_uri: string | null; knowledge_revision: string }>(
+ 'SELECT body_storage, source_path, source_uri, knowledge_revision FROM pages WHERE slug = $1', [slug]))[0]!;
const file = (name: string, content: string | Buffer) => { const path = join(home, name); writeFileSync(path, content); return path; };
beforeAll(async () => {
home = mkdtempSync(join(tmpdir(), `gbrain-cli-page-writes-${backend}-`));
if (backend === 'postgres') {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
- close = pg.close;
- const [database] = await pg.engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ close = isolated.close;
+ pg = isolated.engine;
+ const [database] = await pg.executeRaw<{ name: string }>('SELECT current_database() AS name');
const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${database.name}`;
- await pg.engine.disconnect();
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url.toString(), embedding_disabled: true }));
} else {
+ pglite = new PGLiteEngine();
const init = await cli(['init', '--pglite', '--no-embedding']);
expect(init.code, init.stderr).toBe(0);
}
@@ -113,15 +140,56 @@ for (const backend of testBackends()) {
expect((await page('notes/big-append')).compiled_truth).toBe(`# Big append\n\nstart\n${text}`.trimEnd());
}, 300_000);
- test('put --file over the page ceiling streams through an upload session', async () => {
- const line = `- ${ESCAPE_HEAVY} row\n`;
- const body = '# Huge\n\n' + line.repeat(Math.ceil((25 * 1024 * 1024) / Buffer.byteLength(line)));
- const path = file('huge.md', body);
- const put = await cli(['put', 'notes/huge', '--file', path]);
+ test('local put --file over the page ceiling on a managed brain goes through an upload session, byte-identical', async () => {
+ expect((await sql<{ enabled: boolean }>('SELECT enabled FROM persistence_brain'))[0]!.enabled).toBe(true);
+ const body = hugeBody('Managed huge');
+ const put = await cli(['put', 'notes/managed-huge', '--file', file('managed-huge.md', body)]);
+ expect(put.code, put.stderr).toBe(0);
+ expect(await stored('notes/managed-huge')).toMatchObject({ body_storage: 'segmented' });
+ expect(await uploads()).toBeGreaterThan(0);
+ expect(sha(printedBody((await cli(['get', 'notes/managed-huge'])).stdout))).toBe(sha(body));
+ }, 600_000);
+
+ test('local put --file over the page ceiling on an unmanaged brain streams in segmented and byte-identical, with no upload session', async () => {
+ await sql('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const before = await uploads();
+ const body = hugeBody('Huge');
+ const put = await cli(['put', 'notes/huge', '--file', file('huge.md', body)]);
expect(put.code, put.stderr).toBe(0);
+ expect(await stored('notes/huge')).toMatchObject({ body_storage: 'segmented', source_path: null, source_uri: null });
+ expect(await uploads()).toBe(before);
const read = await cli(['get', 'notes/huge']);
expect(read.code, read.stderr).toBe(0);
- expect(createHash('sha256').update(read.stdout).digest('hex')).toBe(createHash('sha256').update(body).digest('hex'));
+ expect(sha(printedBody(read.stdout))).toBe(sha(body));
+ const replacement = file('huge-2.md', hugeBody('Huge v2'));
+ const unconditional = await cli(['put', 'notes/huge', '--file', replacement]);
+ expect(unconditional.code).not.toBe(0);
+ expect(unconditional.stderr).toContain('revision');
+ const replaced = await cli(['put', 'notes/huge', '--file', replacement, '--expected-revision', (await stored('notes/huge')).knowledge_revision]);
+ expect(replaced.code, replaced.stderr).toBe(0);
+ expect(sha(printedBody((await cli(['get', 'notes/huge'])).stdout))).toBe(sha(hugeBody('Huge v2')));
+ expect(await uploads()).toBe(before);
+ }, 600_000);
+
+ test('local capture --file over the page ceiling on an unmanaged brain streams in under the capture slug and frontmatter once the write gate allows it, with no upload session', async () => {
+ const before = await uploads();
+ const raw = hugeBody('Captured');
+ const path = file('captured.md', raw);
+ const gated = await cli(['capture', '--file', path]);
+ expect(gated.code).toBe(1);
+ expect(gated.stderr).toContain('the write gate scans the whole body of a agent_written page');
+ expect((await cli(['config', 'set', 'write_gate.agent_mode', 'off'])).code).toBe(0);
+ const capture = await cli(['capture', '--file', path, '--json']);
+ expect(capture.code, capture.stderr).toBe(0);
+ const receipt = JSON.parse(capture.stdout);
+ const hash = sha(normalizeForHash(raw));
+ expect(receipt).toMatchObject({ content_hash: hash, source_kind: 'capture-cli', slug: `inbox/${new Date().toISOString().slice(0, 10)}-${hash.slice(0, 8)}` });
+ expect(await stored(receipt.slug)).toMatchObject({ body_storage: 'segmented', source_path: null, source_uri: 'cli-file' });
+ expect(await uploads()).toBe(before);
+ const read = await cli(['get', receipt.slug]);
+ expect(read.code, read.stderr).toBe(0);
+ expect(read.stdout).toContain('captured_via: capture-cli');
+ expect(sha(printedBody(read.stdout))).toBe(sha(raw));
}, 600_000);
});
}
diff --git a/test/normalized-file-hash.test.ts b/test/normalized-file-hash.test.ts
new file mode 100644
index 0000000000..946e60676b
--- /dev/null
+++ b/test/normalized-file-hash.test.ts
@@ -0,0 +1,47 @@
+/**
+ * capture --file over the page ceiling derives the capture slug from a streamed
+ * hash (src/cli/commands/append.ts normalizedFileHash); it must equal
+ * computeContentHash(normalizeForHash(text)) of the whole file, including
+ * across the stream's 64 KiB read boundaries.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { normalizedFileHash } from '../src/cli/commands/append.ts';
+import { normalizeForHash } from '../src/core/capture-content.ts';
+import { computeContentHash } from '../src/core/ingestion/types.ts';
+
+const READ = 64 * 1024;
+/** Text whose byte READ - 1 is `first`'s last byte, so `second` starts the next read. */
+const straddle = (first: string, second: string) => 'x'.repeat(READ - Buffer.byteLength(first)) + first + second;
+
+describe('normalizedFileHash', () => {
+ let dir: string;
+ beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'gbrain-normalized-hash-')); });
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+ const cases: Array<[string, string]> = [
+ ['plain text', '# Title\n\nbody line\n'],
+ ['BOM, surrounding whitespace and CRLF', '\uFEFF \r\n\t# Title\r\nline one\r\nline two\r\n\r\n \n'],
+ ['a CRLF split across reads', straddle('line\r', '\nnext line\n')],
+ ['a combining mark split across reads', straddle('cafe\n', '\u0301 and e\u0301 more\n')],
+ ['a combining mark split across reads mid-line', straddle('cafe', '\u0301 more\n')],
+ ['NFKC compatibility characters', 'file ① Full\nwidth\n'],
+ ['trailing whitespace across reads', straddle('end', ' '.repeat(10) + '\n\n')],
+ ['a whitespace run between text across reads', straddle('a ', ' b\n')],
+ ];
+ for (const [name, text] of cases) {
+ test(name, async () => {
+ const path = join(dir, `${name.replace(/\W+/g, '-')}.md`);
+ writeFileSync(path, text);
+ expect(await normalizedFileHash(path)).toBe(computeContentHash(normalizeForHash(text)));
+ });
+ }
+
+ test('whitespace only is null', async () => {
+ const path = join(dir, 'blank.md');
+ writeFileSync(path, '\uFEFF \r\n\t\n' + ' '.repeat(READ));
+ expect(await normalizedFileHash(path)).toBeNull();
+ });
+});