Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): create a missing source folder on write; refuse a missing checkout as source_checkout_missing (GST-465)

garrytan4a11466a7f04
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84ed06f704..ba8bd42eb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**Page writes to a source whose directory is missing on the brain host no longer fail with a misleading `storage_error`. A source that is a folder inside a checkout now gets its folder created on the first write, and a source whose whole checkout is gone gets a refusal that says so.**
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| The source is a folder inside a checkout and the folder is missing (Git keeps no empty folder, so a fresh clone of a repository whose member folder has no files yet lacks it) | every `put_page`, `capture` and `add_timeline_entry` to it failed with `storage_error` ("The canonical file target cannot be accessed as a regular file"), so a token granted only that member's source could save nothing | the write creates the folder and the page, and the same token reads it back |
+| The source's whole checkout is missing (a brain copied to another machine or into a container without its source directories) | the same `storage_error`, whose fix told the agent to repair file permissions | `recovery_required` with `detail: source_checkout_missing`, naming the source; the fix is the read-only `gbrain sources writer status --source <id> --json`, which shows the registered path. Remote callers are not shown the path. Nothing is written, as before |
+
+A token's source grant decides where it writes exactly as before; this changes only how the file path inside the granted source is resolved.
+
## [0.60.527.0] - 2026-10-31
**A shared brain can now let each member's agent read that member's own private pages, and nobody else's. Access tokens and OAuth clients have a new private-pages grant: `none` for every token and client, existing or new, so remote reads keep hiding `visibility: private` pages exactly as before until the brain host opts a connection in with `gbrain auth rescope --token <name> --private-pages granted-sources` (or `--client <client_id>`). An opted-in connection then reads private pages only in the sources its grant names.**
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e43d770ea2..527b70a180 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -83,7 +83,7 @@ of making a duplicate.
| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |
| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |
| <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |
-| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. |
+| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A page write (`put_page`, `capture`, `add_timeline_entry`, `edit_page` and the other page writers; `detail: source_checkout_missing`) found that the source's canonical checkout directory does not exist on this host, for example a brain copied to another machine or container without its source directories; nothing was written, and the message names the source but not the path. A source directory missing inside a checkout that exists (Git keeps no empty directory, so a fresh clone lacks an empty member folder) is not this refusal: the write creates it. A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry; `gbrain sources writer status --source <source> --json` shows the registered path. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. |
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="schema_behind"></a>`schema_behind` | `migrations_pending` (reason `schema_behind`) | A managed write (`put_page` and every write admitted the same way) was refused before admission because the brain schema is at a lower version than this gbrain build needs: an upgrade installed the new binary but `gbrain apply-migrations` did not finish, often because the database role gbrain connects as does not own the tables. The write path reads tables or columns only the pending migrations add, so publishing now would fail. It is not retryable as is (class `caller`): the same write refuses until the schema is migrated. Nothing was admitted and the request id was not used. A replay of a request id accepted earlier still reconciles, and the `apply-migrations` orchestrators are not refused while they hold the migration lock. | Run `gbrain apply-migrations --yes` on the brain host as the database role that owns the gbrain tables (the fix renders `tell_user_to_run` when this connection's role does not own them), confirm with `gbrain doctor --json` (`schema_version` at head), then resubmit the same write: the same request id commits. A write that already failed on a missing column or table is classified `schema_missing` by `gbrain write-request <request_id> --json`. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 8c51d3f913..65fc082825 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -44,7 +44,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pub
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { landedCommit, PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';
-import { CANONICAL_FILE_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
+import { CANONICAL_FILE_MISSING, SOURCE_CHECKOUT_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import { fenceFailureDetail } from '../fence-repair/refusal.ts';
import { withdrawalFailureDetail } from '../facts/withdrawal.ts';
@@ -205,6 +205,7 @@ function requestError(error: unknown): PublicationFailure {
// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.
const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined)
?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined)
+ ?? (error.detail === SOURCE_CHECKOUT_MISSING ? { origin: SOURCE_CHECKOUT_MISSING } : undefined)
// #6693: a refusal on a page whose file awaits import or is held by sync; the replay after import selects on it.
?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined);
return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 4cd0ffd2de..00ffe06d8d 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -31,7 +31,7 @@ import { ContentSanityBlockError } from '../content-sanity.ts';
import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
import { GIT_HOLD_OP, gitHoldFingerprint, gitHoldFix, readGitHold } from './sync-holds.ts';
import { hostOperatorFix, recordRoute } from './held-reads.ts';
-import { heldFileMessage } from './verb-errors.ts';
+import { heldFileMessage, sourceCheckoutMissingRefusal } from './verb-errors.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';
@@ -313,6 +313,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!binding?.local_path) throw opError('owner_unavailable', 'The canonical worktree is unavailable on this host.',
`This host does not hold source ${row.source_id}'s canonical worktree (or it has no local path), so the file of ${row.slug} was not written. Inspect the owner before resubmitting; the write publishes on the host that owns the source.`,
{ fix: ownerStatusFix(row.source_id) });
+ if (!existsSync(binding.local_path)) throw sourceCheckoutMissingRefusal(row.source_id, row.slug);
const root = join(binding.local_path, binding.relative_path);
// #5622: a new page captured from a file inside the source is published to that file.
const capturedPath = !snapshot && options.capture ? options.capture.path : recordedPathFromFileUri(snapshot?.page.source_uri, root);
@@ -325,7 +326,7 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
if (!options.allowMissing && publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;
throw colonSlugWindowsRefusal(row.slug, row.source_id);
}
- const path = nativeFileTarget(root, candidate);
+ const path = nativeFileTarget(binding.local_path, candidate);
if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The canonical file target is outside its registered source.',
`The file of ${row.slug} resolves outside source ${row.source_id}'s registered root (a symlinked directory or a moved checkout), so nothing was written. Inspect the owner before resubmitting; how to repair the checkout is the user's decision.`,
{ fix: ownerStatusFix(row.source_id) });
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 0d6feaeb20..44bc687c56 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -58,9 +58,12 @@ export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<Publication
/** #6696 (A12): the page's recorded canonical file is gone (`prepareFileTarget`); a producer refuses the same write before admission. */
export const CANONICAL_FILE_MISSING = 'canonical_file_missing';
export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }
+/** GST-465: the source's whole canonical checkout is missing on this host (`prepareFileTarget`, `sourceCheckoutMissingRefusal`). */
+export const SOURCE_CHECKOUT_MISSING = 'source_checkout_missing';
+export interface SourceCheckoutDetail { origin: typeof SOURCE_CHECKOUT_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }
/** #6693: a page write refused because its file holds a committed change sync has not imported (`pending_import`) or sync holds the file (`sync_held`). */
export interface PendingImportDetail { origin: 'pending_import' | 'sync_held'; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }
-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | PendingImportDetail }
+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | SourceCheckoutDetail | PendingImportDetail }
const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;
const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index c456e90090..f3f96df786 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -25,7 +25,8 @@ import type { PgAccessReason } from '../pg-access-classify.ts';
import { contentRefusalFromReceipt } from '../import-screen.ts';
import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/refusal.ts';
import { withdrawnFromDetail } from '../facts/withdrawal.ts';
-import { heldFileDiagnostic } from './verb-errors.ts';
+import { heldFileDiagnostic, sourceCheckoutMissingRefusal } from './verb-errors.ts';
+import { SOURCE_CHECKOUT_MISSING } from './publication-failure.ts';
import { isMissingPageMessage } from './page-identity.ts';
import { registerPersistenceConsumerConfig } from '../embedding-disabled.ts';
@@ -410,6 +411,10 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number
const pending = pendingImportRefusal(row, row.authority?.remote === true);
Object.assign(error, { suggestion: pending.suggestion, fix: pending.fix, reason: pending.reason, detail: pending.detail, docs: pending.docs ?? error.docs });
}
+ if (isTerminal(row) && (row.error_detail as { origin?: unknown } | null | undefined)?.origin === SOURCE_CHECKOUT_MISSING) {
+ const missing = sourceCheckoutMissingRefusal(row.source_id, row.slug || null);
+ Object.assign(error, { suggestion: missing.suggestion, fix: missing.fix, detail: missing.detail, docs: missing.docs });
+ }
// #6317 (B1b): a waiter-only process names the owner that publishes for it, so the caller is told who holds the write instead of polling blind.
if (!isTerminal(row) && hints.waiterOnlyOwner) {
const owner = hints.waiterOnlyOwner;
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 924a9ec6f9..f672def4ee 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -8,6 +8,17 @@ import { fenceLocationFromMessage, fenceWhere } from '../fence-repair/refusal.ts
import { FACT_WITHDRAWN_SUGGESTION } from '../facts/withdrawal.ts';
import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';
import { PAGE_CHANGED_AFTER_READ_MESSAGE } from '../page-state/types.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { ERROR_CATALOGUE } from '../error-catalogue.ts';
+import { SOURCE_CHECKOUT_MISSING } from './publication-failure.ts';
+
+/** GST-465: a page write to a source whose canonical checkout is missing on this host. The path is left to the read-only fix, which a remote caller cannot run. */
+export function sourceCheckoutMissingRefusal(sourceId: string, slug: string | null): OperationError {
+ return opError('recovery_required', `The canonical checkout of source '${sourceId}' is missing on this host, so ${slug ? `the file of ${slug}` : 'the page file'} was not written.`,
+ 'Nothing was written. Restore the checkout at the path the command in fix shows (from a backup or the machine it came from), then submit again with a new request_id; an empty directory recreated there does not help. How to recover the source is the user\'s decision.',
+ { detail: SOURCE_CHECKOUT_MISSING, docs: ERROR_CATALOGUE.source_checkout_missing.docs,
+ fix: readFix(`Shows source ${sourceId}'s canonical binding and the checkout path this host registered for it, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
+}
/** The refusal of a fact-batch completion request whose per-entity requests did not all commit (facts-prepare.ts). */
export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not committed.';
diff --git a/test/e2e/source-checkout-missing-write-postgres.test.ts b/test/e2e/source-checkout-missing-write-postgres.test.ts
new file mode 100644
index 0000000000..b780bbc7c4
--- /dev/null
+++ b/test/e2e/source-checkout-missing-write-postgres.test.ts
@@ -0,0 +1,11 @@
+/** GST-465 on Postgres; the scenarios and their contract are in test/helpers/source-checkout-missing-scenarios.ts. */
+import { describe, test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+import { missingSourceCheckout, missingSourceSubdirectory } from '../helpers/source-checkout-missing-scenarios.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+
+d('GST-465: member-token page writes when the source directory is missing (Postgres)', () => {
+ test('a missing source subdirectory is created and the same token reads the page back', () => missingSourceSubdirectory(process.env.DATABASE_URL), 240_000);
+ test('a missing source checkout refuses with source_checkout_missing and writes nothing', () => missingSourceCheckout(process.env.DATABASE_URL), 240_000);
+});
diff --git a/test/helpers/source-checkout-missing-scenarios.ts b/test/helpers/source-checkout-missing-scenarios.ts
new file mode 100644
index 0000000000..7d7886e0b5
--- /dev/null
+++ b/test/helpers/source-checkout-missing-scenarios.ts
@@ -0,0 +1,99 @@
+/**
+ * GST-465: a source-scoped token's page writes when the source's directory is missing on the brain host.
+ *
+ * Two shapes, each run on PGLite (keyless) and Postgres through a real bearer token granted only the member's source
+ * (remote, the serve-http path):
+ * - the source is a subdirectory of a checkout and that subdirectory is missing (Git keeps no empty directory, so a
+ * fresh clone of a repository whose member folder has no files yet lacks it): put_page, private or not, capture and
+ * add_timeline_entry write the page, the missing directory is created, and the same token reads the page back.
+ * - the source's whole checkout is missing (a brain copied to another machine or container without its source
+ * directories): every page write refuses with the classified source_checkout_missing refusal, not a storage_error
+ * that tells the agent to repair file permissions; a remote caller is not shown the host path; nothing is written.
+ * Regression: both shapes refused every page write with storage_error ("The canonical file target cannot be accessed
+ * as a regular file") because the file target was resolved against the source directory itself.
+ */
+import { expect } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { AuthInfo } from '../../src/core/ops/contract.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { mintLegacyToken } from '../../src/core/token-mint.ts';
+import { parseRescopeTokenArgs, rescopeLegacyToken } from '../../src/core/grants/legacy-token.ts';
+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { managedBrain } from './managed-brain.ts';
+
+const page = (title: string, extra = '') => `---\ntitle: ${title}\ntype: note\n${extra}---\n\n${title} body.\n`;
+
+async function memberToken(engine: BrainEngine, sourceId: string): Promise<AuthInfo> {
+ const name = `bot-${sourceId}`;
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'] });
+ await rescopeLegacyToken(engine, parseRescopeTokenArgs([name, '--sources', sourceId, '--private-pages', 'granted-sources']));
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(minted.token) as unknown as AuthInfo;
+ expect(auth).toMatchObject({ sourceId, allowedSources: [sourceId] });
+ return auth;
+}
+
+function caller(engine: BrainEngine, auth: AuthInfo) {
+ return async (op: string, args: Record<string, unknown>) => {
+ const out = await dispatchToolCall(engine, op, args, { remote: true, transport: 'http', sourceId: auth.sourceId, auth });
+ const text = (out.content[0] as { text: string }).text;
+ return { isError: out.isError === true, text, body: JSON.parse(text) as Record<string, any> };
+ };
+}
+
+export function missingSourceSubdirectory(databaseUrl?: string) {
+ return managedBrain(async ({ engine, root }) => {
+ const checkout = join(root, '..', 'workspace');
+ const memberDir = join(checkout, 'member-a');
+ mkdirSync(memberDir, { recursive: true });
+ writeFileSync(join(checkout, 'README.md'), 'workspace\n');
+ execFileSync('git', ['-C', checkout, 'init', '-q']);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'member-a', path: memberDir });
+ rmSync(memberDir, { recursive: true, force: true });
+ const call = caller(engine, await memberToken(engine, 'member-a'));
+
+ for (const [slug, extra] of [['notes/plain-a', ''], ['notes/private-a', 'visibility: private\n']] as const) {
+ const put = await call('put_page', { slug, content: page(slug, extra) });
+ expect({ slug, error: put.body.error ?? null }).toEqual({ slug, error: null });
+ expect(put.body).toMatchObject({ slug, source_id: 'member-a' });
+ expect(readFileSync(join(memberDir, `${slug}.md`), 'utf8')).toContain(`${slug} body.`);
+ const read = await call('get_page', { slug });
+ expect({ slug, error: read.body.error ?? null, source: read.body.source_id }).toEqual({ slug, error: null, source: 'member-a' });
+ expect(read.body.compiled_truth).toContain(`${slug} body.`);
+ }
+ const captured = await call('capture', { content: 'Captured by the member token.', slug: 'notes/captured-a' });
+ expect(captured.body.error ?? null).toBeNull();
+ expect((await call('get_page', { slug: 'notes/captured-a' })).body.compiled_truth).toContain('Captured by the member token.');
+ const timeline = await call('add_timeline_entry', { slug: 'notes/plain-a', date: '2026-10-31', summary: 'Member timeline entry' });
+ expect(timeline.body.error ?? null).toBeNull();
+ expect((await call('get_page', { slug: 'notes/plain-a' })).body.timeline).toContain('Member timeline entry');
+ }, { databaseUrl });
+}
+
+export function missingSourceCheckout(databaseUrl?: string) {
+ return managedBrain(async ({ engine, root }) => {
+ const memberDir = join(root, '..', 'staging', 'member-b');
+ mkdirSync(memberDir, { recursive: true });
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'member-b', path: memberDir });
+ rmSync(join(root, '..', 'staging'), { recursive: true, force: true });
+ const call = caller(engine, await memberToken(engine, 'member-b'));
+
+ for (const [op, args] of [
+ ['put_page', { slug: 'notes/plain-b', content: page('notes/plain-b') }],
+ ['put_page', { slug: 'notes/private-b', content: page('notes/private-b', 'visibility: private\n') }],
+ ['capture', { content: 'Captured into a missing checkout.', slug: 'notes/captured-b' }],
+ ] as const) {
+ const out = await call(op, { ...args });
+ expect({ op, isError: out.isError, code: out.body.code, detail: out.body.detail }).toEqual({ op, isError: true, code: 'recovery_required', detail: 'source_checkout_missing' });
+ expect(out.body.message).toContain("source 'member-b'");
+ expect(out.text).not.toContain(memberDir);
+ expect((await call('get_page', { slug: args.slug })).body.error).toBe('page_not_found');
+ }
+ expect(existsSync(memberDir)).toBe(false);
+ }, { databaseUrl });
+}
diff --git a/test/source-checkout-missing-write.test.ts b/test/source-checkout-missing-write.test.ts
new file mode 100644
index 0000000000..ffb5ec57e1
--- /dev/null
+++ b/test/source-checkout-missing-write.test.ts
@@ -0,0 +1,8 @@
+/** GST-465 on PGLite (keyless); the scenarios and their contract are in test/helpers/source-checkout-missing-scenarios.ts. */
+import { describe, test } from 'bun:test';
+import { missingSourceCheckout, missingSourceSubdirectory } from './helpers/source-checkout-missing-scenarios.ts';
+
+describe('GST-465: member-token page writes when the source directory is missing (PGLite)', () => {
+ test('a missing source subdirectory is created and the same token reads the page back', () => missingSourceSubdirectory(), 120_000);
+ test('a missing source checkout refuses with source_checkout_missing and writes nothing', () => missingSourceCheckout(), 120_000);
+});