Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sources): keep gbrain-owned --url clones unwritten on unmanaged brains (GBRA-130 C-2, #6946)
garrytan99db2762ddea
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.tsindex c095f3690d..de2498a3e8 100644--- a/src/commands/brainstorm.ts+++ b/src/commands/brainstorm.ts@@ -442,6 +442,13 @@ export function formatSaveOutcome(exitCode: 0,};}+ if (dbSaved && writeThrough.skipped === 'url_clone') {+ return {+ stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a clone gbrain pulls from upstream — kept database-only)._`,+ stderr,+ exitCode: 0,+ };+ }if (dbSaved) {// File write attempted but errored (already on stderr). Row is durable.return {diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 6305a33ae3..8dfd9f82f1 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -45,7 +45,9 @@* `guardTriggered` and the halt rollup still report the run; status returns* `warn` naming each failed page. Rows with no backing page or checkout* (slugify-floor / stub-guard-blocked slugs from the inline writer) are- * structurally unfenceable and never gate.+ * structurally unfenceable and never gate, and neither are the rows of a+ * clone gbrain owns (#6946), which stay database-only and out of+ * reconciliation.*/import { withUnmanagedBeliefs } from '../belief/projection-point.ts';@@ -96,6 +98,7 @@ import { embed, getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '.import { isAborted } from '../abort-check.ts';import { parseMarkdown } from '../markdown.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';+import { urlCloneReadOnly } from '../url-clone.ts';import { acquirePageLock } from '../page-lock.ts';import {lockReconcileRevision,@@ -797,9 +800,10 @@ export async function runExtractFacts(// the destructive reconciliation pass; the other pages reconcile.// #6610: rows the unbound-source policy keeps unfenced on database-only pages stay held out of reconciliation// but never gate the run; doctor fence_integrity names the opt-in that fences them.+ // #6946: so do the database-only rows of a clone gbrain owns, which is never fenced.const pending = await pendingLegacyRows(engine, sourceId);const legacySlugs = new Set(pending.keys());- const gating = [...pending].filter(([slug]) => !unboundRefused.has(slug));+ const gating = await urlCloneReadOnly(engine, sourceId) ? [] : [...pending].filter(([slug]) => !unboundRefused.has(slug));const legacyCount = gating.reduce((sum, [, n]) => sum + n, 0);result.legacyRowsPending = legacyCount;result.legacyPages = gating.map(([slug]) => slug).sort();diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex de6a261218..c773393999 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -1034,7 +1034,7 @@ async function runPipelineBodyInner(// didn't (null-localPath echo, or the write_through flag flipped// mid-pipeline across the config-cache TTL). Route the group to the// legacy DB-only path — never drop facts.- warnOnce(+ if (result.databaseOnlyReason !== 'url_clone') warnOnce('facts:fence-write-unexpected-fallback',`[facts] writeFactsToFence returned legacyFallback for slug=${slug} despite localPath being set — routing to DB-only inserts.`,);diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 573e1b2004..ede5db7749 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -63,6 +63,7 @@ import { recordTaintEdges } from '../trust/taint.ts';import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';import type { TaintInput, WriteTrust } from '../trust/tier.ts';import { gitChildEnv } from '../git-env.ts';+import { urlCloneReadOnly } from '../url-clone.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -115,8 +116,10 @@ export interface FenceWriteResult {inserted: number;/** DB ids assigned to the inserted rows, in input order. */ids: number[];- /** True when the path fell through to DB-only because local_path was unset. */+ /** True when the path fell through to DB-only: local_path unset, `sync.write_through` off, or a gbrain-owned clone (`databaseOnlyReason`). */legacyFallback?: true;+ /** #6946: why a `legacyFallback` is expected — `url_clone`: the source is a clone gbrain owns and pulls (url-clone.ts), so its checkout is never written. */+ databaseOnlyReason?: 'url_clone';/** True when fence parse-validate failed; rows were NOT inserted, .tmp quarantined. */fenceWriteFailed?: true;/**@@ -299,7 +302,9 @@ export function stubEntityPage(* the `## Facts` fence, atomically renames the .tmp into place, and* stamps the DB index via engine.insertFacts.*- * Returns `legacyFallback: true` when `target.localPath` is null —+ * Returns `legacyFallback: true` when `target.localPath` is null (also+ * under `sync.write_through` off and, with `databaseOnlyReason: 'url_clone'`,+ * for a clone gbrain owns, #6946) —* the caller is responsible for falling through to the legacy* DB-only `engine.insertFact` path. We don't do the legacy fallback* here because the caller has the FactsBackstopCtx (visibility,@@ -344,9 +349,8 @@ export async function writeFactsToFence(// choice: no fence file, no stub entity page, no git commit. Same// legacyFallback contract as a missing local_path — the caller's DB-only// path still records the facts.- if (await isWriteThroughDisabled(engine)) {- return { inserted: 0, ids: [], legacyFallback: true };- }+ if (await isWriteThroughDisabled(engine)) return { inserted: 0, ids: [], legacyFallback: true };+ if (await urlCloneReadOnly(engine, target.sourceId)) return { inserted: 0, ids: [], legacyFallback: true, databaseOnlyReason: 'url_clone' };// #4204: compute the SAME path writePageThrough computes for this// (source, slug) — the fence appends to the page's file, so the two writersdiff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex d154f9e60b..a2be5bd424 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -21,7 +21,8 @@* coordinator publishes database-only pages too; archived sources are* skipped) or the source has a `local_path` and the page's canonical file* exists on this host. Everything else is counted and left alone: a NULL- * entity slug, a missing page or file, or a source without a checkout here.+ * entity slug, a missing page or file, a source without a checkout here, or+ * (unmanaged, #6946) a clone gbrain owns, whose checkout is never written.** Adoption oracle (#6278, `adoptableClaim`): the fence codec trims a claim,* folds CRLF/CR to LF, reads `~~x~~` as a struck row and `<br>` as a line@@ -75,6 +76,7 @@ import { UNBOUND_WRITE_KEY } from '../persistence/unbound-source.ts';import { contentHash } from '../utils.ts';import { resolvePageWriteTarget } from '../write-through.ts';import { commitFactFenceFile, gitPathState } from './fence-write.ts';+import { isOwnedClone } from '../url-clone.ts';export interface UnfencedFactRow {id: string;@@ -105,6 +107,8 @@ export interface UnfencedFactsOutcome {skipped_no_local_path: number;skipped_no_page: number;skipped_archived: number;+ /** Unmanaged (#6946): rows of a clone gbrain owns (`sources add --url`), kept database-only so its checkout keeps fast-forwarding. */+ skipped_url_clone: number;pages_touched: number;/** `<slug> (<reason>)` per page whose fence write failed; its rows stay unfenced. */failed_pages: string[];@@ -263,9 +267,10 @@ export function unboundRefusedSentence(pages: UnfencedFactsOutcome['unbound_refu/** Read the unfenced active rows of one source (or every source) and group the fenceable ones per page. */export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?: string } = {}): Promise<UnfencedFactsPlan> {const managed = await managedPersistenceEnabled(engine);- const sources = await engine.executeRaw<{ id: string; local_path: string | null; archived?: boolean }>(- 'SELECT id, local_path, archived FROM sources',+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; archived?: boolean; config: unknown }>(+ 'SELECT id, local_path, archived, config FROM sources',);+ const urlClones = new Set(managed ? [] : sources.filter(isOwnedClone).map(s => s.id));const localPathById = new Map(sources.map(s => [s.id, s.local_path] as const));const archived = new Set(sources.filter(s => s.archived).map(s => s.id));const rows = await engine.executeRaw<UnfencedFactRow>(@@ -282,7 +287,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:);const outcome: UnfencedFactsOutcome = {scanned: rows.length, fenced: 0, skipped_no_entity: 0, skipped_no_local_path: 0, skipped_no_page: 0,- skipped_archived: 0, pages_touched: 0, failed_pages: [], fenced_slugs: [], missing_files: [], unbound_refused: [], unadoptable_rows: [],+ skipped_archived: 0, skipped_url_clone: 0, pages_touched: 0, failed_pages: [], fenced_slugs: [], missing_files: [], unbound_refused: [], unadoptable_rows: [],};const groups = new Map<string, UnfencedFactRow[]>();for (const row of rows) {@@ -290,6 +295,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:// A managed brain publishes through the source's maintenance authority,// which an archived source does not grant; it never blocks the others.if (managed && archived.has(row.source_id)) { outcome.skipped_archived += 1; continue; }+ if (urlClones.has(row.source_id)) { outcome.skipped_url_clone += 1; continue; }if (!localPathById.get(row.source_id) && !managed) { outcome.skipped_no_local_path += 1; continue; }if (!row.page_exists) { outcome.skipped_no_page += 1; continue; }const key = `${row.source_id}\0${row.entity_slug}`;diff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.tsindex 8b8bd5baed..be0e12ce3d 100644--- a/src/core/persistence/mirror-read-only.ts+++ b/src/core/persistence/mirror-read-only.ts@@ -8,14 +8,20 @@* 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).+ *+ * #6946: on an unmanaged brain a clone gbrain owns (`sources add --url`,+ * url-clone.ts) is read-only the same way without the flag, because gbrain+ * pulls it with `git pull --ff-only` on every sync.*/import type { SqlEngine } from './model.ts';+import { urlCloneReadOnly } from '../url-clone.ts';/** `lock`: inside a publication, hold the source row so a concurrent mode change waits for this write. */export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {- const [row] = await engine.executeRaw<{ read_only: boolean }>(- `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;+ const [row] = await engine.executeRaw<{ read_only: boolean; local_path: string | null; config: unknown }>(+ `SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only, local_path, config FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);+ if (!row) return false;+ return row.read_only === true || await urlCloneReadOnly(engine, sourceId, row);}/** Marks a page this publication stored database-only because its source is a read-only mirror and it has no recorded file. */diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex 065a79eb28..573e113e33 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -61,6 +61,7 @@ import { isSyncStrategy, type SyncStrategy } from './sync.ts';import { DEFAULT_CALENDAR_ID } from './google/types.ts';import { resolveSourceWithTier, type SourceTier } from './source-resolver.ts';import { deleteSourceRow } from './source-delete.ts';+import { defaultCloneDir, isOwnedClone } from './url-clone.ts';// ── Errors ──────────────────────────────────────────────────────────────────@@ -312,11 +313,6 @@ async function countVisiblePages(engine: BrainEngine, id: string): Promise<numbereturn rows[0]?.n ?? 0;}-/** Default clone dir for a remote-URL source: $GBRAIN_HOME/clones/<id>/ */-export function defaultCloneDir(id: string): string {- return gbrainPath('clones', id);-}-/** Temp clone dir under $GBRAIN_HOME/clones/.tmp/<id>-<rand>/ */function makeTempCloneDir(id: string): string {const rand = randomBytes(6).toString('hex');@@ -328,39 +324,8 @@ function makeTempCloneDir(id: string): string {// importers (and recloneIfMissing below) keep working unchanged.export { isPathContained };-/**- * Did gbrain CREATE this clone (so re-clone/delete is safe)? Ownership, NOT- * path-containment — a user-supplied working tree is NEVER owned, even if it- * happens to sit under $GBRAIN_HOME. This is the #1881 guard: recloneIfMissing- * deletes local_path, so it must only ever fire on a clone gbrain owns.- *- * Ownership is proven by either:- * 1. config.managed_clone === true — written by addSource's --url path- * (covers both default-location and --clone-dir clones), OR- * 2. local_path === defaultCloneDir(id) — back-compat for clones created- * before the marker existed (gbrain's default location), via exact- * normalized-path equality (symlink-free, so none of isPathContained's- * symlinked-parent / lexical-escape edge cases apply).- *- * Everything else is fail-closed (NOT owned → refuse to touch): the bug's- * federated row (remote_url + a user tree), and pre-marker --clone-dir clones- * (rare, local-only) which are byte-for-byte indistinguishable from it. Those- * must be re-added to regain auto-reclone — the correct trade-off when ownership- * is unprovable.- */-export function isOwnedClone(src: {- id: string;- local_path: string | null;- config: unknown;-}): boolean {- if (!src.local_path) return false;- const cfg =- typeof src.config === 'string'- ? (JSON.parse(src.config) as Record<string, unknown>)- : ((src.config ?? {}) as Record<string, unknown>);- if (cfg.managed_clone === true) return true;- return resolvePath(src.local_path) === resolvePath(defaultCloneDir(src.id));-}+// `isOwnedClone` and `defaultCloneDir` live in url-clone.ts (shared with the #6946 write guards).+export { defaultCloneDir, isOwnedClone };/*** Recovery hint for an unowned source with a remote_url. Splits guidance bydiff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex 669065a58d..0c60bd3723 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -67,6 +67,7 @@ import {type PushLogOutcome,} from './brain-repo-durability.ts';import { extractTimelineFromContent } from './timeline-extract.ts';+import { urlCloneReadOnly } from './url-clone.ts';/** Raw op params for one manual timeline entry (date pre-validated by caller). */export interface TimelineEntryWriteInput {@@ -106,6 +107,7 @@ export interface TimelineWriteThroughOutcome {/** Why the FS-canonical path didn't apply (when handled=false). */skipped?:| 'disabled_by_config'+ | 'url_clone'| 'no_repo_configured'| 'repo_not_found'| 'source_repo_belongs_to_other_source'@@ -309,6 +311,9 @@ export async function writeTimelineEntryThrough(if (await isWriteThroughDisabled(engine)) {return { handled: false, skipped: 'disabled_by_config' };}+ if (await urlCloneReadOnly(engine, sourceId)) {+ return { handled: false, skipped: 'url_clone' };+ }const target = await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) {return { handled: false, skipped: target.skipped };diff --git a/src/core/url-clone.ts b/src/core/url-clone.tsnew file mode 100644index 0000000000..3278ba675e--- /dev/null+++ b/src/core/url-clone.ts@@ -0,0 +1,153 @@+/**+ * gbrain-owned `gbrain sources add --url` clones (#6946, GBRA-130 C-2).+ *+ * gbrain pulls an owned clone with `git pull --ff-only` on every sync, so a+ * local modification in its checkout blocks every pull that touches the same+ * file, forever. On an unmanaged brain gbrain therefore writes nothing into an+ * owned clone's checkout: `urlCloneReadOnly` is the one predicate the fence+ * writer, the page and timeline write-throughs, unfenced-fact fencing and the+ * page publication (through `sourceMirrorReadOnly`) consult, and each keeps the+ * write database-only, the way `mirror_read_only` does for a managed source.+ * A managed brain decides this through `gbrain sources mirror-readonly`.+ *+ * A clone an older release already dirtied gets a typed exit:+ * `urlClonePullBlock` names the files with local changes as+ * `pull_blocked_local_changes`, whose fix asks the user before+ * `gbrain repair url-clone-fences` (repair/url-clone-fences.ts) moves the fence+ * rows gbrain appended database-only and restores those files from HEAD.+ */+import { resolve } from 'node:path';+import { gbrainPath } from './config.ts';+import { execFileSync } from './spawn.ts';+import { gitChildEnv } from './git-env.ts';+import type { Action } from './agent-output.ts';+import { agentBlock } from './agent-markers.ts';+import { managedPersistenceEnabled } from './persistence/ownership.ts';+import type { SqlEngine } from './persistence/model.ts';++/** Default clone dir for a remote-URL source: $GBRAIN_HOME/clones/<id>/ */+export function defaultCloneDir(id: string): string {+ return gbrainPath('clones', id);+}++/**+ * Did gbrain CREATE this clone (so re-clone/delete is safe)? Ownership, NOT+ * path-containment — a user-supplied working tree is NEVER owned, even if it+ * happens to sit under $GBRAIN_HOME. This is the #1881 guard: recloneIfMissing+ * deletes local_path, so it must only ever fire on a clone gbrain owns.+ *+ * Ownership is proven by either:+ * 1. config.managed_clone === true — written by addSource's --url path+ * (covers both default-location and --clone-dir clones), OR+ * 2. local_path === defaultCloneDir(id) — back-compat for clones created+ * before the marker existed (gbrain's default location), via exact+ * normalized-path equality (symlink-free, so none of isPathContained's+ * symlinked-parent / lexical-escape edge cases apply).+ *+ * Everything else is fail-closed (NOT owned → refuse to touch): the bug's+ * federated row (remote_url + a user tree), and pre-marker --clone-dir clones+ * (rare, local-only) which are byte-for-byte indistinguishable from it. Those+ * must be re-added to regain auto-reclone — the correct trade-off when ownership+ * is unprovable.+ */+export function isOwnedClone(src: {+ id: string;+ local_path: string | null;+ config: unknown;+}): boolean {+ if (!src.local_path) return false;+ const cfg =+ typeof src.config === 'string'+ ? (JSON.parse(src.config) as Record<string, unknown>)+ : ((src.config ?? {}) as Record<string, unknown>);+ if (cfg.managed_clone === true) return true;+ return resolve(src.local_path) === resolve(defaultCloneDir(src.id));+}++/** The source row `urlCloneReadOnly` reads; callers that already hold it pass it in. */+export interface CloneSourceRow { local_path: string | null; config: unknown }++/** An unmanaged brain's owned clone: gbrain writes nothing into its checkout. */+export async function urlCloneReadOnly(engine: SqlEngine, sourceId: string, row?: CloneSourceRow): Promise<boolean> {+ const source = row ?? (await engine.executeRaw<CloneSourceRow>('SELECT local_path, config FROM sources WHERE id = $1', [sourceId]))[0];+ if (!source || !isOwnedClone({ id: sourceId, ...source })) return false;+ return !await managedPersistenceEnabled(engine);+}++/** `gbrain repair url-clone-fences --source <id>`, the read-only preview. */+export function urlCloneRepairPreviewArgv(sourceId: string): string[] {+ return ['gbrain', 'repair', 'url-clone-fences', '--source', sourceId];+}++export interface UrlClonePullBlock {+ code: 'pull_blocked_local_changes';+ source_id: string;+ /** Tracked files of the checkout that differ from HEAD (root-relative). */+ paths: string[];+ message: string;+ fix: Action;+}++/** Tracked files of `root` whose index or working copy differs from HEAD. */+export function trackedChanges(root: string): string[] {+ const out = execFileSync('git', ['-C', root, 'diff', '--name-only', '-z', 'HEAD', '--'], { env: gitChildEnv(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) as string;+ return out.split('\0').filter(Boolean).sort();+}++/**+ * Why an owned clone's pull cannot fast-forward, when the reason is local+ * changes in its checkout: null for a clean checkout, a source that is not an+ * unmanaged brain's owned clone, or a checkout git cannot read.+ */+export async function urlClonePullBlock(engine: SqlEngine, sourceId: string): Promise<UrlClonePullBlock | null> {+ const [row] = await engine.executeRaw<CloneSourceRow>('SELECT local_path, config FROM sources WHERE id = $1', [sourceId]);+ if (!row?.local_path || !await urlCloneReadOnly(engine, sourceId, row)) return null;+ let paths: string[];+ try { paths = trackedChanges(row.local_path); } catch { return null; }+ if (!paths.length) return null;+ const preview = urlCloneRepairPreviewArgv(sourceId);+ const shown = paths.slice(0, 5).join(', ') + (paths.length > 5 ? ', …' : '');+ return {+ code: 'pull_blocked_local_changes',+ source_id: sourceId,+ paths,+ message: `Source "${sourceId}" is a clone gbrain owns (sources add --url) and its checkout has local changes in ${paths.length} file(s) (${shown}), `+ + 'so git pull --ff-only cannot fast-forward it and every sync stops at the pull. Older gbrain releases appended ## Facts fence rows to clone files; '+ + 'current releases keep facts about a clone database-only.',+ fix: {+ ask_user: true,+ argv: preview,+ preview_argv: preview,+ consent: ['destructive'],+ actor: 'agent',+ requires_exclusive: false,+ why: 'The preview lists each changed file and proves whether its difference from HEAD is only fence rows gbrain appended; '+ + 'the apply (with the preview hash and the user\'s consent) backs each proven file up, keeps its fact rows database-only and restores it from HEAD.',+ user_message: `gbrain left local changes in ${paths.length} file(s) of the "${sourceId}" clone, so it stopped pulling upstream. `+ + 'Preview a repair that keeps those facts in the database and restores the files from the last pulled commit?',+ verify: { argv: [...preview, '--json'] },+ docs: 'docs/guides/repair.md#url-clone-fences',+ },+ };+}++/** The cycle's sync-phase summary for a pull an owned clone's local changes blocked. */+export function urlClonePullBlockSummary(block: UrlClonePullBlock): string {+ return `git pull blocked (${block.code}): ${block.paths.length} file(s) of the clone have local changes; ask the user, then preview ${block.fix.argv!.join(' ')}`;+}++/** The stderr lines sync prints for a pull an owned clone's local changes blocked. */+export function formatUrlClonePullBlock(block: UrlClonePullBlock): string {+ const preview = block.fix.argv!.join(' ');+ return `[gbrain] ${block.code}: ${block.message}\n` + agentBlock({+ ask: block.fix.user_message,+ why: block.fix.why,+ risk: 'Each restored file is backed up under ~/.gbrain/backups/url-clone-fences/ first; a file with any other local edit is listed and left untouched.',+ consent: 'destructive',+ actor: 'user',+ next: 'ask_user',+ if_yes: `Run ${preview}, then the apply command it prints (--apply --expect <hash> --yes), then gbrain sync --source ${block.source_id}.`,+ if_no: 'Every sync of this source keeps stopping at the pull; its pages stay at the last pulled commit.',+ verify: block.fix.verify!.argv!.join(' '),+ });+}diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 87ef80fe3c..b912a91157 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -35,6 +35,7 @@ import {isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,type PushLogOutcome,} from './brain-repo-durability.ts';+import { urlCloneReadOnly } from './url-clone.ts';/** Minimal logger surface — structurally compatible with operations.ts `Logger`. */export interface WriteThroughLogger {@@ -95,7 +96,7 @@ export interface WriteThroughResult {* - over_push_scan_cap: the rendered file is over the pre-push secret-scan* cap (PUSH_SCAN_MAX_FILE_BYTES), so committing it would block every push.*/- skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap';+ skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap';/** Caller-visible advisory when a permitted DB-only outcome is still risky. */warning?: string;/** Set when the render/write/rename itself threw (EACCES, ENOTDIR, disk full). */@@ -400,6 +401,7 @@ export async function resolvePageWriteTarget(* `sync.repo_path`. Never throws — failures are reported via the result's* `skipped` / `error` fields. put_page calls it before its transaction commits* and rejects non-deliberate skips so a file failure rolls back the DB write.+ * A clone gbrain owns on an unmanaged brain is skipped (`url_clone`, #6946).*/export async function writePageThrough(engine: BrainEngine,@@ -416,6 +418,9 @@ export async function writePageThrough(if (await isWriteThroughDisabled(engine)) {return { written: false, skipped: 'disabled_by_config' };}+ if (await urlCloneReadOnly(engine, sourceId)) {+ return { written: false, skipped: 'url_clone' };+ }const target = await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) {return { written: false, skipped: target.skipped };@@ -537,10 +542,11 @@ export interface DeleteThroughResult {* Non-error reasons nothing was removed. Shares the target-resolution skip* vocabulary (kept in lockstep via the Extract), plus:* - disabled_by_config: the operator opted the brain out of the disk sink.+ * - url_clone: the source is a clone gbrain owns and pulls (#6946); its checkout is never written.* - file_not_present: the page had no artifact on disk (DB-only page, or* already removed by hand) — a clean no-op, not a failure.*/- skipped?: 'disabled_by_config' | 'file_not_present' | Extract<PageWriteTarget, { ok: false }>['skipped'];+ skipped?: 'disabled_by_config' | 'url_clone' | 'file_not_present' | Extract<PageWriteTarget, { ok: false }>['skipped'];/** Set when the unlink itself threw (EACCES, EPERM, read-only mount). */error?: string;}@@ -581,6 +587,9 @@ export async function deletePageThrough(if (await isWriteThroughDisabled(engine)) {return { removed: false, skipped: 'disabled_by_config' };}+ if (await urlCloneReadOnly(engine, sourceId)) {+ return { removed: false, skipped: 'url_clone' };+ }const target = opts.target ?? await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) return { removed: false, skipped: target.skipped };const { filePath, writeRoot } = target;diff --git a/test/brainstorm/save.test.ts b/test/brainstorm/save.test.tsindex 224d77f2f3..c5a3cfc091 100644--- a/test/brainstorm/save.test.ts+++ b/test/brainstorm/save.test.ts@@ -142,6 +142,14 @@ describe('formatSaveOutcome (pure)', () => {expect(m.stdout).toContain('not a directory');});+ test('db only, url_clone (#6946) → exit 0, names the clone instead of an error', () => {+ const o: SaveOutcome = { dbSaved: true, writeThrough: { written: false, skipped: 'url_clone' } };+ const m = formatSaveOutcome(o, ctx);+ expect(m.exitCode).toBe(0);+ expect(m.stdout).toContain('kept database-only');+ expect(m.stdout).not.toContain('file NOT written');+ });+test('db saved but file errored → exit 0, warns on stderr', () => {const o: SaveOutcome = { dbSaved: true, writeThrough: { written: false, error: 'EACCES' } };const m = formatSaveOutcome(o, ctx);