Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: the sync_tail_degraded fix scopes extract --stale with --source-id, and truncated counts only the imported pages the tail left underived (found by GBRA-117)
garrytan3d8fab55a178
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d958c5322d..11547d3f2b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,7 @@ identifiers and attribution are available in the pre-removal Git revision|---|---|---|| a managed sync's checkpoint commits, then link extraction runs for minutes | the drain lease and the governed pass stayed held through the tail | the run returns `synced` at the commit; the tail runs after the lease is released, bounded, and a second sync can take the lease at once || the process dies between the checkpoint commit and the tail | statistics and links for that run were never redone | the checkpoint recorded the tail as owed; the next sync of the source runs it |-| the tail fails, is cut short or the deadline left no time | silent | the run stays `synced` with one `[gbrain notice sync_tail_degraded]` and its fix (`gbrain extract --stale --source <id>`, or doctor for statistics); `sync --all` prints it per source and puts `tail` and `notices` in each source's JSON entry |+| the tail fails, is cut short or the deadline left no time | silent | the run stays `synced` with one `[gbrain notice sync_tail_degraded]` and its fix (`gbrain extract --stale --source-id <id>`, or doctor for statistics); `sync --all` prints it per source and puts `tail` and `notices` in each source's JSON entry || a pass admits nothing with no unfinished request | `drain_stalled` / `no_admission`, a pooler warning, and a delegated run's one-time fallback | `drain_stalled` / `no_progress` with the same step and statement; `no_admission` is a retired reason || `gbrain sync status` on a large brain | every heavy read on every call | a plain status skips the terminal summary, blocker list and cursor join (`*_read: not_read`, fix `--detail`); `state`, `reason` and bounded oldest-blocker / recovery probes always run (an unfinished write is `resumable` / `request_pending`, never synced); under 30 ms on a 61k-request fixture || a short-lived command (`put`, `remember`, `import`) runs while a managed sync drains its source | its consumer could claim and publish the drainer's page requests whenever a lane group backed off | only the drain lease holder publishes them; the command's own write still passes the queued sync rows that do not name its page, and with no live lease nothing changes |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9604b0a5a7..a2b75a3522 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -507,7 +507,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| Stop reason | Code | Outcome | What it means | Recovery || --- | --- | --- | --- | --- || <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain, or a `sync` job reached its own deadline (its `timeout_ms` less a 60 s reserve). Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. A `sync` job that queued a follow-up (`continuation_job_id`) names it in `next` instead: watch it, don't start a second sync beside it. |-| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_progress` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like (older builds named this cause `no_admission`; it is retired, and a receipt carrying it means the same). The pass returns when the run's final checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) runs after the drain lease is released, outside this governor, bounded at 5 minutes; the checkpoint's own transaction records it as owed, so a process that dies before it leaves it for the next sync of the source, and a failed or cut-short tail keeps the run `synced` with a `[gbrain notice sync_tail_degraded]` whose fix is `gbrain extract --stale --source <id>`. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_progress` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like (older builds named this cause `no_admission`; it is retired, and a receipt carrying it means the same). The pass returns when the run's final checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) runs after the drain lease is released, outside this governor, bounded at 5 minutes; the checkpoint's own transaction records it as owed, so a process that dies before it leaves it for the next sync of the source, and a failed or cut-short tail keeps the run `synced` with a `[gbrain notice sync_tail_degraded]` whose fix is `gbrain extract --stale --source-id <id>`. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), 30 s later a Postgres publish still running is cancelled (its connection is discarded, nothing commits, and the write is queued again), and a publish that still has not settled 35 s after the ceiling makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. || <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. || <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. || <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 39a77a2937..1cf5fa710d 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -708,7 +708,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.266.0', text: 'Five `sync.*` config keys are no longer read (#6712): `sync.bulk_max_txn_ms`, `sync.hold_cap`, `sync.hold_escalate_count`, `sync.hold_escalate_pct` and `sync.parser_regression`. Set `GBRAIN_SYNC_BULK_MAX_TXN_MS`, `GBRAIN_SYNC_HOLD_CAP`, `GBRAIN_SYNC_HOLD_ESCALATE_COUNT`, `GBRAIN_SYNC_HOLD_ESCALATE_PCT` or `GBRAIN_SYNC_PARSER_REGRESSION` in the environment of the process that syncs instead; a value stored on the brain is kept but not applied, so a tuned brain runs with the defaults (15000, 500, 50, 5, stop) until the variable is set. `gbrain doctor --only sync_config_keys` lists stored values that stopped applying, `gbrain config get <key>` prints the value in effect and where it comes from, and `gbrain config set` of a retired key warns, names the variable and writes nothing (exit 0).' },{ since: '0.60.266.0', text: '`sync.job_drain`, `sync.foreground_priority`, `sync.federated_v2`, `sync.waive_batch` and `sync.bulk` are rollback keys (#6712): `false` still restores the earlier behavior a notice named, and they stay honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`), but `config set` now writes them with a note that they are not tunables and help text no longer recommends them. `sync.foreground_priority` is accepted without `--force` (it was refused as an unknown key). A serve or PGLite owner that receives a retired field from an older sync client (`explicitProcessing` today) prints one `[gbrain notice]` naming it and its window, and the PGLite owner lane accepts `--lanes N` and `--no-lanes` (ignored there) instead of refusing them.' },// #6712 PR 2 lane L5 (truthful receipts, fast status). `since` is a placeholder until the merge-slot stamp.- { since: '0.60.266.0', text: 'A managed `gbrain sync` returns `synced` when its checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) now runs after the drain lease is released, bounded at 5 minutes, and a second sync can take the lease while it runs. A tail that fails, is cut short or gets no time keeps the run `synced` and adds a `[gbrain notice sync_tail_degraded]` with its fix (`gbrain extract --stale --source <id>`); a tail a crash skipped runs on the next sync of the source.' },+ { since: '0.60.266.0', text: 'A managed `gbrain sync` returns `synced` when its checkpoint commits: the tail after it (planner statistics, link extraction for the imported pages) now runs after the drain lease is released, bounded at 5 minutes, and a second sync can take the lease while it runs. A tail that fails, is cut short or gets no time keeps the run `synced` and adds a `[gbrain notice sync_tail_degraded]` with its fix (`gbrain extract --stale --source-id <id>`); a tail a crash skipped runs on the next sync of the source.' },{ since: '0.60.266.0', text: 'The `drain_stalled` cause `no_admission` is retired: a sync pass that admits nothing with no unfinished request stops `drain_stalled` / `no_progress` with the same step and statement, a delegated run no longer falls back to its own consumer for it, and the transaction-pooler warning line is gone. Scripts matching `no_admission` should match `no_progress`.' },{ since: '0.60.266.0', text: 'While a managed sync holds a source\'s drain lease, short-lived commands (`put`, `remember`, `import` and other CLI writes) no longer publish that source\'s sync page requests; only the drainer does (#6712). A command whose own write names a page the sync is about to publish waits for the drainer, and returns its retryable writer-pending reply when the drainer does not finish in time. With no live lease, every consumer drains as before.' },{ since: '0.60.266.0', text: 'A plain `gbrain sync status` skips the terminal-failure summary, the checkpoint blocker list and the cursor list (their fields stay, empty or `unknown`, with `terminal_failures_read` / `checkpoint_blockers_read` / `cursors_read` set to `not_read` and a `--detail` fix); `gbrain sync status --detail` reads them. New fields: `state`, `reason`, `oldest_blocker`, `recovery`, and `public_category` on holds, `last_error`, receipts and doctor `sync_failures`.' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex a255cda7dd..0aaffc06f6 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -672,7 +672,7 @@ export const NOTICE_CODES = {first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },- sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source <id>`, or doctor for the statistics).' },+ sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },diff --git a/src/core/persistence/sync-tail.ts b/src/core/persistence/sync-tail.tsindex f6f97361c3..1fcac0efe3 100644--- a/src/core/persistence/sync-tail.ts+++ b/src/core/persistence/sync-tail.ts@@ -64,19 +64,21 @@ export async function runSyncTail(engine: BrainEngine, sourceId: string, opts: {}const ran = failure === null && (!extract || links !== undefined);if (ran) await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [SYNC_TAIL_OP, sourceId, JSON.stringify(owed)]).catch(() => undefined);- // Imported pages are re-derived even when a sweep stamped them fresh, so an unvisited one is truncation whatever `remaining` says.- const truncated = !!links && (links.remaining > 0 || slugs.length > links.pages + links.skipped) && (Date.now() >= deadlineAt || links.pages + links.skipped >= SYNC_TAIL_MAX_PAGES);+ // Imported pages are derived first, so the run left some underived only when it visited fewer pages than it imported;+ // `remaining` is the source's whole stale backlog, older pages included, and is not this run's to report.+ const underived = links ? Math.max(0, slugs.length - links.pages - links.skipped) : 0;+ const truncated = underived > 0 && (Date.now() >= deadlineAt || links!.pages + links!.skipped >= SYNC_TAIL_MAX_PAGES);const status: SyncTailReport['status'] = failure !== null ? 'failed' : !ran ? 'deferred' : truncated ? 'truncated' : statistics === 'failed' ? 'degraded' : 'done';- return { status, runs: owed.length, statistics, ...(links ? { links } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, links, failure }) }) };+ return { status, runs: owed.length, statistics, ...(links ? { links } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, underived, failure }) }) };}-function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'], 'done'>, d: { statistics: SyncTailReport['statistics']; links?: ManagedLinkExtraction; failure: string | null }): Notice {- const extract = { argv: ['gbrain', 'extract', '--stale', '--source', sourceId], consent: [], actor: 'agent' as const, requires_exclusive: false,+function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'], 'done'>, d: { statistics: SyncTailReport['statistics']; underived?: number; failure: string | null }): Notice {+ const extract = { argv: ['gbrain', 'extract', '--stale', '--source-id', sourceId], consent: [], actor: 'agent' as const, requires_exclusive: false,why: 'Derives links for the pages this sync imported that are still stale; it changes no page content.',verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } };if (status === 'truncated') {return { code: 'sync_tail_degraded', kind: 'degraded', fix: extract,- why: `The sync of source ${sourceId} is synced, but link extraction stopped at its budget with ${d.links!.remaining || 'some'} imported page(s) not yet derived; their links and backlinks are missing until they are extracted.` };+ why: `The sync of source ${sourceId} is synced, but link extraction stopped at its budget with ${d.underived} imported page(s) not yet derived; their links and backlinks are missing until they are extracted.` };}if (status === 'degraded') {return { code: 'sync_tail_degraded', kind: 'degraded',diff --git a/test/sync-drain-finish-tail.test.ts b/test/sync-drain-finish-tail.test.tsindex 9874f5d7db..753074564e 100644--- a/test/sync-drain-finish-tail.test.ts+++ b/test/sync-drain-finish-tail.test.ts@@ -119,7 +119,7 @@ test('a tail that never ran after its checkpoint committed stays owed and the neexpect(fired).toBe(1);expect(first.drain?.outcome).toBe('synced');expect(first.status).toBe('first_sync');- expect(first.tail).toMatchObject({ status: 'failed', runs: 1, notice: { code: 'sync_tail_degraded', kind: 'degraded', fix: { argv: ['gbrain', 'extract', '--stale', '--source', id] } } });+ expect(first.tail).toMatchObject({ status: 'failed', runs: 1, notice: { code: 'sync_tail_degraded', kind: 'degraded', fix: { argv: ['gbrain', 'extract', '--stale', '--source-id', id] } } });expect(first.links).toBeUndefined();const owed = await readSyncTail(engine, id);expect(owed?.map(item => ({ changed: item.changed, extract: item.extract }))).toEqual([{ changed: 2, extract: true }]);@@ -158,3 +158,50 @@ test('a --no-extract run owes statistics only, and a run past its deadline defer} }) as unknown as BrainEngine;expect(await runSyncTail(unreadable, id)).toMatchObject({ status: 'failed', runs: 0, notice: { code: 'sync_tail_degraded', kind: 'degraded' } });}), 120_000);++test('a tail cut short reports only the imported pages it left underived, never the source\'s older stale backlog (PGLite)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const id = await source();+ await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(await stale(id)).toBe(2);+ const [{ local_path: root }] = await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [id]);+ for (const name of ['n2', 'n3']) writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\nSee [[notes/n0]].\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'two more');+ await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(await stale(id)).toBe(4);+ const { runSyncTail } = await import('../src/core/persistence/sync-tail.ts');+ const { recordSyncTail } = await import('../src/core/persistence/sync-tail-record.ts');+ const [cursor] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [cursor!.fingerprint]);+ // The first page read of each tail outlasts its budget, so exactly one page is derived before the deadline stops it.+ const slowFirst = (budgetMs: number) => {+ let reads = 0;+ return new Proxy(engine, { get(target, prop, receiver) {+ // A transaction engine inherits from this proxy, so the read runs on whichever engine it was called on.+ if (prop === 'readPageSnapshot') return async function (this: BrainEngine, ...args: unknown[]) {+ if (reads++ === 0) await sleep(budgetMs + 200);+ return (target.readPageSnapshot as (...a: unknown[]) => unknown).apply(this, args);+ };+ return Reflect.get(target, prop, receiver);+ } }) as unknown as BrainEngine;+ };+ // Two imported pages, one derived: the notice counts the one left, not the two older stale pages behind it.+ await recordSyncTail(engine, id, cursor!.fingerprint, cursor!.run_id);+ const cut = await runSyncTail(slowFirst(1_000), id, { budgetMs: 1_000 });+ expect(cut?.links).toMatchObject({ pages: 1 });+ expect(cut).toMatchObject({ status: 'truncated', notice: { code: 'sync_tail_degraded', fix: { argv: ['gbrain', 'extract', '--stale', '--source-id', id] } } });+ expect(cut?.notice?.why).toContain('with 1 imported page(s) not yet derived');+ // One imported page, derived before the deadline, with the older backlog still stale: the tail is done.+ writeFileSync(join(root, 'notes', 'n4.md'), '---\ntitle: n4\n---\nSee [[notes/n0]].\n');+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'one more');+ await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ const [next] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [next!.fingerprint]);+ await recordSyncTail(engine, id, next!.fingerprint, next!.run_id);+ const staleBefore = await stale(id);+ expect(staleBefore).toBeGreaterThan(1);+ const done = await runSyncTail(slowFirst(1_000), id, { budgetMs: 1_000 });+ expect(done?.links?.remaining).toBeGreaterThan(0);+ expect(done).toMatchObject({ status: 'done' });+ expect(done?.notice).toBeUndefined();+}), 120_000);+