Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sources): status lists holds limited in SQL and shows recent blocked-cursor conversions (#5988)
garrytan3cad4e48a545
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex f0da368630..95be452774 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -17,7 +17,7 @@- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.-- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `sources status` / `retry-held`, never `readAllSourceHolds`. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v199) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`.+- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v199) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.tsindex 77148f03cd..50cc7df7f7 100644--- a/src/core/op-checkpoint.ts+++ b/src/core/op-checkpoint.ts@@ -485,8 +485,9 @@ 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). 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,+ * sync holds, their summary while it counts any, retry requests, sync+ * import provenance and the blocked-cursor conversion log of a live source+ * incarnation leave only on resolution (or with the incarnation),* and connector hold-retry requests never expire (#5988).*/export async function purgeStaleCheckpoints(@@ -503,7 +504,7 @@ export async function purgeStaleCheckpoints(WHERE updated_at < now() - ($1 || ' days')::intervalAND 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 IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions')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'))diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.tsindex a5ae393963..ac4d8e83c6 100644--- a/src/core/persistence/connector-status.ts+++ b/src/core/persistence/connector-status.ts@@ -3,8 +3,9 @@* upgrade recovery, account pin continuity, pending receipts and the last* run's counts. Never includes the pinned account or installation id.*- * #5988: also each Git source's held files (`readGitHoldStatuses`), shown- * beside connector holds. Only `sources status` and `sources retry-held` merge+ * #5988: also each Git source's held files (`readGitHoldStatuses`, limited+ * in SQL to `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.*/@@ -14,7 +15,7 @@ import { readFix } from '../ops/op-fix.ts';import { readManagedConnectorState, type ConnectorRunCounts, type UpgradeRecovery } from './connector-state.ts';import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store.ts';import type { ItemHoldRecord } from '../connectors/item-holds.ts';-import { gitHoldItem, readGitSourceHolds, readSyncHoldPolicy, type GitHoldItem } from './sync-holds.ts';+import { gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';import { holdLine } from '../../commands/sync-diagnostics.ts';/** Fix wave 4: `sources status` lists this many held items per source, then "+N more". */@@ -99,32 +100,48 @@ export interface GitHoldStatus {count: number;items: GitHoldItem[];truncated?: true;+ /** Blocked sync requests a recent run converted in place (held or re-frozen) instead of staying blocked. */+ recent_conversions?: SyncConversion[];/** The command that runs the next sync of this source (managed brains sync with --no-pull). */sync_argv: string[];}-/** Held files of each listed source that has any (sources with none are absent). */+/** How many converted requests `sources status` shows per source. */+export const CONVERSION_STATUS_LIMIT = 5;++/** Held files and recent conversions of each listed source that has any (sources with neither are absent). */export async function readGitHoldStatuses(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceIds: string[]): Promise<Map<string, GitHoldStatus>> {const out = new Map<string, GitHoldStatus>();if (!sourceIds.length) return out;- const sources = await readGitSourceHolds(engine, { sourceIds });- if (!sources.length) return out;const { cap } = await readSyncHoldPolicy(engine);+ const [sources, conversions] = await Promise.all([readGitHoldListing(engine, sourceIds, cap), readSyncConversions(engine, sourceIds, CONVERSION_STATUS_LIMIT)]);+ if (!sources.length && !conversions.size) return out;const managed = await managedBrain(engine);- for (const source of sources) {- out.set(source.sourceId, { count: source.count, items: source.holds.slice(0, cap).map(gitHoldItem),- ...(source.count > cap ? { truncated: true as const } : {}),- sync_argv: ['gbrain', 'sync', '--source', source.sourceId, ...(managed ? ['--no-pull'] : [])] });+ const counts = new Map(sources.map(source => [source.sourceId, source]));+ for (const sourceId of sourceIds) {+ const source = counts.get(sourceId), converted = conversions.get(sourceId);+ if (!source && !converted) continue;+ const items = (source?.holds ?? []).map(gitHoldItem);+ out.set(sourceId, { count: source?.count ?? 0, items, ...((source?.count ?? 0) > items.length ? { truncated: true as const } : {}),+ ...(converted ? { recent_conversions: converted } : {}),+ sync_argv: ['gbrain', 'sync', '--source', sourceId, ...(managed ? ['--no-pull'] : [])] });}return out;}-/** Held files: up to HELD_STATUS_LIMIT per source with each one's next step, then the re-screen and retry commands. */+/** Held files: up to HELD_STATUS_LIMIT per source with each one's next step, then the re-screen and retry commands; then recent conversions. */export function gitHoldStatusLines(sourceId: string, status: GitHoldStatus): string[] {- const lines = [` ${sourceId}: ${status.count} held file(s): not imported, and they do not block sync. A page whose newer file is held keeps its last good revision and is read-only for put_page until the file is repaired.`];- for (const item of status.items.slice(0, HELD_STATUS_LIMIT)) lines.push(` ${holdLine(item, 'Held').trim()} Held since ${day(item.held_since)}.`);- if (status.count > HELD_STATUS_LIMIT) lines.push(` +${status.count - HELD_STATUS_LIMIT} more; --json lists ${status.truncated ? `the first ${status.items.length}` : 'all'}`);- lines.push(` Most holds re-screen on the next sync by themselves (the file changed or was deleted, or a newer gbrain can read it): ${status.sync_argv.join(' ')}`);- lines.push(` to re-screen the held files on that sync even if nothing changed: gbrain sources retry-held ${sourceId}`);+ const lines: string[] = [];+ if (status.count) {+ lines.push(` ${sourceId}: ${status.count} held file(s): not imported, and they do not block sync. A page whose newer file is held keeps its last good revision and is read-only for put_page until the file is repaired.`);+ for (const item of status.items.slice(0, HELD_STATUS_LIMIT)) lines.push(` ${holdLine(item, 'Held').trim()} Held since ${day(item.held_since)}.`);+ if (status.count > HELD_STATUS_LIMIT) lines.push(` +${status.count - HELD_STATUS_LIMIT} more; --json lists ${status.truncated ? `the first ${status.items.length}` : 'all'}`);+ lines.push(` Most holds re-screen on the next sync by themselves (the file changed or was deleted, or a newer gbrain can read it): ${status.sync_argv.join(' ')}`);+ lines.push(` to re-screen the held files on that sync even if nothing changed: gbrain sources retry-held ${sourceId}`);+ }+ if (status.recent_conversions?.length) {+ lines.push(` ${sourceId}: ${status.recent_conversions.length} blocked sync request(s) recently converted in place (the file was held or re-read instead of blocking the source):`);+ for (const c of status.recent_conversions) lines.push(` ${c.request_id}${c.path ? ` (${c.path})` : ''}: ${c.outcome === 'held' ? 'held' : 're-read and resubmitted'}, ${day(c.converted_at)}, run ${c.run_id}`);+ }return lines;}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex b13d05c1ba..cf087b0c77 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -30,6 +30,10 @@ 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';+/** One row per source incarnation: the blocked requests recent managed syncs converted in place. */+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. */export const GIT_HOLD_CAP = 500;export const GIT_HOLD_ESCALATE_COUNT = 50;@@ -200,6 +204,31 @@ export async function readGitSourceHolds(engine: Exec, opts: { sourceIds?: strinreturn [...out.values()];}+/**+ * A bounded listing for status views: each listed source's outstanding count+ * (its summary row) and its first `limit` holds in path order, limited in SQL+ * so a source with 20k holds never loads them all.+ */+export async function readGitHoldListing(engine: Exec, sourceIds: string[], limit: number): Promise<GitSourceHolds[]> {+ if (!sourceIds.length) return [];+ const rows = await engine.executeRaw<{ source_id: string; incarnation: string; count: number | string; record: GitHoldRecord | null }>(`SELECT s.id AS source_id,+ s.incarnation::text AS incarnation, COALESCE((sm.completed_keys->0->>'count')::int,0) AS count, h.record+ FROM sources s+ JOIN op_checkpoints sm ON sm.op=$1 AND sm.fingerprint=s.id||':'||s.incarnation::text+ LEFT JOIN LATERAL (SELECT x.fingerprint, x.completed_keys->0 AS record FROM op_checkpoints x+ WHERE x.op=$2 AND x.completed_keys->0->>'source_id'=s.id AND x.completed_keys->0->>'incarnation'=s.incarnation::text+ ORDER BY x.fingerprint LIMIT $4) h ON true+ WHERE s.id=ANY($3::text[]) AND COALESCE((sm.completed_keys->0->>'count')::int,0)>0+ ORDER BY s.id, h.fingerprint`, [GIT_HOLD_SUMMARY_OP, GIT_HOLD_OP, sourceIds, Math.max(0, Math.floor(limit))]);+ const out = new Map<string, GitSourceHolds>();+ for (const row of rows) {+ const entry = out.get(row.source_id) ?? { sourceId: row.source_id, incarnation: row.incarnation, count: Number(row.count), holds: [] };+ if (row.record) entry.holds.push(row.record);+ out.set(row.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;@@ -241,6 +270,30 @@ export function gitHoldItem(record: GitHoldRecord): GitHoldItem {fix: gitHoldFix(record), docs: gitHoldDocs(record.code, record.meta.reason) };}+/** A blocked sync request a run converted in place: held (the file is refused) or re-frozen (the file now imports). */+export interface SyncConversion { request_id: string; path: string | null; slug: string | null; run_id: string; outcome: 'held' | 'refrozen'; converted_at: string }++/** Appends a conversion to the source's log (newest first, bounded); call it in the transaction that saves the converted cursor. */+export async function recordSyncConversion(tx: Exec, sourceId: string, incarnation: string, conversion: Omit<SyncConversion, 'converted_at'>): Promise<void> {+ const entry = JSON.stringify([{ ...conversion, converted_at: new Date().toISOString() }]);+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('source_id',$3::text,'incarnation',$4::text,'conversions',$5::text::jsonb)))+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array((op_checkpoints.completed_keys->0)||jsonb_build_object('conversions',+ (SELECT COALESCE(jsonb_agg(c ORDER BY n),'[]'::jsonb) FROM jsonb_array_elements($5::text::jsonb||COALESCE(op_checkpoints.completed_keys->0->'conversions','[]'::jsonb))+ WITH ORDINALITY AS e(c,n) WHERE n<=$6))),updated_at=now()`,+ [SYNC_CONVERSION_OP, summaryFingerprint(sourceId, incarnation), sourceId, incarnation, entry, SYNC_CONVERSION_KEEP]);+}++/** The conversion log of each listed source's current incarnation, newest first (sources with none are absent). */+export async function readSyncConversions(engine: Exec, sourceIds: string[], limit: number): Promise<Map<string, SyncConversion[]>> {+ const out = new Map<string, SyncConversion[]>();+ if (!sourceIds.length || limit <= 0) return out;+ const rows = await engine.executeRaw<{ source_id: string; conversions: SyncConversion[] | null }>(`SELECT s.id AS source_id, c.completed_keys->0->'conversions' AS conversions+ FROM sources s JOIN op_checkpoints c ON c.op=$1 AND c.fingerprint=s.id||':'||s.incarnation::text WHERE s.id=ANY($2::text[])`, [SYNC_CONVERSION_OP, sourceIds]);+ for (const row of rows) if (Array.isArray(row.conversions) && row.conversions.length) out.set(row.source_id, row.conversions.slice(0, limit));+ return out;+}+/** `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)diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 5bf947cb52..a9b1786e18 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -32,7 +32,7 @@ import { assertManagedSyncAllowed } from './worktree-refresh.ts';import { isContentRefusal } from '../import-screen.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';-import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recoveredReport, writeGitHold } from './sync-holds.ts';+import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold } from './sync-holds.ts';export interface ManagedSyncWriteDiagnostic {source_id: string;@@ -316,9 +316,14 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sconst base: Cursor = { ...blocked }; delete base.pending;const again = await freezeEntry(engine, base, key, assertActive, run);const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];- if ('hold' in again) return saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive, heldWrite(blocked, again.hold, run.observedAt!));+ const logged = (outcome: 'held' | 'refrozen') => (tx: BrainEngine) => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation,+ { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome });+ if ('hold' in again) {+ return saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive,+ async tx => { await heldWrite(blocked, again.hold, run.observedAt!)(tx); await logged('held')(tx); });+ }if (previous.converted && again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content) return blocked;- return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive);+ return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive, logged('refrozen'));}/**diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.tsindex 1aab24eb8f..d92ce21692 100644--- a/test/persistence-sync-holds.test.ts+++ b/test/persistence-sync-holds.test.ts@@ -18,6 +18,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { sha256 } from '../src/core/persistence/digest.ts';import { GIT_HOLD_OP, SYNC_IMPORT_PROVENANCE_OP, readGitSourceHolds, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands/sync.ts';+import { gitHoldStatusLines, readGitHoldStatuses } from '../src/core/persistence/connector-status.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -218,6 +219,11 @@ test('a cursor blocked by a pre-upgrade failed receipt converts in place: held wexpect(converted).toMatchObject({ status: 'first_sync', held_count: 1 });expect(converted.held?.[0]?.path).toBe('notes/broken.md');expect(await engine.getPage('notes/ok', { sourceId: s.id })).not.toBeNull();+ // sources status keeps the conversion as history after later runs.+ await s.sync();+ const status = (await readGitHoldStatuses(engine, [s.id])).get(s.id)!;+ expect(status.recent_conversions).toMatchObject([{ request_id: failed!.request_id, path: 'notes/broken.md', outcome: 'held' }]);+ expect(gitHoldStatusLines(s.id, status).join('\n')).toContain(`${failed!.request_id} (notes/broken.md): held`);// Already fixed: a working-tree cursor re-freezes the fixed bytes in place under a new request and imports them.await engine.setConfig('sync.holds', 'fail');@@ -232,6 +238,9 @@ test('a cursor blocked by a pre-upgrade failed receipt converts in place: held wexpect(fixed.status).not.toBe('blocked_by_failures');expect((await engine.getPage('notes/draft', { sourceId: t.id }))?.title).toBe('Payments roundup');expect(await t.holds()).toEqual([]);+ // No hold remains, but the conversion still shows in sources status.+ expect((await readGitHoldStatuses(engine, [t.id])).get(t.id)).toMatchObject({ count: 0, items: [],+ recent_conversions: [{ request_id: draft!.request_id, path: 'notes/draft.md', outcome: 'refrozen' }] });}), 240_000);test('a flagless sync converts a --no-embed cursor with its stored options, and the loop guard mints no receipt per run', () => each(async engine => {diff --git a/test/sync-hold-surfaces.test.ts b/test/sync-hold-surfaces.test.tsindex 0e6ff7da17..1302853413 100644--- a/test/sync-hold-surfaces.test.ts+++ b/test/sync-hold-surfaces.test.ts@@ -21,7 +21,7 @@ import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';import { heldFileMessage, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';-import { readGitHold, readGitHoldRetryPaths, writeGitHold, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';+import { readGitHold, readGitHoldListing, readGitHoldRetryPaths, writeGitHold, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';import { writerAdminState } from '../src/core/persistence/admin-intent.ts';import { carryLegacyFailCounts } from '../src/core/connectors/item-holds.ts';@@ -103,6 +103,20 @@ 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 () => {+ 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 {+ 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 () => {await expect(runSources(engine, ['status', 'missing-src'])).rejects.toMatchObject({ code: 'not_found',fix: { argv: ['gbrain', 'sources', 'list', '--json'] } });diff --git a/test/sync-holds-store.test.ts b/test/sync-holds-store.test.tsindex e1673a1c85..1cb83f89df 100644--- a/test/sync-holds-store.test.ts+++ b/test/sync-holds-store.test.ts@@ -10,8 +10,9 @@ 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,+ recordSyncImportProvenance, readSyncImportProvenance, recordSyncConversion, readSyncConversions, SYNC_CONVERSION_KEEP, type GitHoldRecord,} from '../src/core/persistence/sync-holds.ts';+import { readHeldCoverage } from '../src/core/persistence/held-reads.ts';let engine: BrainEngine;let incarnation: string;@@ -127,6 +128,35 @@ describe('git hold store', () => {expect(JSON.stringify(remote)).not.toContain('notes/');});+ test('the summary row counts holds whose page exists as stale, through updates and clears', async () => {+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('holds-c','holds-c','{}')");+ const inc = (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='holds-c'"))[0].incarnation;+ const at = (path: string, observed: string, page_id: number | null) => ({ ...hold(path, observed), source_id: 'holds-c', incarnation: inc, page_id });+ await writeGitHold(engine, at('n/new.md', '2026-01-01T00:00:00.000Z', null));+ await writeGitHold(engine, at('n/mod.md', '2026-01-01T00:00:00.000Z', 41));+ expect(await readHeldCoverage(engine, { sourceId: 'holds-c' })).toEqual([{ source_id: 'holds-c', missing: 1, stale: 1 }]);+ await writeGitHold(engine, at('n/new.md', '2026-01-02T00:00:00.000Z', 42));+ expect(await readHeldCoverage(engine, { sourceId: 'holds-c' })).toEqual([{ source_id: 'holds-c', missing: 0, stale: 2 }]);+ await clearGitHold(engine, { sourceId: 'holds-c', incarnation: inc, path: 'n/mod.md', observedAt: '2026-01-03T00:00:00.000Z' });+ expect(await readHeldCoverage(engine, { sourceId: 'holds-c' })).toEqual([{ source_id: 'holds-c', missing: 0, stale: 1 }]);+ await clearGitHold(engine, { sourceId: 'holds-c', incarnation: inc, path: 'n/new.md', observedAt: '2026-01-03T00:00:00.000Z' });+ expect(await readHeldCoverage(engine, { sourceId: 'holds-c' })).toEqual([]);+ });++ test('the conversion log keeps the newest conversions, bounded, and survives the checkpoint purge', async () => {+ for (let i = 0; i < SYNC_CONVERSION_KEEP + 3; i++) {+ await recordSyncConversion(engine, 'holds-a', incarnation, { request_id: `req-${i}`, path: `notes/${i}.md`, slug: `notes/${i}`, run_id: 'run-9', outcome: i % 2 ? 'held' : 'refrozen' });+ }+ const all = (await readSyncConversions(engine, ['holds-a', 'holds-b'], 100)).get('holds-a')!;+ expect(all).toHaveLength(SYNC_CONVERSION_KEEP);+ expect(all[0]).toMatchObject({ request_id: `req-${SYNC_CONVERSION_KEEP + 2}`, outcome: 'refrozen' });+ expect(all.at(-1)!.request_id).toBe('req-3');+ expect((await readSyncConversions(engine, ['holds-a'], 2)).get('holds-a')!.map(c => c.request_id)).toEqual([`req-${SYNC_CONVERSION_KEEP + 2}`, `req-${SYNC_CONVERSION_KEEP + 1}`]);+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='sync-conversions'");+ await purgeStaleCheckpoints(engine, 7);+ expect((await readSyncConversions(engine, ['holds-a'], 100)).get('holds-a')).toHaveLength(SYNC_CONVERSION_KEEP);+ });+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 });