Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): managed cycles sync local HEAD on pull:true and report upstream freshness honestly (#5255, #5176)
garrytanfc9a100dfd7d
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 09294273c3..37c0b4076f 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.-- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.+- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`. `loadSyncFreshnessSources(engine)` loads doctor `sync_freshness`'s sync-eligible sources with their upstream observation columns, falling back for brains without them.- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex b8eca6089d..d64ef6f769 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).+- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 8fcb687124..1696308092 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -246,6 +246,19 @@ write on, except for pages created while the source was a mirror: those haveno file in the checkout and stay database-only. Git effects of a mirror'swrites (for example a `forget`) complete as skipped. The flag is off by default.+A managed brain never pulls inside a cycle, so a mirror is advanced outside+gbrain and then synced without pulling:++```bash+git -C <checkout> pull --ff-only+gbrain sync --source <id> --no-pull+```++The autopilot cycle syncs the checkout as it is and reports+`upstream_refresh: "skipped_managed"`; `gbrain doctor` (`sync_freshness`) says+"upstream unknown" when the checkout was not fetched in the last 24 hours. See+[`managed_pull_skipped`](write-refusals.md#managed_pull_skipped).+## The git requirement for --path sourcesEvery `--path` source must be a git repository (or live inside one — adiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 50b9f037e7..ed8d00f686 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -62,6 +62,7 @@ of making a duplicate.| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. || <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. || <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |+| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | For a source whose remote is authoritative (it never receives brain writes you need as files), make it a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) once, then advance it and sync without pulling: `gbrain sources mirror-readonly <source> && git -C <checkout> pull --ff-only && gbrain sync --source <source> --no-pull`. The printed `fix` fills in the real source and checkout. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. A coordinated in-gbrain fast-forward refresh is planned; until then this is the supported sequence. |### Other error codesdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex f18e97205a..fd3a9078ff 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.tssrc/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)-src/core/cycle.ts 3189 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder+src/core/cycle.ts 3196 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refreshsrc/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the mergesrc/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesizesrc/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance optiondiff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 259c38adcb..748844daed 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -10,7 +10,7 @@ import type { BrainEngine } from '../../../core/engine.ts';import { probeSourceGitState } from '../../../core/git-head.ts';// v0.41.32.0: remote staleness reads the stored newest_content_at column via// this pure comparator (no git subprocess on the HTTP MCP doctor path).-import { lagFromContentMs, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';+import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../../../core/link-extraction.ts';@@ -25,7 +25,8 @@ import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/syncimport { resolveSourceLocalFilePath } from '../../../core/markdown.ts';import { scannerSlugRootMode } from '../../../core/write-through.ts';import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';-import { isSyncDisabledConfig } from '../../../core/sync-policy.ts';+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';+import { upstreamFreshness } from '../../../core/sync-upstream.ts';import type { Check } from '../../doctor.ts';import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';@@ -1163,30 +1164,6 @@ export async function computeExtractHealthCheck(}}-async function loadSyncFreshnessSources(engine: BrainEngine) {- type FreshnessSourceRow = {- id: string;- name: string;- local_path: string | null;- last_sync_at: Date | null;- last_commit: string | null;- chunker_version: string | null;- newest_content_at: Date | null;- config: unknown;- };- let sources: FreshnessSourceRow[];- try {- sources = await engine.executeRaw<FreshnessSourceRow>(- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,- );- } catch {- sources = await engine.executeRaw<FreshnessSourceRow>(- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config FROM sources WHERE local_path IS NOT NULL`,- );- }- return sources.filter((source) => !isSyncDisabledConfig(source.config));-}-export async function checkSyncFreshness(engine: BrainEngine,opts?: { nowMs?: number; localOnly?: boolean },@@ -1284,6 +1261,10 @@ export async function checkSyncFreshness(// source is judged against the same number (and the env read + warn-once// machinery runs once, not once per source).const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();+ let managed = false;+ try { managed = await managedPersistenceEnabled(engine); } catch { /* pre-persistence brain */ }+ let upstream_unknown_count = 0;+ let upstream_behind_count = 0;for (const source of sources) {if (ownedContent.has(source.id)) { writer_owned_count++; continue; }// Embed source.id in user-visible messages so `gbrain sync --source <id>`@@ -1292,6 +1273,14 @@ export async function checkSyncFreshness(? `'${source.id}' (${source.name})`: `'${source.id}'`;+ // O-DX-8: judged before (and independently of) the local projection buckets below.+ const upstream = upstreamFreshness(source, display, now, managed);+ if (upstream) {+ issues.push(upstream.issue);+ hasWarnings = true;+ if (upstream.state === 'unknown') upstream_unknown_count++; else upstream_behind_count++;+ }+// BUG 4: actively syncing (live lock) → healthy, count as synced_recently// and skip the staleness checks. Keeps the 3-bucket invariant intact.//@@ -1433,7 +1422,8 @@ export async function checkSyncFreshness(}// D6 invariant: every source incremented exactly one bucket.- const details = { unchanged_count, synced_recently_count, stale_count, ...(writer_owned_count ? { writer_owned_count } : {}) };+ const details = { unchanged_count, synced_recently_count, stale_count, ...(writer_owned_count ? { writer_owned_count } : {}),+ ...(upstream_unknown_count ? { upstream_unknown_count } : {}), ...(upstream_behind_count ? { upstream_behind_count } : {}) };// BUG 4: append in-progress context when any source is actively syncing.// Empty otherwise, so steady-state messages are byte-for-byte unchanged.const inProgressNote = (inProgress.length ? `. ${inProgress.join('; ')}` : '')diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 60c06b1f25..6e7cd0dcc0 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -15,6 +15,7 @@ import type { BrainEngine } from '../../core/engine.ts';import { refreshProjectionStatistics } from '../../core/search/projection-statistics.ts';import { withRefreshingLock, LockUnavailableError, LockStolenError, syncLockId } from '../../core/db-lock.ts';import { readSyncAnchor } from '../../core/sync-anchor.ts';+import { recordUpstreamObservation } from '../../core/sync-upstream.ts';import { SyncLockBusyError, formatLockBusyMessage, buildPartialResult } from '../../core/sync-lock.ts';import type { SyncOpts, SyncResult } from '../sync.ts';import { runConnectorSync } from './connector.ts';@@ -30,6 +31,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<if (refresh && (result.pagesAffected.length > 0 || result.deleted > 0)) {await refreshProjectionStatistics(engine);}+ if (refresh && !opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);return result;};const interruptedBeforeWork = async (): Promise<SyncResult> => {@@ -52,7 +54,11 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<if (connector) return connector;}if (opts.signal?.aborted) return finish(await interruptedBeforeWork());- if (managed) return (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);+ if (managed) {+ const result = await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);+ if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);+ return result;+ }const filesystemRoot = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');if (filesystemRoot && !hasSourceFilesystemLock(filesystemRoot)) {let entered = false;diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 314d3a7d19..7a1bad715a 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -52,6 +52,7 @@ import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';import { tryAcquireDbLock, reapDeadHolderLocks, inspectLock, LockStolenError, type DbLockHandle } from './db-lock.ts';import { timeContainedPhase } from './cycle/phase-containment.ts';import { isManagedBrain } from './cycle/phase-table.ts';+import { managedPullWarning, type UpstreamRefresh } from './sync-upstream.ts';import { assertValidSourceId } from './source-id.ts';import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';import { assertEmbedNotStalled } from './embed-stall.ts';@@ -1222,11 +1223,13 @@ async function runPhaseSync(// instead of the global config key. The global key can drift out of// git history (force push, GC) causing a full reimport of all files.const sourceId = await resolveSourceForDir(engine, brainDir);+ // #5255: managed sync refuses `git pull`; a cycle syncs local HEAD and reports it (explicit sync keeps refusing).+ const managedPullSkipped = pull && await isManagedBrain(engine);const result = await performSync(engine, {repoPath: brainDir,sourceId,dryRun,- noPull: !pull,+ noPull: !pull || managedPullSkipped,noEmbed: true, // embed is a separate phasenoExtract: willRunExtractPhase, // dedupe ONLY when cycle's extract phase will also run.// If extract isn't scheduled (e.g. `gbrain dream --phase sync`),@@ -1249,16 +1252,20 @@ async function runPhaseSync(const uncommittedNote = uncommittedTotal > 0? `; ${uncommittedTotal} uncommitted file(s) invisible to commit-driven sync — commit them or set sync.include_working_tree=true`: '';+ const upstreamRefresh: UpstreamRefresh = !pull ? 'not_requested' : managedPullSkipped ? 'skipped_managed' : pullFailedPartial ? 'failed' : 'pulled';+ const warning = managedPullSkipped ? managedPullWarning(sourceId ?? 'default', brainDir) : undefined;+ const upstreamNote = warning ? `; upstream not refreshed (${warning.code}): ${warning.fix} (${warning.docs})` : '';return {phase: 'sync',- status: result.status === 'blocked_by_failures' || pullFailedPartial || uncommittedTotal > 0 ? 'warn' : 'ok',+ status: result.status === 'blocked_by_failures' || pullFailedPartial || uncommittedTotal > 0 || warning ? 'warn' : 'ok',duration_ms: 0,summary: dryRun? `${syncedCount} page(s) would sync, ${result.deleted} would delete`: pullFailedPartial? `git pull failed, nothing imported — source may be behind its remote (sync anchor unchanged)`- : `+${result.added} added, ~${result.modified} modified, -${result.deleted} deleted${uncommittedNote}`,+ : `+${result.added} added, ~${result.modified} modified, -${result.deleted} deleted${uncommittedNote}${upstreamNote}`,details: {+ source_id: sourceId ?? 'default', upstream_refresh: upstreamRefresh, ...(warning ? { warning } : {}),added: result.added,modified: result.modified,deleted: result.deleted,diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 9e81a0b87d..85cd9384bb 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -37,6 +37,7 @@ export const ERROR_CATALOGUE = {repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },+ managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 43e58690e3..e1773e0468 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -28,6 +28,9 @@ CREATE TABLE IF NOT EXISTS sources (contextual_retrieval_mode TEXT,trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT false,newest_content_at TIMESTAMPTZ,+ upstream_checked_at TIMESTAMPTZ,+ upstream_commit TEXT,+ upstream_behind INTEGER,created_at TIMESTAMPTZ NOT NULL DEFAULT now());diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 67b1e1109d..d10e801e15 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -58,6 +58,12 @@ CREATE TABLE IF NOT EXISTS sources (-- of shelling out to git on a DB-supplied local_path, preserving the-- v0.41.27.0 trust boundary. NULL → reader falls back to wall-clock.newest_content_at TIMESTAMPTZ,+ -- #5255/#5176 (O-DX-8): last upstream observation, recorded by sync from the+ -- checkout's Git state (upstream ref, its last fetch/push time, commits the+ -- synced commit lacks). doctor sync_freshness reads it with no subprocess.+ upstream_checked_at TIMESTAMPTZ,+ upstream_commit TEXT,+ upstream_behind INTEGER,created_at TIMESTAMPTZ NOT NULL DEFAULT now());diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 3879d88fb8..38f4f6d928 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -190,6 +190,7 @@ import { v186 } from './v186-decide-proposals.ts';import { v187 } from './v187-fact-relink-attempts.ts';import { v188 } from './v188-facts-ontology-stint-dedup.ts';import { v189 } from './v189-pages-credential-projection-pending.ts';+import { v190 } from './v190-sources-upstream-observation.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -378,4 +379,5 @@ export const MIGRATIONS: Migration[] = [v187,v188,v189,+ v190,];diff --git a/src/core/schema-migrations/v190-sources-upstream-observation.ts b/src/core/schema-migrations/v190-sources-upstream-observation.tsnew file mode 100644index 0000000000..5783000f85--- /dev/null+++ b/src/core/schema-migrations/v190-sources-upstream-observation.ts@@ -0,0 +1,20 @@+import type { Migration } from './types.ts';++// #5255/#5176 (O-DX-8): the last upstream observation per source, recorded by+// sync from the checkout's own Git state (the upstream ref, the time it was+// last fetched or pushed, and how many upstream commits the synced commit+// lacks). doctor sync_freshness reads these columns, so a remote doctor needs+// no subprocess. Not covered by managed_writer_guard: they are observations,+// not checkpoints. ADD COLUMN with a NULL default is metadata-only on both+// engines. Mirror lives in schema.sql (fresh-install path).+// Lane B placeholder number: the fix-wave-8 integrator renumbers it.+export const v190: Migration = {+ version: 190,+ name: 'sources_upstream_observation',+ idempotent: true,+ sql: `+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_checked_at TIMESTAMPTZ;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_commit TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_behind INTEGER;+ `,+};diff --git a/src/core/source-health.ts b/src/core/source-health.tsindex 8955cd3672..e7c15ffe16 100644--- a/src/core/source-health.ts+++ b/src/core/source-health.ts@@ -26,6 +26,7 @@ import type { BrainEngine } from './engine.ts';import { parseSourceConfig, type SourceRow } from './sources-load.ts';import { isSourceUnchangedSinceSync } from './git-head.ts';import { resolveHoursEnv } from './env-number.ts';+import { isSyncDisabledConfig } from './sync-policy.ts';export interface SourceMetrics {source_id: string;@@ -408,3 +409,43 @@ async function jobCountsBySource(engine: BrainEngine): Promise<Map<string, JobStreturn new Map();}}++/**+ * Sync-eligible sources with a local path, for doctor `sync_freshness`,+ * including the upstream observation sync records (#5255, O-DX-8). Older+ * brains without those columns (or without `archived`) still load.+ */+export async function loadSyncFreshnessSources(engine: BrainEngine) {+ type FreshnessSourceRow = {+ id: string;+ name: string;+ local_path: string | null;+ last_sync_at: Date | null;+ last_commit: string | null;+ chunker_version: string | null;+ newest_content_at: Date | null;+ config: unknown;+ upstream_checked_at: Date | null;+ upstream_commit: string | null;+ upstream_behind: number | null;+ };+ const columns = 'id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config';+ let sources: FreshnessSourceRow[];+ try {+ sources = await engine.executeRaw<FreshnessSourceRow>(+ `SELECT ${columns}, upstream_checked_at, upstream_commit, upstream_behind FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,+ );+ } catch {+ const noUpstream = 'NULL AS upstream_checked_at, NULL AS upstream_commit, NULL AS upstream_behind';+ try {+ sources = await engine.executeRaw<FreshnessSourceRow>(+ `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,+ );+ } catch {+ sources = await engine.executeRaw<FreshnessSourceRow>(+ `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL`,+ );+ }+ }+ return sources.filter((source) => !isSyncDisabledConfig(source.config));+}diff --git a/src/core/sync-upstream.ts b/src/core/sync-upstream.tsnew file mode 100644index 0000000000..3116970b20--- /dev/null+++ b/src/core/sync-upstream.ts@@ -0,0 +1,112 @@+/**+ * Upstream observation for remote-tracking sources (#5255/#5176, O-DX-8).+ *+ * Sync records, from the checkout's own Git state, the last time anything+ * observed the upstream (a fetch, pull or push by any process: FETCH_HEAD and+ * the upstream ref's reflog), the upstream commit it saw, and how many of its+ * commits the source's synced commit lacks. doctor `sync_freshness` reads the+ * three `sources.upstream_*` columns, so a remote doctor needs no subprocess.+ * A missing or older-than-24 h observation is "upstream unknown", never fresh.+ */+import { execFileSync } from 'node:child_process';+import { statSync } from 'node:fs';+import type { BrainEngine } from './engine.ts';+import { ERROR_CATALOGUE } from './error-catalogue.ts';+import { sourceConfigHasRemoteUrl } from './sources-load.ts';++export const UPSTREAM_OBSERVATION_MAX_AGE_HOURS = 24;++/** How a cycle's sync phase treated the requested upstream refresh (cycle sync `details.upstream_refresh`). */+export type UpstreamRefresh = 'pulled' | 'failed' | 'skipped_managed' | 'not_requested';++export interface UpstreamObservation { checkedAt: Date; commit: string; behind: number | null }++function git(root: string, args: string[]): string | null {+ try {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;+ } catch {+ return null;+ }+}++function mtime(path: string | null): number {+ if (!path) return 0;+ try { return statSync(path).mtimeMs; } catch { return 0; }+}++/** Whether the checkout's branch tracks an upstream (a `git pull` would have something to refresh). */+export function tracksUpstream(root: string): boolean {+ return git(root, ['rev-parse', '--verify', '-q', '@{upstream}']) !== null;+}++/** Reads the checkout's upstream state; null when it has no upstream or none was ever fetched or pushed. */+export function observeUpstream(root: string, syncedCommit: string | null): UpstreamObservation | null {+ const commit = git(root, ['rev-parse', '--verify', '-q', '@{upstream}^{commit}']);+ const ref = commit && git(root, ['rev-parse', '--symbolic-full-name', '@{upstream}']);+ if (!commit || !ref) return null;+ const checkedMs = Math.max(+ mtime(git(root, ['rev-parse', '--path-format=absolute', '--git-path', 'FETCH_HEAD'])),+ mtime(git(root, ['rev-parse', '--path-format=absolute', '--git-path', `logs/${ref}`])),+ );+ if (checkedMs === 0) return null;+ const count = syncedCommit ? git(root, ['rev-list', '--count', `${syncedCommit}..${commit}`]) : null;+ return { checkedAt: new Date(checkedMs), commit, behind: count === null ? null : Number(count) };+}++/** Best-effort: never fails a sync. Compares the upstream with the source's synced commit as stored after the run. */+export async function recordUpstreamObservation(engine: BrainEngine, sourceId: string, repoPath?: string): Promise<void> {+ try {+ const [source] = await engine.executeRaw<{ local_path: string | null; last_commit: string | null }>(+ 'SELECT local_path,last_commit FROM sources WHERE id=$1', [sourceId]);+ const root = repoPath ?? source?.local_path;+ if (!source || !root) return;+ const observed = observeUpstream(root, source.last_commit);+ if (!observed) return;+ await engine.executeRaw('UPDATE sources SET upstream_checked_at=$2::timestamptz,upstream_commit=$3,upstream_behind=$4 WHERE id=$1',+ [sourceId, observed.checkedAt.toISOString(), observed.commit, observed.behind]);+ } catch {+ // Pre-migration brain or unreadable checkout: freshness stays "upstream unknown".+ }+}++/** The managed refresh sequence: make the source a read-only mirror, fast-forward its checkout, sync without pulling. */+const managedRefreshFix = (sourceId: string, checkout: string) =>+ `gbrain sources mirror-readonly ${sourceId} && git -C ${JSON.stringify(checkout)} pull --ff-only && gbrain sync --source ${sourceId} --no-pull`;++export interface ManagedPullWarning { code: string; cause: string; fix: string; docs: string }++/** #5255: the cycle warn for a skipped pull, only when the checkout tracks an upstream a pull would have refreshed. */+export function managedPullWarning(sourceId: string, checkout: string): ManagedPullWarning | undefined {+ if (!tracksUpstream(checkout)) return undefined;+ return {+ code: ERROR_CATALOGUE.managed_pull_skipped.code,+ cause: 'Managed brains do not run git pull inside a cycle; this sync imported the checkout as it is, so new upstream commits are not in the brain.',+ fix: managedRefreshFix(sourceId, checkout),+ docs: ERROR_CATALOGUE.managed_pull_skipped.docs,+ };+}++/**+ * O-DX-8: doctor's "upstream checked" verdict, separate from "local projection+ * current". A source with a `remote_url` and no observation, or one older than+ * 24 h, is upstream unknown; any source whose last observation saw upstream+ * commits its synced commit lacks is behind. Null when neither applies.+ */+export function upstreamFreshness(+ source: { id: string; local_path: string | null; config: unknown; upstream_checked_at: Date | null; upstream_behind: number | null },+ display: string, now: number, managed: boolean,+): { state: 'unknown' | 'behind'; issue: string } | null {+ const checkedMs = source.upstream_checked_at ? new Date(source.upstream_checked_at).getTime() : null;+ const behind = source.upstream_behind ?? 0;+ const ageHours = checkedMs === null ? null : Math.floor((now - checkedMs) / 3_600_000);+ const unknown = sourceConfigHasRemoteUrl(source.config) && (ageHours === null || ageHours >= UPSTREAM_OBSERVATION_MAX_AGE_HOURS);+ if (!unknown && behind <= 0) return null;+ const fix = managed ? managedRefreshFix(source.id, source.local_path ?? '<checkout>') : `gbrain sync --source ${source.id}`;+ const fact = unknown+ ? `upstream unknown (${ageHours === null ? 'never checked' : `last checked ${ageHours}h ago`})`+ : `upstream ${behind} commit(s) ahead of the synced commit`;+ return {+ state: unknown ? 'unknown' : 'behind',+ issue: `Source ${display} ${fact}; local projection is not proof of freshness. Fix: ${fix} (${ERROR_CATALOGUE.managed_pull_skipped.docs})`,+ };+}diff --git a/src/schema.sql b/src/schema.sqlindex 5b0eb10313..dc1d59c457 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -54,6 +54,12 @@ CREATE TABLE IF NOT EXISTS sources (-- of shelling out to git on a DB-supplied local_path, preserving the-- v0.41.27.0 trust boundary. NULL → reader falls back to wall-clock.newest_content_at TIMESTAMPTZ,+ -- #5255/#5176 (O-DX-8): last upstream observation, recorded by sync from the+ -- checkout's Git state (upstream ref, its last fetch/push time, commits the+ -- synced commit lacks). doctor sync_freshness reads it with no subprocess.+ upstream_checked_at TIMESTAMPTZ,+ upstream_commit TEXT,+ upstream_behind INTEGER,created_at TIMESTAMPTZ NOT NULL DEFAULT now());diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 60478f21d8..a215177ea9 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -2391,9 +2391,12 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",- "15 chunker_version text/text NULL"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",+ "18 chunker_version text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 9cfdfb9eba..582bc7af70 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -2391,9 +2391,12 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",- "15 chunker_version text/text NULL"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",+ "18 chunker_version text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex e290681008..249c2da626 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -2387,9 +2387,12 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",- "15 chunker_version text/text NULL"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()",+ "18 chunker_version text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 1df1435835..0ad8d5f249 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -1827,8 +1827,11 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 9ef54603ca..59c879ddea 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -1827,8 +1827,11 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 88aa7a6f30..338db5dff2 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -1826,8 +1826,11 @@"10 contextual_retrieval_mode text/text NULL","11 trust_frontmatter_overrides boolean/bool NOT NULL DEFAULT false","12 newest_content_at timestamp with time zone/timestamptz NULL",- "13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "14 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"+ "13 upstream_checked_at timestamp with time zone/timestamptz NULL",+ "14 upstream_commit text/text NULL",+ "15 upstream_behind integer/int4 NULL",+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "17 incarnation uuid/uuid NOT NULL DEFAULT gen_random_uuid()"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 0f6cbcd7e6..0ef28d4f7f 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 184,+ "count": 185,"gaps": [17,18,@@ -27,7 +27,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 189,+ "latest": 190,"records": [{"handler": {@@ -2800,6 +2800,19 @@"transaction": "absent","verify": "absent","version": 189+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "sources_upstream_observation",+ "sql": {+ "length": 230,+ "sha256": "ceb897a20d7e90a9a8cb07d6961337edf718671815ff71ff4655a56d125c96a7"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 190}],"versions": [@@ -2986,7 +2999,8 @@186,187,188,- 189+ 189,+ 190]},"normalizer": "migrations-record-v1"diff --git a/test/managed-cycle-pull-upstream.test.ts b/test/managed-cycle-pull-upstream.test.tsnew file mode 100644index 0000000000..d0f8c98111--- /dev/null+++ b/test/managed-cycle-pull-upstream.test.ts@@ -0,0 +1,177 @@+/**+ * #5255 + short half of #5176 (O-CEO-12, O-DX-8, O-ENG-15): a managed cycle+ * asked to pull syncs local HEAD instead of failing with+ * writer_coordinator_required, reports `upstream_refresh: "skipped_managed"`+ * with the safe refresh sequence, and doctor sync_freshness reports upstream+ * freshness separately from the local projection. An explicit sync without+ * --no-pull keeps refusing.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCycle } from '../src/core/cycle.ts';+import { performSync } from '../src/commands/sync.ts';+import { checkSyncFreshness } from '../src/commands/doctor.ts';+import { runMirrorMode } from '../src/commands/sources-mirror.ts';+import { operations } from '../src/core/operations.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { flagRejection, gbrainInvocations, liveCliVerbs } from './helpers/cli-command-surface.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const dirs: string[] = [];++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_url: '' }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+});++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const page = (title: string, body: string) => `---\ntitle: ${title}\ntype: note\n---\n${body}\n`;+function commit(root: string, path: string, content: string) {+ mkdirSync(join(root, path, '..'), { recursive: true });+ writeFileSync(join(root, path), content);+ git(root, 'add', '.'); git(root, 'commit', '-qm', `add ${path}`);+}+const logger = { info() {}, warn() {}, error() {} };+/** O-DX-2: every gbrain command a fix prints resolves and parses with the real CLI's flags. */+function expectRunnableFix(fix: string) {+ const invocations = gbrainInvocations(fix);+ expect(invocations.length).toBeGreaterThan(0);+ for (const inv of invocations) {+ expect(liveCliVerbs().has(inv.verb)).toBe(true);+ expect(flagRejection(inv)).toBeNull();+ }+}++/** A managed brain whose source checkout tracks a bare remote another clone pushes to. */+async function managedRemoteSource(engine: BrainEngine, fn: (s: { sourceId: string; root: string; upstream: string; home: string }) => Promise<void>) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-pull-')); dirs.push(dir);+ const remote = join(dir, 'origin.git'), upstream = join(dir, 'upstream'), root = join(dir, 'brain');+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);+ execFileSync('git', ['clone', '-q', remote, upstream], { stdio: 'ignore' });+ git(upstream, 'checkout', '-q', '-b', 'main');+ commit(upstream, 'notes/first.md', page('First', 'The first synced observation.'));+ git(upstream, 'push', '-q', 'origin', 'main');+ execFileSync('git', ['clone', '-q', remote, root], { stdio: 'ignore' });+ const sourceId = `remote-${Math.random().toString(36).slice(2, 8)}`;+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ 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,$3::text::jsonb)',+ [sourceId, root, JSON.stringify({ remote_url: remote })]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try { await fn({ sourceId, root, upstream, home: join(dir, 'home') }); }+ finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);+ }+ });+}++for (const backend of backends) {+ const engine = () => engines[backends.indexOf(backend)];++ test(`${backend}: runCycle({pull:true}) on a managed brain syncs local HEAD and reports skipped_managed (#5255)`, async () => {+ await managedRemoteSource(engine(), async ({ sourceId, root }) => {+ const report = await runCycle(engine(), { brainDir: root, sourceId, phases: ['sync'], pull: true });+ const sync = report.phases.find(p => p.phase === 'sync')!;+ expect(JSON.stringify(sync)).not.toContain('writer_coordinator_required');+ expect(sync.status).toBe('warn');+ expect(sync.details).toMatchObject({ source_id: sourceId, upstream_refresh: 'skipped_managed', added: 1,+ warning: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' } });+ const warning = (sync.details as { warning: { fix: string; cause: string } }).warning;+ expect(warning.cause.length).toBeGreaterThan(0);+ expect(warning.fix).toContain(`gbrain sources mirror-readonly ${sourceId}`);+ expect(warning.fix).toContain('pull --ff-only');+ expect(warning.fix).toContain(`gbrain sync --source ${sourceId} --no-pull`);+ expectRunnableFix(warning.fix);+ expect((await engine().getPage('notes/first', { sourceId }))?.compiled_truth).toContain('The first synced observation.');+ });+ }, 120_000);++ test(`${backend}: an explicit managed sync without --no-pull keeps refusing (O-ENG-15)`, async () => {+ await managedRemoteSource(engine(), async ({ sourceId, root }) => {+ await expect(performSync(engine(), { repoPath: root, sourceId, noPull: false, noEmbed: true }))+ .rejects.toMatchObject({ code: 'writer_coordinator_required' });+ });+ }, 120_000);++ test(`${backend}: mirror ff-only pull then no-pull sync makes the upstream commit recallable, and doctor splits upstream from local freshness`, async () => {+ await managedRemoteSource(engine(), async ({ sourceId, root, upstream }) => {+ await runMirrorMode(engine(), [sourceId], true);+ await performSync(engine(), { repoPath: root, sourceId, noPull: true, noEmbed: true });+ commit(upstream, 'notes/second.md', page('Second', 'A zebracorn observation pushed upstream.'));+ git(upstream, 'push', '-q', 'origin', 'main');++ git(root, 'pull', '-q', '--ff-only');+ await performSync(engine(), { repoPath: root, sourceId, noPull: true, noEmbed: true });+ const query = operations.find(op => op.name === 'query')!;+ const ctx = { engine: engine(), config: { engine: engine().kind } as never, logger, dryRun: false, remote: false, sourceId };+ expect(JSON.stringify(await query.handler(ctx as never, { query: 'zebracorn', limit: 5, expand: false }))).toContain('notes/second');+ const [observed] = await engine().executeRaw<{ upstream_commit: string; upstream_behind: number; upstream_checked_at: Date }>(+ 'SELECT upstream_commit,upstream_behind,upstream_checked_at FROM sources WHERE id=$1', [sourceId]);+ expect(observed.upstream_commit).toBe(git(upstream, 'rev-parse', 'HEAD'));+ expect(observed.upstream_behind).toBe(0);+ const fresh = await checkSyncFreshness(engine(), { localOnly: true });+ expect(fresh.status).toBe('ok');+ expect(fresh.details).not.toHaveProperty('upstream_unknown_count');++ // Upstream advances, the checkout fetches but does not merge: the local+ // projection is current (HEAD == last_commit) but upstream is behind.+ commit(upstream, 'notes/third.md', page('Third', 'Not merged yet.'));+ git(upstream, 'push', '-q', 'origin', 'main');+ git(root, 'fetch', '-q');+ await performSync(engine(), { repoPath: root, sourceId, noPull: true, noEmbed: true });+ const behind = await checkSyncFreshness(engine(), { localOnly: true });+ expect(behind.status).toBe('warn');+ expect(behind.message).toContain(`'${sourceId}' upstream 1 commit(s) ahead of the synced commit`);+ expect(behind.message).toContain(`gbrain sync --source ${sourceId} --no-pull`);+ expectRunnableFix(behind.message.slice(behind.message.indexOf('Fix: ') + 5));+ expect(behind.details).toMatchObject({ unchanged_count: 1, upstream_behind_count: 1 });++ // Neither fetched nor pulled for over 24 h: upstream unknown, never fresh.+ await engine().executeRaw("UPDATE sources SET upstream_behind=0 WHERE id=$1", [sourceId]);+ const stale = await checkSyncFreshness(engine(), { nowMs: Date.now() + 25 * 3_600_000 });+ expect(stale.status).not.toBe('ok');+ expect(stale.message).toContain(`'${sourceId}' upstream unknown (last checked 25h ago)`);+ expect(stale.details).toMatchObject({ upstream_unknown_count: 1 });+ });+ }, 180_000);++ test(`${backend}: a remote-tracking source with no upstream observation is upstream unknown, not fresh`, async () => {+ const sourceId = `never-${backend}`;+ await engine().executeRaw('INSERT INTO sources(id,name,local_path,config,last_sync_at) VALUES($1,$1,$2,$3::text::jsonb,now())',+ [sourceId, '/example/never-observed', JSON.stringify({ remote_url: 'https://example.invalid/repo.git' })]);+ try {+ const result = await checkSyncFreshness(engine());+ expect(result.status).toBe('warn');+ expect(result.message).toContain(`'${sourceId}' upstream unknown (never checked)`);+ expect(result.details).toMatchObject({ synced_recently_count: 1, upstream_unknown_count: 1 });+ } finally {+ await engine().executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);+ }+ });+}diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex c276d255d0..a8d1553a88 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -419,3 +419,19 @@ for (const phase of ALL_PHASES) {}, 120_000);}}++// #5255: autopilot asks every cycle to pull. On a managed brain the sync phase+// must still import local HEAD (no refusal) and report the skipped refresh.+for (const backend of backends) {+ test(`sync with pull:true on a managed ${backend} brain: writes, upstream_refresh skipped_managed`, async () => {+ await runPhase(engines[backends.indexOf(backend)], 'sync', { ...MATRIX.sync, cycle: { pull: true } }, async ctx => {+ expect(ctx.result.status).not.toBe('fail');+ for (const refusal of REFUSALS) {+ expect(JSON.stringify(ctx.result)).not.toContain(refusal);+ expect(ctx.logs).not.toContain(refusal);+ }+ expect(ctx.result.details?.upstream_refresh).toBe('skipped_managed');+ await MATRIX.sync.assert!(ctx);+ });+ }, 120_000);+}