Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore: GBRA-133 PR 2b integration: key-files part 1 under its cap, sync-run.ts under its ceiling
garrytanc889026471bc
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 4ed2a83967..95e19ec39e 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -61,5 +61,3 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper, consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`). NO dirty/untracked probe in the estimator — pricing dirty files would create phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget, `GIT_OPTIONAL_LOCKS=0` (`git-env.ts` `GIT_READ_ENV`: sync's Git reads never take `index.lock`). Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`. Classic sync reads the same delta as bytes instead: `computeLosslessSyncDelta` / `buildLosslessWorkingTreeManifest` run `git diff --raw -z -M` (and `ls-files -z --others`) into a Buffer and `parseRawDiffZ` keeps each name exactly as Git has it (no trim, no unquoting); a name that is not UTF-8 or holds a control character goes to `unsupported` (present) or `gone` (left the tree) instead of the manifest, and a gitlink (mode 160000) that appears goes to `gitlinks`, never the manifest (seam `_setGitBytesRunnerForTests`). Managed discovery and the cost estimator keep `computeSyncDelta`. Pinned by `test/pathological/s-classic-byte-paths.test.ts`.- `src/core/sync-byte-paths.ts` — classic sync's byte-exact names (GBRA-133). `classifyGitPathBytes` (strict UTF-8 with the BOM kept, no `[\x00-\x1f\x7f]`, else `not_utf8` / `control_character`); the `unsupported_path` hold key `encodeBytePathKey` (`/gbrain-bytes/` + the path with each byte outside a printable UTF-8 character, and `%`, as `%XX`; Git never emits a leading `/`, so it never equals a path) and `decodeBytePathKey` (canonical keys only, else null); `displayBytePath` (C escapes, 200-character cap); `bytePathItemId` (first 16 hex of the bytes' sha256); `bytePathRenameCommand` (printf octal escapes piped NUL-terminated to `xargs -0 git mv`, plain ASCII); `bytePathHoldGone` (lstat of the exact bytes; null for an ordinary key), read by `commands/sync/holds.ts` re-screen and full-sync settle; `unsupportedPathHoldFix`, dispatched by `gitHoldFix` (ask_user rename, argv a read-only `sources status`, then `sync --no-pull`).- `src/commands/sync/unsupported-paths.ts` — classic sync's routing of the lossless delta's extras: `selectBytePaths` applies the manifest's scope / exclude / syncability filters (name probed with U+FFFD for bad bytes and `_` for control characters) and makes paths mode-relative; `holdUnsupportedPaths` writes each `unsupported_path` hold (`writeGitHold`, mode legacy, slug and page null, never gating the bookmark), schedules the holds of `gone` names to clear and prints one `gitlink_not_followed` line; `gitlinkFields` puts `gitlinks_not_followed` on the result (declared on `SyncResult` by module augmentation here) for the run that advances past them.--- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 09ca49bb77..6cad9699fc 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -3,6 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`. GBRA-130 A-18: the module imports `BILLING_MESSAGE_RE`/`RATE_MESSAGE_RE` from the import-free `ai/errors.ts` (still a leaf). `classifyErrorCode(msg, path?)` never reads path text as a provider error: errno-led messages map to `PERMISSION_DENIED` (EACCES/EPERM) or `FILE_UNREADABLE` (ENOENT and other file errnos), and the infra regexes run on the message with the embed envelope, the path and its tokens stripped, so `billing/q3.md` or `http-429.md` no longer read as `EMBEDDING_QUOTA`/`EMBEDDING_RATE_LIMIT`. `syncFailureCode(error, path)` takes the structured errno first (the import paths pass `SyncFailedFile.code`). `SyncGateInput` gains `code`, `imported` and `systemic`: a run where files imported records `infra_isolated_runs` on an open infra row, and `decideGateAction` treats an infra row with `infra_isolated_runs >= threshold` as chronic, auto-skipped with code `EMBEDDING_INFRA_ISOLATED`; a run where nothing imported never counts toward it. A systemic run (the `sync.import_files` ItemRun breaker, most files failing) adds no attempt to open rows, starts new rows at 1, blocks, and `finalize.ts` prints a blocked message naming `--skip-failed`. Pinned by `test/pathological/a18-ledger-path-text.test.ts` (both engines).- `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` — Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Three call sites: the un-syncable cleanup (which passes `opts.sourceId`), and the bare no-`sourceId` delete and rename-source paths; when `sourceId` IS set the delete and rename loops batch through `engine.resolveSlugsByPaths` instead. The `source_path` lookup is scoped to the DEFAULT source on the bare path, matching every write that path performs (`updateSlug`, `deletePage`, the rename bookkeeping repair are all default-scoped) — an unscoped lookup could return a row from another source sharing the `source_path`, and the rename loop consumes this value directly as its cheap-move source slug. Without the helper, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (that path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path.diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex e40ef797c5..e6a1b9a6c5 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1525,9 +1525,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPassertSyncDispatchActive(); stampDrainStep('await_receipt', signal);// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.- // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry. The run's stop signal- // bounds every wait: an aborted run reads the receipt once and returns, and an accepted write it did not see commit- // stays queued under its request id for the next run.+ // #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; the stop signal bounds every wait (awaitWrite).const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000, signal, ...whileHeld });const done = waited.row;assertSyncDispatchActive();