Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(decide): semantic withdrawal review and the ambiguous-band review lane

garrytanbe64f6d7a363
diff --git a/docs/architecture/key-files/core-decide.md b/docs/architecture/key-files/core-decide.md
index fb915355d8..2be5a81cf6 100644
--- a/docs/architecture/key-files/core-decide.md
+++ b/docs/architecture/key-files/core-decide.md
@@ -69,7 +69,8 @@ The capability contract (API, providers, egress, extension points) is `docs/arch
- `src/core/ai/decide/conflict.ts` — S9's question (`duplicate | supersede | independent`, state = the new fact, one choice per candidate), the ONE pair reducer `reduceConflict` (chosen duplicate at or above threshold → duplicate; else P(supersede) at or above `decide.slots.conflict.proposal_floor` → proposal; else independent), candidate eligibility (the `decideSingleFact` guards, self-exclusion, cosine ≥ 0.80), unordered pair keys, proposal direction, chronology (`isOlderFact`: valid_from, then created_at, then id; `datedConflictState`/`datedConflictQuestion` add `fact_time`/`candidate_time` evidence for a reordered pair) and `sweepWindow` (stops at the first fact younger than 60 s).
-- `src/core/ai/decide/sweep.ts` (+ `proposals-store.ts`) — `runConflictSweep`: per-source watermark in `decide_state` (first run records the max fact id unless `since`), deferred retries first (attempt cap 5, oldest due first so a relinked backlog never starves a transient retry), neighbours filtered BEFORE the k=5 limit by one `executeRaw` query, pairs deduped within the sweep and across sweeps (answered receipts by hashed pair subject, existing proposals), one background-lane request per fact for its older neighbours plus one per neighbour newer than the fact (that neighbour is presented as the new claim with both timestamps, so a proposal always retires the older fact), drift and inactive policy run with off behavior, pending `decide_proposals` rows in `on` mode only; never supersedes. `conflictSweepTail` is the `extract_facts` phase tail: undefined when the slot is off. `proposals-store.ts` holds the watermark, deferred, dedup and proposal SQL, and `enqueueRelinked(engine, sourceId, factIds)` (the `gbrain facts relink` handoff: attempts 0, due now, reason `relinked`, `ON CONFLICT DO NOTHING`, run on the caller's transaction engine). Tests: `test/decide/conflict-sweep.serial.test.ts`, `test/decide/conflict-relink-handoff.serial.test.ts`.
+- `src/core/ai/decide/sweep.ts` (+ `proposals-store.ts`) — `runConflictSweep`: per-source watermark in `decide_state` (first run records the max fact id unless `since`), deferred retries first (attempt cap 5, oldest due first so a relinked backlog never starves a transient retry), neighbours filtered BEFORE the k=5 limit by one `executeRaw` query, pairs deduped within the sweep and across sweeps (answered receipts by hashed pair subject, existing proposals), one background-lane request per fact for its older neighbours plus one per neighbour newer than the fact (that neighbour is presented as the new claim with both timestamps, so a proposal always retires the older fact), drift and inactive policy run with off behavior, pending `decide_proposals` rows in `on` mode only; never supersedes. `conflictSweepTail` is the `extract_facts` phase tail: undefined when the slot is off. `proposals-store.ts` holds the watermark, deferred, dedup and proposal SQL, and `enqueueRelinked(engine, sourceId, factIds)` (the `gbrain facts relink` handoff: attempts 0, due now, reason `relinked`, `ON CONFLICT DO NOTHING`, run on the caller's transaction engine). Tests: `test/decide/conflict-sweep.serial.test.ts`, `test/decide/conflict-relink-handoff.serial.test.ts`. When `decide.slots.conflict.review_withdraw` is on, each swept fact re-queues up to two withdrawn claims it may restate (`requeueWithdrawnAnchorsNear`), and `conflictSweepTail` runs `runReviewLanes` after the sweep (output key `review`).
+- `src/core/ai/decide/review-lane.ts` (+ `src/core/facts/proposal-review.ts`) — the ambiguous-band review lane on the `conflict` slot's provider, egress and spend. Kinds `withdraw` (active facts close to a withdrawn fact; conflict question unchanged, `duplicate` = same claim), `duplicate_page` and `duplicate_entity` (page pairs other subsystems queue with `enqueueReviewCandidate`; `same | different` question, candidates class). Each kind has a switch (`decide.slots.conflict.review_<kind>`, off by default), a call site (`review_<kind>`, listed in `SLOT_SPECS.conflict.callSites`) and its own calibration; `reviewGate` lets a kind propose only with a calibration qualified for action precision (`action_precision_lb >= min_action_precision`, fingerprint match; an operator threshold override never qualifies) and otherwise skips the provider entirely; shadow mode writes receipts only. Work lives in `decide_review_queue` (written in the event's own transaction: `recordFactWithdrawal` for withdraws; no timestamp cursor), at most `REVIEW_BUDGET_PER_RUN` (50) per kind per run, with attempt/backoff deferral and permanent-failure clearing. Pair subjects `review:<kind>:<source>:<a>:<b>` are hashed into receipts, so supersede receipts never suppress a review judgment and judged pairs are not re-asked. A forgotten private fact is skipped unless `decide.egress.private` is `allow`. Proposals go to `decide_review_proposals` (unique per kind/source/a/b/subject; separate table so older binaries never read them). `proposalReviewRates` feeds `gbrain decide status` (pending, oldest pending age, 30-day accepted/rejected per kind). Owner actions (`proposal-review.ts`): withdraw accept re-checks anchor still withdrawn and candidate active with unchanged text (`candidate_hash`), then calls the `forget` operation with a proposal-derived request id and `semantic_review: false` (finishing an interrupted accept when the fact already carries the `(review r<id>)` marker); a changed candidate goes `stale`; undo refuses with `withdrawal_is_durable` and a fix; duplicate kinds run the handler registered with `registerReviewAcceptHandler`, else `accepted_no_action`. CLI in `commands/decide/proposals.ts`: `r<id>` ids, `--yes` required to accept a withdraw, `--all-from` excludes withdraws unless `--include-withdrawals`. Pinned by `test/decide/review-withdraw.serial.test.ts` and `test/decide/review-duplicate-kinds.serial.test.ts`.
- `src/core/ai/decide/datasets-conflict.ts` — `registerConflictDatasets()` (called by `src/commands/decide/writepath.ts`): the conflict dataset adapter (production request shape, no harmful-action reducer) and the `facts-fixtures` builder (labelled fact-pair JSONL; label `true` exactly for `duplicate`, the calibrated threshold). Calibration thresholds the reducer-consistent `duplicateValue` (P(chosen) only when duplicate is chosen) and `calibrateProposalFloor` picks the F1-best P(supersede) floor on the choice label kept in `slice` (≥ 10 supersede labels), stored in the row's notes. Tests: `test/decide/conflict-calibration.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index bbfed08f5c..70858f2eee 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.
+- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`).
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 22a71d490f..3ba7fe1cce 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -422,7 +422,10 @@ in-word dots, so "C++", "C#", ".NET" and "Node.js" stay distinct from
end of the claim follows it. Rows recorded before v174 keep their exact fingerprint and keep
matching; v174 adds a folded row wherever a fact row still holds the claim text
and expires active facts that became matching. A paraphrase with different
-words is a different claim.
+words is a different claim to the ledger: `forget` returns its close
+rewordings as `similar_active` for the agent to confirm with the user, and
+the optional overnight withdrawal review proposes the ones it judges to
+restate the claim for the owner to accept (`gbrain decide proposals list`).
Already queued source-wide effects are converted using the same bounded exact
discovery and retain their individual progress cursors. An over-capacity or
diff --git a/docs/guides/system-one.md b/docs/guides/system-one.md
index 5a822cf867..be85e8a894 100644
--- a/docs/guides/system-one.md
+++ b/docs/guides/system-one.md
@@ -269,6 +269,56 @@ gbrain decide proposals accept <id> | reject <id> # or --all-from <swe
gbrain decide proposals undo <id> # reverse an accepted proposal
```
+### Ambiguous-band review (rides `conflict`)
+
+Some pairs sit in the similarity band where a threshold cannot tell a
+restatement from a related claim. The review lane asks the contradiction
+slot's provider about them overnight, at the end of the same `extract_facts`
+tail, and writes owner-reviewed proposals. Each kind has its own switch, call
+site, calibration and qualification:
+
+| Kind | Switch | Reviews | Accepting |
+|---|---|---|---|
+| `withdraw` | `decide.slots.conflict.review_withdraw` | active facts close to a fact you forgot | withdraws the fact exactly like `forget` (permanent) |
+| `duplicate_page` | `decide.slots.conflict.review_duplicate_page` | page pairs the page-duplicate detector queued | runs the registered merge or link action, or records your verdict |
+| `duplicate_entity` | `decide.slots.conflict.review_duplicate_entity` | entity pairs deterministic entity dedup left ambiguous | same as `duplicate_page` |
+
+Each switch is off by default. A kind proposes only when its calibration for
+call site `review_<kind>` is qualified for action precision
+(`decide.slots.conflict.min_action_precision`, default 0.90); until then it
+does not call the provider at all. An operator `decide.slots.conflict.threshold`
+override does not count as a qualification for review kinds.
+
+```bash
+gbrain decide calibrate --slot conflict --call-site review_withdraw --dataset withdraw.jsonl
+gbrain decide qualify --slot conflict --call-site review_withdraw --dataset withdraw.jsonl
+gbrain config set decide.slots.conflict.review_withdraw true
+```
+
+Work is queued in the same transaction as the event that creates it: a
+withdrawal (unless `forget` passed `semantic_review: false`), or another
+subsystem's enqueue. Nothing older than turning a kind on is reviewed. A fact
+the contradiction sweep processes also re-queues up to two withdrawn claims it
+may restate. The text of a forgotten private fact is sent only when
+`decide.egress.private` is `allow`; the TypeSafe key alone does not cover it.
+
+Review proposals list with `r` ids next to supersede proposals:
+
+```bash
+gbrain decide proposals list
+gbrain decide proposals accept r12 --yes # a withdraw is permanent: confirm with the user first
+gbrain decide proposals reject r12
+gbrain decide proposals accept --all-from <sweep id> --include-withdrawals --yes
+```
+
+`--all-from` skips withdraw proposals unless `--include-withdrawals` is given.
+Accepting re-checks that the claim is still withdrawn and that the affected
+fact is still active and unchanged; otherwise the proposal goes `stale`. A
+withdraw has no undo: the withdrawal ledger is durable, so to state the claim
+again, remember a corrected wording with new provenance. `gbrain decide
+status` shows each kind's pending count, oldest pending age, and 30-day
+accepted and rejected counts.
+
## Turning a slot on
```bash
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 548221f732..6791cc0a29 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -386,6 +386,23 @@ already-expired fact returns `expired: false` (success); unknown id ⇒
Response: `{ id, expired, reason, protocol_version }`.
+#### forget similar_active and semantic_review (additive)
+
+`semantic_review` (boolean, default `true`): `false` keeps this claim out of
+the overnight rewording review, so its text is never sent to a decision
+provider for comparison.
+
+The response carries `similar_active`: `{ state, candidates, semantic_review,
+next }`. `state` is `checked`, `not_checked_no_embedding` or
+`not_checked_pending`. `candidates` lists up to five other active facts about
+the same entity, with the same visibility (world only for remote callers),
+whose embedding is at cosine 0.80 or higher to the withdrawn claim, as
+`{ fact_id, similarity }` (no stored text; zero model calls). `semantic_review`
+is `scheduled`, `off`, `unavailable` or `opted_out`; `next` tells the agent
+what to do. Similarity is not sameness: show the candidates to the user and
+forget one only when the user confirms it restates the withdrawn claim. An
+empty list means no close match was found, not that every rewording is gone.
+
#### Durable write receipts (additive)
Write receipts distinguish accepted work from committed memory. Their public
diff --git a/src/commands/decide.ts b/src/commands/decide.ts
index 4c39e6ccaf..e88fb89a8d 100644
--- a/src/commands/decide.ts
+++ b/src/commands/decide.ts
@@ -187,9 +187,10 @@ function costPer1k(slot: DecideSlot, provider: string, usage?: { decisions: numb
// ---------------------------------------------------------------------------
export async function buildStatus(engine: BrainEngine, state: DecideState) {
- const [spend, usage, noEntity] = await Promise.all([
+ const [spend, usage, noEntity, reviewRates] = await Promise.all([
dailySpend(engine).catch(() => ({ total: 0, remote: 0 })), slotUsage(engine, 24).catch(() => []),
conflictNoEntityShare(engine).catch(() => ({ skipped: 0, receipts: 0, share: 0 })),
+ import('../core/ai/decide/review-lane.ts').then(m => m.proposalReviewRates(engine)).catch(() => []),
]);
const slots = DECIDE_SLOTS.map((slot) => {
const p = policyFor(state, slot);
@@ -208,7 +209,7 @@ export async function buildStatus(engine: BrainEngine, state: DecideState) {
cost_per_1k: { ...costPer1k(slot, p.provider, u), unit: COST_UNITS[slot]?.unit ?? 'units' },
effective_line: effectiveModeLine(p),
...(state.cfg.slots[slot].keyDefault ? { key_default: true, opt_out: keyDefaultOptOut(slot) } : {}),
- ...(slot === 'conflict' ? { no_entity_7d: noEntity } : {}),
+ ...(slot === 'conflict' ? { no_entity_7d: noEntity, proposal_review: reviewRates } : {}),
};
});
return {
@@ -255,6 +256,10 @@ async function cmdStatus(engine: BrainEngine, args: string[]): Promise<number> {
if (s.no_entity_7d && s.no_entity_7d.skipped > 0) {
console.log(` ${(s.no_entity_7d.share * 100).toFixed(1)}% of conflict receipts in 7 days (${s.no_entity_7d.skipped} of ${s.no_entity_7d.receipts}) skipped a fact with no entity (no_entity); link them: gbrain facts relink --dry-run`);
}
+ for (const r of s.proposal_review ?? []) {
+ if (!r.enabled && r.pending === 0) continue;
+ console.log(` ${r.kind} proposals: ${r.pending} pending${r.oldest_pending_days !== null ? ` (oldest ${r.oldest_pending_days} days)` : ''}; last 30 days: ${r.accepted_30d} accepted, ${r.rejected_30d} rejected${r.pending > 0 ? ' (review: gbrain decide proposals list)' : ''}`);
+ }
if (s.opt_out) console.log(` on by default because a TypeSafe key is present (sends ${SLOT_SPECS[s.slot].egressClasses.map((c) => CLASS_TEXT[c]).join(', ')} to TypeSafe); opt out: ${s.opt_out}`);
}
const lines = status.slots.map((s) => s.effective_line).filter(Boolean);
diff --git a/src/commands/decide/proposals.ts b/src/commands/decide/proposals.ts
index ad0aba9c8c..fcc6df673d 100644
--- a/src/commands/decide/proposals.ts
+++ b/src/commands/decide/proposals.ts
@@ -5,7 +5,10 @@
* active source, and prints duplicates, proposals written, independents and
* skipped facts. proposals: list shows both facts' text (local only; receipts
* never carry text); accept / reject take one id or --all-from <sweep id>;
- * undo reverses an accepted proposal with a revision check. Local CLI only
+ * undo reverses an accepted proposal with a revision check. Review-lane
+ * proposals (ids `r<n>`: withdraw, duplicate_page, duplicate_entity) list and
+ * act here too; accepting a withdraw is permanent, so it needs --yes, and
+ * --all-from includes withdraws only with --include-withdrawals. Local CLI only
* (the decide command table refuses thin clients; decide is not an MCP op).
*/
import type { BrainEngine } from '../../core/engine.ts';
@@ -13,7 +16,10 @@ import { refusalLine } from '../../core/ai/decide/outcomes.ts';
import { PROPOSAL_STATUSES, listProposals, proposalIdsFromSweep, type ProposalStatus } from '../../core/ai/decide/proposals-store.ts';
import { runConflictSweep, type ConflictSweepResult } from '../../core/ai/decide/sweep.ts';
import { applyProposalAction, rejectProposal, type ProposalActionResult } from '../../core/facts/proposal-supersede.ts';
+import { listReviewProposals, reviewProposalIdsFromSweep, runReviewLanes, REVIEW_PROPOSAL_STATUSES, type ReviewLaneResult, type ReviewProposalRow } from '../../core/ai/decide/review-lane.ts';
+import { acceptReviewProposal, rejectReviewProposal, undoReviewProposal, type ReviewActionResult } from '../../core/facts/proposal-review.ts';
import { flagValue } from '../decide.ts';
+import { isConsentRefusal, printConsentRefusal, requireConsent } from '../../core/consent.ts';
function sweepLine(r: ConflictSweepResult): string {
if (r.mode === 'off') return `${r.source_id}: the contradiction slot is off; nothing was swept (turn it on: gbrain decide enable conflict).`;
@@ -33,13 +39,44 @@ export async function runSweepCommand(engine: BrainEngine, args: string[]): Prom
const source = flagValue(args, '--source');
const sources = source ? [source] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map((r) => r.id);
const results: ConflictSweepResult[] = [];
- for (const sourceId of sources) results.push(await runConflictSweep(engine, { sourceId, ...(sinceRaw !== undefined ? { since: Number(sinceRaw) } : {}) }));
- if (json) { console.log(JSON.stringify({ sweeps: results }, null, 2)); return 0; }
+ const reviews: ReviewLaneResult[] = [];
+ for (const sourceId of sources) {
+ const r = await runConflictSweep(engine, { sourceId, ...(sinceRaw !== undefined ? { since: Number(sinceRaw) } : {}) });
+ results.push(r);
+ if (r.effective !== 'off') reviews.push(...(await runReviewLanes(engine, sourceId) ?? []));
+ }
+ if (json) { console.log(JSON.stringify({ sweeps: results, reviews }, null, 2)); return 0; }
for (const r of results) console.log(sweepLine(r));
- if (results.some((r) => r.proposals > 0)) console.log('Review: gbrain decide proposals list');
+ for (const r of reviews) console.log(reviewLine(r));
+ if (results.some((r) => r.proposals > 0) || reviews.some((r) => r.proposals > 0)) console.log('Review: gbrain decide proposals list');
return results.every((r) => r.effective === 'off') ? 1 : 0;
}
+function reviewLine(r: ReviewLaneResult): string {
+ if (r.effective === 'off') return `${r.source_id}: ${r.kind} review did not run (${r.inactive ?? 'off'}).${r.inactive === 'no_qualification' ? ` Qualify it: gbrain decide calibrate --slot conflict --call-site review_${r.kind} --dataset <jsonl>, then gbrain decide qualify --slot conflict --call-site review_${r.kind} --dataset <jsonl>` : ''}`;
+ const shadow = r.effective === 'shadow' ? ` (shadow: ${r.shadow_proposals} would-be proposals, none written)` : '';
+ return `${r.source_id}: ${r.kind} review ${r.sweep_id}: ${r.anchors} item(s), ${r.pairs} pair(s) judged, ${r.proposals} proposal(s) written, `
+ + `${r.independents} not the same, ${r.skipped} skipped (${r.deferred} deferred)${shadow}${r.stopped ? `; stopped early: ${r.stopped}` : ''}`;
+}
+
+function reviewRowLines(r: ReviewProposalRow, text: Map<string, string>): string[] {
+ if (r.kind === 'withdraw') {
+ return [`r${r.id} [${r.status}] WITHDRAW ${r.subject === '*' ? '(no entity)' : r.subject} review ${r.sweep_id} p(same claim) ${r.p_action.toFixed(3)} DURABLE: cannot be undone`,
+ ` withdrawn #${r.a_ref}: ${text.get(r.a_ref) ?? '(fact missing)'}`,
+ ` would also withdraw #${r.b_ref}: ${text.get(r.b_ref) ?? '(fact missing)'}`];
+ }
+ return [`r${r.id} [${r.status}] ${r.kind.toUpperCase()} review ${r.sweep_id} p(same) ${r.p_action.toFixed(3)}`, ` ${r.a_ref} <-> ${r.b_ref}`];
+}
+
+function reviewResultLine(r: ReviewActionResult): string {
+ if (r.status === 'not_found') return `proposal ${r.id}: not found`;
+ if (r.status === 'refused') return `proposal ${r.id}: ${r.action} refused (${r.reason})${r.fix ? `. ${r.fix}` : ''}`;
+ if (r.status === 'stale') return `proposal ${r.id}: stale (${r.reason}); nothing was changed`;
+ if (r.status === 'accepted') return `proposal ${r.id}: accepted`;
+ if (r.status === 'accepted_no_action') return `proposal ${r.id}: accepted (${r.reason})`;
+ return `proposal ${r.id}: rejected`;
+}
+
function resultLine(r: ProposalActionResult): string {
if (r.status === 'not_found') return `proposal ${r.id}: not found`;
if (r.status === 'refused') return `proposal ${r.id}: ${r.action} refused (${r.reason})`;
@@ -53,27 +90,79 @@ async function listCommand(engine: BrainEngine, args: string[]): Promise<number>
const status = (flagValue(args, '--status') ?? 'pending') as ProposalStatus | 'all';
if (status !== 'all' && !(PROPOSAL_STATUSES as readonly string[]).includes(status)) { console.error(`--status must be one of ${PROPOSAL_STATUSES.join(', ')}, all`); return 1; }
const rows = await listProposals(engine, { status });
+ const review = (REVIEW_PROPOSAL_STATUSES as readonly string[]).includes(status) || status === 'all' ? await listReviewProposals(engine, { status }) : [];
if (args.includes('--json')) {
- console.log(JSON.stringify({ status, proposals: rows.map(({ before_state: _b, after_state: _a, ...r }) => r) }, null, 2));
+ console.log(JSON.stringify({ status, proposals: rows.map(({ before_state: _b, after_state: _a, ...r }) => r),
+ review_proposals: review.map(r => ({ ...r, id: `r${r.id}`, reversible: r.kind !== 'withdraw' })) }, null, 2));
return 0;
}
- if (rows.length === 0) { console.log(`No ${status === 'all' ? '' : `${status} `}proposals.`); return 0; }
+ if (rows.length === 0 && review.length === 0) { console.log(`No ${status === 'all' ? '' : `${status} `}proposals.`); return 0; }
+ const factIds = [...new Set(review.filter(r => r.kind === 'withdraw').flatMap(r => [Number(r.a_ref), Number(r.b_ref)]))];
+ const text = new Map((factIds.length ? await engine.executeRaw<{ id: number | string; fact: string }>('SELECT id, fact FROM facts WHERE id = ANY($1::bigint[])', [factIds]) : [])
+ .map(f => [String(Number(f.id)), f.fact] as [string, string]));
+ for (const r of review) for (const line of reviewRowLines(r, text)) console.log(line);
for (const r of rows) {
console.log(`#${r.id} [${r.status}] ${r.entity_slug ?? '(no entity)'} sweep ${r.sweep_id} p(supersede) ${r.p_supersede.toFixed(3)} (floor ${r.proposal_floor.toFixed(2)}, ${r.direction})`);
console.log(` new #${r.new_fact_id}: ${r.new_fact ?? '(fact missing)'}`);
console.log(` old #${r.old_fact_id}: ${r.old_fact ?? '(fact missing)'}`);
}
if (status === 'pending') console.log('Accept: gbrain decide proposals accept <id> | reject: gbrain decide proposals reject <id> | undo after accept: gbrain decide proposals undo <id>');
+ if (status === 'pending' && review.some(r => r.kind === 'withdraw')) {
+ console.log('WITHDRAW rows are permanent once accepted (the withdrawal ledger has no undo). These are owner decisions: an agent shows them to the user and accepts only what the user confirms. Accept: gbrain decide proposals accept r<id> --yes');
+ }
return 0;
}
+async function reviewActionCommand(engine: BrainEngine, action: 'accept' | 'reject' | 'undo', ids: number[], args: string[], bulk: boolean): Promise<{ results: ReviewActionResult[]; refusedForConfirmation: boolean }> {
+ const results: ReviewActionResult[] = [];
+ if (action === 'accept') {
+ const rows = (await listReviewProposals(engine, { status: 'all' })).filter(r => ids.includes(r.id) && r.kind === 'withdraw' && r.status === 'pending');
+ if (rows.length) {
+ const facts = rows.map(r => `#${r.b_ref}`).join(', ');
+ try {
+ await requireConsent({
+ command: 'decide proposals accept', effects: ['destructive'], actor: 'user',
+ what: `Permanently withdraw ${rows.length} fact(s) (${facts})`,
+ why: 'The overnight review judged each to restate a claim the user already forgot.',
+ risk: 'The withdrawal ledger has no undo; a wrong acceptance hides a true fact until the user remembers a corrected wording.',
+ user_message: `Withdraw ${facts} as rewordings of claims you already forgot? This cannot be undone.`,
+ argv: ['gbrain', 'decide', 'proposals', 'accept', ...(bulk ? ['--all-from', flagValue(args, '--all-from') ?? '', '--include-withdrawals'] : [`r${rows[0]!.id}`]), '--yes'],
+ args,
+ });
+ } catch (e) {
+ if (!isConsentRefusal(e)) throw e;
+ printConsentRefusal(e, { json: args.includes('--json') });
+ return { results, refusedForConfirmation: true };
+ }
+ }
+ }
+ for (const id of ids) {
+ try {
+ results.push(action === 'accept' ? await acceptReviewProposal(engine, id) : action === 'reject' ? await rejectReviewProposal(engine, id) : await undoReviewProposal(engine, id));
+ } catch (err) {
+ results.push({ id: `r${id}`, action, status: 'refused', reason: `write_failed: ${err instanceof Error ? err.message : String(err)}` });
+ }
+ }
+ return { results, refusedForConfirmation: false };
+}
+
async function actionCommand(engine: BrainEngine, action: 'accept' | 'reject' | 'undo', args: string[]): Promise<number> {
const json = args.includes('--json');
const sweep = flagValue(args, '--all-from');
+ const reviewArg = args.find((a) => /^r\d+$/i.test(a));
+ if (reviewArg && !sweep) {
+ const { results, refusedForConfirmation } = await reviewActionCommand(engine, action, [Number(reviewArg.slice(1))], args, false);
+ if (refusedForConfirmation) return 1;
+ if (json) console.log(JSON.stringify({ action, results }, null, 2)); else for (const r of results) console.log(reviewResultLine(r));
+ return results.every((r) => ['accepted', 'accepted_no_action', 'rejected', 'stale'].includes(r.status)) ? 0 : 1;
+ }
const idArg = args.find((a) => /^\d+$/.test(a));
if (action === 'undo' && sweep) { console.error('undo takes one proposal id'); return 1; }
if (!sweep && !idArg) { console.error(`Usage: gbrain decide proposals ${action} <id>${action === 'undo' ? '' : ' | --all-from <sweep id>'}`); return 1; }
const ids = sweep ? await proposalIdsFromSweep(engine, sweep, 'pending') : [Number(idArg)];
+ const reviewIds = sweep && action !== 'undo' ? await reviewProposalIdsFromSweep(engine, sweep, { includeWithdrawals: args.includes('--include-withdrawals') }) : [];
+ const review = reviewIds.length ? await reviewActionCommand(engine, action, reviewIds, args, true) : { results: [], refusedForConfirmation: false };
+ if (review.refusedForConfirmation) return 1;
const results: ProposalActionResult[] = [];
for (const id of ids) {
try {
@@ -82,17 +171,18 @@ async function actionCommand(engine: BrainEngine, action: 'accept' | 'reject' |
results.push({ id, action, status: 'refused', reason: `write_failed: ${err instanceof Error ? err.message : String(err)}` });
}
}
- if (json) console.log(JSON.stringify({ action, results }, null, 2));
- else if (results.length === 0) console.log(`No pending proposals in sweep ${sweep}.`);
- else for (const r of results) console.log(resultLine(r));
+ if (json) console.log(JSON.stringify({ action, results, review_results: review.results }, null, 2));
+ else if (results.length === 0 && review.results.length === 0) console.log(`No pending proposals in sweep ${sweep}.`);
+ else { for (const r of results) console.log(resultLine(r)); for (const r of review.results) console.log(reviewResultLine(r)); }
const ok = { accept: 'accepted', reject: 'rejected', undo: 'undone' }[action];
- return results.every((r) => r.status === ok || r.status === 'stale') ? 0 : 1;
+ return results.every((r) => r.status === ok || r.status === 'stale')
+ && review.results.every((r) => ['accepted', 'accepted_no_action', 'rejected', 'stale'].includes(r.status)) ? 0 : 1;
}
export async function runProposalsCommand(engine: BrainEngine, args: string[]): Promise<number> {
const sub = args[0] ?? 'list';
if (sub === 'list') return listCommand(engine, args.slice(1));
if (sub === 'accept' || sub === 'reject' || sub === 'undo') return actionCommand(engine, sub, args.slice(1));
- console.error('Usage: gbrain decide proposals list [--status <status>|all] [--json] | accept <id>|--all-from <sweep id> | reject <id>|--all-from <sweep id> | undo <id>');
+ console.error('Usage: gbrain decide proposals list [--status <status>|all] [--json] | accept <id>|r<id> [--yes]|--all-from <sweep id> [--include-withdrawals --yes] | reject <id>|r<id>|--all-from <sweep id> | undo <id>|r<id>');
return 1;
}
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index ec2ef96f0f..b46813256f 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -880,7 +880,7 @@ export async function runForget(engine: BrainEngine | (() => Promise<BrainEngine
const delegated = await maybeDelegateLocalOperation('forget', params, cfg, {
brain: cli.brain, source, timeoutMs: cli.timeoutMs ?? undefined,
});
- let result: { id: string; expired: boolean };
+ let result: { id: string; expired: boolean; similar_active?: { candidates?: Array<{ fact_id: string; similarity: number }>; next?: string } };
if (delegated.handled) result = delegated.result as typeof result;
else {
const connected = typeof engine === 'function' ? await engine() : engine;
@@ -890,7 +890,17 @@ export async function runForget(engine: BrainEngine | (() => Promise<BrainEngine
dryRun: false, sourceId, logger: { info: console.log, warn: console.warn, error: console.error } }, params) as typeof result;
}
if (json) console.log(JSON.stringify(result, null, 2));
- else process.stdout.write(result.expired ? `Forgot fact id=${id}\n` : `Fact id=${id} was already withdrawn\n`);
+ else {
+ process.stdout.write(result.expired ? `Forgot fact id=${id}\n` : `Fact id=${id} was already withdrawn\n`);
+ const similar = result.similar_active;
+ if (similar?.candidates?.length) {
+ process.stdout.write(`Close matches still active: ${similar.candidates.map(c => `#${c.fact_id} (${c.similarity})`).join(', ')}\n`);
+ }
+ if (similar?.next) {
+ const { agentBlock } = await import('../core/agent-markers.ts');
+ process.stderr.write(agentBlock({ next: similar.next }));
+ }
+ }
} catch (error) {
if (await reportPersistenceCliError(error, json)) return;
throw error;
diff --git a/src/core/ai/decide/config.ts b/src/core/ai/decide/config.ts
index e2e5ef0e9d..3cd816223c 100644
--- a/src/core/ai/decide/config.ts
+++ b/src/core/ai/decide/config.ts
@@ -62,6 +62,9 @@ const GLOBAL_KEYS: Record<string, Validator> = {
'decide.receipts.retention_days': number(1, 365, true),
'decide.calibrate.retest_n': number(0, 1000, true),
'decide.slots.conflict.proposal_floor': number(0, 1),
+ 'decide.slots.conflict.review_withdraw': bool,
+ 'decide.slots.conflict.review_duplicate_page': bool,
+ 'decide.slots.conflict.review_duplicate_entity': bool,
'decide.slots.intent.wait_ms': number(0, 2000, true),
'decide.slots.recall_needed.suppress_below': number(0, 1),
...Object.fromEntries(EVIDENCE_CLASSES.map((c) => [`decide.egress.typesafe.${c}`, oneOf('deny', 'allow')])),
diff --git a/src/core/ai/decide/review-lane.ts b/src/core/ai/decide/review-lane.ts
new file mode 100644
index 0000000000..2d672efc82
--- /dev/null
+++ b/src/core/ai/decide/review-lane.ts
@@ -0,0 +1,426 @@
+/**
+ * The ambiguous-band review lane: model-judged, owner-accepted review of pairs
+ * a cosine threshold cannot settle. Kinds:
+ *
+ * withdraw an active fact that may restate a withdrawn (forgotten)
+ * claim; accepting withdraws it the same way `forget` does.
+ * duplicate_page two pages that may describe the same thing (candidates
+ * enqueued by the page-duplicate detector).
+ * duplicate_entity two entity pages left ambiguous by deterministic entity
+ * dedup (candidates enqueued by entity resolution).
+ *
+ * Rides the `conflict` slot's provider, egress and spend controls, with one
+ * call site per kind (`review_<kind>`) so each kind has its own calibration
+ * and qualification. A kind proposes only when its calibration is qualified
+ * for action precision (decide.slots.conflict.min_action_precision); without
+ * that it does not call the provider at all. Never applies anything itself:
+ * outcomes are pending rows in decide_review_proposals, reviewed with
+ * `gbrain decide proposals`. Work is durable in decide_review_queue, written in
+ * the same transaction as the event that created it (a withdrawal, or the
+ * owning subsystem's enqueue), so nothing is skipped by a timestamp cursor.
+ */
+import { randomBytes } from 'node:crypto';
+import type { BrainEngine } from '../../engine.ts';
+import { loadConfigSnapshot } from '../../config-snapshot.ts';
+import { readDecideConfig, type DecideConfig } from './config.ts';
+import { CONFLICT_INSTRUCTIONS, CONFLICT_MIN_COSINE, CONFLICT_NEIGHBOURS, CONFLICT_OPTIONS } from './conflict.ts';
+import { hasTypesafeKey, runDecide } from './index.ts';
+import { packShape } from './pack.ts';
+import { resolveSlotPolicy, type SlotPolicy } from './policy.ts';
+import { writeReceipts } from './receipts.ts';
+import { flushDecideWrites, hmacRef, listCalibrations, receiptSalt, recentResolvedModels } from './store.ts';
+import { DecideError, type ChoiceAnswer, type DecideQuestion, type EvidenceItem } from './types.ts';
+
+export const REVIEW_KINDS = ['withdraw', 'duplicate_page', 'duplicate_entity'] as const;
+export type ReviewKind = typeof REVIEW_KINDS[number];
+
+export const REVIEW_CALL_SITES: Readonly<Record<ReviewKind, string>> = {
+ withdraw: 'review_withdraw', duplicate_page: 'review_duplicate_page', duplicate_entity: 'review_duplicate_entity',
+};
+export const REVIEW_CONFIG_KEYS: Readonly<Record<ReviewKind, string>> = {
+ withdraw: 'decide.slots.conflict.review_withdraw',
+ duplicate_page: 'decide.slots.conflict.review_duplicate_page',
+ duplicate_entity: 'decide.slots.conflict.review_duplicate_entity',
+};
+/** Anchors (or pairs) judged per kind per run, so one kind never starves another. */
+export const REVIEW_BUDGET_PER_RUN = 50;
+const REVIEW_MAX_ATTEMPTS = 5;
+const REVIEW_REQUEST_DEADLINE_MS = 30_000;
+const PAGE_TEXT_LIMIT = 2_000;
+const PERMANENT_FAILURES = new Set(['egress', 'payload_too_large']);
+export const REVIEW_QUESTION_VERSION = 1;
+
+const SAME_OPTIONS: Readonly<Record<'same' | 'different', string>> = {
+ same: '`page` and `candidate` describe the same real-world person, company, place, project or idea',
+ different: '`page` and `candidate` describe different things, even if related',
+};
+const SAME_INSTRUCTIONS = 'Do `page` and `candidate` describe the same thing?';
+
+export interface ReviewLaneResult {
+ kind: ReviewKind;
+ source_id: string;
+ sweep_id: string;
+ effective: 'on' | 'shadow' | 'off';
+ inactive?: string;
+ anchors: number;
+ pairs: number;
+ proposals: number;
+ shadow_proposals: number;
+ independents: number;
+ skipped: number;
+ deferred: number;
+ stopped?: string;
+}
+
+const truthy = (v: string | undefined | null) => ['true', 'on', '1', 'yes'].includes((v ?? '').trim().toLowerCase());
+
+export function reviewKindEnabled(snapshot: Record<string, string | undefined> | null, kind: ReviewKind): boolean {
+ return truthy(snapshot?.[REVIEW_CONFIG_KEYS[kind]]);
+}
+
+// ---------------------------------------------------------------------------
+// Enqueue API (other subsystems) and accept-handler registry
+// ---------------------------------------------------------------------------
+
+export interface ReviewCandidate {
+ kind: Exclude<ReviewKind, 'withdraw'>;
+ source_id: string;
+ /** Page slugs within `source_id`. */
+ a_ref: string;
+ b_ref: string;
+ /** Why the pair was flagged (e.g. `cosine 0.86`); stored, never sent to a provider. */
+ evidence?: string;
+}
+
+/** Queue a candidate pair for review; call inside the transaction that discovered it. Idempotent per pair. */
+export async function enqueueReviewCandidate(tx: BrainEngine, c: ReviewCandidate): Promise<void> {
+ const [a, b] = c.a_ref <= c.b_ref ? [c.a_ref, c.b_ref] : [c.b_ref, c.a_ref];
+ await tx.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref,b_ref,evidence) VALUES ($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`,
+ [c.kind, c.source_id, a, b, c.evidence ?? null]);
+}
+
+export interface ReviewProposalRow {
+ id: number;
+ kind: ReviewKind;
+ source_id: string;
+ sweep_id: string;
+ a_ref: string;
+ b_ref: string;
+ subject: string;
+ visibility: string | null;
+ p_action: number;
+ threshold: number | null;
+ model_resolved: string | null;
+ status: string;
+ created_at: string;
+ decided_at: string | null;
+ receipt: string | null;
+}
+
+/** What accepting a duplicate-kind proposal does; registered by the subsystem that owns the merge or link. */
+export type ReviewAcceptHandler = (engine: BrainEngine, proposal: ReviewProposalRow) => Promise<{ status: 'accepted' | 'stale'; detail?: string }>;
+const acceptHandlers = new Map<ReviewKind, ReviewAcceptHandler>();
+export function registerReviewAcceptHandler(kind: Exclude<ReviewKind, 'withdraw'>, handler: ReviewAcceptHandler): void {
+ acceptHandlers.set(kind, handler);
+}
+export function reviewAcceptHandler(kind: ReviewKind): ReviewAcceptHandler | undefined { return acceptHandlers.get(kind); }
+
+// ---------------------------------------------------------------------------
+// Queue
+// ---------------------------------------------------------------------------
+
+interface QueueRow { kind: ReviewKind; source_id: string; a_ref: string; b_ref: string; attempts: number }
+
+async function dueQueue(engine: BrainEngine, kind: ReviewKind, sourceId: string, limit: number): Promise<QueueRow[]> {
+ const rows = await engine.executeRaw<QueueRow>(
+ `SELECT kind, source_id, a_ref, b_ref, attempts FROM decide_review_queue
+ WHERE kind = $1 AND source_id = $2 AND attempts < $3 AND next_attempt_at <= now()
+ ORDER BY next_attempt_at, created_at, a_ref, b_ref LIMIT $4`, [kind, sourceId, REVIEW_MAX_ATTEMPTS, limit]);
+ return rows.map(r => ({ ...r, attempts: Number(r.attempts) }));
+}
+
+async function clearQueue(engine: BrainEngine, row: QueueRow): Promise<void> {
+ await engine.executeRaw('DELETE FROM decide_review_queue WHERE kind=$1 AND source_id=$2 AND a_ref=$3 AND b_ref=$4', [row.kind, row.source_id, row.a_ref, row.b_ref]);
+}
+
+async function deferQueue(engine: BrainEngine, row: QueueRow, reason: string): Promise<void> {
+ await engine.executeRaw(`UPDATE decide_review_queue SET attempts = attempts + 1, reason = $5,
+ next_attempt_at = now() + ((attempts + 1) * interval '10 minutes')
+ WHERE kind=$1 AND source_id=$2 AND a_ref=$3 AND b_ref=$4`, [row.kind, row.source_id, row.a_ref, row.b_ref, reason]);
+}
+
+/**
+ * A fact the conflict sweep just processed may restate a claim already withdrawn
+ * for its entity: re-queue up to two such withdrawn anchors so the next lane run
+ * compares them against their current neighbours (pair dedup skips old pairs).
+ */
+export async function requeueWithdrawnAnchorsNear(engine: BrainEngine, sourceId: string, factId: number): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number | string }>(
+ `SELECT c.id FROM facts n JOIN facts c
+ ON c.source_id = n.source_id AND c.entity_slug = n.entity_slug AND c.visibility = n.visibility AND c.id <> n.id
+ WHERE n.id = $1 AND n.source_id = $2 AND c.expired_at IS NOT NULL
+ AND c.embedding IS NOT NULL AND n.embedding IS NOT NULL AND c.embedding_model = n.embedding_model
+ AND (1 - (c.embedding <=> n.embedding)) >= $3
+ AND EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = c.source_id AND w.visibility = c.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(c.fact), gbrain_fact_fingerprint_v1(c.fact))
+ AND (w.subject = '*' OR w.subject = c.entity_slug))
+ ORDER BY c.embedding <=> n.embedding, c.id LIMIT 2`, [factId, sourceId, CONFLICT_MIN_COSINE]);
+ for (const r of rows) {
+ await engine.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw',$1,$2)
+ ON CONFLICT (kind, source_id, a_ref, b_ref) DO UPDATE SET next_attempt_at = LEAST(decide_review_queue.next_attempt_at, now())`, [sourceId, String(r.id)]);
+ }
+ return rows.length;
+}
+
+// ---------------------------------------------------------------------------
+// Judging
+// ---------------------------------------------------------------------------
+
+interface Pair {
+ /** Plain subject identity (hashed into the receipt). */
+ subject: string;
+ b_ref: string;
+ candidate: EvidenceItem;
+ candidateHash?: string;
+}
+
+interface Anchor {
+ a_ref: string;
+ subject: string;
+ visibility: string | null;
+ state: Record<string, EvidenceItem>;
+ pairs: Pair[];
+}
+
+/** P(action) for one answer: P(duplicate) for withdraw, P(same) for duplicate kinds. */
+export function reviewActionProbability(kind: ReviewKind, answer: ChoiceAnswer): number {
+ const key = kind === 'withdraw' ? 'duplicate' : 'same';
+ return answer.probabilities[key] ?? (answer.choice === key ? answer.confidence : 0);
+}
+
+function question(kind: ReviewKind, id: string, rank: number, candidate: EvidenceItem): DecideQuestion {
+ return kind === 'withdraw'
+ ? { id, kind: 'choice', rank, instructions: CONFLICT_INSTRUCTIONS, options: { ...CONFLICT_OPTIONS }, inputs: { candidate } }
+ : { id, kind: 'choice', rank, instructions: SAME_INSTRUCTIONS, options: { ...SAME_OPTIONS }, inputs: { candidate } };
+}
+
+async function withdrawAnchor(engine: BrainEngine, row: QueueRow, cfg: DecideConfig): Promise<Anchor | { skip: string }> {
+ const anchorId = Number(row.a_ref);
+ if (!Number.isSafeInteger(anchorId)) return { skip: 'no_candidates' };
+ const [anchor] = await engine.executeRaw<{ id: number; fact: string; entity_slug: string | null; visibility: 'private' | 'world'; has_embedding: boolean; withdrawn: boolean }>(
+ `SELECT f.id, f.fact, f.entity_slug, f.visibility, f.embedding IS NOT NULL AS has_embedding,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = f.source_id AND w.visibility = f.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact))
+ AND (w.subject = '*' OR w.subject = COALESCE(f.entity_slug, '*'))) AS withdrawn
+ FROM facts f WHERE f.id = $1 AND f.source_id = $2`, [anchorId, row.source_id]);
+ if (!anchor || !anchor.withdrawn) return { skip: 'no_candidates' };
+ if (!anchor.has_embedding) return { skip: 'no_embedding' };
+ // A forgotten private claim is sent only when the owner explicitly allows private egress (not by key default).
+ if (anchor.visibility === 'private' && cfg.egressPrivate !== 'allow') return { skip: 'egress_private_denied' };
+ const rows = await engine.executeRaw<{ id: number | string; fact: string; visibility: 'private' | 'world'; text_hash: string }>(
+ `SELECT c.id, c.fact, c.visibility, md5(c.fact) AS text_hash
+ FROM facts n JOIN facts c
+ ON c.source_id = n.source_id AND c.entity_slug IS NOT DISTINCT FROM n.entity_slug AND c.visibility = n.visibility AND c.id <> n.id
+ WHERE n.id = $1 AND n.source_id = $2
+ AND c.expired_at IS NULL AND (c.valid_until IS NULL OR c.valid_until > now())
+ AND c.embedding IS NOT NULL AND c.embedding_model = n.embedding_model
+ AND gbrain_fact_fingerprint(c.fact) <> gbrain_fact_fingerprint(n.fact)
+ AND (1 - (c.embedding <=> n.embedding)) >= $3
+ ORDER BY c.embedding <=> n.embedding, c.id LIMIT $4`, [anchorId, row.source_id, CONFLICT_MIN_COSINE, CONFLICT_NEIGHBOURS]);
+ const subject = anchor.entity_slug ?? '*';
+ return {
+ a_ref: row.a_ref, subject, visibility: anchor.visibility,
+ state: { fact: { text: anchor.fact, class: 'facts', fact_id: anchor.id, source_id: row.source_id, visibility: anchor.visibility } },
+ pairs: rows.map(c => ({
+ subject: `review:withdraw:${row.source_id}:${anchorId}:${Number(c.id)}`, b_ref: String(Number(c.id)), candidateHash: c.text_hash,
+ candidate: { text: c.fact, class: 'facts', fact_id: Number(c.id), source_id: row.source_id, visibility: c.visibility },
+ })),
+ };
+}
+
+async function pagePairAnchor(engine: BrainEngine, row: QueueRow): Promise<Anchor | { skip: string }> {
+ const pages = await engine.executeRaw<{ slug: string; title: string; compiled_truth: string }>(
+ `SELECT slug, title, compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,
+ [row.source_id, [row.a_ref, row.b_ref]]);
+ const a = pages.find(p => p.slug === row.a_ref);
+ const b = pages.find(p => p.slug === row.b_ref);
+ if (!a || !b) return { skip: 'no_candidates' };
+ const text = (p: { title: string; compiled_truth: string }) => `${p.title}\n\n${p.compiled_truth}`.slice(0, PAGE_TEXT_LIMIT);
+ return {
+ a_ref: row.a_ref, subject: '*', visibility: null,
+ state: { page: { text: text(a), class: 'candidates', slug: a.slug, source_id: row.source_id } },
+ pairs: [{ subject: `review:${row.kind}:${row.source_id}:${row.a_ref}:${row.b_ref}`, b_ref: row.b_ref,
+ candidate: { text: text(b), class: 'candidates', slug: b.slug, source_id: row.source_id } }],
+ };
+}
+
+async function answeredSubjects(engine: BrainEngine, refs: readonly string[]): Promise<Set<string>> {
+ if (refs.length === 0) return new Set();
+ const rows = await engine.executeRaw<{ subject_ref: string }>(
+ `SELECT DISTINCT subject_ref FROM decision_receipts WHERE slot = 'conflict' AND subject_ref = ANY($1::text[]) AND outcome IN ('proposal', 'independent')`, [refs]);
+ return new Set(rows.map(r => r.subject_ref));
+}
+
+/** Whether a kind may act: on, and its calibration qualified for action precision. */
+export function reviewGate(policy: SlotPolicy, cfg: DecideConfig): { effective: 'on' | 'shadow' | 'off'; inactive?: string } {
+ if (policy.requested === 'off') return { effective: 'off' };
+ if (policy.effective === 'off') return { effective: 'off', inactive: policy.inactive ?? 'no_provider' };
+ if (policy.requested === 'shadow') return { effective: 'shadow' };
+ const c = policy.calibration;
+ if (policy.thresholdSource === 'override') return { effective: 'off', inactive: 'no_qualification' };
+ if (!c || c.action_precision_lb === null) return { effective: 'off', inactive: 'no_qualification' };
+ if (c.action_precision_lb < cfg.slots.conflict.minActionPrecision) return { effective: 'off', inactive: 'action_precision_low' };
+ if (c.policy_fingerprint && c.policy_fingerprint !== policy.fingerprint) return { effective: 'off', inactive: 'policy_changed' };
+ return { effective: 'on' };
+}
+
+export async function runReviewLane(engine: BrainEngine, opts: { kind: ReviewKind; sourceId?: string; signal?: AbortSignal; maxAnchors?: number; deadlineMs?: number }): Promise<ReviewLaneResult> {
+ const kind = opts.kind;
+ const sourceId = opts.sourceId ?? 'default';
+ const snapshot = await loadConfigSnapshot(engine);
+ const cfg = readDecideConfig(snapshot, { typesafeKey: hasTypesafeKey() });
+ const sweepId = `${new Date().toISOString().replace(/[-:]/g, '').slice(0, 15)}-r${randomBytes(3).toString('hex')}`;
+ const result: ReviewLaneResult = { kind, source_id: sourceId, sweep_id: sweepId, effective: 'off', anchors: 0, pairs: 0, proposals: 0,
+ shadow_proposals: 0, independents: 0, skipped: 0, deferred: 0 };
+ if (!reviewKindEnabled(snapshot, kind)) return { ...result, inactive: 'review_kind_off' };
+ const [calibrations, recent] = await Promise.all([listCalibrations(engine, { slot: 'conflict' }), recentResolvedModels(engine, 24 * 7)]);
+ const lastResolved: Record<string, string> = {};
+ for (const row of recent) lastResolved[row.provider] ??= row.model_resolved;
+ const callSite = REVIEW_CALL_SITES[kind];
+ const policy = resolveSlotPolicy({ cfg, slot: 'conflict', callSite, packShape: packShape('conflict'), calibrations, lastResolved, hasTypesafeKey: hasTypesafeKey() });
+ const gate = reviewGate(policy, cfg);
+ result.effective = gate.effective;
+ if (gate.inactive) result.inactive = gate.inactive;
+ if (gate.effective === 'off') return result;
+ const mode = gate.effective;
+ const salt = await receiptSalt(engine);
+ const receipts: Promise<void>[] = [];
+ const due = await dueQueue(engine, kind, sourceId, opts.maxAnchors ?? REVIEW_BUDGET_PER_RUN);
+ for (const row of due) {
+ if (opts.signal?.aborted) { result.stopped = 'aborted'; break; }
+ result.anchors++;
+ const built = kind === 'withdraw' ? await withdrawAnchor(engine, row, cfg) : await pagePairAnchor(engine, row);
+ if ('skip' in built) {
+ result.skipped++;
+ if (built.skip === 'no_embedding') { await deferQueue(engine, row, built.skip); result.deferred++; } else await clearQueue(engine, row);
+ continue;
+ }
+ const refs = built.pairs.map(p => hmacRef(salt, p.subject));
+ const answered = await answeredSubjects(engine, refs);
+ const pairs = built.pairs.filter((_, i) => !answered.has(refs[i]!));
+ if (pairs.length === 0) { await clearQueue(engine, row); continue; }
+ const questions = pairs.map((p, i) => question(kind, `review:${i}`, i, p.candidate));
+ const subjects = Object.fromEntries(pairs.map((p, i) => [`review:${i}`, p.subject]));
+ const base = { slot: 'conflict' as const, callSite, lane: 'background' as const, state: built.state, subjects, sourceId };
+ let r;
+ try {
+ r = await runDecide({ slot: 'conflict', callSite, state: built.state, questions, deadlineMs: opts.deadlineMs ?? REVIEW_REQUEST_DEADLINE_MS,
+ provider: policy.provider, lane: 'background', signal: opts.signal }, { engine, config: cfg, sourceId });
+ } catch (err) {
+ const reason = err instanceof DecideError ? err.reason : 'provider_error';
+ receipts.push(writeReceipts(engine, { ...base, mode, provider: policy.provider, policy, questions, outcomes: {}, fallbackOutcome: 'error', reason }));
+ result.skipped++;
+ if (PERMANENT_FAILURES.has(reason)) await clearQueue(engine, row);
+ else { await deferQueue(engine, row, reason); result.deferred++; }
+ if (reason === 'budget_exhausted' || opts.signal?.aborted) { result.stopped = opts.signal?.aborted ? 'aborted' : reason; break; }
+ continue;
+ }
+ const outcomes: Record<string, string> = {};
+ for (const [i, pair] of pairs.entries()) {
+ const answer = r.answers[`review:${i}`];
+ if (!answer || answer.kind !== 'choice') continue;
+ result.pairs++;
+ const p = reviewActionProbability(kind, answer);
+ const act = policy.threshold !== undefined ? p >= policy.threshold : answer.choice === (kind === 'withdraw' ? 'duplicate' : 'same');
+ if (!act) { outcomes[`review:${i}`] = 'independent'; result.independents++; continue; }
+ outcomes[`review:${i}`] = 'proposal';
+ if (mode !== 'on') { result.shadow_proposals++; continue; }
+ const inserted = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO decide_review_proposals (kind, source_id, sweep_id, a_ref, b_ref, subject, visibility, p_action, threshold, model_resolved, question_version, receipt)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT DO NOTHING RETURNING id`,
+ [kind, sourceId, sweepId, built.a_ref, pair.b_ref, built.subject, built.visibility, p, policy.threshold ?? null, r.model_resolved || null,
+ String(REVIEW_QUESTION_VERSION), JSON.stringify({ candidate_hash: pair.candidateHash ?? null, call_site: callSite })]);
+ if (inserted.length) result.proposals++;
+ }
+ receipts.push(writeReceipts(engine, { ...base, mode, provider: policy.provider, policy, result: r, questions, outcomes, fallbackOutcome: 'skipped' }));
+ await clearQueue(engine, row);
+ }
+ await Promise.all(receipts);
+ await flushDecideWrites();
+ return result;
+}
+
+/** Every enabled review kind for one source; undefined when none is enabled. */
+export async function runReviewLanes(engine: BrainEngine, sourceId: string, signal?: AbortSignal): Promise<ReviewLaneResult[] | undefined> {
+ const snapshot = await loadConfigSnapshot(engine);
+ const kinds = REVIEW_KINDS.filter(k => reviewKindEnabled(snapshot, k));
+ if (kinds.length === 0) return undefined;
+ const out: ReviewLaneResult[] = [];
+ for (const kind of kinds) out.push(await runReviewLane(engine, { kind, sourceId, signal }));
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Proposals store
+// ---------------------------------------------------------------------------
+
+export const REVIEW_PROPOSAL_STATUSES = ['pending', 'accepted', 'rejected', 'stale', 'accepted_no_action'] as const;
+
+export async function listReviewProposals(engine: BrainEngine, filter: { status?: string | 'all' } = {}): Promise<ReviewProposalRow[]> {
+ const status = filter.status ?? 'pending';
+ const rows = await engine.executeRaw<ReviewProposalRow>(
+ `SELECT id, kind, source_id, sweep_id, a_ref, b_ref, subject, visibility, p_action, threshold, model_resolved, status,
+ created_at::text, decided_at::text, receipt
+ FROM decide_review_proposals WHERE ($1 = 'all' OR status = $1) ORDER BY id`, [status]);
+ return rows.map(r => ({ ...r, id: Number(r.id), p_action: Number(r.p_action), threshold: r.threshold === null ? null : Number(r.threshold) }));
+}
+
+export async function getReviewProposal(engine: BrainEngine, id: number, lock = false): Promise<ReviewProposalRow | null> {
+ const rows = await engine.executeRaw<ReviewProposalRow>(
+ `SELECT id, kind, source_id, sweep_id, a_ref, b_ref, subject, visibility, p_action, threshold, model_resolved, status,
+ created_at::text, decided_at::text, receipt FROM decide_review_proposals WHERE id = $1${lock ? ' FOR UPDATE' : ''}`, [id]);
+ const r = rows[0];
+ return r ? { ...r, id: Number(r.id), p_action: Number(r.p_action), threshold: r.threshold === null ? null : Number(r.threshold) } : null;
+}
+
+export async function transitionReviewProposal(engine: BrainEngine, id: number, from: string, to: string): Promise<boolean> {
+ const rows = await engine.executeRaw(`UPDATE decide_review_proposals SET status = $3, decided_at = now() WHERE id = $1 AND status = $2 RETURNING id`, [id, from, to]);
+ return rows.length > 0;
+}
+
+export async function reviewProposalIdsFromSweep(engine: BrainEngine, sweepId: string, opts: { includeWithdrawals: boolean }): Promise<number[]> {
+ const rows = await engine.executeRaw<{ id: number | string }>(
+ `SELECT id FROM decide_review_proposals WHERE sweep_id = $1 AND status = 'pending' AND ($2::boolean OR kind <> 'withdraw') ORDER BY id`,
+ [sweepId, opts.includeWithdrawals]);
+ return rows.map(r => Number(r.id));
+}
+
+export interface ProposalReviewRate {
+ kind: 'supersede' | ReviewKind;
+ enabled: boolean;
+ pending: number;
+ oldest_pending_days: number | null;
+ accepted_30d: number;
+ rejected_30d: number;
+}
+
+/** Whether owners act on proposals: pending backlog and 30-day decisions per kind (supersede proposals and each review kind). */
+export async function proposalReviewRates(engine: BrainEngine): Promise<ProposalReviewRate[]> {
+ const snapshot = await loadConfigSnapshot(engine);
+ const sql = (table: string, kindExpr: string) => `SELECT ${kindExpr} AS kind,
+ count(*) FILTER (WHERE status = 'pending')::int AS pending,
+ EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE status = 'pending'))) / 86400.0 AS oldest,
+ count(*) FILTER (WHERE status IN ('accepted', 'accepted_no_action') AND decided_at > now() - interval '30 days')::int AS accepted,
+ count(*) FILTER (WHERE status = 'rejected' AND decided_at > now() - interval '30 days')::int AS rejected
+ FROM ${table} GROUP BY 1`;
+ const rows = [
+ ...await engine.executeRaw<{ kind: string; pending: number; oldest: number | null; accepted: number; rejected: number }>(sql('decide_proposals', `'supersede'`)),
+ ...await engine.executeRaw<{ kind: string; pending: number; oldest: number | null; accepted: number; rejected: number }>(sql('decide_review_proposals', 'kind')),
+ ];
+ return (['supersede', ...REVIEW_KINDS] as const).map((kind) => {
+ const r = rows.find(x => x.kind === kind);
+ return { kind, enabled: kind === 'supersede' || reviewKindEnabled(snapshot, kind), pending: Number(r?.pending ?? 0),
+ oldest_pending_days: r?.oldest == null ? null : Math.round(Number(r.oldest) * 10) / 10,
+ accepted_30d: Number(r?.accepted ?? 0), rejected_30d: Number(r?.rejected ?? 0) };
+ });
+}
diff --git a/src/core/ai/decide/schema.ts b/src/core/ai/decide/schema.ts
index a240ed81e5..0e2e39b16a 100644
--- a/src/core/ai/decide/schema.ts
+++ b/src/core/ai/decide/schema.ts
@@ -147,4 +147,48 @@ ${rls('decide_proposals')}
${rls('decide_sweep_deferred')}
`;
-export const DECIDE_SCHEMA_SQL = `${DECIDE_RECEIPTS_SCHEMA_SQL}${DECIDE_CALIBRATIONS_SCHEMA_SQL}${DECIDE_PROPOSALS_SCHEMA_SQL}`;
+/**
+ * The ambiguous-band review lane: decide_review_queue holds durable review work
+ * (a withdrawn fact to compare against its neighbours, or a candidate pair
+ * another subsystem enqueued); decide_review_proposals holds owner-reviewed
+ * outcomes per kind (withdraw | duplicate_page | duplicate_entity). Separate
+ * from decide_proposals so a binary that predates review kinds never reads them.
+ */
+export const DECIDE_REVIEW_SCHEMA_SQL = `
+CREATE TABLE IF NOT EXISTS decide_review_queue (
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL DEFAULT '*',
+ evidence TEXT,
+ reason TEXT NOT NULL DEFAULT 'queued',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kind, source_id, a_ref, b_ref)
+);
+CREATE TABLE IF NOT EXISTS decide_review_proposals (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ sweep_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL,
+ subject TEXT NOT NULL DEFAULT '*',
+ visibility TEXT,
+ p_action REAL NOT NULL,
+ threshold REAL,
+ model_resolved TEXT,
+ question_version TEXT,
+ status TEXT NOT NULL DEFAULT 'pending',
+ decided_at TIMESTAMPTZ,
+ receipt TEXT,
+ UNIQUE (kind, source_id, a_ref, b_ref, subject)
+);
+CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);
+${rls('decide_review_queue')}
+${rls('decide_review_proposals')}
+`;
+
+export const DECIDE_SCHEMA_SQL = `${DECIDE_RECEIPTS_SCHEMA_SQL}${DECIDE_CALIBRATIONS_SCHEMA_SQL}${DECIDE_PROPOSALS_SCHEMA_SQL}${DECIDE_REVIEW_SCHEMA_SQL}`;
diff --git a/src/core/ai/decide/slots.ts b/src/core/ai/decide/slots.ts
index ac5ee3f074..1e2e4384fc 100644
--- a/src/core/ai/decide/slots.ts
+++ b/src/core/ai/decide/slots.ts
@@ -72,7 +72,8 @@ export const SLOT_SPECS: Readonly<Record<DecideSlot, SlotSpec>> = {
failDirection: 'keep the mechanical verification result', wired: true,
},
conflict: {
- slot: 'conflict', lane: 'background', questionKind: 'choice', harmful: false, thresholded: true, callSites: ['sweep'],
+ slot: 'conflict', lane: 'background', questionKind: 'choice', harmful: false, thresholded: true,
+ callSites: ['sweep', 'review_withdraw', 'review_duplicate_page', 'review_duplicate_entity'],
egressClasses: ['facts'], shadowSample: 1, whatIfReproducible: false, questionVersion: 1,
failDirection: 'no proposal; the fact stays as written', wired: true,
},
diff --git a/src/core/ai/decide/sweep.ts b/src/core/ai/decide/sweep.ts
index 2b590ac48c..efd9a6d0df 100644
--- a/src/core/ai/decide/sweep.ts
+++ b/src/core/ai/decide/sweep.ts
@@ -32,6 +32,7 @@ import {
insertProposal, maxFactId, proposedPairs, setSweepWatermark, type ConflictCandidateRow, type SweepFact,
} from './proposals-store.ts';
import { writeReceipts } from './receipts.ts';
+import { requeueWithdrawnAnchorsNear, reviewKindEnabled, runReviewLanes } from './review-lane.ts';
import { flushDecideWrites, hmacRef, listCalibrations, receiptSalt, recentResolvedModels } from './store.ts';
import { DecideError, type DecideQuestion, type DecideResult } from './types.ts';
@@ -102,6 +103,8 @@ interface SweepContext {
result: ConflictSweepResult;
receipts: Promise<void>[];
signal?: AbortSignal;
+ /** Withdrawal review is on: a swept fact re-queues withdrawn claims it may restate. */
+ reviewWithdraw: boolean;
}
const factQuestion: DecideQuestion = { id: 'conflict:fact', kind: 'choice', instructions: CONFLICT_INSTRUCTIONS, options: { ...CONFLICT_OPTIONS } };
@@ -227,6 +230,7 @@ async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Pr
result.deferred++;
return true;
}
+ if (ctx.reviewWithdraw) await requeueWithdrawnAnchorsNear(engine, fact.source_id, fact.id);
const candidates = await candidatesFor(ctx, fact);
if (candidates.length === 0) {
if (retry) await clearDeferred(engine, fact.source_id, fact.id);
@@ -279,6 +283,7 @@ export async function runConflictSweep(engine: BrainEngine, opts: ConflictSweepO
const ctx: SweepContext = {
engine, cfg, policy, floor: proposalFloor(snapshot, policy.thresholdSource === 'override' ? undefined : policy.calibration?.proposal_floor), sweepId: result.sweep_id, sourceId, salt: await receiptSalt(engine),
judged: new Set(), pairIndex: 0, deadlineMs: opts.deadlineMs ?? SWEEP_REQUEST_DEADLINE_MS, now, result, receipts: [], signal: opts.signal,
+ reviewWithdraw: reviewKindEnabled(snapshot, 'withdraw'),
};
const max = opts.maxFacts ?? SWEEP_MAX_FACTS;
let going = true;
@@ -315,9 +320,11 @@ export async function conflictSweepTail(engine: BrainEngine, sourceId: string, s
if (cfg.slots.conflict.mode === 'off') return undefined;
try {
const r = await runConflictSweep(engine, { sourceId, signal });
+ const review = await runReviewLanes(engine, sourceId, signal).catch((err) => [{ error: err instanceof Error ? err.message : String(err) }]);
return {
sweep_id: r.sweep_id, effective: r.effective, ...(r.inactive ? { inactive: r.inactive } : {}), facts: r.facts, duplicates: r.duplicates,
proposals: r.proposals, independents: r.independents, skipped: r.skipped, deferred: r.deferred,
+ ...(review ? { review } : {}),
};
} catch (err) {
return { error: err instanceof Error ? err.message : String(err) };
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 742267af39..9127ae4368 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -39,14 +39,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],
- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],
+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--include-withdrawals', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
- 'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--min', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
diff --git a/src/core/facts/proposal-review.ts b/src/core/facts/proposal-review.ts
new file mode 100644
index 0000000000..3ac4b1a558
--- /dev/null
+++ b/src/core/facts/proposal-review.ts
@@ -0,0 +1,107 @@
+/**
+ * Owner actions on ambiguous-band review proposals (`gbrain decide proposals`).
+ *
+ * withdraw: accepting re-checks that the anchor is still withdrawn and the
+ * candidate is still active with unchanged text, then withdraws the candidate
+ * through the ordinary `forget` operation (same fence strike, ledger row and
+ * page invalidation as a manual forget) with a request id derived from the
+ * proposal, so a crash between the forget and the status change replays the
+ * same withdrawal instead of making a second one. The withdrawal ledger is
+ * durable, so there is no undo. duplicate kinds: accepting runs the handler the
+ * owning subsystem registered, or records the owner's verdict when none is.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { loadConfig } from '../config.ts';
+import {
+ getReviewProposal, reviewAcceptHandler, transitionReviewProposal, type ReviewProposalRow,
+} from '../ai/decide/review-lane.ts';
+
+export interface ReviewActionResult {
+ id: string;
+ action: 'accept' | 'reject' | 'undo';
+ status: 'accepted' | 'accepted_no_action' | 'rejected' | 'stale' | 'refused' | 'not_found';
+ reason?: string;
+ fix?: string;
+}
+
+/** Deterministic UUID (v4 layout) for the forget a withdraw proposal performs. */
+export function reviewRequestId(id: number): string {
+ const h = createHash('sha256').update(`decide-review:${id}`).digest('hex');
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16]!, 16) & 0x3) | 0x8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+async function staleReason(engine: BrainEngine, p: ReviewProposalRow): Promise<string | null> {
+ if (p.kind !== 'withdraw') return null;
+ const [anchor] = await engine.executeRaw<{ withdrawn: boolean }>(
+ `SELECT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = f.source_id AND w.visibility = f.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact))
+ AND (w.subject = '*' OR w.subject = COALESCE(f.entity_slug, '*'))) AS withdrawn
+ FROM facts f WHERE f.id = $1 AND f.source_id = $2`, [Number(p.a_ref), p.source_id]);
+ if (!anchor?.withdrawn) return 'the withdrawn claim is no longer withdrawn';
+ const [candidate] = await engine.executeRaw<{ active: boolean; text_hash: string }>(
+ `SELECT (expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())) AS active, md5(fact) AS text_hash
+ FROM facts WHERE id = $1 AND source_id = $2`, [Number(p.b_ref), p.source_id]);
+ if (!candidate?.active) return 'the affected fact is no longer active';
+ let expected: string | null = null;
+ try { expected = (JSON.parse(p.receipt ?? '{}') as { candidate_hash?: string | null }).candidate_hash ?? null; } catch { expected = null; }
+ if (expected && expected !== candidate.text_hash) return 'the affected fact changed since it was reviewed';
+ return null;
+}
+
+export async function acceptReviewProposal(engine: BrainEngine, id: number): Promise<ReviewActionResult> {
+ const ref = `r${id}`;
+ const p = await getReviewProposal(engine, id);
+ if (!p) return { id: ref, action: 'accept', status: 'not_found' };
+ if (p.status !== 'pending') return { id: ref, action: 'accept', status: 'refused', reason: `proposal is ${p.status}` };
+ if (p.kind !== 'withdraw') {
+ const handler = reviewAcceptHandler(p.kind);
+ if (!handler) {
+ await transitionReviewProposal(engine, id, 'pending', 'accepted_no_action');
+ return { id: ref, action: 'accept', status: 'accepted_no_action', reason: 'verdict recorded; no merge or link handler is registered in this build' };
+ }
+ const out = await handler(engine, p);
+ await transitionReviewProposal(engine, id, 'pending', out.status);
+ return { id: ref, action: 'accept', status: out.status, ...(out.detail ? { reason: out.detail } : {}) };
+ }
+ // A previous accept that withdrew the fact but stopped before the status change: finish it.
+ const [done] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE id = $1 AND source_id = $2 AND expired_at IS NOT NULL
+ AND strpos(COALESCE(context, ''), $3) > 0`, [Number(p.b_ref), p.source_id, `(review r${id})`]);
+ if (done) {
+ await transitionReviewProposal(engine, id, 'pending', 'accepted');
+ return { id: ref, action: 'accept', status: 'accepted' };
+ }
+ const stale = await staleReason(engine, p);
+ if (stale) {
+ await transitionReviewProposal(engine, id, 'pending', 'stale');
+ return { id: ref, action: 'accept', status: 'stale', reason: stale };
+ }
+ const { submitForgetMutation } = await import('../persistence/memory-mutations.ts');
+ const { runMemoryWrite } = await import('../persistence/verb-errors.ts');
+ await runMemoryWrite(() => submitForgetMutation({
+ engine, config: loadConfig() ?? { engine: 'pglite' }, remote: false, dryRun: false, sourceId: p.source_id,
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ } as never, 'forget', { id: p.b_ref, request_id: reviewRequestId(id), semantic_review: false,
+ reason: `paraphrase of withdrawn fact #${p.a_ref} (review r${id})` }));
+ await transitionReviewProposal(engine, id, 'pending', 'accepted');
+ return { id: ref, action: 'accept', status: 'accepted' };
+}
+
+export async function rejectReviewProposal(engine: BrainEngine, id: number): Promise<ReviewActionResult> {
+ const ref = `r${id}`;
+ const p = await getReviewProposal(engine, id);
+ if (!p) return { id: ref, action: 'reject', status: 'not_found' };
+ if (!(await transitionReviewProposal(engine, id, 'pending', 'rejected'))) return { id: ref, action: 'reject', status: 'refused', reason: `proposal is ${p.status}` };
+ return { id: ref, action: 'reject', status: 'rejected' };
+}
+
+export async function undoReviewProposal(engine: BrainEngine, id: number): Promise<ReviewActionResult> {
+ const ref = `r${id}`;
+ const p = await getReviewProposal(engine, id);
+ if (!p) return { id: ref, action: 'undo', status: 'not_found' };
+ if (p.kind === 'withdraw') {
+ return { id: ref, action: 'undo', status: 'refused', reason: 'withdrawal_is_durable',
+ fix: 'The withdrawal ledger is durable by design. To state the claim again, remember a corrected wording with new provenance (gbrain remember "<corrected claim>" --provenance "<source>").' };
+ }
+ return { id: ref, action: 'undo', status: 'refused', reason: 'undo_unsupported', fix: 'Duplicate verdicts have no undo here; reverse the merge or link with the subsystem that applied it.' };
+}
diff --git a/src/core/facts/similar-active.ts b/src/core/facts/similar-active.ts
new file mode 100644
index 0000000000..982c188171
--- /dev/null
+++ b/src/core/facts/similar-active.ts
@@ -0,0 +1,73 @@
+/**
+ * After a forget: other active facts about the same entity that are close in
+ * meaning to the withdrawn claim. Zero model calls: the withdrawn fact's stored
+ * embedding is compared in SQL. Returns fact ids and similarity scores only (no
+ * stored text), plus what the overnight semantic review will do, so the agent
+ * can ask the user whether any of them restate what was withdrawn.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { loadConfigSnapshot } from '../config-snapshot.ts';
+import { readDecideConfig, providerKind } from '../ai/decide/config.ts';
+import { hasTypesafeKey } from '../ai/decide/index.ts';
+import { CONFLICT_MIN_COSINE } from '../ai/decide/conflict.ts';
+import { REVIEW_WITHDRAW_KEY } from './withdrawal.ts';
+
+export const SIMILAR_ACTIVE_LIMIT = 5;
+
+export type SemanticReviewState = 'scheduled' | 'off' | 'unavailable' | 'opted_out';
+
+export interface SimilarActive {
+ state: 'checked' | 'not_checked_no_embedding' | 'not_checked_pending';
+ candidates: Array<{ fact_id: string; similarity: number }>;
+ semantic_review: SemanticReviewState;
+ next: string;
+}
+
+async function reviewState(engine: BrainEngine, optedOut: boolean): Promise<SemanticReviewState> {
+ if (optedOut) return 'opted_out';
+ const snapshot = await loadConfigSnapshot(engine);
+ if (!['true', 'on', '1', 'yes'].includes((snapshot?.[REVIEW_WITHDRAW_KEY] ?? '').trim().toLowerCase())) return 'off';
+ const cfg = readDecideConfig(snapshot, { typesafeKey: hasTypesafeKey() });
+ if (cfg.slots.conflict.mode === 'off') return 'off';
+ const kind = providerKind(cfg.slots.conflict.provider);
+ if (kind === 'none' || (kind === 'typesafe' && !hasTypesafeKey())) return 'unavailable';
+ return 'scheduled';
+}
+
+const REVIEW_LINE: Record<SemanticReviewState, string> = {
+ scheduled: 'An overnight semantic review will also propose rewordings of the withdrawn claim for the owner to accept.',
+ off: 'Overnight semantic review is off, so nothing else will catch rewordings: ask the user before forgetting more.',
+ unavailable: 'Overnight semantic review is on but has no decision provider, so it will not run: ask the user before forgetting more.',
+ opted_out: 'This withdrawal opted out of overnight semantic review.',
+};
+
+export async function similarActiveAfterForget(engine: BrainEngine, opts: {
+ sourceId: string; factId: number; remote: boolean; committed: boolean; semanticReview?: boolean;
+}): Promise<SimilarActive> {
+ const semantic_review = await reviewState(engine, opts.semanticReview === false);
+ const finish = (state: SimilarActive['state'], candidates: SimilarActive['candidates'], lead: string): SimilarActive =>
+ ({ state, candidates, semantic_review, next: `${lead} ${REVIEW_LINE[semantic_review]}` });
+ if (!opts.committed) return finish('not_checked_pending', [], 'Similar facts were not checked because the withdrawal has not committed yet.');
+ const [anchor] = await engine.executeRaw<{ has_embedding: boolean; entity_slug: string | null }>(
+ `SELECT embedding IS NOT NULL AS has_embedding, entity_slug FROM facts WHERE id=$1 AND source_id=$2`, [opts.factId, opts.sourceId]);
+ if (!anchor?.has_embedding) {
+ return finish('not_checked_no_embedding', [], 'The withdrawn fact has no embedding, so close rewordings could not be checked; recall the entity and ask the user if any remaining fact restates it.');
+ }
+ const rows = await engine.executeRaw<{ id: number | string; similarity: number | string }>(
+ `SELECT c.id, (1 - (c.embedding <=> n.embedding))::float8 AS similarity
+ FROM facts n JOIN facts c
+ ON c.source_id = n.source_id AND c.entity_slug IS NOT DISTINCT FROM n.entity_slug AND c.visibility = n.visibility AND c.id <> n.id
+ WHERE n.id = $1 AND n.source_id = $2
+ AND c.expired_at IS NULL AND (c.valid_until IS NULL OR c.valid_until > now())
+ AND c.embedding IS NOT NULL AND c.embedding_model = n.embedding_model
+ AND ($3::boolean = false OR c.visibility = 'world')
+ AND (1 - (c.embedding <=> n.embedding)) >= $4
+ ORDER BY c.embedding <=> n.embedding, c.id
+ LIMIT $5`,
+ [opts.factId, opts.sourceId, opts.remote, CONFLICT_MIN_COSINE, SIMILAR_ACTIVE_LIMIT]);
+ const candidates = rows.map(r => ({ fact_id: String(r.id), similarity: Math.round(Number(r.similarity) * 1000) / 1000 }));
+ if (!candidates.length) return finish('checked', [], 'No close matches found among the remaining active facts (this does not prove every rewording is gone).');
+ const entity = anchor.entity_slug ? ` (recall entity: ${anchor.entity_slug})` : '';
+ return finish('checked', candidates,
+ `Close matches are not necessarily the same claim. Show these facts to the user${entity} and forget one only if the user confirms it restates what they withdrew.`);
+}
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index a8814f44ac..698603f50f 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -10,9 +10,23 @@ export interface WithdrawalCommit {
}
/** DB-first: no filesystem ownership, provider work or root lock is required. */
+/**
+ * Called inside the withdrawal transaction after the ledger row commits with
+ * it: projections derived from the withdrawn claim (beyond pages and chunks,
+ * which this module invalidates) register here to invalidate in the same unit.
+ */
+export type WithdrawalInvalidation = (tx: BrainEngine, w: { sourceId: string; factId: number; subject: string; pages: WithdrawalCommit['pages'] }) => Promise<void>;
+const withdrawalInvalidations: WithdrawalInvalidation[] = [];
+export function registerWithdrawalInvalidation(fn: WithdrawalInvalidation): void {
+ if (!withdrawalInvalidations.includes(fn)) withdrawalInvalidations.push(fn);
+}
+
+/** The DB-plane switch for overnight semantic withdrawal review (decide review lane). */
+export const REVIEW_WITHDRAW_KEY = 'decide.slots.conflict.review_withdraw';
+
export async function recordFactWithdrawal(
engine: BrainEngine, id: number, sourceId: string, worldOnly = false,
- opts: { requestId?: string } = {},
+ opts: { requestId?: string; semanticReview?: boolean } = {},
): Promise<WithdrawalCommit> {
return engine.transaction(async tx => {
// A managed caller takes this EXCLUSIVE source lock before authority,
@@ -45,6 +59,11 @@ export async function recordFactWithdrawal(
WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)
AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL`, [sourceId,row.visibility,row.fact,row.subject]);
if (!inserted.length) return { withdrawn: false, pages: [] };
+ // Overnight semantic review (decide review lane): queued with the ledger row so a late commit is never skipped.
+ // Not queued when the caller opted out (`semantic_review: false`, also used by review-accepted withdrawals).
+ if (opts.semanticReview !== false && ['true', 'on', '1', 'yes'].includes(((await tx.getConfig(REVIEW_WITHDRAW_KEY)) ?? '').trim().toLowerCase())) {
+ await tx.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw',$1,$2) ON CONFLICT DO NOTHING`, [sourceId, String(id)]);
+ }
// Logical revision and projection invalidation commit with the withdrawal.
// The revision trigger queues durable rebuild work even for unmanaged calls.
const pages = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
@@ -58,7 +77,9 @@ export async function recordFactWithdrawal(
CROSS JOIN (VALUES ('withdrawal-mirror'),('git'),('embedding')) AS k(kind)
WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [opts.requestId, sourceId, JSON.stringify({ version: 2, targets: pages.map(page => ({ slug: page.slug, page_id: page.id, revision: page.knowledge_revision })).sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0) })]);
}
- return { withdrawn: true, pages: pages.map(page => ({ sourceId, slug: page.slug, revision: page.knowledge_revision })) };
+ const committed = pages.map(page => ({ sourceId, slug: page.slug, revision: page.knowledge_revision }));
+ for (const invalidate of withdrawalInvalidations) await invalidate(tx, { sourceId, factId: id, subject: row.subject, pages: committed });
+ return { withdrawn: true, pages: committed };
});
}
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index ea9f77a556..67872cc24a 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -172,8 +172,9 @@ interface WithdrawalTarget { id: number; entity_slug: string | null; source_mark
/** Withdrawal commits independently of filesystem ownership and request FIFO. */
export async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>): Promise<Record<string, unknown>> {
const sub = await submission(ctx, operation, params);
- if (sub.prior) return writeResponse(sub.prior);
+ if (sub.prior) return withSimilarActive(ctx, operation, sub.sourceId, sub.p, writeResponse(sub.prior));
const { p, sourceId, principal, callerIntent, requestId } = sub;
+ const semanticReview = p.semantic_review !== false;
const id = Number(p.id);
const rawId = String(p.id).trim();
const reason = typeof p.reason === 'string' && p.reason.trim() ? p.reason.trim() : null;
@@ -212,7 +213,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
return withCoordinatedWrite(tx, [sourceId], async () => {
// Even an expired legacy fact acquires a ledger so a stale import cannot
// reactivate it. Internal affected-page identities never enter the receipt.
- withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id })).pages;
+ withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview })).pages;
if (reason) await tx.executeRaw(`UPDATE facts SET context=concat_ws(' | ',NULLIF(context,''),$3::text)
WHERE id=$1 AND source_id=$2`, [id, sourceId, `forgotten: ${reason}`]);
if (operation === 'forget_fact' && fact.expired_at !== null) {
@@ -231,5 +232,19 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
for (let start = 0; start < slugs.length; start += 100) {
await rebuildPendingPageProjections(ctx.engine, 100, { pages: { sourceId, slugs: slugs.slice(start, start + 100) } }).catch(() => undefined);
}
- return writeResponse(done);
+ return withSimilarActive(ctx, operation, sourceId, p, writeResponse(done));
+}
+
+/** `forget` responses carry `similar_active` (ids and scores only, zero model calls); best-effort, never fails the forget. */
+async function withSimilarActive(ctx: OperationContext, operation: 'forget' | 'forget_fact', sourceId: string,
+ p: Record<string, unknown>, response: Record<string, unknown>): Promise<Record<string, unknown>> {
+ if (operation !== 'forget') return response;
+ const factId = Number(p.id);
+ if (!Number.isSafeInteger(factId)) return response;
+ try {
+ const { similarActiveAfterForget } = await import('../facts/similar-active.ts');
+ const committed = (response.write_request as { state?: string } | undefined)?.state === 'committed' || response.state === 'committed';
+ return { ...response, similar_active: await similarActiveAfterForget(ctx.engine, {
+ sourceId, factId, remote: ctx.remote !== false, committed, semanticReview: p.semantic_review !== false }) };
+ } catch { return response; }
}
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index f9af4910a2..d2cab2162a 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1806,6 +1806,49 @@ DO \$rls\$ BEGIN
END IF;
END \$rls\$;
+CREATE TABLE IF NOT EXISTS decide_review_queue (
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL DEFAULT '*',
+ evidence TEXT,
+ reason TEXT NOT NULL DEFAULT 'queued',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kind, source_id, a_ref, b_ref)
+);
+CREATE TABLE IF NOT EXISTS decide_review_proposals (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ sweep_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL,
+ subject TEXT NOT NULL DEFAULT '*',
+ visibility TEXT,
+ p_action REAL NOT NULL,
+ threshold REAL,
+ model_resolved TEXT,
+ question_version TEXT,
+ status TEXT NOT NULL DEFAULT 'pending',
+ decided_at TIMESTAMPTZ,
+ receipt TEXT,
+ UNIQUE (kind, source_id, a_ref, b_ref, subject)
+);
+CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
+
-- gbrain facts relink attempts and journal (#5836).
CREATE TABLE IF NOT EXISTS fact_relink_attempts (
source_id TEXT NOT NULL,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 01044b0e99..23f687d804 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2523,6 +2523,49 @@ DO \$rls\$ BEGIN
ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY;
END IF;
END \$rls\$;
+
+CREATE TABLE IF NOT EXISTS decide_review_queue (
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL DEFAULT '*',
+ evidence TEXT,
+ reason TEXT NOT NULL DEFAULT 'queued',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kind, source_id, a_ref, b_ref)
+);
+CREATE TABLE IF NOT EXISTS decide_review_proposals (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ sweep_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL,
+ subject TEXT NOT NULL DEFAULT '*',
+ visibility TEXT,
+ p_action REAL NOT NULL,
+ threshold REAL,
+ model_resolved TEXT,
+ question_version TEXT,
+ status TEXT NOT NULL DEFAULT 'pending',
+ decided_at TIMESTAMPTZ,
+ receipt TEXT,
+ UNIQUE (kind, source_id, a_ref, b_ref, subject)
+);
+CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
-- END GENERATED from src/core/ai/decide/schema.ts (DECIDE_SCHEMA_SQL)
-- gbrain facts relink attempts and journal (#5836).
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 16ef4d9ecc..700df4fb28 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';
import { v198 } from './v198-publication-failure-detail.ts';
import { v199 } from './v199-chronicle-page-state.ts';
import { v200 } from './v200-sync-hold-page-index.ts';
+import { v201 } from './v201-decide-review-proposals.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [
v198,
v199,
v200,
+ v201,
];
diff --git a/src/core/schema-migrations/v201-decide-review-proposals.ts b/src/core/schema-migrations/v201-decide-review-proposals.ts
new file mode 100644
index 0000000000..902259cac9
--- /dev/null
+++ b/src/core/schema-migrations/v201-decide-review-proposals.ts
@@ -0,0 +1,11 @@
+import type { Migration } from './types.ts';
+import { DECIDE_REVIEW_SCHEMA_SQL } from '../ai/decide/schema.ts';
+
+// System One decide: the ambiguous-band review lane (durable review queue and
+// per-kind owner-reviewed proposals); DDL in src/core/ai/decide/schema.ts.
+export const v201: Migration = {
+ version: 201,
+ name: 'decide_review_proposals',
+ idempotent: true,
+ sql: DECIDE_REVIEW_SCHEMA_SQL,
+};
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1cd8c68b92..1edcfb1269 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -346,6 +346,7 @@ const forget: Operation = {
request_id: WRITE_REQUEST_PARAM,
id: { type: 'string', required: true, description: 'fact_id from remember or recall.' },
reason: { type: 'string', description: 'Audit note (default "forgotten").' },
+ semantic_review: { type: 'boolean', description: 'false: skip overnight rewording review.' },
},
mutating: true,
scope: 'write',
@@ -605,6 +606,16 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
expired: { type: 'boolean', description: 'true = this call expired the fact; false = it was ALREADY expired (idempotent re-forget).' },
reason: { type: ['string', 'null'] },
write_request: WRITE_RECEIPT_SCHEMA,
+ similar_active: {
+ type: 'object',
+ description: 'Active facts about the same entity close in meaning to the withdrawn claim (ids and scores only; zero model calls). Similarity is not sameness: ask the user before forgetting any of them.',
+ properties: {
+ state: { type: 'string', enum: ['checked', 'not_checked_no_embedding', 'not_checked_pending'] },
+ candidates: { type: 'array', items: { type: 'object', properties: { fact_id: { type: 'string' }, similarity: { type: 'number' } } } },
+ semantic_review: { type: 'string', enum: ['scheduled', 'off', 'unavailable', 'opted_out'] },
+ next: { type: 'string' },
+ },
+ },
},
},
// v0.45.7 (issue #1) — ambient recall. World-only by default; include_private
diff --git a/src/schema.sql b/src/schema.sql
index 43fed65c5e..abb3f62adb 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2519,6 +2519,49 @@ DO $rls$ BEGIN
ALTER TABLE decide_sweep_deferred ENABLE ROW LEVEL SECURITY;
END IF;
END $rls$;
+
+CREATE TABLE IF NOT EXISTS decide_review_queue (
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL DEFAULT '*',
+ evidence TEXT,
+ reason TEXT NOT NULL DEFAULT 'queued',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kind, source_id, a_ref, b_ref)
+);
+CREATE TABLE IF NOT EXISTS decide_review_proposals (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ kind TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ sweep_id TEXT NOT NULL,
+ a_ref TEXT NOT NULL,
+ b_ref TEXT NOT NULL,
+ subject TEXT NOT NULL DEFAULT '*',
+ visibility TEXT,
+ p_action REAL NOT NULL,
+ threshold REAL,
+ model_resolved TEXT,
+ question_version TEXT,
+ status TEXT NOT NULL DEFAULT 'pending',
+ decided_at TIMESTAMPTZ,
+ receipt TEXT,
+ UNIQUE (kind, source_id, a_ref, b_ref, subject)
+);
+CREATE INDEX IF NOT EXISTS decide_review_proposals_status_idx ON decide_review_proposals (status, created_at);
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_queue ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE decide_review_proposals ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
-- END GENERATED from src/core/ai/decide/schema.ts (DECIDE_SCHEMA_SQL)
-- gbrain facts relink attempts and journal (#5836).
diff --git a/test/decide/cli.serial.test.ts b/test/decide/cli.serial.test.ts
index 799e218df0..8cc06ec4fa 100644
--- a/test/decide/cli.serial.test.ts
+++ b/test/decide/cli.serial.test.ts
@@ -83,7 +83,7 @@ describe('gbrain decide CLI', () => {
expect(badSlot.exitCode).toBe(1);
const list = await cli(['decide', 'proposals', 'list', '--json']);
expect(list.exitCode).toBe(0);
- expect(JSON.parse(list.stdout)).toEqual({ status: 'pending', proposals: [] });
+ expect(JSON.parse(list.stdout)).toEqual({ status: 'pending', proposals: [], review_proposals: [] });
const missing = await cli(['decide', 'proposals', 'accept', '999']);
expect(missing.exitCode).toBe(1);
expect(missing.stdout).toContain('proposal 999: not found');
diff --git a/test/decide/review-duplicate-kinds.serial.test.ts b/test/decide/review-duplicate-kinds.serial.test.ts
new file mode 100644
index 0000000000..42cef71434
--- /dev/null
+++ b/test/decide/review-duplicate-kinds.serial.test.ts
@@ -0,0 +1,100 @@
+/**
+ * The duplicate kinds of the ambiguous-band review lane: other subsystems
+ * enqueue candidate page pairs; the lane judges them (once per pair) and writes
+ * pending proposals; accepting runs the owning subsystem's registered handler,
+ * or records the owner's verdict as accepted_no_action when none is registered.
+ * Bulk accept of a sweep excludes withdraw proposals unless asked.
+ * Serial: mutates the process-global decide transport.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { configureGateway, resetGateway, __setDecideTransportForTests } from '../../src/core/ai/gateway.ts';
+import { insertCalibration, __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';
+import { packShape } from '../../src/core/ai/decide/pack.ts';
+import {
+ enqueueReviewCandidate, listReviewProposals, registerReviewAcceptHandler, reviewProposalIdsFromSweep, runReviewLane,
+} from '../../src/core/ai/decide/review-lane.ts';
+import { acceptReviewProposal } from '../../src/core/facts/proposal-review.ts';
+
+let engine: PGLiteEngine;
+let calls = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { __setDecideTransportForTests(null); resetGateway(); await engine.disconnect(); });
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetDecideStoreForTests();
+ calls = 0;
+ configureGateway({ env: { TYPESAFE_API_KEY: 'sk-test-typesafe' } });
+ __setDecideTransportForTests(async (_url, init) => {
+ calls++;
+ const body = JSON.parse(init.body as string);
+ const answers = Object.fromEntries(Object.entries(body.questions).map(([id, q]: [string, any]) => {
+ const same = String(q.instructions.candidate).includes('Acme Example Inc');
+ const probabilities = same ? { same: 0.96, different: 0.04 } : { same: 0.1, different: 0.9 };
+ const choice = same ? 'same' : 'different';
+ return [id, { type: 'choice', choice, confidence: probabilities[choice], probabilities }];
+ }));
+ return new Response(JSON.stringify({ model: 'jev-1.13.0', answers, usage: { input_tokens: 50, output_tokens: 5 } }));
+ });
+ for (const [k, v] of Object.entries({
+ 'decide.provider': 'typesafe:jev-1.13.0', 'decide.slots.conflict.mode': 'on', 'decide.egress.typesafe.candidates': 'allow',
+ 'decide.egress.private': 'allow', 'decide.slots.conflict.review_duplicate_page': 'true',
+ })) await engine.setConfig(k, v);
+ const id = await insertCalibration(engine, {
+ slot: 'conflict', call_site: 'review_duplicate_page', provider: 'typesafe:jev-1.13.0', model_resolved: 'jev-1.13.0', threshold: 0.9, min_keep: null,
+ metric: 'precision', metric_value: 0.97, ece: 0.03, retest_sd: 0.01, repack_sd: 0.01, n: 200, dataset_hash: 'd', split_hash: 's',
+ calibrate_ids_hash: 'c', calibrate_only: false, pack_shape: packShape('conflict'), notes: null,
+ });
+ await engine.executeRaw('UPDATE decide_calibrations SET action_precision_lb = 0.95 WHERE id = $1', [id]);
+ for (const [slug, title, body] of [
+ ['companies/acme-example', 'Acme Example', 'A widget company.'],
+ ['companies/acme-example-inc', 'Acme Example Inc', 'Acme Example Inc makes widgets.'],
+ ['companies/widget-example', 'Widget Example', 'A different company.'],
+ ]) await importFromContent(engine, slug!, `---\ntitle: ${title}\ntype: company\n---\n${body}\n`, { noEmbed: true, sourceId: 'default' });
+});
+
+describe('duplicate_page review', () => {
+ test('enqueued pairs are judged once; same-thing pairs become proposals', async () => {
+ await enqueueReviewCandidate(engine, { kind: 'duplicate_page', source_id: 'default', a_ref: 'companies/acme-example-inc', b_ref: 'companies/acme-example', evidence: 'cosine 0.88' });
+ await enqueueReviewCandidate(engine, { kind: 'duplicate_page', source_id: 'default', a_ref: 'companies/acme-example', b_ref: 'companies/acme-example-inc' });
+ await enqueueReviewCandidate(engine, { kind: 'duplicate_page', source_id: 'default', a_ref: 'companies/acme-example', b_ref: 'companies/widget-example' });
+ const r = await runReviewLane(engine, { kind: 'duplicate_page' });
+ expect(r).toMatchObject({ effective: 'on', anchors: 2, proposals: 1, independents: 1 });
+ const [p] = await listReviewProposals(engine);
+ expect(p).toMatchObject({ kind: 'duplicate_page', a_ref: 'companies/acme-example', b_ref: 'companies/acme-example-inc' });
+ expect(calls).toBe(2);
+ });
+
+ test('accept records the verdict without a handler and runs one when registered', async () => {
+ await enqueueReviewCandidate(engine, { kind: 'duplicate_page', source_id: 'default', a_ref: 'companies/acme-example', b_ref: 'companies/acme-example-inc' });
+ const r = await runReviewLane(engine, { kind: 'duplicate_page' });
+ const [p] = await listReviewProposals(engine);
+ expect((await acceptReviewProposal(engine, p!.id)).status).toBe('accepted_no_action');
+ expect(await reviewProposalIdsFromSweep(engine, r.sweep_id, { includeWithdrawals: false })).toEqual([]);
+
+ await resetPgliteState(engine);
+ for (const [k, v] of Object.entries({ 'decide.provider': 'typesafe:jev-1.13.0', 'decide.slots.conflict.mode': 'shadow', 'decide.egress.typesafe.candidates': 'allow', 'decide.slots.conflict.review_duplicate_page': 'true' })) await engine.setConfig(k, v);
+ const seen: string[] = [];
+ registerReviewAcceptHandler('duplicate_page', async (_e, proposal) => { seen.push(`${proposal.a_ref}=${proposal.b_ref}`); return { status: 'accepted' }; });
+ await engine.executeRaw(`INSERT INTO decide_review_proposals (kind, source_id, sweep_id, a_ref, b_ref, p_action) VALUES ('duplicate_page','default','s1','a','b',0.97)`);
+ const [q] = await listReviewProposals(engine);
+ expect((await acceptReviewProposal(engine, q!.id)).status).toBe('accepted');
+ expect(seen).toEqual(['a=b']);
+ });
+
+ test('a kind that is off never runs', async () => {
+ await engine.setConfig('decide.slots.conflict.review_duplicate_page', 'false');
+ await enqueueReviewCandidate(engine, { kind: 'duplicate_page', source_id: 'default', a_ref: 'companies/acme-example', b_ref: 'companies/acme-example-inc' });
+ const r = await runReviewLane(engine, { kind: 'duplicate_page' });
+ expect(r).toMatchObject({ effective: 'off', inactive: 'review_kind_off' });
+ expect(calls).toBe(0);
+ });
+});
diff --git a/test/decide/review-withdraw.serial.test.ts b/test/decide/review-withdraw.serial.test.ts
new file mode 100644
index 0000000000..686de3ef63
--- /dev/null
+++ b/test/decide/review-withdraw.serial.test.ts
@@ -0,0 +1,274 @@
+/**
+ * Semantic withdrawal review (the `withdraw` kind of the ambiguous-band review
+ * lane) on PGLite with a fixture decide transport; no provider is called.
+ *
+ * Protects: a withdrawal queues review work in its own transaction only when
+ * the kind is on and the caller did not opt out; forget returns zero-model
+ * `similar_active` ids; the lane never calls the provider without a calibration
+ * qualified for action precision (an operator threshold override is not a
+ * qualification); with one, a restatement becomes a pending proposal and an
+ * independent neighbour does not; shadow mode writes receipts only; a forgotten
+ * private claim is not sent unless private egress is explicitly allowed;
+ * accepting withdraws the candidate through `forget` (ledger row, expiry) and
+ * queues no further review; a changed candidate goes stale; undo refuses with
+ * a fix; a later paraphrase re-queues the withdrawn anchor through the sweep.
+ * Serial: mutates the process-global gateway and decide transport.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { writeSingleFact } from '../../src/core/facts/write-single.ts';
+import { configureGateway, resetGateway, __setDecideTransportForTests, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { flushDecideWrites, insertCalibration, __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';
+import { packShape } from '../../src/core/ai/decide/pack.ts';
+import { runReviewLane, listReviewProposals } from '../../src/core/ai/decide/review-lane.ts';
+import { runConflictSweep } from '../../src/core/ai/decide/sweep.ts';
+import { setSweepWatermark } from '../../src/core/ai/decide/proposals-store.ts';
+import { acceptReviewProposal, rejectReviewProposal, undoReviewProposal } from '../../src/core/facts/proposal-review.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+
+let engine: PGLiteEngine;
+let brainDir: string;
+const SLUG = 'people/alice-example';
+const OTHER = 'people/bob-example';
+const DIM = 1536;
+
+/** `[gN]` picks a direction, `[vM]` a small offset: two variants of one group have cosine ~0.86. */
+function embed(text: string): number[] {
+ const v = new Array(DIM).fill(0);
+ const g = /\[g(\d+)\]/.exec(text);
+ const m = /\[v(\d+)\]/.exec(text);
+ if (!g) { v[1000 + ([...text].reduce((n, c) => n + c.charCodeAt(0), 0) % 400)] = 1; return v; }
+ v[Number(g[1]) * 20] = 1;
+ if (m) v[Number(g[1]) * 20 + 1 + Number(m[1])] = 0.4;
+ return v;
+}
+
+type Probs = { duplicate: number; supersede: number; independent: number };
+let bodies: any[] = [];
+function transport(judge: (fact: string, candidate: string) => Probs, model = 'jev-1.13.0') {
+ __setDecideTransportForTests(async (_url, init) => {
+ const body = JSON.parse(init.body as string);
+ bodies.push(body);
+ const answers = Object.fromEntries(Object.entries(body.questions).map(([id, q]: [string, any]) => {
+ const probabilities = judge(body.state.fact, q.instructions.candidate);
+ const choice = (Object.entries(probabilities) as Array<[string, number]>).sort((a, b) => b[1] - a[1])[0]![0];
+ return [id, { type: 'choice', choice, confidence: probabilities[choice as keyof Probs], probabilities }];
+ }));
+ return new Response(JSON.stringify({ model, answers, usage: { input_tokens: 50, output_tokens: 5 } }));
+ });
+}
+/** Restatements carry `[same]` in their text in these fixtures. */
+const judgeSame = (_fact: string, candidate: string): Probs => candidate.includes('[same]') ? { duplicate: 0.97, supersede: 0.02, independent: 0.01 } : { duplicate: 0.05, supersede: 0.1, independent: 0.85 };
+
+const BASE = {
+ 'decide.provider': 'typesafe:jev-1.13.0', 'decide.slots.conflict.mode': 'on',
+ 'decide.egress.typesafe.facts': 'allow', 'decide.egress.private': 'allow', 'decide.slots.conflict.review_withdraw': 'true',
+};
+async function setConfig(kv: Record<string, string>) { for (const [k, v] of Object.entries(kv)) await engine.setConfig(k, v); }
+
+async function qualify(lb = 0.95) {
+ const id = await insertCalibration(engine, {
+ slot: 'conflict', call_site: 'review_withdraw', provider: 'typesafe:jev-1.13.0', model_resolved: 'jev-1.13.0', threshold: 0.9, min_keep: null,
+ metric: 'precision', metric_value: 0.97, ece: 0.03, retest_sd: 0.01, repack_sd: 0.01, n: 200, dataset_hash: 'd', split_hash: 's',
+ calibrate_ids_hash: 'c', calibrate_only: false, pack_shape: packShape('conflict'), notes: null,
+ });
+ await engine.executeRaw('UPDATE decide_calibrations SET action_precision_lb = $2 WHERE id = $1', [id, lb]);
+}
+
+async function remember(fact: string, entity: string | null = SLUG, visibility: 'world' | 'private' = 'world'): Promise<number> {
+ const r = await writeSingleFact(engine, 'default', { fact, provenance: 'test', entity, kind: 'fact', visibility });
+ expect(r.status).toBe('inserted');
+ return r.id;
+}
+
+async function forget(id: number, extra: Record<string, unknown> = {}): Promise<Record<string, any>> {
+ return await operationsByName.forget!.handler({ engine, config: { engine: 'pglite' }, remote: false, dryRun: false, sourceId: 'default',
+ logger: { info: () => {}, warn: () => {}, error: () => {} } } as never, { id: String(id), ...extra }) as Record<string, any>;
+}
+
+async function queue() {
+ return engine.executeRaw<{ kind: string; a_ref: string }>('SELECT kind, a_ref FROM decide_review_queue ORDER BY a_ref');
+}
+async function isActive(id: number): Promise<boolean> {
+ const [r] = await engine.executeRaw<{ active: boolean }>('SELECT expired_at IS NULL AS active FROM facts WHERE id = $1', [id]);
+ return r!.active;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ __setDecideTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetDecideStoreForTests();
+ bodies = [];
+ brainDir = mkdtempSync(join(tmpdir(), 'review-brain-'));
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIM, env: { OPENAI_API_KEY: 'sk-test', TYPESAFE_API_KEY: 'sk-test-typesafe' } });
+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({ embeddings: opts.values.map(embed) })) as never);
+ mkdirSync(join(brainDir, 'people'), { recursive: true });
+ for (const [slug, title] of [[SLUG, 'Alice Example'], [OTHER, 'Bob Example']] as const) {
+ const content = `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\nA person.\n`;
+ writeFileSync(join(brainDir, `${slug}.md`), content);
+ await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' });
+ }
+});
+
+afterEach(async () => {
+ __setDecideTransportForTests(null);
+ await disposePersistenceConsumer(engine);
+ rmSync(brainDir, { recursive: true, force: true });
+});
+
+describe('queueing and the forget response', () => {
+ test('a withdrawal queues review only when the kind is on and the caller did not opt out', async () => {
+ const a = await remember('[g1] Alice Example prefers tea.');
+ await forget(a);
+ expect(await queue()).toEqual([]);
+ await setConfig(BASE);
+ const b = await remember('[g2] Alice Example lives in Lisbon.');
+ await forget(b);
+ const c = await remember('[g3] Alice Example dislikes flying.');
+ await forget(c, { semantic_review: false });
+ expect(await queue()).toEqual([{ kind: 'withdraw', a_ref: String(b) }]);
+ });
+
+ test('forget returns similar active facts as ids and scores only, with what happens next', async () => {
+ await setConfig(BASE);
+ const anchor = await remember('[g4] Alice Example invested in acme-example.');
+ const close = await remember('[g4][v1] Alice Example put money into acme-example.');
+ await remember('[g9] Alice Example runs marathons.');
+ const twin = await remember('[g4][v2] Bob Example invested in acme-example.', OTHER);
+ const res = await forget(anchor);
+ expect(res.similar_active.state).toBe('checked');
+ expect(res.similar_active.candidates.map((c: any) => c.fact_id)).toEqual([String(close)]);
+ expect(res.similar_active.candidates.map((c: any) => c.fact_id)).not.toContain(String(twin));
+ expect(JSON.stringify(res.similar_active)).not.toContain('acme-example.');
+ expect(res.similar_active.next).toContain('forget one only if the user confirms');
+ expect(res.similar_active.semantic_review).toBe('scheduled');
+ });
+});
+
+describe('the review lane', () => {
+ test('without a qualified calibration the provider is never called (an operator threshold is not a qualification)', async () => {
+ await setConfig({ ...BASE, 'decide.slots.conflict.threshold': '0.8' });
+ transport(judgeSame);
+ const anchor = await remember('[g5] Alice Example works at acme-example.');
+ await remember('[g5][v1] Alice Example is employed by acme-example. [same]');
+ await forget(anchor);
+ const r = await runReviewLane(engine, { kind: 'withdraw' });
+ expect(r).toMatchObject({ effective: 'off', inactive: 'no_qualification', proposals: 0 });
+ expect(bodies).toHaveLength(0);
+ });
+
+ test('a restatement becomes a pending proposal; an independent neighbour does not', async () => {
+ await setConfig(BASE);
+ await qualify();
+ transport(judgeSame);
+ const anchor = await remember('[g6] Alice Example works at acme-example.');
+ const same = await remember('[g6][v1] Alice Example is employed by acme-example. [same]');
+ await remember('[g6][v2] Alice Example visited acme-example last spring.');
+ await forget(anchor);
+ const r = await runReviewLane(engine, { kind: 'withdraw' });
+ expect(r).toMatchObject({ effective: 'on', anchors: 1, pairs: 2, proposals: 1, independents: 1 });
+ const [p] = await listReviewProposals(engine);
+ expect(p).toMatchObject({ kind: 'withdraw', a_ref: String(anchor), b_ref: String(same), status: 'pending', subject: SLUG });
+ expect(await queue()).toEqual([]);
+ await flushDecideWrites();
+ const receipts = await engine.executeRaw<{ outcome: string; call_site: string }>(`SELECT outcome, call_site FROM decision_receipts WHERE slot = 'conflict'`);
+ expect(receipts.every(x => x.call_site === 'review_withdraw')).toBe(true);
+ // Judged pairs are not judged again.
+ await engine.executeRaw(`INSERT INTO decide_review_queue(kind,source_id,a_ref) VALUES ('withdraw','default',$1)`, [String(anchor)]);
+ bodies = [];
+ await runReviewLane(engine, { kind: 'withdraw' });
+ expect(bodies).toHaveLength(0);
+ });
+
+ test('shadow mode judges and writes receipts but no proposals', async () => {
+ await setConfig({ ...BASE, 'decide.slots.conflict.mode': 'shadow' });
+ transport(judgeSame);
+ const anchor = await remember('[g7] Alice Example owns a red bicycle.');
+ await remember('[g7][v1] Alice Example has a red bike. [same]');
+ await forget(anchor);
+ const r = await runReviewLane(engine, { kind: 'withdraw' });
+ expect(r).toMatchObject({ effective: 'shadow', proposals: 0, shadow_proposals: 1 });
+ expect(await listReviewProposals(engine)).toEqual([]);
+ });
+
+ test('a forgotten private claim is not sent unless private egress is explicitly allowed', async () => {
+ await setConfig({ ...BASE, 'decide.egress.private': 'deny' });
+ await qualify();
+ transport(judgeSame);
+ const anchor = await remember('[g8] Alice Example takes a daily medication.', SLUG, 'private');
+ await remember('[g8][v1] Alice Example is on daily medication. [same]', SLUG, 'private');
+ await forget(anchor);
+ const r = await runReviewLane(engine, { kind: 'withdraw' });
+ expect(r).toMatchObject({ skipped: 1, proposals: 0 });
+ expect(bodies).toHaveLength(0);
+ });
+});
+
+describe('owner actions', () => {
+ async function proposal(): Promise<{ id: number; anchor: number; same: number }> {
+ await setConfig(BASE);
+ await qualify();
+ transport(judgeSame);
+ const anchor = await remember('[g10] Alice Example founded widget-example.');
+ const same = await remember('[g10][v1] Alice Example started widget-example. [same]');
+ await forget(anchor);
+ await runReviewLane(engine, { kind: 'withdraw' });
+ const [p] = await listReviewProposals(engine);
+ return { id: p!.id, anchor, same };
+ }
+
+ test('accept withdraws the candidate through forget and queues no further review', async () => {
+ const { id, same } = await proposal();
+ const r = await acceptReviewProposal(engine, id);
+ expect(r.status).toBe('accepted');
+ expect(await isActive(same)).toBe(false);
+ const ledger = await engine.executeRaw('SELECT 1 FROM fact_withdrawals');
+ expect(ledger.length).toBeGreaterThanOrEqual(2);
+ expect(await queue()).toEqual([]);
+ expect((await acceptReviewProposal(engine, id)).status).toBe('refused');
+ });
+
+ test('a changed candidate goes stale; reject and undo behave', async () => {
+ const { id, same } = await proposal();
+ await engine.executeRaw(`UPDATE facts SET fact = fact || ' (edited)' WHERE id = $1`, [same]);
+ expect((await acceptReviewProposal(engine, id)).status).toBe('stale');
+ expect(await isActive(same)).toBe(true);
+ const undo = await undoReviewProposal(engine, id);
+ expect(undo).toMatchObject({ status: 'refused', reason: 'withdrawal_is_durable' });
+ expect(undo.fix).toContain('remember a corrected wording');
+ expect((await rejectReviewProposal(engine, id)).status).toBe('refused');
+ });
+});
+
+describe('a later paraphrase', () => {
+ test('re-queues the withdrawn claim through the conflict sweep', async () => {
+ await setConfig(BASE);
+ transport(() => ({ duplicate: 0.1, supersede: 0.1, independent: 0.8 }));
+ const anchor = await remember('[g11] Alice Example speaks Portuguese.');
+ await forget(anchor);
+ await engine.executeRaw('DELETE FROM decide_review_queue');
+ await setSweepWatermark(engine, 'default', anchor);
+ await remember('[g11][v1] Alice Example is fluent in Portuguese.');
+ await runConflictSweep(engine, { now: () => Date.now() + 120_000 });
+ expect(await queue()).toEqual([{ kind: 'withdraw', a_ref: String(anchor) }]);
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 99a6d7000e..fb278adbd2 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -35,6 +35,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -375,6 +378,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -677,6 +686,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -991,6 +1004,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"drift_decisions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=drift_decisions.id",
"entity_identities_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=entity_identities.id",
@@ -1306,6 +1320,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index db8a7c1b35..4091ddc333 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -35,6 +35,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -375,6 +378,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -677,6 +686,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -991,6 +1004,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"drift_decisions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=drift_decisions.id",
"entity_identities_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=entity_identities.id",
@@ -1306,6 +1320,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 796685335b..6157297ec0 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -35,6 +35,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -375,6 +378,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -677,6 +686,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -987,6 +1000,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"drift_decisions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=drift_decisions.id",
"entity_identities_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=entity_identities.id",
@@ -1302,6 +1316,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 3a33f51e94..50329fb851 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -20,6 +20,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -284,6 +287,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -525,6 +534,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -744,6 +757,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"eval_candidates_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_candidates.id",
"eval_capture_failures_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_capture_failures.id",
@@ -961,6 +975,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 358ba68154..5eb319596f 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -20,6 +20,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -284,6 +287,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -525,6 +534,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -744,6 +757,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"eval_candidates_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_candidates.id",
"eval_capture_failures_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_capture_failures.id",
@@ -961,6 +975,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index c53886296f..c1c0c01137 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -20,6 +20,9 @@
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
+ "decide_review_proposals.decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "u UNIQUE (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals.decide_review_proposals_pkey": "p PRIMARY KEY (id)",
+ "decide_review_queue.decide_review_queue_pkey": "p PRIMARY KEY (kind, source_id, a_ref, b_ref)",
"decide_spend.decide_spend_pkey": "p PRIMARY KEY (request_id)",
"decide_state.decide_state_pkey": "p PRIMARY KEY (key)",
"decide_sweep_deferred.decide_sweep_deferred_pkey": "p PRIMARY KEY (slot, source_id, fact_id)",
@@ -284,6 +287,12 @@
"decide_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "decide_review_proposals": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "decide_review_queue": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_spend": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -525,6 +534,10 @@
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
"decide_proposals_status_created_idx": "CREATE INDEX decide_proposals_status_created_idx ON public.decide_proposals USING btree (status, created_at)",
"decide_proposals_sweep_id_pair_index_key": "CREATE UNIQUE INDEX decide_proposals_sweep_id_pair_index_key ON public.decide_proposals USING btree (sweep_id, pair_index)",
+ "decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key": "CREATE UNIQUE INDEX decide_review_proposals_kind_source_id_a_ref_b_ref_subject_key ON public.decide_review_proposals USING btree (kind, source_id, a_ref, b_ref, subject)",
+ "decide_review_proposals_pkey": "CREATE UNIQUE INDEX decide_review_proposals_pkey ON public.decide_review_proposals USING btree (id)",
+ "decide_review_proposals_status_idx": "CREATE INDEX decide_review_proposals_status_idx ON public.decide_review_proposals USING btree (status, created_at)",
+ "decide_review_queue_pkey": "CREATE UNIQUE INDEX decide_review_queue_pkey ON public.decide_review_queue USING btree (kind, source_id, a_ref, b_ref)",
"decide_spend_created_idx": "CREATE INDEX decide_spend_created_idx ON public.decide_spend USING btree (created_at)",
"decide_spend_pkey": "CREATE UNIQUE INDEX decide_spend_pkey ON public.decide_spend USING btree (request_id)",
"decide_state_pkey": "CREATE UNIQUE INDEX decide_state_pkey ON public.decide_state USING btree (key)",
@@ -743,6 +756,7 @@
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
+ "decide_review_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_review_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
"eval_candidates_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_candidates.id",
"eval_capture_failures_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=eval_capture_failures.id",
@@ -960,6 +974,41 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "decide_review_proposals": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('decide_review_proposals_id_seq'::regclass)",
+ "2 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "3 kind text/text NOT NULL",
+ "4 source_id text/text NOT NULL",
+ "5 sweep_id text/text NOT NULL",
+ "6 a_ref text/text NOT NULL",
+ "7 b_ref text/text NOT NULL",
+ "8 subject text/text NOT NULL DEFAULT '*'::text",
+ "9 visibility text/text NULL",
+ "10 p_action real/float4 NOT NULL",
+ "11 threshold real/float4 NULL",
+ "12 model_resolved text/text NULL",
+ "13 question_version text/text NULL",
+ "14 status text/text NOT NULL DEFAULT 'pending'::text",
+ "15 decided_at timestamp with time zone/timestamptz NULL",
+ "16 receipt text/text NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "decide_review_queue": {
+ "columns": [
+ "1 kind text/text NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 a_ref text/text NOT NULL",
+ "4 b_ref text/text NOT NULL DEFAULT '*'::text",
+ "5 evidence text/text NULL",
+ "6 reason text/text NOT NULL DEFAULT 'queued'::text",
+ "7 attempts integer/int4 NOT NULL DEFAULT 0",
+ "8 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_spend": {
"columns": [
"1 request_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 8c613f7b27..1d27400c89 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 196835,
- "stdoutSha256": "7c6a8f58d1ecf9152a0bef45fe6b85d84ea6bc81c4610fc65b2a65eeec68370a",
+ "stdoutBytes": 197008,
+ "stdoutSha256": "3f271e14e9933beb2044f28a4b8ea42dab752934fef26668d4e146a90e265a0b",
"toolNames": [
"remember",
"entity",
@@ -316,7 +316,8 @@
"parameters": {
"id": "string",
"reason": "string?",
- "request_id": "string?"
+ "request_id": "string?",
+ "semantic_review": "boolean?"
},
"required_scopes": [],
"schema": {
@@ -332,6 +333,10 @@
"request_id": {
"description": "UUID; retry with it on timeout.",
"type": "string"
+ },
+ "semantic_review": {
+ "description": "false: skip overnight rewording review.",
+ "type": "boolean"
}
},
"required": [
diff --git a/test/fixtures/goldens/decide/proposals-list-json.json b/test/fixtures/goldens/decide/proposals-list-json.json
index 288a9dcb12..69955c4e07 100644
--- a/test/fixtures/goldens/decide/proposals-list-json.json
+++ b/test/fixtures/goldens/decide/proposals-list-json.json
@@ -21,6 +21,7 @@
"threshold": 0.8
}
],
+ "review_proposals": [],
"status": "all"
},
"normalizer": "decide-proposals-v1"
diff --git a/test/fixtures/goldens/decide/status-keyless-all-off.json b/test/fixtures/goldens/decide/status-keyless-all-off.json
index 100032b37c..57068c40fa 100644
--- a/test/fixtures/goldens/decide/status-keyless-all-off.json
+++ b/test/fixtures/goldens/decide/status-keyless-all-off.json
@@ -292,6 +292,40 @@
"skipped": 0
},
"plain": "contradiction",
+ "proposal_review": [
+ {
+ "accepted_30d": 0,
+ "enabled": true,
+ "kind": "supersede",
+ "oldest_pending_days": null,
+ "pending": 0,
+ "rejected_30d": 0
+ },
+ {
+ "accepted_30d": 0,
+ "enabled": false,
+ "kind": "withdraw",
+ "oldest_pending_days": null,
+ "pending": 0,
+ "rejected_30d": 0
+ },
+ {
+ "accepted_30d": 0,
+ "enabled": false,
+ "kind": "duplicate_page",
+ "oldest_pending_days": null,
+ "pending": 0,
+ "rejected_30d": 0
+ },
+ {
+ "accepted_30d": 0,
+ "enabled": false,
+ "kind": "duplicate_entity",
+ "oldest_pending_days": null,
+ "pending": 0,
+ "rejected_30d": 0
+ }
+ ],
"provider": "none",
"readiness": "off",
"receipts_24h": 0,
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 190c942fa0..44c47a7103 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 195,
+ "count": 196,
"gaps": [
17,
18,
@@ -28,7 +28,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 200,
+ "latest": 201,
"records": [
{
"handler": {
@@ -2968,6 +2968,19 @@
"transaction": "absent",
"verify": "absent",
"version": 200
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "decide_review_proposals",
+ "sql": {
+ "length": 1700,
+ "sha256": "8a20d8dac7096056bb53512bcb34316d15d44582b7d9b0f4f6fff3891c9daac3"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 201
}
],
"versions": [
@@ -3165,7 +3178,8 @@
197,
198,
199,
- 200
+ 200,
+ 201
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 4a7eff8069..1b6a1419a9 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -50,7 +50,7 @@ const PARAM_DESCRIPTION_HARD_CAP = 200;
/** Per-tool budget: JSON.stringify of the served tool definition. */
const TOOL_BUDGETS: Record<string, number> = {
add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,
- delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 560, get_agent_job: 270,
+ delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 640, get_agent_job: 270,
get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,
get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,