Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): hold each image in managed sync instead of refusing the run (#5493)

time-attack5dc76ed32851
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index a5d95a81ca..1aa670ae01 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -20,7 +20,7 @@
- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken entry or one the waiver would take) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the single pending entry, a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). Any failure rolls the group back; members then publish singly, later members are cancelled after a terminal failure or released after a requeue. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly, and a batch member's failure never cancels its siblings. Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading.
- **`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 `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 v200) 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 v200) 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`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. Tests: `test/repair-frontmatter.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` (then the mention pass unless `mentions: false`, which sync passes) 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`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index b032ac137e..1a04318952 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -142,6 +142,7 @@ with each file and fix the ones that need no guessing."*
| <a id="invalid_frontmatter-ambiguous_protected_key"></a>`invalid_frontmatter` (`ambiguous_protected_key`) | A key that decides access or provenance (`visibility`, `derived_from`, …) is malformed, duplicated, swallowed into another value, rewritten by quoting, or inside an unclosed fence. gbrain never reads such a key as a broader value. | Edit the file by hand: write the key on one line with one quoted value. Ask the user which visibility is intended; never guess it. |
| <a id="frontmatter_slug_conflict"></a>`frontmatter_slug_conflict` | The file's frontmatter `slug:` names a different page than its path does (earlier releases reported this as `invalid_params`). The path decides the slug. | Remove the `slug:` line or make it match the path, or move the file to the path its slug names; `gbrain repair frontmatter --source <source> --include-ambiguous` proposes removing the line. Commit and sync. |
| <a id="file_too_large"></a>`file_too_large` | Over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read). The limit is fixed. | Split the file into smaller files and commit, or leave it out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`. The next `gbrain sync --source <source> --no-pull` clears the hold. |
+| <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | With multimodal embedding on (`embedding_multimodal` / `GBRAIN_EMBEDDING_MULTIMODAL`), sync admits image files, but managed sync has no image importer yet. Each image import is held instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken; keeping them held is fine. To stop holding images, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`) or turn multimodal embedding off; either clears the holds on the next `gbrain sync --source <source> --no-pull`. A held image is re-screened when it changes and on `gbrain sources retry-held <source>`. |
| <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |
| <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. |
| <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. |
diff --git a/docs/wave9/sg.md b/docs/wave9/sg.md
index 95b595d18e..6082054c89 100644
--- a/docs/wave9/sg.md
+++ b/docs/wave9/sg.md
@@ -5,9 +5,11 @@ Integrator: fold these into CHANGELOG.md and docs/UPGRADING_DOWNSTREAM_AGENTS.md
## CHANGELOG lines
- **Long page filenames publish again (#5861).** Atomic and journaled writes stage through a short hidden sibling (`.<sha256 of the target path>.tmp.<uuid>`) instead of appending a suffix to the full basename, so a valid basename near the 255-byte limit no longer fails with ENAMETOOLONG or leaves a write request recovering. Recovery still accepts historical stage names and, under the owner lock, durably swaps in a short name only for a recorded stage the filesystem cannot name. Timeline write-through uses the same allocator (D-NEW-3).
+- **One image no longer stops managed sync (#5493).** With multimodal embedding on, managed sync holds each image import as `managed_image_sync_unsupported` instead of refusing the whole run, so Markdown and code beside it import and the checkpoint advances. The image is recorded as incomplete coverage (a durable hold in `gbrain sources status`, doctor `git_held_files`, and the `held_files` read notice), re-screened when it changes, leaves the source, or on `gbrain sources retry-held`; deleting or renaming an image still reconciles its page. Image holds never escalate. Reworked from a contribution by @andreineacsu (#5975).
## Upgrade-note rows
| Change | Who is affected | Doctor / check | How to opt back |
|---|---|---|---|
| Staging files are now hidden `.<hash>.tmp.<uuid>` siblings (#5861) | Anyone with page basenames over ~214 bytes; operators who glob for `*.tmp.*` leftovers (the new names still contain `.tmp.`) | `gbrain sources writer status --json` shows any recovery that still holds a stage | None needed; historical journals keep working |
+| Managed sync holds images instead of refusing the run (#5493) | Managed brains with `embedding_multimodal` on whose sources contain images | doctor `git_held_files` warns with `managed_image_sync_unsupported` paths (never fails for them) | Exclude images with `sync.exclude`, or turn multimodal embedding off; either clears the holds on the next sync |
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index b68f375229..8c9fea7b8c 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -1,6 +1,6 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { gitHoldFix, readGitHoldListing, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';
+import { gitHoldFix, readGitHoldListing, readGitImageHoldCounts, readSyncHoldPolicy } from '../../../core/persistence/sync-holds.ts';
import { readHeldCoverage } from '../../../core/persistence/held-reads.ts';
import { agentFix } from '../check-fix.ts';
import { isContentRefusal } from '../../../core/import-screen.ts';
@@ -15,14 +15,16 @@ const SAMPLE_PATHS = 5;
* step (the check is host-only, so paths never reach a remote caller), and the
* inspect and repair commands; fails once a source carries more holds than
* `sync.hold_escalate_count`, the same count rule that escalates a sync result.
+ * Unsupported-image holds (#5493) are listed but never escalate.
*/
export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
try {
const [coverage, policy] = await Promise.all([readHeldCoverage(engine, sourceIds ? { sourceIds } : {}), readSyncHoldPolicy(engine)]);
const listing = new Map((await readGitHoldListing(engine, coverage.map(source => source.source_id), SAMPLE_PATHS)).map(entry => [entry.sourceId, entry.holds]));
+ const images = await readGitImageHoldCounts(engine, coverage.map(source => source.source_id));
const sources = coverage.map(source => ({ source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing,
first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold).why })),
- escalated: source.missing + source.stale > policy.escalateCount,
+ escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,
status: `gbrain sources status ${source.source_id}`, repair: `gbrain repair frontmatter --source ${source.source_id}` }));
const held = sources.reduce((sum, source) => sum + source.held, 0);
const details = { held, source_ids: sources.map(source => source.source_id), sources, escalate_count: policy.escalateCount,
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index a1735a094e..335017b567 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -8,7 +8,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
-import { isSyncable, isCodeFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
+import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -314,7 +314,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
}
}
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
- const unsupported = selected.find(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path));
+ // #5493: an image import is held at freeze (managed_image_sync_unsupported); an image deletion needs no importer.
+ const unsupported = selected.find(e => e.action === 'import' && !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path) && (company || !isImageFilePath(e.path)));
if (unsupported) throw opError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.',
`Managed sync of ${sourceId} imports only Markdown and code files, and this run selected others (for example ${unsupported.path}). Exclude them with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 35ba78526a..08873ec04a 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -43,7 +43,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;
type Exec = Pick<BrainEngine, 'executeRaw'>;
-export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression';
+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported';
export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed';
export interface GitHoldMeta {
@@ -119,15 +119,20 @@ async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Pro
return Number(row?.count ?? 0);
}
-/** `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages). */
-async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number): Promise<void> {
+/**
+ * `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages);
+ * `images` the #5493 unsupported-image holds, which never escalate.
+ */
+async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number): Promise<void> {
await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)||jsonb_build_object(
'count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),
- 'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,
- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta]);
+ 'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int),
+ 'images',GREATEST(0,COALESCE((completed_keys->0->>'images')::int,0)+$5::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta]);
}
const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record && record.page_id !== null ? 1 : 0;
+const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'managed_image_sync_unsupported' ? 1 : 0;
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',
@@ -151,10 +156,12 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version
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) {
- if (staleWeight(input) !== staleWeight(existing)) await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing));
+ if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing)) {
+ await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing), imageWeight(input) - imageWeight(existing));
+ }
return 'updated';
}
- await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input));
+ await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input));
return 'inserted';
}
@@ -170,7 +177,7 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnat
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, -staleWeight(existing));
+ await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing));
return true;
}
@@ -178,6 +185,15 @@ export async function readGitHold(engine: Exec, sourceId: string, incarnation: s
return readRow(engine, sourceId, incarnation, path);
}
+/** #5493: unsupported-image holds per source's current incarnation (sources with none are absent); they never escalate. */
+export async function readGitImageHoldCounts(engine: Exec, sourceIds: string[]): Promise<Map<string, number>> {
+ if (!sourceIds.length) return new Map();
+ const rows = await engine.executeRaw<{ source_id: string; images: number | string }>(`SELECT s.id AS source_id, COALESCE((h.completed_keys->0->>'images')::int,0) AS images
+ FROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::text
+ WHERE h.op=$1 AND s.id=ANY($2::text[]) AND COALESCE((h.completed_keys->0->>'images')::int,0)>0`, [GIT_HOLD_SUMMARY_OP, sourceIds]);
+ return new Map(rows.map(row => [row.source_id, Number(row.images)]));
+}
+
/** 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",
@@ -244,6 +260,11 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
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 'managed_image_sync_unsupported':
+ return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'user', requires_exclusive: false,
+ user_message: `Managed sync does not import images yet, so ${record.path} is held and the rest of source ${source} keeps syncing. Keeping images held is fine; to stop holding them, leave images out of the source with sync.exclude or turn off multimodal embedding.`,
+ why: 'Whether images stay in the source is the user\'s call. The hold clears when the file is deleted or excluded, and a held image is re-screened when it changes or on gbrain sources retry-held.',
+ verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };
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.`,
@@ -434,10 +455,14 @@ export function recoveredReport(sourceId: string, recovered: { count: number; sa
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 [summary] = await engine.executeRaw<{ count: number | string; images: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,
+ COALESCE((completed_keys->0->>'images')::int,0) AS images FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,
+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]);
+ const outstanding = Number(summary?.count ?? 0);
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 escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0),
+ { held: runHolds.filter(hold => !imageWeight(hold)).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,
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 14c925d8f7..cba055e4a4 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -12,6 +12,7 @@ import { getWriteRequest, admitWriteInTransaction, receiptFor } from './journal.
import { retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer, type WriteWait } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';
+import { isImageFilePath } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
@@ -34,7 +35,7 @@ import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkS
import { cancelWindow } from './sync-window.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 { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { faultPoint } from './fault-points.ts';
import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold } from './sync-holds.ts';
@@ -244,6 +245,12 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined;
if (entry) {
assertSyncEntryOrigin(cursor, entry);
+ if (entry.action === 'import' && !cursor.companyPlan && isImageFilePath(entry.path)) {
+ const imageBlob = entry.working ? null : pinnedBlob(cursor, entry.path);
+ let bytes: Buffer | null = null;
+ if (!imageBlob) { try { bytes = readSyncFile(cursor.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; } }
+ return { hold: managedImageHold(entry, bytes === null ? null : bytes.toString('utf8'), imageBlob) };
+ }
const originScope = syncOriginScope(cursor);
// #5522: another cursor of this source may have imported this new file since enumeration.
const occupant = await alreadyImportedAtOrigin(engine, cursor, entry, originScope);
diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.ts
index 4b1f63abb9..6eaf9abd09 100644
--- a/src/core/persistence/sync-screen.ts
+++ b/src/core/persistence/sync-screen.ts
@@ -12,7 +12,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { loadImportSanityConfig, type ImportSanityConfig } from '../import-screen.ts';
import { RECOVERY_VERSION } from '../markdown.ts';
import { slugConflictHoldMessage } from '../import-file.ts';
-import { resolveSlugForPath } from '../sync.ts';
+import { isImageFilePath, resolveSlugForPath } from '../sync.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { VERSION } from '../../version.ts';
import { sha256 } from './digest.ts';
@@ -55,6 +55,17 @@ function heldEntry(entry: SyncEntry, slug: string, pageId: number | null, refusa
...(entry.renameFrom ?? entry.renameHeld ? { rename_from: entry.renameFrom ?? entry.renameHeld } : {}) } };
}
+/**
+ * #5493: managed sync has no image importer, so an image import is held as
+ * incomplete coverage instead of refusing the run. The hold names the pinned
+ * blob (or the working-tree bytes), so discovery re-screens it when the file
+ * changes, leaves the source, or `sources retry-held` asks.
+ */
+export function managedImageHold(entry: SyncEntry, content: string | null, blob: TreeBlob | null | undefined): HeldEntry {
+ return heldEntry(entry, entry.slug!, entry.pageId ?? null, { code: 'managed_image_sync_unsupported',
+ message: `${entry.path} is an image, which managed sync does not import yet; the rest of the source synced.` }, content, blob);
+}
+
export interface FrozenImportScreen {
cursor: Pick<SyncDiscovery, 'sourceId' | 'incarnation' | 'root'>;
entry: SyncEntry; slug: string; pageId: number | null; snapshot: Snapshot;
@@ -121,6 +132,12 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscovery
for (const entry of entries) {
try {
const blob = entry.working ? null : blobs.get(syncGitPath(discovery, entry.path)) ?? null;
+ if (isImageFilePath(entry.path)) {
+ const hold = managedImageHold(entry, blob ? null : readSyncFile(discovery.root, entry.path)?.toString('utf8') ?? null, blob);
+ held.push(gitHoldItem({ version: 1, source_id: discovery.sourceId, incarnation: discovery.incarnation, ...hold,
+ observed_at: observed, held_at: observed, updated_at: observed, run_id: null, mode: 'managed' }));
+ continue;
+ }
let bytes: Buffer | null = null, oversize: { size: number | null } | undefined;
try { bytes = readSyncFile(discovery.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; oversize = { size: null }; }
if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };
diff --git a/test/managed-sync-images-5493.test.ts b/test/managed-sync-images-5493.test.ts
new file mode 100644
index 0000000000..fafae1f133
--- /dev/null
+++ b/test/managed-sync-images-5493.test.ts
@@ -0,0 +1,185 @@
+/**
+ * #5493: with multimodal embedding on, the sync admission set includes images,
+ * but the managed sync importer has no image branch. One committed image used
+ * to refuse the whole managed sync (`writer_coordinator_required`) before any
+ * page write, so the checkpoint never advanced. Each image import is now held
+ * (`managed_image_sync_unsupported`): the rest of the run imports, the image is
+ * recorded as incomplete coverage (a durable hold, not an import), and a later
+ * sync re-screens it when the file changes, leaves, or `sources retry-held` asks.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importImageFile } from '../src/core/import-file.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { readGitSourceHolds, requestGitHoldRetry } from '../src/core/persistence/sync-holds.ts';
+import { printHoldNotes } from '../src/commands/sync-diagnostics.ts';
+import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-5493-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const IMAGE = 'test/fixtures/images/tiny.avif';
+const CODE = 'managed_image_sync_unsupported';
+const NOTE = '---\ntitle: Plain\n---\nAn ordinary note.\n';
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+function commit(root: string, message: string): string {
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);
+ return git(root, 'rev-parse', 'HEAD');
+}
+/** A Git source claimed by this host; `before` runs while managed persistence is still off. */
+async function managedSource(engine: BrainEngine, files: Record<string, string>, before?: (sourceId: string, root: string) => Promise<void>) {
+ const sourceId = `i${randomUUID().replace(/-/g, '').slice(0, 20)}`;
+ const root = join(home, sourceId); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ for (const [path, body] of Object.entries(files)) {
+ if (body === IMAGE) copyFileSync(IMAGE, join(root, path)); else writeFileSync(join(root, path), body);
+ }
+ const head = commit(root, 'initial');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [sourceId, root]);
+ await before?.(sourceId, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { sourceId, root, head };
+}
+async function lastCommit(engine: BrainEngine, sourceId: string): Promise<string | null> {
+ const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ return source.last_commit;
+}
+async function heldPaths(engine: BrainEngine, sourceId: string) {
+ const [holds] = await readGitSourceHolds(engine, { sourceIds: [sourceId] });
+ return (holds?.holds ?? []).map(hold => [hold.path, hold.code]).sort();
+}
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('#5493 managed sync with multimodal embedding on', () => {
+ test('a committed image is held on first and incremental sync; the Markdown imports and the checkpoint advances', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ for (const engine of engines) {
+ const { sourceId, root, head } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/photo.png': IMAGE });
+
+ const preview = await performManagedSync(engine, { sourceId, noPull: true, dryRun: true });
+ expect(preview.would_hold?.map(item => [item.path, item.code])).toEqual([['notes/photo.png', CODE]]);
+
+ const first = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(first.status).toBe('first_sync');
+ expect(first.added).toBe(1);
+ expect(first.held_count).toBe(1);
+ expect(first.held?.map(item => [item.path, item.code, item.stale])).toEqual([['notes/photo.png', CODE, false]]);
+ expect(first.held![0].docs).toBe(`docs/guides/write-refusals.md#${CODE}`);
+ expect(await engine.getPage('notes/plain', { sourceId })).not.toBeNull();
+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2', [sourceId, 'notes/photo.png'])).toEqual([]);
+ expect(await lastCommit(engine, sourceId)).toBe(head);
+ expect(await heldPaths(engine, sourceId)).toEqual([['notes/photo.png', CODE]]);
+ const lines: string[] = [];
+ printHoldNotes(first, line => lines.push(line));
+ expect(lines.some(line => line.startsWith(` Held notes/photo.png: ${CODE}`))).toBe(true);
+
+ copyFileSync(IMAGE, join(root, 'notes', 'second.webp'));
+ writeFileSync(join(root, 'notes', 'later.md'), '---\ntitle: Later\n---\nA note committed after the first sync.\n');
+ const next = commit(root, 'incremental');
+ const incremental = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(incremental.status).toBe('synced');
+ expect(incremental.held?.map(item => [item.path, item.code])).toEqual([['notes/second.webp', CODE]]);
+ expect(await engine.getPage('notes/later', { sourceId })).not.toBeNull();
+ expect(await lastCommit(engine, sourceId)).toBe(next);
+ expect(await heldPaths(engine, sourceId)).toEqual([['notes/photo.png', CODE], ['notes/second.webp', CODE]]);
+ }
+ }), 180_000);
+
+ test('held images are re-screened later: on change, on retry-held, and released when they leave the source', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ for (const engine of engines) {
+ const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/a.png': IMAGE, 'notes/b.png': IMAGE });
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).held_count).toBe(2);
+
+ writeFileSync(join(root, 'notes', 'a.png'), 'changed image bytes');
+ commit(root, 'change image');
+ const changed = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(changed.held?.map(item => item.path)).toEqual(['notes/a.png']);
+
+ const [holds] = await readGitSourceHolds(engine, { sourceIds: [sourceId] });
+ await requestGitHoldRetry(engine, sourceId, holds!.incarnation, ['notes/b.png']);
+ const retried = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(retried.held?.map(item => item.path)).toEqual(['notes/b.png']);
+
+ git(root, 'rm', '-q', 'notes/a.png');
+ commit(root, 'remove image');
+ await performManagedSync(engine, { sourceId, noPull: true });
+ expect(await heldPaths(engine, sourceId)).toEqual([['notes/b.png', CODE]]);
+ }
+ }), 180_000);
+
+ test('deleting or renaming an image deletes its page; the renamed-to path is held', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ for (const engine of engines) {
+ const { sourceId, root } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/old.png': IMAGE, 'notes/moved.png': IMAGE },
+ async (id, dir) => {
+ for (const path of ['notes/old.png', 'notes/moved.png']) expect((await importImageFile(engine, join(dir, path), path, { sourceId: id, noEmbed: true })).error).toBeUndefined();
+ });
+ const live = async (path: string) => (await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL', [sourceId, path])).length;
+ const first = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(first.status).toBe('first_sync');
+ expect(first.held?.map(item => [item.path, item.stale])).toEqual([['notes/moved.png', true], ['notes/old.png', true]]);
+ expect([await live('notes/old.png'), await live('notes/moved.png')]).toEqual([1, 1]);
+
+ git(root, 'rm', '-q', 'notes/old.png');
+ commit(root, 'remove image');
+ await performManagedSync(engine, { sourceId, noPull: true, full: true });
+ expect([await live('notes/old.png'), await live('notes/moved.png')]).toEqual([0, 1]);
+ expect(await heldPaths(engine, sourceId)).toEqual([['notes/moved.png', CODE]]);
+
+ git(root, 'mv', 'notes/moved.png', 'notes/archived.png');
+ const next = commit(root, 'rename image');
+ const renamed = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(renamed.status).toBe('synced');
+ expect(renamed.held?.map(item => [item.path, item.code])).toEqual([['notes/archived.png', CODE]]);
+ expect(await lastCommit(engine, sourceId)).toBe(next);
+ }
+ }), 180_000);
+
+ test('image holds are incomplete coverage, not a generator fault: they never escalate the sync result or doctor', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ for (const engine of engines) {
+ await engine.setConfig('sync.hold_escalate_count', '1');
+ try {
+ const { sourceId } = await managedSource(engine, { 'notes/plain.md': NOTE, 'notes/a.png': IMAGE, 'notes/b.png': IMAGE, 'notes/c.png': IMAGE });
+ const result = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(result.held_count).toBe(3);
+ expect(result.holds_escalated).toBeUndefined();
+ const check = await gitHeldFilesCheck(engine, [sourceId]);
+ expect(check.status).toBe('warn');
+ expect((check.details as { held: number }).held).toBe(3);
+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.hold_escalate_count'"); }
+ }
+ }), 180_000);
+});
diff --git a/test/persistence-sync-company.serial.test.ts b/test/persistence-sync-company.serial.test.ts
index 5159be2ea0..1660238b18 100644
--- a/test/persistence-sync-company.serial.test.ts
+++ b/test/persistence-sync-company.serial.test.ts
@@ -35,13 +35,14 @@ const check = (name: string, run: (engine: BrainEngine) => Promise<void>) => tes
withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined }, async () => {
for (const { engine } of stores) await run(engine);
}), 120_000);
-async function input(engine: BrainEngine, managed: boolean) {
+async function input(engine: BrainEngine, managed: boolean, extra: Record<string, string> = {}) {
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [managed]);
const root = mkdtempSync(join(home, 'source-')), git = await makeGitFixture(root);
for (const [path, content] of Object.entries({
'people/operator.md': '---\ntype: person\ntitle: Example Operator\n---\n# Example Operator\nOwns the account.\n',
'customers/account.md': '---\ntype: customer\ntitle: Example Account\nowner: "[[people/operator]]"\naudience: internal\n---\n# Example Account\nA synthetic account.\n',
+ ...extra,
})) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), content); }
git.commitAll('Add approved synthetic source');
const plan = await inspectCompanyBrain({ path: root, profile: 'company-brain' });
@@ -120,6 +121,19 @@ check('legacy company consent retry preserves the approved manifest and original
expect(await engine.executeRaw("SELECT id FROM persistence_effects WHERE source_id=$1 AND kind='embedding'", [f.sourceId])).toEqual([]);
});
+// #5493: the company inspection already lists an image as unsupported, so managed discovery neither refuses nor holds it.
+check('a company source with an image and multimodal embedding on syncs without an image hold', async engine => {
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ const f = await input(engine, true, { 'customers/logo.png': 'not decoded' });
+ expect(await connectCompanyBrain(engine, f)).toMatchObject({ ok: true, receipt: { outcome: 'complete' } });
+ const result = await performSync(engine, { sourceId: f.sourceId, full: true });
+ expect(result.status).not.toBe('blocked_by_failures');
+ expect(result.held).toBeUndefined();
+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2', [f.sourceId, 'customers/logo.png'])).toEqual([]);
+ });
+ await disposePersistenceConsumer(engine);
+});
+
for (const phase of ['admitted', 'complete']) for (const caller of ['explicit', 'job']) {
check(`${caller} cancellation during a real ${phase} company profile read preserves every receipt`, async engine => {
const f = await input(engine, true);