Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources): mirror-created pages stay database-only; mirror Git effects complete as skipped (Codex review)

garrytan46ca439fd0cb
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 73c2d6304f..9e3a09e81a 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -195,3 +195,5 @@ src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarn
src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.
src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.
src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.
+src/commands/sources-mirror.ts 1 engine_guard `gbrain sources mirror-readonly|mirror-writable` (#5409) updates only sources.config.mirror_read_only, exactly as `sources federate` updates sources.config.federated; the sources managed_writer_guard trigger governs the row and no page, fact or file is written.
+src/core/persistence/mirror-read-only.ts 1 coordinator classifyMirrorPage stamps pages.database_only_reason=mirror_read_only only inside the coordinator publication transaction of a page write that published no file into a read-only mirror source (#5409), as classifyUnboundPage does for unbound sources.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 9d6274454f..b61d89d11d 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. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `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`.
- `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/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. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
+- `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/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index d3d4a0e020..a15c4fd1fb 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -169,7 +169,9 @@ maintenance write) is stored database-only too; its receipt says
`storage: "database_only"` with `write_through.skipped: "mirror_read_only"`.
`gbrain sources list --json` shows `mirror_read_only` per source. Undo it with
`gbrain sources mirror-writable <id>`; files are written again from the next
-write on. The flag is off by default.
+write on, except for pages created while the source was a mirror: those have
+no file in the checkout and stay database-only. Git effects of a mirror's
+writes (for example a `forget`) complete as skipped. The flag is off by default.
## The git requirement for --path sources
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 7a41442fee..53a2bb5db5 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -60,6 +60,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'connector_checkpoints',
'connector_held_items',
'derived_visibility',
+ 'extractor_facts_expired',
'orphan_persistence_bindings',
'safe_index_pending',
'self_capture',
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index a6a281d459..8ee017187a 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -23,7 +23,7 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFil
import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
interface PreparedMutationBase {
sourceExclusive?: boolean;
@@ -241,6 +241,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx));
if (!skill) await classifyUnboundPage(tx, row);
+ if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if (final) outcome.revision = final.revision;
outcome.persistence = { mode: files.length ? 'filesystem' : 'database', ...(files.length ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 6798f7cd64..c2e8c9c77f 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -35,6 +35,7 @@ import { SYNC_SKIP_FILES } from '../sync.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
+import { sourceMirrorReadOnly } from './mirror-read-only.ts';
export interface EffectWorkerOptions {
hostId: string;
@@ -174,6 +175,8 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {
if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }
+ // #5409: a read-only mirror's checkout is never committed to; its publications wrote no file.
+ if (await sourceMirrorReadOnly(engine, effect.source_id)) { await completeEffect(engine, effect, { git: 'skipped', reason: 'mirror_read_only' }); return; }
const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
diff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.ts
index 57bbc2afcb..8b8bd5baed 100644
--- a/src/core/persistence/mirror-read-only.ts
+++ b/src/core/persistence/mirror-read-only.ts
@@ -5,6 +5,9 @@
* a file into its checkout. Sync imports canonical metadata database-only, and
* a page write into the source is stored database-only (`storage:
* "database_only"` on the receipt), so `git pull --ff-only` keeps working.
+ * A page created that way (no recorded file) carries
+ * `pages.database_only_reason='mirror_read_only'` and stays database-only
+ * after `mirror-writable`, as an unbound-source page does (#5254).
*/
import type { SqlEngine } from './model.ts';
@@ -14,3 +17,15 @@ export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string,
`SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);
return row?.read_only === true;
}
+
+/** Marks a page this publication stored database-only because its source is a read-only mirror and it has no recorded file. */
+export async function classifyMirrorPage(tx: SqlEngine, row: { source_id: string; slug: string }): Promise<void> {
+ await tx.executeRaw(`UPDATE pages SET database_only_reason='mirror_read_only'
+ WHERE source_id=$1 AND slug=$2 AND database_only_reason IS NULL AND NULLIF(source_path,'') IS NULL`, [row.source_id, row.slug]);
+}
+
+export async function isMirrorOnlyPage(engine: SqlEngine, sourceId: string, slug: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ database_only_reason: string | null }>(
+ 'SELECT database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ return row?.database_only_reason === 'mirror_read_only';
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 1a521168cc..002af66cda 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -30,7 +30,7 @@ import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './pag
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
-import { sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { readSlugRootMode } from '../sync-anchor.ts';
@@ -77,6 +77,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!row.worktree_id) return undefined;
// #5409: a read-only mirror's checkout belongs to its Git remote; nothing is written or removed there.
if (await sourceMirrorReadOnly(engine, row.source_id)) return undefined;
+ if (snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(engine, row.source_id, row.slug)) return undefined;
// #5254: a page written while its source was unbound stays database-only in
// every state (live, tombstone, restore, revert, delete, purge); any file at
// its derived path is not its canonical file and is neither written nor removed.
@@ -139,7 +140,9 @@ export function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>,
}
async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {
const reason = databaseOnlyPublication(row, file);
- if (reason.databaseOnlyReason && await sourceMirrorReadOnly(engine, row.source_id)) return { databaseOnlyReason: 'mirror_read_only' };
+ if (reason.databaseOnlyReason && (await sourceMirrorReadOnly(engine, row.source_id) || await isMirrorOnlyPage(engine, row.source_id, row.slug))) {
+ return { databaseOnlyReason: 'mirror_read_only' };
+ }
return reason.databaseOnlyReason && await isUnboundSourcePage(engine, row.source_id, row.slug) ? { databaseOnlyReason: 'unbound_source' } : reason;
}
diff --git a/test/sources-mirror-read-only.test.ts b/test/sources-mirror-read-only.test.ts
index 63cd8e1f27..ae016331d4 100644
--- a/test/sources-mirror-read-only.test.ts
+++ b/test/sources-mirror-read-only.test.ts
@@ -28,6 +28,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
import { runSources } from '../src/commands/sources.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -164,5 +165,37 @@ for (const backend of testBackends()) {
expect(existsSync(join(m.root, 'notes/racing.md'))).toBe(false);
expect(await engine.getPage('notes/racing', { sourceId: m.id })).toBeNull();
}), 120_000);
+
+ test('a page created while read-only stays database-only after mirror-writable and can still be edited (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(true);
+ const put = (body: string, extra: Record<string, unknown> = {}) => submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'notes/brain-only',
+ request_id: randomUUID(), content: `---\ntitle: Brain only\ntype: note\n---\n${body}\n`, ...extra } }) as Promise<Record<string, unknown>>;
+ await put('Created while the source was a read-only mirror.');
+ await cli(['mirror-writable', m.id]);
+ const prior = (await engine.readPageSnapshot('notes/brain-only', { sourceId: m.id }))!;
+ const edited = await put('Edited after mirror-writable.', { expected_revision: prior.revision });
+ expect(edited).toMatchObject({ storage: 'database_only', write_through: { written: false, skipped: 'mirror_read_only' } });
+ expect((await engine.getPage('notes/brain-only', { sourceId: m.id }))?.compiled_truth).toContain('Edited after mirror-writable.');
+ expect(existsSync(join(m.root, 'notes/brain-only.md'))).toBe(false);
+ }), 120_000);
+
+ test('a fact withdrawal in a read-only mirror settles its Git effect as skipped, never failed (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(true);
+ await submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'people/alice-example', request_id: randomUUID(),
+ content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n' } });
+ const [{ id }] = await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES ($1, 'people/alice-example', 'Alice prefers mornings', 'preference', 'private', 'test')
+ RETURNING id::int AS id`, [m.id])));
+ const forgot = await submitForgetMutation(ctx(m.id), 'forget', { id: Number(id), request_id: randomUUID() }) as { request_id: string };
+ let effects: Array<{ kind: string; state: string; outcome: Record<string, unknown> | null }> = [];
+ for (let i = 0; i < 100; i++) {
+ effects = await engine.executeRaw(`SELECT e.kind, e.state, e.outcome FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.request_id=$1::uuid AND e.kind='git'`, [forgot.request_id]);
+ if (effects.length && effects.every(e => e.state !== 'queued' && e.state !== 'running')) break;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ expect(effects).toEqual([expect.objectContaining({ kind: 'git', state: 'committed', outcome: expect.objectContaining({ git: 'skipped', reason: 'mirror_read_only' }) })]);
+ expect(tracked(m.root)).toBe('');
+ }), 120_000);
});
}