Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/fix-6529

garrytan8ebb05f81403
diff --cc CHANGELOG.md
index 0efd925dbc,f87d752f54..470f79f241
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,17 -10,32 +10,43 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
- ## [0.60.180.0] - 2026-10-12
++## [0.60.182.0] - 2026-10-12
+
+**Image pages on a managed multimodal brain get their image vector (#6529).** With `GBRAIN_EMBEDDING_MULTIMODAL=true`, a managed `gbrain sync` now imports image files through the coordinated image importer instead of holding every one as `managed_image_sync_unsupported`, so the page is created with its OCR text, its image vector and its `source_path` in the same publication; holds from earlier syncs are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. `gbrain embed --stale --images` works on a managed brain (it used to be refused by the legacy writer), finds the image pages whose `source_path` was never recorded through their slug, and a plain `gbrain embed --stale` runs that sweep first on a multimodal install. Doctor's new `image_embedding_coverage` check reports the image pages search cannot see, which `embed_coverage_pct` counted as embedded. No migration; the image vector and OCR text are the paid calls the importer already made for `gbrain import`, now also made at sync and sweep time. Image pages whose file is no longer in the checkout are not re-imported: every sweep names the first path it tried, and the explicit `--images` sweep exits non-zero when it could rebuild nothing.
+
+### Itemized changes
+
+- **Managed sync imports images when multimodal embedding is on.** `freezeEntry` freezes an image entry as its bytes in base64 (binary-safe reads through `readPinnedBytes` / `readBlobBytes`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged; an oversize image takes the `file_too_large` hold), `prepareManagedSyncMutation` routes it to `src/core/persistence/sync-image.ts`, and `prepareManagedSyncImage` runs `importImageFile` with `prepare`, the same coordinated path `gbrain import` uses: the importer decides the hash no-op before any provider call, OCRs and embeds otherwise, `--no-embed` skips both, a company plan refuses, a Git rename publishes the new slug and retires the old page. A screening preparation never pays for an image: the no-op waiver and `unchangedManagedImport` leave image paths to the admitted request, and identical bytes are a no-op by hash. `holdRescreenDue` re-screens a `managed_image_sync_unsupported` hold whenever multimodal embedding is on; with it off the hold's message, fix and the runbook row now say images are held while multimodal embedding is off and name the switch. Tests: `test/managed-sync-images-5493.test.ts` (PGLite and Postgres).
+- **`gbrain embed --stale --images` works on managed brains and reports honestly.** On a managed brain the sweep imports through `importManagedFile` (the coordinated importer), only files inside the source root; a page with a NULL `source_path` is located by its slug (the lower-cased repo-relative path) and the import records the path (`missingSourcePath` in the result). The result carries `missing_samples` (up to 5 `source:slug: no file at <path tried>` lines, the first printed to stderr), and an explicit `--images` sweep whose every candidate lacks a file and that rebuilt nothing counts them as failures, so it exits non-zero instead of 0. Plain `gbrain embed --stale` (no `--slugs`) runs the sweep first on a multimodal install, inside the same cost cap, and folds it into the result as `images`: image import failures count, while fileless image pages are reported (`images.missingFile`, one stderr line naming the first path tried) and leave the exit code to the text run, so a routine `embed --stale` stays green over an out-of-scope backlog of fileless pages; the blocked-projection hint points at that sweep's samples, or at `GBRAIN_EMBEDDING_MULTIMODAL=true` on a text-only install. Tests: `test/embed-stale-images-managed-6529.test.ts`.
+- **Doctor `image_embedding_coverage`.** Counts live image pages, those without an `embedding_image` chunk, those with no recorded `source_path`, and the `managed_image_sync_unsupported` holds; ok with no image pages or with multimodal embedding off (informational), warns on a multimodal install with the counts and the `embed --stale --images` / `sync --no-pull` fix. Read-only. Test: `test/doctor-image-embedding-coverage.test.ts`.
+- **Every image import records `source_path`.** The legacy importer's hash-skip path (`importImageFile` on an unchanged, complete image) now refreshes `source_path` the way the Markdown path does, so a re-import of an older page records the origin it never had. Pages imported before this release keep a NULL `source_path` until the sweep or a sync writes it.
+
+ ## [0.60.180.0] - 2026-10-12
+
+ **When `remember` refuses a forgotten claim, the refusal now says when and how widely it was forgotten.** An agent that re-saves a claim the user forgot gets `fact_withdrawn` as before, and the refusal now carries `withdrawn: { at, subject, visibility }`, where `subject` is the entity the claim was forgotten for or `all_entities`. The agent can tell the user "you asked me to forget that on <date>" instead of retrying. The object rides the immediate refusal, the batch item error, the failed write receipt and `get_write_request`. It covers the exact claim only, the message, code and suggestion are unchanged, and nothing is ever restored.
+
+ ### Itemized changes
+
+ - `src/core/facts/single-prepare.ts` (`factWithdrawnRefusal`): the object comes from the withdrawal ledger only (never a purge): the named entity's withdrawal over `all_entities`, then the newest, among withdrawals whose forgotten rows the caller can read. When it cannot read them, the refusal is the one v0.60.176.0 returns, with no object. `src/core/facts/write-single.ts` applies the same rule, fail-closed when the caller is unknown.
+ - `src/core/ops/contract.ts`, `src/core/agent-output.ts`, `src/core/remember-batch.ts`, `src/core/persistence/verb-errors.ts`: `withdrawn` on `OperationError`, the agent envelope (stdio, HTTP, CLI) and batch item errors.
+ - `src/core/facts/withdrawal.ts`, `src/core/persistence/coordinator.ts`, `src/core/persistence/service.ts`, `src/core/ops/persistence.ts`: a refusal at preparation stores the object in the receipt's versioned `error_detail`, read back by the failed response, replay and `get_write_request`.
+ - `src/core/verbs.ts` (`ERROR_SCHEMA.withdrawn`), the conformance fixture for re-remembering a forgotten claim, the `gbrain errors fact_withdrawn` row, MEMORY_VERBS v1 "remember withdrawn refusal detail (additive)".
+ - Tests: `test/withdrawn-detail.test.ts` (PGLite) and `test/e2e/withdrawn-detail-postgres.test.ts` (Postgres) share `test/helpers/withdrawn-detail-scenarios.ts`; `test/agent-contract-goldens.test.ts` pins one object on stdio, HTTP and CLI.
+
+ ## [0.60.179.0] - 2026-10-12
+
+ **A managed sync cursor can no longer deadlock on its own canonical correction (#6513).** On a live checkout, a pinned import whose sanitization (a fixable fence, reflowed frontmatter) has to rewrite the file used to refuse `source_changed` / `pinned_git_worktree_conflict` ("Canonical sanitization cannot overwrite newer working-tree bytes.") when the file already held newer uncommitted bytes, and that refusal blocked the cursor with no exit: `--retry-failed` replayed the same pin against the same bytes, `sources refresh` refused `sync_in_progress` on the unfinished cursor, `--acknowledge-managed` refused `cursor_unfinished`, and doctor called the cursor `resumable`. The production brain's `default` source went 38 hours without a sync and recurred the same day; the only way out was deleting `op_checkpoints` rows by hand. The refusal is now the `worktree_dirty` hold the other pinned-worktree conflict already earned (#6340): the file is held, the local edit is untouched, the rest of the source syncs and the cursor finishes, so the checkout is movable again; committing the file (or `gbrain sync unblock --source <id> --apply`) imports it with its correction, and a file committed at HEAD meanwhile is re-frozen and imported as HEAD has it. A cursor an older release left blocked this way converts in place on its next `--retry-failed` run, without rediscovery. Working-tree bytes that already *are* the correction (gbrain's own writeback, published before the request that carried it settled) are no longer a conflict: the page imports and the file is left as it is.
+
+ ### Itemized changes
+
+ - **The canonical-writeback refusal holds the page, not the run.** `pinnedWorktreeConflict` (`sync-page-fault.ts`) recognizes the sync-prepare.ts sanitization refusal, so the run's receipt branch, the start-of-run conversion of an older blocked cursor and the `--retry-failed` conversion all turn it into a `worktree_dirty` hold whose message names the canonical correction; the hold carries the pinned blob and the working hash as before, counts attempts, and clears when the file is committed and re-screened.
+ - **An already-applied correction is not a conflict.** When the working-tree bytes hash to exactly the canonical file this import would write, the import proceeds with no file write (`sync-prepare.ts`); any other newer bytes are protected as before.
+ - Tests: `test/managed-sync-page-fault-holds.test.ts` adds the three probes on PGLite and Postgres (live run held and cleared by the commit, already-applied writeback, older blocked cursor converted under `--retry-failed`); each fails on the previous release.
+ - Docs: [write refusals](docs/guides/write-refusals.md#worktree_dirty) describes the new hold case.
+ - **A CLI call that lands while `gbrain serve` is still starting waits for the owner socket instead of failing `owner_unavailable` (`submission_status: not_sent`).** The serve takes the PGLite datastore lock before it binds its persistence socket (the MCP handshake sits in between), so a local command in that window saw a serve holder and no socket. `maybeDelegateLocalOperation` / `maybeDelegateLocalAdministration` now repeat the capability probe for up to 3 s while the same serve holds the lock; a released lock, a different holder or any other transport failure ends the wait at once, and nothing falls through to the engine path. Surfaced as a CI flake in `test/shared-skills-live-cli.test.ts`; probe in `test/persistence-local-client.test.ts` (fails on master).
+
+ Fixes #6513.
+
## [0.60.178.0] - 2026-10-12
**Batch entity lookups respect quarantine.** `entity` with `names` now hides quarantined pages from remote callers the way a single-name `entity` lookup and `get_page` already do, whichever way the name resolves, and a quarantined identity sibling no longer appears beside a page for remote callers, in batch rows or in a single-name card. Trusted local callers see the same results as before. No migration, no paid call.
diff --cc src/core/behavior-change-notice.ts
index ef58505dc3,bc34ae7ce0..f2e57de0c8
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -466,10 -466,10 +466,13 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.177.0', text: 'Fact extraction on explicit lanes (sync import, put_page) now measures same-page rewordings: when a page is re-extracted and a new claim sits within cosine 0.85 of a fact the same page produced earlier without changing a number, date, amount or negation, the run counts it as `would_dedup_same_page` and prints one stderr line naming the matched fact id. Nothing is dropped or expired; the counter exists so the rule\'s false-positive rate can be measured before any automatic dedup ships.' },
{ since: '0.60.177.0', text: 'The atom-extraction phase (`extract_atoms`) now honors a schema pack that declares one of the built-in extractable types (meeting, source, article, video, book, original) as `extractable: false`, the way facts extraction already did: such pages are no longer mined into atoms. gbrain-base declares meeting and source extractable and is unchanged; on gbrain-recommended, `source` pages stop being atom-extracted. A pack that does not mention a built-in type keeps it extractable.' },
// Fix wave 15 group 1 (managed sync authority and data safety).
+ // Cat 40 next wave, Part 3 step 1. `since` is provisional; the integrator restamps it at the merge slot.
+ { since: '0.60.180.0', text: 'A `remember` refused with `fact_withdrawn` now carries an additive `withdrawn` object (`at`, `subject`: the entity slug or `all_entities`, `visibility`) on the immediate refusal, the batch item error, the failed write receipt and `get_write_request`, so an agent can tell the user when and how widely the exact claim was forgotten instead of retrying. The message, code and suggestion are unchanged; the object is absent when the caller cannot read the forgotten rows.' },
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
+ { since: '0.60.179.0', text: 'A managed sync no longer parks forever on a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: the file is held `worktree_dirty` with the rest of the source synced, the cursor finishes, and committing the file (or `gbrain sync unblock --source <id> --apply`) imports it. Before, that refusal (`source_changed` / `pinned_git_worktree_conflict`, "Canonical sanitization cannot overwrite newer working-tree bytes.") blocked the cursor with no exit: `--retry-failed` replayed the same pin, `sources refresh` refused `sync_in_progress` and `--acknowledge-managed` refused `cursor_unfinished`. A cursor an older release left blocked this way converts on its next `--retry-failed` run. Working-tree bytes that already are the correction (gbrain\'s own writeback, published before its request settled) import without a second write.' },
+ // #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.180.0 placeholder) at the merge slot.
+ { since: '0.60.178.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },
+ { since: '0.60.178.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --cc src/core/cli-flag-registry.generated.ts
index ebe7d2994d,5aa2a76d90..0c8dad8811
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -72,7 -72,7 +72,7 @@@ export const CLI_FLAG_REGISTRY: Record<
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
++ 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --cc src/core/persistence/sync-prepare.ts
index 80b10be30b,7a55cb676d..ae135fd9ea
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@@ -316,39 -315,20 +316,53 @@@ async function recordSliceCursor(tx: Br
if (settled) await clearSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions);
else await writeSyncSlice(tx, row.source_id, row.source_incarnation, p.syncOptions, p.slice!);
}
+
+/** The code-file branch of `prepareManagedSyncMutation`: `importCodeFile` with `prepare`, text embedding deferred to `embed --stale` (the image branch is `sync-image.ts`). */
+async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p: { content: string; sourcePath: string; rawHash: string | null; lineEndingOnly?: boolean; companyApproval: boolean },
+ ctx: { snapshot: Snapshot | null; validate: (tx: BrainEngine) => Promise<void>; releaseHold: (tx: BrainEngine) => Promise<void>; clock?: ClaimPhaseClock;
+ refuse: (code: RegistryCode, message: string, cause: string) => OperationError; contentRefusal: (refusal: ContentRefusal) => OperationError }): Promise<PreparedMutation> {
+ const { snapshot, validate, releaseHold, clock, refuse } = ctx;
+ if (p.companyApproval) throw refuse('profile_incompatible', 'Company source approval permits only committed Markdown content.',
+ `A company-brain source imports only committed Markdown, and ${row.slug} is a code file; remove it from the approved revision.`);
+ if (snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && snapshot.page.compiled_truth !== p.content) {
+ throw refuse('source_changed', 'Newer code file bytes disagree with the pinned import.',
+ `The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);
+ }
+ const codeScreen = screenImportContent({ content: p.content, path: p.sourcePath });
+ if (codeScreen.status === 'refused') throw ctx.contentRefusal(codeScreen.refusal);
+ let prepared: PreparedContentImport | undefined;
+ enterClaimStep(clock, 'code_import', undefined, 'db');
+ const result = await importCodeFile(engine, p.sourcePath, p.content, { sourceId: row.source_id, noEmbed: true,
+ prepare: async value => { prepared = value; return value.result; } });
+ if (!prepared || prepared.slug !== row.slug) throw refuse('invalid_params', result.error ?? 'The code file identity could not be prepared.',
+ `The code file could not be prepared as page ${row.slug}.`);
+ const ready = prepared;
+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw refuse('revision_conflict', 'The code page changed during preparation.',
+ `Page ${row.slug} changed while this sync was being prepared.`);
+ return { observedRevision: ready.observedRevision, trust: await ownerImportTrust(engine, row, null, p.sourcePath),
+ validate: async tx => { await validate(tx); await ready.validate(tx); },
+ noop: ready.noop, deferEmbedding: true, apply: async tx => {
+ await ready.apply(tx);
+ await releaseHold(tx);
+ return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
+ chunks: result.chunks, noop: ready.noop, imported_file: true };
+ } };
+}
+
+ /**
+ * Whether the import must rewrite its file with `canonicalFile` (its sanitized form). Working-tree bytes that are the
+ * pinned bytes (or differ only by line endings) take the write; bytes that already are the canonical file need none
+ * (#6513: gbrain's own writeback, published before the request that carried it settled); any other newer bytes are
+ * refused, and the run holds the file `worktree_dirty` (sync-page-fault.ts `pinnedWorktreeConflict`).
+ */
+ function canonicalWritebackNeeded(row: WriteRequest, p: SyncIntent, pinned: string, canonicalFile: string | null): canonicalFile is string {
+ if (canonicalFile === null) return false;
+ if (p.lineEndingOnly || p.rawHash === sha256(pinned)) return true;
+ if (p.rawHash === sha256(canonicalFile)) return false;
+ throw syncPublicationRefusal('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.', row, p,
+ `The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);
+ }
+
export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,
screening?: { unsaved: true }): Promise<PreparedMutation> {
const engine = boundedReads(unbounded, clock);