Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): captured-facts database-only expiry publishes a maintenance request on managed brains

garrytan4053a50e5071
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 94c1b409dc..f13ff3dc33 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
-- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows in one (coordinated, owner-checked on a managed brain) transaction, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
+- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
- `src/core/restore-target.ts` -- `resolveRestoreTarget(engine, source, repo)`: the source and repo `gbrain export --restore-only` restores, shared with `gbrain storage status` so its printed restore command restores exactly the files it lists. An explicit source (already resolved) wins; a repo without a source selects the one active source registered at that exact path, refuses a repo registered only to an archived source, else selects the only active source; neither selects the flagless resolver chain's source and its `local_path` (the legacy `sync.repo_path` answers for `default` only). `restoreFilePath(repo, slug, sourcePath, sourcePathBytes, slugRootMode)` is the file whose absence makes the restore write a page: the recorded `source_path` resolved in the repo in the source's slug-root mode (`scannerSlugRootMode`), else `<slug>.md`; an over-long or unsafe recorded path throws. Refusals throw `RestoreTargetError`; resolver and database errors propagate unchanged.
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 329ab26235..6d570dc451 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -283,6 +283,7 @@ export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: nu
export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');
if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);
if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);
if (row.intent?.kind === 'managed_maintenance_page') {
const prepared = await preparePageMutation(engine, row.intent.expected_revision === null
diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.ts
index 95f3cdc4c9..4fd078cb33 100644
--- a/src/core/repair/captured-facts.ts
+++ b/src/core/repair/captured-facts.ts
@@ -27,8 +27,9 @@
* `remember` of the same claim is not blocked. A fenced row (`row_num` on its
* entity page) is struck in the page's `## Facts` fence by one revision-bound
* `put_page` per page, so the canonical projection expires it and a later
- * write of the page cannot reactivate it; a row with no fence row is expired
- * in a coordinated database write. Each fact is rechecked before it is
+ * write of the page cannot reactivate it; rows with no fence row are expired
+ * by one database-only maintenance request on a managed brain (one
+ * transaction on an unmanaged brain). Each fact is rechecked before it is
* touched; a fact that changed since the preview is reported as
* `changed_since_preview` and kept.
*/
@@ -40,9 +41,11 @@ import { parseFactsFence, type ParsedFact } from '../facts-fence.ts';
import { strikeFenceRow } from '../facts/forget.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { digest } from '../persistence/digest.ts';
-import { withCoordinatedWrite } from '../persistence/context.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
-import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';
@@ -284,7 +287,7 @@ export const capturedFactsRepair: RepairHandler = {
});
const expired: number[] = [];
const dbOnly = unchanged.filter(f => f.row_num === null);
- if (dbOnly.length) expired.push(...await expireDatabaseRows(engine, page.source_id, dbOnly.map(f => f.id)));
+ if (dbOnly.length) expired.push(...await expireDatabaseRows(engine, page, hash, dbOnly.map(f => f.id)));
const fenced = unchanged.filter(f => f.row_num !== null);
if (fenced.length) expired.push(...await strikeFencedRows(ctx, entry, page, fenced));
if (last) await clearApprovedSet(engine, { command: 'captured-facts', hash });
@@ -294,15 +297,37 @@ export const capturedFactsRepair: RepairHandler = {
},
};
-/** Database-only rows: expired with a reason in one transaction (coordinated on a managed brain, whose source needs its owner). */
-async function expireDatabaseRows(engine: BrainEngine, sourceId: string, ids: number[]): Promise<number[]> {
- const managed = await managedPersistenceEnabled(engine);
- if (managed) await maintenancePreflight(engine, sourceId);
- const expire = (tx: BrainEngine) => tx.executeRaw<{ id: number | string }>(`UPDATE facts
- SET expired_at=now(), valid_until=LEAST(COALESCE(valid_until, now()), now()), context=concat_ws(' | ', $3::text, NULLIF(context,''))
- WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL AND row_num IS NULL RETURNING id`, [sourceId, ids, EXPIRY_CONTEXT]);
- const rows = await engine.transaction(tx => managed ? withCoordinatedWrite(tx, [sourceId], () => expire(tx)) : expire(tx));
- return rows.map(row => Number(row.id));
+export const CAPTURED_FACTS_INTENT = 'managed_maintenance_expire_captured_facts';
+
+const expireRows = (tx: BrainEngine, sourceId: string, ids: number[]) => tx.executeRaw<{ id: number | string }>(`UPDATE facts
+ SET expired_at=now(), valid_until=LEAST(COALESCE(valid_until, now()), now()), context=concat_ws(' | ', $3::text, NULLIF(context,''))
+ WHERE source_id=$1 AND id=ANY($2::bigint[]) AND expired_at IS NULL AND row_num IS NULL RETURNING id`, [sourceId, ids, EXPIRY_CONTEXT]);
+
+/**
+ * Database-only rows: on a managed brain one database-only maintenance
+ * request on the page key (owner-checked, with a publication receipt); on an
+ * unmanaged brain one transaction.
+ */
+async function expireDatabaseRows(engine: BrainEngine, page: CapturedFactsPage, hash: string, ids: number[]): Promise<number[]> {
+ if (!await managedPersistenceEnabled(engine)) return (await engine.transaction(tx => expireRows(tx, page.source_id, ids))).map(row => Number(row.id));
+ const authority = (await maintenancePreflight(engine, page.source_id))!;
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ const h = digest(['captured-facts-expire-v1', hash, page.source_id, page.slug, ids, snapshot?.revision ?? null]);
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,
+ { kind: CAPTURED_FACTS_INTENT, expected_revision: snapshot?.revision ?? null, fact_ids: ids },
+ `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`);
+ return (receipt.expired as number[] | undefined) ?? [];
+}
+
+/** Preparer for `managed_maintenance_expire_captured_facts`: expires the named database-only rows of the source. */
+export async function prepareCapturedFactsExpiry(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const ids = (row.intent as { fact_ids?: unknown } | null)?.fact_ids;
+ if (!Array.isArray(ids) || !ids.every(id => Number.isSafeInteger(id))) throw new OperationError('invalid_params', 'The captured facts expiry intent does not name its facts.');
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot?.revision ?? null, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => ({ status: 'completed', expired: (await expireRows(tx, row.source_id, ids as number[])).map(r => Number(r.id)) }) };
}
/**
diff --git a/test/repair-captured-facts.test.ts b/test/repair-captured-facts.test.ts
index 288bf338b6..bc87b9ccd0 100644
--- a/test/repair-captured-facts.test.ts
+++ b/test/repair-captured-facts.test.ts
@@ -94,6 +94,8 @@ for (const backend of testBackends()) {
writeSingleFact(engine, 'default', { fact, entity, provenance, sessionId }).then(r => r.id);
const self = await write('Alice Example prefers Rust for systems work', ALICE, 'hook:writeback', 'sess-self');
const selfCompact = await write('Acme Example ships quarterly', ACME, 'hook:compact', 'sess-self');
+ // An entity with no page: the managed writer keeps the row database-only (no fence row).
+ const selfDbOnly = await write('Carol Absent dislikes long meetings', 'Carol Absent', 'hook:writeback', 'sess-self');
const paste = await write('Acme Example raised a Series B round led by Fund Alpha', ACME, 'sweep:corpus', 'sweep:corpus:sess-paste.txt');
const pasteOwn = await write('Acme Example wants a summary of an email', ACME, 'sweep:corpus', 'sweep:corpus:sess-paste.txt');
const twinned = await write('Alice Example lives in Lisbon', ALICE, 'hook:writeback', 'sess-self');
@@ -104,24 +106,28 @@ for (const backend of testBackends()) {
const finding = await capturedFactsCheck(engine);
expect(finding.status).toBe('warn');
- expect(finding.details).toMatchObject({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1 });
+ expect(finding.details).toMatchObject({ evidenced: 3, ambiguous: 1, excluded: 1, unclassifiable: 1 });
expect(finding.message).toContain('gbrain repair captured-facts');
expect(finding.message).toContain('the self_capture check counts corpus files');
const wave = (await runWaveChecks(engine, { only: 'wave' })).find(f => f.spec.id === 'captured_facts_active')!;
expect(wave.state).toBe('finding');
- expect(wave.spec.count(wave.check.details!)).toBe(3);
+ expect(wave.spec.count(wave.check.details!)).toBe(4);
const preview = await repair(engine, []);
- expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 1, excluded: 1, unclassifiable: 1, not_suspect: 2 });
+ expect(preview.results[0].residuals).toEqual({ evidenced: 3, ambiguous: 1, excluded: 1, unclassifiable: 1, not_suspect: 2 });
const classes = Object.fromEntries(preview.results[0].listing!.map(l => [Number(l.item.split('#')[1]), l.class]));
- expect(classes).toEqual({ [self]: 'evidenced', [selfCompact]: 'evidenced', [paste]: 'ambiguous', [twinned]: 'excluded:legitimate_duplicate' });
+ expect(classes).toEqual({ [self]: 'evidenced', [selfCompact]: 'evidenced', [selfDbOnly]: 'evidenced', [paste]: 'ambiguous', [twinned]: 'excluded:legitimate_duplicate' });
expect(preview.results[0].apply_command).toMatch(/^gbrain repair captured-facts --apply --expect [0-9a-f]+$/);
- for (const id of [self, selfCompact, paste, pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
+ expect((await engine.executeRaw<{ row_num: number | null }>('SELECT row_num FROM facts WHERE id=$1', [selfDbOnly]))[0].row_num).toBeNull();
+ for (const id of [self, selfCompact, selfDbOnly, paste, pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
expect((await refusal(() => repair(engine, ['--apply']))).code).toBe('invalid_params');
const applied = await repair(engine, applyArgs(preview));
- expect(applied.results[0].outcomes).toEqual({ expired: 2 });
+ expect(applied.results[0].outcomes).toEqual({ expired: 3 });
expect(await active(engine, self)).toBe(false);
+ expect(await active(engine, selfDbOnly)).toBe(false);
+ // Each expiry committed with a coordinator publication receipt.
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND intent->>'kind'='managed_maintenance_expire_captured_facts'"))[0].n).toBe(1);
expect(await active(engine, selfCompact)).toBe(false);
for (const id of [paste, pasteOwn, twinned, normal, gone]) expect(await active(engine, id)).toBe(true);
expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals'))[0].n).toBe(0);