Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Commit pages written into a symlinked or .git-linked source folder at their real place, and say why any path is left out (GST-2767) (#9413)

Garry Tan76c621e36533
diff --git a/behavior-changes.d/commit_push_symlinked_source_gst2767.md b/behavior-changes.d/commit_push_symlinked_source_gst2767.md
new file mode 100644
index 0000000000..a7c7a11e0f
--- /dev/null
+++ b/behavior-changes.d/commit_push_symlinked_source_gst2767.md
@@ -0,0 +1 @@
+gbrain git commit-push now resolves a named path through any symlinked folder to its real place in the checkout, so a path spelled through a source path that links into the repository is committed instead of refused as outside the checkout, and a leftover .git folder or file that git itself ignores no longer makes a folder count as skipped. Each skipped path carries why next to reason in the JSON detail, and the push log gets a [push] SKIPPED, NEEDS ATTENTION line for it. gbrain embed <slug> refuses a flag it does not take with unknown_flag (exit 2) before asking for spend approval, instead of reading the next argument as a page. gbrain sources writer git-durability --enable returns agents.commit_argv, the exact gbrain git commit-push command, whenever the durability file it owns is not committed, including an untracked copy an earlier run left. A named folder whose tracked files are staged for removal while still on disk is refused as staged_for_removal, naming --untrack and git restore --staged, instead of as commit_prestaged_paths, and --dry-run reports the same skipped paths and reasons the real run would. A source folder whose .git links to the repository's own .git now commits at its real place in the repository instead of in a copy at the top. gbrain sync no longer creates a repository in a brain folder that sits inside another repository it cannot read.
diff --git a/changelog.d/gst-2767-commit-push-symlink-subdir.md b/changelog.d/gst-2767-commit-push-symlink-subdir.md
new file mode 100644
index 0000000000..dfbc6a544a
--- /dev/null
+++ b/changelog.d/gst-2767-commit-push-symlink-subdir.md
@@ -0,0 +1,19 @@
+---
+important: data-loss
+---
+**`gbrain git commit-push` now commits pages named through a symlinked source path, says why for each path it leaves out, `gbrain embed` stops reading a source id as a page, and `sources writer git-durability --enable` names the exact command to commit the AGENTS.md it writes.**
+
+<!-- behavior-change: commit_push_symlinked_source_gst2767 -->
+
+**Who is affected:** anyone with a scheduled writer (a cron job, hook or agent that runs `gbrain git commit-push`) whose source path is a link into a Git repository, or whose source folder contains a `.git` entry of its own: a leftover folder or file, or a link to the repository's `.git`. Those writes were refused or reported as skipped, so the pages stayed on disk and never reached Git or the remote. After upgrading, run the writer once and check `git status` in the repository: anything it left uncommitted before is committed on that run.
+
+### Fixed
+- A source whose path is a symlink to a folder inside its Git repository (for example a source at `~/source-a` pointing to `repo-a/brain`) can be committed with paths spelled through the link: `gbrain git commit-push --path ~/source-a -- ~/source-a/notes/daily/2026` commits the new and modified files in that folder. Before, a path spelled through the link was refused as outside the checkout, or failed with "beyond a symbolic link" when the link sat inside the repository, so scheduled writes stayed out of Git. A named file that is itself a symlink is still committed as the link.
+- A source folder whose `.git` is a link to its repository's own `.git` (for example `repo-a/brain/.git -> ../.git`) is committed at its real place in the repository. Before, a commit-push run with `--path` pointing at that folder wrote the pages into a copy of the folder at the top of the repository, pushed that, and reported success, while the real files stayed uncommitted; run from the repository root, the same folder was reported as a nested repository and skipped. If a source of yours has such a link, check the repository for a stray top-level copy of the folder after upgrading.
+- An empty or broken `.git` folder, or a `.git` file pointing at a repository that no longer exists, left under a source path no longer makes commit-push report `commit_paths_skipped` or "not inside a git checkout" for a folder its repository already tracks. Only a folder that Git treats as its own repository counts as nested, and that one is still refused with its reason.
+- A folder whose tracked files are staged for removal (as after `git rm --cached`) while the files are still on disk is still refused, and nothing is added back or removed, but the refusal now names that cause as `staged_for_removal` and both ways out: `gbrain git commit-push --untrack` to stop tracking the files, or `git restore --staged` to keep them tracked. It used to be refused as files "already staged by another writer". The "staged for removal" explanation no longer appears for a folder that was skipped for any other reason; before, every skipped folder got it, which pointed people at the wrong fix.
+- `gbrain git commit-push --dry-run` now runs the same skipped-path check as the real run and fails with the same paths and reasons, so a dry run no longer reports success for a run that will fail.
+- Each path commit-push leaves out now says why, in the message and in the JSON detail (`skipped[].why`, next to `reason`), and the push log gets one `[push] SKIPPED, NEEDS ATTENTION` line naming every skipped path and its reason. A wrapper that keeps only the error code still leaves the reason in the log.
+- `gbrain embed --status --source <id>` no longer fails with "Page not found: <id>". Embed has no `--status` flag, so a single-page run now refuses any flag it doesn't take with `unknown_flag` (exit 2) before it asks for spend approval, and names `gbrain embed --stale --dry-run --json` as the free way to read embedding coverage. The page slug is now the first argument that isn't a flag or a flag's value, so `--source`, `--batch-size`, `--priority`, `--max-usd` and `--pace-max-concurrency` values are never read as the slug.
+- `gbrain sources writer git-durability <source> --enable` still commits nothing itself, but whenever the AGENTS.md (or RESOLVER.md) it owns is not committed it now returns the exact `gbrain git commit-push` command as `agents.commit_argv`, with a real commit message. That includes a copy an earlier version left untracked while the block is already current, which used to get no hint at all and stayed untracked.
+- When `gbrain sync` finds no readable repository for a brain folder and creates one, it now refuses instead if a folder above it (through any link) already holds a `.git`, so an unreadable outer repository (for example one Git refuses for its ownership) never gets a second repository nested inside it.
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
index 4408cbf358..bd73fa4d65 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -217,7 +217,7 @@ Follow the error's `fix.next` as the
| `commit_lock_busy` | 1 | Another writer held the lock for the whole wait; nothing was committed. Retry once. If it is still busy, tell the user which checkout and lock path the message names and stop. |
| <a id="checkout_not_a_source"></a>`checkout_not_a_source` | 1 | The checkout commit-push resolved from the working directory (no `--path`) is not one of the brain's source checkouts on this host, typically a wrapper that changed into another repository; nothing was staged. The message lists the brain's checkouts. Tell the user to make the script pass `--path` with the absolute brain checkout. A repository that only encloses a source checkout (a brain cloned inside another repository) is not one; a source registered at a subdirectory its checkout tracks is. A host whose brain records no source checkout, or a checkout with `gbrain.sourceRoot` set, is never refused this way. |
| `commit_paths_invalid` | 1 | No paths, a path outside the checkout, the checkout root itself, or a path git would not stage (one outside a sparse-checkout definition included). Name the explicit files you wrote and rerun. |
-| <a id="commit_paths_skipped"></a>`commit_paths_skipped` | 1 | Git left a named path out of the commit: a modified file flagged assume-unchanged or skip-worktree (`reason` `assume_unchanged`, `skip_worktree`) or a file inside a nested Git repository (`not_staged`). The other named paths were committed (and, on a classic checkout, pushed); `detail` lists each skipped path, the commit and the pushed head, or the push failure (`publish`) when the push failed too. Check the flags with `git ls-files -v -- <path>`; clear them only after the user agrees, one flag per call (`git update-index --no-assume-unchanged -- <path>`, `git update-index --no-skip-worktree -- <path>`; given both, git clears only the first), and remember skip-worktree is often set on purpose to keep local edits out of commits, or move the file out of the nested repository, then rerun. A skip-worktree file absent from disk (a sparse checkout), a flagged gitlink and ignored files under a named directory are not reported. |
+| <a id="commit_paths_skipped"></a>`commit_paths_skipped` | 1 | Git left a named path out of the commit: a modified file flagged assume-unchanged or skip-worktree (`reason` `assume_unchanged`, `skip_worktree`) a file inside a nested Git repository (`not_staged`), or, under a named folder, a tracked file the index holds as staged for removal while it is still on disk, as after `git rm --cached` (`staged_for_removal`; nothing is committed, and the refusal names both ways out: `gbrain git commit-push --untrack` to stop tracking it, `git restore --staged` to keep it tracked). The other named paths were committed (and, on a classic checkout, pushed); `detail` lists each skipped path with its `reason` and a plain `why` (for example "it sits inside the nested Git repository brain/imports"), the commit and the pushed head, or the push failure (`publish`) when the push failed too; the push log gets one `[push] SKIPPED, NEEDS ATTENTION` line with the same reasons. `--dry-run` runs the same check and reports the same paths and reasons, without writing the push log. An empty or broken `.git` folder, a `.git` file pointing at a repository that no longer exists, or a `.git` link to the repository's own `.git`, is not a nested repository: Git commits the files under it, and so does commit-push. A path spelled through a symlinked folder (a source path that links into the repository) names the file at its real place in the checkout. Check the flags with `git ls-files -v -- <path>`; clear them only after the user agrees, one flag per call (`git update-index --no-assume-unchanged -- <path>`, `git update-index --no-skip-worktree -- <path>`; given both, git clears only the first), and remember skip-worktree is often set on purpose to keep local edits out of commits, or move the file out of the nested repository, then rerun. A skip-worktree file absent from disk (a sparse checkout), a flagged gitlink and ignored files under a named directory are not reported. |
| `commit_prestaged_paths` | 1 | Another writer staged files under a directory you named; nothing was staged or committed. Name your own files explicitly. Unstage the others (`git restore --staged -- <file>`, which keeps their bytes) only after the user agrees. |
| `commit_outside_source_root` | 1 | The commit, or a local commit about to be published, changes files outside the brain's [source root](#source-roots); nothing was pushed. Show the user `git show --stat <sha>`; rerun with `--allow-outside-source-root` only if they want it published. |
| `git_index_locked` | 1 | A git command that does not take the writer lock held `index.lock`. Retry once after a few seconds. |
diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index 72e58ff27a..afd4a347a4 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -449,10 +449,11 @@ src/core/git/commit-ledger.ts spawn_import 1 W7: process-wide effects move to sr
src/core/git/commit-push.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/git/commit-push.ts module_collection 1 W6: per-engine state, or mark as a constant table
src/core/git/commit-push.ts process_env 6 W6: settings plane out of the core
-src/core/git/commit-push.ts spawn_import 1 W7: process-wide effects move to src/cli
+src/core/git/git-run.ts spawn_import 1 W7: process-wide effects move to src/cli; GST-2767 moved commit-push's git runner here unchanged
src/core/git/range-secret-scan.ts fs_import 1 W7: filesystem boundary moves to the local app (the publish scan streams git output through a private temp file)
src/core/git/range-secret-scan.ts spawn_import 1 W7: process-wide effects move to src/cli (the publish scan runs git plumbing)
src/core/git/reconcile.ts process_env 2 W6: settings plane out of the core; the commit-push child inherits this process environment (GBRAIN_HOME, Git credentials) and resolves its CLI from it, like refresh's publish child
+src/core/git/skipped-paths.ts fs_import 1 W7: filesystem boundary moves to the local app; GST-2767 moved commit-push's skipped-path checks here unchanged
src/core/git/upstream-history.ts fs_import 1 W7: filesystem boundary moves to the local app; reads the tail of the checkout reflog to tell a rewritten upstream from a fast-forward (lifted out of worktree-refresh.ts)
src/core/github-app-token.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/github-source.ts fs_import 2 W7: filesystem boundary moves to the local app
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2c6d0c8134..e13bca3ed1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -50,7 +50,7 @@ src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut re
src/commands/config.ts 1546 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts); +8 train C: #8921 #7346 nested credential redaction on top of master's config growth; +1 train C: #9145 config.ts edit on top of #8921 #7346; +7 #8920: plural, acronym and credential secret words with the count-word exception (isSensitiveConfigKey) and URL userinfo masking (redactConfigValue)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
src/core/behavior-change-notice.ts 1774 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +2 GST-2407: context_pack scope read and attestRead over the owner route; +9 releases per batch: the generated-table import, the releasedIn helper and its comment, the spread of RELEASED_BEHAVIOR_CHANGES; new rows now live in behavior-changes.d/ and stop growing this file (re-summed at the master v0.60.704.0 merge: 1763 + 9 = 1772 measured); +2 #7646 (GBRA-404 salvage): the disclosure lists releases oldest first whatever the table order
-src/core/git/commit-push.ts 1706 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal)
+src/core/git/commit-push.ts 1614 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal); GST-2767: the git runner (git-run.ts) and the skipped-path checks with their reasons (skipped-paths.ts) moved out, 1600; +14 GST-2767 staged_for_removal refusal and dry-run skipped-path parity
src/commands/auth.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move; re-measured at the Train A merge onto master v0.60.708.0: 1503 + 2 (the #8930 shared-token notice) = 1505; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1505 -> 1509, both sides' growth; +3 Wakeshift PR 2 (#8709), one line each: revoke (by name) calls forgetWakePrincipal for every token row its UPDATE returned (RETURNING 1 became RETURNING id, so no line added there), revokeById calls it for the revoked token id, and revokeClient calls it for the revoked OAuth client id; each call ends that principal's open watches and queues its Wakeshift forget (logic in core/wakeshift/forget.ts) after the command's own UPDATE/DELETE; master 1509 + 3 = 1512
src/core/markdown.ts 1501 ratchet new row: crossed the 1500 unlisted cap at the train C merge: #8921 #7052 tag_too_long hold (tagLengthHold import; the limit lives in core/tag-limit.ts) on top of master's 1500
src/mcp/dispatch.ts 1502 ratchet new row: crossed the 1500 unlisted cap with GBRA-504 guest notes (+4): the guest attribution option threaded into dispatch (parsing and checks live in core/guests/admission.ts); next growth should peel the response-cap block into a sibling module
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts
index 8a89b4f167..619e2a471c 100644
--- a/src/cli/commands/embed.ts
+++ b/src/cli/commands/embed.ts
@@ -17,6 +17,10 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
return;
}
const { SELECTED_CONFIG_BY_ENGINE } = ctx;
+ // GST-2767: a single-page run's arguments are read before consent, so an unknown flag is refused before any spend prompt.
+ if (!args.some(a => ['--all', '--stale', '--slugs', '--held', '--facts', '--images'].includes(a))) {
+ (await import('../../commands/embed-slug-args.ts')).embedSlugTarget(args);
+ }
// A4: an explicit backfill is paid work; consent first, on the probe-only engine (startup: 'observational').
const consent = await authorizeEmbed(engine, args);
if (!consent) return;
diff --git a/src/commands/embed-slug-args.ts b/src/commands/embed-slug-args.ts
new file mode 100644
index 0000000000..91efce6c34
--- /dev/null
+++ b/src/commands/embed-slug-args.ts
@@ -0,0 +1,36 @@
+import { opError } from '../core/ops/contract.ts';
+
+/** The flags a single-page run (`gbrain embed <slug>`) reads; the value flags take the next argument. */
+const SLUG_VALUE_FLAGS = new Set(['--source', '--batch-size', '--priority', '--max-usd', '--max-cost', '--pace-max-concurrency']);
+const SLUG_BOOLEAN_FLAGS = new Set(['--dry-run', '--catch-up', '--yes', '--json', '--background', '--follow', '--pace', '--include-null-signature', '--non-interactive']);
+
+/**
+ * GST-2767: the page a single-page run embeds. The slug is the first argument that is neither a flag nor a flag's value,
+ * so `--source <id>` is never read as a slug, and a flag no embed mode accepts (`--status`) is refused as unknown_flag
+ * before anything is spent, instead of the next argument being looked up as a page.
+ */
+export function embedSlugTarget(args: readonly string[]): string | undefined {
+ let slug: string | undefined;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (a === '--') { slug ??= args[i + 1]; break; }
+ if (SLUG_VALUE_FLAGS.has(a)) { i++; continue; }
+ const name = a.split('=')[0]!;
+ if (SLUG_BOOLEAN_FLAGS.has(a) || (a.includes('=') && (name === '--pace' || SLUG_VALUE_FLAGS.has(name)))) continue;
+ if (a.startsWith('-')) {
+ const source = args[args.indexOf('--source') + 1];
+ const dryRun = ['gbrain', 'embed', '--stale', '--dry-run', '--json', ...(args.includes('--source') && source ? ['--source', source] : [])];
+ throw opError('unknown_flag', `gbrain embed does not accept ${name}.`,
+ `Nothing was embedded. ${name === '--status' ? 'Embedding coverage is read with gbrain embed --stale --dry-run --json (add --source <id> for one source; it calls no provider and spends nothing) or gbrain doctor --only embedding_state --json. ' : ''}`
+ + 'Run gbrain embed --help for the flags each mode takes.', {
+ detail: name,
+ why: `A single-page run (gbrain embed <slug>) takes only its own flags, and ${name} is not one of them, so the run stopped before it read a page or asked for spend approval.`,
+ fix: { argv: dryRun, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Lists the pages whose embeddings are missing or stale without calling a provider or spending anything.',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } },
+ });
+ }
+ slug ??= a;
+ }
+ return slug;
+}
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 9efeaca350..8add4aef3b 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -993,7 +993,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
// E-2: CLI-only single-flight for stale runs (the minion path locks itself).
opts = { all, stale, dryRun, sourceId, batchSize, priority, catchUp, ...(pace && { pace }), ...(stale && { singleFlight: true }), ...(includeNullSignature && { includeNullSignature: true }) };
} else {
- const slug = args.find(a => !a.startsWith('--'));
+ const slug = (await import('./embed-slug-args.ts')).embedSlugTarget(args);
if (!slug) {
serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--yes | --max-usd N] | --stale --images (gbrain embed --help: paid runs need the user\'s approval)');
process.exit(1);
diff --git a/src/commands/git.ts b/src/commands/git.ts
index 5646cf2c3f..8694cf4a53 100644
--- a/src/commands/git.ts
+++ b/src/commands/git.ts
@@ -337,8 +337,10 @@ export async function runGit(args: string[]): Promise<number> {
if (code === 'commit_paths_skipped' || code === 'writer_coordinator_required') {
// GST-2116: the other named paths may have been pushed before the run failed, or their push failed (`publish`); the push log records either.
try {
- const d = JSON.parse(String((e as { detail?: string }).detail ?? '{}')) as { pushed?: string; branch?: string; publish?: { code: string | null; detail: string | null } };
+ const d = JSON.parse(String((e as { detail?: string }).detail ?? '{}')) as { dry_run?: boolean; pushed?: string; branch?: string; committed?: string | null;
+ skipped?: Array<{ path: string; reason: string; why?: string }>; publish?: { code: string | null; detail: string | null } };
if (d.pushed && d.branch) appendPushLog('ok', d.branch, d.pushed);
+ if (d.skipped?.length && d.branch && !d.dry_run) appendPushLog('skipped', d.branch, d.committed ?? '', `${code}: ${d.skipped.map(s => `${s.path} (${s.reason}${s.why ? `: ${s.why}` : ''})`).join('; ')}`);
if (d.publish) failed = d.publish;
} catch { /* best-effort */ }
}
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 2010214c00..5436bb3b35 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -7,7 +7,7 @@
* phases drain.
*/
import { existsSync, realpathSync } from 'fs';
-import { resolve as pathResolve, join } from 'path';
+import { dirname, resolve as pathResolve, join } from 'path';
import { chunkerStamp } from '../../core/chunkers/code.ts';
import { currentCompanyBrainSync } from '../../core/company-brain/profile.ts';
import { serr, slog } from '../../core/console-prefix.ts';
@@ -546,6 +546,11 @@ async function discoverSyncGitRoot(
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is the operator-configured local sync repo (sync is localOnly) and '.git' is a constant name
} else if (existsSync(join(repoPath, '.git'))) {
throw err;
+ } else if (enclosingGitEntry(repoPath)) {
+ // GST-2767: a brain dir inside an unreadable repository (dubious ownership, a broken .git above it) must not get
+ // a nested repository of its own that shadows the outer one.
+ const entry = enclosingGitEntry(repoPath)!;
+ throw new Error(`${(err as Error).message} ${entry} sits above it and git cannot open it, so gbrain will not create a repository inside it: run git -C ${dirname(entry)} status to see why git refuses it, fix or remove it, then rerun the sync.`);
} else {
serr(`[gbrain] auto-recovery: git-initializing brain dir ${repoPath} (no git repo found).`);
await gitAsync(repoPath, ['init', '--quiet']);
@@ -556,6 +561,13 @@ async function discoverSyncGitRoot(
return gitContextRoot;
}
+/** The `.git` entry a folder above `repoPath` (through any link in it) holds, or null. */
+function enclosingGitEntry(repoPath: string): string | null {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is the operator-configured local sync repo and '.git' is a constant name
+ for (let at = dirname(realpathSync(repoPath)); dirname(at) !== at; at = dirname(at)) if (existsSync(join(at, '.git'))) return join(at, '.git');
+ return null;
+}
+
/** Detached-HEAD / origin detection, the bookmark read, the git pull and HEAD (with the unborn-HEAD self-heal). */
async function pullAndResolveHead(
engine: BrainEngine,
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index be9e350a05..e276144b37 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -733,9 +733,9 @@ export interface PushLogOutcome {
}
const PUSH_LOG_OK = /^(\S+) \[push\] (?:ok|ok-after-rebase|ok-after-merge|ok-already-on-remote) (\S+)\b/;
-const PUSH_LOG_LOCAL_ONLY = /^(\S+) \[push\] (?:LOCAL-ONLY|CONFLICT), NEEDS ATTENTION: (\S+) /;
+const PUSH_LOG_LOCAL_ONLY = /^(\S+) \[push\] (?:LOCAL-ONLY|CONFLICT|SKIPPED), NEEDS ATTENTION: (\S+) /;
-export type PushLogKind = 'ok' | 'ok-after-merge' | 'nothing' | 'local-only' | 'refused' | 'conflict' | 'lock-timeout' | 'checkout-lagging';
+export type PushLogKind = 'ok' | 'ok-after-merge' | 'nothing' | 'local-only' | 'refused' | 'conflict' | 'lock-timeout' | 'checkout-lagging' | 'skipped';
/**
* #6530: one `brain-push.log` line per `gbrain git commit-push` outcome, in the
@@ -746,12 +746,13 @@ export function appendPushLog(kind: PushLogKind, branch: string, sha: string, de
try {
const at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
const short = sha ? sha.slice(0, 7) : '-';
- const clean = (detail ?? '').replace(/\s+/g, ' ').slice(0, 200);
+ const clean = (detail ?? '').replace(/\s+/g, ' ').slice(0, kind === 'skipped' ? 2000 : 200);
const line = kind === 'ok' ? `[push] ok ${branch} ${short}`
: kind === 'ok-after-merge' ? `[push] ok-after-merge ${branch} ${short}`
: kind === 'nothing' ? `[push] ok-already-on-remote ${branch} ${short}`
: kind === 'lock-timeout' ? `[push] lock-timeout ${branch}`
: kind === 'checkout-lagging' ? `[push] checkout-lagging ${branch} ${short} ${clean}`
+ : kind === 'skipped' ? `[push] SKIPPED, NEEDS ATTENTION: ${branch} @ ${short} git did not commit named path(s), ${clean}. Run: gbrain errors commit_paths_skipped`
: kind === 'refused' ? `[push] LOCAL-ONLY, NEEDS ATTENTION: ${branch} @ ${short} the push was refused (${clean}). Run: gbrain git commit-push --push-only`
: kind === 'conflict' ? `[push] CONFLICT, NEEDS ATTENTION: ${branch} local and remote changed the same file. Run: gbrain git commit-push --push-only --resolve <path>=ours|theirs`
: `[push] LOCAL-ONLY, NEEDS ATTENTION: ${branch} @ ${short} could not reach the remote. Run: gbrain git commit-push --push-only`;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 7d26c4c169..1655528e0b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -52,11 +52,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--only', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--room', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
- 'embed': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-schema', '--gbrain-bin', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--room', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
+ 'embed': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-schema', '--gbrain-bin', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--room', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--as', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--expected-revision', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--of', '--only', '--order', '--output', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--room', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--terms-url', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'founder': ['--brain', '--help', '--json', '--mcp-only', '--request-id', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--local', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],
- 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--attr-source', '--autostash', '--base', '--batch', '--batch-check', '--before', '--brain', '--branch', '--cached', '--cacheinfo', '--cc', '--cherry-mark', '--combined', '--count', '--diff-filter', '--dry-run', '--dst-prefix', '--enable', '--end-of-options', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--from', '--full-index', '--get', '--get-all', '--get-regexp', '--get-url', '--git', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--ignore-unmatch', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-color', '--no-commit-id', '--no-cron', '--no-ext-diff', '--no-follow-tags', '--no-gpg-sign', '--no-index', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-textconv', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-prefix', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--src-prefix', '--staged', '--stat', '--stdin', '--to', '--topo-order', '--type', '--unified', '--uninstall', '--unset', '--unset-all', '--untrack', '--untracked-files', '--verify', '--worktree', '--write-tree'],
+ 'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--attr-source', '--autostash', '--base', '--batch', '--batch-check', '--before', '--brain', '--branch', '--cached', '--cacheinfo', '--cc', '--cherry-mark', '--combined', '--count', '--diff-filter', '--dry-run', '--dst-prefix', '--enable', '--end-of-options', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--from', '--full-index', '--get', '--get-all', '--get-regexp', '--get-url', '--git', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--ignore-unmatch', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-color', '--no-commit-id', '--no-cron', '--no-ext-diff', '--no-follow-tags', '--no-gpg-sign', '--no-index', '--no-merges', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-textconv', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-prefix', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--src-prefix', '--staged', '--stat', '--stdin', '--to', '--topo-order', '--type', '--unified', '--uninstall', '--unset', '--unset-all', '--untrack', '--untracked-files', '--verify', '--worktree', '--write-tree'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embed', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'guests': ['--add', '--brain', '--client', '--guest-source', '--help', '--id', '--if-version', '--json', '--read-sources', '--source', '--sources', '--to', '--writer', '--yes'],
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index 09ef2c0e48..e95dc9e9a2 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -25,13 +25,16 @@
* (#7010; the owner's Git effects publish this way). CLI-only; never exposed
* over MCP (it pushes with host credentials).
*/
-import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { appendFileSync, copyFileSync, existsSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { rangeSecretRefusal, scanRange } from './range-secret-scan.ts';
-import { isAbsolute, join, relative, resolve, sep } from 'node:path';
-import { execFileSync } from '../spawn.ts';
-import { gitChildEnv, literalPathspecs } from '../git-env.ts';
-import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, ownRemoteTransportFlags as transportFlags } from '../git-transport.ts';
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { literalPathspecs } from '../git-env.ts';
+import { git, gitOk, type GitRun } from './git-run.ts';
+export type { SkippedPath } from './skipped-paths.ts';
+import { checkoutBehindStrayGitfile, directoryStatus, worktreeOfGitdir, flaggedChanges, stagedRemovals, STAGED_FOR_REMOVAL_WHY, unindexedFiles, unstagedPaths, type SkippedPath } from './skipped-paths.ts';
+import { GIT_SSRF_SUBCOMMAND_FLAGS, ownRemoteTransportFlags as transportFlags } from '../git-transport.ts';
+import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
import { assertManagedFilesystemWrite, hasFilesystemPublication, managedFilesystemRootFor, type ManagedFilesystemRoot } from '../persistence/filesystem-guard.ts';
import { acquireNativeLock, acquireNativeLockSync, type NativeLockSyncHandle } from '../persistence/native-lock.ts';
import { recordCommit, recordIntent } from './commit-ledger.ts';
@@ -150,38 +153,6 @@ interface Ctx {
scanProgress?: (line: string) => void;
}
-interface GitRun { code: number; stdout: string; stderr: string }
-
-function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string; maxBuffer?: number } = {}): GitRun {
- const base = opts.auth ? { ...GIT_ENV_AUTH } : { ...GIT_ENV };
- try {
- const stdout = execFileSync('git', ['-C', root, ...args], {
- stdio: ['pipe', 'pipe', 'pipe'],
- input: opts.input ?? '',
- timeout: opts.timeoutMs ?? 60_000,
- ...(opts.maxBuffer ? { maxBuffer: opts.maxBuffer } : {}),
- env: gitChildEnv({ ...base, LC_ALL: 'C', LANGUAGE: 'C', ...opts.env }),
- }).toString();
- return { code: 0, stdout, stderr: '' };
- } catch (e) {
- const err = e as { status?: number | null; stdout?: Buffer | string; stderr?: Buffer | string; message?: string };
- return {
- code: typeof err.status === 'number' ? err.status : -1,
- stdout: String(err.stdout ?? ''),
- stderr: String(err.stderr ?? err.message ?? ''),
- };
- }
-}
-
-function gitOk(root: string, args: string[], what: string, opts: Parameters<typeof git>[2] = {}): string {
- const r = git(root, args, opts);
- if (r.code !== 0) {
- throw opError('git_unavailable', `git ${what} failed in ${root}: ${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}`,
- `Run git status in ${root}, fix what git reports, then rerun the same gbrain git commit-push command.`);
- }
- return r.stdout.trim();
-}
-
/** Remote operations: transport hardening on every call, credentials allowed, no prompt. */
function remoteGit(root: string, sub: 'fetch' | 'push', args: string[], timeoutMs = 120_000): GitRun {
return git(root, [...transportFlags(), sub, ...GIT_SSRF_SUBCOMMAND_FLAGS, ...args], { auth: true, timeoutMs });
@@ -206,11 +177,12 @@ export function commitPushCommand(root: string, paths: readonly string[], messag
export function checkoutRoot(dir: string): string {
const r = git(dir, ['rev-parse', '--show-toplevel']);
- if (r.code !== 0 || !r.stdout.trim()) {
+ const top = (r.code === 0 && r.stdout.trim()) || checkoutBehindStrayGitfile(dir);
+ if (!top) {
throw opError('commit_paths_invalid', `${dir} is not inside a git checkout.`,
'Run the command inside the brain checkout or pass --path <checkout>.');
}
- return r.stdout.trim();
+ return worktreeOfGitdir(top);
}
function resolveCtx(root: string): Ctx {
@@ -324,7 +296,10 @@ export function scopePaths(root: string, paths: string[], cwd: string): string[]
}
const out: string[] = [];
for (const p of paths) {
- const abs = resolve(cwd, p);
+ // GST-2767: a path reached through a symlinked directory (a source path linked to a subdirectory of the checkout) names
+ // the file at its real location; only the parent is resolved, so a named symlink file stays itself.
+ const named = resolve(cwd, p);
+ const abs = join(canonicalFilesystemPath(dirname(named)), basename(named));
const rel = relative(root, abs);
if (rel === '' || rel === '.' || rel.startsWith('..') || isAbsolute(rel)) {
throw opError('commit_paths_invalid', `Path ${p} is ${rel === '' || rel === '.' ? 'the whole checkout' : 'outside the checkout'}.`,
@@ -437,101 +412,21 @@ function restoreIndex(root: string, rel: string[], before: string[], flagged: st
interface CommitScope { roots: string[]; lockPath: string; markHeld: boolean; bases?: ReadonlyMap<string, string>; untrack?: 'any' | { dbOnly: ManagedFilesystemRoot } }
/** A named path `git add -A` left out of the index while still exiting 0 (GST-2116). */
-export interface SkippedPath { path: string; reason: 'assume_unchanged' | 'skip_worktree' | 'not_staged' }
-
-/** The flagged index entries in `listed` (`ls-files -v`: lower case for assume-unchanged, S for skip-worktree) whose bytes on disk HEAD lacks. A skip-worktree entry absent from disk is a sparse checkout, not a change. */
-function flaggedChanges(root: string, listed: string[]): SkippedPath[] {
- const changed: SkippedPath[] = [];
- const flagged = listed.filter(entry => /^[a-zS] /.test(entry));
- const gitlinks = new Set(flagged.length
- ? gitOk(root, ['ls-files', '-s', '-z', '--', ...literalPathspecs(flagged.map(line => line.slice(2)))], 'ls-files -s')
- .split('\0').filter(entry => entry.startsWith('160000 ')).map(entry => entry.slice(entry.indexOf('\t') + 1))
- : []);
- for (const line of flagged) {
- const path = line.slice(2);
- if (gitlinks.has(path)) continue;
- const abs = join(root, path);
- const reason = /^[sS]/.test(line) ? 'skip_worktree' as const : 'assume_unchanged' as const;
- const stat = (() => { try { return lstatSync(abs); } catch { return null; } })();
- if (!stat && reason === 'skip_worktree') continue;
- const hashed = !stat ? null : stat.isSymbolicLink()
- ? git(root, ['hash-object', '--stdin'], { input: readlinkSync(abs) })
- : git(root, ['hash-object', '--', path]);
- // An entry git cannot hash (a missing required filter, an unreadable file, a directory now) counts as changed, so it is reported, never dropped.
- const disk = hashed && (hashed.code === 0 ? hashed.stdout.trim() : undefined);
- const committed = git(root, ['rev-parse', '--verify', '--quiet', `HEAD:${path}`]).stdout.trim() || null;
- if (disk !== committed) changed.push({ path, reason });
- }
- return changed;
-}
-
-/**
- * GST-2116: the named paths whose bytes on disk HEAD still lacks once the commit step is done. `git add -A` stages
- * nothing and exits 0 for a modified entry flagged assume-unchanged or skip-worktree (`ls-files -v`: lower case, or S;
- * `commit --only` may still pick one up beside another path, so the check reads HEAD) and for a file inside an untracked
- * nested repository. A skip-worktree entry absent from disk is a sparse checkout, not a change, and a flagged gitlink
- * is left out (its commit lives in the nested repository, which hash-object cannot read). Ignored files under a named
- * directory are left out as git leaves them; a named ignored file is refused by `git add` itself.
- */
-function unstagedPaths(root: string, rel: string[], listed: string[], dirtyBefore: Map<string, string>, sha: string | null): SkippedPath[] {
- const skipped = new Map(flaggedChanges(root, listed).map(s => [s.path, s.reason]));
- for (const path of unindexedFiles(root, rel, listed)) if (!skipped.has(path)) skipped.set(path, 'not_staged');
- // Only a named directory can hide an unstaged change from the two checks above (a nested repository inside it).
- const dirs = rel.filter(path => { try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
- // Status lists nothing under a directory that sits inside an untracked nested repository.
- for (const path of dirs) {
- const parents = path.split('/').slice(0, -1).map((_, i, parts) => parts.slice(0, i + 1).join('/'));
- if (!skipped.has(path) && parents.some(parent => existsSync(join(root, parent, '.git')))) skipped.set(path, 'not_staged');
- }
- // GST-2128: an entry that was clean before the add, or a tracked one this commit carried, is another writer's later change, not a skip.
- const status = directoryStatus(root, dirs);
- const carried = sha && status.size ? committedModes(root, sha) : new Map<string, string>();
- for (const [path, xy] of status) {
- if (xy[1] === ' ' || skipped.has(path) || !dirtyBefore.has(path)) continue;
- if (xy !== '??' && carried.has(path) && carried.get(path) !== '160000') continue;
- skipped.set(path, 'not_staged');
- }
- return [...skipped].map(([path, reason]) => ({ path, reason })).sort((a, b) => a.path.localeCompare(b.path));
-}
-
-/** The `git status` entries under the named paths that are directories, as path (a nested repository keeps its trailing /) to XY code. */
-function directoryStatus(root: string, rel: string[]): Map<string, string> {
- const dirs = rel.filter(path => { try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
- const status = dirs.length ? gitOk(root, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames', '--', ...literalPathspecs(dirs)], 'status') : '';
- return new Map(status.split('\0').filter(Boolean).map(entry => [entry.slice(3), entry.slice(0, 2)]));
-}
-
-/** The paths commit `sha` changed, each with its new mode (160000 for a gitlink, 000000 for a removal). */
-function committedModes(root: string, sha: string): Map<string, string> {
- const fields = gitOk(root, ['diff-tree', '--root', '-r', '--no-renames', '--no-commit-id', '-z', sha], 'diff-tree').split('\0');
- const modes = new Map<string, string>();
- for (let i = 0; i + 1 < fields.length; i += 2) if (fields[i]!.startsWith(':')) modes.set(fields[i + 1]!, fields[i]!.split(' ')[1]!);
- return modes;
-}
-
-/** Named paths that are files on disk yet absent from the index (`listed`: `ls-files -v` after `git add -A`), as a file inside a nested repository is. */
-function unindexedFiles(root: string, rel: string[], listed: string[]): string[] {
- const indexed = new Set(listed.map(line => line.slice(2)));
- return rel.filter(path => {
- if (indexed.has(path)) return false;
- try { return !lstatSync(join(root, path)).isDirectory(); } catch { return false; }
- });
-}
/**
* GST-2116: a run that left a named path uncommitted fails, after committing (and, on a classic checkout, pushing) the
* rest, so a write is never reported as saved when it is not. In a managed canonical worktree a skipped page is the
* owner's to save (`writer_coordinator_required`); anything else is `commit_paths_skipped`.
*/
-function skippedPathsError(root: string, skipped: SkippedPath[], result: CommitPushResult, managed?: ManagedFilesystemRoot, publish?: unknown): OperationError {
- const list = `${skipped.slice(0, 20).map(s => `${s.path} (${s.reason})`).join(', ')}${skipped.length > 20 ? ', ...' : ''}`;
+function skippedPathsError(root: string, skipped: SkippedPath[], result: CommitPushResult, managed?: ManagedFilesystemRoot, publish?: unknown, dryRun = false): OperationError {
+ const list = `${skipped.slice(0, 20).map(s => `${s.path} (${s.reason}: ${s.why})`).join(', ')}${skipped.length > 20 ? ', ...' : ''}`;
const pushed = !!result.committed && (result.outcome === 'pushed' || result.outcome === 'pushed_checkout_lagging');
const done = result.committed
? `The other named paths were committed as ${result.committed.slice(0, 7)}${pushed ? ` and pushed to ${result.remote}/${result.branch}` : ', not pushed'}.`
: 'Nothing was committed.';
const failed = publish as { code?: string; message?: string; detail?: string } | undefined;
const rest = `${done}${failed ? ` The push failed too (${failed.code ?? 'error'}): ${failed.message ?? String(publish)}` : ''}`;
- const detail = JSON.stringify({ skipped, committed: result.committed, ...(pushed ? { pushed: result.sha } : {}), branch: result.branch,
+ const detail = JSON.stringify({ ...(dryRun ? { dry_run: true } : {}), skipped, committed: result.committed, ...(pushed ? { pushed: result.sha } : {}), branch: result.branch,
...(failed ? { publish: { code: failed.code ?? null, detail: failed.detail ?? null } } : {}) });
const docs = 'docs/guides/shared-checkout-git.md#outcomes';
const flagged = skipped.filter(s => s.reason !== 'not_staged');
@@ -544,14 +439,18 @@ function skippedPathsError(root: string, skipped: SkippedPath[], result: CommitP
const flagNote = 'an assume-unchanged or skip-worktree flag; an editor, an indexer or a sparse checkout can leave one, and people also set skip-worktree on purpose to keep local edits out of commits, so clearing it commits those edits';
const chain = (steps: string[][], last?: Action): Action | undefined => steps.reduceRight<Action | undefined>((then, argv) =>
({ argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Clears the flag so git sees the edit on disk; the file keeps its bytes.', ...(then ? { then } : {}) }), last);
- const named = skipped.map(s => s.path);
- const indexed = new Set(git(root, ['ls-files', '-z', '--', ...literalPathspecs(named)]).stdout.split('\0').filter(Boolean));
- const atHead = new Set(git(root, ['ls-tree', '-z', '--name-only', 'HEAD', '--', ...literalPathspecs(named)]).stdout.split('\0').filter(Boolean));
- const removals = skipped.filter(s => s.reason === 'not_staged' && atHead.has(s.path) && !indexed.has(s.path) && existsSync(join(root, s.path))).map(s => s.path);
+ const removals = skipped.filter(s => s.reason === 'staged_for_removal').map(s => s.path);
if (removals.length && removals.length === skipped.length) {
- return opError('commit_paths_skipped', `git did not commit ${skipped.length} named path(s) in ${root}: ${list}. They are staged for removal from Git (git rm --cached) while the files stay on disk, and commit-push does not commit that removal. ${rest}`,
- `To stop tracking them and keep the files, run gbrain git commit-push --untrack -m <msg> -- ${removals.map(p => shellQuote([p])).join(' ')}; to keep them tracked, git -C ${shellQuote([root])} restore --staged -- ${removals.map(p => shellQuote([p])).join(' ')}.`,
- { docs: 'docs/guides/shared-checkout-git.md#untrack', detail });
+ const quoted = removals.map(p => shellQuote([p])).join(' ');
+ return opError('commit_paths_skipped', 'git did not commit ' + skipped.length + ' named path(s) in ' + root + ': ' + list + '. They are staged for removal from Git (git rm --cached) while the files stay on disk, and commit-push does not commit that removal. ' + rest,
+ 'To stop tracking them and keep the files, run gbrain git commit-push --untrack -m <msg> -- ' + quoted + '; to keep them tracked, git -C ' + shellQuote([root]) + ' restore --staged -- ' + quoted + '.',
+ { docs: 'docs/guides/shared-checkout-git.md#untrack', detail,
+ why: 'Something took these files out of the index while leaving them on disk; committing would either publish that removal or quietly add back what someone removed, and only the user knows which was meant.',
+ fix: { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
+ argv: ['git', '-C', root, 'restore', '--staged', '--', ...literalPathspecs(removals)],
+ why: 'Puts the files back in the index as HEAD has them, so the next commit-push commits their edits; the bytes on disk are untouched.',
+ user_message: 'Git has ' + removals.slice(0, 10).join(', ') + ' staged for removal while the files are still on disk, so they were not committed. Keep them in Git (git restore --staged), or stop tracking them and keep the files (gbrain git commit-push --untrack)?',
+ verify: { argv: ['git', '-C', root, 'status', '--porcelain', '--', ...literalPathspecs(removals)] } } });
}
const pages = managed ? skipped.filter(s => isSyncable(s.path)) : [];
if (managed && pages.length) {
@@ -601,7 +500,7 @@ function scopeBases(root: string, opts: CommitPushOptions, rel: string[]): Map<s
* What commitPaths refuses before anything is staged (and the dry run with it): a path outside the source root(s), a
* `--base` blob HEAD no longer holds, and a file another writer already staged under a named directory (name it to claim it).
*/
-function admitPaths(root: string, rel: string[], roots: string[], bases?: ReadonlyMap<string, string>): void {
+function admitPaths(root: string, rel: string[], roots: string[], bases?: ReadonlyMap<string, string>, dryRun = false): void {
const outside = rel.filter(p => !insideSourceRoots(p, roots));
if (outside.length) throw outsideRootError(root, roots, outside, 'Refusing to commit');
for (const [path, base] of bases ?? []) {
@@ -611,6 +510,12 @@ function admitPaths(root: string, rel: string[], roots: string[], bases?: Readon
{ detail: JSON.stringify({ path, base, head }), docs: 'docs/guides/shared-checkout-git.md#base-check' });
}
const swept = stagedPaths(root).filter(p => !rel.includes(p) && rel.some(spec => covers(spec, p)));
+ const removed = new Set(stagedRemovals(root, swept));
+ if (swept.length && swept.every(p => removed.has(p))) {
+ const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();
+ throw skippedPathsError(root, swept.map(path => ({ path, reason: 'staged_for_removal' as const, why: STAGED_FOR_REMOVAL_WHY })),
+ { outcome: 'nothing_to_commit', sha: null, committed: null, branch, remote: '', paths: rel, integrated: 0, checkout: 'unchanged' }, undefined, undefined, dryRun);
+ }
if (swept.length) {
const list = `${swept.slice(0, 10).join(', ')}${swept.length > 10 ? ', ...' : ''}`;
throw opError('commit_prestaged_paths', `${swept.length} file(s) under the named path(s) were already staged by another writer: ${list}.`,
@@ -774,8 +679,8 @@ function previewRoots(root: string, allowOutsideSourceRoot?: boolean): { managed
* worktree as they were (git may add loose objects for the staged files); each refusal carries the real run's code and text.
*/
export function previewPaths(root: string, rel: string[], opts: { allowOutsideSourceRoot?: boolean; bases?: Map<string, string>; cwd?: string } = {}): void {
- const { roots } = previewRoots(root, opts.allowOutsideSourceRoot);
- admitPaths(root, rel, roots, scopeBases(root, { repo: root, bases: opts.bases, cwd: opts.cwd }, rel));
+ const { managed, roots } = previewRoots(root, opts.allowOutsideSourceRoot);
+ admitPaths(root, rel, roots, scopeBases(root, { repo: root, bases: opts.bases, cwd: opts.cwd }, rel), true);
const dir = mkdtempSync(join(tmpdir(), 'gbrain-preview-'));
try {
const index = join(dir, 'index');
@@ -785,6 +690,10 @@ export function previewPaths(root: string, rel: string[], opts: { allowOutsideSo
stagePaths(root, rel, indexEntries(root, rel), flaggedEntries(root, rel), env, true);
const partners = withRenamePartners(root, rel, env).filter(p => !insideSourceRoots(p, roots));
if (partners.length) throw outsideRootError(root, roots, partners, 'A staged rename would commit');
+ const listed = gitOk(root, ['ls-files', '-v', '-z', '--', ...literalPathspecs(rel)], 'ls-files -v', { env }).split('\0').filter(Boolean);
+ const skipped = unstagedPaths(root, rel, listed, new Map(), null);
+ const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).stdout.trim();
+ if (skipped.length) throw skippedPathsError(root, skipped, { outcome: 'nothing_to_commit', sha: null, committed: null, branch, remote: '', paths: rel, integrated: 0, checkout: 'unchanged' }, managed ?? undefined, undefined, true);
} finally {
rmSync(dir, { recursive: true, force: true });
}
diff --git a/src/core/git/git-run.ts b/src/core/git/git-run.ts
new file mode 100644
index 0000000000..8be04fb7b7
--- /dev/null
+++ b/src/core/git/git-run.ts
@@ -0,0 +1,37 @@
+/** The plain git runner commit-push and its skipped-path checks share: C locale, hardened env, no prompt. */
+import { execFileSync } from '../spawn.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { GIT_ENV, GIT_ENV_AUTH } from '../git-transport.ts';
+import { opError } from '../ops/contract.ts';
+
+export interface GitRun { code: number; stdout: string; stderr: string }
+
+export function git(root: string, args: string[], opts: { auth?: boolean; timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string; maxBuffer?: number } = {}): GitRun {
+ const base = opts.auth ? { ...GIT_ENV_AUTH } : { ...GIT_ENV };
+ try {
+ const stdout = execFileSync('git', ['-C', root, ...args], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ input: opts.input ?? '',
+ timeout: opts.timeoutMs ?? 60_000,
+ ...(opts.maxBuffer ? { maxBuffer: opts.maxBuffer } : {}),
+ env: gitChildEnv({ ...base, LC_ALL: 'C', LANGUAGE: 'C', ...opts.env }),
+ }).toString();
+ return { code: 0, stdout, stderr: '' };
+ } catch (e) {
+ const err = e as { status?: number | null; stdout?: Buffer | string; stderr?: Buffer | string; message?: string };
+ return {
+ code: typeof err.status === 'number' ? err.status : -1,
+ stdout: String(err.stdout ?? ''),
+ stderr: String(err.stderr ?? err.message ?? ''),
+ };
+ }
+}
+
+export function gitOk(root: string, args: string[], what: string, opts: Parameters<typeof git>[2] = {}): string {
+ const r = git(root, args, opts);
+ if (r.code !== 0) {
+ throw opError('git_unavailable', `git ${what} failed in ${root}: ${r.stderr.trim().slice(0, 300) || `exit ${r.code}`}`,
+ `Run git status in ${root}, fix what git reports, then rerun the same gbrain git commit-push command.`);
+ }
+ return r.stdout.trim();
+}
diff --git a/src/core/git/skipped-paths.ts b/src/core/git/skipped-paths.ts
new file mode 100644
index 0000000000..fec8d03ccd
--- /dev/null
+++ b/src/core/git/skipped-paths.ts
@@ -0,0 +1,182 @@
+/** GST-2116, GST-2767: which named paths a commit-push left out, and why, in words an operator can act on. */
+import { existsSync, lstatSync, readFileSync, readlinkSync, statSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import { literalPathspecs } from '../git-env.ts';
+import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
+import { git, gitOk } from './git-run.ts';
+
+export interface SkippedPath { path: string; reason: 'assume_unchanged' | 'skip_worktree' | 'not_staged' | 'staged_for_removal'; why: string }
+
+export const STAGED_FOR_REMOVAL_WHY = 'the index holds it as staged for removal from Git (as after git rm --cached) while the file stays on disk, and commit-push neither commits that removal nor adds the file back unasked';
+
+/** The files under `rel` the index holds as staged for removal (HEAD has them, the index does not) whose bytes are still on disk. */
+export function stagedRemovals(root: string, rel: string[]): string[] {
+ if (!rel.length) return [];
+ return gitOk(root, ['diff', '--cached', '--no-renames', '--name-only', '--diff-filter=D', '-z', '--', ...literalPathspecs(rel)], 'diff --cached')
+ .split('\0').filter(path => { try { return !!path && !lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
+}
+
+/** The flagged index entries in `listed` (`ls-files -v`: lower case for assume-unchanged, S for skip-worktree) whose bytes on disk HEAD lacks. A skip-worktree entry absent from disk is a sparse checkout, not a change. */
+export function flaggedChanges(root: string, listed: string[]): SkippedPath[] {
+ const changed: SkippedPath[] = [];
+ const flagged = listed.filter(entry => /^[a-zS] /.test(entry));
+ const gitlinks = new Set(flagged.length
+ ? gitOk(root, ['ls-files', '-s', '-z', '--', ...literalPathspecs(flagged.map(line => line.slice(2)))], 'ls-files -s')
+ .split('\0').filter(entry => entry.startsWith('160000 ')).map(entry => entry.slice(entry.indexOf('\t') + 1))
+ : []);
+ for (const line of flagged) {
+ const path = line.slice(2);
+ if (gitlinks.has(path)) continue;
+ const abs = join(root, path);
+ const reason = /^[sS]/.test(line) ? 'skip_worktree' as const : 'assume_unchanged' as const;
+ const stat = (() => { try { return lstatSync(abs); } catch { return null; } })();
+ if (!stat && reason === 'skip_worktree') continue;
+ const hashed = !stat ? null : stat.isSymbolicLink()
+ ? git(root, ['hash-object', '--stdin'], { input: readlinkSync(abs) })
+ : git(root, ['hash-object', '--', path]);
+ // An entry git cannot hash (a missing required filter, an unreadable file, a directory now) counts as changed, so it is reported, never dropped.
+ const disk = hashed && (hashed.code === 0 ? hashed.stdout.trim() : undefined);
+ const committed = git(root, ['rev-parse', '--verify', '--quiet', `HEAD:${path}`]).stdout.trim() || null;
+ if (disk !== committed) changed.push({ path, reason, why: reason === 'skip_worktree'
+ ? 'the index entry carries the skip-worktree flag, so git add does not see the edit on disk'
+ : 'the index entry carries the assume-unchanged flag, so git add does not see the edit on disk' });
+ }
+ return changed;
+}
+
+/**
+ * GST-2116: the named paths whose bytes on disk HEAD still lacks once the commit step is done. `git add -A` stages
+ * nothing and exits 0 for a modified entry flagged assume-unchanged or skip-worktree (`ls-files -v`: lower case, or S;
+ * `commit --only` may still pick one up beside another path, so the check reads HEAD) and for a file inside an untracked
+ * nested repository. A skip-worktree entry absent from disk is a sparse checkout, not a change, and a flagged gitlink
+ * is left out (its commit lives in the nested repository, which hash-object cannot read). Ignored files under a named
+ * directory are left out as git leaves them; a named ignored file is refused by `git add` itself.
+ */
+export function unstagedPaths(root: string, rel: string[], listed: string[], dirtyBefore: Map<string, string>, sha: string | null): SkippedPath[] {
+ const skipped = new Map(flaggedChanges(root, listed).map(s => [s.path, s]));
+ const notStaged = (path: string, why: string) => { if (!skipped.has(path)) skipped.set(path, { path, reason: 'not_staged', why }); };
+ const removed = new Set(stagedRemovals(root, rel));
+ for (const path of unindexedFiles(root, rel, listed)) {
+ if (removed.has(path)) { skipped.set(path, { path, reason: 'staged_for_removal', why: STAGED_FOR_REMOVAL_WHY }); continue; }
+ const nested = nestedRepositoryOf(root, path);
+ notStaged(path, nested ? `it sits inside the nested Git repository ${nested}, so git add stages nothing for it` : 'git add left it out of the index');
+ }
+ // Only a named directory can hide an unstaged change from the two checks above (a nested repository inside it).
+ const dirs = rel.filter(path => { try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
+ // Status lists nothing under a directory that sits inside an untracked nested repository.
+ for (const path of dirs) {
+ const nested = nestedRepositoryOf(root, path);
+ if (nested) notStaged(path, `it sits inside the nested Git repository ${nested}, so git add stages nothing under it`);
+ }
+ // GST-2128: an entry that was clean before the add, or a tracked one this commit carried, is another writer's later change, not a skip.
+ const status = directoryStatus(root, dirs);
+ const carried = sha && status.size ? committedModes(root, sha) : new Map<string, string>();
+ for (const [path, xy] of status) {
+ if (xy[1] === ' ' || skipped.has(path) || !dirtyBefore.has(path)) continue;
+ if (xy !== '??' && carried.has(path) && carried.get(path) !== '160000') continue;
+ notStaged(path, xy === '??' ? 'it is still untracked after the commit' : `it still differs from the last commit after the commit (git status ${xy.trim()})`);
+ }
+ return [...skipped.values()].sort((a, b) => a.path.localeCompare(b.path));
+}
+
+/**
+ * GST-2767: the directory above `path` (repository-relative) that Git treats as a nested repository, or null. A `.git`
+ * entry alone is not one: an empty or broken `.git` left under a source path is ignored by git, which stages and commits
+ * the files beneath it, so only a directory that is its own work-tree top level counts.
+ */
+export function nestedRepositoryOf(root: string, path: string): string | null {
+ const parts = path.split('/');
+ const own = validGitDir(join(root, '.git'));
+ for (let i = 1; i < parts.length; i++) {
+ const dir = parts.slice(0, i).join('/');
+ const gitDir = validGitDir(join(root, dir, '.git'));
+ if (gitDir && gitDir !== own) return dir;
+ }
+ return null;
+}
+
+/**
+ * The git directory a `.git` entry names (a directory, a link to one, or a `gitdir:` file), canonical, when git's own
+ * discovery would take it as a repository: HEAD names a ref or an object, and objects/ and refs/ exist. Ownership is never
+ * read, as `git add` in the outer repository does not read it, so a nested repository git refuses to open still counts.
+ */
+export function validGitDir(dotGit: string): string | null {
+ try {
+ let dir = dotGit;
+ if (statSync(dotGit).isFile()) {
+ const named = /^gitdir: (.+)$/m.exec(readSmallFile(dotGit));
+ if (!named) return null;
+ dir = resolve(dirname(dotGit), named[1]!.trim());
+ }
+ const head = readSmallFile(join(dir, 'HEAD')).trim();
+ if (!/^ref: refs\//.test(head) && !/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head)) return null;
+ const common = existsSync(join(dir, 'commondir')) ? resolve(dir, readSmallFile(join(dir, 'commondir')).trim()) : dir;
+ return existsSync(join(common, 'objects')) && existsSync(join(common, 'refs')) ? canonicalFilesystemPath(dir) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A git metadata file's text, refusing anything but a small regular file: a FIFO or device there would block the read under the commit lock. */
+function readSmallFile(path: string): string {
+ const stat = statSync(path);
+ if (!stat.isFile() || stat.size > 4096) throw new Error(path + ' is not a small regular file');
+ return readFileSync(path, 'utf8');
+}
+
+/** The `git status` entries under the named paths that are directories, as path (a nested repository keeps its trailing /) to XY code. */
+export function directoryStatus(root: string, rel: string[]): Map<string, string> {
+ const dirs = rel.filter(path => { try { return lstatSync(join(root, path)).isDirectory(); } catch { return false; } });
+ const status = dirs.length ? gitOk(root, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames', '--', ...literalPathspecs(dirs)], 'status') : '';
+ return new Map(status.split('\0').filter(Boolean).map(entry => [entry.slice(3), entry.slice(0, 2)]));
+}
+
+/** The paths commit `sha` changed, each with its new mode (160000 for a gitlink, 000000 for a removal). */
+export function committedModes(root: string, sha: string): Map<string, string> {
+ const fields = gitOk(root, ['diff-tree', '--root', '-r', '--no-renames', '--no-commit-id', '-z', sha], 'diff-tree').split('\0');
+ const modes = new Map<string, string>();
+ for (let i = 0; i + 1 < fields.length; i += 2) if (fields[i]!.startsWith(':')) modes.set(fields[i + 1]!, fields[i]!.split(' ')[1]!);
+ return modes;
+}
+
+/** Named paths that are files on disk yet absent from the index (`listed`: `ls-files -v` after `git add -A`), as a file inside a nested repository is. */
+export function unindexedFiles(root: string, rel: string[], listed: string[]): string[] {
+ const indexed = new Set(listed.map(line => line.slice(2)));
+ return rel.filter(path => {
+ if (indexed.has(path)) return false;
+ try { return !lstatSync(join(root, path)).isDirectory(); } catch { return false; }
+ });
+}
+
+/**
+ * GST-2767: the checkout above `dir` when git refuses `dir` only because a `.git` file in it or above it points at no
+ * repository (a leftover from a moved submodule or worktree), and that checkout already tracks files under `dir`; else
+ * null. Git itself stages such a folder from the checkout above, so the folder is committed there instead of refused.
+ */
+export function checkoutBehindStrayGitfile(dir: string): string | null {
+ for (let at = canonicalFilesystemPath(dir); dirname(at) !== at; at = dirname(at)) {
+ try { if (!lstatSync(join(at, '.git')).isFile()) continue; } catch { continue; }
+ const top = git(dirname(at), ['rev-parse', '--show-toplevel']);
+ if (top.code !== 0) continue;
+ const root = top.stdout.trim();
+ const rel = relative(canonicalFilesystemPath(root), canonicalFilesystemPath(dir));
+ return git(root, ['ls-files', '--', ...literalPathspecs([rel])]).stdout.trim() ? root : null;
+ }
+ return null;
+}
+
+/**
+ * GST-2767: the folder whose own `.git` is the repository `top` reached through a linked `.git` (repo-a/brain/.git ->
+ * ../.git). Git then reports the linked folder as the top level and would commit its files at the wrong place in the
+ * tree, so the real work tree is the folder that holds that git directory; any other `top` is returned unchanged.
+ */
+export function worktreeOfGitdir(top: string): string {
+ const gitDir = git(top, ['rev-parse', '--absolute-git-dir']);
+ if (gitDir.code !== 0) return top;
+ const real = canonicalFilesystemPath(gitDir.stdout.trim());
+ for (let at = dirname(canonicalFilesystemPath(top)); dirname(at) !== at; at = dirname(at)) {
+ if (existsSync(join(at, '.git')) && canonicalFilesystemPath(join(at, '.git')) === real) return at;
+ }
+ return top;
+}
+
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index 7e8d333703..3b872b93ee 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -331,7 +331,13 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, params
if (checkout) {
const agents = patchManagedDurabilityBlock(root, input.sourceId, input.dryRun);
const file = relative(root, findResolverFile(root) ?? join(root, 'AGENTS.md'));
- report.agents = { ...agents, ...(agents.status === 'fixed' && !input.dryRun ? { commit: `The durability block is a non-page file: review it and commit it with gbrain git commit-push --path ${root} -m "<msg>" -- ${file}; it rides the owner's next push.` } : {}) };
+ // GST-2767: the verb itself commits nothing (the apply never moves HEAD); whenever the file it owns is not committed,
+ // including an untracked copy an earlier run left while the block is already current, it names the exact door command.
+ const status = input.dryRun ? null : await execFileBounded('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all', '--', file], { timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }) });
+ const pending = !!status && (status.error !== null || status.stdout.trim() !== '');
+ report.agents = { ...agents, file, ...(pending ? {
+ commit: `The durability block is a non-page file: review it and commit it with gbrain git commit-push --path ${root} -m "<msg>" -- ${file}; it rides the owner's next push.`,
+ commit_argv: ['gbrain', 'git', 'commit-push', '--path', root, '-m', `gbrain: durability rules for source ${input.sourceId}`, '--', file] } : {}) };
}
if (input.dryRun) {
const state = await writerAdminState(engine);
diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.ts
index 4621dfde3d..f823e27356 100644
--- a/test/cli-flag-equals.test.ts
+++ b/test/cli-flag-equals.test.ts
@@ -413,6 +413,8 @@ describe('#7619 split rules', () => {
'src/core/git-head.ts': 'git child argv',
'src/core/git-remote.ts': 'git child argv',
'src/core/git/commit-push.ts': 'git child argv',
+ 'src/core/git/skipped-paths.ts': 'git child argv',
+ 'src/core/persistence/git-durability-administration.ts': 'git child argv',
'src/core/git/range-secret-scan.ts': 'git child argv',
'src/core/git/reconcile.ts': 'git child argv',
'src/core/git/upstream-history.ts': 'git child argv',
diff --git a/test/embed-slug-args-gst2767.test.ts b/test/embed-slug-args-gst2767.test.ts
new file mode 100644
index 0000000000..b59f98f3e1
--- /dev/null
+++ b/test/embed-slug-args-gst2767.test.ts
@@ -0,0 +1,56 @@
+/**
+ * GST-2767: `gbrain embed --status --source <id> --json` answered internal_error "Page not found: <id>": embed has no
+ * --status mode, so the run fell through to the single-page branch, which took the first argument not starting with
+ * `--` as the slug, the source id. The slug is now the first argument that is neither a flag nor a flag's value, and an
+ * unknown flag is refused as unknown_flag (exit 2) before consent or any provider call.
+ * Seams: none; the real CLI against a keyless PGLite brain under a temp GBRAIN_HOME.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { embedSlugTarget } from '../src/commands/embed-slug-args.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-embed-args-'));
+beforeAll(async () => {
+ const init = await runCli(['init', '--pglite', '--no-embedding'], { home, timeoutMs: 120_000 });
+ expect(init.exitCode).toBe(0);
+}, 180_000);
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+test('the slug is never a flag value: --source, --batch-size, --priority, --max-usd and --pace-max-concurrency take the next argument', () => {
+ expect(embedSlugTarget(['--source', 'source-a', 'people/alice-example'])).toBe('people/alice-example');
+ expect(embedSlugTarget(['--batch-size', '50', '--priority', 'recent', 'people/alice-example', '--dry-run'])).toBe('people/alice-example');
+ expect(embedSlugTarget(['--max-usd', '2', '--pace-max-concurrency', '3', 'people/alice-example'])).toBe('people/alice-example');
+ expect(embedSlugTarget(['--pace=gentle', '--source=source-a', 'people/alice-example'])).toBe('people/alice-example');
+ expect(embedSlugTarget(['--source', 'source-a', '--dry-run'])).toBeUndefined();
+ expect(embedSlugTarget(['--non-interactive', 'people/alice-example'])).toBe('people/alice-example');
+ expect(embedSlugTarget(['--dry-run', '--', '-odd-slug', '--status'])).toBe('-odd-slug');
+});
+
+test('a flag no embed mode takes is refused as unknown_flag, naming the read-only way to see embedding coverage for --status', () => {
+ let caught: { code?: string; suggestion?: string; detail?: string } | undefined;
+ try { embedSlugTarget(['--status', '--source', 'source-a', '--json']); } catch (e) { caught = e as typeof caught; }
+ expect(caught?.code).toBe('unknown_flag');
+ expect(caught?.detail).toBe('--status');
+ expect(caught?.suggestion).toContain('gbrain embed --stale --dry-run --json');
+});
+
+test('CLI: embed --status --source <id> --json exits 2 with unknown_flag instead of looking the source id up as a page', async () => {
+ const r = await runCli(['embed', '--status', '--source', 'source-a', '--json'], { home, timeoutMs: 120_000 });
+ expect(r.stdout).not.toContain('Page not found');
+ expect(r.exitCode).toBe(2);
+ const e = JSON.parse(r.stdout) as { code: string; detail: string; why?: string; fix?: { next?: string; argv?: string[]; consent?: unknown[]; verify?: { argv?: string[] } } };
+ expect(e).toMatchObject({ code: 'unknown_flag', detail: '--status' });
+ expect(e.why).toContain('--status');
+ expect(e.fix).toMatchObject({ next: 'run', consent: [] });
+ expect(e.fix?.argv?.slice(0, 7)).toEqual(['gbrain', 'embed', '--stale', '--dry-run', '--json', '--source', 'source-a']);
+ expect(e.fix?.verify?.argv?.slice(0, 5)).toEqual(['gbrain', 'doctor', '--only', 'embedding_state', '--json']);
+}, 180_000);
+
+test('CLI: embed --source <id> <slug> --dry-run reads the slug, not the source id', async () => {
+ const r = await runCli(['embed', '--source', 'default', 'people/alice-example', '--dry-run', '--json'], { home, timeoutMs: 120_000 });
+ expect(r.stdout + r.stderr).toContain('people/alice-example');
+ expect(r.stdout + r.stderr).not.toContain('Page not found: default');
+}, 180_000);
diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.json
index 2c1109dca2..e2900a286b 100644
--- a/test/fixtures/goldens/cli/literal-imports.json
+++ b/test/fixtures/goldens/cli/literal-imports.json
@@ -65,6 +65,7 @@
"./commands/edges-backfill.ts"
],
"embed": [
+ "./commands/embed-slug-args.ts",
"./commands/embed.ts",
"./core/held-embedding.ts"
],
diff --git a/test/git-commit-push-skipped-paths-gst2116.test.ts b/test/git-commit-push-skipped-paths-gst2116.test.ts
index e260aaba47..0c7f89518b 100644
--- a/test/git-commit-push-skipped-paths-gst2116.test.ts
+++ b/test/git-commit-push-skipped-paths-gst2116.test.ts
@@ -97,8 +97,8 @@ test('classic: with one committable and one skipped path, the first is committed
expect(e.fix?.next).toBe('report');
expect(headBlob(f, 'people/bob-example.md')).toContain('Second version.');
expect(remoteTip(f)).toBe(head(f));
- const detail = JSON.parse(e.detail!) as { skipped: { path: string; reason: string }[]; committed: string; pushed: string };
- expect(detail.skipped).toEqual([{ path: nested, reason: 'not_staged' }]);
+ const detail = JSON.parse(e.detail!) as { skipped: { path: string; reason: string; why: string }[]; committed: string; pushed: string };
+ expect(detail.skipped).toEqual([{ path: nested, reason: 'not_staged', why: 'it sits inside the nested Git repository imports, so git add stages nothing for it' }]);
expect(detail.committed).toBe(head(f));
expect(detail.pushed).toBe(head(f));
expect(readFileSync(join(f.home, '.gbrain', 'brain-push.log'), 'utf8')).toContain(`[push] ok main ${head(f).slice(0, 7)}`);
@@ -113,8 +113,9 @@ test('classic: a skip-worktree entry under a named directory and a page inside a
expect(r.exitCode).not.toBe(0);
const e = envelope(r.stdout);
expect(e.code).toBe('commit_paths_skipped');
- const detail = JSON.parse(e.detail!) as { skipped: { path: string; reason: string }[] };
- expect(detail.skipped).toEqual([{ path: 'imports/carol-example.md', reason: 'not_staged' }, { path: 'people/bob-example.md', reason: 'skip_worktree' }]);
+ const detail = JSON.parse(e.detail!) as { skipped: { path: string; reason: string; why: string }[] };
+ expect(detail.skipped).toEqual([{ path: 'imports/carol-example.md', reason: 'not_staged', why: 'it sits inside the nested Git repository imports, so git add stages nothing for it' },
+ { path: 'people/bob-example.md', reason: 'skip_worktree', why: 'the index entry carries the skip-worktree flag, so git add does not see the edit on disk' }]);
expect(head(f)).toBe(before);
}, 60_000);
diff --git a/test/git-commit-push-symlinked-source-gst2767.test.ts b/test/git-commit-push-symlinked-source-gst2767.test.ts
new file mode 100644
index 0000000000..435ff57a5b
--- /dev/null
+++ b/test/git-commit-push-symlinked-source-gst2767.test.ts
@@ -0,0 +1,273 @@
+/**
+ * GST-2767: a source whose registered path is a symlink to a subdirectory of its Git checkout (repo-a/brain, reached
+ * as <dir>/source-a-link). A scheduled writer called `gbrain git commit-push --path <link> -- <link>/<folder>/<sub>/<year>`
+ * with new and modified tracked files under that directory. The absolute pathspec spelled through the symlink was
+ * refused as "outside the checkout", an empty `.git` left under the source path made every named directory report
+ * `commit_paths_skipped` (not_staged) although git committed it, and the refusal named no reason a person could act on.
+ * Every named path now resolves to its real place in the checkout, only a directory that is its own work tree counts as
+ * a nested repository, and each skipped path carries its reason in the JSON detail, the message and the push log.
+ * Seams: none; the real CLI against temp repositories, a bare remote and a managed-root registry under a temp GBRAIN_HOME.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getLastPushOutcome } from '../src/core/brain-repo-durability.ts';
+import { recordManagedRoots } from '../src/core/persistence/root-registry.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-symlinked-source-')));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+const identity = { GIT_AUTHOR_NAME: 'Example', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Example', GIT_COMMITTER_EMAIL: '[email protected]' };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const page = (title: string, body: string) => `---\ntitle: ${title}\n---\n${body}\n`;
+const YEAR = 'notes/daily/2026';
+
+interface Fixture { home: string; remote: string; repo: string; link: string }
+
+/** repo-a with its brain under brain/, a page already committed under the year folder, and the source path a symlink to brain/. */
+function fixture(name: string, kind: 'classic' | 'managed', linkAt: 'outside' | 'inside' = 'outside'): Fixture {
+ const remote = join(dir, `${name}.git`), repo = join(dir, `${name}-repo-a`), home = join(dir, `${name}-home`);
+ mkdirSync(home);
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
+ execFileSync('git', ['clone', '-q', remote, repo], { stdio: 'ignore' });
+ git(repo, 'checkout', '-q', '-b', 'main');
+ mkdirSync(join(repo, 'brain', YEAR), { recursive: true });
+ writeFileSync(join(repo, 'brain', YEAR, 'alice-example.md'), page('Alice', 'First version.'));
+ writeFileSync(join(repo, 'README.md'), 'Repository readme.\n');
+ git(repo, 'add', '.'); git(repo, 'commit', '-qm', 'init'); git(repo, 'push', '-q', '-u', 'origin', 'main');
+ const link = linkAt === 'outside' ? join(dir, `${name}-source-a`) : join(repo, 'current');
+ symlinkSync(join(repo, 'brain'), link);
+ if (linkAt === 'inside') writeFileSync(join(repo, '.git', 'info', 'exclude'), 'current\n');
+ if (kind === 'managed') withEnv({ GBRAIN_HOME: home }, () => { recordManagedRoots('00000000-0000-4000-8000-000000002767', [{ local_path: link, source_id: 'source-a' }]); });
+ return { home, remote, repo, link };
+}
+
+/** A modified tracked page and a new one under the year folder, as the scheduled writer leaves them. */
+function write(f: Fixture): void {
+ writeFileSync(join(f.repo, 'brain', YEAR, 'alice-example.md'), page('Alice', 'Second version.'));
+ writeFileSync(join(f.repo, 'brain', YEAR, 'bob-example.md'), page('Bob', 'New page.'));
+}
+
+const commitPush = (f: Fixture, ...paths: string[]) =>
+ runCli(['git', 'commit-push', '--json', '--path', f.link, '-m', 'write pages', '--', ...paths], { cwd: dir, home: f.home, env: identity });
+const committed = (f: Fixture, rev: string) => git(f.repo, 'ls-tree', '-r', '--name-only', rev, '--', `brain/${YEAR}`).split('\n');
+const clean = (f: Fixture) => git(f.repo, 'status', '--porcelain', '--', 'brain');
+const remoteTip = (f: Fixture) => git(f.remote, 'rev-parse', 'refs/heads/main');
+
+for (const kind of ['classic', 'managed'] as const) {
+ test(`${kind}: a directory pathspec spelled through the symlinked source path commits its new and modified files`, async () => {
+ const f = fixture(`${kind}-dir-abs`, kind);
+ write(f);
+ const r = await commitPush(f, join(f.link, YEAR));
+ expect(r.stderr + r.stdout).not.toContain('outside the checkout');
+ expect(r.exitCode).toBe(0);
+ const out = JSON.parse(r.stdout) as { outcome: string; paths: string[]; repo: string };
+ expect(out.paths).toEqual([`brain/${YEAR}`]);
+ expect(out.repo).toBe(f.repo);
+ expect(clean(f)).toBe('');
+ expect(committed(f, 'HEAD')).toEqual([`brain/${YEAR}/alice-example.md`, `brain/${YEAR}/bob-example.md`]);
+ if (kind === 'classic') expect(remoteTip(f)).toBe(git(f.repo, 'rev-parse', 'HEAD'));
+ }, 60_000);
+
+ test(`${kind}: file paths spelled through the symlinked source path, and the same paths relative to it, commit`, async () => {
+ const f = fixture(`${kind}-files`, kind);
+ write(f);
+ const abs = await commitPush(f, join(f.link, YEAR, 'alice-example.md'), join(f.link, YEAR, 'bob-example.md'));
+ expect(abs.exitCode).toBe(0);
+ expect(clean(f)).toBe('');
+ writeFileSync(join(f.repo, 'brain', YEAR, 'alice-example.md'), page('Alice', 'Third version.'));
+ const rel = await commitPush(f, `${YEAR}/alice-example.md`);
+ expect(rel.exitCode).toBe(0);
+ expect(git(f.repo, 'show', `HEAD:brain/${YEAR}/alice-example.md`)).toContain('Third version.');
+ }, 60_000);
+
+ test(`${kind}: an empty .git left under the source path is not a nested repository; the directory commits and the run succeeds`, async () => {
+ const f = fixture(`${kind}-stray-git`, kind);
+ mkdirSync(join(f.repo, 'brain', '.git'));
+ write(f);
+ const r = await commitPush(f, YEAR);
+ expect(r.stdout).not.toContain('commit_paths_skipped');
+ expect(r.exitCode).toBe(0);
+ expect(clean(f)).toBe('');
+ expect(committed(f, 'HEAD')).toContain(`brain/${YEAR}/bob-example.md`);
+ }, 60_000);
+}
+
+/** The stray `.git` shapes a source folder is left with that git itself ignores: a file, and a directory whose HEAD is broken. */
+const strays: Array<[string, (at: string) => void]> = [
+ ['a .git file pointing nowhere', at => writeFileSync(at, 'gitdir: /nonexistent/example.git\n')],
+ ['a .git directory with a broken HEAD', at => { mkdirSync(join(at, 'objects'), { recursive: true }); mkdirSync(join(at, 'refs')); writeFileSync(join(at, 'HEAD'), 'not a ref\n'); }],
+];
+for (const [shape, make] of strays) {
+ test(`${shape} under the source path and under the named folder: the folder's files commit and nothing is skipped`, async () => {
+ const f = fixture(`stray-${shape.split(' ').slice(1, 3).join('-').replace(/[^a-z-]/g, '')}`, 'managed');
+ make(join(f.repo, 'brain', '.git'));
+ make(join(f.repo, 'brain', 'notes', '.git'));
+ write(f);
+ const r = await commitPush(f, join(f.link, YEAR));
+ expect(r.stdout).not.toContain('commit_paths_skipped');
+ expect(r.exitCode).toBe(0);
+ expect(git(f.repo, 'status', '--porcelain', '--', `brain/${YEAR}`)).toBe('');
+ expect(committed(f, 'HEAD')).toEqual([`brain/${YEAR}/alice-example.md`, `brain/${YEAR}/bob-example.md`]);
+ }, 60_000);
+}
+
+test('a symlink inside the checkout: a pathspec through it names the real directory instead of failing "beyond a symbolic link"', async () => {
+ const f = fixture('inside-link', 'classic', 'inside');
+ write(f);
+ const r = await commitPush(f, join(f.link, YEAR));
+ expect(r.stdout).not.toContain('beyond a symbolic link');
+ expect(r.exitCode).toBe(0);
+ expect(clean(f)).toBe('');
+}, 60_000);
+
+test('a real nested repository: each skipped path carries its reason in the JSON detail, the message and the push log', async () => {
+ const f = fixture('nested', 'classic');
+ write(f);
+ execFileSync('git', ['init', '-q', join(f.repo, 'brain', 'imports')]);
+ writeFileSync(join(f.repo, 'brain', 'imports', 'export.csv'), 'a,b\n');
+ const r = await commitPush(f, YEAR, 'imports/export.csv');
+ expect(r.exitCode).not.toBe(0);
+ const e = JSON.parse(r.stdout) as { code: string; message: string; detail: string };
+ expect(e.code).toBe('commit_paths_skipped');
+ const detail = JSON.parse(e.detail) as { skipped: Array<{ path: string; reason: string; why: string }>; committed: string };
+ expect(detail.skipped).toEqual([{ path: 'brain/imports/export.csv', reason: 'not_staged', why: expect.stringContaining('nested Git repository brain/imports') }]);
+ expect(e.message).toContain('brain/imports/export.csv (not_staged: it sits inside the nested Git repository brain/imports');
+ expect(committed(f, 'HEAD')).toContain(`brain/${YEAR}/bob-example.md`);
+ const log = join(f.home, '.gbrain', 'brain-push.log');
+ expect(existsSync(log)).toBe(true);
+ const line = readFileSync(log, 'utf8').split('\n').find(l => l.includes('SKIPPED'));
+ expect(line).toContain('brain/imports/export.csv (not_staged: it sits inside the nested Git repository brain/imports');
+ expect((await withEnv({ GBRAIN_HOME: f.home }, () => getLastPushOutcome('main'))).status).toBe('needs_attention');
+}, 60_000);
+
+const dryRun = (f: Fixture, ...paths: string[]) =>
+ runCli(['git', 'commit-push', '--json', '--dry-run', '--path', f.link, '-m', 'write pages', '--', ...paths], { cwd: dir, home: f.home, env: identity });
+const pushLog = (f: Fixture) => { const log = join(f.home, '.gbrain', 'brain-push.log'); return existsSync(log) ? readFileSync(log, 'utf8') : ''; };
+interface Refusal { code: string; message: string; detail: string; why?: string; fix?: { argv?: string[]; next?: string } }
+const skippedOf = (x: Refusal) => (JSON.parse(x.detail) as { skipped: Array<{ path: string; reason: string; why: string }> }).skipped;
+
+for (const kind of ['classic', 'managed'] as const) {
+ test(kind + ': the field report shape, a stray .git above the named folder on a run with nothing new, succeeds and never hints at a staged removal', async () => {
+ const f = fixture(kind + '-field-quiet', kind);
+ mkdirSync(join(f.repo, 'brain', 'notes', '.git'));
+ const dry = await dryRun(f, join(f.link, YEAR));
+ const r = await commitPush(f, join(f.link, YEAR));
+ for (const out of [dry.stdout + dry.stderr, r.stdout + r.stderr]) {
+ expect(out).not.toContain('commit_paths_skipped');
+ expect(out).not.toContain('staged for removal');
+ }
+ expect(dry.exitCode).toBe(0);
+ expect(r.exitCode).toBe(0);
+ expect((JSON.parse(r.stdout) as { outcome: string }).outcome).toBe('nothing_to_commit');
+ expect(pushLog(f)).not.toContain('SKIPPED');
+ expect(committed(f, 'HEAD')).toEqual(['brain/' + YEAR + '/alice-example.md']);
+ expect(clean(f)).toBe('');
+ }, 60_000);
+
+ test(kind + ': a named folder whose tracked file is staged for removal and still on disk is refused as staged_for_removal, the dry run says the same, and nothing is re-added or removed', async () => {
+ const f = fixture(kind + '-staged-removal', kind);
+ git(f.repo, 'rm', '-q', '-r', '--cached', '--', 'brain/' + YEAR);
+ writeFileSync(join(f.repo, 'brain', YEAR, 'alice-example.md'), page('Alice', 'Second version.'));
+ const head = git(f.repo, 'rev-parse', 'HEAD'), tip = remoteTip(f);
+ const dry = await dryRun(f, join(f.link, YEAR));
+ expect(pushLog(f)).not.toContain('SKIPPED');
+ const r = await commitPush(f, join(f.link, YEAR));
+ for (const x of [dry, r]) {
+ expect(x.exitCode).toBe(1);
+ const e = JSON.parse(x.stdout) as Refusal;
+ expect(e.code).toBe('commit_paths_skipped');
+ expect(skippedOf(e)).toEqual([{ path: 'brain/' + YEAR + '/alice-example.md', reason: 'staged_for_removal', why: expect.stringContaining('staged for removal') }]);
+ expect(e.message).toContain('staged for removal');
+ expect(JSON.stringify(e)).toContain('commit-push --untrack');
+ expect(JSON.stringify(e)).toContain('restore --staged');
+ expect(e.why).toBeTruthy();
+ expect(e.fix?.next).toBe('ask_user');
+ expect((JSON.parse(e.detail) as { dry_run?: boolean }).dry_run).toBe(x === dry ? true : undefined);
+ }
+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(head);
+ expect(remoteTip(f)).toBe(tip);
+ expect(git(f.repo, 'diff', '--cached', '--name-status', '--', 'brain')).toBe('D\tbrain/' + YEAR + '/alice-example.md');
+ const line = pushLog(f).split('\n').find(l => l.includes('SKIPPED'));
+ expect(line).toContain('brain/' + YEAR + '/alice-example.md (staged_for_removal: the index holds it as staged for removal');
+ }, 60_000);
+}
+
+test('the dry run reports the same skipped path and reason as the real run for a file inside a real nested repository, and writes no push-log line', async () => {
+ const f = fixture('nested-dry', 'classic');
+ execFileSync('git', ['init', '-q', join(f.repo, 'brain', 'imports')]);
+ writeFileSync(join(f.repo, 'brain', 'imports', 'export.csv'), 'a,b\n');
+ const dry = await dryRun(f, 'imports/export.csv');
+ expect(dry.exitCode).toBe(1);
+ expect(pushLog(f)).not.toContain('SKIPPED');
+ const r = await commitPush(f, 'imports/export.csv');
+ const d = JSON.parse(dry.stdout) as Refusal, e = JSON.parse(r.stdout) as Refusal;
+ expect(d.code).toBe(e.code);
+ expect(skippedOf(d)).toEqual(skippedOf(e));
+ expect(skippedOf(d)).toEqual([{ path: 'brain/imports/export.csv', reason: 'not_staged', why: expect.stringContaining('nested Git repository brain/imports') }]);
+ expect(d.message).not.toContain('staged for removal');
+}, 60_000);
+
+/** The source folder's own .git is a link to the repository's .git (repo-a/brain/.git -> ../.git), made on purpose. */
+for (const kind of ['classic', 'managed'] as const) {
+ for (const via of ['link', 'real', 'repo'] as const) {
+ for (const change of [false, true]) {
+ test(kind + ', path via ' + via + ', ' + (change ? 'a new and an edited page' : 'nothing new') + ': a .git linked to the repository\'s own .git commits the pages at their place in the tree and reports nothing skipped', async () => {
+ const f = fixture(kind + '-gitlink-' + via + '-' + change, kind);
+ symlinkSync('../.git', join(f.repo, 'brain', '.git'));
+ if (change) write(f);
+ const at = via === 'link' ? f.link : via === 'real' ? join(f.repo, 'brain') : f.repo;
+ const named = via === 'repo' ? join(f.repo, 'brain', YEAR) : join(at, YEAR);
+ const head = git(f.repo, 'rev-parse', 'HEAD');
+ const dry = await runCli(['git', 'commit-push', '--json', '--dry-run', '--path', at, '-m', 'write pages', '--', named], { cwd: dir, home: f.home, env: identity });
+ const r = await runCli(['git', 'commit-push', '--json', '--path', at, '-m', 'write pages', '--', named], { cwd: dir, home: f.home, env: identity });
+ for (const x of [dry, r]) {
+ expect(x.stdout).not.toContain('commit_paths_skipped');
+ expect(x.stdout).not.toContain('staged for removal');
+ expect(x.exitCode).toBe(0);
+ }
+ const out = JSON.parse(r.stdout) as { outcome: string; repo: string; paths: string[] };
+ expect(out.repo).toBe(f.repo);
+ expect(out.paths).toEqual(['brain/' + YEAR]);
+ expect(git(f.repo, 'ls-tree', '-r', '--name-only', 'HEAD').split('\n')).toEqual(['README.md', ...committed(f, 'HEAD')]);
+ expect(git(f.repo, 'status', '--porcelain')).toBe('');
+ if (!change) {
+ expect(out.outcome).toBe('nothing_to_commit');
+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(head);
+ expect(committed(f, 'HEAD')).toEqual(['brain/' + YEAR + '/alice-example.md']);
+ return;
+ }
+ expect(committed(f, 'HEAD')).toEqual(['brain/' + YEAR + '/alice-example.md', 'brain/' + YEAR + '/bob-example.md']);
+ expect(git(f.repo, 'show', 'HEAD:brain/' + YEAR + '/alice-example.md')).toContain('Second version.');
+ if (kind === 'classic') expect(remoteTip(f)).toBe(git(f.repo, 'rev-parse', 'HEAD'));
+ }, 60_000);
+ }
+ }
+}
+
+test('a nested repository git refuses to open for its ownership still counts as nested, so the folder is reported skipped, never as committed', async () => {
+ const { nestedRepositoryOf } = await import('../src/core/git/skipped-paths.ts');
+ const f = fixture('nested-dubious', 'classic');
+ execFileSync('git', ['init', '-q', join(f.repo, 'brain', 'imports')]);
+ mkdirSync(join(f.repo, 'brain', 'imports', 'sub'));
+ writeFileSync(join(f.repo, 'brain', 'imports', 'sub', 'export.csv'), 'a,b\n');
+ const nested = await withEnv({ GIT_TEST_ASSUME_DIFFERENT_OWNER: '1' }, () => nestedRepositoryOf(f.repo, 'brain/imports/sub'));
+ expect(nested).toBe('brain/imports');
+ expect(nestedRepositoryOf(f.repo, 'brain/' + YEAR)).toBeNull();
+ symlinkSync('../.git', join(f.repo, 'brain', '.git'));
+ expect(nestedRepositoryOf(f.repo, 'brain/' + YEAR)).toBeNull();
+ expect(nestedRepositoryOf(f.repo, 'brain/imports/sub')).toBe('brain/imports');
+});
+
+test('a FIFO or other special file where a nested .git keeps HEAD is never read, so the check returns at once instead of blocking under the commit lock', async () => {
+ const { nestedRepositoryOf } = await import('../src/core/git/skipped-paths.ts');
+ const f = fixture('nested-fifo', 'classic');
+ mkdirSync(join(f.repo, 'brain', 'notes', '.git', 'objects'), { recursive: true });
+ mkdirSync(join(f.repo, 'brain', 'notes', '.git', 'refs'));
+ execFileSync('mkfifo', [join(f.repo, 'brain', 'notes', '.git', 'HEAD')]);
+ expect(nestedRepositoryOf(f.repo, 'brain/' + YEAR)).toBeNull();
+});
diff --git a/test/persistence-admin-git-durability.test.ts b/test/persistence-admin-git-durability.test.ts
index 5cf94d7b09..61c63693a8 100644
--- a/test/persistence-admin-git-durability.test.ts
+++ b/test/persistence-admin-git-durability.test.ts
@@ -33,6 +33,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { v234 } from '../src/core/schema-migrations/v234-persistence-git-durability.ts';
import { PERSISTENCE_GIT_DURABILITY_COLUMN_SQL, PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/persistence/schema.ts';
import { gitAsync } from './helpers/git-publication.ts';
+import { runCli } from './helpers/cli-spawn.ts';
import { withEnv } from './helpers/with-env.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
@@ -284,3 +285,25 @@ describe('[R7ii] writer git-durability verb', () => {
.rejects.toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--pat-file cannot be combined with --disable') });
}), 120_000);
});
+
+
+describe('GST-2767 the durability block the verb writes is never left untracked without the exact commit command', () => {
+ test('enable names the door command for the AGENTS.md it writes and for an untracked copy an earlier run left; the command commits it', () => isolated(async home => {
+ const root = await gitRoot(home, { remote: true });
+ const { sourceId } = await claimedSource(root);
+ const argv = ['gbrain', 'git', 'commit-push', '--path', root, '-m', `gbrain: durability rules for source ${sourceId}`, '--', 'AGENTS.md'];
+ const head = (await gitAsync(root, 'rev-parse', 'HEAD')).trim();
+ const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') }) as Record<string, any>;
+ expect(applied.agents).toMatchObject({ status: 'fixed', file: 'AGENTS.md', commit_argv: argv });
+ expect((await gitAsync(root, 'rev-parse', 'HEAD')).trim()).toBe(head);
+ // The block is already current on the next run, and the untracked file still gets the command (it used to get nothing).
+ const again = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') }) as Record<string, any>;
+ expect(again.agents).toMatchObject({ status: 'ok', commit_argv: argv, commit: expect.stringContaining('gbrain git commit-push') });
+ const run = await runCli(argv.slice(1), { home, cwd: root, timeoutMs: 120_000 });
+ expect(run.exitCode).toBe(0);
+ expect((await gitAsync(root, 'status', '--porcelain', '--untracked-files=all', '--', 'AGENTS.md')).trim()).toBe('');
+ const settled = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') }) as Record<string, any>;
+ expect(settled.agents.commit_argv).toBeUndefined();
+ }), 180_000);
+});
+
diff --git a/test/sync-git-autoinit.test.ts b/test/sync-git-autoinit.test.ts
index 82c999737c..bb285530db 100644
--- a/test/sync-git-autoinit.test.ts
+++ b/test/sync-git-autoinit.test.ts
@@ -370,3 +370,28 @@ describe('#2964: sync auto-inits a never-git-initialized default brain dir', ()
});
});
+
+describe('GST-2767: the self-heal never initializes a brain dir that sits inside another repository', () => {
+ let engine: PGLiteEngine;
+ let outer: string;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+ afterAll(async () => { await engine.disconnect(); }, 60_000);
+ afterEach(() => { if (outer) rmSync(outer, { recursive: true, force: true }); });
+
+ for (const via of ['real', 'link'] as const) {
+ test('a brain dir under a repository git cannot read (both probes throw), reached by its ' + via + ' path, is refused and gets no .git of its own', async () => {
+ await resetPgliteState(engine);
+ const { performSync } = await import('../src/commands/sync.ts');
+ const { mkdirSync, symlinkSync } = await import('fs');
+ outer = mkdtempSync(join(tmpdir(), 'gbrain-2767-outer-'));
+ mkdirSync(join(outer, 'repo-a', 'brain'), { recursive: true });
+ writeFileSync(join(outer, 'repo-a', '.git'), 'gitdir: /nonexistent-gitdir-2767\n');
+ writeFileSync(join(outer, 'repo-a', 'brain', 'page1.md'), mdPage('Page 1'));
+ const brain = via === 'real' ? join(outer, 'repo-a', 'brain') : join(outer, 'source-a');
+ if (via === 'link') symlinkSync(join(outer, 'repo-a', 'brain'), brain);
+ await engine.setConfig('sync.repo_path', brain);
+ await expect(performSync(engine, { repoPath: brain, noPull: true, noEmbed: true, full: true })).rejects.toThrow(/sits above it and git cannot open it/);
+ expect(existsSync(join(outer, 'repo-a', 'brain', '.git'))).toBe(false);
+ });
+ }
+});