Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

config: sync.* keys as tunables, rollback keys and retired keys (#6712 PR 2, L3)

garrytan44589bc7615f
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 2b4d20df4b..1d21cca24c 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -892,6 +892,15 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
console.error(`[config] source: ${effective.note}`);
return;
}
+ if (action === 'get' && key) {
+ // #6712 PR 2: a retired or rollback sync key prints the value a sync runs with, and where it comes from.
+ const effective = (await import('../core/sync-config-keys.ts')).effectiveSyncKey(key, await engine.getConfig(key));
+ if (effective) {
+ console.log(effective.value);
+ console.error(`[config] source: ${effective.origin}`);
+ return;
+ }
+ }
if (action === 'get' && key) {
// #2120: `get` used to read only the DB plane, so a runtime-effective key
// in ~/.gbrain/config.json (or env) reported not-found. Resolve the way
@@ -977,6 +986,12 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
process.exit(1);
}
const value = tail.find(a => !a.startsWith('-')) ?? args[2];
+ // #6712 PR 2: a retired sync key is no longer read (warn, write nothing); a rollback key is written with its window.
+ const syncNotice = (await import('../core/sync-config-keys.ts')).syncKeySetNotice(key);
+ if (syncNotice) {
+ for (const line of syncNotice.lines) console.error(line);
+ if (!syncNotice.writes) return;
+ }
// Bootstrap hook-lane keys are FILE-plane canonical: they are read by
// engine-free processes (the harness hook children and the detached
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index 5f2b09464d..b0b77b39c3 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -19,7 +19,7 @@ const SAMPLE_PATHS = 5;
* host-only, so paths never reach a remote caller), and each source's next
* step from the hold router (D6: the frontmatter repair preview, the fence
* repair preview, or both); fails once a source carries more holds than
- * `sync.hold_escalate_count`, the same count rule that escalates a sync result.
+ * `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, the same count rule that escalates a sync result.
* Unsupported-image holds (#5493) are listed but never escalate. With fence
* holds, details carry `fences` and `auto_repair` (whether the maintenance run
* repairs them by itself), which the post-upgrade banner reads.
@@ -56,7 +56,7 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[
return {
name: 'git_held_files', status: escalated.length ? 'fail' : 'warn', details,
message: `${held} file(s) in Git sources are held and not imported; the rest of each sync continues. ${lines.join('; ')}. `
- + (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (sync.hold_escalate_count), so ${stalled * 2 > held
+ + (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (GBRAIN_SYNC_HOLD_ESCALATE_COUNT), so ${stalled * 2 > held
? 'the write owner (not the files) is the likely cause; inspect it with writer status' : 'a generator or an upgrade is likely writing or reading them wrong; fix the cause'} first. ` : '')
+ 'A page whose newer file is held is read-only for put_page until the file is repaired, so do not retry a refused write. '
+ `Inspect with ${sources.map(source => source.status).join('; ')}; `
diff --git a/src/commands/doctor/checks/sync-config-keys.ts b/src/commands/doctor/checks/sync-config-keys.ts
new file mode 100644
index 0000000000..dd62b9c6fa
--- /dev/null
+++ b/src/commands/doctor/checks/sync-config-keys.ts
@@ -0,0 +1,42 @@
+/**
+ * #6712 PR 2 (L3): `sync_config_keys`. A retired `sync.*` key stored on the brain before the upgrade is no longer
+ * read, so a value the user chose silently stopped applying. The check names each one with the value in effect and
+ * the environment variable that replaces it, and lists stored rollback keys with their windows.
+ */
+import type { Check } from '../../doctor.ts';
+import { agentFix } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { RETIRED_SYNC_KEYS, SYNC_ROLLBACK_KEYS, effectiveSyncKey, type RetiredSyncKey } from '../../../core/sync-config-keys.ts';
+import { CONFIG_ROLLBACK_WINDOWS } from '../../../core/wire-skew.ts';
+
+async function runSyncConfigKeys(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ const stored = async (key: string) => engine.getConfig(key).catch(() => null);
+ const unapplied: Array<{ key: string; stored: string; effective: string; replacement: string | null }> = [];
+ for (const retired of Object.values(RETIRED_SYNC_KEYS) as RetiredSyncKey[]) {
+ const value = await stored(retired.key);
+ if (value === null) continue;
+ unapplied.push({ key: retired.key, stored: value, effective: effectiveSyncKey(retired.key, value)!.value, replacement: retired.replacement?.env ?? null });
+ }
+ const rollback: Array<{ key: string; stored: string; honored_until: string }> = [];
+ for (const key of SYNC_ROLLBACK_KEYS) {
+ const value = await stored(key);
+ if (value !== null) rollback.push({ key, stored: value, honored_until: CONFIG_ROLLBACK_WINDOWS[key].honored_until });
+ }
+ const rollbackLine = rollback.length
+ ? ` Rollback keys set on this brain (honored, not tunables): ${rollback.map(row => `${row.key}=${row.stored} (until at least ${row.honored_until})`).join(', ')}.` : '';
+ if (!unapplied.length) {
+ checks.push({ name: 'sync_config_keys', status: 'ok', message: `No retired sync config key is stored on this brain.${rollbackLine}`, details: { unapplied, rollback } });
+ return checks;
+ }
+ checks.push({ name: 'sync_config_keys', status: 'warn', details: { unapplied, rollback },
+ message: `${unapplied.length} retired sync config key(s) are stored but no longer applied: `
+ + unapplied.map(row => `${row.key}=${row.stored} (in effect: ${row.effective}${row.replacement ? `; set ${row.replacement} for the process that syncs to change it` : '; removed, nothing replaces it'})`).join('; ')
+ + `. Ask the user whether to carry each value over to its environment variable, then remove the stored key with gbrain config unset <key>.${rollbackLine}`,
+ fix: agentFix(['gbrain', 'config', 'get', unapplied[0]!.key],
+ 'Prints the value in effect for the first unapplied key and the environment variable that replaces it; read-only.', 'sync_config_keys') });
+ return checks;
+}
+
+export const syncConfigKeysEntry: DoctorEntry = { name: 'sync_config_keys', emits: ['sync_config_keys'], run: runSyncConfigKeys };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 13da7fe1d3..c839c85cd7 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -110,6 +110,7 @@ import { chatFallbackChainEntry } from './checks/chat-fallback.ts';
import { providerConsentEntry } from './checks/provider-consent.ts';
import { behaviorChangesEntry } from './checks/behavior-changes.ts';
import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
+import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';
import { ghostPagesEntry } from './checks/ghost-pages.ts';
import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
@@ -223,6 +224,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
ghostPagesEntry,
missingRecordedFilesEntry,
fenceIntegrityEntry,
+ syncConfigKeysEntry,
searchModeEntry,
];
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 528fd86e68..fd9f7e2ee6 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -127,7 +127,7 @@ export interface SyncResult {
connectorHolds?: { held: number; newly_held: number; retry_command: string; status_command: string };
/**
* #5988 Git holds: files held this run instead of blocking (detail capped at
- * `sync.hold_cap`), their count, the source's outstanding total and the
+ * `GBRAIN_SYNC_HOLD_CAP`), their count, the source's outstanding total and the
* exact inspect and repair commands. Remote callers get `held_count` and
* `holds_fix` (a host-operator relay) only.
*/
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index 7d7613021e..d05022b78a 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -110,10 +110,9 @@ Options:
index up to it.
--no-bulk Managed Postgres sync: publish one page per transaction
instead of bulk groups (each page keeps its own write
- request either way). Persist with
- 'gbrain config set sync.bulk false' or
- GBRAIN_SYNC_BULK=0; tune with sync.bulk_size and
- sync.bulk_max_txn_ms.
+ request either way). GBRAIN_SYNC_BULK=0 does the
+ same for every run of a process; tune the group size
+ with 'gbrain config set sync.bulk_size N'.
--lanes N Managed Postgres sync: publish at most N bulk groups at
once (1-16, default 16, capped by the connection pool:
GBRAIN_POOL_SIZE minus 4). Pages still commit in file
diff --git a/src/core/config.ts b/src/core/config.ts
index 6f595ad036..6dafbca932 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1721,8 +1721,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
'sync.bulk',
'sync.bulk_size',
- 'sync.bulk_max_txn_ms', 'sync.job_drain', // the last: #6706, `false` keeps a managed `sync` job single-pass
- 'sync.lanes', 'sync.waive_batch', 'persistence.single_write_group', 'persistence.preadmit_cache', // the last three: write-path kill switches (persistence/switches.ts)
+ // #6712 PR 2: rollback keys (src/core/sync-config-keys.ts; windows in wire-skew.ts): readable and honored, not tunables.
+ 'sync.job_drain', 'sync.waive_batch', 'sync.foreground_priority',
+ 'sync.lanes', 'persistence.single_write_group', 'persistence.preadmit_cache', // the last two: write-path kill switches (persistence/switches.ts)
// Persisted indexing scope (comma/newline-separated glob list; trailing '/'
// normalizes to a '/**' subtree glob). Read best-effort at the top of
// performSyncInner and UNIONED with any per-call --exclude so internal
@@ -1734,13 +1735,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// include-hidden flag, which bulk sync refuses); registered so `config set` accepts it.
'sync.include_hidden',
// #5988: Git sync holds (read by readSyncHoldPolicy). `sync.holds=fail`
- // restores fail-closed blocking; the rest tune detail, escalation and the
- // parser-regression stop. Registered so the documented `config set` works.
+ // restores fail-closed blocking. Detail, escalation and the parser-regression
+ // stop are tuned by GBRAIN_SYNC_* env since #6712 PR 2 (RETIRED_SYNC_KEYS).
'sync.holds',
- 'sync.hold_cap',
- 'sync.hold_escalate_count',
- 'sync.hold_escalate_pct',
- 'sync.parser_regression',
'fences.normalize', // #6188: inline Tier 1 fence normalization (fence-repair/config.ts); default on
'fences.repair.enabled', 'fences.repair.llm', // #6188: the fence_repair cycle phase and its Tier 3 model step (fence-repair/config.ts); default on
'fences.repair.max_usd_per_page', 'fences.repair.max_usd_per_day', // #6188: Tier 3 fence repair caps; 0 = no model spend
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 85ba5b7973..ebdfaa4bc1 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -368,6 +368,8 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
'schema_pack_source_drift',
'schema_version',
'slug_fallback_audit',
+ // #6712 PR 2: retired sync.* keys stored on the brain and no longer applied.
+ 'sync_config_keys',
'timeline_dedup_index',
'type_proliferation',
'upgrade_errors',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9b579eab25..149b908881 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -359,7 +359,7 @@ export const CODES = {
page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },
parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
- parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `sync.parser_regression=hold` such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed.' },
+ parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `GBRAIN_SYNC_PARSER_REGRESSION=hold` for the process that syncs, such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed.' },
pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },
diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.ts
index 9bcaa23d00..0e17c25af5 100644
--- a/src/core/persistence/connector-status.ts
+++ b/src/core/persistence/connector-status.ts
@@ -4,7 +4,7 @@
* run's counts. Never includes the pinned account or installation id.
*
* #5988: also each Git source's held files (`readGitHoldStatuses`, limited
- * in SQL to `sync.hold_cap`) and the blocked sync requests recent runs
+ * in SQL to `GBRAIN_SYNC_HOLD_CAP`) and the blocked sync requests recent runs
* converted in place, shown beside connector holds. Only `sources status` and `sources retry-held` merge
* the two; `readAllSourceHolds`, `gbrain waiting` and doctor
* `connector_held_items` stay connector-only.
@@ -95,7 +95,7 @@ export function statusSourceNotFound(sourceId: string) {
{ fix: readFix('Lists the registered sources and their ids, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
}
-/** A Git source's held files: the outstanding count and up to `sync.hold_cap` of them in detail. */
+/** A Git source's held files: the outstanding count and up to `GBRAIN_SYNC_HOLD_CAP` of them in detail. */
export interface GitHoldStatus {
count: number;
items: GitHoldItem[];
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
index 9eac7333b2..549a0d952d 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -26,7 +26,7 @@ import { assertDrainLease } from './sync-lease.ts';
/** What sets a drain's lane ceiling: lanes off, the configured maximum, or the connection pool. */
export type LanesCap = 'disabled' | 'maximum' | 'pool';
export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number;
- /** Whether `sync.bulk_max_txn_ms` (or its env) was set; an explicit budget only ever lowers the group budget. */
+ /** Whether `GBRAIN_SYNC_BULK_MAX_TXN_MS` was set; an explicit budget only ever lowers the group budget. */
maxTxnExplicit?: boolean;
/** #5984 lanes: groups published at once (1 = one at a time), and why it is lower than asked when it is. */
lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap;
@@ -43,8 +43,9 @@ async function resolveGrouping(engine: BrainEngine, noBulk: boolean | undefined)
const env = process.env.GBRAIN_SYNC_BULK;
const configured = await engine.getConfig('sync.bulk').catch(() => null);
const size = await whole(engine, 'GBRAIN_SYNC_BULK_SIZE', 'sync.bulk_size', 16, 1, 64);
- const maxTxnMs = await whole(engine, 'GBRAIN_SYNC_BULK_MAX_TXN_MS', 'sync.bulk_max_txn_ms', 15_000, 100, 300_000);
- const maxTxnExplicit = !!process.env.GBRAIN_SYNC_BULK_MAX_TXN_MS || await engine.getConfig('sync.bulk_max_txn_ms').then(v => v != null).catch(() => false);
+ // #6712 PR 2: `sync.bulk_max_txn_ms` retired; only its environment variable tunes the budget (RETIRED_SYNC_KEYS).
+ const maxTxnMs = envWhole('GBRAIN_SYNC_BULK_MAX_TXN_MS', 15_000, 100, 300_000);
+ const maxTxnExplicit = !!process.env.GBRAIN_SYNC_BULK_MAX_TXN_MS?.trim();
const reason = noBulk ? 'disabled by --no-bulk' : env === '0' || env === 'false' ? 'disabled by GBRAIN_SYNC_BULK=0'
: env === undefined || env === '' ? (configured === 'false' || configured === '0' ? 'disabled by config sync.bulk=false' : null) : null;
if (reason) return { enabled: false, reason, size, maxTxnMs, maxTxnExplicit };
@@ -71,6 +72,14 @@ async function resolveLanes(engine: BrainEngine, bulk: BulkSettings, flag: numbe
if (capacity >= asked) return { lanes: asked, lanesMax: asked, lanesReason: null, lanesCap: 'maximum' };
return { lanes: Math.max(1, capacity), lanesMax: asked, lanesReason: `the connection pool holds ${capacity + 3} long transactions; set GBRAIN_POOL_SIZE=${asked + 4} for ${asked} lanes`, lanesCap: 'pool' };
}
+function envWhole(env: string, fallback: number, min: number, max: number): number {
+ const value = process.env[env]?.trim();
+ if (!value) return fallback;
+ const raw = Number(value);
+ if (!Number.isFinite(raw) || raw < min || raw > max) throw new OperationError('invalid_params', `${env} must be a whole number from ${min} to ${max}; got ${value}.`,
+ `Unset ${env} (default ${fallback}) or set it within range, then retry.`);
+ return Math.floor(raw);
+}
async function whole(engine: BrainEngine, env: string, key: string, fallback: number, min: number, max: number): Promise<number> {
const raw = process.env[env] ? Number(process.env[env]) : await engine.getConfig(key).then(v => v == null ? undefined : Number(v)).catch(() => undefined);
if (raw === undefined) return fallback;
@@ -91,8 +100,8 @@ export const FOREGROUND_GROUP_BUDGET_MS = 2_000;
* Adaptive group size: as many members as fit the time budget at the last observed time per member, within
* the configured maximum. The budget is, in order: the first group of a drain is small (2 pages) so its first
* commit lands early; with lanes a group gets `LANE_GROUP_BUDGET_MS` of apply time (`FOREGROUND_GROUP_BUDGET_MS`
- * while a foreground write is queued or just committed), without lanes `sync.bulk_max_txn_ms`; an explicit
- * `sync.bulk_max_txn_ms` only ever lowers it. With lanes the time per member is the lanes' measured apply time
+ * while a foreground write is queued or just committed), without lanes `GBRAIN_SYNC_BULK_MAX_TXN_MS`; an explicit
+ * `GBRAIN_SYNC_BULK_MAX_TXN_MS` only ever lowers it. With lanes the time per member is the lanes' measured apply time
* (transaction begin to the commit-turn wait), which does not grow with how long a group waited in the window;
* without a measurement a group takes the configured size. Foreground writes queued behind a group wait at
* most about this budget (ENG-A5).
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 807836ae38..762af55dfe 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -49,6 +49,7 @@ import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { gitBlobOid, sha256 } from './digest.ts';
import { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';
+import { retiredSyncSetting, type RetiredSyncKeyName } from '../sync-config-keys.ts';
export const GIT_HOLD_OP = 'sync-hold';
export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';
@@ -58,7 +59,7 @@ export const SYNC_IMPORT_PROVENANCE_OP = 'sync-import-provenance';
export const SYNC_CONVERSION_OP = 'sync-conversions';
/** How many conversions the log keeps per source. */
export const SYNC_CONVERSION_KEEP = 20;
-/** Default for `sync.hold_cap`: how many holds a result lists in detail. Storage is never capped. */
+/** Default for `GBRAIN_SYNC_HOLD_CAP`: how many holds a result lists in detail. Storage is never capped. */
export const GIT_HOLD_CAP = 500;
export const GIT_HOLD_ESCALATE_COUNT = 50;
export const GIT_HOLD_ESCALATE_PCT = 5;
@@ -600,7 +601,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
case 'parser_regression':
return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `gbrain refuses ${record.path}, whose exact bytes imported under an earlier version. This is a gbrain bug: report it with the gbrain version, the file and the code, then upgrade or pin the last good version.`,
- why: 'The same bytes imported before, so only gbrain changed; sync holds the file under sync.parser_regression=hold.' };
+ why: 'The same bytes imported before, so only gbrain changed; sync holds the file under GBRAIN_SYNC_PARSER_REGRESSION=hold.' };
case 'rename_held':
return repair(true, `The page that ${record.path} renames changed after the rename was recorded, so it was not moved; the preview proposes re-binding the rename to the current page for approval.`);
case 'frontmatter_slug_conflict':
@@ -701,18 +702,19 @@ export interface SyncHoldPolicy {
parserRegression: 'stop' | 'hold';
}
-export async function readSyncHoldPolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<SyncHoldPolicy> {
- const read = async (key: string) => (await engine.getConfig(key).catch(() => null))?.trim().toLowerCase() || null;
- const number = (value: string | null, fallback: number) => {
- const parsed = value === null ? NaN : Number(value);
+/**
+ * `sync.holds` is the brain's choice (fail-closed or hold). The cap, the escalation thresholds and the
+ * parser-regression stop retired as config keys in #6712 PR 2: their `GBRAIN_SYNC_*` environment variables
+ * (`RETIRED_SYNC_KEYS`) tune them for the process that syncs, and a stored key is not applied.
+ */
+export async function readSyncHoldPolicy(engine: Pick<BrainEngine, 'getConfig'>, env: NodeJS.ProcessEnv = process.env): Promise<SyncHoldPolicy> {
+ const mode = (await engine.getConfig('sync.holds').catch(() => null))?.trim().toLowerCase() || null;
+ const number = (key: RetiredSyncKeyName, fallback: number) => {
+ const parsed = Number(retiredSyncSetting(key, env));
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
};
- // Sequential: five point reads, without widening the caller's connection pool.
- const values: Array<string | null> = [];
- for (const key of ['sync.holds', 'sync.hold_cap', 'sync.hold_escalate_count', 'sync.hold_escalate_pct', 'sync.parser_regression']) values.push(await read(key));
- const [mode, cap, count, pct, regression] = values;
- return { mode: mode === 'fail' ? 'fail' : 'hold', cap: Math.floor(number(cap, GIT_HOLD_CAP)), escalateCount: number(count, GIT_HOLD_ESCALATE_COUNT),
- escalatePct: number(pct, GIT_HOLD_ESCALATE_PCT), parserRegression: regression === 'hold' ? 'hold' : 'stop' };
+ return { mode: mode === 'fail' ? 'fail' : 'hold', cap: Math.floor(number('sync.hold_cap', GIT_HOLD_CAP)), escalateCount: number('sync.hold_escalate_count', GIT_HOLD_ESCALATE_COUNT),
+ escalatePct: number('sync.hold_escalate_pct', GIT_HOLD_ESCALATE_PCT), parserRegression: retiredSyncSetting('sync.parser_regression', env).toLowerCase() === 'hold' ? 'hold' : 'stop' };
}
/** More holds than the source should carry, or too large a share of this run's screened imports. */
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 6d9482fb48..ef3da43f4a 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -241,10 +241,10 @@ export async function screenFrozenImport(engine: BrainEngine, input: FrozenImpor
const provenance = await readSyncImportProvenance(engine, input.cursor.sourceId, input.cursor.incarnation, snapshot.page.id);
if (provenance?.validated === true && provenance.raw_sha256 === sha256(content) && provenance.origin === entry.sourcePath) {
const why = `gbrain ${VERSION} refuses ${entry.path} (${refusal.reason ?? 'yaml_parse'}${refusal.line !== undefined ? `, line ${refusal.line}` : ''}), but gbrain ${provenance.gbrain_version} imported these exact bytes and validated them.`;
- if (run.policy.parserRegression === 'hold') return heldEntry(entry, slug, pageId, { code: 'parser_regression', message: `${why} Held under sync.parser_regression=hold.` }, content, blob);
+ if (run.policy.parserRegression === 'hold') return heldEntry(entry, slug, pageId, { code: 'parser_regression', message: `${why} Held under GBRAIN_SYNC_PARSER_REGRESSION=hold.` }, content, blob);
throw opError('sync_parser_regression', `Sync stopped: ${why}`,
`This is a gbrain bug. Report it with the gbrain version (${VERSION}), the file (${entry.path}) and the code (${refusal.code}${refusal.reason ? `/${refusal.reason}` : ''}). `
- + `Upgrade, or pin the last good version (${provenance.gbrain_version}), then run: ${input.retryCommand}. To hold such files and let the rest sync meanwhile, the user can set sync.parser_regression=hold.`,
+ + `Upgrade, or pin the last good version (${provenance.gbrain_version}), then run: ${input.retryCommand}. To hold such files and let the rest sync meanwhile, the user can set GBRAIN_SYNC_PARSER_REGRESSION=hold for the process that syncs.`,
{ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
why: 'Collects the gbrain version and brain health to attach to the bug report; the sync checkpoint did not advance past this file.' } });
}
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
new file mode 100644
index 0000000000..3f7f722970
--- /dev/null
+++ b/src/core/sync-config-keys.ts
@@ -0,0 +1,117 @@
+/**
+ * #6712 PR 2 (L3): the `sync.*` config keys in three kinds.
+ *
+ * - Tunables: user intent a brain keeps (`config set` writes them, every sync reads them).
+ * - Rollback keys: a published notice or migration names them as the way back from a default
+ * (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts` holds each one's window). They stay readable and honored,
+ * but they are not tunables: `config set` says so, and help text and printed fixes never recommend them.
+ * - Retired keys: no longer read. Each names its replacement (a `GBRAIN_SYNC_*` environment variable read by the
+ * process that syncs, or nothing when the behavior itself was removed). `config set` warns and writes nothing,
+ * `config get` prints the value in effect and where it comes from, and doctor (`sync_config_keys`) reports a value
+ * stored before the upgrade as unapplied.
+ */
+import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';
+
+export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',
+ 'sync.write_through', 'sync.cost_gate_min_usd'] as const;
+
+export interface RetiredSyncKey {
+ key: string;
+ retired_in: string;
+ /** What the key tuned, in the words `config get` and doctor print. */
+ tuned: string;
+ /** The environment variable that replaces it and the value in effect without one; null when the behavior was removed. */
+ replacement: { env: string; default: string } | null;
+}
+
+export const RETIRED_SYNC_KEYS = {
+ 'sync.bulk_max_txn_ms': { key: 'sync.bulk_max_txn_ms', retired_in: '0.60.256.0', tuned: 'the target time of one bulk group without lanes, in ms',
+ replacement: { env: 'GBRAIN_SYNC_BULK_MAX_TXN_MS', default: '15000' } },
+ 'sync.hold_cap': { key: 'sync.hold_cap', retired_in: '0.60.256.0', tuned: 'how many held files a sync result lists in detail',
+ replacement: { env: 'GBRAIN_SYNC_HOLD_CAP', default: '500' } },
+ 'sync.hold_escalate_count': { key: 'sync.hold_escalate_count', retired_in: '0.60.256.0', tuned: 'the held-file count above which a source escalates',
+ replacement: { env: 'GBRAIN_SYNC_HOLD_ESCALATE_COUNT', default: '50' } },
+ 'sync.hold_escalate_pct': { key: 'sync.hold_escalate_pct', retired_in: '0.60.256.0', tuned: 'the share of a run\'s screened imports above which it escalates, in percent',
+ replacement: { env: 'GBRAIN_SYNC_HOLD_ESCALATE_PCT', default: '5' } },
+ 'sync.parser_regression': { key: 'sync.parser_regression', retired_in: '0.60.256.0', tuned: 'whether sync stops (stop) or holds the file (hold) when bytes that imported before are refused',
+ replacement: { env: 'GBRAIN_SYNC_PARSER_REGRESSION', default: 'stop' } },
+ 'sync.knock_on_refreeze_limit': { key: 'sync.knock_on_refreeze_limit', retired_in: '0.60.255.0', tuned: 'the knock-on re-freeze budget', replacement: null },
+ 'sync.knock_on_run_limit': { key: 'sync.knock_on_run_limit', retired_in: '0.60.255.0', tuned: 'the knock-on re-freeze budget per run', replacement: null },
+} as const satisfies Record<string, RetiredSyncKey>;
+
+export type RetiredSyncKeyName = keyof typeof RETIRED_SYNC_KEYS;
+export const SYNC_ROLLBACK_KEYS = Object.keys(CONFIG_ROLLBACK_WINDOWS) as Array<keyof typeof CONFIG_ROLLBACK_WINDOWS>;
+
+export function retiredSyncKey(key: string): RetiredSyncKey | null {
+ return (RETIRED_SYNC_KEYS as Record<string, RetiredSyncKey>)[key] ?? null;
+}
+export function rollbackSyncKey(key: string): ConfigRollbackWindow | null {
+ return (CONFIG_ROLLBACK_WINDOWS as Record<string, ConfigRollbackWindow>)[key] ?? null;
+}
+
+/** The value a retired key's replacement puts in effect: its environment variable, else the built-in default. */
+export function retiredSyncSetting(key: RetiredSyncKeyName, env: NodeJS.ProcessEnv = process.env): string {
+ const replacement = (RETIRED_SYNC_KEYS[key] as RetiredSyncKey).replacement!;
+ const value = env[replacement.env]?.trim();
+ return value ? value : replacement.default;
+}
+
+const isOff = (value: string | null | undefined) => typeof value === 'string' && /^(0|false)$/i.test(value.trim());
+const isOn = (value: string | null | undefined) => typeof value === 'string' && /^(1|true)$/i.test(value.trim());
+const exactOff = (value: string) => value === '0' || value === 'false';
+
+/** How each rollback key resolves at runtime (the readers' own rules), so `config get` reports what a sync does. */
+const ROLLBACK_RESOLVERS: Record<keyof typeof CONFIG_ROLLBACK_WINDOWS, { env?: string; resolve: (stored: string | null, envValue: string | undefined) => { on: boolean; from: 'env' | 'config' | 'default' } }> = {
+ // sync-group.ts resolveGrouping: a non-empty env wins; `0`/`false` exactly turn it off.
+ 'sync.bulk': { env: 'GBRAIN_SYNC_BULK', resolve: (stored, envValue) => envValue ? { on: !exactOff(envValue), from: 'env' } : stored !== null ? { on: !exactOff(stored), from: 'config' } : { on: true, from: 'default' } },
+ // sync-waivers.ts waiverBatchEnabled: env ?? config; `0`/`false` exactly turn it off.
+ 'sync.waive_batch': { env: 'GBRAIN_SYNC_WAIVE_BATCH', resolve: (stored, envValue) => envValue !== undefined ? { on: !exactOff(envValue), from: 'env' } : stored !== null ? { on: !exactOff(stored), from: 'config' } : { on: true, from: 'default' } },
+ // persistence/switches.ts: env `0|false|1|true` (any case) wins, else config, else on.
+ 'sync.foreground_priority': { env: 'GBRAIN_SYNC_FOREGROUND_PRIORITY', resolve: (stored, envValue) => isOff(envValue) || isOn(envValue) ? { on: isOn(envValue), from: 'env' }
+ : stored !== null ? { on: !isOff(stored), from: 'config' } : { on: true, from: 'default' } },
+ // feature-flags.ts and handlers/sync-job-drain.ts: exactly `false` turns it off.
+ 'sync.federated_v2': { resolve: stored => stored !== null ? { on: stored !== 'false', from: 'config' } : { on: true, from: 'default' } },
+ 'sync.job_drain': { resolve: stored => stored !== null ? { on: stored !== 'false', from: 'config' } : { on: true, from: 'default' } },
+};
+
+export interface EffectiveSyncKey {
+ /** The value a sync runs with (stdout of `config get`). */
+ value: string;
+ /** Where it comes from, one line (stderr of `config get`). */
+ origin: string;
+}
+
+/** The value in effect for a retired or rollback key and where it comes from; null for any other key. */
+export function effectiveSyncKey(key: string, stored: string | null, env: NodeJS.ProcessEnv = process.env): EffectiveSyncKey | null {
+ const retired = retiredSyncKey(key);
+ if (retired) {
+ const unapplied = stored !== null ? ` The stored ${key}=${stored} is not applied.` : '';
+ if (!retired.replacement) return { value: 'removed', origin: `${key} was retired in ${retired.retired_in} with ${retired.tuned}; nothing replaces it.${unapplied}` };
+ const fromEnv = env[retired.replacement.env]?.trim();
+ return { value: fromEnv || retired.replacement.default,
+ origin: `${fromEnv ? `environment ${retired.replacement.env}` : `built-in default (${retired.replacement.env} unset)`}: ${key} was retired in ${retired.retired_in}; `
+ + `set ${retired.replacement.env} for the process that syncs to change ${retired.tuned}.${unapplied}` };
+ }
+ const window = rollbackSyncKey(key);
+ if (!window) return null;
+ const resolver = ROLLBACK_RESOLVERS[key as keyof typeof CONFIG_ROLLBACK_WINDOWS];
+ const { on, from } = resolver.resolve(stored, resolver.env ? env[resolver.env] : undefined);
+ const where = from === 'env' ? `environment ${resolver.env}` : from === 'config' ? 'brain config' : 'default';
+ return { value: String(on), origin: `${where}: ${key} is a rollback key, not a tunable; false restores ${window.restores}. Honored until at least ${window.honored_until} (named in ${window.named_in}).` };
+}
+
+/** The `config set` warning for a retired or rollback key (null for any other key); `writes` says whether the value is stored. */
+export function syncKeySetNotice(key: string): { writes: boolean; lines: string[] } | null {
+ const retired = retiredSyncKey(key);
+ if (retired) return { writes: false, lines: [
+ `[config] WARN: ${key} was retired in ${retired.retired_in} and is no longer read; nothing was written.`,
+ retired.replacement
+ ? `[config] To change ${retired.tuned}, set ${retired.replacement.env}=<value> in the environment of the process that syncs (the serve, the cron line or the shell); default ${retired.replacement.default}.`
+ : `[config] ${retired.tuned} was removed with the behavior it tuned; nothing replaces it.`,
+ ] };
+ const window = rollbackSyncKey(key);
+ if (window) return { writes: true, lines: [
+ `[config] note: ${key} is a rollback key, not a tunable: false restores ${window.restores}. It is honored until at least ${window.honored_until} (named in ${window.named_in}); after that a release may stop reading it.`,
+ ] };
+ return null;
+}
diff --git a/test/doctor-frontmatter-holds.test.ts b/test/doctor-frontmatter-holds.test.ts
index 76b608f246..42b5492307 100644
--- a/test/doctor-frontmatter-holds.test.ts
+++ b/test/doctor-frontmatter-holds.test.ts
@@ -78,7 +78,7 @@ async function each(run: (engine: BrainEngine) => Promise<void>) {
try { await run(engine); }
finally {
await disposePersistenceConsumer(engine);
- for (const key of ['sync.holds', 'sync.hold_escalate_count']) await engine.unsetConfig(key);
+ await engine.unsetConfig('sync.holds');
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
await engine.executeRaw("UPDATE sources SET local_path=NULL WHERE id LIKE 'fmh-%'");
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op LIKE 'sync-hold%' OR op LIKE 'managed-sync%'");
@@ -166,8 +166,7 @@ test('holds and repairable files: the plan says explicit_kind_required with the
expect(banner).toContain(`[AGENT] git_held_files: 2 (explicit_kind_required; preview with: ${preview})`);
expect(banner).not.toMatch(/--apply|--yes/);
- await engine.setConfig('sync.hold_escalate_count', '1');
- const escalated = await gitHeldFilesCheck(engine);
+ const escalated = await withEnv({ GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '1' }, () => gitHeldFilesCheck(engine));
expect(escalated.status).toBe('fail');
expect(escalated.message).toContain(`Escalated: ${s.id} hold more than 1 files`);
}), 240_000);
diff --git a/test/error-registry-retired.test.ts b/test/error-registry-retired.test.ts
index 4d531babd7..3104b27736 100644
--- a/test/error-registry-retired.test.ts
+++ b/test/error-registry-retired.test.ts
@@ -6,6 +6,9 @@
* Protects: no registered fix, suggestion, `why`, fault-table reason or terminal-classifier action names a retired
* config key; every `--flag` a registered fix argv passes to `gbrain` is a flag that command still accepts; a retired
* code's fix is read-only and needs no consent; the retired keys are no longer accepted by `config set`.
+ * #6712 PR 2 extends it to the sync config-key table: no source line outside the table and the historical behavior
+ * notices names a retired key (help text, doctor messages, hold reasons and refusals included), and `gbrain sync --help`
+ * and `gbrain config --help` name neither a retired key nor a rollback key (rollback keys are not tunables).
*/
import { expect, test } from 'bun:test';
import { CODES, NOTICE_CODES, type CodeEntry } from '../src/core/error-registry.ts';
@@ -14,9 +17,12 @@ import { SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';
import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';
import { knockOnDetail } from '../src/core/persistence/sync-knock-on.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { RETIRED_SYNC_KEYS, SYNC_ROLLBACK_KEYS } from '../src/core/sync-config-keys.ts';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
-/** Config keys and CLI flags a release deleted; a printed fix must never name them. Add to this list when retiring one. */
-const RETIRED_KEYS = ['sync.knock_on_refreeze_limit', 'sync.knock_on_run_limit'];
+/** Config keys a release retired (src/core/sync-config-keys.ts); a printed fix must never name them. Retire a key there. */
+const RETIRED_KEYS = Object.keys(RETIRED_SYNC_KEYS);
const entries = (registry: Record<string, unknown>) => Object.entries(registry) as Array<[string, CodeEntry]>;
const fixText = (entry: CodeEntry) => [entry.suggestion, entry.why, ...(entry.fix ? [(entry.fix.argv ?? []).join(' '), entry.fix.why] : [])].filter(Boolean).join('\n');
@@ -63,3 +69,38 @@ test('a retired code renders superseded: its fix is read-only, needs no consent,
}
expect(CODES.knock_on_exhausted.suggestion).toContain('gbrain sync --source <id> --no-pull');
});
+
+const sourceFiles = (dir: string): string[] => readdirSync(dir).flatMap(name => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];
+});
+
+test('no source line outside the key table and the historical notices names a retired config key', () => {
+ // The table defines them; behavior-change-notice keeps the rows older brains are shown on upgrade.
+ const allowed = new Set(['src/core/sync-config-keys.ts', 'src/core/behavior-change-notice.ts']);
+ const named: string[] = [];
+ for (const file of sourceFiles('src').filter(path => !allowed.has(path))) {
+ readFileSync(file, 'utf8').split('\n').forEach((line, i) => {
+ const code = line.trim();
+ if (code.startsWith('//') || code.startsWith('*') || code.startsWith('/*')) return;
+ // A typed lookup of the retired key's replacement (sync-holds.ts) names the key as data, never as advice.
+ const text = line.replace(/\b(?:retiredSyncSetting|number)\('sync\.[a-z_]+'/g, '');
+ for (const key of RETIRED_KEYS) if (new RegExp(`\\b${key.replace('.', '\\.')}\\b`).test(text)) named.push(`${file}:${i + 1} names ${key}`);
+ });
+ }
+ expect(named).toEqual([]);
+});
+
+test('sync and config help name no retired key and no rollback key', async () => {
+ const captured: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { captured.push(parts.join(' ')); };
+ try {
+ (await import('../src/commands/sync/args.ts')).printSyncHelp();
+ (await import('../src/commands/config.ts')).printUsage();
+ } finally { console.log = log; }
+ const help = captured.join('\n');
+ expect(help).toContain('--no-bulk');
+ const named = [...RETIRED_KEYS, ...SYNC_ROLLBACK_KEYS].filter(key => new RegExp(`\\b${key.replace('.', '\\.')}\\b`).test(help));
+ expect(named).toEqual([]);
+});
diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.ts
index 263c699f06..5f3079844e 100644
--- a/test/managed-sync-preparation-stalled-holds.test.ts
+++ b/test/managed-sync-preparation-stalled-holds.test.ts
@@ -453,9 +453,8 @@ test('breaker: five consecutive stalled entries with no commit between stop the
expect(await s.holds()).toEqual([]);
}), 240_000);
-test('breaker: the count rule trips above sync.hold_escalate_count (greater than), and a committed page resets the consecutive streak', () => each(async engine => {
- await engine.setConfig('sync.hold_escalate_count', '2');
- try {
+test('breaker: the count rule trips above GBRAIN_SYNC_HOLD_ESCALATE_COUNT (greater than), and a committed page resets the consecutive streak', () => each(async engine => {
+ await withEnv({ GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '2' }, async () => {
const files: Record<string, string> = {};
for (let i = 0; i < 4; i++) files[`notes/s${i}.md`] = note(`S${i}`);
const s = await source(engine, files);
@@ -463,7 +462,7 @@ test('breaker: the count rule trips above sync.hold_escalate_count (greater than
const tripped = await s.sync();
expect(tripped).toMatchObject({ status: 'blocked_by_failures', breaker: { rule: 'count', stalled: 3, consecutive: 3 } });
expect(await s.holds()).toHaveLength(2);
- } finally { await engine.unsetConfig('sync.hold_escalate_count'); }
+ });
// Streak: four stalled, one committed, four stalled: eight holds and no trip.
const files: Record<string, string> = { 'notes/m-ok.md': note('Ok') };
for (let i = 0; i < 4; i++) { files[`notes/a${i}.md`] = note(`A${i}`); files[`notes/z${i}.md`] = note(`Z${i}`); }
diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.ts
index 705fc6b1cc..94041e1b4d 100644
--- a/test/persistence-sync-holds.test.ts
+++ b/test/persistence-sync-holds.test.ts
@@ -69,7 +69,7 @@ async function each(run: (engine: BrainEngine) => Promise<void>) {
await withEnv(env, async () => {
for (const engine of engines) {
try { await run(engine); }
- finally { await disposePersistenceConsumer(engine); for (const key of ['sync.holds', 'sync.parser_regression', 'sync.hold_escalate_count']) await engine.unsetConfig(key); }
+ finally { await disposePersistenceConsumer(engine); for (const key of ['sync.holds', 'sync.parser_regression']) await engine.unsetConfig(key); }
}
});
}
@@ -330,13 +330,16 @@ test('parser regression: stops only when provenance proves the same bytes import
const head = await s.lastCommit();
await expect(s.sync()).rejects.toMatchObject({ code: 'sync_parser_regression' });
expect(await s.lastCommit()).toBe(head);
+ // #6712 PR 2: a stored sync.parser_regression (retired) is not applied; the process's GBRAIN_SYNC_PARSER_REGRESSION is.
await engine.setConfig('sync.parser_regression', 'hold');
- const held = await s.sync({ retryFailed: true });
+ await expect(s.sync({ retryFailed: true })).rejects.toMatchObject({ code: 'sync_parser_regression' });
+ expect(await s.lastCommit()).toBe(head);
+ await engine.unsetConfig('sync.parser_regression');
+ const held = await withEnv({ GBRAIN_SYNC_PARSER_REGRESSION: 'hold' }, () => s.sync({ retryFailed: true }));
expect(held.held?.[0]).toMatchObject({ path: 'notes/a.md', code: 'parser_regression' });
expect(await s.lastCommit()).not.toBe(head);
// A page without provenance (imported before validation) is held normally on a full walk, never a stop.
- await engine.unsetConfig('sync.parser_regression');
const t = await source(engine, { 'notes/b.md': note('B') });
await t.sync();
await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [SYNC_IMPORT_PROVENANCE_OP, `${t.id}:%`]);
@@ -345,8 +348,7 @@ test('parser regression: stops only when provenance proves the same bytes import
expect(full.held?.[0]).toMatchObject({ path: 'notes/b.md', code: 'invalid_frontmatter', stale: true });
}), 240_000);
-test('escalation flags a source past its threshold; sync.holds=fail restores blocking; retry-held re-screens an unchanged hold', () => each(async engine => {
- await engine.setConfig('sync.hold_escalate_count', '1');
+test('escalation flags a source past its threshold; sync.holds=fail restores blocking; retry-held re-screens an unchanged hold', () => each(async engine => withEnv({ GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '1' }, async () => {
const s = await source(engine, { 'notes/a.md': FOLDED, 'notes/b.md': FOLDED, 'notes/ok.md': note('Ok') });
const result = await s.sync();
expect(result).toMatchObject({ held_count: 2, holds_escalated: true });
@@ -363,7 +365,7 @@ test('escalation flags a source past its threshold; sync.holds=fail restores blo
const t = await source(engine, { 'notes/a.md': FOLDED });
expect((await t.sync()).status).toBe('blocked_by_failures');
expect(await t.holds()).toEqual([]);
-}), 240_000);
+})), 240_000);
test('files imported by quoting are counted with their common directory', () => each(async engine => {
const s = await source(engine, { 'tweets/2026/one.md': AUTHOR, 'tweets/2026/two.md': AUTHOR.replace('Payments roundup', 'Second roundup') });
diff --git a/test/sync-config-keys-6712.test.ts b/test/sync-config-keys-6712.test.ts
new file mode 100644
index 0000000000..cad34a5865
--- /dev/null
+++ b/test/sync-config-keys-6712.test.ts
@@ -0,0 +1,150 @@
+/**
+ * #6712 PR 2 (L3): the `sync.*` keys in three kinds (src/core/sync-config-keys.ts).
+ *
+ * Protects:
+ * - `config set` of a retired key warns, names its GBRAIN_SYNC_* replacement and writes nothing (exit 0, not a refusal);
+ * - `config get` of a retired key prints the value a sync runs with (env, else the built-in default) and says a
+ * stored value is not applied; the readers really ignore the stored key;
+ * - a rollback key is written with a note naming its window, and `config get` prints the value in effect and
+ * where it comes from; `sync.foreground_priority` (named as the way back since 0.60.111.0) is accepted without
+ * --force, where it used to be refused as an unknown key;
+ * - `config get`'s resolution of each rollback key agrees with the reader the sync uses;
+ * - doctor `sync_config_keys` reports a stored retired key as unapplied, with the value in effect and its env.
+ */
+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runConfig } from '../src/commands/config.ts';
+import { RETIRED_SYNC_KEYS, SYNC_ROLLBACK_KEYS, SYNC_TUNABLE_KEYS, effectiveSyncKey } from '../src/core/sync-config-keys.ts';
+import { CONFIG_ROLLBACK_WINDOWS } from '../src/core/wire-skew.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { GIT_HOLD_CAP, GIT_HOLD_ESCALATE_COUNT, GIT_HOLD_ESCALATE_PCT, readSyncHoldPolicy } from '../src/core/persistence/sync-holds.ts';
+import { resolveBulkSettings } from '../src/core/persistence/sync-group.ts';
+import { waiverBatchEnabled } from '../src/core/persistence/sync-waivers.ts';
+import { isFederatedV2Enabled } from '../src/core/feature-flags.ts';
+import { readWriteSwitches, resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { syncConfigKeysEntry } from '../src/commands/doctor/checks/sync-config-keys.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const KEYS = [...Object.keys(RETIRED_SYNC_KEYS), ...SYNC_ROLLBACK_KEYS];
+const CLEAR = { GBRAIN_SYNC_HOLD_CAP: undefined, GBRAIN_SYNC_HOLD_ESCALATE_COUNT: undefined, GBRAIN_SYNC_HOLD_ESCALATE_PCT: undefined, GBRAIN_SYNC_PARSER_REGRESSION: undefined,
+ GBRAIN_SYNC_BULK_MAX_TXN_MS: undefined, GBRAIN_SYNC_BULK: undefined, GBRAIN_SYNC_WAIVE_BATCH: undefined, GBRAIN_SYNC_FOREGROUND_PRIORITY: undefined };
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { for (const key of KEYS) await engine.unsetConfig(key); });
+
+async function config(args: string[]) {
+ const logs: string[] = [], errs: string[] = [];
+ let exit: number | null = null;
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);
+ try { await runConfig(engine, args); }
+ catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; }
+ finally { logSpy.mockRestore(); errSpy.mockRestore(); exitSpy.mockRestore(); }
+ return { out: logs.join('\n'), err: errs.join('\n'), exit: exit as number | null };
+}
+
+test('the three kinds are disjoint; tunables and rollback keys are registered, retired keys are not; defaults match the readers', () => {
+ const retired = Object.keys(RETIRED_SYNC_KEYS);
+ for (const key of SYNC_TUNABLE_KEYS) { expect(KNOWN_CONFIG_KEYS).toContain(key); expect(retired).not.toContain(key); expect(SYNC_ROLLBACK_KEYS as string[]).not.toContain(key); }
+ for (const key of SYNC_ROLLBACK_KEYS) { expect(KNOWN_CONFIG_KEYS).toContain(key); expect(retired).not.toContain(key); }
+ for (const key of retired) expect(KNOWN_CONFIG_KEYS).not.toContain(key);
+ expect(RETIRED_SYNC_KEYS['sync.hold_cap'].replacement.default).toBe(String(GIT_HOLD_CAP));
+ expect(RETIRED_SYNC_KEYS['sync.hold_escalate_count'].replacement.default).toBe(String(GIT_HOLD_ESCALATE_COUNT));
+ expect(RETIRED_SYNC_KEYS['sync.hold_escalate_pct'].replacement.default).toBe(String(GIT_HOLD_ESCALATE_PCT));
+ for (const window of Object.values(CONFIG_ROLLBACK_WINDOWS)) {
+ expect(window.honored_until).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect(window.floor).toMatch(/^\d+\.\d+\.\d+\.\d+$/);
+ }
+});
+
+test('config set of a retired key warns, names its replacement and writes nothing', async () => withEnv(CLEAR, async () => {
+ const set = await config(['set', 'sync.hold_cap', '200']);
+ expect(set.exit).toBeNull();
+ expect(set.err).toContain('sync.hold_cap was retired in 0.60.256.0');
+ expect(set.err).toContain('GBRAIN_SYNC_HOLD_CAP=<value>');
+ expect(set.err).toContain('nothing was written');
+ expect(await engine.getConfig('sync.hold_cap')).toBeNull();
+ const removed = await config(['set', 'sync.knock_on_run_limit', '5']);
+ expect(removed.exit).toBeNull();
+ expect(removed.err).toContain('nothing replaces it');
+ expect(await engine.getConfig('sync.knock_on_run_limit')).toBeNull();
+}));
+
+test('config get of a retired key prints the value in effect, and a stored value is reported and not applied', async () => withEnv(CLEAR, async () => {
+ await engine.setConfig('sync.hold_cap', '200');
+ await engine.setConfig('sync.parser_regression', 'hold');
+ const got = await config(['get', 'sync.hold_cap']);
+ expect(got.out).toBe('500');
+ expect(got.err).toContain('built-in default (GBRAIN_SYNC_HOLD_CAP unset)');
+ expect(got.err).toContain('The stored sync.hold_cap=200 is not applied.');
+ expect(await readSyncHoldPolicy(engine)).toMatchObject({ cap: 500, parserRegression: 'stop' });
+ await withEnv({ GBRAIN_SYNC_HOLD_CAP: '7' }, async () => {
+ const env = await config(['get', 'sync.hold_cap']);
+ expect(env.out).toBe('7');
+ expect(env.err).toContain('environment GBRAIN_SYNC_HOLD_CAP');
+ expect((await readSyncHoldPolicy(engine)).cap).toBe(7);
+ });
+ await engine.setConfig('sync.bulk_max_txn_ms', '100');
+ const settings = await resolveBulkSettings(engine, false);
+ expect({ maxTxnMs: settings.maxTxnMs, explicit: settings.maxTxnExplicit }).toEqual({ maxTxnMs: 15_000, explicit: false });
+}));
+
+test('a rollback key is written with its window; get prints the value in effect and where it comes from', async () => withEnv(CLEAR, async () => {
+ const set = await config(['set', 'sync.bulk', 'false']);
+ expect(set.exit).toBeNull();
+ expect(set.err).toContain('sync.bulk is a rollback key, not a tunable');
+ expect(set.err).toContain(CONFIG_ROLLBACK_WINDOWS['sync.bulk'].honored_until);
+ expect(await engine.getConfig('sync.bulk')).toBe('false');
+ const got = await config(['get', 'sync.bulk']);
+ expect(got.out).toBe('false');
+ expect(got.err).toContain('brain config: sync.bulk is a rollback key');
+ await withEnv({ GBRAIN_SYNC_BULK: '1' }, async () => {
+ const env = await config(['get', 'sync.bulk']);
+ expect(env.out).toBe('true');
+ expect(env.err).toContain('environment GBRAIN_SYNC_BULK');
+ });
+ const unset = await config(['get', 'sync.job_drain']);
+ expect(unset).toMatchObject({ out: 'true', exit: null });
+ expect(unset.err).toContain('default: sync.job_drain is a rollback key');
+}));
+
+test('sync.foreground_priority is accepted without --force (it used to be refused as an unknown key)', async () => withEnv(CLEAR, async () => {
+ const set = await config(['set', 'sync.foreground_priority', 'false']);
+ expect(set.exit).toBeNull();
+ expect(await engine.getConfig('sync.foreground_priority')).toBe('false');
+ resetWriteSwitches();
+ expect((await readWriteSwitches(engine)).foreground_priority).toBe(false);
+}));
+
+test('config get resolves every rollback key the way its reader does', async () => {
+ const cases: Array<[string | null, string | undefined]> = [[null, undefined], ['false', undefined], ['0', undefined], ['true', undefined], ['FALSE', undefined],
+ [null, '0'], [null, 'false'], [null, '1'], ['false', '1'], ['true', '0'], [null, '']];
+ for (const [stored, envValue] of cases) {
+ for (const key of SYNC_ROLLBACK_KEYS) { if (stored === null) await engine.unsetConfig(key); else await engine.setConfig(key, stored); }
+ await withEnv({ ...CLEAR, GBRAIN_SYNC_BULK: envValue, GBRAIN_SYNC_WAIVE_BATCH: envValue, GBRAIN_SYNC_FOREGROUND_PRIORITY: envValue }, async () => {
+ const said = (key: string) => effectiveSyncKey(key, stored)!.value === 'true';
+ const bulk = await resolveBulkSettings(engine, false);
+ // PGLite turns bulk off for its own reason; only an explicit off is the key's.
+ expect(said('sync.bulk')).toBe(!(bulk.reason && /GBRAIN_SYNC_BULK|sync\.bulk/.test(bulk.reason)));
+ expect(said('sync.waive_batch')).toBe(await waiverBatchEnabled(engine));
+ expect(said('sync.federated_v2')).toBe(await isFederatedV2Enabled(engine));
+ resetWriteSwitches();
+ expect(said('sync.foreground_priority')).toBe((await readWriteSwitches(engine)).foreground_priority);
+ expect(said('sync.job_drain')).toBe(stored !== 'false');
+ });
+ }
+});
+
+test('doctor sync_config_keys reports a stored retired key as unapplied, and is ok without one', async () => withEnv(CLEAR, async () => {
+ const ctx = { engine, progress: { heartbeat: () => {} } } as never;
+ const clean = await syncConfigKeysEntry.run(ctx);
+ expect(clean).toMatchObject([{ name: 'sync_config_keys', status: 'ok' }]);
+ await engine.setConfig('sync.hold_escalate_count', '10');
+ await engine.setConfig('sync.waive_batch', 'false');
+ const [check] = await syncConfigKeysEntry.run(ctx);
+ expect(check).toMatchObject({ name: 'sync_config_keys', status: 'warn', fix: { argv: ['gbrain', 'config', 'get', 'sync.hold_escalate_count'], actor: 'agent' } });
+ expect(check!.message).toContain('sync.hold_escalate_count=10 (in effect: 50; set GBRAIN_SYNC_HOLD_ESCALATE_COUNT');
+ expect(check!.message).toContain('sync.waive_batch=false (until at least');
+}));
diff --git a/test/sync-flag-table-6712.test.ts b/test/sync-flag-table-6712.test.ts
index 1b21f246db..8e275c1178 100644
--- a/test/sync-flag-table-6712.test.ts
+++ b/test/sync-flag-table-6712.test.ts
@@ -116,7 +116,7 @@ test('a newer CLI never sends a retired field to the serve, whatever its options
const received: Array<Record<string, unknown>> = [];
const server = await startResolveIpcServer(sock, {
resolve: async () => null,
- sync_start: req => { received.push(req.options as Record<string, unknown>); return { ok: false, protocol: 2, error: 'shutting_down' }; },
+ sync_start: (req: { options: unknown }) => { received.push(req.options as Record<string, unknown>); return { ok: false, protocol: 2, error: 'shutting_down' }; },
sync_status: () => ({ ok: false, protocol: 2, error: 'unknown_job' }),
sync_abort: () => ({ ok: true, protocol: 2 as const }),
} as never, { secret });
diff --git a/test/sync-hold-surfaces.test.ts b/test/sync-hold-surfaces.test.ts
index 8c7b7e5893..d9772f8e0a 100644
--- a/test/sync-hold-surfaces.test.ts
+++ b/test/sync-hold-surfaces.test.ts
@@ -50,6 +50,7 @@ import { operations, type OperationContext } from '../src/core/operations.ts';
import { cliRenderContext, renderAction, type Action } from '../src/core/agent-output.ts';
import { fenceMessage } from '../src/core/fence-repair/reasons.ts';
import { RECOVERY_VERSION } from '../src/core/markdown.ts';
+import { withEnv } from './helpers/with-env.ts';
type HoldInput = Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'>;
@@ -124,18 +125,17 @@ describe('sources status and retry-held on Git sources', () => {
expect(text).not.toContain('other-git');
});
- test('sources status lists at most sync.hold_cap holds per source, limited in SQL, with the outstanding count from the summary row', async () => {
+ test('sources status lists at most GBRAIN_SYNC_HOLD_CAP holds per source, limited in SQL, with the outstanding count from the summary row', async () => {
const listing = await readGitHoldListing(engine, ['notes-git', 'other-git', 'default'], 1);
expect(listing.map(source => [source.sourceId, source.count, source.holds.map(record => record.path)])).toEqual([
['notes-git', 2, ['notes/huge.md']], ['other-git', 1, ['other/a.md']]]);
- await engine.setConfig('sync.hold_cap', '1');
- try {
+ await withEnv({ GBRAIN_SYNC_HOLD_CAP: '1' }, async () => {
const doc = JSON.parse(await captured(() => runSources(engine, ['status', 'notes-git', '--json'])));
expect(doc.sources[0].git_holds).toMatchObject({ count: 2, truncated: true });
expect(doc.sources[0].git_holds.items.map((item: { path: string }) => item.path)).toEqual(['notes/huge.md']);
const text = await captured(() => runSources(engine, ['status', 'notes-git']));
expect(text).toContain('notes-git: 2 held file(s)');
- } finally { await engine.unsetConfig('sync.hold_cap'); }
+ });
});
test('sources status <unknown id> refuses with not_found and the list command', async () => {
diff --git a/test/sync-holds-store.test.ts b/test/sync-holds-store.test.ts
index 1cb83f89df..2f0e91feff 100644
--- a/test/sync-holds-store.test.ts
+++ b/test/sync-holds-store.test.ts
@@ -103,9 +103,13 @@ describe('git hold store', () => {
test('policy defaults, overrides and escalation thresholds (count, and percentage only from 40 screened)', async () => {
expect(await readSyncHoldPolicy(engine)).toEqual({ mode: 'hold', cap: 500, escalateCount: 50, escalatePct: 5, parserRegression: 'stop' });
+ // #6712 PR 2: sync.holds stays a brain key; the cap, the thresholds and the parser-regression stop are tuned by their
+ // GBRAIN_SYNC_* environment variables, and the retired keys stored on a brain are not applied.
await engine.setConfig('sync.holds', 'fail'); await engine.setConfig('sync.hold_cap', '2'); await engine.setConfig('sync.parser_regression', 'hold');
await engine.setConfig('sync.hold_escalate_count', '10'); await engine.setConfig('sync.hold_escalate_pct', '20');
- expect(await readSyncHoldPolicy(engine)).toEqual({ mode: 'fail', cap: 2, escalateCount: 10, escalatePct: 20, parserRegression: 'hold' });
+ expect(await readSyncHoldPolicy(engine, {})).toEqual({ mode: 'fail', cap: 500, escalateCount: 50, escalatePct: 5, parserRegression: 'stop' });
+ expect(await readSyncHoldPolicy(engine, { GBRAIN_SYNC_HOLD_CAP: '2', GBRAIN_SYNC_PARSER_REGRESSION: 'hold', GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '10', GBRAIN_SYNC_HOLD_ESCALATE_PCT: '20' }))
+ .toEqual({ mode: 'fail', cap: 2, escalateCount: 10, escalatePct: 20, parserRegression: 'hold' });
const defaults = { escalateCount: 50, escalatePct: 5 };
expect(holdsEscalated(defaults, 51, { held: 0, screened: 0 })).toBe(true);
expect(holdsEscalated(defaults, 50, { held: 0, screened: 0 })).toBe(false);
diff --git a/test/sync-legacy-holds.test.ts b/test/sync-legacy-holds.test.ts
index 6dd0aaa36e..abe05631a5 100644
--- a/test/sync-legacy-holds.test.ts
+++ b/test/sync-legacy-holds.test.ts
@@ -302,15 +302,12 @@ test('quote-recovered frontmatter imports and is counted with the generator pref
}), 120_000);
test('escalation fires past the configured hold count', () => eachEngine(async () => {
- await engine.setConfig('sync.hold_escalate_count', '0');
- try {
+ await withEnv({ GBRAIN_SYNC_HOLD_ESCALATE_COUNT: '0' }, async () => {
const { id, root } = await source({ 'notes/a.md': good('Alpha'), 'notes/broken.md': BROKEN });
const result = await sync(id, root);
expect(result).toMatchObject({ holds_escalated: true, held_count: 1 });
expect(printed(result)).toContain('HOLDS ESCALATED');
- } finally {
- await engine.setConfig('sync.hold_escalate_count', '50');
- }
+ });
}), 120_000);
test('#6188 (T5): legacy sync imports a page with a malformed fence as before and never holds it', async () => eachEngine(async () => {
diff --git a/test/sync-managed-cron-flags-6712.test.ts b/test/sync-managed-cron-flags-6712.test.ts
new file mode 100644
index 0000000000..718b2bf298
--- /dev/null
+++ b/test/sync-managed-cron-flags-6712.test.ts
@@ -0,0 +1,66 @@
+/**
+ * #6712 PR 2: doctor's managed cron recipe (`gbrain sync --all --no-pull --hard-deadline 13m`) and the managed
+ * catch-up knobs `--no-bulk` / `--no-lanes` are never refused on a managed source, on any path a CLI sync takes:
+ * the in-process run (single source and `--all`), the serve ladder's argv gate, and the PGLite owner lane (which
+ * used to refuse `--no-lanes` / `--lanes N`; a PGLite owner runs no bulk lanes, so the CLI accepts and drops them).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runSync } from '../src/commands/sync.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { parseDelegatedSyncArgs } from '../src/commands/sync-delegate.ts';
+import { parsePersistenceSyncArgs } from '../src/commands/sync-persistence-delegate.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-cron-flags-'));
+let engine: BrainEngine;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1', OPENAI_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+async function fixture(): Promise<string> {
+ const id = `cron-${randomUUID().slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'a.md'), '---\ntitle: a\n---\nA durable observation about acme-example.\n');
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb) WHERE id<>$1", [id]);
+ return id;
+}
+const quiet = async <T>(fn: () => Promise<T>): Promise<T> => {
+ const origError = console.error, origLog = console.log, origWrite = process.stderr.write.bind(process.stderr), origOut = process.stdout.write.bind(process.stdout);
+ console.error = () => {}; console.log = () => {};
+ process.stderr.write = (() => true) as typeof process.stderr.write; process.stdout.write = (() => true) as typeof process.stdout.write;
+ try { return await fn(); } finally { console.error = origError; console.log = origLog; process.stderr.write = origWrite; process.stdout.write = origOut; }
+};
+const KNOBS = ['--no-pull', '--no-embed', '--no-bulk', '--no-lanes', '--hard-deadline', '13m'];
+
+test('a managed single-source sync with the cron knobs runs and imports', async () => withEnv(env, async () => {
+ const id = await fixture();
+ await quiet(() => runSync(engine, ['--source', id, ...KNOBS]));
+ expect(await engine.getPage('a', { sourceId: id })).not.toBeNull();
+}), 120_000);
+
+test('doctor\'s managed cron recipe (--all) runs and imports', async () => withEnv(env, async () => {
+ const id = await fixture();
+ await quiet(() => runSync(engine, ['--all', ...KNOBS]));
+ expect(await engine.getPage('a', { sourceId: id })).not.toBeNull();
+}), 120_000);
+
+test('the serve ladder and the PGLite owner lane accept the knobs', async () => {
+ expect(parseDelegatedSyncArgs(['--source', 'notes', ...KNOBS])).toEqual({ ok: true, explicitSource: 'notes', options: { noPull: true, noEmbed: true, noBulk: true, lanes: 1 } });
+ expect((await parsePersistenceSyncArgs(['--source', 'notes', ...KNOBS], home)).options).toEqual({ sourceId: 'notes', noPull: true, noEmbed: true, noBulk: true });
+});