Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: review follow-ups (#6803): managed connector cycles reconcile changed pages, failed phases keep the window, doctor reads stalls without an age cutoff, stall record lands after in-flight progress, dry-run follows drain order

garrytan81370f5c4eec
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e5bd29143..55578064ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,9 +52,9 @@ Nothing runs on upgrade: the drain and the re-sync are explicit steps. Automatic
- **Embed-backfill stall cap** (`src/core/embed-backfill-stall.ts`, `src/core/embed-backfill-submit.ts`, `src/core/minions/handlers/embed-backfill.ts`). A run that embeds nothing records a blocker fingerprint (stale chunk count, archived embedding work, pages still waiting for a projection) in its job progress. `submitEmbedBackfill` backs off by the cooldown times 2 per identical failure and returns the new `stalled` status at 3 (`EMBED_BACKFILL_STALL_LIMIT`). A `delayed` job (between retries) now counts as in flight. The handler throws an unrecoverable error when a retry finds the fingerprint it recorded, so the job dead-letters instead of using its remaining attempts. The sync, connector, GitHub and federation submitters report `stalled` as a skip.
- **Mis-pinned connector skip** (`src/core/persistence/connector-account-mismatch.ts`, `connector-state.ts`, `connector-sync.ts`, `src/commands/autopilot-fanout.ts`, `src/commands/autopilot-dispatch.ts`). An `account_changed` or `account_unresolved` refusal records `account_mismatch` with a digest of the source's connector config in the connector state; a passing account check clears it. The fan-out puts such a source in the `unavailable-path` bucket and the freshness loop skips it with `freshness_source_path_skipped` (`code: connector_account_changed`), while the recorded config digest matches the current one. Both fail open when the state cannot be read.
-- **Connector cycle scope** (`src/core/cycle.ts`, `src/core/cycle/extract-facts.ts`, `src/core/minions/handlers/autopilot-cycle.ts`). A connector source's cycle passes `sourceChangedSince` (its last completed cycle): `extract_facts` drains its watermark for that source instead of a full walk, and `recompute_emotional_weight` recomputes only the source's changed pages. A full `extract_facts` walk under a source now lists only that source's slugs.
+- **Connector cycle scope** (`src/core/cycle.ts`, `src/core/cycle/extract-facts.ts`, `src/core/minions/handlers/autopilot-cycle.ts`). A connector source's cycle passes `sourceChangedSince`: `extract_facts` and `recompute_emotional_weight` reconcile only the source's pages changed since the previous cycle listed its pages (`last_source_cycle_window_at`; a cycle whose fact or weight phase failed keeps the previous window). A full `extract_facts` walk under a source now lists only that source's slugs.
- **Doctor**: new `embed_backfill_stalled` (fix `gbrain projections drain`, preview `gbrain projections drain --dry-run --json`) and `connector_account_mismatch` (fix `gbrain sync --source <source>` after restoring the credential) checks. New error code `embed_backfill_stalled`; `gbrain errors connector_account_changed` describes the skip.
-- **`gbrain projections drain --dry-run`** lists the queued rows (rows that last failed first, with their reason) up to `--limit` (default 50) and rebuilds nothing; `--json` gives `{pending, failed, rows}`.
+- **`gbrain projections drain --dry-run`** lists the queued rows a drain with the same `--limit` (default 50) would try, in its order and with each row's queue reason, and rebuilds nothing; `--json` gives `{pending, failed, rows}`.
## [0.60.257.0] - 2026-10-16
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 0fb9d6def5..1ab0633f71 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -298,12 +298,13 @@ To drain now:
gbrain projections drain # until every page queued at the start was tried once
gbrain projections drain --limit 5000
gbrain projections drain --json # {rebuilt, superseded, failed: [{source_id, slug, reason}], remaining}
-gbrain projections drain --dry-run # rebuild nothing: list the queued rows, rows that last failed first
+gbrain projections drain --dry-run # rebuild nothing: list the queued rows in the order a drain tries them
```
-`--dry-run` is the preview: it reads the queue only and prints each row it
-would try with its queue reason (`rebuild_failed` rows first), up to `--limit`
-(default 50); `--json` gives `{pending, failed, rows}`.
+`--dry-run` is the preview: it reads the queue only and prints the rows a
+drain with the same `--limit` (default 50) would try, in that order, each with
+its queue reason (`rebuild_failed` for a row whose last rebuild failed);
+`--json` gives `{pending, failed, rows}`.
<a id="embed-backfill-stalled"></a>
**An automatic embed-backfill that keeps failing the same way.** A page whose
diff --git a/src/commands/doctor/checks/embed-backfill-stalled.ts b/src/commands/doctor/checks/embed-backfill-stalled.ts
index b8f8f51ac1..51ae2e0b50 100644
--- a/src/commands/doctor/checks/embed-backfill-stalled.ts
+++ b/src/commands/doctor/checks/embed-backfill-stalled.ts
@@ -24,8 +24,7 @@ export async function embedBackfillStalledCheck(engine: BrainEngine): Promise<Ch
try {
const sources = await engine.executeRaw<{ source_id: string }>(
`SELECT DISTINCT data->>'sourceId' AS source_id FROM minion_jobs
- WHERE name = 'embed-backfill' AND status IN ('failed', 'dead') AND progress ? 'stall'
- AND finished_at > now() - interval '7 days'`);
+ WHERE name = 'embed-backfill' AND status IN ('failed', 'dead') AND progress ? 'stall'`);
const stalled = [];
for (const { source_id } of sources) {
const stall = source_id ? await readEmbedBackfillStall(engine, source_id) : null;
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 897319dc23..a3fdde8a5c 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -584,8 +584,7 @@ export interface CycleOpts {
* #6803: set by the autopilot-cycle handler for a connector source, whose
* cycle has no sync phase. The source's pages changed after this instant
* (null: never cycled, so every page of the source) are the cycle's
- * incremental set; extract_facts reconciles through its bounded watermark
- * drain. Without it a checkout-less source cycle took the full-walk mode and
+ * incremental set for extract_facts and recompute_emotional_weight. Without it a checkout-less source cycle took the full-walk mode and
* walked every page of the brain on every cycle.
*/
sourceChangedSince?: string | null;
@@ -2425,7 +2424,7 @@ async function runCycleUnscoped(
// (#1928, codex: keying off phases.includes('sync') wrongly suppressed
// the skipped-sync full reconcile).
const syncRanButFailed = syncAttempted && syncPagesAffected === undefined;
- const xfSlugs = syncRanButFailed || sourceChangedSlugs ? [] : syncPagesAffected;
+ const xfSlugs = syncRanButFailed ? [] : (sourceChangedSlugs ?? syncPagesAffected);
const { result, duration_ms } = await timePhase(() =>
runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal), 'extract_facts');
result.duration_ms = duration_ms;
@@ -3174,8 +3173,13 @@ async function runCycleUnscoped(
await engine.updateSourceConfig(opts.sourceId, {
last_source_cycle_at: nowIso,
last_full_cycle_at: nowIso,
- // #6803: where the next connector cycle's changed-page window starts (read before this cycle listed its pages).
- ...(sourceWindowAt ? { last_source_cycle_window_at: sourceWindowAt } : {}),
+ // #6803: where the next connector cycle's changed-page window starts: when this cycle listed its pages,
+ // or, when a phase that consumed the window failed, the same window again ('' = every page of the source).
+ ...(sourceWindowAt ? {
+ last_source_cycle_window_at: phaseResults.some(r => (r.phase === 'extract_facts' || r.phase === 'recompute_emotional_weight') && r.status === 'fail')
+ ? (opts.sourceChangedSince ?? '')
+ : sourceWindowAt,
+ } : {}),
});
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
diff --git a/src/core/minions/handlers/autopilot-cycle.ts b/src/core/minions/handlers/autopilot-cycle.ts
index c5fa2ebd40..9d70185a3e 100644
--- a/src/core/minions/handlers/autopilot-cycle.ts
+++ b/src/core/minions/handlers/autopilot-cycle.ts
@@ -68,7 +68,8 @@ export function makeAutopilotCycleHandler(engine: BrainEngine): MinionHandler {
// source's own checkout (the #2227/#2194 mixed-scope fix).
const rows = await engine.executeRaw<{ archived: boolean | null; local_path: string | null; kind: string | null; last_cycle: string | null }>(
`SELECT archived, local_path, config->>'kind' AS kind,
- COALESCE(config->>'last_source_cycle_window_at', config->>'last_source_cycle_at', config->>'last_full_cycle_at') AS last_cycle FROM sources WHERE id = $1`,
+ CASE WHEN config->'last_source_cycle_window_at' IS NOT NULL THEN NULLIF(config->>'last_source_cycle_window_at', '')
+ ELSE COALESCE(config->>'last_source_cycle_at', config->>'last_full_cycle_at') END AS last_cycle FROM sources WHERE id = $1`,
[rawSourceId],
);
if (rows.length === 0) {
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 5933f3f677..9895e079b0 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -271,6 +271,7 @@ export function makeEmbedBackfillHandler(
if (job.signal?.aborted) drainAbort.abort();
job.signal?.addEventListener('abort', onJobAbort, { once: true });
let progressCounter = 0;
+ const progressWrites = new Set<Promise<unknown>>();
const watchdog = stallSeconds > 0
? createEmbedStallWatchdog({ thresholdSeconds: stallSeconds, readProgress: () => progressCounter })
: undefined;
@@ -308,13 +309,15 @@ export function makeEmbedBackfillHandler(
// Banked forward progress feeds the stall watchdog's clock.
progressCounter = embedded + chunksProcessed;
// Fire-and-forget; updateProgress returns a Promise but the
- // handler is sync inside the loop.
- void job.updateProgress({
+ // handler is sync inside the loop. Tracked so the #6803 stall
+ // record below is written after every in-flight update.
+ const write: Promise<unknown> = job.updateProgress({
embedded,
chunksProcessed,
cursor,
spentUsd: tracker.totalSpent,
- });
+ }).catch(() => undefined).finally(() => progressWrites.delete(write));
+ progressWrites.add(write);
},
}),
);
@@ -355,6 +358,7 @@ export function makeEmbedBackfillHandler(
let repeated = false;
if (result.embedded === 0) {
try {
+ await Promise.all(progressWrites);
const { fingerprint, remaining, blocked, signature } = await readEmbedBackfillBlockers(engine, sourceId, currentEmbeddingSignature());
const [prior] = job.attempts_made > 0
? await engine.executeRaw<{ fingerprint: string | null }>("SELECT progress->'stall'->>'fingerprint' AS fingerprint FROM minion_jobs WHERE id=$1", [job.id])
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 54b9c22c3b..91a6d2ad6a 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -463,7 +463,7 @@ export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>)
/**
* #6803: the read-only preview of `gbrain projections drain`: the queued
- * Markdown and code rows a drain would try, rows that last failed first, then oldest (at most `limit`),
+ * Markdown and code rows a drain would try, in the order it tries them (at most `limit`),
* with each row's queue reason, so a row that last failed (`rebuild_failed`)
* is named before anything is rebuilt.
*/
@@ -472,7 +472,7 @@ export async function previewProjectionDrain(engine: Pick<BrainEngine, 'executeR
const backlog = await projectionBacklog(engine);
const rows = await engine.executeRaw<{ source_id: string; slug: string; reason: string; updated_at: string }>(`SELECT s.id AS source_id,j.slug,j.reason,j.updated_at::text AS updated_at
FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}
- ORDER BY (j.reason='rebuild_failed') DESC,j.updated_at,j.slug LIMIT $1`, [Math.max(1, limit)]);
+ ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, limit)]);
return { pending: backlog.pending, failed: backlog.failed, rows };
}
diff --git a/test/connector-cycle-extract-facts-scope.serial.test.ts b/test/connector-cycle-extract-facts-scope.serial.test.ts
index 008626716c..9011e8e258 100644
--- a/test/connector-cycle-extract-facts-scope.serial.test.ts
+++ b/test/connector-cycle-extract-facts-scope.serial.test.ts
@@ -66,6 +66,18 @@ describe('#6803 connector cycle extract_facts scope', () => {
}
}), 180_000);
+ test('with managed persistence (no watermark drain) the cycle still reconciles the source\'s changed pages', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const { connector } = await seed(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const out = await makeAutopilotCycleHandler(engine)({ id: 4, data: { source_id: connector } } as never) as {
+ report: { phases: Array<{ phase: string; status: string; details: Record<string, unknown> }> };
+ };
+ expect(Number(out.report.phases.find(p => p.phase === 'extract_facts')!.details.pagesScanned)).toBe(1);
+ await disposePersistenceConsumer(engine);
+ }
+ }), 180_000);
+
test('a full walk for one source never visits another source\'s slugs', async () => withEnv(env, async () => {
for (const engine of engines) {
const { connector } = await seed(engine);