Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): name a parked Git effect of a former binding apart from the current binding's empty bulk selection (#7985)
garrytan5557df554477
diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.mdindex f42bbd8338..aa3856ad2f 100644--- a/docs/architecture/key-files/core-persistence-capacity.md+++ b/docs/architecture/key-files/core-persistence-capacity.md@@ -22,4 +22,4 @@ What a managed publish costs in statements and round trips, and how it is measur- `addCodeReferenceLinks` in `src/core/engine-sql/links.ts` (#6712 L6) — a page's doc↔impl code-reference edges (`documents` from the page, `documented_by` back) in one set-based statement: endpoints resolve in the page's source under `FOR KEY SHARE`, a missing endpoint drops its edge, a repeated edge keeps its last context, and a re-import updates context and origin field in place. `import-file.ts` and `page-body/streamed-import.ts` call it once per page inside a savepoint (a failure leaves the page import intact), where each reference used to cost two sequential `addLink` statements.- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.-- `src/core/persistence/effect-settle.ts` — `gbrain sources writer settle-effects <source> (--request-id|--parked-code) [--unsettle] [--dry-run|--apply --expect <plan_hash>]` (`writer_settle_effects`, an administration extension) (#7423, #7378): records `data.settled` (and appends to `data.settlements`) on a failed Git effect no retry can move, never touching its failure, parked targets, request or bytes. It settles only on an exact-target proof re-checked under row locks at apply: each target declared `db_only` in the current binding's gbrain.yml (`sourceDbOnlyDir`), or, for an effect `guardEffectSource` refuses `source_changed` because the source moved to a new worktree (same incarnation, this host owning the active binding), a later committed and pushed Git effect of the current worktree whose `expected_hash` equals the canonical file now and a blob at the already-fetched `@{upstream}` equal to it (no fetch). Withdrawal effects, claims, open recovery records, revoked writers, replaced sources and unknown targets refuse; an effect of the current binding that is not db_only refuses `retry_instead`. The plan hash is doctor --remediate's `computePlanHash` over the brain, source, selector, owner epoch and each proof (`preview_changed` otherwise). Readers that skip settled rows: doctor `parked_effects`, `rearmWithheldTargets`, `readParkedGroups`, `readGitPushHolds`, `retryParkedPushes`/`--parked-code`, `retryIndexLockParks`, `sync status`, `failedEffectHistory`; `retryParkedEffects` reports a settled effect as `action: settled`. `retryParkedPushes` also reaches a push that failed without parked targets (#7378, `failedCodes`). Tests: `test/persistence-effect-settle.test.ts` (scenarios in `test/helpers/effect-settle-scenarios.ts`) + the Postgres arm in `test/e2e/w5-persistence-postgres.test.ts`.+- `src/core/persistence/effect-settle.ts` — `gbrain sources writer settle-effects <source> (--request-id|--parked-code) [--unsettle] [--dry-run|--apply --expect <plan_hash>]` (`writer_settle_effects`, an administration extension) (#7423, #7378): records `data.settled` (and appends to `data.settlements`) on a failed Git effect no retry can move, never touching its failure, parked targets, request or bytes. It settles only on an exact-target proof re-checked under row locks at apply: each target declared `db_only` in the current binding's gbrain.yml (`sourceDbOnlyDir`), or, for an effect `guardEffectSource` refuses `source_changed` because the source moved to a new worktree (same incarnation, this host owning the active binding), a later committed and pushed Git effect of the current worktree whose `expected_hash` equals the canonical file now and a blob at the already-fetched `@{upstream}` equal to it (no fetch). Withdrawal effects, claims, open recovery records, revoked writers, replaced sources and unknown targets refuse; an effect of the current binding that is not db_only refuses `retry_instead`. The plan hash is doctor --remediate's `computePlanHash` over the brain, source, selector, owner epoch and each proof (`preview_changed` otherwise). Readers that skip settled rows: doctor `parked_effects`, `rearmWithheldTargets`, `readParkedGroups`, `readGitPushHolds`, `retryParkedPushes`/`--parked-code`, `retryIndexLockParks`, `sync status`, `failedEffectHistory`; `retryParkedEffects` reports a settled effect as `action: settled`. `retryParkedPushes` also reaches a push that failed without parked targets (#7378, `failedCodes`). #7985: an effect outside its source's current binding (`CURRENT_BINDING_SQL` in `parked-groups.ts`, the guard's own test) gets its own `readParkedGroups` group (`former_binding`: `binding_changed` or `source_replaced`, recorded and current worktree, up to five request ids, the settle preview as `command`), doctor's per-effect command for it is `settle-effects --request-id`, `retryParkedEffects` rethrows the guard's `source_changed` naming both bindings with that preview as `fix`, and the bulk retries' `former_worktree` lists its worktree and requests (`test/orphan-effect-diagnostics-7985.test.ts`). Tests: `test/persistence-effect-settle.test.ts` (scenarios in `test/helpers/effect-settle-scenarios.ts`) + the Postgres arm in `test/e2e/w5-persistence-postgres.test.ts`.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 190b6f5fff..bf5290fa9c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -193,7 +193,13 @@ retry parks it again; or the effect belongs to a former canonical worktree (thesource was moved with set-path or a transfer), so `retry-effects --request-id`refuses it `source_changed` and `--parked-pushes`, which only reaches the currentworktree, previews nothing (it now names those effects under `former_worktree`,-and doctor's `git_push_holds` fix for them is the settle preview). Do not claim+and doctor's `git_push_holds` fix for them is the settle preview). Doctor+`parked_effects` and writer status give such effects their own parked group+(`former_binding`: the recorded worktree, the current one, the request ids and+the settle preview as `command`), and the exact retry's refusal names both+bindings with `settle-effects --request-id <id> --dry-run` as its fix; the+bulk retry's zero never covers them+([disposition](repair.md#former-binding-effects)). Do not claimor transfer the source to force the old effect through. Settle it on proofinstead: preview with `gbrain sources writer settle-effects <source> --parked-code<code> --dry-run` (or `--request-id <id>`), show the user each effect's proof, anddiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex f8d5361c1c..b1aa5ec146 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1755 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned)src/commands/config.ts 1524 ratchet 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)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 1572 ratchet 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); +1 #7973 plain_directory_sync_7973 row; +1 #7988 managed_marker_own_directory_7988 row+src/core/behavior-change-notice.ts 1573 ratchet 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); +1 #7973 plain_directory_sync_7973 row; +1 #7988 managed_marker_own_directory_7988 row; +1 #7985 former_binding_parked_group_7985 rowdiff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsindex 71d467f779..991edee958 100644--- a/src/commands/doctor/checks/parked-effects.ts+++ b/src/commands/doctor/checks/parked-effects.ts@@ -48,17 +48,21 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringtry {const scoped = `${sourceIds ? ' AND e.source_id=ANY($1::text[])' : ''} AND NOT (e.data ? 'settled')`;const params = sourceIds ? [sourceIds] : [];+ const { readParkedGroups, CURRENT_BINDING_SQL } = await import('../../../core/persistence/parked-groups.ts');const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects e WHERE e.data ? 'parked'${scoped}`, params);- const rows = await engine.executeRaw<{ request: WriteRequest; source_id: string; kind: string; state: string; parked: ParkedTarget[] }>(- `SELECT to_jsonb(r) AS request,e.source_id,e.kind,e.state,e.data->'parked' AS parked FROM persistence_effects e+ const rows = await engine.executeRaw<{ request: WriteRequest; source_id: string; kind: string; state: string; parked: ParkedTarget[]; former_binding: boolean }>(+ `SELECT to_jsonb(r) AS request,e.source_id,e.kind,e.state,e.data->'parked' AS parked,NOT ${CURRENT_BINDING_SQL} AS former_binding FROM persistence_effects eJOIN persistence_requests r ON r.id=e.request_id WHERE e.data ? 'parked'${scoped} ORDER BY e.id LIMIT ${SAMPLE}`, params);const effects = [];- for (const { request, ...row } of rows) {- const preview = `gbrain sources writer retry-effects ${row.source_id} --request-id ${request.request_id} --dry-run`;+ for (const { request, former_binding: former, ...row } of rows) {+ // #7985: an effect of a former binding is never retried (the binding guard refuses it); its exit is the settle preview.+ const preview = former && row.kind === 'git'+ ? `gbrain sources writer settle-effects ${row.source_id} --request-id ${request.request_id} --dry-run`+ : `gbrain sources writer retry-effects ${row.source_id} --request-id ${request.request_id} --dry-run`;const revoked = await revokedAuthority(engine, request);// GBRA-133: a target a .gitignore rule excludes parks again on any retry while the rule stands; its group says what to change first.const ignored = row.parked.every(target => target.error_code === 'git_target_ignored');- effects.push({ request_id: request.request_id, ...row, ...(ignored ? {} : { command: preview }), ...(revoked === null ? {} : {+ effects.push({ request_id: request.request_id, ...row, ...(former ? { former_binding: true } : {}), ...(ignored ? {} : { command: preview }), ...(revoked === null ? {} : {owner_revoked: revoked,exit: row.kind === 'git'? `the original writer is revoked; ask the user, then retry once under the brain owner's authority: gbrain sources writer retry-effects ${row.source_id} --request-id ${request.request_id} --admin-intent writer_retry_effects --expected-state <admin_state from gbrain sources writer status>`@@ -70,7 +74,7 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string// GBRA-133: per source, effects that have waited on a busy worktree for over 10 minutes (a catch-up that does not move).const stalled = await (await import('../../../core/persistence/effect-catchup.ts')).readStalledCatchups(engine, sourceIds);// GBRA-133: parked Git targets grouped per source and code, each with one bulk command instead of one per request.- const groups = await (await import('../../../core/persistence/parked-groups.ts')).readParkedGroups(engine, sourceIds);+ const groups = await readParkedGroups(engine, sourceIds);const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, parked_groups: groups, git_push_holds: pushHolds,...(stalled.length ? { stalled_catchups: stalled } : {}), ...(reclaims ? { index_lock_reclaims: reclaims } : {}) };const conflicts = pushHolds.filter(hold => hold.conflict);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d629002792..c4c18c60c8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1373,6 +1373,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.514.0', id: 'company_db_only_keep_8014', text: 'A company-brain source now keeps a live page under a declared `storage.db_only` directory when its file is not in the approved manifest, and keeps every such page while its gbrain.yml storage section is invalid, as other managed sources do; it used to delete them. The decision reads gbrain.yml at the approved commit, never the working tree.' },{ since: '0.60.514.0', id: 'redaction_marker_not_credential_7997', text: 'The transcript `labeled_credential` detector no longer reads an importer redaction marker (`login **<REDACTED:user-pattern>**`) as a typed user/password pair, so a correctly redacted page clears `gbrain transcripts audit-secrets`; a password written beside a marker is still found. The audit detector version moves to 3, so `gbrain doctor` asks for a fresh audit once.' },{ since: '0.60.516.0', id: 'plain_directory_sync_7973', text: '`gbrain sync` on a plain directory registered with `gbrain sources add --path <dir> --force` (no Git checkout at or above it) now imports its files into the source the way `gbrain import` does; it used to fail with a raw `git rev-parse` internal_error. There are no commits to diff, so a file removed from the directory keeps its page.' },+ { since: '0.60.516.0', id: 'former_binding_parked_group_7985', text: 'Doctor `parked_effects` and `gbrain sources writer status` now list parked Git effects recorded under a former canonical binding in their own parked group (`former_binding`: reason, recorded and current worktree, request ids), whose `command` is the `settle-effects` preview instead of the bulk retry that never selects them; doctor\'s per-effect command for them is `settle-effects --request-id`, the exact retry\'s `source_changed` refusal names both bindings with that preview as its fix, and the bulk retries\' `former_worktree` lists the worktree and requests. A tool reading one parked group per source and code can now see two.' },{ since: '0.60.516.0', id: 'managed_marker_own_directory_7988', text: 'Managed persistence now marks a root that no Git checkout tracks (a connector clone or plain directory under a dotfiles home) in its own directory instead of in the enclosing repository, so legacy writers elsewhere in that repository are no longer refused, and the autopilot HEAD probe no longer reads the enclosing repository\'s HEAD for it. A marker an older release already wrote there stays until `gbrain sources writer deactivate` removes it (preview with `--dry-run --json`; activate again afterwards), and a write it refuses now says so.' },];diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.tsindex 88b3df1d28..2e17d8c7d3 100644--- a/src/core/persistence/effect-retry.ts+++ b/src/core/persistence/effect-retry.ts@@ -16,6 +16,7 @@ import type { WriteRequest } from './model.ts';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';import { declarePersistenceProtocol } from './protocol.ts';import { writerAdminState } from './admin-intent.ts';+import { getWorktreeBinding } from './ownership.ts';const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its blocking, retrying and parked effects, read-only.`,{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });@@ -132,7 +133,16 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,tracked.some(effect => effect.kind === 'git' && effect.state === 'failed' && effect.error_code === 'targets_parked')) : null;const effects = [];for (const selected of tracked) {- await guardEffectSource(tx, selected, hostId);+ try { await guardEffectSource(tx, selected, hostId); }+ catch (error) {+ if (!(error instanceof OperationError) || error.code !== 'source_changed') throw error;+ // #7985: an effect of a former binding: name its recorded binding, the current one and the settle preview, never only "inspect".+ const current = await getWorktreeBinding(tx, sourceId, hostId);+ throw opError('source_changed', error.message,+ `Request ${request.request_id}'s ${selected.kind} effect was recorded under worktree ${selected.worktree_id ?? '(none)'} of source incarnation ${selected.source_incarnation}; source ${sourceId} is now bound to ${current ? `worktree ${current.worktree_id} of incarnation ${current.source_incarnation}` : 'no worktree'}. Retry cannot run it, and the bulk retry previews (--parked-code, --parked-pushes) select only the current binding's effects, so their zero does not cover it. Preview settling it on proof: the fix command settles it or names what blocks it. Do not claim or transfer the source to force it through.`,+ { fix: readFix(`Previews settling request ${request.request_id}'s effects of a former binding of source ${sourceId} on proof, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'settle-effects', sourceId, '--request-id', request.request_id, '--dry-run', '--json'] }) });+ }const [effect] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);const parked = effect.data.parked ?? [];const summary = { kind: effect.kind, error_code: effect.error_code, parked_targets: parked.length, targets: parked.slice(0, 20), retried: effect.data.retried ?? 0 };diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.tsindex 081083a554..9d7b9a86c7 100644--- a/src/core/persistence/git-durability-administration.ts+++ b/src/core/persistence/git-durability-administration.ts@@ -182,15 +182,16 @@ const HELD_ON_CODES = `e.error_code=ANY($2::text[]) OR e.error_code='targets_par* resolution: they are named with the settle preview that can account for them.*/async function formerWorktreeHolds(engine: BrainEngine, sourceId: string, worktreeId: string, codes: readonly string[]) {- const [row] = await engine.executeRaw<{ effects: number; code: string | null }>(`SELECT count(*)::int AS effects,+ const [row] = await engine.executeRaw<{ effects: number; code: string | null; worktree_ids: string[]; requests: string[] }>(`SELECT count(*)::int AS effects,min(CASE WHEN e.error_code=ANY($2::text[]) THEN e.error_code ELSE (SELECT min(p->>'error_code') FROM jsonb_array_elements(e.data->'parked') p- WHERE p->>'error_code'=ANY($2::text[])) END) AS code- FROM persistence_effects e WHERE e.source_id=$1 AND e.worktree_id IS DISTINCT FROM $3::uuid AND e.kind='git' AND e.state='failed'+ WHERE p->>'error_code'=ANY($2::text[])) END) AS code,+ array_agg(DISTINCT e.worktree_id::text) AS worktree_ids, (array_agg(DISTINCT r.request_id::text))[1:5] AS requests+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.source_id=$1 AND e.worktree_id IS DISTINCT FROM $3::uuid AND e.kind='git' AND e.state='failed'AND NOT (e.data ? 'settled') AND (${HELD_ON_CODES})`, [sourceId, [...codes], worktreeId]);if (!row?.effects || !row.code) return {};const command = ['gbrain', 'sources', 'writer', 'settle-effects', sourceId, '--parked-code', row.code, '--dry-run'];- return { former_worktree: { effects: Number(row.effects), command,- why: `${row.effects} held Git effect(s) of source ${sourceId} belong to a former canonical worktree: retry cannot run them (their binding changed) and this preview does not resolve them. Preview settling them on proof: ${command.join(' ')}` } };+ return { former_worktree: { effects: Number(row.effects), command, worktree_ids: row.worktree_ids, requests: row.requests,+ why: `${row.effects} held Git effect(s) of source ${sourceId} (requests ${row.requests.join(', ')}) belong to former canonical worktree ${row.worktree_ids.join(', ')}, not the current ${worktreeId}: retry cannot run them (their binding changed) and this preview does not resolve them, so its counts do not include them. Preview settling them on proof: ${command.join(' ')}` } };}export type ParkedPushRefusal = { source_id: string; request_id: string; code: string; message: string; suggestion?: string; fix?: Action };diff --git a/src/core/persistence/parked-groups.ts b/src/core/persistence/parked-groups.tsindex 9552bc646b..007f2ff89b 100644--- a/src/core/persistence/parked-groups.ts+++ b/src/core/persistence/parked-groups.ts@@ -1,29 +1,59 @@import type { BrainEngine } from '../engine.ts';import { GIT_PUSH_CODES } from './git-push-holds.ts';+/**+ * #7985: parked Git effects recorded under a binding the source no longer has. `binding_changed`: the source moved to+ * another worktree (or its binding names another incarnation), so the binding guard refuses a retry `source_changed`;+ * `source_replaced`: the source was archived, removed or re-created since. The bulk retry of the current binding never+ * selects them, so its zero is not their clearance.+ */+export interface FormerBinding { reason: 'binding_changed' | 'source_replaced'; worktree_ids: string[]; current_worktree_id: string | null; requests: string[] }+/** GBRA-133: one source's parked Git targets of one error code, with the one command that retries them all. */-export interface ParkedGroup { source_id: string; code: string; effects: number; targets: number; rule?: string; command: string[]; next: string }+export interface ParkedGroup { source_id: string; code: string; effects: number; targets: number; rule?: string; command: string[]; next: string; former_binding?: FormerBinding }++/** SQL that is true when effect `e` belongs to its source's current binding: the binding guard's own test. */+export const CURRENT_BINDING_SQL = `(e.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_source_bindings sb+ WHERE sb.source_id=e.source_id AND sb.worktree_id=e.worktree_id AND sb.source_incarnation::text=e.source_incarnation::text))`;/*** Parked Git targets per source and error code (doctor `parked_effects`, `sources writer status`). Each group names its* bulk retry (`--parked-pushes` for push codes, `--parked-code <code>` otherwise) as a preview. A `git_target_ignored`* group names the .gitignore rule and says the rule has to change first: a retry while it stands parks again. Other groups* also name the settle preview (#7423, #7378) for targets a retry can never move; settled effects are not counted.+ * #7985: effects of a former binding form their own group (`former_binding`) naming their recorded worktree, the current+ * one, up to five request ids and the settle preview, never the bulk retry that cannot select them.*/export async function readParkedGroups(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<ParkedGroup[]> {- const rows = await engine.executeRaw<{ source_id: string; code: string; effects: number; targets: number; rule: string | null }>(- `SELECT e.source_id, p->>'error_code' AS code, count(DISTINCT e.id)::int AS effects, count(*)::int AS targets, min(p->>'rule') AS rule- FROM persistence_effects e CROSS JOIN LATERAL jsonb_array_elements(e.data->'parked') p- WHERE e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND jsonb_typeof(e.data->'parked')='array' AND NOT (e.data ? 'settled')- AND ($1::text[] IS NULL OR e.source_id=ANY($1::text[]))- GROUP BY 1, 2 ORDER BY 1, 2`, [sourceIds ?? null]);- return rows.map(({ rule, ...row }) => {+ const rows = await engine.executeRaw<{ source_id: string; code: string; former: FormerBinding['reason'] | null; effects: number; targets: number;+ rule: string | null; worktree_ids: string[]; current_worktree_id: string | null; requests: string[] }>(+ `WITH parked AS (+ SELECT e.id, e.source_id, e.worktree_id, r.request_id, p->>'error_code' AS code, p->>'rule' AS rule,+ CASE WHEN ${CURRENT_BINDING_SQL} THEN NULL+ WHEN EXISTS (SELECT 1 FROM sources src WHERE src.id=e.source_id AND NOT src.archived AND src.incarnation::text=e.source_incarnation::text)+ THEN 'binding_changed' ELSE 'source_replaced' END AS former+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id CROSS JOIN LATERAL jsonb_array_elements(e.data->'parked') p+ WHERE e.kind='git' AND e.state='failed' AND e.error_code='targets_parked' AND jsonb_typeof(e.data->'parked')='array' AND NOT (e.data ? 'settled')+ AND ($1::text[] IS NULL OR e.source_id=ANY($1::text[])))+ SELECT source_id, code, former, count(DISTINCT id)::int AS effects, count(*)::int AS targets, min(rule) AS rule,+ array_agg(DISTINCT worktree_id::text) AS worktree_ids, (array_agg(DISTINCT request_id::text))[1:5] AS requests,+ (SELECT sb.worktree_id::text FROM persistence_source_bindings sb WHERE sb.source_id=parked.source_id) AS current_worktree_id+ FROM parked GROUP BY source_id, code, former ORDER BY source_id, code, former NULLS FIRST`, [sourceIds ?? null]);+ return rows.map(({ rule, former, worktree_ids, current_worktree_id, requests, ...row }) => {+ if (former) {+ const command = ['gbrain', 'sources', 'writer', 'settle-effects', row.source_id, '--parked-code', row.code, '--dry-run'];+ const recorded = `${row.effects} parked Git effect(s) of source ${row.source_id} (requests ${requests.join(', ')}) were recorded under worktree ${worktree_ids.join(', ')}`;+ const next = former === 'binding_changed'+ ? `${recorded}, a former canonical binding: the source is now bound to ${current_worktree_id ?? 'no worktree'}. retry-effects refuses them (source_changed) and the bulk retry selects none of them, so its zero is not a clearance. Preview settling them on proof: ${command.join(' ')}; an effect it refuses stays parked and its refusal names what is missing. Never claim or transfer the source to force them through.`+ : `${recorded}, under an earlier incarnation of the source (archived, removed or re-created since), so they owe nothing to the current source: neither retry-effects nor settle-effects runs them (settle refuses source_replaced). They stay parked as history; never re-create, claim or transfer the source to force them through.`;+ return { ...row, command, next, former_binding: { reason: former, worktree_ids, current_worktree_id, requests } };+ }const push = (GIT_PUSH_CODES as readonly string[]).includes(row.code);const command = ['gbrain', 'sources', 'writer', 'retry-effects', row.source_id, ...(push ? ['--parked-pushes'] : ['--parked-code', row.code]), '--dry-run'];const settle = `gbrain sources writer settle-effects ${row.source_id} --parked-code ${row.code} --dry-run`;const next = row.code === 'git_target_ignored'? `Git ignores these files${rule ? ` (${rule})` : ''}, so a retry parks them again while the rule stands. Change the rule and commit it, then preview ${command.join(' ')} and rerun it without --dry-run; or keep the files out of Git and leave them parked (their pages are committed in the database).`- : `Fix the cause, then preview ${command.join(' ')} and rerun it without --dry-run to authorize one more attempt per target. A target that can never succeed (now declared db_only, or left in a former canonical worktree) settles on proof instead: preview ${settle}.`;+ : `Fix the cause, then preview ${command.join(' ')} and rerun it without --dry-run to authorize one more attempt per target. A target that can never succeed (now declared db_only) settles on proof instead: preview ${settle}.`;return { ...row, ...(rule ? { rule } : {}), command, next };});}diff --git a/test/orphan-effect-diagnostics-7985.test.ts b/test/orphan-effect-diagnostics-7985.test.tsnew file mode 100644index 0000000000..222b4c8489--- /dev/null+++ b/test/orphan-effect-diagnostics-7985.test.ts@@ -0,0 +1,102 @@+/**+ * #7985: a parked Git effect recorded under a former canonical binding is refused by the exact retry (source_changed,+ * the guard stays) and is never selected by the bulk retry of the current binding. The diagnostics now tell the two apart:+ * the parked groups (doctor \`parked_effects\`, \`sources writer status\`) give such effects their own group naming the+ * recorded worktree, the current one, the requests and the settle preview; doctor's per-effect command is that preview;+ * the exact retry refusal names both bindings and the settle preview; the bulk retry names the effects it leaves out.+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { cpSync, writeFileSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { retryParkedEffects } from '../src/core/persistence/effect-retry.ts';+import { retrySourceParkedCode } from '../src/core/persistence/git-durability-administration.ts';+import { settleEffects } from '../src/core/persistence/effect-settle.ts';+import { readParkedGroups } from '../src/core/persistence/parked-groups.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { isPhysicalRootMetadata } from '../src/core/persistence/physical-root.ts';+import { checkParkedEffects } from '../src/commands/doctor/checks/parked-effects.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { durableGitRepo } from './helpers/git-publication.ts';++const backends: Array<string | undefined> = [undefined, ...(process.env.DATABASE_URL ? [process.env.DATABASE_URL] : [])];+const put = async (ctx: OperationContext, slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${body}\n`,+ ...await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }).then(page => page ? { expected_revision: page.revision } : {}) } });+async function sql(engine: BrainEngine, statement: string, params: unknown[]) {+ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(statement, params); });+}+/** Parks the newest Git effect of a page on git_unavailable (the resident consumer stopped); returns its ids and worktree. */+async function park(engine: BrainEngine, slug: string) {+ await disposePersistenceConsumer(engine);+ const [effect] = await engine.executeRaw<{ id: number; request_id: string; worktree_id: string }>(`SELECT e.id,r.request_id::text AS request_id,+ e.worktree_id::text AS worktree_id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE e.kind='git' AND r.slug=$1 ORDER BY e.id DESC LIMIT 1`, [slug]);+ await sql(engine, `UPDATE persistence_effects SET state='failed',error_code='targets_parked',execution_token=NULL,claim_expires_at=NULL,+ data=data||jsonb_build_object('parked',jsonb_build_array(jsonb_build_object('slug',$2::text,'error_code','git_unavailable'))) WHERE id=$1`, [effect!.id, slug]);+ return effect!;+}++describe.each(backends.map(url => [url ? 'postgres' : 'pglite', url] as const))('#7985 effects of a former binding (%s)', (_name, url) => {+ test('the diagnostics name a former-binding effect, its recorded binding and the settle preview, apart from the current binding', () => managedBrain(async ({ engine, ctx, root }) => {+ await put(ctx, 'aa/page', 'Parked under the old binding.');+ const orphan = await park(engine, 'aa/page');+ const old = (await getWorktreeBinding(engine, 'default'))!;+ expect(orphan.worktree_id).toBe(old.worktree_id);++ const moved = join(dirname(root), 'moved');+ cpSync(root, moved, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) });+ await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'default', path: moved });+ const current = (await getWorktreeBinding(engine, 'default'))!;+ expect(current.worktree_id).not.toBe(old.worktree_id);+ await put(ctx, 'bb/page', 'Parked under the current binding.');+ const live = await park(engine, 'bb/page');+ expect(live.worktree_id).toBe(current.worktree_id);++ const settleCode = ['gbrain', 'sources', 'writer', 'settle-effects', 'default', '--parked-code', 'git_unavailable', '--dry-run'];+ const groups = await readParkedGroups(engine, ['default']);+ expect(groups).toMatchObject([+ { source_id: 'default', code: 'git_unavailable', effects: 1, targets: 1, command: ['gbrain', 'sources', 'writer', 'retry-effects', 'default', '--parked-code', 'git_unavailable', '--dry-run'] },+ { source_id: 'default', code: 'git_unavailable', effects: 1, targets: 1, command: settleCode,+ former_binding: { reason: 'binding_changed', worktree_ids: [old.worktree_id], current_worktree_id: current.worktree_id, requests: [orphan.request_id] } },+ ]);+ expect(groups[0]).not.toHaveProperty('former_binding');+ expect(groups[1]!.next).toContain('the bulk retry selects none of them, so its zero is not a clearance');+ expect(groups[1]!.next).toContain(orphan.request_id);++ const doctor = await checkParkedEffects(engine);+ expect(doctor.details).toMatchObject({ parked_effects: 2, parked_groups: groups });+ const listed = (doctor.details as { effects: Array<{ request_id: string; command?: string; former_binding?: boolean }> }).effects;+ expect(listed.find(effect => effect.request_id === orphan.request_id)).toMatchObject({ former_binding: true,+ command: `gbrain sources writer settle-effects default --request-id ${orphan.request_id} --dry-run` });+ expect(listed.find(effect => effect.request_id === live.request_id)).toMatchObject({+ command: `gbrain sources writer retry-effects default --request-id ${live.request_id} --dry-run` });+ expect(listed.find(effect => effect.request_id === live.request_id)).not.toHaveProperty('former_binding');++ const refusal = await retryParkedEffects(engine, 'default', orphan.request_id, true).then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'source_changed', message: 'The effect canonical binding changed.',+ fix: { argv: ['gbrain', 'sources', 'writer', 'settle-effects', 'default', '--request-id', orphan.request_id, '--dry-run', '--json'] } });+ expect(refusal.suggestion).toContain(`worktree ${old.worktree_id}`);+ expect(refusal.suggestion).toContain(`now bound to worktree ${current.worktree_id}`);++ const bulk = await retrySourceParkedCode(engine, 'default', 'git_unavailable', true);+ expect(bulk).toMatchObject({ requests: 1, queued: 1, refused: [],+ former_worktree: { effects: 1, command: settleCode, worktree_ids: [old.worktree_id], requests: [orphan.request_id] } });+ expect(String((bulk.former_worktree as { why: string }).why)).toContain('its counts do not include them');++ expect(await settleEffects(engine, { sourceId: 'default', requestId: orphan.request_id })).toMatchObject({ settleable: 0, refused: 1,+ effects: [{ request_id: orphan.request_id, action: 'refused', refusal: { code: 'no_covering_receipt' } }] });++ await sql(engine, 'UPDATE persistence_effects SET source_incarnation=$2::uuid WHERE id=$1', [orphan.id, randomUUID()]);+ const replaced = (await readParkedGroups(engine, ['default']))[1]!;+ expect(replaced).toMatchObject({ command: settleCode, former_binding: { reason: 'source_replaced', requests: [orphan.request_id] } });+ expect(replaced.next).toContain('earlier incarnation of the source');+ }, { databaseUrl: url, setup: ({ root }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); } }), 240_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 629a45ec8f..e8571d6396 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -274,6 +274,7 @@ test/oneshot-housekeeping-cli.test.tstest/origin-guard-6948.test.tstest/origin-twin-sequence-7150.test.tstest/origin-twins-6948.test.ts+test/orphan-effect-diagnostics-7985.test.tstest/overwritten-edits-6712.test.tstest/owner-refusal.test.tstest/pack-relation-direction-engine.test.ts