Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(status): oldest unsynced commit grading, classic equivalent and HEAD-only source lag; BEHAVIOR_CHANGES row (GBRA-133 PR 2b.5)

garrytan20c709ae6b71
diff --git a/docs/architecture/key-files/commit-notifier.md b/docs/architecture/key-files/commit-notifier.md
index 2b22b7f532..d9236b7bb4 100644
--- a/docs/architecture/key-files/commit-notifier.md
+++ b/docs/architecture/key-files/commit-notifier.md
@@ -9,6 +9,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.
- `src/core/notifier/status.ts` — what users and agents see, from rows only (no git call): `readSourceFreshness` feeds the `freshness` entry of search and query responses (`src/core/ops/search.ts` `buildRetrievalResponseMeta`; current, behind, syncing, unknown, not_monitored), and `readNotifierBlock` / `formatNotifierBlock` the notifier block for sync status and doctor (resident or none with the `gbrain sync --source <id> --no-pull` fix; remote callers get no trace path, pid or host id). An owner is live by its unexpired lease (Postgres) or a running pid on this host (PGLite). Tests: `test/pathological/s-notifier-freshness-status.test.ts`.
+- `src/core/sync-pending.ts` — GBRA-133 2b.5: the oldest unsynced commit per source and the embedding backlog, read by doctor `managed_sync_latency` and `src/core/source-health.ts`. Behind = checkout HEAD differs from `sources.last_commit` (HEAD only). Dated from the reflog entry that first moved HEAD off `last_commit` (`<git dir>/logs/HEAD` read as a file, last 1 MiB), else the notifier's persisted `first_due_at` (`sync_notifier_sources` while not idle, or a due freshness marker; current incarnation only), else `unknown` with `no_reflog` or `history_rewritten`. `git: false` (a remote doctor) reads the database only; a source the notifier never recorded reads `not_observed`, never current. `readEmbedBacklog` ages live unembedded chunks from `embedding_pending_since` (keyless brains read `disabled`). `managed_sync_latency` grades a waiting commit like a p95 sample (over the target warns, over max(1 h, target) fails, unknown age warns, only with `sync.on_commit` or a target), grades classic sources on a non-managed brain, and reports `details.freshness_by_source` with `keyword_visible` and `embedded` per source (embedded is not graded). Tests: `test/pathological/s-truthful-sync-status.test.ts` + its Postgres twin, `test/sync-freshness-6858.test.ts`.
+
## Autopilot and the jobs worker
In `src/commands/autopilot.ts`: #7003: `--status` passes the daemon's sidecar verdict (`readDaemonStaleAfter`, `src/core/autopilot-heartbeat.ts`) to `classifyAutopilotStatus` as `daemon`; without a matching sidecar it keeps 6 x `--interval`. `--status --json` adds `stale_after_source` and `next_tick_at`. Tests: `test/pathological/s-7003-autopilot-heartbeat.test.ts` + its Postgres twin.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index fd0e1db1bb..33d7761645 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -45,7 +45,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.
-- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`. `loadSyncFreshnessSources(engine)` loads doctor `sync_freshness`'s sync-eligible sources with their upstream observation columns, falling back for brains without them.
+- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `probeSourceGitState` HEAD only (an uncommitted tracked edit is not lag) `? 0 :` the age of the reflog entry that moved HEAD off `last_commit`, else of the commit notifier's persisted `first_due_at`, else wall-clock since `last_sync_at` (GBRA-133 2b.5, `src/core/sync-pending.ts`; the live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)` raised to `first_due_at`'s age, NO git subprocess (trust boundary). Tests: `test/pathological/s-truthful-sync-status.test.ts` + its Postgres twin. `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`. `loadSyncFreshnessSources(engine)` loads doctor `sync_freshness`'s sync-eligible sources with their upstream observation columns, falling back for brains without them.
- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed); `NO_SOURCES = '__none__'` is the explicit no-source legacy-token grant, refused rather than translated. `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.
diff --git a/docs/guides/on-commit-sync.md b/docs/guides/on-commit-sync.md
index b92d901d06..6bd51b57e6 100644
--- a/docs/guides/on-commit-sync.md
+++ b/docs/guides/on-commit-sync.md
@@ -191,8 +191,21 @@ entries are not counted, and a run that spans several commits is dated by its
newest. Doctor managed_sync_latency warns when p95 commit to 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. gbrain doctor --source <id> grades only that source. A stopped or
-stalled sync is reported by doctor managed_sync_not_moving, not by this check.
+numbers. gbrain doctor --source <id> grades only that source.
+
+The check also grades the commit that is still waiting, so a stalled source
+does not read ok for lack of samples. A source is behind when its checkout
+HEAD differs from the last synced commit (an uncommitted edit does not count).
+The wait runs from the reflog entry that moved HEAD (when the commit landed in
+the checkout), or from the commit notifier's recorded first_due_at when there
+is no usable reflog, and is graded with the same target and one-hour limit.
+When neither can date it (no reflog, or history rewritten so the synced commit
+is no longer an ancestor of HEAD), the wait reads unknown and warns. Classic
+sources are graded the same way. Each source reports keyword-visible and
+embedded freshness separately (details.freshness_by_source in --json); the
+embedding backlog is reported, not graded, and reads disabled on a keyless
+brain. gbrain sources status dates a source's lag the same way. A stopped run
+is reported by doctor managed_sync_blocked and managed_sync_not_moving.
The rest of managed sync (backlogs, holds, the drain) is in
[live sync](live-sync.md).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 155b310a47..9d67f0f57c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -974,6 +974,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.316.0', text: 'The autopilot daemon dispatches a freshness sync when a checkout\'s HEAD differs from the commit its source last synced, at the next tick instead of after the 5-minute wall-clock interval (which stays as the backstop), once per HEAD and never in the middle of a rebase or merge; classic and managed sources alike. With `sync.on_commit` on, the daemon also reads every checkout\'s HEAD between ticks (every 3 s, git only; `GBRAIN_AUTOPILOT_HEAD_PROBE_MS`) and queues the sync within seconds.' },
{ since: '0.60.316.0', text: 'On Postgres, `gbrain jobs work` starts a persistence consumer at boot (#7002), so queued persistence effects drain after a `serve` stops even while the worker is idle. It joins the existing election: with `persistence.single_consumer` on it waits beside a live owner and takes over when that owner stops; with the switch off (the default) a worker beside a `serve` runs its own full consumer, as every resident process already does, and doctor `two_consumers_on_host` lists it. A queued sync job now wakes an idle worker at once: LISTEN on a direct session (one extra connection), a 1 s sync-queue read behind a transaction pooler; `GBRAIN_WORKER_SYNC_WAKE=0` turns it off.' },
{ since: '0.60.316.0', text: '`gbrain autopilot --status` grades a running daemon from its own schedule (#7003): the daemon writes `autopilot.heartbeat.json` beside its lock with its next tick, so a healthy daemon on a long adaptive sleep no longer reads `stale` (exit 1); a missing or outdated sidecar falls back to the interval-flag rule. `--status --json` adds `stale_after_source` (`daemon` or `flag`) and `next_tick_at`.' },
+ // GBRA-133 PR 2b (truthful status). `since` is restamped at the merge slot.
+ { since: '0.60.316.0', text: 'Doctor `managed_sync_latency` now grades the commit that is still waiting, not only commits that already synced: with `sync.on_commit` on or `sync.freshness_target_seconds` set, a source whose checkout HEAD has waited past the target (default 300 s) warns and past one hour fails, dated from the reflog entry that moved HEAD or the notifier\'s recorded first_due_at, and a waiting commit it cannot date (no reflog, rewritten history) warns as unknown. It grades classic sources the same way and reports keyword-visible and embedded freshness per source (`details.freshness_by_source`). `gbrain sources status` compares HEAD only (an uncommitted edit is no longer lag) and dates a behind source\'s lag from when the commit landed instead of from the last no-op sync.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */