Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): sync_freshness keeps sync outcome apart from freshness for a source with no successful sync (#4960)

garrytan97c02e1b8a07
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a763f639b9..8ba639e825 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3142,6 +3142,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |
+### sync_first_run_in_progress
+
+<a id="sync_first_run_in_progress"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A source's first sync is running (it holds a live sync lock inside the staleness ceiling) and no successful sync is recorded yet, so doctor sync_freshness warns instead of reading it as fresh. | A sync stamps last_sync_at only when it succeeds; a running sync is not a fresh source, and starting a second one beside it only contends for the lock. Over the staleness ceiling the lock reads as wedged (fail) instead. | Wait for the running sync, then run gbrain doctor --only sync_freshness --json again. | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/guides/troubleshooting.md#sync-freshness-no-successful-sync](../../docs/guides/troubleshooting.md#sync-freshness-no-successful-sync)
+
### sync_in_progress
<a id="sync_in_progress"></a>
@@ -3154,6 +3164,18 @@ Reasons: `candidate_in_flight`, `busy_set_unreadable`.
More: [docs/guides/write-refusals.md#sync_in_progress](../../docs/guides/write-refusals.md#sync_in_progress)
+### sync_no_successful_sync
+
+<a id="sync_no_successful_sync"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| No successful sync is recorded for a source (last_sync_at is NULL) and no sync of it is running; doctor sync_freshness fails with the last attempt's time, result and held files. | The attempt comes from the newest sync job and, on a managed brain, the source's sync status (read-only). `reason` names the state: no_attempt (nothing recorded: run a sync), attempt_queued (a job is queued: wait), holds_pending (held files: inspect them first), last_attempt_unsuccessful (inspect the job or failure, then retry). | Follow the check fix: it waits, inspects holds (gbrain sync status --source <id> --json) or retries (gbrain sync --source <id>) depending on the state. | agent | `gbrain doctor --json` | 1 | no |
+
+Reasons: `no_attempt`, `attempt_queued`, `holds_pending`, `last_attempt_unsuccessful`.
+
+More: [docs/guides/troubleshooting.md#sync-freshness-no-successful-sync](../../docs/guides/troubleshooting.md#sync-freshness-no-successful-sync)
+
### sync_not_applicable
<a id="sync_not_applicable"></a>
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 4252bc1e87..8ba7921957 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -13,6 +13,7 @@
| Symptom | Next step | Who acts | Consent | Verify |
|---|---|---|---|---|
| A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |
+| Doctor `sync_freshness` says a source has "no successful sync recorded" or "first sync running" | follow the check's `fix`: `first sync running` (code `sync_first_run_in_progress`, warn) means wait; `no successful sync recorded` (code `sync_no_successful_sync`, fail) names the last attempt and its `reason`: wait for a queued job, inspect holds (`gbrain sync status --source <id> --json`), or retry (`gbrain sync --source <id>`) ([details](#sync-freshness-no-successful-sync)) | agent | none | `gbrain doctor --only sync_freshness --json` |
| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok |
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
@@ -539,3 +540,31 @@ Automatic event extraction is on by default. See the
three-step check, and the skip codes. `gbrain doctor` reports it as the
`auto_chronicle` check. To turn it off, run
`gbrain config set auto_chronicle false`.
+
+## Sync freshness: no successful sync recorded
+
+<a id="sync-freshness-no-successful-sync"></a>
+
+**Say to your agent:** *"Doctor says my source was never synced, but a sync keeps running. What's going on?"*
+
+A sync stamps a source's `last_sync_at` only when it succeeds, so a source whose
+syncs keep ending `partial` or failing has none, however many pages it imported.
+`gbrain doctor` keeps freshness and sync outcome apart for such a source:
+
+- **First sync running** (`warn`, code `sync_first_run_in_progress`): the source
+ holds a live sync lock inside the staleness ceiling. Running is not fresh, and
+ a second sync only contends for the lock, so the fix is to wait and re-run
+ `gbrain doctor --only sync_freshness --json`. A lock held past the ceiling
+ reads as wedged (`fail`) with its `--break-lock` command.
+- **No successful sync recorded** (`fail`, code `sync_no_successful_sync`): no
+ sync is running. The message names the last attempt, read-only from the newest
+ `sync` job and (on a managed brain) `gbrain sync status`: its time, result
+ (`failed`, `completed (partial)`, a managed error code) and held files, or
+ `no attempt recorded`. `details.no_successful_sync[]` carries each source's
+ `reason` and `fix`:
+ - `attempt_queued`: a sync job is queued or running; wait.
+ - `holds_pending`: files are held; inspect them with
+ `gbrain sync status --source <id> --json` and follow its `next`.
+ - `last_attempt_unsuccessful`: read the job (`gbrain jobs get <id> --json`)
+ or the managed failure, then retry.
+ - `no_attempt`: run `gbrain sync --source <id>` (`--no-pull` on a managed brain).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 03787a67cf..d59f35fd77 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -43,7 +43,7 @@ src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap a
src/core/ops/pages.ts 706 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts)
src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
-src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts
+src/commands/doctor/checks/extraction-sync.ts 1543 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts)
src/core/search/evidence-delivery.ts 1673 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136)
src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index bcfa6b0651..8cb223362b 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -34,6 +34,7 @@ import { isOwnedContentSchemaMissing, ownedContentFreshness } from '../../../cor
import { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';
import { parseSourceConfig } from '../../../core/sources-load.ts';
import { checkError } from '../check-fix.ts';
+import { firstSyncRunning, noSuccessfulSync, type SyncOutcomeEntry } from '../sync-outcome.ts';
import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';
/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */
@@ -1250,6 +1251,8 @@ export async function checkSyncFreshness(
const currentChunkerVersion = chunkerStamp();
const issues: string[] = [];
+ // #4960: sources with no successful sync carry their own state, fix and wording (no generic "run sync" suffix).
+ const outcomes: SyncOutcomeEntry[] = [];
let ownedContent = new Set<string>();
try { ownedContent = new Set((await ownedContentFreshness(engine)).map(source => source.sourceId)); }
catch (error) { if (!isOwnedContentSchemaMissing(error)) throw error; }
@@ -1324,7 +1327,7 @@ export async function checkSyncFreshness(
}
// BUG 4: actively syncing (live lock) → healthy, count as synced_recently
- // and skip the staleness checks. Keeps the 3-bucket invariant intact.
+ // and skip the staleness checks (#4960: a first sync, no success yet, is warn).
//
// ...but ONLY up to the staleness ceiling. `withRefreshingLock` bumps the
// heartbeat on its own timer regardless of whether the import is making
@@ -1337,6 +1340,11 @@ export async function checkSyncFreshness(
const liveSnap = await liveSyncSnap(source.id);
if (liveSnap) {
const ceilingMs = stalenessCeilingSeconds * 1000;
+ if (liveSnap.age_ms <= ceilingMs && !source.last_sync_at) {
+ const first = firstSyncRunning(source.id, display, liveSnap);
+ issues.push(first.issue); outcomes.push(first.entry); hasWarnings = true; stale_count++;
+ continue;
+ }
if (liveSnap.age_ms <= ceilingMs) {
inProgress.push(`${display} sync in progress (pid ${liveSnap.holder_pid} on ${liveSnap.holder_host})`);
synced_recently_count++;
@@ -1358,7 +1366,8 @@ export async function checkSyncFreshness(
}
if (!source.last_sync_at) {
- issues.push(`Source ${display} has never been synced`);
+ const never = await noSuccessfulSync(engine, source.id, display, managed);
+ issues.push(never.issue); outcomes.push(never.entry);
hasFailures = true;
stale_count++;
continue;
@@ -1465,26 +1474,29 @@ export async function checkSyncFreshness(
// D6 invariant: every source incremented exactly one bucket.
const details = { unchanged_count, synced_recently_count, stale_count, ...(writer_owned_count ? { writer_owned_count } : {}),
+ ...(outcomes.length ? { code: outcomes[0]!.code, no_successful_sync: outcomes } : {}),
...(upstream_unknown_count ? { upstream_unknown_count } : {}), ...(upstream_behind_count ? { upstream_behind_count } : {}) };
// BUG 4: append in-progress context when any source is actively syncing.
// Empty otherwise, so steady-state messages are byte-for-byte unchanged.
const inProgressNote = (inProgress.length ? `. ${inProgress.join('; ')}` : '')
+ (writer_owned_count ? `. ${writer_owned_count} writer-owned canonical content source(s): upstream sync is not applicable; see canonical_content_writes for publication status` : '');
+ const remedy = issues.length > outcomes.length;
+ const outcomeFix = outcomes.find(o => o.code === 'sync_no_successful_sync')?.fix ?? outcomes[0]?.fix;
if (hasFailures) {
return {
name: 'sync_freshness',
status: 'fail',
- message: `${issues.join('; ')}. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` for each stale source${inProgressNote}`,
- details,
+ message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` for each stale source` : ''}${inProgressNote}`,
+ details, ...(outcomeFix ? { fix: outcomeFix } : {}),
};
}
if (hasWarnings) {
return {
name: 'sync_freshness',
status: 'warn',
- message: `${issues.join('; ')}. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` to refresh${inProgressNote}`,
- details,
+ message: `${issues.join('; ')}${remedy ? `. Run \`gbrain sync --source <id>${managed ? ' --no-pull' : ''}\` to refresh` : ''}${inProgressNote}`,
+ details, ...(outcomeFix ? { fix: outcomeFix } : {}),
};
}
if (writer_owned_count === sources.length) return {
diff --git a/src/commands/doctor/sync-outcome.ts b/src/commands/doctor/sync-outcome.ts
new file mode 100644
index 0000000000..d44ad3c968
--- /dev/null
+++ b/src/commands/doctor/sync-outcome.ts
@@ -0,0 +1,63 @@
+/**
+ * sync_freshness's verdict for a source with no successful sync recorded
+ * (#4960). Freshness and sync outcome are separate: a live first sync is
+ * `warn` (running is not fresh), and a source with no lock is `fail` with its
+ * last attempt (time, result, holds) and a fix for that state: wait, inspect
+ * holds, or retry. Each entry carries its registered code for `details`.
+ */
+import type { Action } from '../../core/agent-output.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+import { readLastSyncAttempt, type SyncAttemptState } from '../../core/sync-attempt.ts';
+import { doctorVerify } from './check-fix.ts';
+
+export interface SyncOutcomeEntry {
+ source_id: string;
+ code: 'sync_first_run_in_progress' | 'sync_no_successful_sync';
+ reason: 'first_sync_running' | SyncAttemptState;
+ last_attempt_at: string | null;
+ result: string | null;
+ held: number;
+ job_id: number | null;
+ fix: Action;
+}
+
+const DOCS = 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync';
+const VERIFY = doctorVerify('sync_freshness');
+
+/** `next: wait`: re-read the verdict once the running work finishes. */
+const waitFix = (why: string): Action =>
+ ({ argv: [...VERIFY.argv], consent: [], actor: 'provider', requires_exclusive: false, why, verify: VERIFY, docs: DOCS });
+
+export function firstSyncRunning(sourceId: string, display: string, snap: { holder_pid: number; holder_host: string }): { issue: string; entry: SyncOutcomeEntry } {
+ return {
+ issue: `Source ${display}: first sync running (pid ${snap.holder_pid} on ${snap.holder_host}), no successful sync yet; wait for it to finish`,
+ entry: { source_id: sourceId, code: 'sync_first_run_in_progress', reason: 'first_sync_running', last_attempt_at: null, result: 'running', held: 0, job_id: null,
+ fix: waitFix(`The first sync of ${sourceId} holds its live sync lock; it stamps last_sync_at only when it succeeds, so wait and re-run this check rather than starting a second sync.`) },
+ };
+}
+
+export async function noSuccessfulSync(engine: BrainEngine, sourceId: string, display: string, managed: boolean): Promise<{ issue: string; entry: SyncOutcomeEntry }> {
+ const attempt = await readLastSyncAttempt(engine, sourceId, managed);
+ const retry: Action = { argv: ['gbrain', 'sync', '--source', sourceId, ...(managed ? ['--no-pull'] : [])], consent: [], actor: 'agent', requires_exclusive: false,
+ verify: VERIFY, docs: DOCS, why: `No successful sync of ${sourceId} is recorded; this runs one and stamps last_sync_at when it succeeds.` };
+ const inspect: Action = attempt.job_id !== null && !managed
+ ? { argv: ['gbrain', 'jobs', 'get', String(attempt.job_id), '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify: VERIFY, docs: DOCS,
+ why: `Read-only: sync job #${attempt.job_id}'s status, result and error, before retrying.` }
+ : { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify: VERIFY, docs: DOCS,
+ why: `Read-only: the held files of ${sourceId}, each with its safe action, and the next step.` };
+ const fix = attempt.state === 'attempt_queued'
+ ? waitFix(`Sync job #${attempt.job_id} of ${sourceId} is queued or running; wait for it instead of starting another.`)
+ : attempt.state === 'holds_pending' ? (attempt.managed_next ?? inspect)
+ : attempt.state === 'last_attempt_unsuccessful' ? (attempt.managed_next ?? (attempt.job_id !== null ? { ...inspect, then: retry } : retry))
+ : retry;
+ const what = attempt.state === 'no_attempt'
+ ? `no attempt recorded${attempt.unreadable ? ` (last attempt unreadable: ${attempt.unreadable})` : ''}`
+ : `last attempt ${attempt.last_attempt_at ?? 'at an unknown time'}, result ${attempt.result ?? 'unknown'}, ${attempt.held} held`;
+ const step = attempt.state === 'attempt_queued' ? 'wait for the queued sync' : attempt.state === 'holds_pending' ? `inspect holds with \`gbrain sync status --source ${sourceId}\``
+ : `run \`${retry.argv!.join(' ')}\``;
+ return {
+ issue: `Source ${display}: no successful sync recorded; ${what}; ${step}`,
+ entry: { source_id: sourceId, code: 'sync_no_successful_sync', reason: attempt.state, last_attempt_at: attempt.last_attempt_at, result: attempt.result,
+ held: attempt.held, job_id: attempt.job_id, fix },
+ };
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 01178a9914..5aaf24b941 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -489,6 +489,14 @@ export const CODES = {
why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",
reasons: ['candidate_in_flight', 'busy_set_unreadable'],
suggestion: 'Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull.' },
+ // wave 18b #4960: doctor sync_freshness separates sync outcome from freshness for a source with no successful sync.
+ sync_first_run_in_progress: { class: 'retryable', summary: "A source's first sync is running (it holds a live sync lock inside the staleness ceiling) and no successful sync is recorded yet, so doctor sync_freshness warns instead of reading it as fresh.",
+ why: "A sync stamps last_sync_at only when it succeeds; a running sync is not a fresh source, and starting a second one beside it only contends for the lock. Over the staleness ceiling the lock reads as wedged (fail) instead.",
+ docs: 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync', suggestion: 'Wait for the running sync, then run gbrain doctor --only sync_freshness --json again.' },
+ sync_no_successful_sync: { class: 'unavailable', summary: "No successful sync is recorded for a source (last_sync_at is NULL) and no sync of it is running; doctor sync_freshness fails with the last attempt's time, result and held files.",
+ why: "The attempt comes from the newest sync job and, on a managed brain, the source's sync status (read-only). `reason` names the state: no_attempt (nothing recorded: run a sync), attempt_queued (a job is queued: wait), holds_pending (held files: inspect them first), last_attempt_unsuccessful (inspect the job or failure, then retry).",
+ reasons: ['no_attempt', 'attempt_queued', 'holds_pending', 'last_attempt_unsuccessful'], docs: 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync',
+ suggestion: 'Follow the check fix: it waits, inspects holds (gbrain sync status --source <id> --json) or retries (gbrain sync --source <id>) depending on the state.' },
// wave 16 (GBRA-79) #6513: a managed-sync checkpoint whose cursor another run of the source replaced.
sync_cursor_replaced: { class: 'caller', summary: "Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish.",
why: "The replacing run (a --retry-failed rediscovery or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
diff --git a/src/core/sync-attempt.ts b/src/core/sync-attempt.ts
new file mode 100644
index 0000000000..ad563e60ad
--- /dev/null
+++ b/src/core/sync-attempt.ts
@@ -0,0 +1,86 @@
+/**
+ * The last sync attempt of a source that has no successful sync recorded
+ * (`sources.last_sync_at` NULL), for doctor `sync_freshness` (#4960). Read-only:
+ * a managed brain reads `readSyncStatus` (holds, the last error, the cursor and
+ * its own `next`); any brain reads the newest `sync` Minions job of the source.
+ * Nothing found is "no attempt recorded", never a guess.
+ */
+import type { Action } from './agent-output.ts';
+import type { BrainEngine } from './engine.ts';
+import { isMissingSchemaObject } from './utils.ts';
+
+export type SyncAttemptState = 'no_attempt' | 'attempt_queued' | 'holds_pending' | 'last_attempt_unsuccessful';
+
+export interface SyncAttempt {
+ state: SyncAttemptState;
+ /** When the attempt last ran (job finish/start/enqueue, or the managed failure or cursor advance), ISO. */
+ last_attempt_at: string | null;
+ /** Job status (`failed`, `completed`, …) plus its sync result (`partial`, …), or the managed last error code. */
+ result: string | null;
+ /** Files held by the managed sync (or the failed-file count of the job's result). */
+ held: number;
+ job_id: number | null;
+ /** The source's managed `readSyncStatus.next`, when it names one. */
+ managed_next: Action | null;
+ /** Why the attempt could not be read; the state is then `no_attempt`. */
+ unreadable?: string;
+}
+
+const JOB_SQL = `SELECT id AS job_id, status, result->>'status' AS result_status, result->>'failedFiles' AS failed_files,
+ COALESCE(finished_at, started_at, created_at) AS at
+ FROM minion_jobs WHERE name='sync'
+ AND (COALESCE(data->>'sourceId', data->>'source_id')=$1 OR (COALESCE(data->>'sourceId', data->>'source_id') IS NULL
+ AND (data->>'repoPath' IS NULL AND $1='default' OR data->>'repoPath'=(SELECT local_path FROM sources WHERE id=$1))))
+ ORDER BY created_at DESC, id DESC LIMIT 1`;
+
+const iso = (value: unknown): string | null => {
+ if (value === null || value === undefined) return null;
+ const date = value instanceof Date ? value : new Date(String(value));
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
+};
+
+async function lastSyncJob(engine: BrainEngine, sourceId: string): Promise<Omit<SyncAttempt, 'managed_next'> | null> {
+ let rows: Array<{ job_id: number | string | null; status: string | null; result_status: string | null; failed_files: string | null; at: unknown }>;
+ try {
+ rows = await engine.executeRaw(JOB_SQL, [sourceId]);
+ } catch (error) {
+ if (isMissingSchemaObject(error, 'table', 'minion_jobs')) return null;
+ throw error;
+ }
+ const row = rows?.[0];
+ if (!row || row.job_id === null || row.job_id === undefined || typeof row.status !== 'string') return null;
+ const queued = ['waiting', 'delayed', 'active', 'waiting-children', 'paused'].includes(row.status);
+ const failed = Number(row.failed_files ?? 0);
+ return {
+ state: queued ? 'attempt_queued' : 'last_attempt_unsuccessful',
+ last_attempt_at: iso(row.at),
+ result: row.result_status ? `${row.status} (${row.result_status})` : row.status,
+ held: Number.isFinite(failed) ? failed : 0,
+ job_id: Number(row.job_id),
+ };
+}
+
+export async function readLastSyncAttempt(engine: BrainEngine, sourceId: string, managed: boolean): Promise<SyncAttempt> {
+ const none: SyncAttempt = { state: 'no_attempt', last_attempt_at: null, result: null, held: 0, job_id: null, managed_next: null };
+ try {
+ const job = await lastSyncJob(engine, sourceId);
+ if (!managed) return job ? { ...job, managed_next: null } : none;
+ const { readSyncStatus } = await import('./persistence/sync-status.ts');
+ const status = await readSyncStatus(engine, sourceId);
+ const held = status.holds.length;
+ const lastAt = status.last_error?.first_seen ?? status.cursor?.last_advance_at ?? null;
+ const managedResult = status.last_error?.code ?? (status.cursor && !status.cursor.done ? `cursor at ${status.cursor.index}/${status.cursor.total}` : null);
+ if (!job && !held && !lastAt && !managedResult) return { ...none, managed_next: status.next };
+ const newerJob = job && (!lastAt || (job.last_attempt_at ?? '') > lastAt);
+ return {
+ state: held ? 'holds_pending' : job?.state === 'attempt_queued' ? 'attempt_queued' : 'last_attempt_unsuccessful',
+ last_attempt_at: newerJob ? job!.last_attempt_at : iso(lastAt),
+ result: newerJob ? job!.result : managedResult ?? job?.result ?? null,
+ held: held || job?.held || 0,
+ job_id: job?.job_id ?? null,
+ managed_next: status.next,
+ };
+ } catch (error) {
+ return { ...none, unreadable: error instanceof Error ? error.message : String(error) };
+ }
+}
diff --git a/test/doctor-sync-freshness-outcome-4960.test.ts b/test/doctor-sync-freshness-outcome-4960.test.ts
new file mode 100644
index 0000000000..762724bd54
--- /dev/null
+++ b/test/doctor-sync-freshness-outcome-4960.test.ts
@@ -0,0 +1,178 @@
+/**
+ * #4960 (wave 18b 1.2): doctor sync_freshness keeps freshness and sync outcome
+ * apart for a source with no successful sync (last_sync_at NULL).
+ *
+ * - a live first sync inside the staleness ceiling is WARN
+ * (`sync_first_run_in_progress`, fix `next: wait`), never fresh;
+ * - no lock is FAIL with the last attempt (time, result, held) read from the
+ * newest sync job, or "no attempt recorded", and a fix for that state;
+ * - a lock held past the ceiling stays FAIL; an unchanged quiet repo stays OK.
+ *
+ * PGLite in-memory ($0).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'child_process';
+import { mkdtempSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+import { chunkerStamp } from '../src/core/chunkers/code.ts';
+import { cliRenderContext, renderAction, type Action } from '../src/core/agent-output.ts';
+import { readLastSyncAttempt } from '../src/core/sync-attempt.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); }, 60_000);
+beforeEach(async () => {
+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');
+ await engine.executeRaw("DELETE FROM minion_jobs WHERE name = 'sync'");
+});
+
+async function addSource(id: string, lastSyncAt: Date | null, extra: { localPath?: string; lastCommit?: string | null } = {}) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, last_sync_at, last_commit, chunker_version, config)
+ VALUES ($1, $1, $2, $3, $4, $5, '{"federated":true}'::jsonb)
+ ON CONFLICT (id) DO UPDATE SET last_sync_at = EXCLUDED.last_sync_at, local_path = EXCLUDED.local_path,
+ last_commit = EXCLUDED.last_commit, chunker_version = EXCLUDED.chunker_version`,
+ [id, extra.localPath ?? `/tmp/${id}`, lastSyncAt, extra.lastCommit ?? null, chunkerStamp()],
+ );
+}
+
+async function holdLock(sourceId: string, acquiredMinutesAgo = 1) {
+ await engine.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
+ VALUES ($1, 4242, 'testhost', now() - ($2 || ' minutes')::interval, now() + interval '30 minutes', now())`,
+ [syncLockId(sourceId), String(acquiredMinutesAgo)],
+ );
+}
+
+async function addSyncJob(sourceId: string, status: string, result: Record<string, unknown> | null): Promise<number> {
+ const job = await new MinionQueue(engine).add('sync', { sourceId }, { queue: 'default' }, { allowProtectedSubmit: true });
+ const done = ['completed', 'failed', 'dead'].includes(status);
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status=$2, result=$3::text::jsonb, started_at=now() - interval '20 minutes',
+ finished_at=CASE WHEN $4::boolean THEN now() - interval '10 minutes' END, attempts_started=1, attempts_made=CASE WHEN $4::boolean THEN 1 ELSE 0 END
+ WHERE id=$1`,
+ [job.id, status, result ? JSON.stringify(result) : null, done],
+ );
+ return Number(job.id);
+}
+
+const next = (fix: unknown) => renderAction(fix as Action, cliRenderContext()).next;
+const counted = (d: Record<string, unknown> | undefined) =>
+ Number(d?.unchanged_count) + Number(d?.synced_recently_count) + Number(d?.stale_count) + Number(d?.writer_owned_count ?? 0);
+
+describe('#4960 sync_freshness: a source with no successful sync', () => {
+ test('a live first sync inside the ceiling is warn, not fresh, with a wait fix', async () => {
+ await addSource('wiki', null);
+ await holdLock('wiki');
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('warn');
+ expect(result.message).toContain("Source 'wiki': first sync running (pid 4242 on testhost), no successful sync yet");
+ expect(result.message).not.toContain('Run `gbrain sync --source <id>`');
+ expect(result.details?.code).toBe('sync_first_run_in_progress');
+ expect(result.details?.stale_count).toBe(1);
+ expect(result.details?.synced_recently_count).toBe(0);
+ expect(counted(result.details)).toBe(1);
+ expect(next(result.fix)).toBe('wait');
+ expect((result.fix as Action).verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'sync_freshness', '--json']);
+ });
+
+ test('a first sync lock held past the staleness ceiling stays fail (wedged)', async () => {
+ await addSource('wiki', null);
+ await holdLock('wiki', 10 * 24 * 60);
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('fail');
+ expect(result.message).toContain('has held the sync lock for');
+ });
+
+ test('no lock and no attempt is fail: "no successful sync recorded; no attempt recorded" and a retry fix', async () => {
+ await addSource('wiki', null);
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('fail');
+ expect(result.message).toBe("Source 'wiki': no successful sync recorded; no attempt recorded; run `gbrain sync --source wiki`");
+ expect(result.message).not.toContain('never been synced');
+ expect(result.details?.code).toBe('sync_no_successful_sync');
+ const [entry] = result.details?.no_successful_sync as Array<Record<string, unknown>>;
+ expect(entry).toMatchObject({ source_id: 'wiki', reason: 'no_attempt', last_attempt_at: null, result: null, held: 0 });
+ expect((result.fix as Action).argv).toEqual(['gbrain', 'sync', '--source', 'wiki']);
+ expect(next(result.fix)).toBe('run');
+ });
+
+ test('a partial last attempt names its time, result and held count, and inspects the job before retrying', async () => {
+ await addSource('wiki', null);
+ const jobId = await addSyncJob('wiki', 'completed', { status: 'partial', failedFiles: 3 });
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('fail');
+ expect(result.message).toMatch(/^Source 'wiki': no successful sync recorded; last attempt \d{4}-\d\d-\d\dT[\d:.]+Z, result completed \(partial\), 3 held; run `gbrain sync --source wiki`$/);
+ const [entry] = result.details?.no_successful_sync as Array<Record<string, unknown>>;
+ expect(entry).toMatchObject({ reason: 'last_attempt_unsuccessful', result: 'completed (partial)', held: 3, job_id: jobId });
+ const fix = result.fix as Action;
+ expect(fix.argv).toEqual(['gbrain', 'jobs', 'get', String(jobId), '--json']);
+ expect(fix.then?.argv).toEqual(['gbrain', 'sync', '--source', 'wiki']);
+ });
+
+ test('a queued sync job is a wait, not a retry', async () => {
+ await addSource('wiki', null);
+ await addSyncJob('wiki', 'waiting', null);
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('fail');
+ expect(result.message).toContain('result waiting, 0 held; wait for the queued sync');
+ expect(next(result.fix)).toBe('wait');
+ });
+
+ test('another source\'s job is not this source\'s attempt', async () => {
+ await addSource('wiki', null);
+ await addSyncJob('other', 'failed', null);
+ const result = await checkSyncFreshness(engine);
+ expect(result.message).toContain('no attempt recorded');
+ });
+
+ test('a managed read (readSyncStatus) on a source with nothing recorded is "no attempt", not unreadable', async () => {
+ await addSource('wiki', null);
+ const attempt = await readLastSyncAttempt(engine, 'wiki', true);
+ expect(attempt.unreadable).toBeUndefined();
+ expect(attempt.state).toBe('no_attempt');
+ });
+
+ test('both codes are registered', () => {
+ expect(CODES.sync_first_run_in_progress.class).toBe('retryable');
+ expect(CODES.sync_no_successful_sync.reasons).toEqual(['no_attempt', 'attempt_queued', 'holds_pending', 'last_attempt_unsuccessful']);
+ });
+});
+
+describe('#4960 sync_freshness: fresh sources keep their verdict', () => {
+ function quietRepo(): { dir: string; head: string } {
+ const dir = mkdtempSync(join(tmpdir(), 'sync-outcome-quiet-'));
+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: dir });
+ writeFileSync(join(dir, 'note.md'), '# note\n');
+ execSync('git add -A && git commit -qm seed', { cwd: dir });
+ return { dir, head: execSync('git rev-parse HEAD', { cwd: dir }).toString().trim() };
+ }
+
+ test('an unchanged quiet repo synced long ago stays ok', async () => {
+ const { dir, head } = quietRepo();
+ await addSource('quiet', new Date(Date.now() - 30 * 24 * 3600_000), { localPath: dir, lastCommit: head });
+ const result = await checkSyncFreshness(engine, { localOnly: true });
+ expect(result.status).toBe('ok');
+ expect(result.details?.unchanged_count).toBe(1);
+ expect(result.fix).toBeUndefined();
+ });
+
+ test('a synced source with a live lock still reads in progress (ok)', async () => {
+ await addSource('wiki', new Date(Date.now() - 3600_000));
+ await holdLock('wiki');
+ const result = await checkSyncFreshness(engine);
+ expect(result.status).toBe('ok');
+ expect(result.message).toContain('sync in progress');
+ });
+});
diff --git a/test/doctor-sync-policy.test.ts b/test/doctor-sync-policy.test.ts
index 39800475b5..7b13586396 100644
--- a/test/doctor-sync-policy.test.ts
+++ b/test/doctor-sync-policy.test.ts
@@ -66,8 +66,9 @@ describe('doctor sync freshness honors automatic sync policy', () => {
await seed('enabled-example', config);
const result = await checkSyncFreshness(engine, { nowMs: NOW });
expect(result.status).toBe('fail');
- expect(result.message).toContain("'enabled-example' has never been synced");
- expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 0, stale_count: 1 });
+ expect(result.message).toContain("'enabled-example': no successful sync recorded");
+ expect(result.details).toEqual({ unchanged_count: 0, synced_recently_count: 0, stale_count: 1, code: 'sync_no_successful_sync',
+ no_successful_sync: [expect.objectContaining({ source_id: 'enabled-example', reason: 'no_attempt' })] });
});
test('legacy archived-column fallback also loads and honors config', async () => {
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 4eb06efdb4..9a330d9a52 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -840,25 +840,25 @@ describe('v0.32.4 — sync_freshness check', () => {
expect(result.message).toBe('No federated sources to sync');
});
- test('last_sync_at IS NULL → fail with "never been synced"', async () => {
+ test('last_sync_at IS NULL → fail with "no successful sync recorded" (#4960)', async () => {
const { checkSyncFreshness } = await import('../src/commands/doctor.ts');
const result = await checkSyncFreshness(makeStubEngine([
{ id: 'wiki', name: '', local_path: '/tmp/wiki', last_sync_at: null },
]));
expect(result.status).toBe('fail');
- expect(result.message).toContain('never been synced');
+ expect(result.message).toContain('no successful sync recorded');
expect(result.message).toContain(`'wiki'`); // source.id embedded
- expect(result.message).toContain('gbrain sync --source <id>');
+ expect(result.message).toContain('gbrain sync --source wiki');
});
test('#5477: a managed brain is told to sync with --no-pull; unmanaged wording is unchanged', async () => {
const { checkSyncFreshness } = await import('../src/commands/doctor.ts');
const rows = [{ id: 'wiki', name: '', local_path: '/tmp/wiki', last_sync_at: null }];
const unmanaged = await checkSyncFreshness(makeStubEngine(rows));
- expect(unmanaged.message).toBe("Source 'wiki' has never been synced. Run `gbrain sync --source <id>` for each stale source");
+ expect(unmanaged.message).toBe("Source 'wiki': no successful sync recorded; no attempt recorded; run `gbrain sync --source wiki`");
const managed = await checkSyncFreshness(makeStubEngine(rows, true));
expect(managed.status).toBe('fail');
- expect(managed.message).toBe("Source 'wiki' has never been synced. Run `gbrain sync --source <id> --no-pull` for each stale source");
+ expect(managed.message).toMatch(/^Source 'wiki': no successful sync recorded; .*run `gbrain sync --source wiki --no-pull`$/);
});
test('last_sync_at > 72h ago → fail with day-rounded "Nd ago"', async () => {
@@ -1827,14 +1827,14 @@ describe('BUG 4 — in-progress sync via live lock, not stale freshness', () =>
expect(result.message).toContain('pid 4242');
});
- test('never-synced source WITH a live lock → ok (initial sync in progress)', async () => {
+ test('never-synced source WITH a live lock → warn (#4960: a first sync running is not fresh)', async () => {
const { checkSyncFreshness } = await import('../src/commands/doctor.ts');
await addSource('wiki', null);
await holdLock('wiki', 30);
const result = await checkSyncFreshness(engine);
- expect(result.status).toBe('ok');
- expect(result.details?.synced_recently_count).toBe(1);
- expect(result.message).toContain('sync in progress');
+ expect(result.status).toBe('warn');
+ expect(result.details?.stale_count).toBe(1);
+ expect(result.message).toContain('first sync running (pid 4242 on testhost), no successful sync yet');
});
test('never-synced source with NO lock → fail (unchanged behavior)', async () => {
@@ -1842,7 +1842,7 @@ describe('BUG 4 — in-progress sync via live lock, not stale freshness', () =>
await addSource('wiki', null);
const result = await checkSyncFreshness(engine);
expect(result.status).toBe('fail');
- expect(result.message).toContain('never been synced');
+ expect(result.message).toContain('no successful sync recorded');
});
test('expired-TTL lock does NOT mask staleness (wedged-but-not-refreshing holder)', async () => {
diff --git a/test/graduation-verify-sync-freshness.test.ts b/test/graduation-verify-sync-freshness.test.ts
index 30afa68cef..c07876559f 100644
--- a/test/graduation-verify-sync-freshness.test.ts
+++ b/test/graduation-verify-sync-freshness.test.ts
@@ -58,7 +58,7 @@ test('the verifying target of this run inherits the source flag; every other com
{ GBRAIN_GRADUATION_RUN: undefined, GBRAIN_GRADUATION_SOURCE_PERSISTENCE: 'enabled' }]) {
const check = await freshness(env);
expect(check.status).toBe('fail');
- expect(check.message).toContain(`'${sourceId}' has never been synced`);
+ expect(check.message).toContain(`'${sourceId}': no successful sync recorded`);
}
for (const row of ["state='verified'", "role='source'"]) {
await engine.executeRaw(`UPDATE persistence_graduation SET ${row}`);
diff --git a/test/shared-content-freshness.test.ts b/test/shared-content-freshness.test.ts
index 6a7817bed9..8578380762 100644
--- a/test/shared-content-freshness.test.ts
+++ b/test/shared-content-freshness.test.ts
@@ -67,13 +67,13 @@ test('external roots and absent, incomplete, unowned or mismatched receipts stil
expect(await ownedContentFreshness(engine, [f.sourceId])).toEqual([]);
const check = await checkSyncFreshness(engine);
expect(check.status).toBe('fail');
- expect(check.message).toContain(`'${f.sourceId}' has never been synced`);
+ expect(check.message).toContain(`'${f.sourceId}': no successful sync recorded`);
}
await engine.setConfig(f.key, JSON.stringify(f.receipt));
for (const config of [{ kind: 'google' }, { remote_url: 'https://example.invalid/repo' }, { managed_clone: true }, { company_brain: {} }, 'invalid-policy']) {
await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1', [f.sourceId, JSON.stringify(config)]);
expect(await ownedContentFreshness(engine, [f.sourceId])).toEqual([]);
- expect((await checkSyncFreshness(engine)).message).toContain(`'${f.sourceId}' has never been synced`);
+ expect((await checkSyncFreshness(engine)).message).toContain(`'${f.sourceId}': no successful sync recorded`);
}
await withManagedFixtureWrite(engine, [f.sourceId], tx => tx.executeRaw("UPDATE sources SET config='{}',last_commit=$2 WHERE id=$1", [f.sourceId, 'a'.repeat(40)]));
expect(await ownedContentFreshness(engine, [f.sourceId])).toEqual([]);
@@ -85,7 +85,7 @@ test('source incarnation and canonical host-binding changes invalidate the owned
const f = await fixture(engine);
await engine.executeRaw('UPDATE persistence_host_bindings SET local_path=$2 WHERE worktree_id=$1::uuid', [f.binding.worktree_id, join(home, 'moved')]);
expect(await ownedContentFreshness(engine, [f.sourceId])).toEqual([]);
- expect((await checkSyncFreshness(engine)).message).toContain(`'${f.sourceId}' has never been synced`);
+ expect((await checkSyncFreshness(engine)).message).toContain(`'${f.sourceId}': no successful sync recorded`);
await engine.executeRaw('UPDATE persistence_host_bindings SET local_path=$2 WHERE worktree_id=$1::uuid', [f.binding.worktree_id, f.root]);
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");