Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): replay subagent and restricted-namespace failed writes under their stored authority (#5994)
garrytane84031e8bcf3
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 4f9768f8fb..52da96c0b5 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -7,7 +7,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.-- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`).+- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`). #5994: a context carrying `replayAuthority` (set only by `gbrain repair failed-writes`) gets that stored authority back from `submissionAuthority` (`replayedAuthority`): same source incarnation or refused, `databaseOnlyReason`/`takeHoldersUsed` dropped for admission to recompute, then `authorizeWrite` and page visibility against the live grant.- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`).- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex f574908563..0b253be359 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.-- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`).+- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`). `enforceSubagentSlugFence` stays fail-closed on a missing `subagentId`; its one exception (#5994) is a failed-writes replay whose `replayAuthority` is restricted and whose allow-list equals the stored non-empty `delegatedPrefixes` exactly, and the slug must still match it.- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex aba379ff65..c779e68954 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.-- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969).- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/repair/frontmatter.ts` — `gbrain repair frontmatter` (#5988), explicit-only, preview-bound, destructive consent (`--yes` with the hash, registry `consent`). Scope: Git-visible `.md`/`.mdx` per source (managed owner root or legacy `local_path`) plus every Git hold row; database side, pages whose body begins with an embedded frontmatter block or whose title is the humanized slug while the file names one. `frontmatterCandidates` builds a safe rewrite (NUL strip, nested-quote swap, `repairRecoverableFrontmatter` quoting; parsed values must be unchanged) and an interpretive one (`autoFixFrontmatter` missing close / slug line, fold, dup, unclosed, `#` rescue); both must strict-parse with no hold. `prepareRepairPublication` binds each proposal to the page fields its import would store; a refusal or canonical overlay is `needs_review`. The hash covers sources, `include_ambiguous`, `--only`/`--skip`, and per file before/after sha256, page id/revision, result digest and `rename_from`; the approved set stores no frontmatter text. Apply refuses while an unfinished managed sync cursor names a selected path, re-derives each change, then publishes through `managed_file_repair` (managed) or backup, write, `importFromFile`, hold clear and a printed commit step (legacy). Tests: `test/repair-frontmatter.test.ts`.- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 2091a45491..60134ea70d 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -587,16 +587,25 @@ and its original caller's authority is checked again first: a write thatchanged class since the preview reports `changed_since_preview`, and one whosecaller lost its grant or whose source was re-created reports`authority_revoked`; both are kept. A replay goes through the operation's-normal path on the original caller's trust lane: a write an agent sent over MCP-is prepared as a remote write again, with its take-holder and delegated-namespace limits, so it can do no more than the original could. A `put_page`+normal path on the original caller's trust lane and under its stored authority:+the same writer (an OAuth client stays that client), delegation, scopes,+take-holder and delegated namespace limits and link trust, for the same source+incarnation, checked against the live grant at admission and again at+publication. A write an agent sent over MCP is prepared as a remote write+again, so it can do no more than the original could; a grant revoked or+narrowed between admission and publication refuses the replay at publication.+A subagent or restricted-namespace write gets back the identity it recorded+(the job id of an OAuth-delegated job, or the `wiki/agents/<id>/` namespace of+a legacy subagent, which stays database-only); one that recorded neither is+confined to exactly its stored namespace allow-list. Live subagent dispatches+without a job id are still refused. A `put_page`replay is bound to the page revision the preview saw (an original `force: true`is dropped), so a page changed since the preview reports `changed_since_preview`or `conflict` instead of being overwritten. A `remember` replay targets thesubject the original resolved. Each replay uses a new request id derived fromthe failed one, so a rerun after a crash resumes the same request and a secondapply never writes it twice (`pending_elsewhere` when another writer holds that-request). Attribution names the local owner's writer for that lane. A replay the+request). Attribution names the original writer. A replay thebrain refuses reports `refused` with the code. The failed receipts stay ashistory.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3831179592..fcf78661e6 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -260,6 +260,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.0.0-wave11', text: '`gbrain repair <kind> --apply` and `gbrain doctor --remediate` now wait for each publication with the CLI write wait (`--wait`, `GBRAIN_WRITE_WAIT_MS`, `persistence.write_wait_ms`, else 30 s) instead of 5 s, so one run repairs a slow source; `--wait 0` stops at the first pending write and the rerun resumes.' },{ since: '0.0.0-wave11', text: '`gbrain sources reconcile` now identifies a private fact row by its row number and claim, so a page whose world row shares a private row\'s claim publishes instead of being refused; it now also refuses a world row that copies a stored private row\'s context (24 or more characters) verbatim, naming only the row number.' },{ since: '0.0.0-wave11', text: 'A remote put_page or put_pages entry whose content has no Timeline section is now refused with `timeline_rows_would_be_removed` when it would delete the page\'s dated entries; keep the section (get_page include_content:true) or pass `drop_timeline: true`. A local `gbrain put` without an expected revision keeps those rows; an explicitly empty `## Timeline` still deletes them, and every write that deletes rows reports `timeline_rows_removed` (count and dates).' },+ { since: '0.0.0-wave11', text: '`gbrain repair failed-writes` now replays subagent and restricted-namespace writes (they were all refused "via subagent requires ctx.subagentId"), under the original writer\'s stored authority re-checked against its live grant; replayed writes are attributed to that original writer.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 320213984b..f95019d0bb 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -265,10 +265,14 @@ export function matchesSlugAllowList(slug: string, prefixes: readonly string[]):* - Legacy default: slug must live under `wiki/agents/<subagentId>/...`* (anchored, slash-boundary \u2014 `wiki/agents/12evil/*` can't impersonate* subagent 12).+ *+ * #5994: the one exception to the missing-`subagentId` refusal is the trusted+ * local failed-writes replay of a stored restricted authority that recorded no+ * job id (`replayedAllowList`); it still checks the slug against that list.*/export function enforceSubagentSlugFence(ctx: OperationContext, slug: string, opName: string): void {if (ctx.viaSubagent !== true) return;- if (typeof ctx.subagentId !== 'number' || Number.isNaN(ctx.subagentId)) {+ if ((typeof ctx.subagentId !== 'number' || Number.isNaN(ctx.subagentId)) && !replayedAllowList(ctx)) {throw opError('permission_denied', `${opName} via subagent requires ctx.subagentId`,'This is a gbrain dispatch fault, not a caller mistake: report it to the user instead of resubmitting the write.');}@@ -286,6 +290,14 @@ export function enforceSubagentSlugFence(ctx: OperationContext, slug: string, op);}+/** A failed-writes replay of a restricted authority, confined to exactly the stored, non-empty allow-list. */+function replayedAllowList(ctx: OperationContext): boolean {+ const stored = ctx.replayAuthority;+ const list = ctx.allowedSlugPrefixes;+ return !!stored?.restrictedNamespace && !!list?.length && !!stored.delegatedPrefixes?.length+ && list.length === stored.delegatedPrefixes.length && list.every((prefix, i) => prefix === stored.delegatedPrefixes![i]);+}+/*** The subagent fence's MATCH RULE, without the throwing. Split out so the* resolved-slug re-check in put_page can ask the same question the entrydiff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 40bd825607..2ae6b49ec5 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -17,6 +17,7 @@ import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from '../p// renderer below when it loads.import type { Action, Notice } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';+import type { WriteAuthority } from '../persistence/model.ts';import type { StdioSurfaceState } from '../../mcp/surface.ts';/** Agent contract v1: the wire renderer for `fix`/`notices` in toJSON(), registered by agent-output.ts on load. */@@ -492,6 +493,17 @@ export interface OperationContext {* v0.15 behavior; pure addition, no regression).*/allowedSlugPrefixes?: string[];+ /**+ * #5994: the stored authority of a failed write that `gbrain repair+ * failed-writes` replays. Set only by that trusted local repair lane; no+ * transport, dispatcher or job hydrates it. Admission reuses it as the+ * write's authority ceiling (principal, delegation, source incarnation,+ * autoLinkTrusted), re-authorized against the live grant, instead of+ * deriving local authority from the replay context. The subagent fence+ * accepts a missing `subagentId` only with this marker and a non-empty+ * allow-list equal to the stored delegated prefixes.+ */+ replayAuthority?: WriteAuthority;/*** #4216 — defer chunk embeddings on put_page writes: importFromContent runs* noEmbed and the standing embed machinery (embed phase / phase-enddiff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 4f9b7a4516..eadd9b81a8 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -42,6 +42,7 @@ function assertSkillWriteScopes(scopes: readonly string[], operation: string, re}}export async function submissionAuthority(ctx: OperationContext, operation: string, sourceId: string, sourceIncarnation: string, slug: string): Promise<WriteAuthority> {+ if (ctx.replayAuthority) return replayedAuthority(ctx.engine, ctx.replayAuthority, operation, sourceId, sourceIncarnation, slug);if (ctx.auth?.sourceId === NO_SOURCES || sourceId === NO_SOURCES) throw noSourceGrantError(operation, ctx.auth);if (ctx.auth?.fenceProjectionDegraded || ctx.auth?.grantProjectionDegraded) deny('The grant projection is incomplete.');let principal: Principal;@@ -76,6 +77,24 @@ export async function submissionAuthority(ctx: OperationContext, operation: strireturn a;}+/**+ * #5994: a failed write replayed by `gbrain repair failed-writes` keeps its+ * original authority ceiling instead of the replay context's: the same+ * principal, delegation, scopes, holders and autoLinkTrusted, for the same+ * source incarnation, re-authorized against the live grant (a revoked or+ * narrowed grant refuses here and again at publication). Admission recomputes+ * the database-only reason; published-take bookkeeping is not carried.+ */+async function replayedAuthority(engine: SqlEngine, stored: WriteAuthority, operation: string, sourceId: string, sourceIncarnation: string, slug: string): Promise<WriteAuthority> {+ if (stored.sourceId !== sourceId || stored.sourceIncarnation !== sourceIncarnation) deny('The source was removed and re-added since the original write.');+ const { databaseOnlyReason: _reason, takeHoldersUsed: _used, ...kept } = stored;+ const a: WriteAuthority = structuredClone(kept);+ if (!prefixAllowed(a.slugPrefixes, slug)) deny('The target is outside this writer grant.');+ await authorizeWrite(engine, a, operation, slug);+ if (!skillWrite(operation)) await authorizePageVisibility(engine, a, slug);+ return a;+}+/** Caller holds source guards first. FOR SHARE serializes publication against revocation. */export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, slug: string, lock = false): Promise<void> {if (a.version !== 1 || !a.principal || !a.sourceId || !a.sourceIncarnation) deny('Missing durable write authority.');diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 7a14ff6ded..cab275cd9d 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -31,6 +31,8 @@ import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { isConnectorSourceKind } from './connector-identity.ts';export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {+ // #5994: a failed-writes replay is admitted under the original writer.+ if (ctx.replayAuthority) return { ...ctx.replayAuthority.principal };if (ctx.auth?.principal) return { ...ctx.auth.principal };const verified = currentVerifiedLocalWriter();if (verified) return verified.principal;diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 3d2ec0b616..342e487a55 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -193,11 +193,28 @@ export const failedWritesRepair: RepairHandler = {},};-/** The original caller's trust lane: a remote caller's write is prepared as a remote write, within its holder and namespace limits. */+/** The subagent job a stored restricted authority names: wave 10's delegatedJobId, else a legacy `wiki/agents/<id>/*` namespace. */+function recordedSubagentId(authority: WriteAuthority): number | undefined {+ if (authority.delegatedJobId !== undefined) return authority.delegatedJobId;+ const [only, ...rest] = authority.delegatedPrefixes ?? [];+ const id = rest.length ? undefined : /^wiki\/agents\/([1-9]\d*)\/\*$/.exec(only ?? '')?.[1];+ return id && Number.isSafeInteger(Number(id)) ? Number(id) : undefined;+}++/**+ * The original caller's trust lane: a remote caller's write is prepared as a+ * remote write, within its holder and namespace limits, under its stored+ * authority (#5994: `replayAuthority`, re-authorized live). A restricted+ * write gets back the subagent identity it recorded; a legacy sandboxed+ * subagent write (no allow-list) replays on the legacy namespace path.+ */function laneContext(ctx: OperationContext, authority: WriteAuthority): OperationContext {- if (!authority.remote) return { ...ctx, remote: false };- return { ...ctx, remote: true, takesHoldersAllowList: authority.takesHolders ? [...authority.takesHolders] : ['world'],- ...(authority.restrictedNamespace ? { viaSubagent: true, allowedSlugPrefixes: [...(authority.delegatedPrefixes ?? [])] } : {}) };+ if (!authority.remote) return { ...ctx, remote: false, replayAuthority: authority };+ const lane: OperationContext = { ...ctx, remote: true, replayAuthority: authority, takesHoldersAllowList: authority.takesHolders ? [...authority.takesHolders] : ['world'] };+ if (!authority.restrictedNamespace) return lane;+ const subagentId = recordedSubagentId(authority);+ if (authority.databaseOnlyReason === 'subagent_sandbox' && subagentId !== undefined) return { ...lane, viaSubagent: true, subagentId };+ return { ...lane, viaSubagent: true, allowedSlugPrefixes: [...(authority.delegatedPrefixes ?? [])], ...(subagentId === undefined ? {} : { subagentId }) };}/** The caller's params, without what preparation added, bound to the previewed page revision. */diff --git a/test/e2e/repair-failed-writes-5994.test.ts b/test/e2e/repair-failed-writes-5994.test.tsnew file mode 100644index 0000000000..f84509d369--- /dev/null+++ b/test/e2e/repair-failed-writes-5994.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-failed-writes-5994.test.ts'));diff --git a/test/repair-failed-writes-5994.test.ts b/test/repair-failed-writes-5994.test.tsnew file mode 100644index 0000000000..5668d401a6--- /dev/null+++ b/test/repair-failed-writes-5994.test.ts@@ -0,0 +1,212 @@+/**+ * #5994: `gbrain repair failed-writes` replays subagent and restricted-namespace+ * writes under their stored identity and authority, while the global subagent+ * fence stays fail-closed for every live dispatch. Runs on PGLite and, through+ * test/e2e, Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { enforceSubagentSlugFence } from '../src/core/ops/context.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import type { WriteAuthority, WriteRequest } from '../src/core/persistence/model.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../src/core/persistence/writer-guard-schema.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { installPre5983Guard } from './helpers/pre-5983-guard.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-replay-5994-db-'));+let closePostgres: (() => Promise<void>) | undefined;+const logger = { info() {}, warn() {}, error() {} };+const JOB = 4107;++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) {+ for (const table of ['tags', 'timeline_entries', 'takes']) await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS source_id TEXT`);+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++/** Tagged content, so the pre-#5983 guard refuses its publication and leaves a failed receipt. */+const page = (title: string) => `---\ntitle: ${title}\ntype: note\ntags: [example]\n---\n${title} body.`;++interface Brain { engine: BrainEngine; sourceId: string; local: OperationContext; remote: OperationContext }++async function brain(run: (b: Brain) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-5994-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `r5994-${randomUUID().slice(0, 8)}`;+ const local = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run({ engine, sourceId, local, remote: { ...local, remote: true } });+ });+ } finally {+ installFaultHook(undefined);+ await engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await disposePersistenceConsumer(engine);+ }+ }+}++/** Submit under the pre-#5983 guard, restore the guard, and return the failed receipt. */+async function failedWrite(b: Brain, ctx: OperationContext, slug: string): Promise<WriteRequest> {+ await installPre5983Guard(b.engine);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: page(slug), request_id: randomUUID() } }).catch(() => undefined);+ await b.engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);+ const [row] = await b.engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='failed'+ AND error_code='writer_coordinator_required'`, [b.sourceId, slug]);+ expect(row).toBeDefined();+ return row;+}++async function replay(b: Brain) {+ const scope = await resolveRepairScope(b.engine, b.sourceId);+ const preview = await (await repairRunner(b.engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: b.sourceId });+ return (await repairRunner(b.engine, { apply: true, logger })).run('failed-writes', scope,+ { explicit: true, sourceFlag: b.sourceId, expect: preview.apply_command.split('--expect ')[1] });+}++const committedReplay = async (b: Brain, slug: string) => (await b.engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests+ WHERE source_id=$1 AND slug=$2 AND state='committed' ORDER BY sequence DESC LIMIT 1`, [b.sourceId, slug]))[0];++async function delegatedClient(b: Brain): Promise<OperationContext> {+ const clientId = `delegated-job-${randomUUID()}`;+ await b.engine.executeRaw(`INSERT INTO oauth_clients (client_id,client_name,client_secret_hash,scope,source_id,bound_source_id,+ federated_read,bound_tools,delegated_namespace,delegated_slug_prefixes)+ VALUES($1,'example-delegate','fixture-hash','read agent',$2,$2,ARRAY[$2]::text[],ARRAY['mcp__gbrain__put_page'],'job',NULL)`, [clientId, b.sourceId]);+ return { ...b.remote, viaSubagent: true, subagentId: JOB,+ auth: { token: 'fixture-token', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'agent'], sourceId: b.sourceId } } as OperationContext;+}++describe('#5994 failed-writes replays subagent writes under their stored identity', () => {+ test('a restricted-namespace write with an allow-list and no recorded job replays inside that list', async () => {+ await brain(async b => {+ const failed = await failedWrite(b, { ...b.remote, viaSubagent: true, subagentId: 7, allowedSlugPrefixes: ['wiki/personal/*'] }, 'wiki/personal/note-a');+ expect(failed.authority).toMatchObject({ restrictedNamespace: true, delegatedPrefixes: ['wiki/personal/*'] });+ expect((await replay(b)).outcomes).toEqual({ replayed: 1 });+ expect(await b.engine.getTags('wiki/personal/note-a', { sourceId: b.sourceId })).toEqual(['example']);+ const replayed = await committedReplay(b, 'wiki/personal/note-a');+ expect(replayed.authority).toMatchObject({ restrictedNamespace: true, delegatedPrefixes: ['wiki/personal/*'], remote: true });+ expect({ kind: replayed.principal_kind, id: replayed.principal_id }).toEqual({ kind: failed.principal_kind, id: failed.principal_id });+ });+ }, 120_000);++ test('a legacy subagent write (job id only) replays on its own wiki/agents/<id>/ path, still sandboxed', async () => {+ await brain(async b => {+ const failed = await failedWrite(b, { ...b.remote, viaSubagent: true, subagentId: 9 }, 'wiki/agents/9/notes');+ expect(failed.authority).toMatchObject({ restrictedNamespace: true, delegatedPrefixes: ['wiki/agents/9/*'], databaseOnlyReason: 'subagent_sandbox' });+ expect((await replay(b)).outcomes).toEqual({ replayed: 1 });+ expect((await committedReplay(b, 'wiki/agents/9/notes')).authority).toMatchObject({ databaseOnlyReason: 'subagent_sandbox', delegatedPrefixes: ['wiki/agents/9/*'] });+ });+ }, 120_000);++ test('an OAuth-delegated job write replays under the original client and delegation, not local authority', async () => {+ await brain(async b => {+ const failed = await failedWrite(b, await delegatedClient(b), `wiki/agents/${JOB}/summary`);+ expect(failed.authority).toMatchObject({ delegated: true, delegatedJobId: JOB });+ expect((await replay(b)).outcomes).toEqual({ replayed: 1 });+ const replayed = await committedReplay(b, `wiki/agents/${JOB}/summary`);+ expect(replayed.principal_kind).toBe('oauth_client');+ expect(replayed.authority).toMatchObject({ principal: failed.authority.principal, delegated: true, delegatedJobId: JOB, scopes: ['read', 'agent'],+ autoLinkTrusted: failed.authority.autoLinkTrusted });+ });+ }, 120_000);++ test('a revoked or narrowed grant refuses the replay before admission', async () => {+ await brain(async b => {+ const ctx = await delegatedClient(b);+ await failedWrite(b, ctx, `wiki/agents/${JOB}/plan`);+ await b.engine.executeRaw("UPDATE oauth_clients SET bound_tools=ARRAY['mcp__gbrain__get_page'] WHERE client_id=$1", [ctx.auth!.clientId]);+ expect((await replay(b)).outcomes).toEqual({ authority_revoked: 1 });+ await b.engine.executeRaw("UPDATE oauth_clients SET bound_tools=ARRAY['mcp__gbrain__put_page'], deleted_at=now() WHERE client_id=$1", [ctx.auth!.clientId]);+ expect((await replay(b)).outcomes).toEqual({ authority_revoked: 1 });+ expect(await b.engine.getPage(`wiki/agents/${JOB}/plan`, { sourceId: b.sourceId })).toBeNull();+ });+ }, 120_000);++ test('a grant narrowed after replay admission, before publication, refuses at publication', async () => {+ await brain(async b => {+ const ctx = await delegatedClient(b);+ await failedWrite(b, ctx, `wiki/agents/${JOB}/late`);+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:prepared' || detail.operation !== 'put_page') return;+ installFaultHook(undefined);+ await b.engine.executeRaw("UPDATE oauth_clients SET delegated_namespace='prefixes', delegated_slug_prefixes=ARRAY['notes/*'] WHERE client_id=$1", [ctx.auth!.clientId]);+ });+ const applied = await replay(b);+ expect(applied.outcomes).toEqual({ refused: 1 });+ expect(applied.outcome_items?.[0]?.reason).toMatch(/^permission_denied/);+ // The replay was admitted under the original client and refused by publication's live re-check.+ const attempts = await b.engine.executeRaw<{ state: string; principal_kind: string }>(`SELECT state, principal_kind FROM persistence_requests+ WHERE source_id=$1 AND slug=$2 ORDER BY sequence`, [b.sourceId, `wiki/agents/${JOB}/late`]);+ expect(attempts).toEqual([{ state: 'failed', principal_kind: 'oauth_client' }, { state: 'failed', principal_kind: 'oauth_client' }]);+ expect(await b.engine.getPage(`wiki/agents/${JOB}/late`, { sourceId: b.sourceId })).toBeNull();+ });+ }, 120_000);+});++describe('#5994 the replay marker is narrow', () => {+ const stored = (over: Partial<WriteAuthority> = {}): WriteAuthority => ({ version: 1, principal: { kind: 'local_stdio', id: randomUUID() }, remote: true,+ sourceId: 'default', sourceIncarnation: 'inc-1', scopes: ['write'], operations: null, slugPrefixes: null,+ restrictedNamespace: true, delegatedPrefixes: ['wiki/personal/*'], ...over });+ const fenced = (ctx: Partial<OperationContext>, slug: string) => () => enforceSubagentSlugFence(ctx as OperationContext, slug, 'put_page');++ test('a live dispatch with viaSubagent and no subagentId still fails closed, with or without an allow-list', () => {+ expect(fenced({ viaSubagent: true }, 'wiki/agents/1/x')).toThrow(/requires ctx.subagentId/);+ expect(fenced({ viaSubagent: true, allowedSlugPrefixes: ['wiki/personal/*'] }, 'wiki/personal/x')).toThrow(/requires ctx.subagentId/);+ });++ test('the replay marker passes only its exact non-empty stored list, and the slug must match it', () => {+ const replay = { viaSubagent: true, allowedSlugPrefixes: ['wiki/personal/*'], replayAuthority: stored() };+ expect(fenced(replay, 'wiki/personal/x')).not.toThrow();+ expect(fenced(replay, 'notes/elsewhere')).toThrow(/not within the trusted-workspace allow-list/);+ expect(fenced({ ...replay, allowedSlugPrefixes: ['notes/*'] }, 'notes/x')).toThrow(/requires ctx.subagentId/);+ expect(fenced({ viaSubagent: true, allowedSlugPrefixes: [], replayAuthority: stored({ delegatedPrefixes: [] }) }, 'wiki/personal/x')).toThrow(/requires ctx.subagentId/);+ expect(fenced({ ...replay, replayAuthority: stored({ restrictedNamespace: false }) }, 'wiki/personal/x')).toThrow(/requires ctx.subagentId/);+ });++ test('a replayed authority refuses a reincarnated source and a resolved slug outside its namespace', async () => {+ await brain(async b => {+ const [{ incarnation }] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [b.sourceId]);+ const failed = await failedWrite(b, { ...b.remote, viaSubagent: true, subagentId: 7, allowedSlugPrefixes: ['wiki/personal/*'] }, 'wiki/personal/note-b');+ const ctx = { ...b.remote, replayAuthority: failed.authority } as OperationContext;+ await expect(submissionAuthority(ctx, 'put_page', b.sourceId, randomUUID(), 'wiki/personal/note-b')).rejects.toMatchObject({ code: 'permission_denied' });+ await expect(submissionAuthority(ctx, 'put_page', b.sourceId, incarnation, 'notes/resolved-elsewhere')).rejects.toMatchObject({ code: 'permission_denied' });+ await expect(submissionAuthority(ctx, 'put_page', b.sourceId, incarnation, 'wiki/personal/note-b')).resolves.toMatchObject({ restrictedNamespace: true });+ });+ }, 120_000);+});