Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Skip automatic sync for a plain content directory with one predicate (fix wave 15 P4.2)

garrytan582ddd4b8062
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index c1f1086dbd..9402ad2f31 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -11,7 +11,7 @@ import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts
import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
import { automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
import { isSyncDisabledConfig } from '../core/sync-policy.ts';
-import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';
+import { automaticSyncSkip, loadActivationPendingSourceIds, reportAutomaticSyncSkip, skipActivationPendingSync } from '../core/sync-policy.ts';
import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';
import {
autopilotRemediationIdempotencyKey,
@@ -271,11 +271,12 @@ export async function dispatchFreshnessSyncs(
continue;
}
if (!src.local_path) continue;
- // #4399: config.syncEnabled=false excludes a source from AUTOMATIC
- // sync (this loop, the full-cycle fan-out, `sync --all`); an
- // explicit `gbrain sync --source <id>` is unaffected.
- if (isSyncDisabledConfig(src.config)) continue;
- if (skipActivationPendingSync(activationPending, src.id, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'))) continue; // #5198
+ // #4399 / #5198 / P4.2 (supersedes #6465): one predicate decides whether AUTOMATIC sync runs for this source
+ // (disabled config, claim awaiting activation, gbrain-owned content directory where sync does not apply); the
+ // reason is stated once per source and reason, and an explicit `gbrain sync --source <id>` is unaffected.
+ const skip = await automaticSyncSkip(engine, src, activationPending);
+ if (skip?.reason !== 'sync_disabled') reportAutomaticSyncSkip(src.id, skip, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'));
+ if (skip) continue;
// A local_path this machine cannot use — relative (#3696: cwd is
// launchd's, not the registering shell's) or absent on disk and
// not a managed clone sync can re-create — would sync a phantom
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index 5e6964baa6..1347da3b3d 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -44,8 +44,7 @@ import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts
import { attemptedConnectorSourceIds } from '../core/persistence/connector-state.ts';
import { parseSourceConfig, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
import { automaticSyncPull } from '../core/persistence/automatic-sync-policy.ts';
-import { isSyncDisabledConfig } from '../core/sync-policy.ts';
-import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';
+import { automaticSyncSkip, loadActivationPendingSourceIds, reportAutomaticSyncSkip } from '../core/sync-policy.ts';
import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';
// #2194 fix #2: failure cooldown. A source whose autopilot-cycle keeps
@@ -575,11 +574,11 @@ export async function dispatchPerSource(
// stamp; only the sync phase (and the pull that feeds it) is dropped —
// normalizeQueuedSourcePhases passes a freshness subset through as-is.
// #5198: a claimed source awaiting activation is treated the same way,
- // so its cycle does not fail on a sync that is refused by contract.
- const pendingActivation = skipActivationPendingSync(
- activationPending, src.id, 'fanout_sync_skipped', opts.jsonMode === true, opts.jsonMode ? emit : log,
- );
- const syncDisabled = isSyncDisabledConfig(src.config) || pendingActivation;
+ // so its cycle does not fail on a sync that is refused by contract, and
+ // so is a gbrain-owned content directory where sync does not apply (P4.2).
+ const skip = await automaticSyncSkip(engine, src, activationPending);
+ if (skip?.reason !== 'sync_disabled') reportAutomaticSyncSkip(src.id, skip, 'fanout_sync_skipped', opts.jsonMode === true, opts.jsonMode ? emit : log);
+ const syncDisabled = !!skip;
const connector = connectorIds.has(src.id);
const shouldPull = !syncDisabled && !connector && await automaticSyncPull(engine, src);
const job = await queue.add(
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 8db718e5b3..b3d8aa5058 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -19,8 +19,7 @@ import {
} from '../../core/sync-embed-backfill.ts';
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 { automaticSyncSkip, isSyncDisabledConfig } from '../../core/sync-policy.ts';
import { composeAbortSignals } from '../../core/sync-reconcile.ts';
import { acknowledgeFailures, unacknowledgedSyncFailures } from '../../core/sync.ts';
import type { SyncResult, SyncOpts } from '../sync.ts';
@@ -38,6 +37,7 @@ import {
} from './report.ts';
import { runSyncTrigger } from './trigger.ts';
import { drainJsonFields, formatDrainSummary, syncOutcome } from '../../core/persistence/sync-drain.ts';
+import { readManagedMode } from '../../core/persistence/ownership.ts';
import { writeJsonDocument } from '../../core/cli-force-exit.ts';
/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */
@@ -359,9 +359,10 @@ 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.
+ // P4.2: the same predicate the autopilot dispatchers use decides which sources this bulk run skips.
const notApplicable: string[] = [];
for (const s of sources) {
- if (await syncContentDirectory(engine, { sourceId: s.id, repoPath: s.local_path ?? undefined })) notApplicable.push(s.id);
+ if ((await automaticSyncSkip(engine, s))?.reason === 'sync_not_applicable') 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;
@@ -558,8 +559,8 @@ async function runSyncAll(
// capped at min(sourceCount, --max-sources, 8) in the parallel path.
// #5984 (ENG-A14): managed sources drain one at a time. Parallel drains contend on the brain-wide
// publication counters (55P03) and, at high RTT, made no progress at all.
- const [persistence] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1').catch(() => []);
- const managedSerial = fanOutEligible && persistence?.enabled === true && runnableSources.length > 1;
+ // #6482: no catch-to-unmanaged; an unknown persistence state refuses before any source is dispatched.
+ const managedSerial = fanOutEligible && runnableSources.length > 1 && await readManagedMode(engine);
if (managedSerial) writeHuman('Managed brain: sources drain one at a time (parallel drains contend on the shared publication counters).');
const effectiveParallel = fanOutEligible && !managedSerial
? Math.min(runnableSources.length, maxSources ?? 8)
@@ -819,9 +820,9 @@ async function runSingleSourceSync(
// carry source_id (#1939), so a single-source retry shouldn't report
// another source's failures.
// A managed retry resumes only the cursor its own options select; failures under other options are named, not counted.
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const managedBrain = await readManagedMode(engine);
let failures: Array<{ source_id: string }> = unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);
- if (brain?.enabled) {
+ if (managedBrain) {
const managed = await readManagedSyncFailures(engine, [sourceId]);
const key = await managedSyncCursorKey(engine, opts).catch(() => null);
const other = key ? managed.filter(f => f.cursor_key !== key) : [];
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index aee5c81b14..df4fb83ebd 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -103,6 +103,12 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
);
return { skipped: true, reason: 'sync_in_progress', source_id: sourceId ?? 'default' };
}
+ // P4.2 (supersedes #6465): a job an older daemon queued for a gbrain-owned content directory completes as a
+ // skip instead of dying after its attempts; the dispatchers no longer queue one (automaticSyncSkip).
+ if ((err as { code?: unknown } | null)?.code === 'sync_not_applicable') {
+ console.error(`[sync] skipped: sync does not apply to ${sourceId ?? 'default'} (gbrain-owned content directory, not a Git checkout).`);
+ return { skipped: true, reason: 'sync_not_applicable', source_id: sourceId ?? 'default' };
+ }
throw err;
}
diff --git a/src/core/sync-policy.ts b/src/core/sync-policy.ts
index facc7aaac8..a6f3e029af 100644
--- a/src/core/sync-policy.ts
+++ b/src/core/sync-policy.ts
@@ -14,6 +14,8 @@
import type { BrainEngine } from './engine.ts';
import { parseSourceConfig } from './sources-load.ts';
+import { readManagedMode } from './persistence/managed-mode.ts';
+import { syncContentDirectory } from './sync-applicability.ts';
/**
* True iff `config` explicitly sets `syncEnabled: false`. parseSourceConfig
@@ -33,18 +35,18 @@ export function isSyncDisabledConfig(config: unknown): boolean {
* way on every tick. The refusal contract itself is unchanged: an explicit
* `gbrain sync --source <id>` still reaches performSync and still refuses.
*
- * Mirrors resolveSyncPersistenceMode: a missing persistence_brain row counts as
- * not activated. Fail-open: when the persistence tables are unreadable (older
- * schema, stub engine) nothing is skipped and dispatch behaves as before.
+ * Mirrors resolveSyncPersistenceMode through the shared `readManagedMode`
+ * (#6482). Fail-open by design, as a dispatch filter: when the persistence
+ * tables are unreadable (older schema, stub engine) or the singleton is
+ * malformed, nothing is skipped here and the dispatched sync itself refuses
+ * with the typed `storage_error`; this filter never routes a write.
*/
export async function loadActivationPendingSourceIds(
engine: Pick<BrainEngine, 'executeRaw'>,
): Promise<Set<string>> {
try {
- const rows = await engine.executeRaw<{ source_id: string }>(
- `SELECT b.source_id FROM persistence_source_bindings b
- WHERE NOT COALESCE((SELECT enabled FROM persistence_brain WHERE singleton=1), false)`,
- );
+ if (await readManagedMode(engine)) return new Set();
+ const rows = await engine.executeRaw<{ source_id: string }>('SELECT b.source_id FROM persistence_source_bindings b');
return new Set(rows.map((r) => r.source_id));
} catch {
return new Set();
@@ -90,3 +92,53 @@ export function activationPendingSkipMessage(sourceId: string): string {
'so sync refuses with writer_coordinator_required. Review `gbrain sources writer status`; ' +
'automatic sync resumes after activation.';
}
+
+export type AutomaticSyncSkipReason = 'sync_disabled' | 'activation_pending' | 'sync_not_applicable';
+export interface AutomaticSyncSkip { reason: AutomaticSyncSkipReason; message: string }
+/** Per-source latch for `reportAutomaticSyncSkip`: the last reason written for each source. */
+export type AutomaticSyncSkipLatch = Map<string, AutomaticSyncSkipReason>;
+const processSkipLatch: AutomaticSyncSkipLatch = new Map();
+
+/**
+ * The one "automatic sync does not run for this source" decision (fix wave 15 P4.2, supersedes #6465 by
+ * @mattverlaque): `config.syncEnabled === false` (#4399), a claim awaiting activation (#5198, when the caller loaded
+ * the pending set) and a gbrain-owned content directory that is not a Git checkout (`sync_not_applicable`), the
+ * refusal performSync would raise. The freshness dispatcher, the full-cycle fan-out and `sync --all` all ask here,
+ * so a source where sync does not apply is skipped before a job is queued instead of failing a job every tick.
+ * Path usability (relative or absent `local_path`) stays with each caller: it is a per-machine condition with its own
+ * `--missing-path` modes and events. An explicit `gbrain sync --source <id>` never consults this.
+ */
+export async function automaticSyncSkip(
+ engine: BrainEngine,
+ src: { id: string; local_path: string | null; config: unknown },
+ activationPending?: ReadonlySet<string>,
+): Promise<AutomaticSyncSkip | null> {
+ if (isSyncDisabledConfig(src.config)) return { reason: 'sync_disabled', message: `[sync] skipping automatic sync for source=${src.id}: config.syncEnabled is false.` };
+ if (activationPending?.has(src.id)) return { reason: 'activation_pending', message: activationPendingSkipMessage(src.id) };
+ const dir = await syncContentDirectory(engine, { sourceId: src.id, repoPath: src.local_path ?? undefined });
+ if (dir) {
+ return { reason: 'sync_not_applicable', message: `[sync] skipping automatic sync for source=${src.id}: ${dir.root} is a gbrain-owned content directory, not a Git checkout. ` +
+ `Add markdown files with \`gbrain import <dir>${dir.keyless ? ' --no-embed' : ''} --source ${src.id}\`; automatic sync applies once the directory is a Git checkout.` };
+ }
+ return null;
+}
+
+/**
+ * Writes a skip once per source and reason (an NDJSON `event` line under --json, the message otherwise): a daemon
+ * states the reason on the tick it first applies and again only when the reason changes. A source that is not skipped
+ * clears its entry, so the reason is stated again if it returns. The latch is per process by default (the freshness
+ * loop and the fan-out share one daemon); a caller may hold its own.
+ */
+export function reportAutomaticSyncSkip(
+ sourceId: string,
+ skip: AutomaticSyncSkip | null,
+ event: string,
+ jsonMode: boolean,
+ write: (line: string) => void,
+ latch: AutomaticSyncSkipLatch = processSkipLatch,
+): void {
+ if (!skip) { latch.delete(sourceId); return; }
+ if (latch.get(sourceId) === skip.reason) return;
+ latch.set(sourceId, skip.reason);
+ write(jsonMode ? JSON.stringify({ event, source_id: sourceId, reason: skip.reason }) : skip.message);
+}
diff --git a/test/autopilot-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.ts
index ca64c62f29..a11753e8e8 100644
--- a/test/autopilot-fanout-wiring.test.ts
+++ b/test/autopilot-fanout-wiring.test.ts
@@ -140,19 +140,22 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
const loopBody = DISPATCH_SRC.slice(loopIdx, queueAddIdx);
// Exact-literal match on the FULL guard clause (condition + continue),
// not just the function-call substring — a mutation that keeps calling
- // isSyncDisabledConfig() but drops the `if (...) continue` (e.g.
- // `isSyncDisabledConfig(src.config);` as a no-op statement) restores the
- // #4399 bug while still containing the bare substring, so a loose
- // `.toContain('isSyncDisabledConfig')` check alone would not catch it.
- expect(loopBody).toContain('if (isSyncDisabledConfig(src.config)) continue;');
+ // the predicate but drops the `if (skip) continue` (a no-op statement)
+ // restores the #4399 bug while still containing the bare substring, so a
+ // loose `.toContain('automaticSyncSkip')` check alone would not catch it.
+ // P4.2: the disabled-config check is the first arm of the shared
+ // automaticSyncSkip predicate (unit coverage in test/sync-policy.test.ts
+ // and test/autopilot-freshness-not-applicable-6465.test.ts).
+ expect(loopBody).toContain('const skip = await automaticSyncSkip(engine, src, activationPending);');
+ expect(loopBody).toContain('if (skip) continue;');
// The predicate comes from the sync-policy module via a STATIC import
// (the wave review made sources-load static for the same loop; a dynamic
// import here would re-introduce what that review removed), not from
// performSync's own enforcement — this dispatcher is meant to stand on
// its own regardless of what performSync does internally.
- expect(AUTOPILOT_SRC).toContain("import { isSyncDisabledConfig } from '../core/sync-policy.ts';");
+ expect(AUTOPILOT_SRC).toMatch(/import \{ automaticSyncSkip, [^\n]*\} from '\.\.\/core\/sync-policy\.ts';/);
expect(AUTOPILOT_SRC).not.toContain("await import('../core/sync-policy.ts')");
- const skipIdx = loopBody.indexOf('if (isSyncDisabledConfig(src.config)) continue;');
+ const skipIdx = loopBody.indexOf('if (skip) continue;');
const localPathGuardIdx = loopBody.indexOf("if (!src.local_path) continue;");
expect(localPathGuardIdx).toBeGreaterThan(-1);
expect(skipIdx).toBeGreaterThan(localPathGuardIdx);
@@ -168,8 +171,11 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
expect(loopIdx).toBeGreaterThan(-1);
expect(queueAddIdx).toBeGreaterThan(loopIdx);
const loopBody = DISPATCH_SRC.slice(loopIdx, queueAddIdx);
- expect(loopBody).toContain("if (skipActivationPendingSync(activationPending, src.id, 'freshness_sync_skipped', jsonMode,");
- expect(loopBody).toMatch(/if \(skipActivationPendingSync\([^\n]*\)\) continue;/);
+ // P4.2: the pending-activation check is the second arm of the shared automaticSyncSkip predicate; the loop
+ // passes the loaded set and `continue`s on any skip.
+ expect(loopBody).toContain('const skip = await automaticSyncSkip(engine, src, activationPending);');
+ expect(loopBody).toContain("reportAutomaticSyncSkip(src.id, skip, 'freshness_sync_skipped', jsonMode,");
+ expect(loopBody).toContain('if (skip) continue;');
const setupIdx = DISPATCH_SRC.lastIndexOf('const activationPending = await loadActivationPendingSourceIds(engine);', loopIdx);
expect(setupIdx).toBeGreaterThan(-1);
expect(loopIdx - setupIdx).toBeLessThan(300);
diff --git a/test/autopilot-freshness-not-applicable-6465.test.ts b/test/autopilot-freshness-not-applicable-6465.test.ts
new file mode 100644
index 0000000000..7eb7684b3f
--- /dev/null
+++ b/test/autopilot-freshness-not-applicable-6465.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Fix wave 15 P4.2 (supersedes PR #6465 by @mattverlaque, whose diagnosis and fail-first test this follows): a brain
+ * whose source is a gbrain-owned content directory (`gbrain init`, no Git checkout) had autopilot's freshness loop queue
+ * a `sync` job for it every slot; performSync refused it (`sync_not_applicable`), never stamped `last_sync_at`, the job
+ * went dead and the next slot queued it again, forever. One `automaticSyncSkip` predicate now decides automatic sync for
+ * the freshness loop, the full-cycle fan-out and `sync --all`; the reason is stated once per source and reason; and a
+ * job an older daemon already queued completes as a skip instead of dying.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync } 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 { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { dispatchFreshnessSyncs } from '../src/commands/autopilot-dispatch.ts';
+import { dispatchPerSource } from '../src/commands/autopilot-fanout.ts';
+import { SOURCE_FRESHNESS_PHASES } from '../src/core/cycle.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
+import { automaticSyncSkip, reportAutomaticSyncSkip } from '../src/core/sync-policy.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);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ home = mkdtempSync(join(tmpdir(), 'gbrain-6465-'));
+});
+
+const inHome = <T,>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+const addSource = (id: string, localPath: string, config: Record<string, unknown> = {}) =>
+ engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, localPath, JSON.stringify(config)]);
+function ownedContentDir(sourceId: string): string {
+ const dir = join(home, '.gbrain', 'content', 'brain-example', sourceId);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+function checkout(name: string): string {
+ const dir = join(home, name);
+ mkdirSync(dir, { recursive: true });
+ execFileSync('git', ['-C', dir, 'init', '-q']);
+ return dir;
+}
+const queued = () => engine.executeRaw<{ name: string; data: Record<string, unknown> }>('SELECT name, data FROM minion_jobs ORDER BY id');
+
+async function freshnessTick(): Promise<string[]> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const log = console.log;
+ (process.stderr as { write: unknown }).write = (chunk: unknown) => { lines.push(String(chunk)); return true; };
+ console.log = () => {};
+ try {
+ await dispatchFreshnessSyncs(engine, new MinionQueue(engine), { baseInterval: 60, slot: `slot-${Math.random()}`, timeoutMs: 60_000, jsonMode: true });
+ } finally {
+ (process.stderr as { write: unknown }).write = write;
+ console.log = log;
+ }
+ return lines.flatMap(l => l.split('\n')).filter(Boolean);
+}
+
+describe('automaticSyncSkip (one predicate for automatic sync)', () => {
+ test('a content directory is sync_not_applicable; a checkout, or the same directory after git init, is not skipped', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir);
+ const skip = await automaticSyncSkip(engine, { id: 'notes-example', local_path: dir, config: {} });
+ expect(skip).toMatchObject({ reason: 'sync_not_applicable' });
+ expect(skip!.message).toContain('gbrain import <dir> --source notes-example');
+ const repo = checkout('repo-example');
+ await addSource('repo-example', repo);
+ expect(await automaticSyncSkip(engine, { id: 'repo-example', local_path: repo, config: {} })).toBeNull();
+ execFileSync('git', ['-C', dir, 'init', '-q']);
+ expect(await automaticSyncSkip(engine, { id: 'notes-example', local_path: dir, config: {} })).toBeNull();
+ }));
+
+ test('disabled config and a pending activation come first, in that order, and are the same reasons the dispatchers already used', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir, { syncEnabled: false });
+ expect(await automaticSyncSkip(engine, { id: 'notes-example', local_path: dir, config: { syncEnabled: false } }, new Set(['notes-example']))).toMatchObject({ reason: 'sync_disabled' });
+ expect(await automaticSyncSkip(engine, { id: 'notes-example', local_path: dir, config: {} }, new Set(['notes-example']))).toMatchObject({ reason: 'activation_pending' });
+ }));
+
+ test('the latch states a reason once per source, again when it changes, and again after the source ran in between', () => {
+ const lines: string[] = [];
+ const latch = new Map();
+ const say = (skip: Parameters<typeof reportAutomaticSyncSkip>[1]) => reportAutomaticSyncSkip('s-example', skip, 'x_skipped', true, l => lines.push(l), latch);
+ say({ reason: 'sync_not_applicable', message: 'm' }); say({ reason: 'sync_not_applicable', message: 'm' });
+ say({ reason: 'activation_pending', message: 'm' });
+ say(null); say({ reason: 'activation_pending', message: 'm' });
+ expect(lines.map(l => JSON.parse(l).reason)).toEqual(['sync_not_applicable', 'activation_pending', 'activation_pending']);
+ });
+});
+
+describe('autopilot on a brain whose source is a gbrain-owned content directory', () => {
+ test('the freshness loop queues no sync job for it, states the reason once across ticks, and still dispatches a checkout beside it', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir);
+ const repo = checkout('repo-example');
+ await addSource('repo-example', repo);
+ const first = await freshnessTick();
+ const second = await freshnessTick();
+ const jobs = await queued();
+ // The checkout's two ticks coalesce on the waiting job (maxWaiting: 1); the content directory gets none.
+ expect(jobs.map(j => [j.name, j.data.sourceId])).toEqual([['sync', 'repo-example']]);
+ const skips = [...first, ...second].map(l => JSON.parse(l)).filter(e => e.event === 'freshness_sync_skipped');
+ expect(skips).toEqual([{ event: 'freshness_sync_skipped', source_id: 'notes-example', reason: 'sync_not_applicable' }]);
+ }));
+
+ test('after the user runs git init there, the next tick dispatches it', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir);
+ await freshnessTick();
+ expect(await queued()).toEqual([]);
+ execFileSync('git', ['-C', dir, 'init', '-q']);
+ await freshnessTick();
+ expect((await queued()).map(j => [j.name, j.data.sourceId])).toEqual([['sync', 'notes-example']]);
+ }));
+
+ test('the full-cycle fan-out drops the sync phase for it (same predicate), with one fanout_sync_skipped event', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir);
+ const events: string[] = [];
+ const opts = { repoPath: dir, slot: 's', timeoutMs: 60_000, fanoutMax: 10, jsonMode: true, emit: (line: string) => events.push(line), log: () => {} };
+ await dispatchPerSource(engine, new MinionQueue(engine), opts);
+ await dispatchPerSource(engine, new MinionQueue(engine), { ...opts, slot: 's2' });
+ const cycles = (await queued()).filter(j => j.name === 'autopilot-cycle');
+ expect(cycles).toHaveLength(1);
+ for (const job of cycles) {
+ expect(job.data.phases).toEqual(SOURCE_FRESHNESS_PHASES.filter(p => p !== 'sync'));
+ expect(job.data.pull).toBe(false);
+ }
+ expect(events.map(e => JSON.parse(e)).filter(e => e.event === 'fanout_sync_skipped'))
+ .toEqual([{ event: 'fanout_sync_skipped', source_id: 'notes-example', reason: 'sync_not_applicable' }]);
+ }));
+
+ test('a sync job an older daemon already queued for it completes as a skip instead of a dead job', () => inHome(async () => {
+ const dir = ownedContentDir('notes-example');
+ await addSource('notes-example', dir);
+ const logged: string[] = [];
+ const error = console.error;
+ console.error = (line: unknown) => { logged.push(String(line)); };
+ let result: unknown;
+ try {
+ result = await makeSyncHandler(engine)({ id: 1, name: 'sync', data: { sourceId: 'notes-example', repoPath: dir, pull: false, auto_embed_backfill: true, embed_reason: 'autopilot_freshness' },
+ signal: new AbortController().signal, updateProgress: async () => {}, log: async () => {} } as never);
+ } finally { console.error = error; }
+ expect(result).toEqual({ skipped: true, reason: 'sync_not_applicable', source_id: 'notes-example' });
+ expect(logged.some(l => l.includes('[sync] skipped: sync does not apply to notes-example'))).toBe(true);
+ expect(await queued()).toEqual([]);
+ }));
+});
diff --git a/test/sync-policy.test.ts b/test/sync-policy.test.ts
index 2a2cda2b03..152a0a4c84 100644
--- a/test/sync-policy.test.ts
+++ b/test/sync-policy.test.ts
@@ -44,7 +44,8 @@ describe('isSyncDisabledConfig', () => {
describe('#5198: activation-pending sync skip', () => {
test('returns the bound source ids the query yields', async () => {
- const engine = { executeRaw: async () => [{ source_id: 'alpha' }, { source_id: 'beta' }] };
+ // #6482: the mode read is the strict shared reader, so the fake answers it with one well-formed unmanaged row.
+ const engine = { executeRaw: async (sql: string) => sql.includes('persistence_brain') ? [{ enabled: false }] : [{ source_id: 'alpha' }, { source_id: 'beta' }] };
expect(await loadActivationPendingSourceIds(engine as never)).toEqual(new Set(['alpha', 'beta']));
});