Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a Git-synced source that lost its checkout refuses checkout_missing instead of importing as plain (#7973)
garrytanbdfb5a90400f
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 55fa8fc3b6..74f1cf6b7a 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4263,9 +4263,9 @@ More: [docs/guides/troubleshooting.md#sync-freshness-no-successful-sync](../../d| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Sync does not apply to this source: its directory is not a Git checkout. | Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own. `reason: plain_directory` (#7973): a plain directory registered with `sources add --force` is not a Git checkout, so the managed Git path refuses it; `gbrain sync --source <id>` imports its files without Git. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| Sync does not apply to this source: its directory is not a Git checkout. | Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own. `reason: plain_directory` (#7973): a plain directory registered with `sources add --force` is not a Git checkout, so the managed Git path refuses it; `gbrain sync --source <id>` imports its files without Git. `reason: checkout_missing`: a source that has synced from Git and whose root is no longer inside a Git checkout is refused, so its pages are not overwritten by an import; the user restores the checkout. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |-Reasons: `content_directory`, `plain_directory`.+Reasons: `checkout_missing`, `content_directory`, `plain_directory`.### sync_parser_regressiondiff --git a/src/commands/sync/plain-directory.ts b/src/commands/sync/plain-directory.tsindex 30aef21445..f694dce2a3 100644--- a/src/commands/sync/plain-directory.ts+++ b/src/commands/sync/plain-directory.ts@@ -14,6 +14,7 @@ import { isAnchorOwnedSyncPath } from '../../core/sync-anchor.ts';import { syncExcludePatterns } from '../../core/persistence/sync-discovery.ts';import { maintenanceAttribution } from '../../core/persistence/attribution.ts';import { withCoordinatedWrite } from '../../core/persistence/context.ts';+import { opError } from '../../core/ops/contract.ts';import type { SyncOpts, SyncResult } from '../sync.ts';/** Whether `dir` or any directory above it has a `.git` entry (read from the filesystem, no Git process). */@@ -27,13 +28,15 @@ function underGitCheckout(dir: string): boolean {/*** The registered root of a plain-directory source, or null when sync's Git path applies: a connector, a path override* other than the registered root, a root inside any Git checkout, or the classic default brain repo, whose sync keeps- * its own self-heal (#2964).+ * its own self-heal (#2964). A source that has synced from Git (`last_commit` set) and lost its checkout refuses+ * `sync_not_applicable` (`checkout_missing`): importing it as plain would overwrite database-only edits and stop+ * deletions from propagating.*/export async function plainDirectorySyncRoot(engine: BrainEngine, opts: SyncOpts, managed: boolean): Promise<string | null> {if (opts.githubItem || opts.srcSubpath) return null;const sourceId = opts.sourceId ?? 'default';- const [source] = await engine.executeRaw<{ local_path: string | null; config: { kind?: unknown } | null }>(- 'SELECT local_path,config FROM sources WHERE id=$1 AND NOT archived', [sourceId]);+ const [source] = await engine.executeRaw<{ local_path: string | null; last_commit: string | null; config: { kind?: unknown } | null }>(+ 'SELECT local_path,last_commit,config FROM sources WHERE id=$1 AND NOT archived', [sourceId]);const registered = source?.local_path;if (!registered || !isAbsolute(registered) || source.config?.kind != null) return null;let root: string;@@ -44,6 +47,13 @@ export async function plainDirectorySyncRoot(engine: BrainEngine, opts: SyncOpts} catch { return null; }if (underGitCheckout(root)) return null;if (!managed && await isAnchorOwnedSyncPath(engine, opts, root)) return null;+ if (source.last_commit) throw opError('sync_not_applicable',+ `Sync refused for source ${sourceId}: it last synced from Git commit ${source.last_commit.slice(0, 12)}, but ${root} is no longer inside a Git checkout.`,+ `Ask the user whether the checkout was moved or deleted. Restore the Git checkout at ${root} (or point the source at where it now lives) and sync again. Nothing was synced.`,+ { reason: 'checkout_missing', why: 'Importing a former Git checkout as a plain directory would overwrite pages edited since the last commit and stop deletions from propagating.',+ fix: { argv: ['gbrain', 'sources', 'status', sourceId], consent: [], actor: 'user', ask_user: true, requires_exclusive: false,+ user_message: `Source ${sourceId} used to sync from a Git checkout at ${root}, but that folder is no longer a Git checkout. Was it moved or deleted? Restore it (or tell me where it lives now) and I will sync again.`,+ why: 'Shows the source and its registered path; nothing changes until the checkout is back.' } });return root;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f34518e5f4..73c86297ab 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1381,7 +1381,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.516.0', id: 'file_drift_followups_7974', text: 'A page a read-only mirror stored database-only is compared with the file at its slug path the way `gbrain sources reconcile` reads it: one that agrees is listed `release_hold` instead of drifted, and one whose slug path has several spellings is listed unknown (`slug_path_ambiguous`) instead of aborting `gbrain repair file-drift` and the conflict audit. A held file whose page agrees with a different file than the held one is listed unknown instead of `release_hold`. The slug path of a page with no recorded file follows the source\'s slug-root mode and never resolves through a symlink.' },{ since: '0.60.516.0', id: 'provenance_repair_held_8009', text: '`gbrain repair provenance` now lists a page whose file sync holds (a `file_drift` hold, for example) as `held`, with the hold\'s code and fix, instead of planning it: the owner page write refuses such a page, so the preview used to count pages the apply could not write and the batch ended with a failed item. The apply also skips a page held after its preview as `held` rather than failing it, so it writes the count the preview printed.' },{ since: '0.60.516.0', id: 'pass_transient_streak_7982', text: '`gbrain sync status` and doctor `managed_sync_blocked` now read a managed source `blocked` / `pass_abandoned` (next: `gbrain doctor --json` and a report) when its last two sync passes each ended on a transient stop (a statement timeout, a lost connection, write back-pressure, a worktree refresh), as they already did for passes left open; one such pass still reads `resumable` with the plain sync. The idle-pass and stalled-holder readings compare database timestamps with the database clock, so a host clock running ahead no longer reads a running pass as abandoned or a progressing holder as stalled.' },- { since: '0.60.516.0', id: 'plain_directory_sync_7973', text: '`gbrain sync` on a plain directory registered with `gbrain sources add --path <dir> --force` (no Git checkout at or above it) now imports its files into the source the way `gbrain import` does; it used to fail with a raw `git rev-parse` internal_error. There are no commits to diff, so a file removed from the directory keeps its page.' },+ { since: '0.60.516.0', id: 'plain_directory_sync_7973', text: '`gbrain sync` on a plain directory registered with `gbrain sources add --path <dir> --force` (no Git checkout at or above it) now imports its files into the source the way `gbrain import` does; it used to fail with a raw `git rev-parse` internal_error. There are no commits to diff, so a file removed from the directory keeps its page. A source that has synced from Git and lost its checkout refuses `sync_not_applicable` (`checkout_missing`) instead.' },{ since: '0.60.516.0', id: 'former_binding_parked_group_7985', text: 'Doctor `parked_effects` and `gbrain sources writer status` now list parked Git effects recorded under a former canonical binding in their own parked group (`former_binding`: reason, recorded and current worktree, request ids), whose `command` is the `settle-effects` preview instead of the bulk retry that never selects them; doctor\'s per-effect command for them is `settle-effects --request-id`, the exact retry\'s `source_changed` refusal names both bindings with that preview as its fix, and the bulk retries\' `former_worktree` lists the worktree and requests. A tool reading one parked group per source and code can now see two.' },{ since: '0.60.516.0', id: 'settle_effects_retire_7985', text: '`gbrain sources writer settle-effects --retire` settles a parked Git effect of a former binding that nothing current owes, on evidence: its source was archived, removed or re-created, or each target\'s page moved to a later revision, was deleted or lost its slug to another page. It is previewed, bound to its plan hash, applied only after the user agrees, never retried, and `--unsettle` reverses it. The parked group for a replaced source now names that preview, and plain settle\'s `source_replaced` refusal points to it.' },{ since: '0.60.516.0', id: 'managed_marker_own_directory_7988', text: 'Managed persistence now marks a root that no Git checkout tracks (a connector clone or plain directory under a dotfiles home) in its own directory instead of in the enclosing repository, so legacy writers elsewhere in that repository are no longer refused, and the autopilot HEAD probe no longer reads the enclosing repository\'s HEAD for it. A marker an older release already wrote there stays until `gbrain sources writer deactivate` removes it (preview with `--dry-run --json`; activate again afterwards), and a write it refuses now says so.' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a3c0c880d3..26a39ff576 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -694,7 +694,7 @@ export const CODES = {summary: "Sync refused: the source's stored directory (sources.local_path, or sync.repo_path) is a relative path such as \".\", which names whatever directory gbrain runs from.",why: "A relative stored path cannot prove which folder is the brain. Before #7630 a sync run from an unrelated folder treated that folder as the brain repo: it Git-initialized it, committed everything in it and imported its markdown. gbrain now refuses before any Git probe or import, and nothing is changed.",suggestion: 'Ask the user which directory holds the source, then gbrain sources set-path <id> <absolute-directory>; or clear the pointer with gbrain sources set-path <id> --clear. A path that is absolute only on another operating system (a Windows drive path read on Linux or macOS) is refused the same way; set-path fixes it and --clear does not apply.' },- sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own. `reason: plain_directory` (#7973): a plain directory registered with `sources add --force` is not a Git checkout, so the managed Git path refuses it; `gbrain sync --source <id>` imports its files without Git.", reasons: ['content_directory', 'plain_directory'] },+ sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own. `reason: plain_directory` (#7973): a plain directory registered with `sources add --force` is not a Git checkout, so the managed Git path refuses it; `gbrain sync --source <id>` imports its files without Git. `reason: checkout_missing`: a source that has synced from Git and whose root is no longer inside a Git checkout is refused, so its pages are not overwritten by an import; the user restores the checkout.", reasons: ['checkout_missing', 'content_directory', 'plain_directory'] },// #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).sync_admission_restricted: { class: 'host_only', retryable: false, actor: 'user',summary: "`sync.admission` is not `normal`, so managed sync admits less than it classifies: `imports_only` admits no deletes and no keep_db writes (they wait as `paused_deletes` and `paused_keep_db`), and `classify_only` writes and stamps nothing.",diff --git a/test/sync-plain-directory-7973.test.ts b/test/sync-plain-directory-7973.test.tsindex dba7f17c28..30b06b6564 100644--- a/test/sync-plain-directory-7973.test.ts+++ b/test/sync-plain-directory-7973.test.ts@@ -2,7 +2,8 @@* #7973: a plain directory registered with `sources add --path <dir> --force` (no Git checkout at or above it)* syncs without Git: the run imports its files into the source the way `gbrain import` does on a repo-less brain.* Fails when: sync dies with a raw `git rev-parse` internal_error, a dry run writes, a removed file deletes its- * page, or `sources add` and sync disagree about what a forced plain directory does.+ * page, `sources add` and sync disagree about what a forced plain directory does, or a Git-synced source whose+ * checkout is gone is imported as plain (its database-only edits would be overwritten and deletions stop propagating).* PGLite always; Postgres too when DATABASE_URL is set.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';@@ -95,4 +96,20 @@ describe('classic brain', () => {});} finally { rmSync(home, { recursive: true, force: true }); }}, 120_000);++ test('a Git-synced source whose checkout is gone refuses instead of importing over the database', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-plain-lost-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const dir = join(home, 'lost-checkout'); mkdirSync(join(dir, 'people'), { recursive: true });+ writeFileSync(join(dir, 'people', 'bob-example.md'), person('Bob Example', 'Works at acme-example.'));+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config,last_commit) VALUES('source-b','source-b',$1,'{}','0123456789abcdef0123456789abcdef01234567')", [dir]);+ await expect(performSync(engine, { sourceId: 'source-b', noPull: true, noEmbed: true })).rejects.toMatchObject({+ code: 'sync_not_applicable', reason: 'checkout_missing', fix: { actor: 'user', ask_user: true } });+ expect(await engine.getPage('people/bob-example', { sourceId: 'source-b' })).toBeNull();+ const [row] = await engine.executeRaw<{ last_sync_at: unknown }>("SELECT last_sync_at FROM sources WHERE id='source-b'");+ expect(row?.last_sync_at).toBeNull();+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 120_000);});