Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ownership): keep ownership markers out of Git and off the remote (#5186)
garrytane6ccb0df895e
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex d4e1c699ed..e7caabc017 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -41,7 +41,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.-- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.+- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex c024308c82..44d3ebc9a8 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -45,7 +45,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; the `graduation_drain_timeout` refusal is built by `graduation-errors.ts`. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.-- `src/core/persistence/root-metadata.ts` — engine-free physical-root ownership metadata names. `isPhysicalRootMetadata` matches exactly `.gbrain-owner.json`, its `.gbrain-owner-<sha256>.json` reservation and its `.gbrain-owner.json.<uuid>.tmp` temp file (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `withoutPhysicalRootMetadata` drops `git status --porcelain` entries whose every path is such metadata, for the doctor `bootstrap_push_health` and stop-hook dirty probes: a stamp-only tree is clean, a real change beside the stamp, a rename onto or away from it and a quoted path still count. Pinned by `test/persistence-root-metadata.test.ts`.+- `src/core/persistence/root-metadata.ts` — engine-free physical-root ownership metadata names. `isPhysicalRootMetadata` matches exactly `.gbrain-owner.json`, its `.gbrain-owner-<sha256>.json` reservation and its `.gbrain-owner.json.<uuid>.tmp` temp file (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `OWNERSHIP_MARKER_GLOBS` (#5186) are the same three names in gitignore dialect: `physical-root-record.ts`'s `excludeOwnershipMarkers` appends them to `<gitdir>/info/exclude` (resolved with `git rev-parse --git-path`, idempotent, best effort) after every `writePhysicalRootStamp` / `adoptTransferredRootStamp` for the stamped directory, the root and the directory holding the reservation, `PUSH_DENY_GLOBS` denies them together with `.gbrain-bootstrap.lock/**`, the bootstrap `.gitignore` template lists them, and doctor `tracked_ownership_marker` warns when one is already in a source checkout's index. `withoutPhysicalRootMetadata` drops `git status --porcelain` entries whose every path is such metadata, for the doctor `bootstrap_push_health` and stop-hook dirty probes: a stamp-only tree is clean, a real change beside the stamp, a rename onto or away from it and a quoted path still count. Pinned by `test/persistence-root-metadata.test.ts`.- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`).diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex fca1acc2fd..4b4dea2a6a 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -8,4 +8,4 @@ guide: [backup check](../../operations/backup-check.md).Key files:- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).-- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted.+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 1812789bc5..a65f779b41 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -105,6 +105,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace, `git push` otherwise). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.+<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.+**`brain_score` shows a low "timeline density (entity and event pages)"?** The 15-point timeline component grades only linkable pages whose type's active-pack primitive is `entity` or `temporal` (people, companies, meetings, emails, events…); reference documents such as notes, writing and guides have no events and are not graded, so do not stamp "page created" rows onto them. Types the pack does not declare are still graded. Raise the score by giving those entity and event pages real timeline entries (`gbrain extract timeline`).**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.diff --git a/llms-full.txt b/llms-full.txtindex 749a7fca90..f046d1285d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9898,6 +9898,8 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p<a id="git-convergence"></a>**`gbrain doctor` warns or fails `git_convergence`, or `bootstrap_push_health` warns that a workspace is ahead?** A Git checkout the brain syncs from (a source's `local_path` or `sync.repo_path`) has commits its upstream does not have, or uncommitted changes, so the system of record on the remote is behind the brain (#5063). Commits not on the upstream warn after 6 hours and fail after 24; uncommitted changes older than 6 hours warn. Doctor compares with the local `@{u}` ref and never fetches, so it is only as fresh as the last fetch; checkouts without an upstream and connector sources are skipped. Commit and push the checkout (`gbrain sources push --path <root>` for a bootstrap workspace, `git push` otherwise). `bootstrap_push_health` no longer reports `ok` on a recent successful push while the workspace still has commits not on origin.+<a id="tracked-ownership-marker"></a>**`gbrain doctor` warns `tracked_ownership_marker`, or `gbrain sources push` / `bootstrap verify` refuses a `.gbrain-owner*.json` or `.gbrain-bootstrap.lock/` path?** An ownership marker (`.gbrain-owner.json`, the `.gbrain-owner-<hash>.json` reservation beside a root, a `.gbrain-owner.json.<uuid>.tmp` staging file) or the bootstrap lock directory was committed to a source checkout (#5186). These files are this machine's claim on the checkout, never brain content, and must not reach a remote. Since this fix gbrain appends their patterns to the checkout's `.git/info/exclude` whenever it stamps or adopts a root, the bootstrap `.gitignore` template lists them, and the push deny list refuses a tracked one while an untracked one is excluded from the commit (`excludedUntracked`). None of that un-tracks a file already in the index: run the `git -C <root> rm --cached <paths>` the check prints (the files stay on disk, gbrain keeps reading them), commit, push, then `gbrain doctor --only tracked_ownership_marker --json`. A root stamped before this fix gains the exclude rule on its next stamp or transfer; until then the deny list is the backstop, and `bootstrap verify`'s `deny_globs` treats a merely-on-disk marker as fine. If a marker already reached a remote, rotate it the same way you would any published credential: the token alone is not remote authority (the reservation that proves ownership lives outside the root), but treat the history as exposed.+**`brain_score` shows a low "timeline density (entity and event pages)"?** The 15-point timeline component grades only linkable pages whose type's active-pack primitive is `entity` or `temporal` (people, companies, meetings, emails, events…); reference documents such as notes, writing and guides have no events and are not graded, so do not stamp "page created" rows onto them. Types the pack does not declare are still graded. Raise the score by giving those entity and event pages real timeline entries (`gbrain extract timeline`).**`gbrain doctor` warns `slug_collisions`, or sync prints slug collisions?** Two or more files in a source map to the same page slug (for example `notes/Foo Bar.md` and `notes/foo-bar.md`), and only one is indexed. Rename all but one file in each group, commit, then sync.diff --git a/src/commands/doctor/checks/git-convergence.ts b/src/commands/doctor/checks/git-convergence.tsindex 866b701866..887b6b770a 100644--- a/src/commands/doctor/checks/git-convergence.ts+++ b/src/commands/doctor/checks/git-convergence.ts@@ -10,6 +10,8 @@* fail past 24 hours. Uncommitted changes warn once the oldest changed file is* older than 6 hours, never fail (they may be deliberate work in progress).* Being behind is reported, not judged: sync pulls.+ *+ * The same entry emits `tracked_ownership_marker` (#5186) for the same roots.*/import { execFileSync } from 'node:child_process';import { statSync } from 'node:fs';@@ -18,7 +20,9 @@ import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';+import { isPhysicalRootMetadata } from '../../../core/persistence/root-metadata.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { doctorVerify } from '../check-fix.ts';export const GIT_CONVERGENCE_WARN_MS = 6 * 3_600_000;export const GIT_CONVERGENCE_FAIL_MS = 24 * 3_600_000;@@ -59,7 +63,8 @@ function probe(root: string, sourceIds: string[], now: number): RootReport | { roldest_dirty_at: Number.isFinite(oldestDirty) ? new Date(oldestDirty).toISOString() : null, status };}-export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now()): Promise<Check | null> {+/** Every non-archived filesystem source root plus `sync.repo_path`, with the source ids that name each root. */+async function sourceRoots(engine: BrainEngine): Promise<Map<string, string[]>> {const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: unknown }>('SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id');const roots = new Map<string, string[]>();@@ -69,6 +74,11 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())}const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);if (repoPath && !roots.has(repoPath)) roots.set(repoPath, []);+ return roots;+}++export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now()): Promise<Check | null> {+ const roots = await sourceRoots(engine);if (!roots.size) return null;const byTop = new Map<string, RootReport | { root: string; source_ids: string[]; skipped: string }>();for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {@@ -93,16 +103,57 @@ export async function gitConvergenceCheck(engine: BrainEngine, now = Date.now())message: `Git checkouts have not converged with their upstream: ${lines.join(' | ')}. Commit and push them (gbrain sources push --path <root> for a bootstrap workspace, or git push in the checkout); this compares with the last fetched upstream and does not fetch.` };}+/**+ * #5186: `tracked_ownership_marker`, whether a source checkout has an ownership+ * marker (`.gbrain-owner.json`, the reservation beside the root, a staged stamp)+ * in its Git index. Stamping excludes the markers and `sources push` denies+ * them, but neither un-tracks a file already committed, so the fix is+ * `git rm --cached` run by the user. Markers that are merely on disk are fine.+ */+export async function trackedOwnershipMarkerCheck(engine: BrainEngine): Promise<Check | null> {+ const roots = await sourceRoots(engine);+ if (!roots.size) return null;+ const tracked: Array<{ root: string; source_ids: string[]; paths: string[] }> = [];+ let checkouts = 0;+ const seen = new Set<string>();+ for (const [root, ids] of [...roots].slice(0, MAX_ROOTS)) {+ const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();+ if (!top || seen.has(top)) continue;+ seen.add(top);+ checkouts++;+ const paths = (git(top, ['ls-files', '-z', '--cached']) ?? '').split('\0').filter(path => path && isPhysicalRootMetadata(path.slice(path.lastIndexOf('/') + 1)));+ if (paths.length) tracked.push({ root: top, source_ids: ids, paths });+ }+ const details = { checkouts, tracked, ...(roots.size > MAX_ROOTS ? { not_probed: roots.size - MAX_ROOTS } : {}) };+ if (!tracked.length) {+ return { name: 'tracked_ownership_marker', status: 'ok', details,+ message: `${checkouts} Git checkout(s) track no ownership marker (markers on disk stay untracked and are denied on push).` };+ }+ const first = tracked[0]!;+ return { name: 'tracked_ownership_marker', status: 'warn', details,+ message: `Ownership marker file(s) are tracked by Git: ${tracked.map(t => `${t.root}: ${t.paths.join(', ')}`).join(' | ')}. `+ + 'They hold this machine\'s claim on the checkout and are not content; gbrain sources push refuses them, and an ignore rule cannot un-track a file already in the index.',+ fix: { argv: ['git', '-C', first.root, 'rm', '--cached', ...first.paths], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Removes the marker from the Git index and the next commit while leaving the file on disk, where gbrain still reads it.',+ user_message: `${first.root} tracks ownership marker file(s) (${first.paths.join(', ')}). Please run the command shown, commit, and push; `+ + `the files stay on disk.${tracked.length > 1 ? ` ${tracked.length - 1} other checkout(s) need the same, see details.tracked.` : ''}`,+ verify: doctorVerify('tracked_ownership_marker') } };+}+async function runGitConvergence(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];+ const engine = connectedEngine(ctx);ctx.progress.heartbeat('git_convergence');- const check = await gitConvergenceCheck(connectedEngine(ctx));+ const check = await gitConvergenceCheck(engine);if (check) checks.push(check);+ ctx.progress.heartbeat('tracked_ownership_marker');+ const markers = await trackedOwnershipMarkerCheck(engine);+ if (markers) checks.push(markers);return checks;}export const gitConvergenceEntry: DoctorEntry = {name: 'git_convergence',- emits: ['git_convergence'],+ emits: ['git_convergence', 'tracked_ownership_marker'],run: runGitConvergence,};diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 3f44bdace8..e537d1dd01 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -49,6 +49,7 @@ import {PUSH_DENY_GLOBS, SECRET_SCAN_REFUSAL_DOCS, verifyRemotePrivacy, readPushStatuses, summarizePushStatuses,} from '../workspace-push.ts';import { shellQuote } from '../mcp-registration.ts';+import { OWNERSHIP_MARKER_GLOBS } from '../persistence/root-metadata.ts';import { FACTS_DEFAULT_VISIBILITY_KEY } from '../facts/visibility.ts';import { byteFloors } from './render.ts';import { CLAUDE_HOOK_EVENTS, claudeUserSettingsPath } from './host-specs.ts';@@ -370,13 +371,25 @@ function checkSecretScan(ws: string): VerifyCheck {}}-function checkDenyGlobs(ws: string): VerifyCheck {+const OWNERSHIP_DENY_GLOBS: readonly string[] = [...OWNERSHIP_MARKER_GLOBS, '.gbrain-bootstrap.lock/**'];++export function checkDenyGlobs(ws: string): VerifyCheck {const id = 'deny_globs';try {const { files, via } = trackedWorkspaceFiles(ws);const matches = files.filter((f) => PUSH_DENY_GLOBS.some((g) => matchesGlob(g, f)));if (via === 'git' && matches.length > 0) {- return { id, ok: false, detail: `deny-glob matches among candidate files: ${matches.slice(0, 10).join(', ')} — remove from the index (git rm --cached) before any push` };+ // #5186: an ownership marker or bootstrap lock that is merely on disk (a root+ // stamped before the exclude rule, a concurrent run's lock) is not a finding:+ // `sources push` excludes it. One in the INDEX is, with `git rm --cached` as the fix.+ const indexed = new Set(execFileSync('git', ['-C', ws, 'ls-files', '--cached', '-z'], {+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000, maxBuffer: 16 * 1024 * 1024,+ }).toString().split('\0').filter((f) => f.length > 0));+ const findings = matches.filter((f) => indexed.has(f) || !OWNERSHIP_DENY_GLOBS.some((g) => matchesGlob(g, f)));+ if (findings.length > 0) {+ return { id, ok: false, detail: `deny-glob matches among candidate files: ${findings.slice(0, 10).join(', ')} — remove from the index (git rm --cached) before any push` };+ }+ return { id, ok: true, detail: `no tracked files match the push deny list; ${matches.length} untracked ownership marker/lock file(s) stay out of every push (${matches.slice(0, 5).join(', ')})` };}return { id, ok: true, detail: via === 'git' ? 'no tracked files match the push deny list' : 'not a git repo yet — deny-glob backstop applies at push time' };} catch (e) {diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 13f7a34600..094c7830eb 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -79,7 +79,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex e0bb1c687a..9749a25b37 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -161,6 +161,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['sync_freshness',// #5063: source checkouts with commits not on their upstream or stale uncommitted changes.'git_convergence',+ // #5186: an ownership marker committed to a source checkout's Git index.+ 'tracked_ownership_marker','takes_count','takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex f5f04506ec..3a51135ea0 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -1,14 +1,46 @@import { randomUUID } from 'node:crypto';-import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';-import { dirname, isAbsolute, join, relative, sep } from 'node:path';+import { execFileSync } from 'node:child_process';+import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { OperationError } from '../ops/contract.ts';import { flushDirectory } from '../fs-durable.ts';import { digest, sha256 } from './digest.ts';import { canonicalFilesystemPath } from './root-registry.ts';-import { PHYSICAL_ROOT_MARKER } from './root-metadata.ts';+import { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER } from './root-metadata.ts';-export { PHYSICAL_ROOT_MARKER, isPhysicalRootMetadata } from './root-metadata.ts';+export { OWNERSHIP_MARKER_GLOBS, PHYSICAL_ROOT_MARKER, isPhysicalRootMetadata } from './root-metadata.ts';const RESERVATION_PREFIX = '.gbrain-owner-';+/**+ * Appends the marker globs to the exclude file of every Git checkout holding+ * `directories` (resolved with `git rev-parse --git-path`, so a linked+ * worktree writes its shared file). Idempotent; a repository-local file, never+ * committed; a missing trailing newline is repaired first. Best effort: an+ * unreadable checkout or a read-only git dir leaves the stamp in place and the+ * push deny list as the backstop.+ */+export function excludeOwnershipMarkers(directories: readonly string[]): void {+ const written = new Set<string>();+ for (const directory of directories) {+ let exclude: string;+ try {+ if (!statSync(directory).isDirectory()) continue;+ const path = execFileSync('git', ['-C', directory, 'rev-parse', '--git-path', 'info/exclude'],+ { stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }).toString().trim();+ if (!path) continue;+ exclude = resolve(directory, path);+ } catch { continue; }+ if (written.has(exclude)) continue;+ written.add(exclude);+ try {+ mkdirSync(dirname(exclude), { recursive: true });+ const body = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';+ const present = new Set(body.split('\n').map(line => line.trim()));+ const missing = OWNERSHIP_MARKER_GLOBS.filter(glob => !present.has(glob));+ if (!missing.length) continue;+ appendFileSync(exclude, `${body.length && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);+ } catch { /* best effort; the push deny list refuses a tracked marker */ }+ }+}export interface PhysicalRootReservation {version: 1; token: string; brainId: string; worktreeId: string; hostId: string;root: string; coordinationPath: string; initialDevice: string | null; initialInode: string | null; initialBirth: string | null;@@ -109,6 +141,7 @@ export function writePhysicalRootStamp(directory: string, reservation: PhysicalRroot: reservation.root, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() };createPrivate(join(directory, PHYSICAL_ROOT_MARKER), stamp);assertPhysicalRootStamp(directory, reservation);+ excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);}/** directory may be a verified staging directory; its stamp always names the final root. */export function assertPhysicalRootStamp(directory: string, reservation: PhysicalRootReservation): void {@@ -172,6 +205,7 @@ export function adoptTransferredRootStamp(directory: string, reservation: PhysicrenameSync(temporary, path); flushDirectory(directory);} finally { if (created) try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }assertPhysicalRootStamp(directory, reservation);+ excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);}export function assertPhysicalRoot(path: string, identity: { worktreeId: string; coordinationPath?: string | null }): void {try {diff --git a/src/core/persistence/root-metadata.ts b/src/core/persistence/root-metadata.tsindex 5affde2d2c..163c46280a 100644--- a/src/core/persistence/root-metadata.ts+++ b/src/core/persistence/root-metadata.ts@@ -1,6 +1,13 @@import { basename } from 'node:path';export const PHYSICAL_ROOT_MARKER = '.gbrain-owner.json';+/**+ * #5186: gitignore-dialect globs for every file `isPhysicalRootMetadata`+ * recognizes (the stamp, the reservation beside the root, a staged stamp).+ * Written to `<gitdir>/info/exclude` on stamp/adopt and denied by+ * `workspace-push`, so the ownership token never reaches a remote.+ */+export const OWNERSHIP_MARKER_GLOBS: readonly string[] = ['.gbrain-owner.json', '.gbrain-owner-*.json', '.gbrain-owner.json.*.tmp'];/** Ownership metadata gbrain writes inside or beside a managed canonical root; never brain content. */export function isPhysicalRootMetadata(name: string): boolean {diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 647ebce48c..1df9eaa0c4 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -1,4 +1,5 @@import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts';+import { OWNERSHIP_MARKER_GLOBS } from './persistence/root-metadata.ts';import { OperationError } from './ops/contract.ts';/*** workspace-push.ts — the `gbrain sources push` core: scan-gated@@ -159,9 +160,13 @@ export interface WorkspacePushOpts {holdLockMs?: number;}-/** Deny-glob backstop list [G6]. Matched with secret-scan's glob dialect. */+/**+ * Deny-glob backstop list [G6]. Matched with secret-scan's glob dialect.+ * #5186: ownership markers (`OWNERSHIP_MARKER_GLOBS`) and the bootstrap lock+ * are denied like credentials; the ownership token never reaches a remote.+ */export const PUSH_DENY_GLOBS: readonly string[] = [- '*.pglite', '.env*', '*.pem', '*.key', '.gbrain/**',+ '*.pglite', '.env*', '*.pem', '*.key', '.gbrain/**', ...OWNERSHIP_MARKER_GLOBS, '.gbrain-bootstrap.lock/**',];/** Files larger than this are neither scanned nor considered text candidates. */diff --git a/templates/bootstrap/gitignore.template b/templates/bootstrap/gitignore.templateindex 41263f96bc..a9eed64fdc 100644--- a/templates/bootstrap/gitignore.template+++ b/templates/bootstrap/gitignore.template@@ -20,6 +20,13 @@*.sqlite3*.db+# Ownership markers and the bootstrap lock — this machine's claim on the+# checkout, never content (`gbrain sources push` denies them as well)+.gbrain-owner.json+.gbrain-owner-*.json+.gbrain-owner.json.*.tmp+.gbrain-bootstrap.lock/+# Machine-local state (committed state/ files are allowlisted explicitly)state/*.localstate/*.local.jsondiff --git a/templates/bootstrap/template-repo/.gitignore b/templates/bootstrap/template-repo/.gitignoreindex 41263f96bc..a9eed64fdc 100644--- a/templates/bootstrap/template-repo/.gitignore+++ b/templates/bootstrap/template-repo/.gitignore@@ -20,6 +20,13 @@*.sqlite3*.db+# Ownership markers and the bootstrap lock — this machine's claim on the+# checkout, never content (`gbrain sources push` denies them as well)+.gbrain-owner.json+.gbrain-owner-*.json+.gbrain-owner.json.*.tmp+.gbrain-bootstrap.lock/+# Machine-local state (committed state/ files are allowlisted explicitly)state/*.localstate/*.local.jsondiff --git a/test/bootstrap-render.test.ts b/test/bootstrap-render.test.tsindex ec8989d803..04c06e7038 100644--- a/test/bootstrap-render.test.ts+++ b/test/bootstrap-render.test.ts@@ -455,6 +455,10 @@ describe('renderWorkspace — machine-specific wiring stays out of the repo [B8]const gi = readFileSync(join(ws, '.gitignore'), 'utf8');expect(gi).toContain('.mcp.json');expect(gi).toContain('.claude/settings.local.json');+ // #5186 (W14 P1.5a): ownership markers and the bootstrap lock never reach the remote.+ for (const pattern of ['.gbrain-owner.json', '.gbrain-owner-*.json', '.gbrain-owner.json.*.tmp', '.gbrain-bootstrap.lock/']) {+ expect(gi.split('\n')).toContain(pattern);+ }const gh = readFileSync(join(ws, 'GITHUB.md'), 'utf8');// The portable state/mcp.json snippet was never built — the promise is gone.expect(gh).not.toContain('state/mcp.json');diff --git a/test/bootstrap-verify-deny-globs.test.ts b/test/bootstrap-verify-deny-globs.test.tsnew file mode 100644index 0000000000..889c45941a--- /dev/null+++ b/test/bootstrap-verify-deny-globs.test.ts@@ -0,0 +1,52 @@+/**+ * #5186 (W14 P1.5a): `bootstrap verify`'s deny_globs check. An ownership+ * marker or bootstrap lock that is merely on disk is not a finding (a root+ * stamped before the exclude rule existed; `sources push` excludes it); one in+ * the index is, as is any untracked credential-class match, exactly as before.+ */+import { afterEach, beforeEach, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { checkDenyGlobs } from '../src/core/bootstrap/verify.ts';++let ws: string;+function git(...args: string[]): string {+ return execFileSync('git', ['-C', ws, ...args], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', env: process.env }).trim();+}+beforeEach(() => {+ ws = mkdtempSync(join(tmpdir(), 'gb-verify-deny-'));+ git('init', '-q', '-b', 'main');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 'Example');+ writeFileSync(join(ws, 'README.md'), 'init\n');+ git('add', 'README.md');+ git('commit', '-qm', 'init');+});+afterEach(() => { rmSync(ws, { recursive: true, force: true }); });++test('untracked markers and the bootstrap lock pass with a note; an indexed marker fails with git rm --cached', () => {+ mkdirSync(join(ws, 'brain'));+ writeFileSync(join(ws, 'brain', '.gbrain-owner.json'), '{"version":1}\n');+ writeFileSync(join(ws, `.gbrain-owner-${'0'.repeat(64)}.json`), '{"version":1}\n');+ mkdirSync(join(ws, '.gbrain-bootstrap.lock'));+ writeFileSync(join(ws, '.gbrain-bootstrap.lock', 'meta.json'), '{"pid":1}\n');+ const quiet = checkDenyGlobs(ws);+ expect(quiet.ok).toBe(true);+ expect(quiet.detail).toContain('3 untracked ownership marker/lock file(s)');++ git('add', '-f', 'brain/.gbrain-owner.json');+ const tracked = checkDenyGlobs(ws);+ expect(tracked.ok).toBe(false);+ expect(tracked.detail).toContain('brain/.gbrain-owner.json');+ expect(tracked.detail).toContain('git rm --cached');+ expect(tracked.detail).not.toContain('meta.json');+});++test('an untracked credential-class match is still a finding', () => {+ writeFileSync(join(ws, 'server.key'), 'not-a-key\n');+ const res = checkDenyGlobs(ws);+ expect(res.ok).toBe(false);+ expect(res.detail).toContain('server.key');+});diff --git a/test/doctor-ownership-marker.test.ts b/test/doctor-ownership-marker.test.tsnew file mode 100644index 0000000000..c0cc43c877--- /dev/null+++ b/test/doctor-ownership-marker.test.ts@@ -0,0 +1,89 @@+/**+ * #5186 (W14 P1.5a): `tracked_ownership_marker` warns when a source checkout+ * has an ownership marker in its Git index. An ignore rule never un-tracks a+ * file, so the fix is `git rm --cached <path>` (the push deny list is the+ * backstop). Untracked or ignored markers are fine; a source that is not a Git+ * checkout emits nothing.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { trackedOwnershipMarkerCheck } from '../src/commands/doctor/checks/git-convergence.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-tracked-marker-'));++function git(cwd: string, args: string[]): string {+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: process.env }).toString().trim();+}+function checkout(name: string): string {+ const work = join(dir, name);+ mkdirSync(work, { recursive: true });+ git(work, ['init', '-q', '-b', 'main']);+ git(work, ['config', 'user.email', '[email protected]']);+ git(work, ['config', 'user.name', 'Example']);+ writeFileSync(join(work, 'note.md'), 'first\n');+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'first']);+ return work;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++test('tracked_ownership_marker is registered and categorized', () => {+ expect(DOCTOR_CHECK_REGISTRY.some(entry => entry.emits.includes('tracked_ownership_marker'))).toBe(true);+ expect(categorizeCheck('tracked_ownership_marker')).toBe('brain');+});++test('no source emits nothing; a marker in the index warns with git rm --cached; untracked markers and plain directories are quiet', async () => {+ expect(await trackedOwnershipMarkerCheck(engine)).toBeNull();+ const clean = checkout('clean'), untracked = checkout('untracked'), tracked = checkout('tracked');+ const plain = join(dir, 'plain'); mkdirSync(plain);+ writeFileSync(join(plain, '.gbrain-owner.json'), '{"version":1}\n');+ for (const [id, path] of [['clean', clean], ['untracked', untracked], ['tracked', tracked], ['plain', plain]]) {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);+ }+ writeFileSync(join(untracked, '.gbrain-owner.json'), '{"version":1}\n');+ writeFileSync(join(untracked, `.gbrain-owner-${'0'.repeat(64)}.json`), '{"version":1}\n');++ let check = await trackedOwnershipMarkerCheck(engine);+ expect(check?.status).toBe('ok');+ expect(check?.details).toMatchObject({ checkouts: 3, tracked: [] });++ mkdirSync(join(tracked, 'brain'));+ writeFileSync(join(tracked, 'brain', '.gbrain-owner.json'), '{"version":1,"token":"not-a-real-token"}\n');+ writeFileSync(join(tracked, `.gbrain-owner-${'0'.repeat(64)}.json`), '{"version":1}\n');+ writeFileSync(join(tracked, 'brain', '.gbrain-owner.json.11111111-2222-3333-4444-555555555555.tmp'), '{}\n');+ writeFileSync(join(tracked, 'brain', 'page.md'), 'a page\n');+ git(tracked, ['add', '-A']);+ check = await trackedOwnershipMarkerCheck(engine);+ expect(check?.status).toBe('warn');+ expect(check?.message).toContain('Ownership marker file(s) are tracked by Git');+ expect(check?.message).not.toContain('not-a-real-token');+ const details = check!.details as { tracked: Array<{ root: string; source_ids: string[]; paths: string[] }> };+ expect(details.tracked).toHaveLength(1);+ expect(details.tracked[0]).toMatchObject({ root: tracked, source_ids: ['tracked'] });+ expect(details.tracked[0]!.paths.sort()).toEqual([+ `.gbrain-owner-${'0'.repeat(64)}.json`, 'brain/.gbrain-owner.json', 'brain/.gbrain-owner.json.11111111-2222-3333-4444-555555555555.tmp']);+ const fix = check!.fix as { argv: string[]; actor: string; verify: { argv: string[] } };+ expect(fix.actor).toBe('user');+ expect(fix.argv.slice(0, 5)).toEqual(['git', '-C', tracked, 'rm', '--cached']);+ expect(fix.argv.slice(5).sort()).toEqual(details.tracked[0]!.paths.sort());+ expect(fix.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'tracked_ownership_marker', '--json']);++ git(tracked, ['rm', '-q', '--cached', ...details.tracked[0]!.paths]);+ check = await trackedOwnershipMarkerCheck(engine);+ expect(check?.status).toBe('ok');+});diff --git a/test/ownership-marker-exclude.test.ts b/test/ownership-marker-exclude.test.tsnew file mode 100644index 0000000000..3bee886d62--- /dev/null+++ b/test/ownership-marker-exclude.test.ts@@ -0,0 +1,109 @@+/**+ * #5186 (W14 P1.5a): stamping or adopting an ownership marker inside a Git+ * checkout appends the marker patterns to `<gitdir>/info/exclude` once, so+ * `git add -A` and the first hardened commit never publish the ownership token.+ * The write is idempotent, resolves the exclude file through+ * `git rev-parse --git-path` (linked worktrees), and repairs a missing trailing+ * newline instead of gluing a pattern onto the last line.+ */+import { afterEach, beforeEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import {+ OWNERSHIP_MARKER_GLOBS, adoptTransferredRootStamp, physicalRootReservationPath, reservePhysicalRootRecord, writePhysicalRootStamp,+} from '../src/core/persistence/physical-root-record.ts';++let dir: string;+beforeEach(() => { dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-marker-exclude-'))); });+afterEach(() => { rmSync(dir, { recursive: true, force: true }); });++function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', ['-C', cwd, ...args], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', env: process.env }).trim();+}+function repo(name: string): string {+ const path = join(dir, name);+ mkdirSync(path, { recursive: true });+ git(path, 'init', '-q', '-b', 'main');+ git(path, 'config', 'user.email', '[email protected]');+ git(path, 'config', 'user.name', 'Example');+ writeFileSync(join(path, 'README.md'), 'init\n');+ git(path, 'add', 'README.md');+ git(path, 'commit', '-qm', 'init');+ return path;+}+function identity() {+ return { brainId: randomUUID(), worktreeId: randomUUID(), hostId: randomUUID(), coordinationPath: join(dir, 'coordination') };+}+function excludeFile(checkout: string): string {+ return resolve(checkout, git(checkout, 'rev-parse', '--git-path', 'info/exclude'));+}+function countLines(body: string, pattern: string): number {+ return body.split('\n').filter(line => line.trim() === pattern).length;+}++test('the marker globs name the stamp, the reservation and the staged stamp, nothing else', () => {+ expect(OWNERSHIP_MARKER_GLOBS).toEqual(['.gbrain-owner.json', '.gbrain-owner-*.json', '.gbrain-owner.json.*.tmp']);+});++test('stamping a root nested in a checkout excludes the stamp and the reservation beside it', () => {+ const checkout = repo('work');+ const root = join(checkout, 'brain');+ mkdirSync(root);+ const reservation = reservePhysicalRootRecord(root, identity());+ expect(existsSync(physicalRootReservationPath(root))).toBe(true);+ writePhysicalRootStamp(root, reservation);++ const body = readFileSync(excludeFile(checkout), 'utf-8');+ for (const glob of OWNERSHIP_MARKER_GLOBS) expect(countLines(body, glob)).toBe(1);+ expect(body.endsWith('\n')).toBe(true);+ const porcelain = git(checkout, 'status', '--porcelain', '--untracked-files=all');+ expect(porcelain).not.toContain('.gbrain-owner');+ expect(git(checkout, 'check-ignore', 'brain/.gbrain-owner.json')).toBe('brain/.gbrain-owner.json');+});++test('a rerun and an adopted stamp add nothing twice; a file without a trailing newline keeps its last pattern intact', () => {+ const checkout = repo('work');+ const exclude = excludeFile(checkout);+ mkdirSync(join(checkout, '.git', 'info'), { recursive: true });+ writeFileSync(exclude, '*.log\nscratch/');+ const root = join(checkout, 'brain');+ mkdirSync(root);+ const reservation = reservePhysicalRootRecord(root, identity());+ writePhysicalRootStamp(root, reservation);+ const once = readFileSync(exclude, 'utf-8');+ expect(countLines(once, 'scratch/')).toBe(1);+ expect(once.startsWith('*.log\nscratch/\n')).toBe(true);++ rmSync(join(root, '.gbrain-owner.json'));+ writePhysicalRootStamp(root, reservation);+ adoptTransferredRootStamp(root, reservation);+ expect(readFileSync(exclude, 'utf-8')).toBe(once);+});++test('a linked worktree writes the exclude file git names for it, not <root>/.git/info/exclude', () => {+ const main = repo('main');+ const linked = join(dir, 'linked');+ git(main, 'worktree', 'add', '-q', linked, '-b', 'side');+ const reservation = reservePhysicalRootRecord(linked, identity());+ writePhysicalRootStamp(linked, reservation);++ const exclude = excludeFile(linked);+ expect(exclude.startsWith(join(main, '.git'))).toBe(true);+ const body = readFileSync(exclude, 'utf-8');+ for (const glob of OWNERSHIP_MARKER_GLOBS) expect(countLines(body, glob)).toBe(1);+ expect(existsSync(join(linked, '.git', 'info', 'exclude'))).toBe(false);+ expect(git(linked, 'status', '--porcelain', '--untracked-files=all')).not.toContain('.gbrain-owner');+});++test('a root outside any checkout stamps as before and writes no exclude file', () => {+ const root = join(dir, 'plain');+ mkdirSync(root);+ const reservation = reservePhysicalRootRecord(root, identity());+ writePhysicalRootStamp(root, reservation);+ expect(existsSync(join(root, '.gbrain-owner.json'))).toBe(true);+ expect(existsSync(join(root, '.git'))).toBe(false);+ expect(existsSync(join(dir, '.git'))).toBe(false);+});diff --git a/test/workspace-push.serial.test.ts b/test/workspace-push.serial.test.tsindex d781fd84d8..40c2b9d37e 100644--- a/test/workspace-push.serial.test.ts+++ b/test/workspace-push.serial.test.ts@@ -182,9 +182,47 @@ describe('deny-glob backstop [G6]', () => {}, T);test('the deny list covers the documented classes', () => {- expect(PUSH_DENY_GLOBS).toEqual(['*.pglite', '.env*', '*.pem', '*.key', '.gbrain/**']);+ expect(PUSH_DENY_GLOBS).toEqual(['*.pglite', '.env*', '*.pem', '*.key', '.gbrain/**',+ '.gbrain-owner.json', '.gbrain-owner-*.json', '.gbrain-owner.json.*.tmp', '.gbrain-bootstrap.lock/**']);});+ // #5186 (W14 P1.5a): ownership markers and the bootstrap lock are denied like+ // credentials; the ownership token must never reach a remote.+ test('a TRACKED ownership marker hard-fails the push (#5186)', async () => {+ mkdirSync(join(work, 'brain'));+ writeFileSync(join(work, 'brain', '.gbrain-owner.json'), '{"version":1,"token":"not-a-real-token"}\n');+ writeFileSync(join(work, `.gbrain-owner-${'ab'.repeat(32)}.json`), '{"version":1}\n');+ git(work, 'add', '-A');+ git(work, 'commit', '-qm', 'oops tracked markers');+ const before = originHead(bare);+ const r = await push();+ expect(r.status).toBe('blocked_tracked_deny');+ expect(r.denyMatches?.sort()).toEqual([`.gbrain-owner-${'ab'.repeat(32)}.json`, 'brain/.gbrain-owner.json']);+ expect(originHead(bare)).toBe(before);+ }, T);++ test('UNTRACKED markers and the bootstrap lock are excluded from the commit; a page push is unchanged (#5186)', async () => {+ // A stamp at the push root itself makes the root managed (writer_coordinator_required),+ // so the markers sit on a nested root, where the first hardened commit would sweep them up.+ mkdirSync(join(work, 'brain'));+ writeFileSync(join(work, 'brain', '.gbrain-owner.json'), '{"version":1}\n');+ writeFileSync(join(work, 'brain', '.gbrain-owner.json.11111111-2222-3333-4444-555555555555.tmp'), '{"version":1}\n');+ writeFileSync(join(work, `.gbrain-owner-${'ab'.repeat(32)}.json`), '{"version":1}\n');+ mkdirSync(join(work, '.gbrain-bootstrap.lock'));+ writeFileSync(join(work, '.gbrain-bootstrap.lock', 'meta.json'), '{"pid":1}\n');+ writeFileSync(join(work, 'note.md'), 'keep me\n');+ const r = await push();+ expect(r.status).toBe('pushed');+ expect(r.excludedUntracked?.sort()).toEqual([+ '.gbrain-bootstrap.lock/meta.json', `.gbrain-owner-${'ab'.repeat(32)}.json`, 'brain/.gbrain-owner.json',+ 'brain/.gbrain-owner.json.11111111-2222-3333-4444-555555555555.tmp']);+ const shipped = git(bare, 'ls-tree', '-r', '--name-only', 'main');+ expect(shipped).toContain('note.md');+ expect(shipped).not.toContain('.gbrain-owner');+ expect(shipped).not.toContain('.gbrain-bootstrap.lock');+ expect(existsSync(join(work, 'brain', '.gbrain-owner.json'))).toBe(true);+ }, T);+test('a GITIGNORED deny match is named in excludedUntracked and never reaches the index', async () => {writeFileSync(join(work, '.gitignore'), '*.pglite\n');writeFileSync(join(work, 'brain.pglite'), Buffer.from([0, 1, 2, 0]));