Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(g6): ingest_capture and brainstorm --save write through the door on a managed brain; a private connector page on a strict source publishes database-only (GBRA-60)

garrytan22e5e8c31999
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.ts
index bb1cf62500..2d021eec2e 100644
--- a/src/commands/brainstorm.ts
+++ b/src/commands/brainstorm.ts
@@ -28,6 +28,10 @@ import { serializeMarkdown } from '../core/markdown.ts';
import { importFromContent } from '../core/import-file.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough, type WriteThroughResult } from '../core/write-through.ts';
import { fileDatabaseDriftToken, replaceableFile } from '../core/facts/file-body-guard.ts';
+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
+import { submitPageMutation } from '../core/persistence/page-mutations.ts';
+import { currentCliWriteWait, pendingReceiptOf, pollCommand } from '../core/persistence/write-wait.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../core/exit-codes.ts';
import { randomBytes } from 'crypto';
import { legacyNestedErrorDocument } from '../core/agent-output.ts';
import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
@@ -360,6 +364,8 @@ export interface SaveOutcome {
writeThrough: WriteThroughResult;
/** Set when nothing was saved because the page's file holds content the database lacks (`file_database_drift`). */
held?: string;
+ /** G6: the door accepted the save and it was still pending when the CLI write wait ended; it may still commit. */
+ pending?: { requestId: string; poll: string; acceptPending: boolean };
}
export interface SaveMessage {
@@ -391,6 +397,26 @@ export async function persistSavedIdea(
args: { slug: string; content: string; sourceId?: string; provenanceVia: string },
): Promise<SaveOutcome> {
const sourceId = args.sourceId ?? 'default';
+ const wait = currentCliWriteWait();
+ // G6: a managed brain refuses direct imports. put_page through the door publishes the file before the row; a --resume
+ // overwrite binds to the revision it read (expected_revision), and the door's compare-before-replace guards the file.
+ try {
+ if (await managedPersistenceEnabled(engine)) {
+ const snapshot = await engine.readPageSnapshot(args.slug, { sourceId, includeDeleted: true });
+ const response = await submitPageMutation({ engine, config: loadConfig() ?? { engine: engine.kind } as never, remote: false, dryRun: false, sourceId,
+ writeWaitMs: wait.waitMs,
+ logger: { info() {}, warn() {}, error() {} } }, { operation: 'put_page', params: { slug: args.slug, source_id: sourceId, content: args.content,
+ source_kind: args.provenanceVia, ...(snapshot ? { expected_revision: snapshot.revision } : {}) } });
+ const writeThrough = (response.write_through ?? { written: false }) as WriteThroughResult;
+ const target = writeThrough.written ? await resolvePageWriteTarget(engine, args.slug, sourceId) : null;
+ return { dbSaved: true, writeThrough: target?.ok ? { ...writeThrough, path: target.filePath } : writeThrough };
+ }
+ } catch (err) {
+ const receipt = pendingReceiptOf(err);
+ if (receipt) return { dbSaved: false, writeThrough: { written: false }, pending: { requestId: receipt.request_id,
+ poll: pollCommand(receipt.request_id, (err as { fix?: { argv?: readonly string[] } }).fix), acceptPending: wait.acceptPending } };
+ return { dbSaved: false, dbError: err instanceof Error ? err.message : String(err), writeThrough: { written: false } };
+ }
let dbSaved = false;
let dbError: string | undefined;
let expectedFileBytes: string | null | undefined;
@@ -437,6 +463,13 @@ export function formatSaveOutcome(
stderr.push(`gbrain ${ctx.profileLabel}: save refused: ${outcome.held}. Rerun with --resume <run_id> once the page and its file agree.`);
return { stderr, exitCode: 1 };
}
+ if (outcome.pending) {
+ return {
+ stdout: `\n_Save of page \`${ctx.slug}\` accepted and still pending (request ${outcome.pending.requestId}); it may still commit. Check it with \`${outcome.pending.poll}\`._`,
+ stderr,
+ exitCode: outcome.pending.acceptPending ? 0 : PENDING_WRITE_EXIT_CODE,
+ };
+ }
if (dbError) stderr.push(`gbrain ${ctx.profileLabel}: DB save failed: ${dbError}`);
if (writeThrough.error) {
stderr.push(`gbrain ${ctx.profileLabel}: file write failed: ${writeThrough.error}`);
diff --git a/src/core/minions/handlers/ingest-capture.ts b/src/core/minions/handlers/ingest-capture.ts
index 5345308676..e62d700d45 100644
--- a/src/core/minions/handlers/ingest-capture.ts
+++ b/src/core/minions/handlers/ingest-capture.ts
@@ -16,6 +16,9 @@
* improvement (would require routing through the put_page op AND
* extending OperationContext with the trust tag). See TODOs in the
* plan.
+ * - G6: on a managed brain the capture is a local put_page through the
+ * persistence door (a tombstone a delete_page), so its file is published
+ * before its row; content_origin tool_output keeps it external_untrusted.
*
* Slug resolution (in order):
* 1. `job.data.slug` if caller provided one
@@ -35,6 +38,9 @@ import type { IngestionEvent } from '../../ingestion/types.ts';
import { validateIngestionEvent } from '../../ingestion/types.ts';
import { importFromContent } from '../../import-file.ts';
import { maintenanceTransaction } from '../../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../../persistence/ownership.ts';
+import { OperationError, type OperationContext } from '../../ops/contract.ts';
+import { submitPageMutation } from '../../persistence/page-mutations.ts';
export interface IngestCaptureResult {
slug: string;
@@ -197,12 +203,20 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
if (rows.length > 0) sourceId = event.source_id;
}
+ // G6: a managed brain refuses direct writes, so its captures and tombstones go through the door (put_page /
+ // delete_page), which publishes the file before the row.
+ const managed = await managedPersistenceEnabled(engine);
+ const door = (operation: 'put_page' | 'delete_page', sid: string, params: Record<string, unknown>) => submitPageMutation(
+ { engine, config: { engine: engine.kind } as OperationContext['config'], remote: false, dryRun: false, sourceId: sid, logger: { info() {}, warn() {}, error() {} } },
+ { operation, params: { ...params, slug, source_id: sid } });
+
// #3756: tombstone → reconciler-style soft-delete (deleted_at stamp, page
// restorable), scoped to the resolved source — never unscoped, so a
// same-slug page in another source is untouched. Idempotent: a missing or
// already-deleted page reports 'skipped'.
if (isTombstone) {
- const deleted = await maintenanceTransaction(engine, tx => tx.softDeletePage(slug, { sourceId: sourceId ?? 'default' }));
+ const deleted = managed ? await managedTombstone(engine, slug, sourceId ?? 'default', door)
+ : await maintenanceTransaction(engine, tx => tx.softDeletePage(slug, { sourceId: sourceId ?? 'default' }));
if (sourceFallback) {
console.error(
`[WARN] ingest_capture: requested source '${sourceFallback.requested}' unavailable ` +
@@ -238,6 +252,47 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
writeGate: { tier: 'external_untrusted' as const, origin: { channel: `ingest:${event.source_kind}`, source_uri: event.source_uri ?? null, source_kind: event.source_kind }, requestId: null },
};
+ if (managed) {
+ // The door's put_page strips gate-owned markers from every ordinary write (#1699/#6259), and content_origin
+ // tool_output stores and gates the capture external_untrusted (#5575 A3), as importOpts does unmanaged.
+ // A capture replaces the page as it stands, so it binds to the revision read just before (the door requires one to
+ // replace an existing page); a write landing in between refuses revision_conflict and the job retries.
+ const put = async (sid: string) => {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: sid, includeDeleted: true });
+ return door('put_page', sid, { content: event.content, content_origin: 'tool_output', source_kind: event.source_kind, source_uri: event.source_uri,
+ ingested_via: 'ingest_capture', ...(snapshot ? { expected_revision: snapshot.revision } : {}),
+ // #2044/#4548: as `remote: untrustedPayload` does unmanaged, an untrusted body keeps the non-world facts rows and takes rows its sender could not see.
+ ...(untrustedPayload ? { keep_hidden_rows: true } : {}) });
+ };
+ let response: Record<string, unknown>;
+ try {
+ response = await put(sourceId ?? 'default');
+ } catch (err) {
+ // The door refuses a source that vanished or was archived after the pre-check (the managed form of the FK retry).
+ const vanished = sourceId !== undefined && err instanceof OperationError && err.code === 'source_changed'
+ ? await engine.executeRaw<{ archived: boolean | null }>('SELECT archived FROM sources WHERE id = $1', [sourceId]) : null;
+ if (!vanished || (vanished.length > 0 && vanished[0]?.archived !== true)) throw err;
+ sourceFallback = { requested: sourceId!, effective: 'default', reason: vanished.length ? 'archived' : 'fk_violation' };
+ response = await put('default');
+ }
+ if (sourceFallback) {
+ console.error(
+ `[WARN] ingest_capture: requested source '${sourceFallback.requested}' unavailable ` +
+ `(${sourceFallback.reason}); wrote under default`,
+ );
+ }
+ const outcome = (response.outcome ?? {}) as { noop?: boolean; chunks?: number };
+ return {
+ slug,
+ status: outcome.noop ? 'skipped' : 'imported',
+ chunks: Number(outcome.chunks ?? 0),
+ untrusted_payload: untrustedPayload,
+ source_kind: event.source_kind,
+ source_uri: event.source_uri,
+ ...(sourceFallback ? { source_fallback: sourceFallback } : {}),
+ };
+ }
+
let result;
try {
result = await importFromContent(engine, slug, event.content, { ...importOpts, sourceId });
@@ -291,3 +346,17 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
};
};
}
+
+/** A managed tombstone: delete_page through the door when the page is live in the source; a missing page is skipped. */
+async function managedTombstone(engine: BrainEngine, slug: string, sourceId: string,
+ door: (operation: 'delete_page', sid: string, params: Record<string, unknown>) => Promise<Record<string, unknown>>): Promise<boolean> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot || snapshot.page.deleted_at) return false;
+ try {
+ await door('delete_page', sourceId, { expected_revision: snapshot.revision });
+ return true;
+ } catch (err) {
+ if (err instanceof OperationError && err.code === 'page_not_found') return false;
+ throw err;
+ }
+}
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 11f192de9f..3cc1488d28 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -28,6 +28,8 @@ import type { PreparedContentImport } from './prepared-import.ts';
import { persistenceFileHash, type PreparedMutation } from './coordinator.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { databaseOnlyPublication, prepareFileTarget } from './page-prepare.ts';
+import { sourceCanonicalGit } from './git-door.ts';
+import { isPrivatePage } from '../search/private-visibility.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';
@@ -239,6 +241,17 @@ async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest,
return { path, root, content, expectedBeforeHash: before };
}
+/**
+ * G6: on a strict (canonical: git) source a private page is a declared database-only class and is never committed
+ * (docs/designs/GIT_CANONICAL_MEMORY.md), so a connector import of one (a calendar event the provider marks private,
+ * or a re-render of a page already private) publishes no file. Submission and publication decide it the same way.
+ */
+async function strictPrivateImport(engine: BrainEngine, sourceId: string, content: string, sourcePath: string, snapshot: PageSnapshot | null): Promise<boolean> {
+ const parsed = parseMarkdown(content, sourcePath);
+ const frontmatter = snapshot?.page.frontmatter.visibility === 'private' ? { ...parsed.frontmatter, visibility: 'private' } : parsed.frontmatter;
+ return isPrivatePage({ type: parsed.type, frontmatter }) && await sourceCanonicalGit(engine, sourceId);
+}
+
export async function beginConnectorSync(engine: BrainEngine, sourceId: string, connector: ConnectorKind,
suppliedConfig: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, lease?: ConnectorLease): Promise<ManagedConnectorSync | null> {
if (!await readManagedMode(engine)) return null;
@@ -879,7 +892,8 @@ export class ManagedConnectorSync {
if (kind === 'connector_v2_delete') {
if (this.binding || prepared.noop !== true) return false;
} else {
- const verdict = await inspectUnchanged(this.engine, { prepared, snapshot, sourcePath, databaseOnly: !this.binding });
+ const databaseOnly = !this.binding || await strictPrivateImport(this.engine, this.sourceId, intent.content ?? '', sourcePath ?? `${slug}.md`, snapshot);
+ const verdict = await inspectUnchanged(this.engine, { prepared, snapshot, sourcePath, databaseOnly });
if (verdict.admitReason) return false;
}
await prepared.validate?.(this.engine);
@@ -902,7 +916,8 @@ export class ManagedConnectorSync {
extra.googleReceipts = ownedGoogleReceipts(snapshot, (this.identity.config as GoogleSourceConfig).account, extra.googleReceipts!);
sourcePath = snapshot!.page.source_path!;
}
- const file = kind === 'connector_v2_checkpoint' ? undefined : await connectorFileTarget(this.engine,
+ const file = kind === 'connector_v2_checkpoint' || kind === 'connector_v2_import' && sourcePath && typeof extra.content === 'string'
+ && await strictPrivateImport(this.engine, this.sourceId, extra.content, sourcePath, snapshot) ? undefined : await connectorFileTarget(this.engine,
{ source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug }, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);
if (file && sourcePath && resolve(file.path) !== resolve(this.canonicalRoot!, sourcePath)) {
throw opError('source_changed', 'The connector source path no longer names its canonical file.',
@@ -1180,7 +1195,8 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, 'preserving');
const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();
const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };
- const target = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);
+ const target = await strictPrivateImport(engine, row.source_id, p.content, p.sourcePath, snapshot) ? undefined
+ : await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);
// Google pages hold private mail: derived here from the stored connector, never submitted, so request ids are unchanged.
const file = target && p.connector === 'google' ? { ...target, publishMode: 0o600 } : target;
if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw connectorPublicationRefusal('source_changed', 'The connector canonical file changed during preparation.', row,
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index f479e77114..aa17073e6d 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -275,6 +275,12 @@ export async function preparePageAdmission(ctx: OperationContext,
throw new OperationError('invalid_params', 'fence_repair is reserved for the trusted fence repair.',
'Drop fence_repair and submit the page without it; gbrain repair fences records its own receipt on the brain host. To fix a malformed facts or takes fence, correct it in content (or write facts with remember and takes with takes_add); a held file is repaired by the brain host operator with gbrain repair fences, so ask the user to run it.');
}
+ // G6: the hidden-row merge of an untrusted capture's body (page-prepare.ts) is opted into only by the trusted local ingest_capture
+ // handler, whose caller never saw the page's non-world rows; a remote put_page has it already, through its authority.
+ if (Object.hasOwn(input.params, 'keep_hidden_rows') && (input.operation !== 'put_page' || ctx.remote !== false || input.params.keep_hidden_rows !== true)) {
+ throw new OperationError('invalid_params', 'keep_hidden_rows is reserved for trusted local ingestion.',
+ 'Drop keep_hidden_rows and submit the page without it; a remote put_page already keeps the rows its caller could not read.');
+ }
// A body over the page ceiling can never be admitted: refuse it as a caller error before the journal
// reserves intent bytes, so an oversized write never reads as retryable queue_capacity.
const body = input.params.content;
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d43874740a..cd1cd49eb3 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -827,7 +827,8 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;
enterClaimStep(clock, 'import_content', undefined, 'db');
const result = await importFromContent(engine, row.slug, content, {
- ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean, boundedChunkWrites: options.boundedChunkWrites,
+ // G6: keep_hidden_rows (a trusted ingest_capture of untrusted content) gets the remote hidden-row merge without remote authority.
+ ...source, noEmbed: true, remote: row.authority.remote || p.keep_hidden_rows === true, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean, boundedChunkWrites: options.boundedChunkWrites,
segmentedOwner: { kind: row.operation === 'edit_page' ? 'edit' : 'put', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: observedRevision },
...(lean ? { existingSnapshot: snapshot } : {}),
// #6259: only owner-tier intents keep gate-owned markers; an ordinary put_page, local or remote, has them stripped.
diff --git a/test/e2e/g6-calendar-private-strict-postgres.test.ts b/test/e2e/g6-calendar-private-strict-postgres.test.ts
new file mode 100644
index 0000000000..253bd171a2
--- /dev/null
+++ b/test/e2e/g6-calendar-private-strict-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../g6-calendar-private-strict.test.ts'));
diff --git a/test/g6-brainstorm-strict.test.ts b/test/g6-brainstorm-strict.test.ts
index 75e4302409..d99d6fee4d 100644
--- a/test/g6-brainstorm-strict.test.ts
+++ b/test/g6-brainstorm-strict.test.ts
@@ -9,8 +9,14 @@
* PGLite here; Postgres in test/e2e/g6-brainstorm-strict-postgres.test.ts.
*/
import { describe, expect, test } from 'bun:test';
-import { buildIdeaSlug, persistSavedIdea } from '../src/commands/brainstorm.ts';
+import { buildIdeaSlug, formatSaveOutcome, persistSavedIdea } from '../src/commands/brainstorm.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { waitForWrite } from '../src/core/persistence/service.ts';
+import { WRITE_WAIT_ENV } from '../src/core/persistence/write-wait.ts';
+import { withEnv } from './helpers/with-env.ts';
import { serializeMarkdown } from '../src/core/markdown.ts';
+import { git } from './helpers/git-publication.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';
@@ -38,4 +44,39 @@ for (const backend of testBackends()) describe(`[${backend}] G6: brainstorm and
expect(outcomes.map(o => o.dbSaved)).toEqual(slugs.map(() => true));
expectDoorOnly(m, expect);
}, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
+
+ test('a --resume save overwrites the same idea page through the door, bound to the revision it read', () => managedBrain(async ({ engine, root }) => {
+ await strictSource(engine);
+ const slug = buildIdeaSlug(runs[0]!.question, 'brainstorm', 'g6resume');
+ const first = await persistSavedIdea(engine, { slug, content: saved('brainstorm', runs[0]!.question), provenanceVia: 'brainstorm' });
+ const base = head(root);
+ const resumed = serializeMarkdown({ mode: 'brainstorm', question: runs[0]!.question, source_kind: 'brainstorm' }, `# ${runs[0]!.question}\n\nRe-scored idea body.`, '',
+ { type: 'note', title: `Brainstorm: ${runs[0]!.question}`, tags: [] });
+ const second = await persistSavedIdea(engine, { slug, content: resumed, provenanceVia: 'brainstorm' });
+ expect([first.dbSaved, second.dbSaved, second.writeThrough.written]).toEqual([true, true, true]);
+ expect(second.writeThrough.path).toBe(`${root}/${slug}.md`);
+ const m = await measureBatch(engine, 'default', root, base, [slug]);
+ console.log(describeMeasure(`brainstorm-resume/${backend}`, m));
+ expect(m.commits).toHaveLength(1);
+ expectDoorOnly(m, expect);
+ expect(git(root, 'show', `HEAD:${slug}.md`)).toContain('Re-scored idea body.');
+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
+
+ test('a save still pending when the CLI write wait ends reports accepted and pending, exit 10, and later commits', () => managedBrain(async ({ engine, root }) => {
+ await strictSource(engine);
+ const slug = buildIdeaSlug(runs[1]!.question, 'brainstorm', 'g6pending');
+ const outcome = await withEnv({ [WRITE_WAIT_ENV]: '0' }, () => persistSavedIdea(engine, { slug, content: saved('brainstorm', runs[1]!.question), provenanceVia: 'brainstorm' }));
+ console.log(`[G6 brainstorm-pending/${backend}] ${JSON.stringify(outcome)}`);
+ expect(outcome.pending?.requestId).toBeString();
+ expect(outcome.dbError).toBeUndefined();
+ const msg = formatSaveOutcome(outcome, { profileLabel: 'brainstorm', slug });
+ expect(msg.exitCode).toBe(PENDING_WRITE_EXIT_CODE);
+ expect(msg.stdout).toContain('accepted and still pending');
+ expect(msg.stdout).toContain(outcome.pending!.requestId);
+ expect(msg.stderr.join('\n')).not.toContain('NOT persisted');
+ expect(formatSaveOutcome({ ...outcome, pending: { ...outcome.pending!, acceptPending: true } }, { profileLabel: 'brainstorm', slug }).exitCode).toBe(0);
+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1', [outcome.pending!.requestId]);
+ expect((await waitForWrite(engine, row!, { engine: engine.kind } as never, 30_000)).state).toBe('committed');
+ expect(git(root, 'show', `HEAD:${slug}.md`)).toContain('Idea body.');
+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
});
diff --git a/test/g6-calendar-private-strict.test.ts b/test/g6-calendar-private-strict.test.ts
new file mode 100644
index 0000000000..fc9b6c3efb
--- /dev/null
+++ b/test/g6-calendar-private-strict.test.ts
@@ -0,0 +1,64 @@
+/**
+ * G6 (git-canonical memory): a managed Google calendar sweep on a strict (canonical: git) source never commits a private
+ * event. Private pages are a declared database-only class (docs/designs/GIT_CANONICAL_MEMORY.md): the event marked
+ * `visibility: private` (or confidential) by Google publishes database-only, so its text appears in no commit, while the
+ * world events of the same sweep are committed at HEAD through the door. A second sweep re-renders the same events and
+ * still commits nothing private.
+ * PGLite here; Postgres in test/e2e/g6-calendar-private-strict-postgres.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';
+import { completeBaselineSweep, googleConfig, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';
+import { git } from './helpers/git-publication.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';
+
+const config = { ...googleConfig, g_services: 'calendar' };
+const PRIVATE_MARKER = 'privatemarkeracmeexample';
+const at = Date.parse('2026-10-20T17:00:00Z');
+const event = (id: string, summary: string, extra: Record<string, unknown> = {}) => ({ id, summary, status: 'confirmed',
+ start: { dateTime: new Date(at).toISOString() }, end: { dateTime: new Date(at + 3_600_000).toISOString() }, ...extra });
+const events = [
+ event('world-event-a', 'Acme example planning'),
+ event('world-event-b', 'Bob example sync'),
+ event('private-event-c', `Alice example ${PRIVATE_MARKER}`, { visibility: 'private', description: `Agenda ${PRIVATE_MARKER} notes` }),
+];
+const calendarFetch = withGoogleAccount(async (url: string) => {
+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });
+ if (url.includes('/calendar/')) return json({ items: events, nextSyncToken: 'calendar-g6' });
+ throw new Error('Unexpected external fixture route');
+});
+
+for (const backend of testBackends()) describe(`[${backend}] G6: a private calendar event on a strict source`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test('the private event stays database-only and out of git history; the world events are committed', () => withEnv({ CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, () => managedBrain(async ({ engine, root }) => {
+ await strictSource(engine);
+ const base = head(root);
+ const run = () => runGoogleSync(engine, 'default', parseGoogleSourceConfig(config, root), options, calendarFetch);
+ await completeBaselineSweep(engine, 'default', run);
+ await run();
+ const rows = await engine.executeRaw<{ slug: string; source_path: string | null; visibility: string | null }>(
+ "SELECT slug, source_path, frontmatter->>'visibility' AS visibility FROM pages WHERE source_id='default' AND slug LIKE 'calendar/%' AND deleted_at IS NULL ORDER BY slug");
+ const priv = rows.filter(row => row.visibility === 'private');
+ const world = rows.filter(row => row.visibility !== 'private');
+ expect(priv).toHaveLength(1);
+ expect(priv[0]!.slug).toContain(PRIVATE_MARKER);
+ expect(world).toHaveLength(2);
+ const history = git(root, 'log', '-p', '--all', '--format=%H %s');
+ const m = await measureBatch(engine, 'default', root, base, world.map(row => row.slug));
+ console.log(describeMeasure(`calendar-private/${backend}`, m) + ` declared=${JSON.stringify(m.census.declared)} declared_with_head_blob=${m.census.declared_with_head_blob}`);
+ expect(history.includes(PRIVATE_MARKER)).toBe(false);
+ expect(existsSync(join(root, priv[0]!.source_path ?? `${priv[0]!.slug}.md`))).toBe(false);
+ expect(m.census.declared.private).toBe(1);
+ expect(m.census.declared_with_head_blob).toBe(0);
+ expectDoorOnly(m, expect);
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ initStrictCheckout(root);
+ await engine.executeRaw("UPDATE sources SET config=$1::text::jsonb WHERE id='default'", [JSON.stringify(config)]);
+ } })), 120_000);
+});
diff --git a/test/g6-ingestion-strict.test.ts b/test/g6-ingestion-strict.test.ts
index 91950ed4db..378e5319f6 100644
--- a/test/g6-ingestion-strict.test.ts
+++ b/test/g6-ingestion-strict.test.ts
@@ -18,6 +18,9 @@ import { createInboxFolderSource } from '../src/core/ingestion/sources/inbox-fol
import { IngestionTestHarness } from '../src/core/ingestion/test-harness.ts';
import { makeIngestCaptureHandler } from '../src/core/minions/handlers/ingest-capture.ts';
import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../src/core/facts-fence.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { git } from './helpers/git-publication.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';
@@ -67,4 +70,55 @@ for (const backend of testBackends()) describe(`[${backend}] G6: inbox-folder ca
expectDoorOnly(m, expect);
} finally { rmSync(inbox, { recursive: true, force: true }); }
}, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
+
+ test('an untrusted capture is stored external_untrusted with gate-owned markers stripped; a trusted tombstone deletes through the door', () => managedBrain(async ({ engine, root }) => {
+ await strictSource(engine);
+ const handler = makeIngestCaptureHandler(engine);
+ const content = '---\nquarantine: true\ncontent_flag:\n detail: trust me\n---\n\n# Smuggled markers from acme-example\n';
+ const event = { source_id: 'webhook-acme-example', source_kind: 'webhook', source_uri: 'mcp-webhook:client-a:1', received_at: new Date().toISOString(),
+ content_type: 'text/markdown', content, content_hash: 'a'.repeat(64), untrusted_payload: true };
+ expect((await handler(job({ event, slug: 'inbox/smuggled' }))).status).toBe('imported');
+ const [page] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; trust_tier: string; source_kind: string | null; source_uri: string | null }>(
+ "SELECT frontmatter, trust_tier, source_kind, source_uri FROM pages WHERE source_id='default' AND slug='inbox/smuggled' AND deleted_at IS NULL");
+ expect(page!.frontmatter.quarantine).toBeUndefined();
+ expect(page!.frontmatter.content_flag).toBeUndefined();
+ expect(page!.trust_tier).toBe('external_untrusted');
+ expect({ kind: page!.source_kind, uri: page!.source_uri }).toEqual({ kind: 'webhook', uri: 'mcp-webhook:client-a:1' });
+ expect(git(root, 'ls-tree', '--name-only', 'HEAD', 'inbox/')).toContain('inbox/smuggled.md');
+
+ const tombstone = { ...event, kind: 'tombstone', slug: 'inbox/smuggled', content: 'tombstone', untrusted_payload: false };
+ expect((await handler(job({ event: tombstone }))).status).toBe('deleted');
+ expect((await handler(job({ event: tombstone }))).status).toBe('skipped');
+ const rows = await engine.executeRaw<{ deleted_at: unknown }>("SELECT deleted_at FROM pages WHERE source_id='default' AND slug='inbox/smuggled'");
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.deleted_at).not.toBeNull();
+ expect(git(root, 'ls-tree', '--name-only', 'HEAD', 'inbox/')).not.toContain('inbox/smuggled.md');
+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('');
+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
+
+ test('an untrusted capture that overwrites a page keeps the non-world facts row its caller could not see, in the file and the database', () => managedBrain(async ({ engine, ctx, root }) => {
+ await strictSource(engine);
+ const slug = 'inbox/alice-example';
+ const fence = (rows: string[]) => `# Alice example\n\nNotes.\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n`
+ + `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n${rows.join('\n')}\n${FACTS_FENCE_END}\n`;
+ const world = '| 1 | Alice example works at acme-example | fact | 1.0 | world | high | 2026-01-01 | | s | |';
+ const hidden = '| 2 | HIDDEN_ROW_ALICE_EXAMPLE | fact | 1.0 | private | high | 2026-01-02 | | s | |';
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: fence([world, hidden]) } });
+ const content = fence([world]).replace('Notes.', 'Notes edited by the webhook.');
+ const event = { source_id: 'webhook-acme-example', source_kind: 'webhook', source_uri: 'mcp-webhook:client-a:2', received_at: new Date().toISOString(),
+ content_type: 'text/markdown', content, content_hash: 'b'.repeat(64), untrusted_payload: true };
+ expect((await makeIngestCaptureHandler(engine)(job({ event, slug }))).status).toBe('imported');
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id='default' AND slug=$1 AND deleted_at IS NULL", [slug]);
+ const facts = await engine.executeRaw<{ fact: string }>("SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND expired_at IS NULL ORDER BY row_num", [slug]);
+ const committed = git(root, 'show', `HEAD:${slug}.md`);
+ console.log(`[G6 ingest-hidden-rows/${backend}] page_has_row=${page!.compiled_truth.includes('HIDDEN_ROW_ALICE_EXAMPLE')} file_has_row=${committed.includes('HIDDEN_ROW_ALICE_EXAMPLE')} facts=${JSON.stringify(facts.map(f => f.fact))}`);
+ expect(page!.compiled_truth).toContain('Notes edited by the webhook.');
+ expect(page!.compiled_truth).toContain('HIDDEN_ROW_ALICE_EXAMPLE');
+ expect(committed).toContain('Notes edited by the webhook.');
+ expect(committed).toContain('HIDDEN_ROW_ALICE_EXAMPLE');
+ expect(facts.map(f => f.fact)).toContain('HIDDEN_ROW_ALICE_EXAMPLE');
+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('');
+ await expect(submitPageMutation({ ...ctx, remote: true }, { operation: 'put_page', params: { slug, content, keep_hidden_rows: true } }))
+ .rejects.toMatchObject({ code: 'invalid_params' });
+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);
});