Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
repair accepted-takes: restore takes the v0.60.253.0 accept removed, from receipts and page versions; CHANGELOG + BEHAVIOR_CHANGES
garrytan61d20394429a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 21d3d61fd6..f04437df02 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,38 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.254.0] - 2026-10-16++**Accepting an agent's strike-through on a take you confirmed no longer deletes the take, and a repair brings back takes the last release deleted that way.** In v0.60.253.0, when an agent struck through a take you had confirmed, or changed its kind, gbrain held the change for you. Accepting it with `gbrain trust confirm` removed the whole take from the page and from search, instead of striking it through. This release applies exactly the change you accepted. If you accepted one of these on v0.60.253.0, one command finds and restores those takes from the page's own history.++### How to check and repair++```bash+gbrain repair accepted-takes # lists every take the records prove was removed this way; writes nothing+gbrain repair accepted-takes --apply --expect <preview-hash> # restores exactly that list+```++### What you'd see++| Situation | v0.60.253.0 | Now |+|---|---|---|+| You accept an agent's strike-through of a confirmed take | the take was deleted from the page and the index | the take is struck through, as the agent wrote it |+| You accept an agent's kind or holder change to a confirmed take | the take was deleted | the take gets the new kind or holder |+| The take had a grade in its fence | the accept refused; nothing was lost | unchanged |+| You accept a held change on a page stored in segments | refused with `page_body_segmented` | applied, as on any page |++### Things to watch++- **Only takes accepted on v0.60.253.0 can be affected,** and only a strike-through or a same-claim kind or holder change. A sync or a later publish does not bring them back: the page no longer carries the row, so run the repair.+- **What the repair cannot restore:** a grade or resolution stored only in the database (none of the records hold it), the take's id and its embedding (re-embedded). The restored take carries the trust tier of the write you accepted, which is what a correct accept leaves.+- A removal you asked for with `takes_remove` still refuses on a page stored in segments, as every takes command does.++### Itemized changes++- `src/core/trust/held-removals.ts`: only a proposal filed by `takes_remove` reruns as an owner `takes_remove`; every other held take change applies the page's fence row. A segmented page within the single-string ceiling is read from its segments (`materializeSegmentedBody`).+- `src/core/repair/accepted-takes.ts` (new): `gbrain repair accepted-takes`, explicit-only and preview-bound. Evidence per take: the accepted `forget` proposal, the `takes_remove` receipt with its `trust_accept`, the page version that receipt archived and the live reservation row.+- Tests: `test/trust-held-removals.test.ts` adds the strike-through and kind-change accept, the segmented-page accept and the repair (managed and unmanaged), on PGLite and Postgres.+## [0.60.253.0] - 2026-10-15**A note an agent writes can no longer quietly erase a take or timeline entry you confirmed. And when something an agent derived from is downgraded, everything derived from it is downgraded too.** Until now, an agent rewriting a page could drop or reword a take you had confirmed, or a dated timeline line, and the stored row went with it. The same happened when the takes cleanup or the timeline cleanup decided a row was gone. Now the row stays exactly as it was, and you get a proposal to approve or dismiss. Separately, when a page or fact loses trust (an agent edited it, or you lowered it), the facts, takes and pages computed from it now drop to match. Raising trust never lifts them back up on its own.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex b8dea7037c..30a5e9f887 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -131,6 +131,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `request-indexes` | `persistence_request_indexes` | Creates a missing managed sync request index, or drops an INVALID one (left by an interrupted concurrent build) and rebuilds it, on a brain whose schema version is already current. Postgres builds each index `CONCURRENTLY`, one at a time, so writes continue; PGLite builds inline. It changes no user data, takes no journal admission and runs brain-wide (`--source` does not narrow it). See [managed sync request indexes](#request-indexes). | `building`: an index another session is still building; it is never dropped. || `connector-fences` | none (a `connector_fence_below_timeline` refusal names it) | Moves a facts or takes fence that sits below the timeline sentinel of a Google or GitHub page into the page body through a revision-bound `put_page`, so the connector's next re-render carries the fence instead of refusing. Then re-attempt the held item with `gbrain sources retry-held <source>`. | `kept_ambiguous_pages`: pages whose fences are duplicated, unbalanced or unparseable. Move the fence by hand: read the page, place the fence above the `<!-- timeline -->` line, and save it with the current `expected_revision`. || `take-supersession` | none | Rebuilds `takes.superseded_by` for supersession chains written before the pointer moved onto the old fence row (#5886). Each struck take is linked to the row that replaced it only from evidence: a committed `takes_supersede` receipt, a stored `superseded_by`, or a row carrying the old `superseded by #<own row>` pointer with exactly one possible predecessor. The pointer is written onto the old row (`<source>; superseded by #N`) and stale self-pointers are dropped through a revision-bound `put_page`; a page whose fence is already right but whose stored pointers differ is reprojected without a page write. See [take supersession](#take-supersession). | `ambiguous_pages` / `ambiguous_rows`: pages where a new row has two or more possible predecessors, or where evidence conflicts. The preview lists each with its candidates and the manual edit; nothing on them changes. `unparsed_pages`: pages whose takes fence does not parse cleanly. |+| `accepted-takes` | none | Explicit-only, preview-bound. Restores takes that accepting a held strike-through or kind change removed on v0.60.253.0 (`gbrain trust confirm tp<id>` ran a `takes_remove` instead of applying the change). It restores only what the records prove: the accepted proposal, the `takes_remove` receipt bound to it, the page version that receipt archived (the row the accept should have applied) and the reservation row still holding its number. `--apply --expect <hash>` republishes each page with that row through a revision-bound `put_page`. See [accepted takes](#accepted-takes). | `version_missing` (the archived version was pruned), `row_number_in_use` (the number holds a take again), `page_missing`, `fence_unreadable`. A grade or resolution the database alone held is not in any record and is not restored. || `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. || `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. || `managed-sync-orphans` | `sync_failures` | Explicit-only, preview-bound. Retires managed sync bookkeeping nothing current can resume or clear: a `managed-sync-failure` row whose cursor key has no cursor, and an unfinished `managed-sync` cursor recorded by a principal that is no longer an active local writer (or a pre-options cursor a later run superseded) whose pending request is terminal. `op_checkpoints` rows only; no journal admission, no page or file changes. The preview prints a hash; `--apply --expect <hash>` retires exactly that set. See [managed sync orphans](#managed-sync-orphans). | An unfinished cursor whose pending request is still queued, running or recovering, or one the live writer can resume with its recorded options (doctor prints that sync command). |@@ -393,6 +394,39 @@ hand: read the page (`gbrain get --source <source> -- <slug>`), appendreplaced, save it with the current `expected_revision`, then run the repairagain; it drops the leftover self-pointers and stores the pointers.+<a id="accepted-takes"></a>+### Accepted takes++**Say to your agent:** *"I accepted held take changes on v0.60.253.0. Check whether any take was removed and restore it."*++On v0.60.253.0, accepting a held change to a take you had confirmed+(`gbrain trust confirm tp<id>`, or `gbrain trust review --accept-all`) removed+the take when the change kept its claim: an agent struck it through+(`~~claim~~`) or changed its kind or holder. The take left the page's takes+fence and the takes index; the accept should have applied the change instead.+A later sync or publish cannot bring it back, because the page no longer+carries the row. A take with a grade in its fence was safe: the removal+refused it.++Preview, then apply after you agree:++```bash+gbrain repair accepted-takes # each removed take, its proposal and the page version it comes from+gbrain repair accepted-takes --json # listing[] and residuals+gbrain repair accepted-takes --apply --expect <preview-hash>+```++A take is listed only when every record agrees: the accepted proposal (a strike+or same-claim change, filed by a page publish or reconcile), the committed+`takes_remove` receipt bound to it, the page version that removal archived+(whose fence holds the row at that number) and the reservation row the removal+left in the live fence. The apply puts that fence row back in place of the+reservation through a revision-bound `put_page`, at the tier of the write you+accepted, which is what a correct accept leaves. Not restored, because no+record holds it: a grade or resolution stored only in the database, the take's+id (the row gets a new one) and its embedding (re-embedded). A second preview+lists nothing.+<a id="orphan-bindings"></a>### Orphan persistence bindingsdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 0307a68e2e..506f929f5b 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -434,6 +434,9 @@ src/core/questions/refresh.ts refreshPin field INLINE owner claims of the questisrc/core/questions/refresh.ts retrieveEvidence field LEAD inline candidates onlysrc/core/questions/refresh.ts retrieveEvidence sql LEAD segmented candidate pages excluded in SQL (skip): their excerpt and laundering check need the bodysrc/core/reindex-consent.ts estimateReindexSpend sql META+src/core/repair/accepted-takes.ts archivedRow field SEGW inline versions only: a segmented archived version counts as version_missing (the v0.60.253.0 accept refused segmented pages, so none exists)+src/core/repair/accepted-takes.ts archivedRow sql SEGW selects body_storage; a segmented archived version counts as version_missing+src/core/repair/accepted-takes.ts livePage call:serializePageToMarkdown SEGW materializedSnapshot within the single-string ceiling; over it counts as fence_unreadable (no fences there)src/core/repair/captured-facts.ts strikeFencedRows call:serializePageToMarkdown SEGWsrc/core/repair/captured-facts.ts strikeFencedRows field SEGWsrc/core/repair/connector-fences.ts candidates sql STREAMdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex db349dc23d..805a28e2cf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -648,8 +648,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// W1 trust prerequisites (#6783 §12 (a) and (b)).{ since: '0.60.253.0', text: 'A write less trusted than a take or timeline row no longer deletes, replaces or deactivates it. A page publish (`put_page`, sync, a maintenance republish) that drops or rewrites such a row, `takes_remove`, the takes reconcile (`gbrain extract takes`) and the timeline orphan prune now keep the row as it is and file a `forget` proposal (`gbrain trust review`): `gbrain trust confirm tp<id>` applies the change, `gbrain trust drop tp<id>` keeps the row. A refused `takes_remove` returns `forget_requires_owner` with the proposal ref. The page text keeps what the writer published, and the put_page response lists the proposals under `contested`.' },{ since: '0.60.253.0', text: 'Lowering a row\'s trust tier now lowers what was derived from it: facts, takes, pages and timeline rows reached through their recorded derivation inputs drop to the least trusted of their current inputs (an agent edit that lowers a page, an owner tier change, the `gbrain trust claim-sources` relower repair, a derived republish, a fence field rewrite). Raising a tier never promotes a derivative, and recorded history keeps its tiers. A lowered row\'s `write_origin.input_lowered` names the tier it had; on a managed brain a dependent in another source is marked `needs_rederive` instead.' },- // Held-removal accept follow-up. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.- { since: '0.60.253.0', text: 'Accepting a held take change (`gbrain trust confirm tp<id>`) that struck the take through or changed its kind now applies exactly that change; before, the accept removed the take from the page and the index. Accepting a held take or timeline change on a page stored in segments now applies it as on any page instead of refusing with `page_body_segmented`.' },+ // Held-removal accept fix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.253.0', text: 'Accepting a held take change (`gbrain trust confirm tp<id>`, or accept-all in `gbrain trust review`) that struck a take through or changed its kind or holder now applies exactly that change. On v0.60.253.0 the accept removed the take from the page and the takes index instead (a take graded in its fence was refused and kept). `gbrain repair accepted-takes` lists each take the records prove was removed that way and, with `--apply --expect <hash>`, restores it at the tier of the accepted write; a grade only the database held is not restored. Accepting a held take or timeline change on a page stored in segments now applies it instead of refusing with `page_body_segmented`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex fbcf07b4fd..f4f2b3db63 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/accepted-takes.ts b/src/core/repair/accepted-takes.tsnew file mode 100644index 0000000000..f13bba4c24--- /dev/null+++ b/src/core/repair/accepted-takes.ts@@ -0,0 +1,176 @@+/**+ * `gbrain repair accepted-takes` (v0.60.253.0 accept bug): restore takes that+ * an owner accept of a held strike-through or kind change removed.+ *+ * On v0.60.253.0, accepting a held `forget` proposal whose take the page's+ * fence still carried with the same claim (a strike-through, the guard's+ * `deactivated` change, or a kind or holder change, a same-claim `replaced`)+ * ran an owner `takes_remove`: the row left the fence (a reservation row kept+ * its number) and the takes index. The accept should have applied the fence+ * row as the page said. A later sync or publish cannot bring it back: the+ * page no longer carries the row.+ *+ * Only what the records prove is restored. An item needs all of:+ * 1. an accepted `forget` proposal on a take, `change` deactivated or+ * replaced, filed by a page publish or reconcile (not `takes_remove`);+ * 2. the committed `takes_remove` receipt bound to that proposal+ * (`intent.trust_accept`), naming the page and the row number;+ * 3. the page version that receipt archived (`archived_write_request_id`),+ * whose takes fence holds the row at that number: the row the accept+ * should have applied;+ * 4. the live page's fence still holding the reservation row at that number,+ * with no take there in the fence or the index.+ * The apply republishes the live page with that fence row in place of its+ * reservation (a revision-bound `put_page`), then lowers the restored take to+ * the tier of the write the owner accepted when the republish stamped it+ * higher. What the records never held cannot come back: a grade or resolution+ * stored only in the database, the take's id and its embedding (re-embedded).+ *+ * Explicit-only and preview-bound: the preview lists each take with its+ * evidence and saves the set under its hash; `--apply --expect <hash>`+ * restores exactly that set, rechecking every condition per item.+ */+import type { BrainEngine } from '../engine.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { stableJson } from '../persistence/digest.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { materializedSnapshot, segmentedOverCeiling } from '../persistence/segmented-apply.ts';+import { locateOutsideCode } from '../fence-scan.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, renderTakesFence, type ParsedTake } from '../takes-fence.ts';+import { setRowTier } from '../trust/page-handlers.ts';+import { compareTrust, storedTrustTier, type TrustTier } from '../trust/tier.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairScope } from './core.ts';++const DOCS = 'docs/guides/repair.md#accepted-takes';+const COMMAND = 'gbrain repair accepted-takes';++/** One take the records prove an accept removed, with the fence row to restore. */+export interface RemovedTake {+ proposal_id: number; source_id: string; slug: string; page_id: number; row_num: number;+ receipt_id: string; version_id: number; change: string; writer_tier: TrustTier; row: ParsedTake;+}+interface AcceptedTakeItem extends RepairItem { take: RemovedTake; hash: string; last: boolean }+type Residual = 'version_missing' | 'row_not_in_version' | 'row_number_in_use' | 'page_missing' | 'fence_unreadable';++interface Candidate { proposal_id: number; source_id: string; slug: string; page_id: number; row_num: number; receipt_id: string; change: string; writer_tier: string }++async function candidates(engine: BrainEngine, sourceIds: readonly string[], proposalId?: number): Promise<Candidate[]> {+ return engine.executeRaw<Candidate>(`SELECT p.id::int AS proposal_id, r.source_id, r.slug, r.page_id::int AS page_id,+ (r.intent->>'row_num')::int AS row_num, r.id::text AS receipt_id, p.before_state->>'change' AS change,+ p.before_state->>'writer_tier' AS writer_tier+ FROM trust_proposals p+ JOIN persistence_requests r ON r.operation = 'takes_remove' AND r.state = 'committed' AND r.source_id = p.source_id+ AND r.intent->>'trust_accept' = p.id::text AND r.page_id IS NOT NULL AND (r.intent->>'row_num') ~ '^[0-9]+$'+ WHERE p.action = 'forget' AND p.target_table = 'takes' AND p.status = 'accepted' AND p.proposer <> 'takes_remove'+ AND p.before_state->>'change' IN ('deactivated', 'replaced') AND p.source_id = ANY($1::text[])+ AND ($2::bigint IS NULL OR p.id = $2::bigint)+ ORDER BY p.id`, [[...sourceIds], proposalId ?? null]);+}++/** The archived fence row the accept should have applied, or why it cannot be read. */+async function archivedRow(engine: BrainEngine, c: Candidate): Promise<{ version_id: number; row: ParsedTake } | Residual> {+ const [version] = await engine.executeRaw<{ id: number; body_storage: string | null; compiled_truth: string | null; timeline: string | null }>(+ `SELECT id::int AS id, body_storage, compiled_truth, timeline FROM page_versions+ WHERE page_id = $1 AND archived_write_request_id::text = $2 ORDER BY id DESC LIMIT 1`, [c.page_id, c.receipt_id]);+ if (!version || version.body_storage === 'segmented' || version.compiled_truth === null) return 'version_missing';+ const row = parseTakesFence(`${version.compiled_truth}\n${version.timeline ?? ''}`).takes.find(t => t.rowNum === c.row_num);+ return row ? { version_id: Number(version.id), row } : 'row_not_in_version';+}++/** The live page's markdown and revision when its fence still reserves `rowNum` and nothing else uses it. */+async function livePage(engine: BrainEngine, take: Pick<RemovedTake, 'source_id' | 'slug' | 'page_id' | 'row_num'>): Promise<{ content: string; revision: string; takes: ParsedTake[]; reserved: number[] } | Residual> {+ const raw = await engine.readPageSnapshot(take.slug, { sourceId: take.source_id });+ if (!raw || Number(raw.page.id) !== take.page_id) return 'page_missing';+ if (segmentedOverCeiling(raw.page as never)) return 'fence_unreadable';+ const snapshot = (await materializedSnapshot(engine, raw))!;+ const content = serializePageToMarkdown(snapshot.page, snapshot.tags);+ if (content.split(TAKES_FENCE_BEGIN).length !== 2) return 'fence_unreadable';+ const fence = parseTakesFence(content);+ if (fence.warnings.length) return 'fence_unreadable';+ const [stored] = await engine.executeRaw('SELECT 1 FROM takes WHERE page_id = $1 AND row_num = $2', [take.page_id, take.row_num]);+ if (stored || fence.takes.some(t => t.rowNum === take.row_num) || !fence.reservedRowNums.includes(take.row_num)) return 'row_number_in_use';+ return { content, revision: snapshot.revision, takes: fence.takes, reserved: fence.reservedRowNums };+}++/** Every take of the selected sources the records prove restorable, and the count of each reason one is not. */+export async function scanRemovedTakes(engine: BrainEngine, sourceIds: readonly string[], proposalId?: number): Promise<{ takes: RemovedTake[]; residuals: Record<Residual, number> }> {+ const residuals: Record<Residual, number> = { version_missing: 0, row_not_in_version: 0, row_number_in_use: 0, page_missing: 0, fence_unreadable: 0 };+ const takes: RemovedTake[] = [];+ for (const c of await candidates(engine, sourceIds, proposalId)) {+ const archived = await archivedRow(engine, c);+ if (typeof archived === 'string') { residuals[archived]++; continue; }+ const live = await livePage(engine, c);+ if (typeof live === 'string') { residuals[live]++; continue; }+ takes.push({ proposal_id: c.proposal_id, source_id: c.source_id, slug: c.slug, page_id: c.page_id, row_num: c.row_num, receipt_id: c.receipt_id,+ version_id: archived.version_id, change: c.change, writer_tier: storedTrustTier(c.writer_tier), row: archived.row });+ }+ return { takes, residuals };+}++const label = (t: RemovedTake) => `${t.row.active ? '' : '~~'}${t.row.claim}${t.row.active ? '' : '~~'} (${t.row.kind}, ${t.row.holder})`;+const hashParts = (scope: RepairScope, takes: RemovedTake[]) => ({ kind: 'accepted-takes-v1', brain_id: scope.brain_id, source_ids: scope.source_ids, takes });+const item = (take: RemovedTake, hash: string, last: boolean): AcceptedTakeItem => ({ cursor: { phase: 1, id: take.proposal_id }, source_id: take.source_id,+ slug: take.slug, chars: 0, action: `restore_take:#${take.row_num}`, take, hash, last });++export const acceptedTakesRepair: RepairHandler = {+ kind: 'accepted-takes',+ async plan(engine, scope, after, opts) {+ const scan = await scanRemovedTakes(engine, scope.source_ids);+ if (!opts?.apply) {+ const hash = previewHash(hashParts(scope, scan.takes));+ if (scan.takes.length) await saveApprovedSet(engine, { command: 'accepted-takes', hash }, scan.takes);+ return {+ items: scan.takes.map((take, index) => item(take, hash, index === scan.takes.length - 1)), preview_hash: hash, residuals: scan.residuals,+ listing: scan.takes.map(t => ({ item: `${t.source_id}:${t.slug}#${t.row_num}`, class: `accepted_${t.change}`,+ detail: `tp${t.proposal_id} removed ${label(t)}; restored from page version ${t.version_id} at "${t.writer_tier}"` })),+ ...(scan.takes.length ? { warnings: ['A grade or resolution the database alone held, and the take\'s id, are not in any record and are not restored.'] } : {}),+ details: { docs: DOCS },+ };+ }+ if (!opts.expect) {+ throw opError('invalid_params', `${COMMAND} --apply restores only the set a preview printed.`,+ `Preview first: ${COMMAND} — then, after the user agrees, run the apply command it prints: ${COMMAND} --apply --expect <preview-hash>`,+ { fix: readFix('Previews the takes the records prove an accept removed; writes nothing.', { argv: ['gbrain', 'repair', 'accepted-takes', '--json'] }), docs: DOCS });+ }+ const approved = await loadApprovedSet<RemovedTake>(engine, { command: 'accepted-takes', hash: opts.expect, previewCommand: COMMAND,+ emptyHash: async () => previewHash(hashParts(scope, [])) });+ const items = approved.items.map((take, index) => item(take, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { take, hash, last } = entry as AcceptedTakeItem;+ try {+ return await restoreTake(ctx.engine, ctx, entry, take);+ } finally {+ if (last) await clearApprovedSet(ctx.engine, { command: 'accepted-takes', hash });+ }+ },+ render(details) {+ return [` each restored take: republished from the page version its removal archived; guide: ${details.docs}`];+ },+};++const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason: `${reason}; run ${COMMAND} again for a new preview.` });++async function restoreTake(engine: BrainEngine, ctx: Parameters<RepairHandler['apply']>[0], entry: RepairItem, take: RemovedTake): Promise<RepairItemOutcome> {+ const [now] = (await scanRemovedTakes(engine, [take.source_id], take.proposal_id)).takes;+ if (!now || now.version_id !== take.version_id || now.row_num !== take.row_num || stableJson(now.row) !== stableJson(take.row)) {+ return changed(`take #${take.row_num} on ${take.slug} is no longer restorable as previewed`);+ }+ const live = await livePage(engine, take);+ if (typeof live === 'string') return changed(`page ${take.slug} changed (${live})`);+ const rows = [...live.takes, take.row].sort((a, b) => a.rowNum - b.rowNum);+ const { beginIdx, endIdx } = locateOutsideCode(live.content, TAKES_FENCE_BEGIN, TAKES_FENCE_END);+ const content = live.content.slice(0, beginIdx) + renderTakesFence(rows, live.reserved.filter(n => n !== take.row_num)) + live.content.slice(endIdx + TAKES_FENCE_END.length);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: take.slug, source_id: take.source_id, content, expected_revision: live.revision,+ request_id: await repairRequestId(ctx, 'accepted-takes', entry, live.revision) } });+ const [restored] = await engine.executeRaw<{ id: number; trust_tier: string }>('SELECT id::int AS id, trust_tier FROM takes WHERE page_id = $1 AND row_num = $2',+ [take.page_id, take.row_num]);+ if (restored && compareTrust(storedTrustTier(restored.trust_tier), take.writer_tier) > 0) {+ await setRowTier(engine, { table: 'takes', id: Number(restored.id), sourceId: take.source_id, tier: take.writer_tier, note: { repair: 'accepted-takes', proposal: take.proposal_id } });+ }+ return { applied: true, outcome: 'restored', detail: { proposal: `tp${take.proposal_id}`, row_num: take.row_num, version_id: take.version_id, tier: take.writer_tier } };+}diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex aafb1d5277..6975658947 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex d5d5b7439e..2fc2738214 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -43,6 +43,7 @@ import { connectorCheckpointsRepair } from './connector-checkpoints.ts';import { requestIndexesRepair } from './request-indexes.ts';import { connectorFencesRepair } from './connector-fences.ts';import { takeSupersessionRepair } from './take-supersession.ts';+import { acceptedTakesRepair } from './accepted-takes.ts';import { orphanBindingsRepair } from './orphan-bindings.ts';import { managedSyncOrphansRepair } from './managed-sync-orphans.ts';import { embeddingEffectsRepair } from './embedding-effects.ts';@@ -134,6 +135,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'dropped through a revision-bound put_page; a page whose fence is right but whose stored pointers differ is reprojected. Ambiguous pages are '+ 'listed with the manual edit and never changed.',},+ 'accepted-takes': {+ handler: acceptedTakesRepair, embeds: 'effect', checks: [], explicit_only: true, preview_bound: true,+ summary: 'Restore takes that accepting a held strike-through or kind change removed on v0.60.253.0 (gbrain trust confirm tp<id> ran a takes_remove '+ + 'instead of applying the change). Only what the records prove: the accepted proposal, the takes_remove receipt bound to it, the page version that '+ + 'receipt archived (the fence row the accept should have applied) and the reservation row still holding its number. --apply --expect <hash> '+ + 'republishes each page with that row (a revision-bound put_page) at the tier of the write the owner accepted. A grade or resolution only the '+ + 'database held is not in any record and is not restored. Runs only when named.',+ },'orphan-bindings': {handler: orphanBindingsRepair, embeds: 'none', checks: ['orphan_persistence_bindings'],summary: 'Delete persistence source bindings whose source or source incarnation no longer exists (#5732), so a source re-added under the same id can be claimed again. 'diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 8f41e62d8b..1445adcc5b 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -193,7 +193,7 @@ for (const backend of testBackends()) {const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };- const previews = { 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts',+ const previews = { 'accepted-takes': 'gbrain repair accepted-takes', 'google-file-modes': 'gbrain repair google-file-modes', 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts','conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift','stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases' };diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 8944358ae3..1e7a28fbd9 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));@@ -109,7 +109,7 @@ describe('surfaces that list instead of run', () => {expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));}- expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair loop-facts');+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair accepted-takes; gbrain repair google-file-modes; gbrain repair stale-atoms; gbrain repair extractor-facts; gbrain repair conversation-labels; gbrain repair captured-facts; gbrain repair loop-facts');});test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {diff --git a/test/trust-held-removals.test.ts b/test/trust-held-removals.test.tsindex dadc9cfffe..d46dd222c0 100644--- a/test/trust-held-removals.test.ts+++ b/test/trust-held-removals.test.ts@@ -33,6 +33,8 @@ import { recordDerivationInputs } from '../src/core/facts/derivation-inputs.ts';import { setRowTier } from '../src/core/trust/page-handlers.ts';import { extractTakesFromDb } from '../src/core/cycle/extract-takes.ts';import { materializeSegmentedBody } from '../src/core/page-body/ingest.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -283,6 +285,78 @@ describe('held removals (W1 #6783 §12 (a))', () => {}), 120_000);});+/** The v0.60.253.0 accept of a held take whose fence row kept its claim: an owner takes_remove bound to the proposal (what that release ran). */+async function acceptAsV253(b: Brain, proposalId: number, slug: string, rowNum: number) {+ const nonce = randomUUID();+ await b.engine.executeRaw(`UPDATE trust_proposals SET after_state = after_state || jsonb_build_object('accept_nonce', $2::text) WHERE id = $1`, [proposalId, nonce]);+ await submitPageMutation(b.local as never, { operation: 'takes_remove', params: { slug, source_id: b.sourceId, row_num: rowNum,+ trust_accept: proposalId, trust_accept_nonce: nonce, request_id: randomUUID() } });+}+async function repairCli(b: Brain, args: string[]): Promise<Record<string, any>> {+ let printed = '';+ const original = console.log, write = process.stdout.write;+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;+ try { await runRepairCommand(b.engine, [...args, '--source', b.sourceId, '--json']); } finally { console.log = original; process.stdout.write = write; }+ return JSON.parse(printed).results[0];+}++describe('gbrain repair accepted-takes (the v0.60.253.0 accept bug)', () => {+ test('a take the v0.60.253.0 accept removed stays gone through a republish and reconcile; the repair restores exactly the accepted row from the records (managed and unmanaged)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const [engine, managed] of engines.flatMap(e => [[e, true], [e, false]] as const)) {+ const b = await brain(engine);+ if (!managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const slug = 'people/mina-example';+ await run(b.local, 'put_page', { slug, content: page('Mina', 'Mina.') });+ for (const claim of ['Mina will move to Lima', 'Mina prefers tea', 'Mina ships the atlas']) await run(b.local, 'takes_add', { slug, claim, kind: 'bet', holder: 'world', weight: 0.6 });+ const before = await takesOf(b, slug);+ // Take 3 is graded in its fence (v0.60.253.0's takes_remove refused a resolved row); take 2 only in the database.+ await run(b.local, 'takes_resolve', { slug, row_num: before[2]!.row_num, quality: 'correct', resolved_at: '2026-10-01' });+ await coordinated(b, tx => tx.executeRaw(`UPDATE takes SET resolved_at='2026-10-02', resolved_quality='incorrect' WHERE id=$1`, [before[1]!.id]));+ for (const take of before) await confirm(b, 'takes', take.id);+ const current = await localContent(b, slug);+ const edited = String(current.content).replace('Mina will move to Lima', '~~Mina will move to Lima~~').replace(/(\| Mina prefers tea \| )bet/, '$1take')+ .replace(/(\| )(Mina ships the atlas)( \|)/, '$1~~$2~~$3');+ await run(b.local, 'put_page', { slug, content: edited, expected_revision: current.revision });+ const struck = (await proposalsFor(b, 'takes', before[0]!.id))[0]!;+ const rekinded = (await proposalsFor(b, 'takes', before[1]!.id))[0]!;+ const graded = (await proposalsFor(b, 'takes', before[2]!.id))[0]!;+ await acceptAsV253(b, struck.id, slug, before[0]!.row_num);+ await acceptAsV253(b, rekinded.id, slug, before[1]!.row_num);+ expect(((await acceptAsV253(b, graded.id, slug, before[2]!.row_num).then(() => null, (e: unknown) => e)) as Error | null)?.message).toBe('Resolved takes are immutable.');+ expect((await takesOf(b, slug)).map(t => t.claim)).toEqual(['Mina ships the atlas']);+ // Nothing brings them back on its own: the page no longer carries the rows.+ const again = await localContent(b, slug);+ expect(String(again.content)).not.toContain('Mina will move to Lima');+ await run(b.local, 'put_page', { slug, content: `${String(again.content)}\nMore.`, expected_revision: again.revision });+ await extractTakesFromDb(engine, { slugs: [slug], sourceId: b.sourceId } as never);+ expect((await takesOf(b, slug)).map(t => t.claim)).toEqual(['Mina ships the atlas']);+ // Preview lists both, writes nothing.+ const preview = await repairCli(b, ['accepted-takes']);+ expect(preview.preview_hash).toBeString();+ expect((preview.listing as Array<{ item: string; class: string }>).map(l => [l.item, l.class])).toEqual([+ [`${b.sourceId}:${slug}#${before[0]!.row_num}`, 'accepted_deactivated'], [`${b.sourceId}:${slug}#${before[1]!.row_num}`, 'accepted_replaced']]);+ expect((await takesOf(b, slug)).map(t => t.claim)).toEqual(['Mina ships the atlas']);+ const applied = await repairCli(b, ['accepted-takes', '--apply', '--expect', preview.preview_hash]);+ expect(applied.applied).toBe(2);+ const after = await engine.executeRaw<{ row_num: number; claim: string; kind: string; active: boolean; trust_tier: string; resolved_quality: string | null }>(+ 'SELECT row_num, claim, kind, active, trust_tier, resolved_quality FROM takes WHERE page_id=$1 ORDER BY row_num', [await pageId(b, slug)]);+ // The tier is the accepted write's (what a correct accept leaves); take 2's database-only grade is in no record and stays lost.+ expect(after).toEqual([+ { row_num: before[0]!.row_num, claim: 'Mina will move to Lima', kind: 'bet', active: false, trust_tier: 'agent_written', resolved_quality: null },+ { row_num: before[1]!.row_num, claim: 'Mina prefers tea', kind: 'take', active: true, trust_tier: 'agent_written', resolved_quality: null },+ { row_num: before[2]!.row_num, claim: 'Mina ships the atlas', kind: 'bet', active: true, trust_tier: 'user_confirmed', resolved_quality: 'correct' },+ ]);+ const text = String((await localContent(b, slug)).content);+ expect(text).toContain('~~Mina will move to Lima~~');+ expect(text).toContain('| Mina prefers tea | take |');+ expect(text).not.toContain('(removed)');+ // A second preview finds nothing; the restored rows hold.+ expect((await repairCli(b, ['accepted-takes'])).listing ?? []).toEqual([]);+ }+ }), 240_000);+});+describe('derived-tier propagation (W1 #6783 §12 (b))', () => {test('an agent edit that lowers a page lowers the fact derived from it; an owner raise never promotes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {