Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): on-commit sync in the resident serve and a commit-to-searchable freshness metric (#6858 ask 6, option C)

garrytand20e5c019ce7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1089d28226..7c3b39b671 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A managed brain can now make a commit searchable in seconds, and every managed source reports how long that takes.** Until now a commit reached search only when the next scheduled sync ran, which on a managed brain could be most of an hour. Turn on `sync.on_commit` and `gbrain serve` notices the commit within about 3 seconds, waits 3 more for the commit burst to settle, and runs one managed sync for that source. The setting is off by default, so nothing changes until you turn it on.
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| a commit to a managed source while `gbrain serve` runs, with `sync.on_commit` on | searchable after the next scheduled sync | searchable about 5 to 15 s later (notice, 3 s debounce, the page write) |
+| the same, with `sync.on_commit` off (the default) | the next scheduled sync | unchanged |
+| with `sync.on_commit` on, a commit that lands while a sync is running | (no on-commit sync) | gets one more sync when the running one ends, unless that sync already took it |
+| `gbrain sync status --source <id>` | no latency figure | a `freshness` line, and a `freshness` block in `--json`: p50 and p95 of commit→searchable and commit→embedded over the last 24 h |
+| `gbrain status` | no latency figure | one freshness line per managed source |
+| `gbrain doctor` | nothing about latency | a new check, `managed_sync_latency`, that reports the numbers; it warns over the target and fails over an hour only when `sync.on_commit` is on or `sync.freshness_target_seconds` is set |
+
+### What to do
+
+To turn it on, run `gbrain config set sync.on_commit true` on the brain host. The serve picks it up within 30 seconds; no restart is needed. Change the latency target with `gbrain config set sync.freshness_target_seconds <seconds>` (default 300). Nothing is rewritten on upgrade and there is no migration.
+
+### Itemized changes
+
+- New `src/core/serve-head-watcher.ts`, started next to the movement watch in `gbrain serve` (stdio). With `sync.on_commit` on it polls `git rev-parse HEAD` in the checkout of each managed source this host owns every 3 s (`GBRAIN_SERVE_HEAD_POLL_MS`, 1 to 30 s), with an `fs.watch` on the git directory that only brings the next poll forward, debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the existing `startDelegatedSync` as this host's CLI writer. It never starts beside a running delegated sync or a held drain lease, skips a commit the source has already synced, resumes a resumable stop up to three times, never writes into the checkout or `.git`, and logs each distinct error once. With the setting off it makes no git call. `gbrain serve --http` does not run it yet.
+- New `src/core/persistence/sync-freshness.ts`: commit→searchable and commit→embedded p50/p95 per managed source from existing columns (the commit's committer time from git, `persistence_requests.completed_at` of committed `managed_sync_import` receipts, `content_chunks.embedded_at`). First syncs and working-tree entries are not counted; a run that spans several commits is dated by its newest. No schema change.
+- New config keys `sync.on_commit` and `sync.freshness_target_seconds` (tunables in `src/core/sync-config-keys.ts`).
+- New doctor check `managed_sync_latency` (`src/commands/doctor/checks/managed-sync-latency.ts`); the doctor goldens are regenerated for it.
+- Tests: `test/serve-head-watcher.test.ts` (debounce, single flight, follow-up, resume cap, error handling, stop), `test/serve-head-watcher-managed.serial.test.ts` (a real managed source on PGLite and Postgres: a commit becomes searchable with no manual sync), `test/sync-freshness-6858.test.ts` (percentiles, exclusions, doctor thresholds, the additive `sync status --json` block). The two database tests are listed in `test/postgres-unit-arms.txt`.
+
## [0.60.271.0] - 2026-10-16
**A page write no longer waits behind a sync group that an idle managed sync started in the moment it was being claimed.** While a managed sync drains with lanes, the lanes can sit idle between groups. If an agent's page write arrived just then and its own process was still claiming it, the drain skipped the write and started the next sync group, so the write waited for that group: about 730 ms instead of about 60 ms in the test traces. The FIFO claim now holds that group back, as the lane-head claim already did. The sync still gets one group after each such write commits, so a stream of writes cannot stall it. Three flaky tests on master are fixed with it.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index eb8fe8e613..7ab12f077f 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -40,3 +40,4 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/since.ts` — #6712 PR 2: `parseSince(input, flag, now)`, the one `--since` parser (`gbrain agent logs --since`, `gbrain repair file-drift --since`). An age (`90s`, `30m`, `12h`, `7d`) becomes one concrete UTC instant at parse time; an ISO-8601 date or timestamp is normalized; anything else throws `invalid_params` naming the flag. Callers print and hash the instant, never the age. Tests: `test/sync-exits-l4-6712.test.ts`, `test/agent-cli.test.ts`.
- `src/core/persistence/sync-ghosts.ts` — #6712 PR 2: `countSyncGhosts(engine, sourceId)`, the post-sync ghost count. It reuses `scanGhostSource` from `repair/ghost-pages.ts` (no second classifier) with a candidate bound of `SYNC_GHOST_CHECK_LIMIT` (50) stats, leaves out paths sync holds (a held file is the hold's to explain), and returns the count, samples and the `gbrain repair ghost-pages --source <id>` preview as its fix. Sync never deletes or tombstones a ghost; `commands/sync/perform.ts` prints one line and sets `SyncResult.ghostPages`. Test: `test/sync-exits-l4-6712.test.ts`.
- `src/core/persistence/soak-counters.ts` — #6712 PR 2: the soak counters doctor `sync_soak_counters` reports (one `op_checkpoints` row per UTC day under op `sync-soak-counters`). Interventions: `sync_non_plain` (`nonPlainSyncFlags`, from `sync/run.ts`), `repair_apply` (`repair.ts`), `unblock_apply` (`sync/operator.ts`), `retry_held` (`sources-retry-held.ts`) and `needs_human` (`sweepNeedsHumanHolds`, run after each managed sync: stamps `needs_human_at` on a hold the fault table now calls `needs_human` and counts it once; the stamp survives same-code re-holds). Content decisions: `file_drift_apply` and `file_drift_hold`. `readSoakCounters` sums the last seven days. Counting never fails the command that counts. Test: `test/sync-exits-l4-6712.test.ts`.
+- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (one call site: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/sync-freshness-6858.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 059ff9fae7..b74e3b1a83 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -123,7 +123,8 @@ Timing knobs the drain uses:
`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
- `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`.
+ `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
+ `sync.freshness_target_seconds` ([On-commit sync](#on-commit-sync)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
@@ -208,6 +209,45 @@ Two more tips:
A shell loop around `gbrain sync --source <id> --no-pull` until it prints
`synced` also works; each run drains as far as its deadline allows.
+## On-commit sync
+
+On a managed brain, `gbrain serve` can sync a source as soon as a commit lands
+in its checkout, instead of waiting for the next scheduled sync. It is off by
+default; turn it on with:
+
+```bash
+gbrain config set sync.on_commit true
+```
+
+The serve reads the flag every 30 seconds, so no restart is needed in either
+direction. While it is on, the stdio `gbrain serve` polls `git rev-parse HEAD`
+in the checkout of every managed source this host owns, every 3 seconds
+(`GBRAIN_SERVE_HEAD_POLL_MS`, 1 to 30 s), with a file watch on the git
+directory that only brings the next poll forward. When HEAD has stopped moving
+for 3 seconds (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and differs from what the
+source last synced, the serve runs one managed sync (`--no-pull`) as this
+host's CLI writer. A sync that is already running, here or in another process,
+is never doubled: the commit waits and gets one more sync when that one ends.
+A sync that stops resumable is resumed up to three times. Nothing is written
+into the checkout or `.git`, and an idle poll costs one git call per checkout.
+`gbrain serve --http` does not run the watcher yet.
+
+For a small page, expect a commit to be searchable in about 5 to 15 seconds:
+up to 3 s to notice, the 3 s debounce, then the page write. Embedding follows
+the sync's own embedding path, so commit→embedded is longer.
+
+Each managed source's freshness over the last 24 hours shows in
+`gbrain sync status --source <id>` (the `freshness` block in `--json`) and
+in `gbrain status`: p50 and p95 of commit→searchable (from the commit's
+committer time to the page write's `completed_at`) and commit→embedded (to
+the page's last chunk embedding). A first sync and working-tree entries are not
+counted, and a run that spans several commits is dated by its newest. Doctor
+`managed_sync_latency` warns when p95 commit→searchable is over
+`sync.freshness_target_seconds` (default 300) and fails over one hour; it
+grades only a brain with `sync.on_commit` on or a target set, and otherwise
+reports the numbers. A stopped or stalled sync is reported by doctor
+`managed_sync_not_moving`, not by this check.
+
## Implementation
### Prerequisite: a reachable direct connection
diff --git a/llms-full.txt b/llms-full.txt
index 2138876efa..4ba8be4f59 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6727,7 +6727,8 @@ Timing knobs the drain uses:
`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
- `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`.
+ `sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
+ `sync.freshness_target_seconds` ([On-commit sync](#on-commit-sync)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
@@ -6812,6 +6813,45 @@ Two more tips:
A shell loop around `gbrain sync --source <id> --no-pull` until it prints
`synced` also works; each run drains as far as its deadline allows.
+## On-commit sync
+
+On a managed brain, `gbrain serve` can sync a source as soon as a commit lands
+in its checkout, instead of waiting for the next scheduled sync. It is off by
+default; turn it on with:
+
+```bash
+gbrain config set sync.on_commit true
+```
+
+The serve reads the flag every 30 seconds, so no restart is needed in either
+direction. While it is on, the stdio `gbrain serve` polls `git rev-parse HEAD`
+in the checkout of every managed source this host owns, every 3 seconds
+(`GBRAIN_SERVE_HEAD_POLL_MS`, 1 to 30 s), with a file watch on the git
+directory that only brings the next poll forward. When HEAD has stopped moving
+for 3 seconds (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and differs from what the
+source last synced, the serve runs one managed sync (`--no-pull`) as this
+host's CLI writer. A sync that is already running, here or in another process,
+is never doubled: the commit waits and gets one more sync when that one ends.
+A sync that stops resumable is resumed up to three times. Nothing is written
+into the checkout or `.git`, and an idle poll costs one git call per checkout.
+`gbrain serve --http` does not run the watcher yet.
+
+For a small page, expect a commit to be searchable in about 5 to 15 seconds:
+up to 3 s to notice, the 3 s debounce, then the page write. Embedding follows
+the sync's own embedding path, so commit→embedded is longer.
+
+Each managed source's freshness over the last 24 hours shows in
+`gbrain sync status --source <id>` (the `freshness` block in `--json`) and
+in `gbrain status`: p50 and p95 of commit→searchable (from the commit's
+committer time to the page write's `completed_at`) and commit→embedded (to
+the page's last chunk embedding). A first sync and working-tree entries are not
+counted, and a run that spans several commits is dated by its newest. Doctor
+`managed_sync_latency` warns when p95 commit→searchable is over
+`sync.freshness_target_seconds` (default 300) and fails over one hour; it
+grades only a brain with `sync.on_commit` on or a target set, and otherwise
+reports the numbers. A stopped or stalled sync is reported by doctor
+`managed_sync_not_moving`, not by this check.
+
## Implementation
### Prerequisite: a reachable direct connection
diff --git a/src/commands/doctor/checks/managed-sync-latency.ts b/src/commands/doctor/checks/managed-sync-latency.ts
new file mode 100644
index 0000000000..0a3a1dac7d
--- /dev/null
+++ b/src/commands/doctor/checks/managed-sync-latency.ts
@@ -0,0 +1,60 @@
+/**
+ * managed_sync_latency (#6858 ask 6): the p95 commit→searchable latency of each managed source over the last 24 h
+ * (reader: persistence/sync-freshness.ts, which also reports commit→embedded). It grades only a brain that asked for low
+ * latency, with `sync.on_commit` true or `sync.freshness_target_seconds` set: a p95 over the target (default 300 s)
+ * warns and one over max(1 h, target) fails. Otherwise, with no samples, and on a brain that is not managed it reports
+ * ok with the numbers, so a cron-synced brain sees no new warning. A stopped run belongs to managed_sync_blocked (#6861) and a
+ * run that stopped moving to managed_sync_not_moving; this check reads latency only. Reads the database and runs one
+ * read-only `git log` per sampled source.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { readManagedMode } from '../../../core/persistence/managed-mode.ts';
+import { FRESHNESS_FAIL_SECONDS, formatLatency, readFreshnessTarget, readSyncFreshness, type SourceFreshness } from '../../../core/persistence/sync-freshness.ts';
+import { SYNC_ON_COMMIT_KEY } from '../../../core/sync-config-keys.ts';
+
+const DOCS = 'docs/guides/live-sync.md#on-commit-sync';
+const p95 = (f: SourceFreshness) => f.commit_to_searchable.p95_seconds ?? 0;
+const line = (f: SourceFreshness) => `${f.source_id} (p95 ${formatLatency(f.commit_to_searchable.p95_seconds)}, p50 ${formatLatency(f.commit_to_searchable.p50_seconds)}, ${f.commit_to_searchable.samples} page(s))`;
+
+async function runManagedSyncLatencyCheck(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ try {
+ const engine = connectedEngine(ctx);
+ if (!await readManagedMode(engine)) {
+ checks.push({ name: 'managed_sync_latency', status: 'ok', message: 'Not a managed brain; commit→searchable latency is measured for managed sources only.' });
+ return checks;
+ }
+ const onCommit = /^(1|true|on|yes)$/i.test((await engine.getConfig(SYNC_ON_COMMIT_KEY))?.trim() ?? '');
+ const target = await readFreshnessTarget(engine);
+ const failSeconds = Math.max(FRESHNESS_FAIL_SECONDS, target.seconds);
+ const graded = onCommit || target.explicit;
+ const freshness = await readSyncFreshness(engine);
+ const sampled = freshness.filter(f => f.commit_to_searchable.samples > 0);
+ const details = { graded, on_commit: onCommit, target_seconds: target.seconds, fail_seconds: failSeconds, sources: freshness, docs: DOCS };
+ const failing = sampled.filter(f => p95(f) > failSeconds);
+ const slow = sampled.filter(f => p95(f) > target.seconds);
+ const first = failing[0] ?? slow[0];
+ const fix = first ? agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],
+ `Read-only: shows whether ${first.source_id}'s managed sync is behind, held or stopped, and the next step it names.`, 'managed_sync_latency', { docs: DOCS }) : undefined;
+ if (!sampled.length) {
+ checks.push({ name: 'managed_sync_latency', status: 'ok', details,
+ message: `No commit→searchable samples in the last ${freshness[0]?.window_hours ?? 24} h (no managed sync imported a new commit).` });
+ } else if (graded && failing.length) {
+ checks.push({ name: 'managed_sync_latency', status: 'fail', readiness_state: 'degraded', details, fix,
+ message: `${failing.map(line).join('; ')}: p95 commit→searchable is over ${formatLatency(failSeconds)}. New commits take that long to reach search.` });
+ } else if (graded && slow.length) {
+ checks.push({ name: 'managed_sync_latency', status: 'warn', readiness_state: 'degraded', details, fix,
+ message: `${slow.map(line).join('; ')}: p95 commit→searchable is over the ${formatLatency(target.seconds)} target (sync.freshness_target_seconds).` });
+ } else {
+ checks.push({ name: 'managed_sync_latency', status: 'ok', severity: 'info', details,
+ message: `Commit→searchable over the last 24 h: ${sampled.map(line).join('; ')}${graded ? `, within the ${formatLatency(target.seconds)} target` : '; not graded (sync.on_commit is off and no target is set)'}.` });
+ }
+ } catch (error) {
+ checks.push(checkError('managed_sync_latency', 'read managed sync freshness', error, { details: { health: 'unknown', docs: DOCS } }));
+ }
+ return checks;
+}
+
+export const managedSyncLatencyEntry: DoctorEntry = { name: 'managed_sync_latency', emits: ['managed_sync_latency'], run: runManagedSyncLatencyCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index e0aafeab7f..145f521f98 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -119,6 +119,7 @@ import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';
import { ghostPagesEntry } from './checks/ghost-pages.ts';
import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
+import { managedSyncLatencyEntry } from './checks/managed-sync-latency.ts';
import { atomHeldFailedEntry } from './checks/atom-holds.ts';
import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';
import {
@@ -214,6 +215,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
imageAssetsEntry,
imageEmbeddingCoverageEntry,
syncFreshnessEntry,
+ managedSyncLatencyEntry,
gitConvergenceEntry,
decideHealthEntry,
unlinkedFactsEntry,
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index c948ad15a9..495b2fce5c 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -12,6 +12,7 @@ import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';
+import { startServeHeadWatcher } from '../core/serve-head-watcher.ts';
import { onForwardProgress } from '../core/forward-progress.ts';
import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';
import {
@@ -593,13 +594,16 @@ function installFactsDrain(engine: BrainEngine, opts: ServeOptions, deps: StdioL
/**
* #6317 (B4): the facts drain plus the movement watch (one `[gbrain notice]`
* when a managed source's sync data stops moving; reader in
- * persistence/sync-movement.ts), stopped together at shutdown.
+ * persistence/sync-movement.ts), stopped together at shutdown. #6858 ask 6:
+ * the on-commit HEAD watcher (`sync.on_commit`, core/serve-head-watcher.ts)
+ * stops with them, before shutdownDelegatedSync aborts the sync it started.
*/
function installResidentTickers(engine: BrainEngine, opts: ServeOptions, deps: StdioLifecycleDeps, shuttingDown: () => boolean): { stop(): Promise<void> } {
const factsDrain = installFactsDrain(engine, opts, deps, shuttingDown);
// The watch keeps its own unref'd timer: the injected lifecycle timers are the parent watchdog's and the idle sweep's, which tests count.
const movementWatch: MovementWatch = startMovementWatch(engine, { log: deps.log });
- return { stop: async () => { movementWatch.stop(); await factsDrain?.stop(); } };
+ const headWatcher = startServeHeadWatcher(engine, { log: deps.log });
+ return { stop: async () => { headWatcher.stop(); movementWatch.stop(); await factsDrain?.stop(); } };
}
function installStdioLifecycle(
diff --git a/src/commands/status.ts b/src/commands/status.ts
index 377f9c9f13..67c313d782 100644
--- a/src/commands/status.ts
+++ b/src/commands/status.ts
@@ -53,6 +53,7 @@ import {
readSupervisorEvents,
summarizeCrashes,
} from '../core/minions/handlers/supervisor-audit.ts';
+import { formatSyncFreshness, readSyncFreshness, type SourceFreshness } from '../core/persistence/sync-freshness.ts';
const SCHEMA_VERSION = 1 as const;
@@ -158,6 +159,8 @@ export interface StatusReport {
generated_at: string;
mode: 'local' | 'thin-client';
sync?: SyncStatusReport;
+ /** #6858 ask 6: commit→searchable / commit→embedded latency of each managed source (local mode, with the sync section). */
+ freshness?: SourceFreshness[];
cycle?: CycleSnapshot;
locks?: LockRow[] | { local_only_remote: true };
workers?: WorkerSummary | RemoteWorkersSnapshot | SectionUnavailable | RemoteUnsupported | { local_only_remote: true };
@@ -511,6 +514,12 @@ async function buildLocalReport(
} catch (err) {
warnings.push(`sync section failed: ${(err as Error).message}`);
}
+ try {
+ const freshness = await withSectionDeadline(readSyncFreshness(engine), remaining(), () => { if (!staleSections.includes('sync')) markStale('sync'); });
+ if (freshness?.length) report.freshness = freshness;
+ } catch (err) {
+ warnings.push(`freshness read failed: ${(err as Error).message}`);
+ }
}
if (want('cycle')) {
try {
@@ -657,6 +666,9 @@ export function renderHuman(report: StatusReport): string {
if (report.sync.unacknowledged_failures > 0) {
lines.push(` ${report.sync.unacknowledged_failures} unacknowledged sync failure(s)`);
}
+ for (const f of report.freshness ?? []) {
+ if (f.commit_to_searchable.samples || f.unresolved_commits) lines.push(` freshness ${f.source_id}: ${formatSyncFreshness(f)}`);
+ }
}
lines.push('');
}
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index c12ac5e28a..70ccdedf03 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -101,16 +101,20 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
const { renderNotice } = await import('../../core/agent-output.ts');
const snapshot = await cachedCapacitySnapshot(engine);
const notices = (await capacityNotices(engine, { throttle: false })).map(notice => renderNotice(notice, ctx));
+ // #6858 ask 6: commit→searchable / commit→embedded latency over 24 h (null for a source with no managed binding).
+ const { readSyncFreshness, formatSyncFreshness } = await import('../../core/persistence/sync-freshness.ts');
+ const [freshness = null] = await readSyncFreshness(engine, { sourceIds: [sourceId] }).catch(() => []);
const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };
const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,
checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),
- capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, ...(notices.length ? { notices } : {}) };
+ capacity: { status: snapshot.status, pause_pct: snapshot.pause_pct, low: snapshot.low, paused: snapshot.paused }, freshness, ...(notices.length ? { notices } : {}) };
if (args.includes('--json')) return writeJsonDocument(JSON.stringify(rendered, null, 2));
const c = status.cursor;
console.log(syncStatusHeadline(status));
console.log(` ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`
+ `${c.last_advance_at ? `, last advance ${c.last_advance_at}` : ''}` : 'no managed cursor'}`);
console.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);
+ if (freshness) console.log(` freshness: ${formatSyncFreshness(freshness)}`);
console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);
for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);
if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index c5e65f63de..c10cff8bbc 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear-never-installed', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -118,7 +118,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
+ 'serve': ['--absolute-git-dir', '--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--verify', '--yes'],
'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
@@ -126,10 +126,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
- 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--prefer', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/config.ts b/src/core/config.ts
index 50bfceb191..0043113cac 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1725,6 +1725,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
'sync.bulk',
'sync.bulk_size',
+ // #6858 ask 6: on-commit sync in the resident serve and its freshness target (src/core/sync-config-keys.ts).
+ 'sync.on_commit', 'sync.freshness_target_seconds',
// #6712 PR 2: rollback keys (src/core/sync-config-keys.ts; windows in wire-skew.ts): readable and honored, not tunables.
'sync.job_drain', 'sync.waive_batch', 'sync.foreground_priority',
'sync.lanes', 'persistence.single_write_group', 'persistence.preadmit_cache', // the last two: write-path kill switches (persistence/switches.ts)
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 148417c6c5..c1362211f2 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -176,6 +176,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
// #5984: unfinished managed sync cursors, their remaining entries and indexing ETA.
'managed_sync_backlog',
'sync_freshness',
+ // #6858 ask 6: p95 commit→searchable of managed sources over 24 h (doctor/checks/managed-sync-latency.ts).
+ 'managed_sync_latency',
// #5063: source checkouts with commits not on their upstream or stale uncommitted changes.
'git_convergence',
// #5186: an ownership marker committed to a source checkout's Git index.
diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.ts
new file mode 100644
index 0000000000..458bd71559
--- /dev/null
+++ b/src/core/persistence/sync-freshness.ts
@@ -0,0 +1,134 @@
+/**
+ * #6858 ask 6 (option C): how long a commit takes to become searchable, and embedded, per managed source.
+ *
+ * One sample per committed `managed_sync_import` receipt of the current source incarnation in the window (24 h):
+ * - commit time: the git committer time of the run's pinned target (`intent.target`), read from this host's
+ * checkout (one `git log --no-walk` per source). A run that spans several commits is dated by its newest, so the
+ * sample is a lower bound for the older commits in it. A first sync (`intent.from` null) and a working-tree entry
+ * are not samples: they import history or uncommitted files, not a commit that just landed.
+ * - searchable: the receipt's `completed_at` (the page write committed; search reads it from then on).
+ * - embedded: the newest `content_chunks.embedded_at` of the page's visible chunks, once every one has one (a page with a
+ * chunk still waiting counts as `pending`; a page with no chunks is not an embedding sample). A chunk embedded
+ * before the write committed counts as embedded at the write.
+ * Latencies are clamped at 0 (a committer clock ahead of the database clock). The read uses the partial index
+ * `persistence_requests_sync_watermark` (its predicate is repeated verbatim) and stops after one probe when the window
+ * is empty. Nothing is written. Readers: `gbrain sync status` (the `freshness` block), `gbrain status`, and doctor
+ * `managed_sync_latency` (src/commands/doctor/checks/managed-sync-latency.ts).
+ */
+import type { BrainEngine } from '../engine.ts';
+import { execFileBounded } from '../bounded-child-exec.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { SYNC_FRESHNESS_TARGET_KEY } from '../sync-config-keys.ts';
+import { chunkVisibleFilter } from '../search/safe-chunks.ts';
+
+export const FRESHNESS_WINDOW_HOURS = 24;
+/** The newest distinct targets dated per source; older ones in the window are left out of the sample. */
+export const FRESHNESS_MAX_TARGETS = 200;
+export const DEFAULT_FRESHNESS_TARGET_SECONDS = 300;
+export const FRESHNESS_FAIL_SECONDS = 3600;
+
+export interface LatencyStats { samples: number; p50_seconds: number | null; p95_seconds: number | null }
+export interface SourceFreshness {
+ source_id: string;
+ window_hours: number;
+ commit_to_searchable: LatencyStats;
+ commit_to_embedded: LatencyStats & { pending: number };
+ /** Distinct run targets dated from git. */
+ commits: number;
+ /** Targets in the window git could not date here (no checkout on this host, or the commit is not in it); their pages are not sampled. */
+ unresolved_commits: number;
+}
+
+/** Commit time (unix seconds) of each sha that the checkout at `root` can resolve. */
+export type CommitTimeReader = (root: string, shas: string[]) => Promise<Map<string, number>>;
+
+const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
+const SAMPLE_WHERE = `r.worktree_id=$1::uuid AND r.source_incarnation=$2::uuid AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%'
+ AND r.completed_at > now() - ($3::int * interval '1 hour') AND r.intent->>'kind'='managed_sync_import' AND r.intent->>'from' IS NOT NULL
+ AND COALESCE(r.intent->>'working','false') <> 'true'`;
+
+export const readGitCommitTimes: CommitTimeReader = async (root, shas) => {
+ const out = new Map<string, number>();
+ const run = (args: string[]) => execFileBounded('git', ['-C', root, ...args], { timeout: 10_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ const parse = (stdout: string) => {
+ for (const line of stdout.split('\n')) {
+ const [sha, at] = line.trim().split(' ');
+ if (sha && SHA.test(sha) && Number.isFinite(Number(at))) out.set(sha, Number(at));
+ }
+ };
+ const all = await run(['log', '--no-walk=unsorted', '--format=%H %ct', ...shas]);
+ if (!all.error) { parse(all.stdout); return out; }
+ for (const sha of shas) {
+ const one = await run(['log', '-1', '--format=%H %ct', sha]);
+ if (!one.error) parse(one.stdout);
+ }
+ return out;
+};
+
+const num = (value: unknown): number | null => value === null || value === undefined || !Number.isFinite(Number(value)) ? null : Math.round(Number(value) * 10) / 10;
+
+interface BindingRow { source_id: string; worktree_id: string; source_incarnation: string; root: string | null }
+interface AggregateRow { samples: number | string; s50: unknown; s95: unknown; embedded: number | string; e50: unknown; e95: unknown; pending: number | string }
+
+/** The freshness of every bound managed source (or of `sourceIds`); a source without a binding is omitted. */
+export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?: string[]; commitTimes?: CommitTimeReader } = {}): Promise<SourceFreshness[]> {
+ const { existingLocalHostId } = await import('./identity.ts');
+ const bindings = await engine.executeRaw<BindingRow>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, b.source_incarnation::text AS source_incarnation, COALESCE(h.local_path, s.local_path) AS root
+ FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
+ LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id::text=$2
+ WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null, existingLocalHostId()]);
+ const commitTimes = opts.commitTimes ?? readGitCommitTimes;
+ const out: SourceFreshness[] = [];
+ for (const b of bindings) {
+ const empty: SourceFreshness = { source_id: b.source_id, window_hours: FRESHNESS_WINDOW_HOURS, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },
+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0 };
+ const targets = (await engine.executeRaw<{ target: string }>(`SELECT r.intent->>'target' AS target FROM persistence_requests r WHERE ${SAMPLE_WHERE}
+ GROUP BY 1 ORDER BY max(r.completed_at) DESC LIMIT ${FRESHNESS_MAX_TARGETS}`, [b.worktree_id, b.source_incarnation, FRESHNESS_WINDOW_HOURS]))
+ .map(row => row.target).filter(target => typeof target === 'string' && SHA.test(target));
+ if (!targets.length) { out.push(empty); continue; }
+ const dated = b.root ? await commitTimes(b.root, targets).catch(() => new Map<string, number>()) : new Map<string, number>();
+ const times = Object.fromEntries(targets.filter(t => dated.has(t)).map(t => [t, dated.get(t)!]));
+ const commits = Object.keys(times).length;
+ if (!commits) { out.push({ ...empty, unresolved_commits: targets.length }); continue; }
+ const [row] = await engine.executeRaw<AggregateRow>(`WITH c AS (SELECT key AS target, to_timestamp(value::double precision) AS committed_at FROM jsonb_each_text($4::text::jsonb)),
+ s AS (SELECT r.completed_at, c.committed_at, COALESCE(r.page_id, (SELECT p.id FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug LIMIT 1)) AS page_id
+ FROM persistence_requests r JOIN c ON c.target=r.intent->>'target' WHERE ${SAMPLE_WHERE}),
+ e AS (SELECT s.completed_at, s.committed_at, ch.n, ch.missing, ch.last_at FROM s
+ LEFT JOIN LATERAL (SELECT count(*) AS n, count(*) FILTER (WHERE cc.embedded_at IS NULL) AS missing, max(cc.embedded_at) AS last_at FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
+ WHERE cc.page_id=s.page_id AND ${chunkVisibleFilter('p', 'cc')}) ch ON true),
+ l AS (SELECT GREATEST(0, extract(epoch FROM completed_at - committed_at)) AS searchable,
+ CASE WHEN n > 0 AND missing = 0 THEN GREATEST(0, extract(epoch FROM GREATEST(last_at, completed_at) - committed_at)) END AS embedded,
+ (n > 0 AND missing > 0) AS pending FROM e)
+ SELECT count(*) AS samples, percentile_cont(0.5) WITHIN GROUP (ORDER BY searchable) AS s50, percentile_cont(0.95) WITHIN GROUP (ORDER BY searchable) AS s95,
+ count(embedded) AS embedded, percentile_cont(0.5) WITHIN GROUP (ORDER BY embedded) AS e50, percentile_cont(0.95) WITHIN GROUP (ORDER BY embedded) AS e95,
+ count(*) FILTER (WHERE pending) AS pending FROM l`, [b.worktree_id, b.source_incarnation, FRESHNESS_WINDOW_HOURS, JSON.stringify(times)]);
+ out.push({ ...empty, commits, unresolved_commits: targets.length - commits,
+ commit_to_searchable: { samples: Number(row?.samples ?? 0), p50_seconds: num(row?.s50), p95_seconds: num(row?.s95) },
+ commit_to_embedded: { samples: Number(row?.embedded ?? 0), p50_seconds: num(row?.e50), p95_seconds: num(row?.e95), pending: Number(row?.pending ?? 0) } });
+ }
+ return out;
+}
+
+/** The p95 commit→searchable target in seconds (`sync.freshness_target_seconds`, default 300) and whether it is set explicitly. */
+export async function readFreshnessTarget(engine: BrainEngine): Promise<{ seconds: number; explicit: boolean }> {
+ const raw = (await engine.getConfig(SYNC_FRESHNESS_TARGET_KEY).catch(() => null))?.trim();
+ const value = raw ? Number(raw) : NaN;
+ return Number.isFinite(value) && value > 0 ? { seconds: value, explicit: true } : { seconds: DEFAULT_FRESHNESS_TARGET_SECONDS, explicit: false };
+}
+
+export function formatLatency(value: number | null): string {
+ if (value === null) return '?';
+ if (value < 120) return `${value}s`;
+ if (value < 7200) return `${Math.round(value / 6) / 10}m`;
+ return `${Math.round(value / 360) / 10}h`;
+}
+
+/** One human line per source: `commit→searchable p50 8s, p95 14s (12 page(s), last 24 h); commit→embedded ...`. */
+export function formatSyncFreshness(f: SourceFreshness): string {
+ if (!f.commit_to_searchable.samples) {
+ return `no commit→searchable samples in the last ${f.window_hours} h${f.unresolved_commits ? `, ${f.unresolved_commits} commit(s) not datable from this host's checkout` : ''}`;
+ }
+ const s = f.commit_to_searchable, e = f.commit_to_embedded;
+ return `commit→searchable p50 ${formatLatency(s.p50_seconds)}, p95 ${formatLatency(s.p95_seconds)} (${s.samples} page(s), last ${f.window_hours} h); `
+ + `commit→embedded ${e.samples ? `p50 ${formatLatency(e.p50_seconds)}, p95 ${formatLatency(e.p95_seconds)}` : 'no samples'} (${e.samples} page(s), ${e.pending} pending)`;
+}
diff --git a/src/core/serve-head-watcher.ts b/src/core/serve-head-watcher.ts
new file mode 100644
index 0000000000..b64563cfe4
--- /dev/null
+++ b/src/core/serve-head-watcher.ts
@@ -0,0 +1,304 @@
+/**
+ * #6858 ask 6, option C (Garry's "rec", via GBRA-108): on-commit sync inside the resident serve.
+ *
+ * With `sync.on_commit` true, `gbrain serve` polls `git rev-parse HEAD` in the checkout of every managed source this host
+ * owns (its worktree's `owner_host_id` is this host) every `GBRAIN_SERVE_HEAD_POLL_MS` (default 3 s, 1 to 30 s), plus a
+ * best-effort `fs.watch` on the git dir (and its `logs/`) that only brings the next poll forward; the poll is the source
+ * of truth. A HEAD move arms a trailing debounce (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`, default 3 s, 0 to 60 s); when HEAD
+ * has been still that long and differs from what the source last synced, the watcher starts ONE managed sync through
+ * the unchanged `startDelegatedSync` (`noPull`, background origin, the sync hard deadline) as this host's `cli` writer,
+ * the registration a `gbrain sync` on this host uses.
+ *
+ * Single flight: while any delegated sync runs, or another process holds the source's drain lease, nothing starts and
+ * the move stays pending; when the running sync ends the pending move starts one more sync, and a move during the
+ * watcher's own sync starts exactly one follow-up once it ends (HEAD then differs from the HEAD that sync started at),
+ * so a commit is never left for cron. A sync that ends resumable (deadline or another partial stop) is "not yet
+ * searchable", not a failure: the watcher resumes it after the debounce, up to MAX_RESUMES times in a row, then leaves
+ * it to the next HEAD move or scheduled sync. A refused or failed start is logged and not retried until HEAD moves.
+ *
+ * Cost when idle: one git call per checkout per poll and no database read except the flag (re-read every 30 s, so
+ * flipping `sync.on_commit` needs no restart) and the source list (every 60 s while on). With the flag off nothing
+ * else runs: no git call, no sync. It never writes into the checkout or `.git` (`GIT_OPTIONAL_LOCKS=0`). Every error
+ * is caught and logged once per distinct message; the loop never throws into serve. serve.ts starts it beside the
+ * movement watch (installResidentTickers) and stops it before shutdownDelegatedSync.
+ */
+import { randomUUID } from 'node:crypto';
+import { existsSync, watch as fsWatch } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from './engine.ts';
+import { execFileBounded } from './bounded-child-exec.ts';
+import { gitChildEnv } from './git-env.ts';
+import { SYNC_ON_COMMIT_KEY } from './sync-config-keys.ts';
+
+export const HEAD_POLL_MS_DEFAULT = 3_000;
+export const HEAD_DEBOUNCE_MS_DEFAULT = 3_000;
+export const HEAD_FLAG_EVERY_MS = 30_000;
+export const HEAD_LIST_EVERY_MS = 60_000;
+/** Resumable syncs in a row the watcher resumes on its own before it leaves the source to the next move or cron. */
+export const MAX_RESUMES = 3;
+const NUDGE_MS = 250;
+const LOG_ONCE_CAP = 200;
+
+export interface WatchedSource { sourceId: string; root: string; gitDir: string | null; lastCommit: string | null }
+export type OnCommitStart = { jobId: string } | { busy: true } | { refused: string };
+export interface OnCommitJobStatus { state: 'running' | 'aborting' | 'done' | 'error'; outcome?: 'synced' | 'resumable' | 'blocked'; reason?: string; error?: string }
+
+export interface ServeHeadWatcherOptions {
+ log: (line: string) => void;
+ pollMs?: number;
+ debounceMs?: number;
+ env?: Record<string, string | undefined>;
+ now?: () => number;
+ setInterval?: (fn: () => void, ms: number) => unknown;
+ clearInterval?: (handle: unknown) => void;
+ setTimeout?: (fn: () => void, ms: number) => unknown;
+ clearTimeout?: (handle: unknown) => void;
+ readFlag?: () => Promise<boolean>;
+ listSources?: () => Promise<WatchedSource[]>;
+ /** The source's last synced commit (`sources.last_commit`), re-read right before a start. */
+ lastCommit?: (sourceId: string) => Promise<string | null>;
+ revParse?: (root: string) => Promise<string>;
+ syncRunning?: () => boolean | Promise<boolean>;
+ drainHeld?: (sourceId: string) => Promise<boolean>;
+ startSync?: (sourceId: string) => Promise<OnCommitStart>;
+ jobStatus?: (jobId: string) => OnCommitJobStatus | null;
+ watch?: (gitDir: string, onChange: () => void) => (() => void) | null;
+}
+
+export interface ServeHeadWatcher { tick(): Promise<void>; stop(): void; readonly enabled: boolean }
+
+interface SourceState extends WatchedSource { head: string | null; movedAt: number | null; synced: string | null; resumes: number }
+
+const truthy = (value: string | null | undefined) => typeof value === 'string' && /^(1|true|on|yes)$/i.test(value.trim());
+const bounded = (raw: string | undefined, fallback: number, min: number, max: number) => {
+ const value = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : fallback;
+};
+const short = (sha: string | null) => sha ? sha.slice(0, 8) : 'none';
+
+async function git(root: string, args: string[]): Promise<string> {
+ const r = await execFileBounded('git', ['-C', root, ...args], { timeout: 5_000, env: gitChildEnv({ GIT_OPTIONAL_LOCKS: '0' }) });
+ if (r.error) throw new Error((r.stderr || r.error.message).trim().split('\n')[0] || 'git failed');
+ return r.stdout.trim();
+}
+
+function defaultDeps(engine: BrainEngine): Required<Pick<ServeHeadWatcherOptions, 'readFlag' | 'listSources' | 'lastCommit' | 'revParse' | 'syncRunning' | 'drainHeld' | 'startSync' | 'jobStatus' | 'watch'>> {
+ let runner: typeof import('./serve-sync-runner.ts') | null = null;
+ const loadRunner = async () => runner ??= await import('./serve-sync-runner.ts');
+ return {
+ readFlag: async () => truthy(await engine.getConfig(SYNC_ON_COMMIT_KEY)),
+ listSources: async () => {
+ const { readManagedMode } = await import('./persistence/managed-mode.ts');
+ if (!await readManagedMode(engine)) return [];
+ const { existingLocalHostId } = await import('./persistence/identity.ts');
+ const host = existingLocalHostId();
+ if (!host) return [];
+ const rows = await engine.executeRaw<{ source_id: string; root: string; last_commit: string | null }>(`SELECT b.source_id, h.local_path AS root, s.last_commit
+ FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation AND NOT s.archived
+ JOIN persistence_worktrees w ON w.id=b.worktree_id JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id
+ WHERE w.owner_host_id::text=$1 ORDER BY b.source_id`, [host]);
+ const gitDirs = new Map<string, string | null>();
+ const out: WatchedSource[] = [];
+ for (const row of rows) {
+ if (!gitDirs.has(row.root)) gitDirs.set(row.root, await git(row.root, ['rev-parse', '--absolute-git-dir']).catch(() => null));
+ out.push({ sourceId: row.source_id, root: row.root, gitDir: gitDirs.get(row.root) ?? null, lastCommit: row.last_commit });
+ }
+ return out;
+ },
+ lastCommit: async (sourceId) => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]))[0]?.last_commit ?? null,
+ revParse: (root) => git(root, ['rev-parse', '--verify', '-q', 'HEAD']),
+ syncRunning: async () => (await loadRunner()).isDelegatedSyncRunning(),
+ drainHeld: async (sourceId) => (await (await import('./persistence/sync-lease.ts')).readDrainHolder(engine, sourceId)) !== null,
+ startSync: async (sourceId) => {
+ const r = await loadRunner();
+ const { registerLocalWriter } = await import('./persistence/identity.ts');
+ const local = await registerLocalWriter(engine, 'cli');
+ const { resolveSyncHardDeadline } = await import('./sync-reconcile.ts');
+ const deadline = resolveSyncHardDeadline([], { isTty: false, env: process.env });
+ const timeoutSeconds = deadline ? Math.max(1, Math.round(deadline.deadlineMs / 1000)) : 3600;
+ const start = await r.startDelegatedSync(engine, { sourceId, noPull: true, timeoutSeconds, origin: 'background' }, `on-commit-${randomUUID()}`,
+ { registration: { id: local.id, credential: local.credential, lane: 'cli' } });
+ if (start.ok && start.jobId) return { jobId: start.jobId };
+ if (start.error === 'busy' || start.error === 'shutting_down') return { busy: true };
+ return { refused: String(start.refusal?.message ?? start.error ?? 'refused') };
+ },
+ jobStatus: (jobId) => {
+ const s = runner?.getDelegatedSyncStatus(jobId);
+ if (!s || !s.ok || !s.state) return null;
+ return { state: s.state, ...(s.drain ? { outcome: s.drain.outcome, ...(s.drain.stop_reason ? { reason: s.drain.stop_reason } : {}) } : {}), ...(s.jobError ? { error: s.jobError } : {}) };
+ },
+ watch: (gitDir, onChange) => {
+ const closers: Array<() => void> = [];
+ for (const dir of [gitDir, join(gitDir, 'logs')]) {
+ if (!existsSync(dir)) continue;
+ try {
+ const w = fsWatch(dir, { persistent: false }, () => onChange());
+ w.on('error', () => { try { w.close(); } catch { /* already closed */ } });
+ closers.push(() => w.close());
+ } catch { /* best effort: polling is the source of truth */ }
+ }
+ return closers.length ? () => { for (const close of closers) { try { close(); } catch { /* already closed */ } } } : null;
+ },
+ };
+}
+
+export function startServeHeadWatcher(engine: BrainEngine, opts: ServeHeadWatcherOptions): ServeHeadWatcher {
+ const env = opts.env ?? process.env;
+ const pollMs = opts.pollMs ?? bounded(env.GBRAIN_SERVE_HEAD_POLL_MS, HEAD_POLL_MS_DEFAULT, 1_000, 30_000);
+ const debounceMs = opts.debounceMs ?? bounded(env.GBRAIN_SERVE_HEAD_DEBOUNCE_MS, HEAD_DEBOUNCE_MS_DEFAULT, 0, 60_000);
+ const d = { ...defaultDeps(engine), ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined)) } as ReturnType<typeof defaultDeps> & ServeHeadWatcherOptions;
+ const now = opts.now ?? Date.now;
+ const setTimer = opts.setTimeout ?? ((fn: () => void, ms: number) => { const t = setTimeout(fn, ms); t.unref?.(); return t; });
+ const clearTimer = opts.clearTimeout ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>));
+ const log = (line: string) => { try { opts.log(`[serve-sync] on-commit: ${line}`); } catch { /* logging never breaks the loop */ } };
+ const logged = new Set<string>();
+ const logOnce = (key: string, line: string) => {
+ if (logged.has(key)) return;
+ if (logged.size >= LOG_ONCE_CAP) logged.clear();
+ logged.add(key);
+ log(line);
+ };
+ const guard = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {
+ try { return await fn(); } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ logOnce(`${what}\u0000${message}`, `${what} failed: ${message} (logged once; the watcher keeps polling)`);
+ return fallback;
+ }
+ };
+
+ let enabled = false;
+ let stopped = false;
+ let flagReadAt = -Infinity;
+ let listedAt = -Infinity;
+ let job: { id: string; sourceId: string; head: string } | null = null;
+ const sources = new Map<string, SourceState>();
+ const watchers = new Map<string, () => void>();
+ let fireTimer: unknown = null;
+ let nudgeTimer: unknown = null;
+ let inflight: Promise<void> | null = null;
+ let again = false;
+
+ const closeWatchers = () => { for (const close of watchers.values()) { try { close(); } catch { /* best effort */ } } watchers.clear(); };
+ const armFire = (ms: number) => {
+ if (stopped) return;
+ if (fireTimer !== null) clearTimer(fireTimer);
+ fireTimer = setTimer(() => { fireTimer = null; void tick(); }, ms + 50);
+ };
+ const nudge = () => {
+ if (stopped || nudgeTimer !== null) return;
+ nudgeTimer = setTimer(() => { nudgeTimer = null; void tick(); }, NUDGE_MS);
+ };
+
+ const refreshSources = async () => {
+ const listed = await guard('listing managed sources', d.listSources, null);
+ if (!listed) return;
+ const seen = new Set<string>();
+ for (const s of listed) {
+ seen.add(s.sourceId);
+ const prior = sources.get(s.sourceId);
+ if (prior && prior.root === s.root) { prior.gitDir = s.gitDir; continue; }
+ sources.set(s.sourceId, { ...s, head: null, movedAt: null, synced: s.lastCommit, resumes: 0 });
+ }
+ for (const id of [...sources.keys()]) if (!seen.has(id)) sources.delete(id);
+ const dirs = new Set([...sources.values()].map(s => s.gitDir).filter((dir): dir is string => !!dir));
+ for (const [dir, close] of watchers) if (!dirs.has(dir)) { try { close(); } catch { /* best effort */ } watchers.delete(dir); }
+ for (const dir of dirs) {
+ if (watchers.has(dir)) continue;
+ const close = await guard(`watching ${dir}`, async () => d.watch(dir, nudge), null);
+ if (close) watchers.set(dir, close);
+ }
+ };
+
+ const settle = (j: NonNullable<typeof job>, st: OnCommitJobStatus | null) => {
+ job = null;
+ const s = sources.get(j.sourceId);
+ if (!s) return;
+ if (st?.state === 'done' && st.outcome === 'resumable') {
+ if (++s.resumes <= MAX_RESUMES) {
+ log(`${s.sourceId}: the sync stopped resumable (${st.reason ?? 'partial'}); the commit is not yet searchable, resuming (${s.resumes}/${MAX_RESUMES})`);
+ s.movedAt = now();
+ armFire(debounceMs);
+ return;
+ }
+ log(`${s.sourceId}: still resumable after ${MAX_RESUMES} passes; the next HEAD move or scheduled sync resumes it`);
+ } else if (st?.state === 'error') {
+ logOnce(`job-error\u0000${s.sourceId}\u0000${st.error ?? ''}`, `${s.sourceId}: the sync failed: ${st.error ?? 'unknown error'} (not retried until HEAD moves)`);
+ } else if (st?.state === 'done' && st.outcome === 'blocked') {
+ logOnce(`job-blocked\u0000${s.sourceId}\u0000${st.reason ?? ''}`, `${s.sourceId}: the sync stopped blocked (${st.reason ?? 'unknown'}); see gbrain sync status --source ${s.sourceId} (not retried until HEAD moves)`);
+ }
+ s.resumes = 0;
+ s.synced = j.head;
+ if (s.head && s.head !== j.head) armFire(debounceMs);
+ };
+
+ const step = async () => {
+ const t = now();
+ if (t - flagReadAt >= HEAD_FLAG_EVERY_MS) {
+ flagReadAt = t;
+ const on = await guard('reading sync.on_commit', d.readFlag, enabled);
+ if (on !== enabled) {
+ enabled = on;
+ listedAt = -Infinity;
+ if (!on) { sources.clear(); closeWatchers(); job = null; }
+ log(on ? `enabled (poll ${pollMs} ms, debounce ${debounceMs} ms)` : 'disabled');
+ }
+ }
+ if (!enabled || stopped) return;
+ if (t - listedAt >= HEAD_LIST_EVERY_MS) { listedAt = t; await refreshSources(); }
+ const heads = new Map<string, string | null>();
+ for (const s of sources.values()) {
+ if (!heads.has(s.root)) heads.set(s.root, await guard(`reading HEAD in ${s.root}`, () => d.revParse(s.root), null));
+ const head = heads.get(s.root) ?? null;
+ if (head && head !== s.head) { s.head = head; s.movedAt = t; armFire(debounceMs); }
+ }
+ if (job) {
+ const st = d.jobStatus(job.id);
+ if (st && st.state !== 'done' && st.state !== 'error') return;
+ settle(job, st);
+ }
+ if (stopped) return;
+ const due = [...sources.values()].find(s => s.head && s.head !== s.synced && (s.movedAt === null || now() - s.movedAt >= debounceMs));
+ if (!due || await d.syncRunning()) return;
+ const synced = await guard(`reading the last synced commit of ${due.sourceId}`, () => d.lastCommit(due.sourceId), null);
+ if (synced && synced === due.head) { due.synced = synced; due.resumes = 0; return; }
+ if (await guard(`reading the drain lease of ${due.sourceId}`, () => d.drainHeld(due.sourceId), true)) return;
+ if (stopped) return;
+ const head = due.head!;
+ const start = await guard(`starting a sync of ${due.sourceId}`, () => d.startSync(due.sourceId), null);
+ if (!start) { due.synced = head; return; }
+ if ('busy' in start) return;
+ if ('refused' in start) {
+ logOnce(`refused\u0000${due.sourceId}\u0000${start.refused}`, `${due.sourceId}: the serve refused the sync: ${start.refused} (not retried until HEAD moves)`);
+ due.synced = head;
+ return;
+ }
+ job = { id: start.jobId, sourceId: due.sourceId, head };
+ log(`${due.sourceId}: HEAD moved to ${short(head)} (last synced ${short(due.synced)}); started managed sync job ${start.jobId}`);
+ };
+
+ const tick = (): Promise<void> => {
+ if (stopped) return Promise.resolve();
+ if (inflight) { again = true; return inflight; }
+ inflight = (async () => {
+ do {
+ again = false;
+ try { await step(); } catch (error) { logOnce(`step\u0000${String(error)}`, `unexpected error: ${error instanceof Error ? error.message : String(error)}`); }
+ } while (again && !stopped);
+ })().finally(() => { inflight = null; });
+ return inflight;
+ };
+
+ const interval = (opts.setInterval ?? ((fn: () => void, ms: number) => { const h = setInterval(fn, ms); h.unref?.(); return h; }))(() => { void tick(); }, pollMs);
+ return {
+ tick,
+ get enabled() { return enabled; },
+ stop: () => {
+ if (stopped) return;
+ stopped = true;
+ (opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>)))(interval);
+ if (fireTimer !== null) clearTimer(fireTimer);
+ if (nudgeTimer !== null) clearTimer(nudgeTimer);
+ closeWatchers();
+ },
+ };
+}
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
index 4c8526da63..77151d0729 100644
--- a/src/core/sync-config-keys.ts
+++ b/src/core/sync-config-keys.ts
@@ -13,7 +13,15 @@
import { CONFIG_ROLLBACK_WINDOWS, type ConfigRollbackWindow } from './wire-skew.ts';
export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',
- 'sync.write_through', 'sync.cost_gate_min_usd'] as const;
+ 'sync.write_through', 'sync.cost_gate_min_usd', 'sync.on_commit', 'sync.freshness_target_seconds'] as const;
+
+/**
+ * #6858 ask 6, option C (Garry's "rec", via GBRA-108): a resident serve starts a managed source's sync when its
+ * checkout's HEAD moves (serve-head-watcher.ts). Off by default. `sync.freshness_target_seconds` (default 300) is the
+ * p95 commit→searchable target doctor `managed_sync_latency` grades against (persistence/sync-freshness.ts).
+ */
+export const SYNC_ON_COMMIT_KEY = 'sync.on_commit';
+export const SYNC_FRESHNESS_TARGET_KEY = 'sync.freshness_target_seconds';
export interface RetiredSyncKey {
key: string;
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 70eac0d171..e66498151e 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -175,6 +175,7 @@
" [OK] code_chunk_metadata: All code-page chunks carry symbol metadata",
" [OK] undeclared_db_only_pages: Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: life/events/ atoms/ concepts/ extracts/ dream-cycle-summaries/).",
" [OK] db_only_collector_collision: No configured collectors declare output paths",
+ " [OK] managed_sync_latency: No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
" [OK] tracked_ownership_marker: 1 Git checkout(s) track no ownership marker (markers on disk stay untracked and are denied on push).",
" [OK] decide_health: System One is off (every decide slot is off; nothing is sent).",
" [OK] unlinked_facts: No active facts yet; nothing to link.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 968d5d6d52..19287f1023 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -2277,6 +2277,56 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "notes",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index 2ce1098498..ebdc6a2291 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -2401,6 +2401,73 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "notes",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "plain",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -6318,6 +6385,73 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "notes",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "plain",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 882cacbef5..84dae82d46 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -2405,6 +2405,73 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "notes",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "plain",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -6323,6 +6390,73 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "notes",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ },
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "plain",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 92472188c0..f64fbdf9bb 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2028,6 +2028,39 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 9677738d65..db7cee5c0a 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2084,6 +2084,39 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 4f1243add9..abf5201023 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2088,6 +2088,39 @@
"name": "db_only_collector_collision",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/live-sync.md#on-commit-sync",
+ "fail_seconds": 3600,
+ "graded": false,
+ "on_commit": false,
+ "sources": [
+ {
+ "commit_to_embedded": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "pending": 0,
+ "samples": 0
+ },
+ "commit_to_searchable": {
+ "p50_seconds": null,
+ "p95_seconds": null,
+ "samples": 0
+ },
+ "commits": 0,
+ "source_id": "default",
+ "unresolved_commits": 0,
+ "window_hours": 24
+ }
+ ],
+ "target_seconds": 300
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "No commit→searchable samples in the last 24 h (no managed sync imported a new commit).",
+ "name": "managed_sync_latency",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index a354504bb6..0767fa16a2 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -741,6 +741,10 @@
"category": "ops",
"name": "db_only_collector_collision"
},
+ {
+ "category": "brain",
+ "name": "managed_sync_latency"
+ },
{
"category": "brain",
"name": "git_convergence"
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 097c80d69f..823c3dd7df 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -179,6 +179,7 @@ test/scripts/test-stress-postgres.test.ts
test/search/page-rank-cut.test.ts
test/search/rerank-gate-hybrid.test.ts
test/search/rerank-gate-telemetry.test.ts
+test/serve-head-watcher-managed.serial.test.ts
test/shared-content-freshness.test.ts
test/shared-skills-catalog.test.ts
test/shared-skills-retention-capacity.test.ts
@@ -195,6 +196,7 @@ test/sync-drain-head-blocked-6543.test.ts
test/sync-drain-inpass-stall.test.ts
test/sync-drain-write-capacity.test.ts
test/sync-exits-l4-6712.test.ts
+test/sync-freshness-6858.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
test/sync-full-cursor-slices-6349.test.ts
diff --git a/test/serve-head-watcher-managed.serial.test.ts b/test/serve-head-watcher-managed.serial.test.ts
new file mode 100644
index 0000000000..8672cf6b12
--- /dev/null
+++ b/test/serve-head-watcher-managed.serial.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #6858 ask 6 (option C): a real managed source end to end. The serve-style watcher (default seams: the flag from
+ * config, the owned managed sources from the bindings, `git rev-parse HEAD`, the drain lease, and the unchanged
+ * `startDelegatedSync` with this host's cli registration) picks up a new commit and the page becomes searchable without
+ * any manual sync; the freshness reader then reports commit→searchable for that run. PGLite always; Postgres when
+ * DATABASE_URL is set (test/postgres-unit-arms.txt). Serial: the delegated-sync runner is a module singleton.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+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 { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __resetDelegatedSyncForTests, isDelegatedSyncRunning } from '../src/core/serve-sync-runner.ts';
+import { startServeHeadWatcher } from '../src/core/serve-head-watcher.ts';
+import { readSyncFreshness } from '../src/core/persistence/sync-freshness.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-on-commit-'));
+const engines: Array<{ name: string; engine: BrainEngine }> = [];
+const sources: string[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+function commit(root: string, file: string, body: string): string {
+ writeFileSync(join(root, file), body);
+ git(root, 'add', '.');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', `add ${file}`);
+ return git(root, 'rev-parse', 'HEAD');
+}
+async function fixture(engine: BrainEngine): Promise<{ id: string; root: string }> {
+ const id = `oncommit-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ commit(root, 'notes/alice-example.md', '---\ntitle: Alice Example\n---\nAlice Example keeps the acme-example ledger.\n');
+ 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,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+async function until(what: string, fn: () => Promise<boolean>, timeoutMs = 150_000, lines: string[] = []): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!(await fn())) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}; watcher log: ${JSON.stringify(lines)}`);
+ await Bun.sleep(100);
+ }
+}
+const searchable = async (engine: BrainEngine, word: string, slug: string) =>
+ (await engine.searchKeyword(word, { limit: 20 })).some(r => r.slug === slug);
+
+beforeAll(async () => {
+ // An earlier file in the same process may have run a serve shutdown, which leaves the runner refusing starts.
+ __resetDelegatedSyncForTests();
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push({ name: 'pglite', engine: lite });
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push({ name: 'postgres', engine: pg.engine }); closePostgres = pg.close; }
+}, 120_000);
+afterEach(() => { __resetDelegatedSyncForTests(); });
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { engine } of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ if (engine.kind === 'pglite') await engine.disconnect();
+ }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('with sync.on_commit on, a new commit becomes searchable without a manual sync, and freshness reports it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { name, engine } of engines) {
+ const f = await fixture(engine);
+ const first = git(f.root, 'rev-parse', 'HEAD');
+ await engine.setConfig('sync.on_commit', 'true');
+ const lines: string[] = [];
+ const watcher = startServeHeadWatcher(engine, { log: line => lines.push(line), pollMs: 200, debounceMs: 200 });
+ try {
+ await until(`${name}: the first sync`, async () => searchable(engine, 'ledger', 'notes/alice-example'), 150_000, lines);
+ await until(`${name}: the first sync to settle`, async () => !isDelegatedSyncRunning()
+ && (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0]?.last_commit === first);
+ const head = commit(f.root, 'notes/acme-example.md', '---\ntitle: Acme Example\n---\nAcme Example ships the quarterly zeppelin report.\n');
+ await until(`${name}: the commit to become searchable`, async () => searchable(engine, 'zeppelin', 'notes/acme-example'));
+ await until(`${name}: the sync to settle`, async () => !isDelegatedSyncRunning()
+ && (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0]?.last_commit === head);
+ expect(lines.filter(l => l.includes('started managed sync job')).length).toBeGreaterThanOrEqual(2);
+ expect(lines.some(l => /failed|refused/.test(l))).toBe(false);
+ expect(git(f.root, 'status', '--porcelain')).toBe('');
+ const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });
+ expect(fresh).toMatchObject({ source_id: f.id, window_hours: 24, commits: 1, unresolved_commits: 0 });
+ expect(fresh!.commit_to_searchable.samples).toBe(1);
+ expect(fresh!.commit_to_searchable.p50_seconds).toBeGreaterThanOrEqual(0);
+ expect(fresh!.commit_to_searchable.p95_seconds!).toBeLessThan(600);
+ } finally {
+ watcher.stop();
+ await engine.setConfig('sync.on_commit', 'false');
+ await until(`${name}: the runner to idle`, async () => !isDelegatedSyncRunning(), 60_000);
+ }
+ }
+}), 400_000);
diff --git a/test/serve-head-watcher.test.ts b/test/serve-head-watcher.test.ts
new file mode 100644
index 0000000000..65bb553c46
--- /dev/null
+++ b/test/serve-head-watcher.test.ts
@@ -0,0 +1,196 @@
+/**
+ * #6858 ask 6 (option C): the serve's on-commit HEAD watcher (src/core/serve-head-watcher.ts), driven through its
+ * seams with a fake clock: no timers fire on their own, each test calls `tick()`. What it protects:
+ * - `sync.on_commit` off: no git call and no sync, and flipping it on takes effect at the next flag read;
+ * - a burst of HEAD moves inside the debounce starts one sync, at the last HEAD;
+ * - a commit during the watcher's own sync starts exactly one follow-up once that sync ends;
+ * - while another sync runs or another process holds the drain lease, the move waits and fires afterwards;
+ * - a resumable stop is resumed up to MAX_RESUMES times, then left to the next move;
+ * - errors never leave the loop and are logged once per distinct message; stop() halts polling.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { MAX_RESUMES, HEAD_FLAG_EVERY_MS, startServeHeadWatcher, type OnCommitJobStatus, type ServeHeadWatcherOptions } from '../src/core/serve-head-watcher.ts';
+
+const sha = (c: string) => c.repeat(40);
+const A = sha('a'), B = sha('b'), C = sha('c'), D = sha('d');
+
+function harness(over: Partial<ServeHeadWatcherOptions> = {}, init: { head?: string; dbCommit?: string | null; flag?: boolean } = {}) {
+ const s = { t: 1_000_000, head: init.head ?? A, dbCommit: init.dbCommit === undefined ? A : init.dbCommit, flag: init.flag ?? true, running: false, held: false,
+ git: 0, flagReads: 0, starts: [] as Array<{ id: string; jobId: string }>, jobs: new Map<string, OnCommitJobStatus>(), lines: [] as string[], intervalCleared: false };
+ const w = startServeHeadWatcher({} as BrainEngine, {
+ log: line => s.lines.push(line), pollMs: 3000, debounceMs: 3000,
+ now: () => s.t,
+ setInterval: () => 'interval', clearInterval: () => { s.intervalCleared = true; },
+ setTimeout: () => 'timer', clearTimeout: () => {},
+ readFlag: async () => { s.flagReads++; return s.flag; },
+ listSources: async () => [{ sourceId: 'acme-example', root: '/brains/acme-example', gitDir: null, lastCommit: s.dbCommit }],
+ lastCommit: async () => s.dbCommit,
+ revParse: async () => { s.git++; return s.head; },
+ syncRunning: () => s.running,
+ drainHeld: async () => s.held,
+ startSync: async (id) => { const jobId = `job-${s.starts.length + 1}`; s.starts.push({ id, jobId }); s.jobs.set(jobId, { state: 'running' }); return { jobId }; },
+ jobStatus: (jobId) => s.jobs.get(jobId) ?? null,
+ ...over,
+ });
+ const finish = (jobId: string, status: OnCommitJobStatus = { state: 'done', outcome: 'synced' }, synced?: string) => { s.jobs.set(jobId, status); if (synced) s.dbCommit = synced; };
+ return { w, s, finish, advance: (ms: number) => { s.t += ms; } };
+}
+
+describe('serve HEAD watcher', () => {
+ test('flag off: no git call and no sync; flipping it on takes effect at the next flag read without a restart', async () => {
+ const h = harness({}, { flag: false, head: B });
+ for (let i = 0; i < 5; i++) { await h.w.tick(); h.advance(10_000); }
+ expect(h.s.git).toBe(0);
+ expect(h.s.starts).toEqual([]);
+ expect(h.s.flagReads).toBeGreaterThan(0);
+ expect(h.w.enabled).toBe(false);
+ h.s.flag = true;
+ h.advance(HEAD_FLAG_EVERY_MS);
+ await h.w.tick();
+ expect(h.w.enabled).toBe(true);
+ expect(h.s.git).toBe(1);
+ expect(h.s.lines.some(l => l.includes('on-commit: enabled'))).toBe(true);
+ h.s.flag = false;
+ h.advance(HEAD_FLAG_EVERY_MS);
+ await h.w.tick();
+ expect(h.w.enabled).toBe(false);
+ const git = h.s.git;
+ h.advance(10_000);
+ await h.w.tick();
+ expect(h.s.git).toBe(git);
+ expect(h.s.starts).toEqual([]);
+ });
+
+ test('a HEAD equal to the last synced commit starts nothing; an idle poll is one git call', async () => {
+ const h = harness();
+ for (let i = 0; i < 4; i++) { await h.w.tick(); h.advance(3000); }
+ expect(h.s.git).toBe(4);
+ expect(h.s.starts).toEqual([]);
+ });
+
+ test('a burst of HEAD moves inside the debounce starts one sync, at the last HEAD', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ h.advance(1000); h.s.head = C; await h.w.tick();
+ h.advance(1000); h.s.head = D; await h.w.tick();
+ h.advance(2000); await h.w.tick();
+ expect(h.s.starts).toEqual([]);
+ h.advance(1000); await h.w.tick();
+ expect(h.s.starts.map(x => x.id)).toEqual(['acme-example']);
+ expect(h.s.lines.some(l => l.includes(`HEAD moved to ${D.slice(0, 8)}`))).toBe(true);
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(1);
+ });
+
+ test('a commit during the running sync starts exactly one follow-up after it ends', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(1);
+ h.s.head = C; h.advance(1000); await h.w.tick();
+ h.advance(5000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(1);
+ h.finish('job-1', { state: 'done', outcome: 'synced' }, B);
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(2);
+ h.finish('job-2', { state: 'done', outcome: 'synced' }, C);
+ for (let i = 0; i < 5; i++) { h.advance(3000); await h.w.tick(); }
+ expect(h.s.starts).toHaveLength(2);
+ });
+
+ test('while another sync runs or another process holds the drain lease, the move waits and fires afterwards', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.running = true; h.s.head = B; await h.w.tick();
+ h.advance(10_000); await h.w.tick();
+ expect(h.s.starts).toEqual([]);
+ h.s.running = false; h.s.held = true;
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toEqual([]);
+ h.s.held = false;
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(1);
+ });
+
+ test('a sync that already covered HEAD (cron, or the CLI) is not repeated', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.running = true; h.s.head = B; await h.w.tick();
+ h.s.dbCommit = B; h.s.running = false;
+ h.advance(3000); await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toEqual([]);
+ });
+
+ test('a resumable stop is not yet searchable, not a failure: resumed up to MAX_RESUMES times, then left to the next move', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ for (let i = 0; i < MAX_RESUMES + 3; i++) {
+ h.advance(3000); await h.w.tick();
+ const last = h.s.starts.at(-1);
+ if (last && h.s.jobs.get(last.jobId)?.state === 'running') h.finish(last.jobId, { state: 'done', outcome: 'resumable', reason: 'deadline' });
+ h.advance(10); await h.w.tick();
+ }
+ expect(h.s.starts).toHaveLength(1 + MAX_RESUMES);
+ expect(h.s.lines.filter(l => l.includes('not yet searchable'))).toHaveLength(MAX_RESUMES);
+ expect(h.s.lines.some(l => l.includes(`still resumable after ${MAX_RESUMES} passes`))).toBe(true);
+ expect(h.s.lines.some(l => /failed/.test(l))).toBe(false);
+ h.s.head = C; h.advance(3000); await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ expect(h.s.starts).toHaveLength(2 + MAX_RESUMES);
+ });
+
+ test('errors never leave the loop and are logged once per distinct message; a failed start waits for the next move', async () => {
+ let failGit = true;
+ let failStart = true;
+ let listFails = 1;
+ const h = harness({
+ revParse: async () => { if (failGit) throw new Error('fatal: not a git repository'); return h.s.head; },
+ listSources: async () => { if (listFails-- > 0) throw new Error('connection refused'); return [{ sourceId: 'acme-example', root: '/brains/acme-example', gitDir: null, lastCommit: A }]; },
+ startSync: async () => { if (failStart) throw new Error('writer_lock_unavailable'); return { jobId: 'job-ok' }; },
+ jobStatus: () => ({ state: 'running' }),
+ });
+ await h.w.tick();
+ expect(h.s.lines.filter(l => l.includes('connection refused'))).toHaveLength(1);
+ h.advance(60_000); await h.w.tick();
+ for (let i = 0; i < 3; i++) { h.advance(3000); await expect(h.w.tick()).resolves.toBeUndefined(); }
+ expect(h.s.lines.filter(l => l.includes('not a git repository'))).toHaveLength(1);
+ failGit = false;
+ h.s.head = B; await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ expect(h.s.lines.filter(l => l.includes('writer_lock_unavailable'))).toHaveLength(1);
+ failStart = false;
+ h.advance(3000); await h.w.tick();
+ expect(h.s.lines.some(l => l.includes('job-ok'))).toBe(false);
+ h.s.head = C; h.advance(1); await h.w.tick();
+ h.advance(3000); await h.w.tick();
+ expect(h.s.lines.some(l => l.includes('job-ok'))).toBe(true);
+ });
+
+ test('a refused start is logged once and not retried until HEAD moves', async () => {
+ let starts = 0;
+ const h = harness({ startSync: async () => { starts++; return { refused: 'permission_denied' }; } });
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ for (let i = 0; i < 4; i++) { h.advance(3000); await h.w.tick(); }
+ expect(starts).toBe(1);
+ expect(h.s.lines.filter(l => l.includes('refused the sync: permission_denied'))).toHaveLength(1);
+ });
+
+ test('stop() halts polling', async () => {
+ const h = harness();
+ await h.w.tick();
+ const git = h.s.git;
+ h.w.stop();
+ expect(h.s.intervalCleared).toBe(true);
+ h.s.head = B; h.advance(10_000);
+ await h.w.tick();
+ expect(h.s.git).toBe(git);
+ expect(h.s.starts).toEqual([]);
+ });
+});
diff --git a/test/sync-freshness-6858.test.ts b/test/sync-freshness-6858.test.ts
new file mode 100644
index 0000000000..51e417615e
--- /dev/null
+++ b/test/sync-freshness-6858.test.ts
@@ -0,0 +1,199 @@
+/**
+ * #6858 ask 6: commit→searchable and commit→embedded latency (src/core/persistence/sync-freshness.ts), doctor
+ * `managed_sync_latency` (src/commands/doctor/checks/managed-sync-latency.ts) and the additive `freshness` block of
+ * `gbrain sync status --json`. Fixtures: a claimed managed worktree whose commit carries a chosen committer time, and
+ * committed `managed_sync_import` receipts stamped at chosen `completed_at` values, with pages and chunks for the
+ * embedded side. PGLite always; Postgres when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+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 { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { readSyncFreshness, formatSyncFreshness } from '../src/core/persistence/sync-freshness.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { managedSyncLatencyEntry } from '../src/commands/doctor/checks/managed-sync-latency.ts';
+import { runSyncStatus } from '../src/commands/sync/operator.ts';
+import { renderHuman, type StatusReport } from '../src/commands/status.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-freshness-'));
+const engines: Array<{ name: string; engine: BrainEngine }> = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const FROM = 'f'.repeat(40);
+
+interface Fixture { id: string; root: string; worktreeId: string; incarnation: string; sha: string; committedAt: number }
+/** A managed source whose HEAD commit was made `ageSeconds` ago (committer time). */
+async function managedSource(engine: BrainEngine, ageSeconds: number): Promise<Fixture> {
+ const id = `fresh-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true });
+ const committedAt = Math.floor(Date.now() / 1000) - ageSeconds;
+ const env = { ...process.env, GIT_COMMITTER_DATE: `@${committedAt} +0000`, GIT_AUTHOR_DATE: `@${committedAt} +0000` };
+ execFileSync('git', ['-C', root, 'init', '-q'], { env });
+ writeFileSync(join(root, 'alice-example.md'), '# Alice Example\n');
+ execFileSync('git', ['-C', root, 'add', '.'], { env });
+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes'], { env });
+ const sha = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
+ 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,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const [row] = await engine.executeRaw<{ worktree_id: string; incarnation: string }>(
+ 'SELECT b.worktree_id::text AS worktree_id, b.source_incarnation::text AS incarnation FROM persistence_source_bindings b WHERE b.source_id=$1', [id]);
+ return { id, root, worktreeId: row!.worktree_id, incarnation: row!.incarnation, sha, committedAt };
+}
+/** A committed sync receipt `afterSeconds` after the fixture's commit; `chunks` embeds a page for it (null = a chunk not embedded yet). */
+async function receipt(engine: BrainEngine, f: Fixture, afterSeconds: number, opts: { intent?: Record<string, unknown>; chunks?: Array<number | null> } = {}): Promise<void> {
+ const slug = `notes/${randomUUID().slice(0, 8)}`;
+ const completed = (f.committedAt + afterSeconds) * 1000;
+ let pageId: number | null = null;
+ if (opts.chunks) {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const [page] = await engine.executeRaw<{ id: number }>("INSERT INTO pages(source_id,slug,type,title) VALUES($1,$2,'note',$2) RETURNING id", [f.id, slug]);
+ pageId = page!.id;
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pageId]);
+ for (const [i, at] of opts.chunks.entries()) {
+ await engine.executeRaw('INSERT INTO content_chunks(page_id,chunk_index,chunk_text,embedded_at) VALUES($1,$2,$3,$4::timestamptz)',
+ [pageId, i, `chunk ${i}`, at === null ? null : new Date(completed + at * 1000).toISOString()]);
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ const intent = { kind: 'managed_sync_import', path: `${slug}.md`, target: f.sha, from: FROM, runId: randomUUID(), index: 0, total: 1, ...opts.intent };
+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,page_id,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,state,completed_at)
+ VALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,$4,$5,$6::uuid,'d','{}'::jsonb,$7::text::jsonb,1,16384,'committed',$8::timestamptz)`,
+ [randomUUID(), f.id, f.incarnation, slug, pageId, f.worktreeId, JSON.stringify(intent), new Date(completed).toISOString()]);
+}
+const doctor = async (engine: BrainEngine) => (await managedSyncLatencyEntry.run({ engine } as unknown as Parameters<typeof managedSyncLatencyEntry.run>[0]) as unknown as Array<Record<string, any>>)[0]!;
+async function reset(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw('DELETE FROM persistence_requests');
+ await engine.executeRaw("DELETE FROM config WHERE key IN ('sync.on_commit','sync.freshness_target_seconds')");
+}
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push({ name: 'pglite', engine: lite });
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push({ name: 'postgres', engine: pg.engine }); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { engine } of engines) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ if (engine.kind === 'pglite') await engine.disconnect();
+ }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('sync freshness (#6858 ask 6)', () => {
+ test('no receipts: no samples; doctor ok; a brain that is not managed is skipped', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { engine } of engines) {
+ await reset(engine);
+ const f = await managedSource(engine, 60);
+ const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });
+ expect(fresh).toEqual({ source_id: f.id, window_hours: 24, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },
+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0 });
+ expect(formatSyncFreshness(fresh!)).toBe('no commit→searchable samples in the last 24 h');
+ await engine.setConfig('sync.on_commit', 'true');
+ expect(await doctor(engine)).toMatchObject({ name: 'managed_sync_latency', status: 'ok', message: expect.stringContaining('No commit→searchable samples') });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { expect(await doctor(engine)).toMatchObject({ status: 'ok', message: expect.stringContaining('Not a managed brain') }); }
+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ }
+ }), 120_000);
+
+ test('receipts give p50/p95 commit→searchable and commit→embedded; first syncs, working-tree entries and deletes are not samples', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { name, engine } of engines) {
+ await reset(engine);
+ const f = await managedSource(engine, 3600);
+ await receipt(engine, f, 10, { chunks: [5, 8] });
+ await receipt(engine, f, 20, { chunks: [2] });
+ await receipt(engine, f, 30, { chunks: [1, null] });
+ await receipt(engine, f, 400);
+ await receipt(engine, f, 5, { intent: { from: null } });
+ await receipt(engine, f, 5, { intent: { working: true } });
+ await receipt(engine, f, 5, { intent: { kind: 'managed_sync_delete' } });
+ const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });
+ // searchable: [10, 20, 30, 400] -> p50 25, p95 30 + 0.85 * 370; embedded: [18, 22] (the page waiting on a chunk is pending).
+ expect(fresh, name).toEqual({ source_id: f.id, window_hours: 24, commits: 1, unresolved_commits: 0,
+ commit_to_searchable: { samples: 4, p50_seconds: 25, p95_seconds: 344.5 },
+ commit_to_embedded: { samples: 2, p50_seconds: 20, p95_seconds: 21.8, pending: 1 } });
+ expect(formatSyncFreshness(fresh!)).toBe('commit→searchable p50 25s, p95 5.7m (4 page(s), last 24 h); commit→embedded p50 20s, p95 21.8s (2 page(s), 1 pending)');
+ }
+ }), 120_000);
+
+ test('a commit this checkout cannot date is counted unresolved, not sampled', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { engine } of engines) {
+ await reset(engine);
+ const f = await managedSource(engine, 60);
+ await receipt(engine, f, 10, { intent: { target: 'e'.repeat(40) } });
+ const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });
+ expect(fresh).toMatchObject({ commits: 0, unresolved_commits: 1, commit_to_searchable: { samples: 0 } });
+ }
+ }), 120_000);
+
+ test('doctor grades only with sync.on_commit on or a target set: warn over the target, fail over 1 h', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { engine } of engines) {
+ await reset(engine);
+ const slow = await managedSource(engine, 3600);
+ for (const after of [400, 500, 600]) await receipt(engine, slow, after);
+ const off = await doctor(engine);
+ expect(off).toMatchObject({ status: 'ok', severity: 'info', details: { graded: false, target_seconds: 300 } });
+ expect(off.message).toContain('not graded');
+ await engine.setConfig('sync.on_commit', 'true');
+ const warn = await doctor(engine);
+ expect(warn).toMatchObject({ status: 'warn', details: { graded: true, on_commit: true, target_seconds: 300, fail_seconds: 3600 } });
+ expect(warn.message).toContain(slow.id);
+ expect(warn.fix.argv).toEqual(['gbrain', 'sync', 'status', '--source', slow.id, '--json']);
+ await engine.setConfig('sync.on_commit', 'false');
+ await engine.setConfig('sync.freshness_target_seconds', '900');
+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { graded: true, on_commit: false, target_seconds: 900 } });
+ const stale = await managedSource(engine, 3 * 3600);
+ await receipt(engine, stale, 2 * 3600);
+ const fail = await doctor(engine);
+ expect(fail).toMatchObject({ status: 'fail', details: { graded: true, fail_seconds: 3600 } });
+ expect(fail.message).toContain(stale.id);
+ expect(fail.message).not.toContain(slow.id);
+ }
+ }), 120_000);
+
+ test('sync status --json gains only the freshness block; the human view prints one freshness line', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {
+ for (const { engine } of engines) {
+ await reset(engine);
+ const f = await managedSource(engine, 600);
+ await receipt(engine, f, 12);
+ const capture = async (args: string[]) => {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...a: unknown[]) => { lines.push(a.join(' ')); };
+ try { await runSyncStatus(engine, ['--source', f.id, ...args]); } finally { console.log = log; }
+ return lines;
+ };
+ const json = JSON.parse((await capture(['--json'])).join('\n')) as Record<string, unknown>;
+ const core = await readSyncStatus(engine, f.id, {});
+ const added = Object.keys(json).filter(k => !(k in core)).sort();
+ expect(added).toEqual(['capacity', 'freshness', ...(json.notices ? ['notices'] : [])].sort());
+ expect(json.freshness).toMatchObject({ source_id: f.id, commit_to_searchable: { samples: 1, p50_seconds: 12, p95_seconds: 12 } });
+ const human = await capture([]);
+ expect(human.filter(l => l.startsWith(' freshness: '))).toEqual([' freshness: commit→searchable p50 12s, p95 12s (1 page(s), last 24 h); commit→embedded no samples (0 page(s), 0 pending)']);
+ }
+ }), 120_000);
+
+ test('gbrain status prints one freshness line per managed source with samples, and none for a source without', () => {
+ const sampled = { source_id: 'acme-example', window_hours: 24, commits: 2, unresolved_commits: 0,
+ commit_to_searchable: { samples: 3, p50_seconds: 8, p95_seconds: 14 }, commit_to_embedded: { samples: 3, p50_seconds: 15, p95_seconds: 31, pending: 0 } };
+ const quiet = { ...sampled, source_id: 'alice-example', commits: 0, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },
+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 } };
+ const report = { schema_version: 1, version: 'test', generated_at: '2026-10-16T00:00:00.000Z', mode: 'local',
+ sync: { sources: [{ source_id: 'acme-example', last_sync_at: null, staleness_class: 'fresh', pages: 2, embedding_coverage_pct: 100 }], unacknowledged_failures: 0 },
+ freshness: [sampled, quiet] } as unknown as StatusReport;
+ const lines = renderHuman(report).split('\n').filter(l => l.includes('freshness'));
+ expect(lines).toEqual([' freshness acme-example: commit→searchable p50 8s, p95 14s (3 page(s), last 24 h); commit→embedded p50 15s, p95 31s (3 page(s), 0 pending)']);
+ });
+});