Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): refuse sync on gbrain-owned content directories with sync_not_applicable; managed refusals name gbrain sync --no-pull --source <id> (E4)
garrytanabbff0f6d643
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 511d88e871..9e5ff62ec5 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).+- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `performSync` calls `assertSyncApplicable` first, so such a source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 108622e556..164a2f5ee1 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -125,7 +125,7 @@ src/core/persistence/source-lifecycle.ts 25src/core/persistence/staging.ts 2src/core/persistence/sync-administration.ts 2src/core/persistence/sync-authority.ts 7-src/core/persistence/sync-discovery.ts 20+src/core/persistence/sync-discovery.ts 19src/core/persistence/sync-origin.ts 3src/core/persistence/sync-prepare.ts 31src/core/persistence/sync-run.ts 8diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex b24ef379dc..952b26f932 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -3,10 +3,26 @@* engine connectEngine() opened. Moved verbatim from the src/cli.ts* handleCliOnly switch (refactor wave 1, W4 cli); the record lives in* src/cli/command-table.ts.+ *+ * A refusal that carries an agent-contract `fix` (e.g. `sync_not_applicable`,+ * `writer_coordinator_required`) renders through `renderCliError` so the+ * operator sees the code, the exact next command and why (`--json`: the v1+ * envelope on stdout).*/import type { BrainEngine } from '../../core/engine.ts';+import { OperationError } from '../../core/ops/contract.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {const { runSync } = await import('../../commands/sync.ts');- await runSync(engine, args);+ try {+ await runSync(engine, args);+ } catch (err) {+ if (!(err instanceof OperationError) || !err.fix) throw err;+ const { renderCliError } = await import('../../core/agent-output.ts');+ const { setCliExitVerdict, writeStdoutFinal } = await import('../../core/cli-force-exit.ts');+ const out = renderCliError(err, { json: args.includes('--json'), command: 'sync', tty: !!process.stderr.isTTY });+ if (out.stdout) await writeStdoutFinal(out.stdout);+ if (out.stderr) process.stderr.write(out.stderr);+ setCliExitVerdict(out.exitCode);+ }}diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 6e7cd0dcc0..387e2dbbc6 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -16,6 +16,7 @@ import { refreshProjectionStatistics } from '../../core/search/projection-statisimport { withRefreshingLock, LockUnavailableError, LockStolenError, syncLockId } from '../../core/db-lock.ts';import { readSyncAnchor } from '../../core/sync-anchor.ts';import { recordUpstreamObservation } from '../../core/sync-upstream.ts';+import { assertSyncApplicable } from '../../core/sync-applicability.ts';import { SyncLockBusyError, formatLockBusyMessage, buildPartialResult } from '../../core/sync-lock.ts';import type { SyncOpts, SyncResult } from '../sync.ts';import { runConnectorSync } from './connector.ts';@@ -25,6 +26,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<assertSyncDispatchActive();const inheritedSignal = currentSourceFilesystemSignal();if (inheritedSignal) opts = { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, inheritedSignal]) : inheritedSignal };+ await assertSyncApplicable(engine, opts);const managed = await resolveSyncPersistenceMode(engine, opts);const finish = async (result: SyncResult, refresh = false): Promise<SyncResult> => {assertSyncDispatchActive();diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex fcb8a423a2..425b959e97 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -17,6 +17,7 @@ import {import type { SyncEmbedBackfillOutcome } from '../../core/sync-embed-backfill.ts';import { runBreakLock } from '../../core/sync-lock.ts';import { isSyncDisabledConfig } from '../../core/sync-policy.ts';+import { syncContentDirectory } from '../../core/sync-applicability.ts';import { composeAbortSignals } from '../../core/sync-reconcile.ts';import { acknowledgeFailures, unacknowledgedSyncFailures } from '../../core/sync.ts';import type { SyncResult, SyncOpts } from '../sync.ts';@@ -316,14 +317,21 @@ async function runSyncAll(// performSync get the [<source-id>] prefix under parallel mode (D6)// - stable JSON envelope {schema_version:1, sources, ...} when --json// v0.41.31: v2Enabled resolved once above (cost gate). Reused here.- const activeSources = sources.filter((s) => !isSyncDisabledConfig(s.config));- const disabledCount = sources.length - activeSources.length;+ const notApplicable: string[] = [];+ for (const s of sources) {+ if (await syncContentDirectory(engine, { sourceId: s.id, repoPath: s.local_path ?? undefined })) notApplicable.push(s.id);+ }+ const activeSources = sources.filter((s) => !isSyncDisabledConfig(s.config) && !notApplicable.includes(s.id));+ const disabledCount = sources.filter((s) => isSyncDisabledConfig(s.config)).length;const humanSink: NodeJS.WriteStream = jsonOut ? process.stderr : process.stdout;const writeHuman = (line: string) => humanSink.write(line + '\n');if (disabledCount > 0) {writeHuman(`Skipping ${disabledCount} disabled source(s).`);}+ if (notApplicable.length > 0) {+ writeHuman(`Skipping ${notApplicable.length} source(s) where sync does not apply (gbrain-owned content directory, not a Git checkout): ${notApplicable.join(', ')}. Add markdown files with \`gbrain import <dir> --source <id>\`.`);+ }// --missing-path skip: classify sources whose checkout is not on this// machine instead of failing them (see parseMissingPathMode's rationale).diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex d2a21519d4..1cd15dbb9c 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1290,13 +1290,10 @@ async function runPhaseSync(// sync overruns into the next cron tick. Report it as a skip.const { SyncLockBusyError } = await import('../commands/sync.ts');if (e instanceof SyncLockBusyError) {- return {- phase: 'sync',- status: 'skipped',- duration_ms: 0,- summary: 'sync already in progress elsewhere — skipped',- details: { syncStatus: 'lock_busy' },- };+ return { phase: 'sync', status: 'skipped', duration_ms: 0, summary: 'sync already in progress elsewhere — skipped', details: { syncStatus: 'lock_busy' } };+ }+ if ((e as { code?: unknown } | null)?.code === 'sync_not_applicable') {+ return { phase: 'sync', status: 'skipped', duration_ms: 0, summary: (e as Error).message, details: { reason: 'sync_not_applicable' } };}return {phase: 'sync',diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex cc9ffe9a25..dcf1676d88 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -4,7 +4,7 @@ import { join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { SyncOpts } from '../../commands/sync.ts';import { parseMarkdown } from '../markdown.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';import { isSyncable, isCodeFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';import { resolveSlugRootMode } from '../sync-anchor.ts';@@ -92,12 +92,22 @@ export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'gittree = matches[0].object;}}+/** A managed-sync `writer_coordinator_required` refusal whose fix is the supported `gbrain sync --no-pull --source <id>` run. */+function managedSyncRefusal(sourceId: string, message: string, suggestion: string): OperationError {+ return opError('writer_coordinator_required', message, suggestion, {+ fix: { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'A managed brain syncs its registered checkout through the persistence coordinator: it imports local HEAD without git pull and keeps every ignored-file and failed-receipt guard.',+ verify: { argv: ['gbrain', 'sources', 'status', sourceId] } },+ });+}/** Validate the current owner and source without enumerating a new manifest. */export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOpts): Promise<ManagedSyncContext> {await assertManagedSyncActive(engine);- if (!opts.noPull && !opts.dryRun) throw new OperationError('writer_coordinator_required', 'Managed sync requires --no-pull; Git pull/rebase needs an explicit drained maintenance window.', `Fast-forward and sync the checkout with gbrain sources refresh ${opts.sourceId ?? 'default'}`);- if (opts.includeGitignored || opts.skipFailed) throw new OperationError('writer_coordinator_required', 'Managed sync cannot bypass ignored-file or failed-receipt guards.');const sourceId = opts.sourceId ?? 'default';+ if (!opts.noPull && !opts.dryRun) throw managedSyncRefusal(sourceId, 'Managed sync requires --no-pull; Git pull/rebase needs an explicit drained maintenance window.',+ `Run gbrain sync --no-pull --source ${sourceId} to import the checkout as it is; to bring in upstream commits first, run gbrain sources refresh ${sourceId}, which fast-forwards and then syncs.`);+ if (opts.includeGitignored || opts.skipFailed) throw managedSyncRefusal(sourceId, 'Managed sync cannot bypass ignored-file or failed-receipt guards.',+ `Run gbrain sync --no-pull --source ${sourceId} without --include-gitignored or --skip-failed; resolve failed files with --retry-failed after fixing them.`);const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; last_commit: string | null; config: Record<string, unknown> }>('SELECT incarnation,archived,local_path,last_commit,config FROM sources WHERE id=$1', [sourceId]);const binding = await getWorktreeBinding(engine, sourceId);diff --git a/src/core/sync-applicability.ts b/src/core/sync-applicability.tsnew file mode 100644index 0000000000..3f45cf7579--- /dev/null+++ b/src/core/sync-applicability.ts@@ -0,0 +1,89 @@+/**+ * Sync applicability (agent-first operator wave, Lane E4).+ *+ * `gbrain init` creates a gbrain-owned content directory+ * (`<GBRAIN_HOME>/.gbrain/content/<brain_id>/<source>`, or an owned+ * `--content-root`) that is not a Git checkout. Sync imports changes between+ * Git commits, so it does not apply there: performSync refuses with+ * `sync_not_applicable` (why + the import fix) before any Git probe, instead of+ * a raw `git rev-parse` failure or the legacy anchor self-heal that would+ * `git init` the directory. gbrain never initializes Git on the user's behalf;+ * the refusal names `git init` only as something to ask the user about.+ */+import { existsSync, realpathSync } from 'node:fs';+import { isAbsolute, join, relative, resolve } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { gbrainPath, loadConfig } from './config.ts';+import { opError, type OperationError } from './ops/contract.ts';+import { readSyncAnchor } from './sync-anchor.ts';+import { contentSetupKey } from './shared-skills/setup.ts';++/** A source whose sync root is a gbrain-owned content directory with no Git checkout. */+export interface SyncContentDirectory {+ sourceId: string;+ root: string;+ keyless: boolean;+}++function canonical(path: string): string {+ try { return realpathSync(path); } catch { return resolve(path); }+}++function underGbrainContent(root: string): boolean {+ const rel = relative(canonical(gbrainPath('content')), canonical(root));+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);+}++async function ownedByContentReceipt(engine: BrainEngine, sourceId: string, root: string): Promise<boolean> {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);+ if (!source?.incarnation) return false;+ const saved = await engine.getConfig(contentSetupKey(sourceId, source.incarnation));+ if (!saved) return false;+ try {+ const receipt = JSON.parse(saved) as { owned_root?: unknown; root?: unknown };+ return receipt.owned_root === true && typeof receipt.root === 'string' && canonical(receipt.root) === canonical(root);+ } catch { return false; }+}++/**+ * The gbrain-owned, non-Git content directory this sync would run against, or+ * null when sync applies (a Git checkout, a user directory, or no root). The+ * root resolves exactly as performSync does (`repoPath`, else the source's+ * anchor). Best-effort: a probe failure means "applies", never a refusal.+ */+export async function syncContentDirectory(engine: BrainEngine, opts: { sourceId?: string; repoPath?: string }): Promise<SyncContentDirectory | null> {+ try {+ const root = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');+ if (!root || !existsSync(root) || existsSync(join(root, '.git'))) return null;+ const sourceId = opts.sourceId ?? 'default';+ if (!underGbrainContent(root) && !(await ownedByContentReceipt(engine, sourceId, root))) return null;+ const keyless = loadConfig()?.embedding_disabled === true || (await engine.getConfig('embedding_disabled')) === 'true';+ return { sourceId, root, keyless };+ } catch {+ return null;+ }+}++/** The `sync_not_applicable` refusal: why, the import fix, and `git init` only after asking the user. */+export function syncNotApplicableError(dir: SyncContentDirectory): OperationError {+ return opError('sync_not_applicable',+ `Sync does not apply to source "${dir.sourceId}": ${dir.root} is a gbrain-owned content directory, not a Git checkout.`,+ `To add markdown files to this brain, import the directory that holds them. To sync this content directory from Git instead, ask the user first; if they agree, initialize Git in ${dir.root} and commit, and sync applies from then on.`,+ {+ reason: 'content_directory',+ why: 'gbrain created this directory for content it manages itself (skills, owned pages); memory lives in the database, so there are no Git commits to sync. gbrain never initializes Git on its own.',+ fix: {+ argv: ['gbrain', 'import', '<dir>', ...(dir.keyless ? ['--no-embed'] : []), '--source', dir.sourceId],+ inputs: [{ name: 'dir', how: 'The directory of markdown files the user wants in this brain (not the gbrain-owned content directory itself).' }],+ consent: [], actor: 'agent', requires_exclusive: true,+ why: `Import reads a directory of markdown files into source "${dir.sourceId}" without Git; pages and facts already in the brain are kept.`,+ verify: { argv: ['gbrain', 'sources', 'status', dir.sourceId] },+ },+ });+}++/** Refuse a sync whose root is a gbrain-owned content directory (no-op when sync applies). */+export async function assertSyncApplicable(engine: BrainEngine, opts: { sourceId?: string; repoPath?: string }): Promise<void> {+ const dir = await syncContentDirectory(engine, opts);+ if (dir) throw syncNotApplicableError(dir);+}diff --git a/test/managed-cycle-pull-upstream.test.ts b/test/managed-cycle-pull-upstream.test.tsindex 2302e52cea..5166742e29 100644--- a/test/managed-cycle-pull-upstream.test.ts+++ b/test/managed-cycle-pull-upstream.test.ts@@ -113,8 +113,11 @@ for (const backend of backends) {test(`${backend}: an explicit managed sync without --no-pull keeps refusing (O-ENG-15)`, async () => {await managedRemoteSource(engine(), async ({ sourceId, root }) => {- await expect(performSync(engine(), { repoPath: root, sourceId, noPull: false, noEmbed: true }))- .rejects.toMatchObject({ code: 'writer_coordinator_required', suggestion: `Fast-forward and sync the checkout with gbrain sources refresh ${sourceId}` });+ const refusal = await performSync(engine(), { repoPath: root, sourceId, noPull: false, noEmbed: true }).then(() => null, (e: unknown) => e);+ expect(refusal).toMatchObject({ code: 'writer_coordinator_required',+ fix: { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], actor: 'agent' } });+ expect((refusal as { suggestion: string }).suggestion).toContain(`gbrain sync --no-pull --source ${sourceId}`);+ expect((refusal as { suggestion: string }).suggestion).toContain(`gbrain sources refresh ${sourceId}`);});}, 120_000);diff --git a/test/sync-applicability.test.ts b/test/sync-applicability.test.tsnew file mode 100644index 0000000000..ad94496c6c--- /dev/null+++ b/test/sync-applicability.test.ts@@ -0,0 +1,117 @@+/**+ * Lane E4 (agent-first operator wave): sync on a gbrain-owned content+ * directory refuses with `sync_not_applicable` (why + the import fix, never a+ * Git step it runs itself); `sync --all` skips it; the dream cycle's sync phase+ * reports it as a skip, not a failure.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { syncContentDirectory } from '../src/core/sync-applicability.ts';+import { contentSetupKey } from '../src/core/shared-skills/setup.ts';+import { performSync } from '../src/commands/sync.ts';+import { runCycle } from '../src/core/cycle.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ home = mkdtempSync(join(tmpdir(), 'gbrain-sync-applicability-'));+});++function inHome<T>(fn: () => Promise<T>): Promise<T> {+ return withEnv({ GBRAIN_HOME: home }, fn);+}++async function addSource(id: string, localPath: string): Promise<void> {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2) ON CONFLICT (id) DO UPDATE SET local_path=EXCLUDED.local_path', [id, localPath]);+}++function ownedContentDir(sourceId: string): string {+ const dir = join(home, '.gbrain', 'content', 'brain-example', sourceId);+ mkdirSync(dir, { recursive: true });+ return dir;+}++describe('syncContentDirectory', () => {+ test('a gbrain-owned content directory without .git is not syncable', () => inHome(async () => {+ const dir = ownedContentDir('notes-example');+ await addSource('notes-example', dir);+ expect(await syncContentDirectory(engine, { sourceId: 'notes-example' })).toMatchObject({ sourceId: 'notes-example', root: dir });+ }));++ test('the same directory after the user ran git init is syncable', () => inHome(async () => {+ const dir = ownedContentDir('notes-example');+ mkdirSync(join(dir, '.git'));+ await addSource('notes-example', dir);+ expect(await syncContentDirectory(engine, { sourceId: 'notes-example' })).toBeNull();+ }));++ test('a user directory outside gbrain content keeps the existing sync path', () => inHome(async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-user-notes-'));+ await addSource('user-example', dir);+ expect(await syncContentDirectory(engine, { sourceId: 'user-example' })).toBeNull();+ rmSync(dir, { recursive: true, force: true });+ }));++ test('an owned --content-root recorded in the setup receipt is not syncable', () => inHome(async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-owned-root-'));+ await addSource('custom-example', dir);+ const [row] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='custom-example'");+ await engine.setConfig(contentSetupKey('custom-example', row.incarnation), JSON.stringify({ version: 1, owned_root: true, root: dir, repository_kind: 'content_directory' }));+ expect(await syncContentDirectory(engine, { sourceId: 'custom-example' })).toMatchObject({ root: dir });+ rmSync(dir, { recursive: true, force: true });+ }));+});++describe('performSync on a content directory', () => {+ test('refuses with sync_not_applicable, the import fix and the source id filled', () => inHome(async () => {+ const dir = ownedContentDir('notes-example');+ await addSource('notes-example', dir);+ const err = await performSync(engine, { sourceId: 'notes-example', noPull: true, noEmbed: true }).then(() => null, (e: unknown) => e);+ expect(err).toBeInstanceOf(OperationError);+ const e = err as OperationError;+ expect(e.code).toBe('sync_not_applicable');+ expect(e.reason).toBe('content_directory');+ expect(e.fix?.argv).toEqual(['gbrain', 'import', '<dir>', '--source', 'notes-example']);+ expect(e.fix?.inputs?.[0]?.name).toBe('dir');+ expect(e.fix?.consent).toEqual([]);+ expect(e.suggestion).toContain('ask the user first');+ const env = toAgentError(e, { transport: 'cli', command: 'sync', render: cliRenderContext() });+ expect(env.code).toBe('sync_not_applicable');+ expect(env.class).toBe('caller');+ expect(env.why).toContain('never initializes Git');+ expect(env.fix?.next).toBe('run');+ }));++ test('a keyless brain gets --no-embed in the import fix', () => inHome(async () => {+ const dir = ownedContentDir('notes-example');+ await addSource('notes-example', dir);+ await engine.setConfig('embedding_disabled', 'true');+ const err = await performSync(engine, { sourceId: 'notes-example', noPull: true, noEmbed: true }).then(() => null, (e: unknown) => e) as OperationError;+ expect(err.fix?.argv).toEqual(['gbrain', 'import', '<dir>', '--no-embed', '--source', 'notes-example']);+ }));++ test('the dream sync phase reports sync_not_applicable as a skip, not a failure', () => inHome(async () => {+ const dir = ownedContentDir('notes-example');+ await addSource('notes-example', dir);+ const report = await runCycle(engine, { brainDir: dir, phases: ['sync'], pull: false });+ const sync = report.phases.find(p => p.phase === 'sync');+ expect(sync?.status).toBe('skipped');+ expect(sync?.details).toMatchObject({ reason: 'sync_not_applicable' });+ expect(report.status).not.toBe('failed');+ }), 60_000);+});