Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): durable Git hold store and hold surfaces in sync output (#5988)

garrytan261bd018fa32
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fdc004996b..cde8edb60c 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)
src/commands/serve-http.ts 919 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities)
src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)
-src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
+src/commands/sync.ts 496 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
src/core/cycle.ts 3207 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index 63bdb9f91b..f5ce1390a5 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -1,4 +1,34 @@
import type { SyncResult } from './sync.ts';
+import type { GitHoldItem } from '../core/persistence/sync-holds.ts';
+
+const HOLD_LINES = 20;
+
+function holdLine(item: GitHoldItem, verb: string): string {
+ const where = [item.line !== undefined ? `line ${item.line}` : '', item.key ? `key "${item.key}"` : ''].filter(Boolean).join(', ');
+ const page = item.stale ? 'its page keeps its last good revision and is read-only for put_page until the file is repaired' : 'its page is missing until the file imports';
+ return ` ${verb} ${item.path}: ${item.code}${item.reason ? ` (${item.reason})` : ''}${where ? ` at ${where}` : ''}; ${page}. Next: ${item.fix.argv?.join(' ') ?? item.fix.why} (${item.docs})`;
+}
+
+/**
+ * #5988: new holds this run (capped) and the outstanding total with the
+ * inspect and repair commands. Every sync output mode prints it, including
+ * resumed, no-change and `sync --all` runs on otherwise green sources.
+ */
+export function printHoldNotes(result: SyncResult, write: (line: string) => void): void {
+ if (result.would_hold_count) {
+ for (const item of (result.would_hold ?? []).slice(0, HOLD_LINES)) write(holdLine(item, 'Would hold'));
+ if (result.would_hold_count > HOLD_LINES) write(` ... and ${result.would_hold_count - HOLD_LINES} more would be held (--json lists them).`);
+ }
+ for (const skipped of (result.screen_skipped ?? []).slice(0, HOLD_LINES)) write(` Screen skipped ${skipped.path}: ${skipped.code} (not a content problem; the real sync reports it).`);
+ for (const item of (result.held ?? []).slice(0, HOLD_LINES)) write(holdLine(item, 'Held'));
+ const shown = Math.min(result.held?.length ?? 0, HOLD_LINES);
+ if ((result.held_count ?? 0) > shown) write(` ... and ${(result.held_count ?? 0) - shown} more held this run (--json lists ${result.holds_truncated ? 'the first ones' : 'them all'}).`);
+ const fix = result.holds_fix;
+ if (fix) write(` ${result.holds_escalated ? 'HOLDS ESCALATED: ' : ''}${fix.user_message ?? `${fix.why} Preview the repair: ${fix.argv!.join(' ')}`}`);
+ if (result.converted_from_failed?.length) write(` Converted ${result.converted_from_failed.length} failed request(s) of the blocked cursor in place: ${result.converted_from_failed.join(', ')}.`);
+ const recovered = result.recovered_frontmatter?.fix;
+ if (recovered) write(` ${recovered.why} Preview: ${recovered.argv!.join(' ')}`);
+}
export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.WriteStream): boolean {
const d = result.managedWrite;
@@ -18,6 +48,7 @@ export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.Writ
/** Informational managed-sync lines: skipped slug collisions, refused files and the links derived after the checkpoint. */
export function printManagedSyncNotes(result: SyncResult, write: (line: string) => void): void {
+ printHoldNotes(result, write);
for (const collision of result.slugCollisions ?? []) {
write(` Slug collision: ${collision.skipped.join(', ')} and ${collision.kept} map to ${collision.slug}; kept ${collision.kept}. Rename one file to import both.`);
}
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index f1e9408b66..dab1c85b20 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -96,6 +96,29 @@ export interface SyncResult {
bankedFiles?: number;
/** Fix wave 4: connector items held after repeated item-scoped failures (not blocking freshness). */
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
+ * exact inspect and repair commands. Remote callers get `held_count` and
+ * `holds_fix` (a host-operator relay) only.
+ */
+ held?: import('../core/persistence/sync-holds.ts').GitHoldItem[];
+ held_count?: number;
+ holds_outstanding?: number;
+ holds_escalated?: boolean;
+ holds_truncated?: boolean;
+ /** A sliced run (`writer_yield`) has not screened every entry yet. */
+ holds_pending_screen?: boolean;
+ holds_fix?: import('../core/agent-output.ts').Action;
+ /** Requests of a blocked cursor this run converted in place (held, or re-frozen after the file was fixed). */
+ converted_from_failed?: string[];
+ /** Files imported by quoting unquoted frontmatter values, cumulative for the run. */
+ recovered_frontmatter?: import('../core/persistence/sync-holds.ts').RecoveredFrontmatter;
+ /** Dry run: files the run would hold, and entries the screen could not judge (never holds). */
+ dry_run?: true;
+ would_hold?: import('../core/persistence/sync-holds.ts').GitHoldItem[];
+ would_hold_count?: number;
+ screen_skipped?: Array<{ path: string; code: string }>;
}
// The cost-gate / token-estimate cluster (estimateSourceTreeTokens,
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 095a98816f..e4b489f39b 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -5,6 +5,8 @@ import { slog, withSourcePrefix } from '../../core/console-prefix.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { msysToNativePath } from '../../core/path-confine.ts';
import { syncFailureJsonFields, readManagedSyncFailures } from '../../core/persistence/sync-failures.ts';
+import { syncHoldJsonFields } from '../../core/persistence/sync-holds.ts';
+import { printHoldNotes } from '../sync-diagnostics.ts';
import { getDefaultSourcePath } from '../../core/source-resolver.ts';
import {
resolveSyncAllEmbedPlan,
@@ -591,6 +593,7 @@ async function dispatchSyncAll(input: {
if (r.status === 'fulfilled') {
writeHuman(` ${r.value.result.managedWrite || r.value.result.status === 'blocked_by_failures' ? '✗' : '✓'} ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);
if (r.value.result.managedWrite || r.value.result.status === 'blocked_by_failures') printSyncResult(r.value.result, humanSink);
+ else printHoldNotes(r.value.result, writeHuman);
perSourceResults.push({
sourceId: src.id,
sourceName: src.name,
@@ -658,6 +661,7 @@ function emitSyncAllEnvelope(input: {
...(r.localPath ? { local_path: r.localPath } : {}),
...(r.result ? {
...syncFailureJsonFields(r.result),
+ ...syncHoldJsonFields(r.result),
sync_status: r.result.status,
// #3068: surface the partial reason (e.g. pull_failed) so JSON
// consumers can distinguish a self-healing timeout from a wedge.
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 3e75f3d0bd..77148f03cd 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -484,7 +484,10 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s
/**
* Cycle's purge phase calls this to drop stale checkpoints. 7-day TTL is
* deliberately generous — any reasonable long-running op finishes inside
- * that window, and the row is cheap (few KB).
+ * that window, and the row is cheap (few KB). Durable state is exempt: Git
+ * sync holds, their summary while it counts any, retry requests and sync
+ * import provenance of a live source incarnation leave only on resolution,
+ * and connector hold-retry requests never expire (#5988).
*/
export async function purgeStaleCheckpoints(
engine: BrainEngine,
@@ -499,6 +502,11 @@ export async function purgeStaleCheckpoints(
DELETE FROM op_checkpoints
WHERE updated_at < now() - ($1 || ' days')::interval
AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
+ AND op<>'connector-hold-retry'
+ AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary')
+ AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'
+ AND s.incarnation::text=op_checkpoints.completed_keys->0->>'incarnation'))
AND NOT (op='managed-sync' AND (COALESCE(completed_keys->0->>'done','false')<>'true' OR EXISTS (
SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=op_checkpoints.fingerprint)))
AND op<>'managed-sync-failure'
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
new file mode 100644
index 0000000000..9fc32b8e7e
--- /dev/null
+++ b/src/core/persistence/sync-holds.ts
@@ -0,0 +1,395 @@
+/**
+ * #5988: Git sync holds. A file whose content gbrain refuses deterministically
+ * (unreadable or ambiguous frontmatter, a frontmatter slug naming another page,
+ * over-size, an operator content reject) is held instead of blocking the sync:
+ * the rest of the source imports, the checkpoint advances, and the hold stays
+ * visible until the file changes, is deleted, or a newer gbrain can read it.
+ *
+ * Storage: one `op_checkpoints` row per hold (op `sync-hold`, fingerprint
+ * `source:incarnation:path`) and one small per-source summary row (op
+ * `sync-hold-summary`) holding the count, so a sync that holds 20k files
+ * writes O(1) rows per hold and a status read never loads a source-wide list.
+ * Managed and legacy sync write the same rows; they survive writer mode
+ * changes and are exempt from the 7-day checkpoint purge.
+ *
+ * Writes are version-conditional on `observed_at` (the run's discovery time):
+ * a run never replaces or clears a hold a newer run wrote. Every write locks the
+ * source's summary row first, so concurrent cursors of one source serialize.
+ * Rows carry key name, line, code and a location-only message, never a raw
+ * frontmatter value.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import type { ContentRefusal } from '../import-screen.ts';
+import type { InvalidFrontmatterReason } from '../markdown.ts';
+import type { SyncRename } from './sync-discovery.ts';
+
+export const GIT_HOLD_OP = 'sync-hold';
+export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';
+export const GIT_HOLD_RETRY_OP = 'sync-hold-retry';
+export const SYNC_IMPORT_PROVENANCE_OP = 'sync-import-provenance';
+/** Default for `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;
+/** The percentage rule needs at least this many screened imports. */
+export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression';
+export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed';
+
+export interface GitHoldMeta {
+ reason?: GitHoldReason;
+ key?: string;
+ line?: number;
+ /** The frontmatter reader version that refused it; an older one is re-screened by a newer gbrain. */
+ recovery_version: number;
+ /** Git-mode holds: the pinned blob, so discovery re-checks every hold with one `ls-tree`. */
+ blob_oid?: string;
+ /** The held bytes came from the working tree, not the pinned commit. */
+ working?: boolean;
+ /** The held file is a rename destination: the page it moves when the hold clears. */
+ rename_from?: SyncRename;
+}
+
+export interface GitHoldRecord {
+ version: 1;
+ source_id: string;
+ incarnation: string;
+ /** Source-root-relative file path (the hold key). */
+ path: string;
+ /** The page origin the file maps to. */
+ source_path: string;
+ slug: string | null;
+ /** The page the held file would update (stale); null when the file is new (missing). */
+ page_id: number | null;
+ code: GitHoldCode;
+ /** Location-only: key, line and cause, never a frontmatter value. */
+ message: string;
+ /** sha256 of the exact content sync would import; null when the content was never read (over-size). */
+ upstream_version: string | null;
+ /** Discovery time of the run that wrote it; a run never replaces a hold a newer run wrote. */
+ observed_at: string;
+ held_at: string;
+ updated_at: string;
+ run_id: string | null;
+ mode: 'managed' | 'legacy';
+ meta: GitHoldMeta;
+}
+
+export interface GitSourceHolds { sourceId: string; incarnation: string; count: number; holds: GitHoldRecord[] }
+
+/** One hold as every surface shows it: what, where, and the exact next command. */
+export interface GitHoldItem {
+ path: string;
+ code: GitHoldCode;
+ reason?: GitHoldReason;
+ key?: string;
+ line?: number;
+ message: string;
+ slug: string | null;
+ /** True when a page exists and keeps its last good revision; false when the file's page is missing. */
+ stale: boolean;
+ held_since: string;
+ fix: Action;
+ docs: string;
+}
+
+export function gitHoldFingerprint(sourceId: string, incarnation: string, path: string): string {
+ return `${sourceId}:${incarnation}:${path}`;
+}
+
+const summaryFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;
+
+/** Locks the source's summary row (creating it), so hold writes of one source serialize. */
+async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Promise<number> {
+ const [row] = await tx.executeRaw<{ count: number | string }>(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('source_id',$3::text,'incarnation',$4::text,'count',0)))
+ ON CONFLICT(op,fingerprint) DO UPDATE SET updated_at=now()
+ RETURNING COALESCE((completed_keys->0->>'count')::int,0) AS count`,
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), sourceId, incarnation]);
+ return Number(row?.count ?? 0);
+}
+
+async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number): Promise<void> {
+ await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,count}',
+ to_jsonb(GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta]);
+}
+
+async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
+ const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [GIT_HOLD_OP, gitHoldFingerprint(sourceId, incarnation, path)]);
+ return row?.record ?? null;
+}
+
+/**
+ * Records or replaces a hold. Call it inside the transaction that advances the
+ * run past the file. Idempotent on (path, upstream_version); returns `skipped`
+ * when a newer run already wrote this path's hold.
+ */
+export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'>): Promise<'inserted' | 'updated' | 'skipped'> {
+ await lockSummary(tx, input.source_id, input.incarnation);
+ const existing = await readRow(tx, input.source_id, input.incarnation, input.path);
+ if (existing && existing.observed_at > input.observed_at) return 'skipped';
+ const now = new Date().toISOString();
+ const record: GitHoldRecord = { version: 1, ...input,
+ held_at: existing && existing.upstream_version === input.upstream_version && existing.code === input.code ? existing.held_at : now, updated_at: now };
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [GIT_HOLD_OP, gitHoldFingerprint(input.source_id, input.incarnation, input.path), JSON.stringify([record])]);
+ if (existing) return 'updated';
+ await adjustSummary(tx, input.source_id, input.incarnation, 1);
+ return 'inserted';
+}
+
+/**
+ * Clears a path's hold. Call it only inside the transaction that commits the
+ * file's import, deletion or no-op; `observedAt` is the discovery time of the
+ * run doing it, so an older run never clears a newer hold.
+ */
+export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnation: string; path: string; observedAt: string }): Promise<boolean> {
+ const [any] = await tx.executeRaw('SELECT 1 FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);
+ if (!any) return false;
+ await lockSummary(tx, input.sourceId, input.incarnation);
+ const existing = await readRow(tx, input.sourceId, input.incarnation, input.path);
+ if (!existing || existing.observed_at > input.observedAt) return false;
+ await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);
+ await adjustSummary(tx, input.sourceId, input.incarnation, -1);
+ return true;
+}
+
+export async function readGitHold(engine: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {
+ return readRow(engine, sourceId, incarnation, path);
+}
+
+/** Outstanding holds of the source's current incarnation (one indexed read). */
+export async function countGitHolds(engine: Exec, sourceId: string, incarnation: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ count: number | string }>("SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation)]);
+ return Number(row?.count ?? 0);
+}
+
+/**
+ * Git-source holds of each source's current incarnation (sources with none are
+ * omitted). Connector holds are read by `readAllSourceHolds`; only `sources
+ * status` and `sources retry-held` merge the two.
+ */
+export async function readGitSourceHolds(engine: Exec, opts: { sourceIds?: string[]; runId?: string } = {}): Promise<GitSourceHolds[]> {
+ const rows = await engine.executeRaw<{ record: GitHoldRecord }>(`SELECT h.completed_keys->0 AS record FROM op_checkpoints h
+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'
+ WHERE h.op=$1 AND ($2::text[] IS NULL OR s.id=ANY($2::text[])) AND ($3::text IS NULL OR h.completed_keys->0->>'run_id'=$3)
+ ORDER BY s.id,h.fingerprint`, [GIT_HOLD_OP, opts.sourceIds ?? null, opts.runId ?? null]);
+ const out = new Map<string, GitSourceHolds>();
+ for (const { record } of rows) {
+ const entry = out.get(record.source_id) ?? { sourceId: record.source_id, incarnation: record.incarnation, count: 0, holds: [] };
+ entry.holds.push(record); entry.count++;
+ out.set(record.source_id, entry);
+ }
+ return [...out.values()];
+}
+
+/** The exact next step for one hold: the repair preview for frontmatter, the split or exclude for size. */
+export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'code' | 'meta'>): Action {
+ const source = record.source_id;
+ const repair = (ambiguous: boolean, why: string): Action => ({ argv: ['gbrain', 'repair', 'frontmatter', '--source', source, ...(ambiguous ? ['--include-ambiguous'] : [])],
+ consent: [], actor: 'agent', requires_exclusive: false, why,
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } });
+ switch (record.code) {
+ case 'file_too_large':
+ return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
+ case 'content_rejected':
+ return { argv: ['gbrain', 'config', 'get', 'content_sanity'], consent: [], actor: 'user', requires_exclusive: false,
+ user_message: `${record.path} was rejected by the content-sanity gate because junk_disposition is reject. Remove the matched junk from the file, or decide whether to switch junk_disposition back to quarantine.`,
+ why: 'The operator chose to reject junk; changing that setting is a user decision. Editing the file and committing clears the hold on the next sync.' };
+ 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.' };
+ case 'rename_held':
+ return repair(true, `The page ${record.path} was renamed from changed after the rename; the preview proposes re-binding the rename to the current page for approval.`);
+ case 'frontmatter_slug_conflict':
+ return repair(true, `The frontmatter slug of ${record.path} names another page; the preview proposes removing that line for approval.`);
+ default:
+ return record.meta.reason === 'needs_interpretation'
+ ? repair(true, `Reading ${record.path} needs an interpretation (folded lines, a duplicate key or an unclosed list); the preview shows the exact proposal for approval.`)
+ : repair(false, `Previews the minimal line fix for ${record.path} (or names the line to fix by hand); nothing is written until a hash-bound apply.`);
+ }
+}
+
+export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason): string {
+ return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;
+}
+
+export function gitHoldItem(record: GitHoldRecord): GitHoldItem {
+ return { path: record.path, code: record.code, ...(record.meta.reason ? { reason: record.meta.reason } : {}),
+ ...(record.meta.key ? { key: record.meta.key } : {}), ...(record.meta.line !== undefined ? { line: record.meta.line } : {}),
+ message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,
+ fix: gitHoldFix(record), docs: gitHoldDocs(record.code, record.meta.reason) };
+}
+
+/** `sources retry-held` on a Git source: the next sync re-screens these paths even if Git did not touch them. */
+export async function requestGitHoldRetry(engine: Exec, sourceId: string, incarnation: string, paths: string[]): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('version',1,'source_id',$3::text,'incarnation',$5::text,'paths',$4::text::jsonb,'requested_at',now())))
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array(jsonb_build_object('version',1,'source_id',$3::text,'incarnation',$5::text,
+ 'paths',(SELECT COALESCE(jsonb_agg(DISTINCT p),'[]'::jsonb) FROM (
+ SELECT jsonb_array_elements_text(COALESCE(op_checkpoints.completed_keys->0->'paths','[]'::jsonb)) AS p
+ UNION SELECT jsonb_array_elements_text($4::text::jsonb)) paths),
+ 'requested_at',now())),updated_at=now()`,
+ [GIT_HOLD_RETRY_OP, summaryFingerprint(sourceId, incarnation), sourceId, JSON.stringify(paths), incarnation]);
+}
+
+export async function readGitHoldRetryPaths(engine: Exec, sourceId: string, incarnation: string): Promise<string[]> {
+ const [row] = await engine.executeRaw<{ completed_keys: Array<{ paths?: unknown }> }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [GIT_HOLD_RETRY_OP, summaryFingerprint(sourceId, incarnation)]);
+ const paths = row?.completed_keys?.[0]?.paths;
+ return Array.isArray(paths) ? paths.filter((p): p is string => typeof p === 'string') : [];
+}
+
+/** Removes the paths a run took into its manifest; paths requested meanwhile stay. */
+export async function clearGitHoldRetryPaths(engine: Exec, sourceId: string, incarnation: string, taken: string[]): Promise<void> {
+ if (!taken.length) return;
+ const fingerprint = summaryFingerprint(sourceId, incarnation);
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,paths}',
+ (SELECT COALESCE(jsonb_agg(p),'[]'::jsonb) FROM jsonb_array_elements_text(completed_keys->0->'paths') p WHERE NOT (p = ANY($3::text[])))),
+ updated_at=now() WHERE op=$1 AND fingerprint=$2`, [GIT_HOLD_RETRY_OP, fingerprint, taken]);
+ await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND jsonb_array_length(completed_keys->0->'paths')=0`, [GIT_HOLD_RETRY_OP, fingerprint]);
+}
+
+export interface SyncHoldPolicy {
+ /** `fail` restores fail-closed blocking: a content refusal blocks the sync as before holds existed. */
+ mode: 'hold' | 'fail';
+ cap: number;
+ escalateCount: number;
+ escalatePct: number;
+ /** What a refusal of bytes that imported before does: stop the run (default) or hold it as `parser_regression`. */
+ 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);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
+ };
+ const [mode, cap, count, pct, regression] = await Promise.all(['sync.holds', 'sync.hold_cap', 'sync.hold_escalate_count', 'sync.hold_escalate_pct', 'sync.parser_regression'].map(read));
+ 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' };
+}
+
+/** More holds than the source should carry, or too large a share of this run's screened imports. */
+export function holdsEscalated(policy: Pick<SyncHoldPolicy, 'escalateCount' | 'escalatePct'>, outstanding: number, run: { held: number; screened: number }): boolean {
+ return outstanding > policy.escalateCount
+ || (run.screened >= GIT_HOLD_ESCALATE_MIN_SCREENED && run.held * 100 > policy.escalatePct * run.screened);
+}
+
+/**
+ * Import provenance of a page synced from a file: the exact bytes it imported
+ * and the gbrain that validated them. The parser-regression stop fires only
+ * when a newer gbrain refuses bytes this record says imported validated.
+ */
+export interface SyncImportProvenance {
+ source_id: string;
+ incarnation: string;
+ page_id: number;
+ origin: string;
+ raw_sha256: string;
+ blob_oid?: string;
+ gbrain_version: string;
+ validated: true;
+ recovery?: Array<{ kind: string; key: string; line: number; recovery_version: number }>;
+ recorded_at: string;
+}
+
+const provenanceFingerprint = (sourceId: string, incarnation: string, pageId: number) => `${sourceId}:${incarnation}:${pageId}`;
+
+export async function recordSyncImportProvenance(tx: Exec, value: Omit<SyncImportProvenance, 'recorded_at' | 'validated'>): Promise<void> {
+ const record: SyncImportProvenance = { ...value, validated: true, recorded_at: new Date().toISOString() };
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [SYNC_IMPORT_PROVENANCE_OP, provenanceFingerprint(value.source_id, value.incarnation, value.page_id), JSON.stringify([record])]);
+}
+
+export async function readSyncImportProvenance(engine: Exec, sourceId: string, incarnation: string, pageId: number): Promise<SyncImportProvenance | null> {
+ const [row] = await engine.executeRaw<{ record: SyncImportProvenance }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [SYNC_IMPORT_PROVENANCE_OP, provenanceFingerprint(sourceId, incarnation, pageId)]);
+ return row?.record ?? null;
+}
+
+export interface RecoveredFrontmatter {
+ count: number;
+ /** Up to 5 imported files; their common directory names the generator to fix. */
+ sample_paths: string[];
+ common_prefix: string;
+ /** `title: #...`-style values YAML reads as a comment; imported, but repair can rescue them. */
+ comment_values?: number;
+ fix?: Action;
+}
+
+/** The common directory of the paths ('' when they share none). */
+export function commonPathPrefix(paths: string[]): string {
+ if (!paths.length) return '';
+ const split = paths.map(path => path.split('/').slice(0, -1));
+ const first = split[0];
+ let length = first.length;
+ for (const parts of split) {
+ let i = 0;
+ while (i < length && parts[i] === first[i]) i++;
+ length = i;
+ }
+ return first.slice(0, length).join('/');
+}
+
+/** Folds a run's recovered-frontmatter paths into the cursor's running total. */
+export function addRecovered(previous: { count: number; sample_paths: string[]; comment_values?: number } | undefined,
+ add: { paths?: string[]; commentValues?: number }): { count: number; sample_paths: string[]; comment_values?: number } {
+ const paths = add.paths ?? [];
+ const comment = (previous?.comment_values ?? 0) + (add.commentValues ?? 0);
+ return { count: (previous?.count ?? 0) + paths.length, sample_paths: [...(previous?.sample_paths ?? []), ...paths].slice(0, 5),
+ ...(comment ? { comment_values: comment } : {}) };
+}
+
+export function recoveredReport(sourceId: string, recovered: { count: number; sample_paths: string[]; comment_values?: number } | undefined): RecoveredFrontmatter | undefined {
+ if (!recovered || (!recovered.count && !recovered.comment_values)) return undefined;
+ const prefix = commonPathPrefix(recovered.sample_paths);
+ return { ...recovered, common_prefix: prefix, fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `${recovered.count} file(s)${prefix ? ` under ${prefix}/` : ''} imported only after quoting unquoted frontmatter values: whatever writes them emits YAML other tools refuse. Fix the generator to quote values (or write through put_page); the preview shows the on-disk quoting fix.` } };
+}
+
+/**
+ * The hold fields of a sync result: this run's holds (detail capped), the
+ * source's outstanding total, escalation, and the exact inspect and repair
+ * commands. Remote callers get the counts and a relay instruction only.
+ */
+export async function buildHoldReport(engine: Exec, input: { sourceId: string; incarnation: string; runId: string; remote: boolean;
+ policy: SyncHoldPolicy; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,
+ 'held' | 'held_count' | 'holds_outstanding' | 'holds_escalated' | 'holds_truncated' | 'holds_pending_screen' | 'holds_fix'>> {
+ const outstanding = await countGitHolds(engine, input.sourceId, input.incarnation);
+ const runHolds = (await readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }))[0]?.holds ?? [];
+ if (!outstanding && !runHolds.length) return {};
+ const escalated = holdsEscalated(input.policy, outstanding, { held: runHolds.length, screened: input.screened });
+ const repair = ['gbrain', 'repair', 'frontmatter', '--source', input.sourceId];
+ const verify = { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'] };
+ if (input.remote) return { held_count: runHolds.length, holds_fix: { argv: repair, consent: [], actor: 'host_admin', requires_exclusive: false, verify,
+ why: `${outstanding} file(s) in source ${input.sourceId} are held and not imported; only the brain host can inspect and repair them.`,
+ user_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' and '${repair.join(' ')}' on the brain host.` } };
+ const fix: Action = { argv: repair, consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; the repair preview proposes each fix and writes nothing.`
+ + (escalated ? ' Escalated: more files are held than a source should carry, so a generator or a gbrain upgrade is likely writing or reading them wrong; fix the cause before the backlog grows.' : '') };
+ return { held: runHolds.slice(0, input.policy.cap).map(gitHoldItem), held_count: runHolds.length, holds_outstanding: outstanding,
+ ...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),
+ ...(input.pendingScreen ? { holds_pending_screen: true } : {}), holds_fix: fix };
+}
+
+/** The hold fields as the sync JSON envelopes carry them (snake_case already). */
+export function syncHoldJsonFields(result: object): Record<string, unknown> {
+ const fields = result as Record<string, unknown>;
+ return Object.fromEntries(['held', 'held_count', 'holds_outstanding', 'holds_escalated', 'holds_truncated', 'holds_pending_screen', 'holds_fix',
+ 'converted_from_failed', 'recovered_frontmatter', 'dry_run', 'would_hold', 'would_hold_count', 'screen_skipped']
+ .filter(key => fields[key] !== undefined).map(key => [key, fields[key]]));
+}
diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.ts
index e426e1ea27..a091c04392 100644
--- a/src/core/sync-embed-backfill.ts
+++ b/src/core/sync-embed-backfill.ts
@@ -6,6 +6,7 @@
*/
import type { BrainEngine } from './engine.ts';
import { syncFailureJsonFields, type ManagedSyncFailure } from './persistence/sync-failures.ts';
+import { syncHoldJsonFields } from './persistence/sync-holds.ts';
import { submitEmbedBackfill } from './embed-backfill-submit.ts';
import { resolveWorkerBackedSyncEmbedMode } from './embedding.ts';
import {
@@ -221,6 +222,7 @@ export function buildSingleSyncJsonEnvelope(
source_id: sourceId,
sync_status: result.status,
...syncFailureJsonFields(result),
+ ...syncHoldJsonFields(result),
...(result.reason ? { reason: result.reason } : {}),
added: result.added,
modified: result.modified,
diff --git a/test/sync-holds-store.test.ts b/test/sync-holds-store.test.ts
new file mode 100644
index 0000000000..e1673a1c85
--- /dev/null
+++ b/test/sync-holds-store.test.ts
@@ -0,0 +1,136 @@
+/**
+ * #5988 Lane B: the Git hold store. One row per hold plus a per-source
+ * summary; version-conditional on the run's discovery time; exempt from the
+ * 7-day checkpoint purge while the source incarnation lives.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
+import {
+ GIT_HOLD_OP, buildHoldReport, clearGitHold, commonPathPrefix, countGitHolds, gitHoldFingerprint, gitHoldItem, holdsEscalated,
+ readGitHold, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, requestGitHoldRetry, clearGitHoldRetryPaths, writeGitHold,
+ recordSyncImportProvenance, readSyncImportProvenance, type GitHoldRecord,
+} from '../src/core/persistence/sync-holds.ts';
+
+let engine: BrainEngine;
+let incarnation: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('holds-a','holds-a','{}'),('holds-b','holds-b','{}')");
+ incarnation = (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='holds-a'"))[0].incarnation;
+}, 120_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+const hold = (path: string, observed: string, extra: Partial<GitHoldRecord> = {}): Omit<GitHoldRecord, 'version' | 'held_at' | 'updated_at'> => ({
+ source_id: 'holds-a', incarnation, path, source_path: path, slug: path.replace(/\.md$/, ''), page_id: null, code: 'invalid_frontmatter',
+ message: 'Invalid YAML frontmatter: key "title" at line 2 continues on unquoted lines.', upstream_version: `sha-${observed}`, observed_at: observed,
+ run_id: 'run-1', mode: 'managed', meta: { reason: 'needs_interpretation', key: 'title', line: 2, recovery_version: 1 }, ...extra,
+});
+
+describe('git hold store', () => {
+ test('write, re-write and clear keep the summary count exact', async () => {
+ expect(await writeGitHold(engine, hold('notes/a.md', '2026-01-01T00:00:00.000Z'))).toBe('inserted');
+ expect(await writeGitHold(engine, hold('notes/a.md', '2026-01-01T00:00:00.000Z'))).toBe('updated');
+ expect(await writeGitHold(engine, hold('notes/b.md', '2026-01-01T00:00:00.000Z'))).toBe('inserted');
+ expect(await countGitHolds(engine, 'holds-a', incarnation)).toBe(2);
+ expect(await clearGitHold(engine, { sourceId: 'holds-a', incarnation, path: 'notes/b.md', observedAt: '2026-01-02T00:00:00.000Z' })).toBe(true);
+ expect(await clearGitHold(engine, { sourceId: 'holds-a', incarnation, path: 'notes/b.md', observedAt: '2026-01-02T00:00:00.000Z' })).toBe(false);
+ expect(await countGitHolds(engine, 'holds-a', incarnation)).toBe(1);
+ });
+
+ test('an older run neither replaces nor clears a hold a newer run wrote', async () => {
+ await writeGitHold(engine, hold('notes/c.md', '2026-02-01T00:00:00.000Z'));
+ const before = await readGitHold(engine, 'holds-a', incarnation, 'notes/c.md');
+ expect(await writeGitHold(engine, hold('notes/c.md', '2026-01-15T00:00:00.000Z', { upstream_version: 'older' }))).toBe('skipped');
+ expect(await clearGitHold(engine, { sourceId: 'holds-a', incarnation, path: 'notes/c.md', observedAt: '2026-01-15T00:00:00.000Z' })).toBe(false);
+ expect(await readGitHold(engine, 'holds-a', incarnation, 'notes/c.md')).toEqual(before);
+ });
+
+ test('reads are scoped to the source and its current incarnation, and items carry code, reason, key, line, fix and docs', async () => {
+ const listed = await readGitSourceHolds(engine, { sourceIds: ['holds-a'] });
+ expect(listed.map(entry => entry.holds.map(h => h.path))).toEqual([['notes/a.md', 'notes/c.md']]);
+ expect(await readGitSourceHolds(engine, { sourceIds: ['holds-b'] })).toEqual([]);
+ const item = gitHoldItem(listed[0].holds[0]);
+ expect(item).toMatchObject({ path: 'notes/a.md', code: 'invalid_frontmatter', reason: 'needs_interpretation', key: 'title', line: 2,
+ docs: 'docs/guides/write-refusals.md#invalid_frontmatter-needs_interpretation' });
+ expect(item.fix.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'holds-a', '--include-ambiguous']);
+ const big = gitHoldItem({ ...listed[0].holds[0], code: 'file_too_large', meta: { recovery_version: 1 } });
+ expect(big.fix.why).toContain('size limit is fixed');
+ expect(big.fix.why).toContain('sync.exclude');
+ });
+
+ test('hold rows 8 days old survive the checkpoint purge; a retired incarnation does not', async () => {
+ await writeGitHold(engine, hold('notes/old.md', '2026-01-01T00:00:00.000Z'));
+ await engine.executeRaw('UPDATE op_checkpoints SET updated_at=now()-interval \'8 days\' WHERE op LIKE \'sync-hold%\'');
+ await purgeStaleCheckpoints(engine, 7);
+ expect(await readGitHold(engine, 'holds-a', incarnation, 'notes/old.md')).not.toBeNull();
+ expect(await countGitHolds(engine, 'holds-a', incarnation)).toBe(3);
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now()-interval '8 days')`,
+ [GIT_HOLD_OP, gitHoldFingerprint('holds-a', '00000000-0000-0000-0000-000000000000', 'x.md'),
+ JSON.stringify([{ ...hold('x.md', '2026-01-01T00:00:00.000Z'), incarnation: '00000000-0000-0000-0000-000000000000' }])]);
+ await purgeStaleCheckpoints(engine, 7);
+ const [retired] = await engine.executeRaw('SELECT 1 FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint('holds-a', '00000000-0000-0000-0000-000000000000', 'x.md')]);
+ expect(retired).toBeUndefined();
+ });
+
+ test('a hold write costs the same statements with 20k holds already stored', async () => {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ SELECT $1,'holds-b:'||$2||':bulk/'||g||'.md',jsonb_build_array(jsonb_build_object('source_id','holds-b','incarnation',$2::text,'path','bulk/'||g||'.md','observed_at','2026-01-01T00:00:00.000Z'))
+ FROM generate_series(1,20000) g`, [GIT_HOLD_OP, 'inc-b']);
+ let statements = 0;
+ const counting = { executeRaw: async (sql: string, params?: unknown[]) => { statements++; return engine.executeRaw(sql, params); } } as Pick<BrainEngine, 'executeRaw'>;
+ await writeGitHold(counting, hold('notes/d.md', '2026-03-01T00:00:00.000Z'));
+ const few = statements;
+ statements = 0;
+ await writeGitHold(counting, { ...hold('bulk/20001.md', '2026-03-01T00:00:00.000Z'), source_id: 'holds-b', incarnation: 'inc-b' });
+ expect(statements).toBe(few);
+ expect(few).toBeLessThanOrEqual(4);
+ });
+
+ test('retry requests accumulate paths and clear only the ones taken', async () => {
+ await requestGitHoldRetry(engine, 'holds-a', incarnation, ['notes/a.md']);
+ await requestGitHoldRetry(engine, 'holds-a', incarnation, ['notes/c.md', 'notes/a.md']);
+ expect((await readGitHoldRetryPaths(engine, 'holds-a', incarnation)).sort()).toEqual(['notes/a.md', 'notes/c.md']);
+ await clearGitHoldRetryPaths(engine, 'holds-a', incarnation, ['notes/a.md']);
+ expect(await readGitHoldRetryPaths(engine, 'holds-a', incarnation)).toEqual(['notes/c.md']);
+ await clearGitHoldRetryPaths(engine, 'holds-a', incarnation, ['notes/c.md']);
+ expect(await readGitHoldRetryPaths(engine, 'holds-a', incarnation)).toEqual([]);
+ });
+
+ 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' });
+ 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' });
+ 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);
+ expect(holdsEscalated(defaults, 3, { held: 3, screened: 39 })).toBe(false);
+ expect(holdsEscalated(defaults, 3, { held: 3, screened: 40 })).toBe(true);
+ expect(holdsEscalated(defaults, 2, { held: 2, screened: 40 })).toBe(false);
+ for (const key of ['sync.holds', 'sync.hold_cap', 'sync.parser_regression', 'sync.hold_escalate_count', 'sync.hold_escalate_pct']) await engine.unsetConfig(key);
+ });
+
+ test('the report caps detail at the cap, never storage, and remote callers get counts only', async () => {
+ const policy = { mode: 'hold' as const, cap: 1, escalateCount: 50, escalatePct: 5, parserRegression: 'stop' as const };
+ const local = await buildHoldReport(engine, { sourceId: 'holds-a', incarnation, runId: 'run-1', remote: false, policy, screened: 10 });
+ expect(local.held).toHaveLength(1);
+ expect(local).toMatchObject({ held_count: 4, holds_outstanding: 4, holds_truncated: true });
+ expect(local.holds_fix!.why).toContain('gbrain sources status holds-a');
+ expect(local.holds_fix!.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', 'holds-a']);
+ const remote = await buildHoldReport(engine, { sourceId: 'holds-a', incarnation, runId: 'run-1', remote: true, policy, screened: 10 });
+ expect(Object.keys(remote).sort()).toEqual(['held_count', 'holds_fix']);
+ expect(remote.holds_fix).toMatchObject({ actor: 'host_admin' });
+ expect(JSON.stringify(remote)).not.toContain('notes/');
+ });
+
+ test('import provenance round-trips and the common prefix names the generator directory', async () => {
+ await recordSyncImportProvenance(engine, { source_id: 'holds-a', incarnation, page_id: 7, origin: 'notes/a.md', raw_sha256: 'abc', gbrain_version: '0.0.0' });
+ expect(await readSyncImportProvenance(engine, 'holds-a', incarnation, 7)).toMatchObject({ raw_sha256: 'abc', validated: true });
+ expect(commonPathPrefix(['tweets/2026/a.md', 'tweets/2026/b.md'])).toBe('tweets/2026');
+ expect(commonPathPrefix(['a.md', 'tweets/b.md'])).toBe('');
+ });
+});