Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.42.18.0 fix: sync orphan-pileup watchdog (#1633) + links-lag µs stamp (#1768) (#1807)
Garry Tanbde11bb18f66
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cab3b27250..ab7b8f8b5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,31 @@All notable changes to GBrain will be documented in this file.+## [0.42.18.0] - 2026-06-03++**A scheduled `gbrain sync` can no longer spin forever and pile up dead processes, and `gbrain doctor` stops showing "100% of pages need link extraction" right after you ran the thing that's supposed to fix it.**++Two unrelated bugs, both reported from real Postgres/Supabase brains, both fixed here.++The first one is the scary one. A `gbrain sync --source <id>` fired from cron could get stuck in a busy loop, peg a CPU core, and ignore `Ctrl-C` and `kill` (only `kill -9` stopped it). When the cron parent exited, the stuck sync was left orphaned, and the next cron tick spawned another. One reporter woke up to 13 of them, 24+ hours old, thrashing a 16 GB Mac mini down to 121 MB free. The root cause: when a sync spins on synchronous work, it starves its own event loop, so the SIGTERM handler and `--timeout` that gbrain already had could never actually run.++The fix is a watchdog that runs on a separate OS thread and kills the process from outside the starved loop. On a non-interactive run (cron), gbrain now arms a hard deadline by default (1 hour), sends SIGTERM at the deadline for a clean exit, and SIGKILL shortly after if the process is too wedged to respond. A runaway sync now dies on its own instead of piling up. Sync is resumable, so a deadline-hit run just picks up next tick.++- **Default on for cron, off for you at the keyboard.** Interactive (TTY) syncs stay unbounded. Tune the cron deadline with `GBRAIN_SYNC_MAX_RUNTIME_SECONDS=N`, set a one-off with `gbrain sync --hard-deadline 600`, or opt out with `--no-hard-deadline`. `gbrain sync --source x --timeout 300` now also arms the hard backstop automatically.+- **`Ctrl-C` is clean now too.** Hitting Ctrl-C during a long sync returns a partial result and releases the lock through the normal path, instead of a hard cut that could leave the sync lock stuck until its TTL expired.+- **The spin itself isn't root-caused yet** (it needs a live reproduction; the leading suspect is a pathological regex in a schema pack's link rules, already partly mitigated). The watchdog makes the *symptom* impossible. A `[sync-watchdog]` heartbeat line in your logs, plus the existing `[gbrain phase]` lines, will pinpoint where the next one hangs.++The second fix: on Postgres, `gbrain doctor`'s `links_extraction_lag` check was permanently stuck at 100%. You'd run `gbrain extract --stale`, it would stamp every page as extracted, and the check would still say every page needs extraction. The stamp was being truncated to millisecond precision while the database kept microseconds, so "last extracted" always looked a hair older than "last updated." Now the stamp carries full microsecond precision and the check clears the moment extraction runs. (Postgres-only; the health score stops being dragged down by a check that could never pass.)++## To take advantage of v0.42.18.0++`gbrain upgrade` is all that's required — both fixes are automatic. Two things worth knowing:++1. **Scheduled (non-interactive) syncs now have a 1-hour hard deadline by default.** If you run a legitimately long sync from cron (e.g. a first import of a very large brain), raise it: `GBRAIN_SYNC_MAX_RUNTIME_SECONDS=14400 gbrain sync ...` (4h), pass `gbrain sync --hard-deadline <seconds>`, or opt out with `--no-hard-deadline`. Interactive runs at your keyboard are unbounded as before.+2. **Verify the link-extraction fix (Postgres):** `gbrain extract --stale` then `gbrain doctor` — the `links_extraction_lag` check should now read near 0% and stay there on a re-run (it was stuck at 100%).++### For contributors+- New reusable primitive `src/core/process-watchdog.ts` (Bun worker-thread self-kill, `eval:true` so it survives `bun --compile`); `resolveSyncHardDeadline` + `composeAbortSignals` in `sync.ts`; watchdog armed in `cli.ts` before `connectEngine` (bounds connect-phase hangs). #1768 fix threads a full-µs `updated_at_iso` (projected via `to_char(... AT TIME ZONE 'UTC', '…US"Z"')`) into `StalePageRow`; the `markPagesExtractedBatch` SQL is unchanged so the version-arm / CDX-1 tests stay green. New tests: `test/process-watchdog.test.ts` (+ `.serial`), `test/sync-hard-deadline.test.ts`, and a deterministic µs regression in `test/extract-stale.test.ts`. Eng review + Codex outside-voice both cleared the plan (Codex empirically validated the worker-self-kill on Bun 1.3.13).## [0.42.17.0] - 2026-06-03**A huge `gbrain sync` can no longer get stuck forever losing all its progress when it's killed partway through.** If your brain suddenly grows by tens of thousands of pages (say a background process is enriching one page per commit, all night long), the next sync has a giant backlog to import. If that sync gets killed before it finishes — a session timeout, a laptop sleep, anything — it used to throw away **everything** it had done and start over from zero. The next hour the backlog was even bigger, so it got killed again, and again. It could never catch up. This release makes sync **resumable**: a killed sync banks what it imported, and the next run picks up where it left off. It converges.diff --git a/VERSION b/VERSIONindex 343912cea8..2ff0d04653 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.42.17.0\ No newline at end of file+0.42.18.0\ No newline at end of filediff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 1a6c07e32c..a0aeb9753f 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -144,6 +144,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/dry-fix.ts` — `gbrain doctor --fix` engine. `autoFixDryViolations(fixes, {dryRun})` rewrites inlined rules to `> **Convention:** see [path](path).` callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (`getWorkingTreeStatus()` 3-state `'clean' | 'dirty' | 'not_a_repo'`), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout. `execFileSync` array args (no shell, no injection surface). EOF newline preserved. Safety primitives are in `src/core/skill-fix-gates.ts` (back-compat re-exports preserved). `MISSING_RULE_PATTERNS` INSERT pattern type lives alongside REPLACE patterns — same auto-fix entry point + git-safety gates, but places a canonical callout at a target offset (`after-h1-paragraph` only). First INSERT pattern is `brain_first`, auto-inserting `> **Convention:** see [conventions/brain-first.md](../conventions/brain-first.md) for the lookup chain (search → query → get_page → external).` on any flagged SKILL.md whose verdict is `missing_brain_first`. Idempotent — re-runs detect the existing callout and skip.- `src/core/backoff.ts` — Adaptive load-aware throttling: CPU/memory checks, exponential backoff, active hours multiplier.- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter allowed near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).+- `src/core/process-watchdog.ts` (#1633) — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+ (the reported incident). `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests. Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Reusable beyond sync (autopilot/cycle are follow-up adopters). Pinned by `test/process-watchdog.test.ts` (pure decision matrix + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).- `src/core/audit/batch-retry-audit.ts` — JSONL audit primitive for batch-retry events, built on `audit-writer.ts`. Schema: `{ts, site, batch_size, attempt, outcome: 'success' | 'exhausted', delay_ms, error_message_summary, error_code?}`. Privacy: NEVER logs slugs / page IDs / content (mirrors `shell-audit.ts`). `logBatchRetry` fires per successful retry recovery; `logBatchExhausted` fires when retries exhaust and rows are lost. `readRecentBatchRetryEvents(hours=24)` returns `{events, corrupted_lines, files_scanned, files_unreadable}` — corruption + permission errors surface to doctor, not silently swallowed. `pruneOldBatchRetryAuditFiles(daysToKeep=30)` deletes old files, called from `gbrain dream --phase purge`. File: `~/.gbrain/audit/batch-retry-YYYY-Www.jsonl` (honors `GBRAIN_AUDIT_DIR`). `summarizeError` routes error messages through the shared `redactConnectionInfo` helper from `src/core/audit/redact-connection-info.ts` BEFORE truncation so DSNs / hostnames / credentials / IPv4 octets can't leak into operator-shared JSONL dumps. Pinned by `test/audit/batch-retry-audit.test.ts` (12 cases) + `test/audit/batch-retry-redaction.test.ts` (3 privacy regressions).- `src/core/audit/lock-renewal-audit.ts` — JSONL audit primitive for per-job lock-renewal faults. Sibling of `batch-retry-audit.ts`, built on `audit-writer.ts`. Four outcomes: `failure` (single renewLock throw, counter incremented), `success_after_failure` (recovery; emits the recovery count), `gave_up` (time-based deadline exceeded; abort fired), `executeJob_rejected` (the second unhandledRejection vector — the stored `executeJob(...).finally(...)` promise itself rejected, e.g. failJob threw during the same DB outage). Schema: `{ts, job_id, job_name, attempt?, outcome, error_message_summary?, error_code?}`. Privacy: NEVER logs `lock_token` or `job.data`; error summaries route through `redactConnectionInfo` BEFORE truncation. Defense-in-depth: every audit call inside the lock-renewal tick's catch block is wrapped in its own inner try/catch so a misbehaving audit-writer can't re-introduce the unhandledRejection bug class. `readRecentLockRenewalEvents(hours=24)` walks current + previous ISO week with corrupted-line tolerance. `pruneOldLockRenewalAuditFiles(daysToKeep=30)` is ready for future dream-cycle purge wiring. File: `~/.gbrain/audit/lock-renewal-YYYY-Www.jsonl`. Pinned by `test/audit/lock-renewal-audit.test.ts` (11 cases).- `src/core/audit/redact-connection-info.ts` — Shared pure helper. `redactConnectionInfo(text: string): string` strips Postgres connection info before any audit JSONL write: `postgres://`/`postgresql://` URLs, `host=foo`, `user=foo`, `password=foo`, `pwd=foo`, IPv4 octets — each match becomes `<REDACTED:kind>`. Negative-lookbehind/lookahead `[\w.@-]` on the IPv4 pattern defeats version-string false positives (`v3.1.4.0`, `[email protected]`) while still matching real IPs in PG errors (`(192.168.1.42)`). Order-sensitive pattern set: URL forms first so substrings inside URLs don't get double-redacted. Idempotent, pure (no I/O), hot-path-safe (regex compiled at module load). Wired into BOTH `lock-renewal-audit.ts` AND `batch-retry-audit.ts`. Known limitations: bare-quoted hostnames (`at "db.example.com"`) and usernames (`for user "postgres.foo"`) are NOT caught — the highest-value leak (the IP in those shapes) IS caught. Pinned by `test/audit/redact-connection-info.test.ts` (15 cases: all 5 patterns + Supabase fixture + ENOTFOUND fixture + version-string false-positive defense).@@ -170,7 +171,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email pages, splits into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and runs through `extractFactsFromTurn()` so anchor-rich facts surface in `gbrain search`. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because PHASE_SCOPE='source' is taxonomy-only); **two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap MAX_PAGE_BODY_BYTES=25MB with `pages_skipped_too_large` counter surfaced in doctor); **page-global row_num accumulator** (facts unique index is `(source_id, source_markdown_slug, row_num)` per migration v51 — per-segment row_num would collide); **page-level TERMINAL audit row** to facts table after all segments commit (source='cli:extract-conversation-facts:terminal'; doctor's NOT EXISTS matches the terminal row so partial-extraction pages stay in backlog); **optional `opts.budgetTracker?`** (when present, used as-is — nested `withBudgetTracker` REPLACES; when absent, core auto-wraps with `BudgetTracker({maxCostUsd})`); **body read covers compiled_truth + timeline**; **honors `facts.extraction_enabled` kill-switch** with `--override-disabled` escape; **--types LIST allowlist** (`conversation,meeting,slack,email`) with CLI default reading `cycle.conversation_facts_backfill.types`; **fingerprint on sourceId only**; **string-encoded op-checkpoint** entries `"<sourceId>|<slug>|<endIso>"` for resume (durable audit is the facts terminal row); **`--background` via maybeBackground** (Minion handler `extract-conversation-facts` re-creates BudgetTracker from `data.max_cost_usd`; on `BudgetExhausted` mid-job catches + persists + marks `completed` with `result.budget_exhausted=true`). The companion cycle phase `conversation_facts_backfill` (default OFF) iterates `listSources(engine)`, creates ONE brain-wide tracker per tick + wraps the loop in `withBudgetTracker` + passes the tracker into every per-source call. Two-layer cost AND walltime caps: per-source (`max_cost_usd=$1`, `max_walltime_min=20`) AND brain-wide (`max_total_cost_usd=$5`, `max_total_walltime_min=30`). Pinned by `test/extract-conversation-facts.test.ts` (27 cases). Migration v94 adds partial index `idx_facts_extract_conversation_session ON facts(source_id, source_session) WHERE source LIKE 'cli:extract-conversation-facts%'` (`transaction:false` + invalid-index pre-drop on Postgres; plain CREATE INDEX on PGLite). `src/commands/doctor.ts:computeConversationFactsBacklogCheck` is 3-state (SKIPPED when disabled; OK when caught up; WARN when >10 pages lack the terminal row, with paste-ready `gbrain doctor --remediate` step). `src/commands/sources.ts:runAudit` adds `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Schema-pack `gbrain-base.yaml` promotes `conversation` (temporal, extractable) + `atom` (annotation, NOT extractable) into the base seed; backstop uses hardcoded `ELIGIBLE_TYPES` in `src/core/facts/eligibility.ts:51` not pack extractable. `ALL_PAGE_TYPES` in `src/core/types.ts` extended with the two new types.- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. `DIR_PATTERN` covers `people`, `companies`, `deals`, `topics`, `concepts`, `projects`, `entities`, `tech`, `finance`, `personal`, `openclaw`. Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (issue #972, default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter` (replaces the old `nullResolver` ternary). All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.-- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three new `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). Race fix: `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` gains `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` adds `'extract.stale'` to `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` adds `links_extraction_lag` to `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp regression + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip.+- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three new `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). Race fix: `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` gains `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` adds `'extract.stale'` to `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` adds `links_extraction_lag` to `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp regression + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite regression in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).- `src/commands/import.ts` — `gbrain import <path> [--source-id <id>]`: page import with the path-set checkpoint. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). Pinned by `test/import-source-id.test.ts`.- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). Foreign-edge footer always present (`X foreign edges (use --include-foreign to traverse)`) so cross-source edges never disappear silently; `--include-foreign` widens the SQL filter to walk them. Pinned by `test/graph-query.test.ts`.@@ -277,7 +278,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/embedding-dim-check.ts` extension — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. Pinned by `test/embedding-dim-check-facts.test.ts`.- `src/core/postgres-engine.ts` extension — `insertFact` + `insertFacts` no longer hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache.- `src/core/cycle.ts` + `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts` extensions — six daily-driver ops fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Shorter cycle lock TTL + active in-phase refresh: `LOCK_TTL_MINUTES = 5` (was 30); `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock 6x faster while a healthy long-running cycle keeps it alive (residual: a single `await chat()` past 5 min can expire the lock mid-await — TODO-OPS-2). (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`.-- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; legacy single-default-source brains keep the bare `tryAcquireDbLock(SYNC_LOCK_ID)` path; `SyncOpts.lockId?: string` is the explicit override. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths in two `op_checkpoints` rows (both keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` — an `op:'sync'` paths row + an `op:'sync-target'` target row) via `recordCompleted` every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files, and advances `last_commit`/`last_sync_at` ONLY at full import completion. A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` reject when combined with `--parallel > 1` (the brain-global `sync-failures.jsonl` has no per-source scope); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok, 1 any error, 2 cost-prompt-not-confirmed. The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The `sync --all` cost gate is mode-aware via `willEmbedSynchronously` + `shouldBlockSync` from `src/core/embedding.ts` (federated_v2 resolved once up front): the DEFERRED path (v2 on, parallel) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog `sumStaleChunkChars({signature})` priced via `estimateCostFromChars` at `currentEmbeddingPricePerMTok()` + queued-job count, NEVER exits 2); the INLINE path BLOCKS only when the new-content estimate exceeds `sync.cost_gate_min_usd` (default $0.50). The new-content estimate (`estimateInlineNewTokens`) contributes ZERO for sources provably unchanged since last sync (`isSourceUnchangedSinceSync` HEAD==last_commit + clean tree AND `chunker_version === CURRENT`) and the full-tree ceiling for changed sources; the pre-existing stale backlog is shown informationally but NEVER gated on (sync doesn't sweep it inline). Helpers `resolveCostGateFloorUsd(engine)` (fail-open $0.50, accepts 0) + `resolveBackfillCapUsd(engine)`. JSON envelopes gain `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | confirmation_required`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (PGLite single-writer serve↔sync contention + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`.+- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; legacy single-default-source brains keep the bare `tryAcquireDbLock(SYNC_LOCK_ID)` path; `SyncOpts.lockId?: string` is the explicit override. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths in two `op_checkpoints` rows (both keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` — an `op:'sync'` paths row + an `op:'sync-target'` target row) via `recordCompleted` every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files, and advances `last_commit`/`last_sync_at` ONLY at full import completion. A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` reject when combined with `--parallel > 1` (the brain-global `sync-failures.jsonl` has no per-source scope); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok, 1 any error, 2 cost-prompt-not-confirmed. The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The `sync --all` cost gate is mode-aware via `willEmbedSynchronously` + `shouldBlockSync` from `src/core/embedding.ts` (federated_v2 resolved once up front): the DEFERRED path (v2 on, parallel) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog `sumStaleChunkChars({signature})` priced via `estimateCostFromChars` at `currentEmbeddingPricePerMTok()` + queued-job count, NEVER exits 2); the INLINE path BLOCKS only when the new-content estimate exceeds `sync.cost_gate_min_usd` (default $0.50). The new-content estimate (`estimateInlineNewTokens`) contributes ZERO for sources provably unchanged since last sync (`isSourceUnchangedSinceSync` HEAD==last_commit + clean tree AND `chunker_version === CURRENT`) and the full-tree ceiling for changed sources; the pre-existing stale backlog is shown informationally but NEVER gated on (sync doesn't sweep it inline). Helpers `resolveCostGateFloorUsd(engine)` (fail-open $0.50, accepts 0) + `resolveBackfillCapUsd(engine)`. JSON envelopes gain `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | confirmation_required`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (PGLite single-writer serve↔sync contention + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`).- `src/commands/import.ts` — `gbrain import` CLI + `runImport` library entrypoint. Uses a path-set checkpoint via `src/core/import-checkpoint.ts` (the walk still applies `sortNewestFirst()` for embed-cost ordering, but checkpoint correctness no longer depends on sort order). A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. This closes three classes: parallel-import-with-slow-worker dropping the slow file on crash-resume (the slow file isn't in `completed` until its own `processFile` resolves), failed-file-bumps-counter-past-itself (failures don't add to `completed`), and sort-flip-drops-newest-N-on-cross-version-resume (order is no longer part of the checkpoint). Old positional checkpoints are detected and discarded with a stderr line on first resume (re-walking is cheap because `content_hash` short-circuits unchanged files). Checkpoint persists every 100 successful adds, not every 100 processed files. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry regression).- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).diff --git a/package.json b/package.jsonindex b679afbc08..a022efddc1 100644--- a/package.json+++ b/package.json@@ -143,5 +143,5 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.42.17.0"+ "version": "0.42.18.0"}diff --git a/src/cli.ts b/src/cli.tsindex 6b3c2de08f..c9bfe10cfc 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1439,6 +1439,39 @@ async function handleCliOnly(command: string, args: string[]) {return;}+ // #1633: out-of-band hard-deadline watchdog for `gbrain sync`. Installed+ // BEFORE connectEngine so a connect-phase hang (the reported zombie class) is+ // bounded too. A Bun Worker on its own OS thread SIGKILLs the process at the+ // deadline even when the main event loop is starved by a synchronous spin —+ // the only thing that stops the cron orphan-pileup. Disposed in the finally.+ let syncWatchdog: { dispose(): void } | null = null;+ if (command === 'sync') {+ try {+ const { resolveSyncHardDeadline } = await import('./commands/sync.ts');+ const res = resolveSyncHardDeadline(args, {+ isTty: Boolean(process.stdout.isTTY),+ env: process.env,+ });+ if (res) {+ const { installProcessWatchdog } = await import('./core/process-watchdog.ts');+ syncWatchdog = installProcessWatchdog({+ deadlineMs: res.deadlineMs,+ graceMs: res.graceMs,+ label: 'sync-watchdog',+ heartbeatMs: 60_000,+ });+ process.stderr.write(+ `[sync-watchdog] hard deadline armed: ${Math.round(res.deadlineMs / 1000)}s ` ++ `+ ${Math.round(res.graceMs / 1000)}s grace (${res.reason}); disable with --no-hard-deadline\n`,+ );+ }+ } catch (e) {+ // A bad --hard-deadline value throws here (same posture as --timeout).+ console.error(e instanceof Error ? e.message : String(e));+ process.exit(1);+ }+ }+// All remaining CLI-only commands need a DB connectionconst engine = await connectEngine();try {@@ -1875,6 +1908,7 @@ async function handleCliOnly(command: string, args: string[]) {}}} finally {+ syncWatchdog?.dispose(); // #1633: tear down the hard-deadline watchdog on clean exitif (command !== 'serve') await engine.disconnect();}}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 04ab7e3d4e..a4a8bb7888 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -1636,7 +1636,12 @@ async function extractStaleFromDB(// landing between this SELECT and the stamp advances updated_at past the// stamped value, so the page stays stale and re-extracts next run instead// of being marked fresh-with-stale-content.- processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: page.updated_at.toISOString() });+ //+ // #1768: stamp the FULL-µs `updated_at_iso` (projected via to_char), NOT+ // `page.updated_at.toISOString()` — the JS Date is ms-truncated, so the+ // µs-precision DB updated_at stayed strictly greater and the page never+ // cleared on Postgres. Stamping the exact value makes them equal.+ processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: page.updated_at_iso });}// Flush NON-swallowing (CDX-4): a throw here propagates out of the sweep sodiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 852ec4d911..bee832d5fb 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -2348,6 +2348,85 @@ async function performFullSync(};}+/**+ * Grace window (seconds) between the watchdog's SIGTERM and SIGKILL. SIGTERM+ * gives a responsive loop a clean shutdown; SIGKILL is the starvation backstop.+ */+export const HARD_DEADLINE_GRACE_SEC = 30;++export interface HardDeadlineResolution {+ deadlineMs: number;+ graceMs: number;+ /** Where the deadline came from (for the armed-log line + tests). */+ reason: string;+}++/**+ * Resolve the out-of-band hard-deadline for a `gbrain sync` invocation (#1633).+ * Pure + argv/env-only so it runs BEFORE `connectEngine` (so a connect-phase hang+ * is also bounded — `timeout-layer-vs-connectengine` learning). DB-plane config+ * (`gbrain config set`) is unreadable pre-connect, so the operator knob is the+ * `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env var; bare cron is covered by the non-TTY+ * default. Returns null when no watchdog should arm (TTY interactive with no+ * flag, or an explicit opt-out / 0).+ *+ * Precedence: --no-hard-deadline > --hard-deadline > --timeout(non-all) > env >+ * non-TTY default (3600s) > none.+ */+export function resolveSyncHardDeadline(+ args: string[],+ opts: { isTty: boolean; env?: Record<string, string | undefined>; defaultNonTtySec?: number },+): HardDeadlineResolution | null {+ const env = opts.env ?? {};+ const graceMs = HARD_DEADLINE_GRACE_SEC * 1000;+ const mk = (sec: number, reason: string): HardDeadlineResolution | null =>+ sec > 0 ? { deadlineMs: sec * 1000, graceMs, reason } : null;++ if (args.includes('--no-hard-deadline')) return null;++ const hardStr = args.find((a, i) => args[i - 1] === '--hard-deadline');+ if (hardStr !== undefined) {+ // Throws on a bad value (cli.ts surfaces it + exits 1) — same posture as --timeout.+ const sec = parseDurationSeconds(hardStr, '--hard-deadline');+ return mk(sec ?? 0, 'flag:--hard-deadline');+ }++ // --timeout auto-arms a hard backstop at timeout(+grace), but ONLY single-source.+ // For --all, per-source budgets don't collapse to one wall-clock; fall through.+ const isAll = args.includes('--all');+ const timeoutStr = args.find((a, i) => args[i - 1] === '--timeout');+ if (timeoutStr !== undefined && !isAll) {+ const sec = parseDurationSeconds(timeoutStr, '--timeout');+ if (sec && sec > 0) return mk(sec, 'flag:--timeout');+ }++ const envRaw = env.GBRAIN_SYNC_MAX_RUNTIME_SECONDS;+ if (envRaw !== undefined && envRaw !== '') {+ const n = Number(envRaw);+ if (Number.isFinite(n)) return mk(n, 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS'); // n<=0 disables+ }++ if (!opts.isTty) return mk(opts.defaultNonTtySec ?? 3600, 'default:non-tty');++ return null;+}++/**+ * Compose 1..N AbortSignals into one (CQ2). Undefined inputs are dropped; the+ * result aborts when ANY input aborts. Returns a single signal directly (no+ * wrapper), `undefined` when nothing is set. Used at both performSync call sites+ * so the SIGINT graceful-cancel signal and the per-source `--timeout` signal+ * compose without duplicating `AbortSignal.any` logic.+ */+export function composeAbortSignals(+ ...signals: Array<AbortSignal | undefined>+): AbortSignal | undefined {+ const live = signals.filter((s): s is AbortSignal => s !== undefined);+ if (live.length === 0) return undefined;+ if (live.length === 1) return live[0];+ return AbortSignal.any(live);+}+export async function runSync(engine: BrainEngine, args: string[]) {// v0.40 Federated Sync v2: `gbrain sync trigger` subcommand// Routes to runSyncTrigger which queues a 'sync' minion job with@@ -2827,6 +2906,13 @@ See also:};const perSourceResults: PerSourceResult[] = [];+ // #1633 (Part B): one shared SIGINT controller for the whole --all fan-out.+ // process-cleanup.ts doesn't own SIGINT, so without this Ctrl-C hard-cuts the+ // run and can leak per-source locks; here it aborts every in-flight source so+ // each performSync returns `partial` + releases its lock cleanly.+ const allInterrupt = new AbortController();+ const onAllSigint = () => { try { allInterrupt.abort(new Error('SIGINT')); } catch { /* */ } };+const runOne = async (src: typeof sources[number]): Promise<SyncResult> => {const cfg = (src.config || {}) as { strategy?: 'markdown' | 'code' | 'auto' };// D18: parallel path defers embed; auto-enqueue embed-backfill after.@@ -2862,7 +2948,7 @@ See also:sourceId: src.id,strategy: cfg.strategy,concurrency,- signal: controller?.signal,+ signal: composeAbortSignals(allInterrupt.signal, controller?.signal),};// v0.40.6.0 (D6): wrap performSync in withSourcePrefix so every slog /// serr line emitted from inside the sync code path gets prefixed with@@ -2941,6 +3027,8 @@ See also:? Math.min(activeSources.length, maxSources ?? 8): 1;+ process.on('SIGINT', onAllSigint);+ try {if (parallelEligible) {const { pMapAllSettled } = await import('../core/parallel.ts');const cap = effectiveParallel;@@ -3013,6 +3101,9 @@ See also:}}}+ } finally {+ process.off('SIGINT', onAllSigint);+ }const okCount = perSourceResults.filter((r) => r.status === 'ok').length;const errCount = perSourceResults.filter((r) => r.status === 'error').length;@@ -3062,10 +3153,17 @@ See also:? setTimeout(() => singleSourceController!.abort(), timeoutSeconds * 1000): undefined;singleSourceTimer?.unref?.();+ // #1633 (Part B): graceful SIGINT cancel. process-cleanup.ts owns SIGTERM+ // (lock release + exit) and the watchdog owns the hard deadline; SIGINT is+ // deliberately left to callers, so Ctrl-C during a long sync aborts the+ // in-flight import cleanly (performSync returns `partial`, bookmark unadvanced,+ // lock released by its own finally) instead of a hard cut.+ const singleSourceInterrupt = new AbortController();+ const onSingleSourceSigint = () => { try { singleSourceInterrupt.abort(new Error('SIGINT')); } catch { /* */ } };const opts: SyncOpts = {repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, noSchemaPack, sourceId,strategy: strategyArg, concurrency,- signal: singleSourceController?.signal,+ signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),};// Bug 9 — --retry-failed: before running normal sync, clear acknowledgment@@ -3086,10 +3184,12 @@ See also:// v0.41.13.0 (T6): try/finally clears the single-source timer so it// doesn't fire after performSync resolves OR throws.let result: SyncResult;+ process.on('SIGINT', onSingleSourceSigint);try {result = await performSync(engine, opts);} finally {if (singleSourceTimer !== undefined) clearTimeout(singleSourceTimer);+ process.off('SIGINT', onSingleSourceSigint);}printSyncResult(result);// v0.42.7 (#1696, D5): extraction-lag nudge after a completed single-sourcediff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex f69fa0f39c..4c01e4ce2a 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -672,6 +672,10 @@ export async function withRefreshingLock<T>(}})();}, refreshIntervalMs);+ // #1633: don't let the refresh timer keep the process alive on its own. The+ // finally clearInterval is the primary cleanup; unref is belt-and-suspenders+ // so a missed clear can't pin the event loop open past real work completion.+ (interval as unknown as { unref?: () => void }).unref?.();try {return await work();diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex aa5ffa1f69..93157bb9a1 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2358,7 +2358,10 @@ export class PGLiteEngine implements BrainEngine {params.push(opts.batchSize);const limitIdx = params.length;const { rows } = await this.db.query(- `SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at+ // #1768: engine parity — project the same deterministic full-µs UTC string+ // as postgres-engine.ts so extractStaleFromDB stamps the exact updated_at.+ `SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at,+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_isoFROM pagesWHERE ${where}${afterClause}ORDER BY iddiff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 9126909a69..5b50d51e4a 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -2420,7 +2420,11 @@ export class PostgresEngine implements BrainEngine {params.push(opts.batchSize);const limitIdx = params.length;const rows = await this.sql.unsafe(- `SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at+ // #1768: project a deterministic full-µs UTC string alongside updated_at.+ // to_char (not ::text — DateStyle-fragile) so extractStaleFromDB can stamp+ // links_extracted_at = the exact updated_at and the staleness predicate clears.+ `SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at,+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_isoFROM pagesWHERE ${where}${afterClause}ORDER BY iddiff --git a/src/core/process-watchdog.ts b/src/core/process-watchdog.tsnew file mode 100644index 0000000000..60b7b5c36d--- /dev/null+++ b/src/core/process-watchdog.ts@@ -0,0 +1,172 @@+/**+ * Out-of-band hard-deadline watchdog (#1633).+ *+ * THE PROBLEM. A `gbrain sync` that spins (e.g. synchronous catastrophic-regex+ * in pack link-inference) STARVES the main event loop. When the loop never+ * yields, the SIGTERM handler (process-cleanup.ts) can't run, a `--timeout`+ * `setTimeout` can't fire, and the abort-flag checks between import iterations+ * can't run either. The process becomes unkillable-by-SIGTERM and, under cron,+ * orphans pile up for 24h+ (the reported incident). The ONLY thing that kills a+ * loop-starved process is an OS signal delivered from OUTSIDE that loop.+ *+ * THE MECHANISM. A Bun `worker_threads` Worker runs on a real, independent OS+ * thread with its own event loop. Its timer fires even while the main thread is+ * in an unyielding synchronous loop. At the deadline it sends SIGTERM to its own+ * process (a clean-shutdown chance if the loop happens to be responsive); at+ * deadline+grace it sends SIGKILL (uncatchable — guaranteed death even when+ * starved). Signaling SELF (`process.kill(process.pid, ...)`) has no PID-reuse+ * footgun: the current process's PID is never reused while it's alive. (The+ * rejected alternative — a detached child that signals the PARENT pid — CAN hit+ * PID reuse and kill an innocent process.)+ *+ * `eval: true` keeps the worker body an inline string so it bakes into the+ * `bun build --compile` binary with no separate-file embedding to worry about.+ * Empirically validated on Bun 1.3.13 (a Worker timer fired + SIGKILLed the+ * process while main was in `while(true){}`).+ *+ * ┌─ main thread (may be starved) ──────────────┐ ┌─ watchdog worker (OS thread) ─┐+ * │ sync work / ReDoS spin / connect hang │ │ t=deadline -> SIGTERM │+ * │ ...never yields... │ │ t=deadline+grace-> SIGKILL │+ * │ on clean finish: handle.dispose() ──────────┼──▶│ worker.terminate() │+ * └──────────────────────────────────────────────┘ └────────────────────────────────┘+ *+ * Reusable beyond sync (autopilot / cycle are follow-up adopters): the API is+ * just (deadline, grace, label).+ */++import { Worker } from 'node:worker_threads';++export type WatchdogAction = 'wait' | 'sigterm' | 'sigkill';++/**+ * Pure decision function — the watchdog's whole state machine, extracted so it's+ * unit-testable without spawning threads or real timers.+ * elapsed < deadline -> 'wait'+ * deadline <= elapsed < +grace -> 'sigterm' (clean-shutdown chance)+ * elapsed >= deadline + grace -> 'sigkill' (guaranteed)+ */+export function watchdogDecision(elapsedMs: number, deadlineMs: number, graceMs: number): WatchdogAction {+ if (elapsedMs >= deadlineMs + graceMs) return 'sigkill';+ if (elapsedMs >= deadlineMs) return 'sigterm';+ return 'wait';+}++export interface ProcessWatchdogOpts {+ /** Wall-clock ms after which SIGTERM is sent. Must be > 0 or the watchdog is a no-op. */+ deadlineMs: number;+ /** ms after the deadline before SIGKILL. Default 30_000. */+ graceMs?: number;+ /** Prefix for stderr log lines, e.g. 'sync-watchdog'. Default 'watchdog'. */+ label?: string;+ /** Periodic "still alive, kill in Ns" heartbeat interval ms. 0 = off (default). */+ heartbeatMs?: number;+ /** Injectable warn sink (tests). Default writes to process.stderr. */+ onWarn?: (msg: string) => void;+}++export interface WatchdogHandle {+ /** Tear down the watchdog (clean completion). Idempotent. */+ dispose(): void;+ /** True when an out-of-band worker is actually running (false on no-op / fallback). */+ readonly active: boolean;+}++const DEFAULT_GRACE_MS = 30_000;++function defaultWarn(msg: string): void {+ try { process.stderr.write(msg + '\n'); } catch { /* stderr may be broken */ }+}++const INERT: WatchdogHandle = { dispose() {}, get active() { return false; } };++/**+ * Worker body (runs on its own OS thread). Inline string so `eval: true` bakes+ * it into the compiled binary. Uses only built-ins available in a Bun worker.+ *+ * `label` is validated by the caller to a safe charset before it reaches here,+ * so it can't break the string literal or inject log lines.+ */+const WORKER_SRC = `+const { workerData } = require('node:worker_threads');+const { deadlineMs, graceMs, label, heartbeatMs } = workerData;+const t0 = Date.now();+function w(m) { try { process.stderr.write('[' + label + '] ' + m + '\\n'); } catch (e) {} }+if (heartbeatMs > 0) {+ const hb = setInterval(() => {+ const elapsed = Math.round((Date.now() - t0) / 1000);+ const killIn = Math.round((deadlineMs + graceMs - (Date.now() - t0)) / 1000);+ w('parent alive ' + elapsed + 's elapsed, hard-kill in ~' + killIn + 's');+ }, heartbeatMs);+ if (typeof hb.unref === 'function') hb.unref();+}+setTimeout(() => {+ w('deadline reached (' + Math.round(deadlineMs/1000) + 's) — sending SIGTERM for graceful shutdown');+ try { process.kill(process.pid, 'SIGTERM'); } catch (e) {}+}, deadlineMs);+setTimeout(() => {+ w('grace expired — sending SIGKILL (event loop was starved; this is the orphan-pileup backstop)');+ try { process.kill(process.pid, 'SIGKILL'); } catch (e) {}+}, deadlineMs + graceMs);+`;++/**+ * Install the out-of-band hard-deadline watchdog. Returns a handle whose+ * `dispose()` MUST be called on clean completion (a `finally`) so the worker is+ * torn down. If the deadline is non-positive, returns an inert no-op handle.+ *+ * Fallback: if the Worker can't be constructed (unexpected on Bun), degrades to+ * an in-process timer with a loud warning. The in-process timer canNOT fire+ * under event-loop starvation — it only covers the responsive case — so the+ * warning tells the operator the hard guarantee is degraded.+ */+export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandle {+ const warn = opts.onWarn ?? defaultWarn;+ const deadlineMs = Math.floor(opts.deadlineMs);+ const graceMs = Math.max(0, Math.floor(opts.graceMs ?? DEFAULT_GRACE_MS));+ // Sanitize label to a safe charset (defends the inline worker string + log lines).+ const label = (opts.label ?? 'watchdog').replace(/[^A-Za-z0-9_.:-]/g, '').slice(0, 40) || 'watchdog';+ const heartbeatMs = Math.max(0, Math.floor(opts.heartbeatMs ?? 0));++ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return INERT;++ try {+ const worker = new Worker(WORKER_SRC, {+ eval: true,+ workerData: { deadlineMs, graceMs, label, heartbeatMs },+ });+ // Don't let the watchdog keep the process alive past clean completion.+ (worker as unknown as { unref?: () => void }).unref?.();+ // A worker-side error must never crash the host; log and move on.+ worker.on('error', (err) => warn(`[${label}] watchdog worker error: ${err instanceof Error ? err.message : String(err)}`));+ let disposed = false;+ return {+ dispose() {+ if (disposed) return;+ disposed = true;+ void worker.terminate();+ },+ get active() { return !disposed; },+ };+ } catch (err) {+ // Fallback: in-process timer. Starvation-vulnerable — say so loudly.+ warn(+ `[${label}] could not start out-of-band watchdog (${err instanceof Error ? err.message : String(err)}); ` ++ `falling back to an in-process timer that will NOT fire if the event loop is starved.`,+ );+ let killed = false;+ const term = setTimeout(() => { try { process.kill(process.pid, 'SIGTERM'); } catch { /* */ } }, deadlineMs);+ const kill = setTimeout(() => { killed = true; try { process.kill(process.pid, 'SIGKILL'); } catch { /* */ } }, deadlineMs + graceMs);+ (term as unknown as { unref?: () => void }).unref?.();+ (kill as unknown as { unref?: () => void }).unref?.();+ let disposed = false;+ return {+ dispose() {+ if (disposed || killed) return;+ disposed = true;+ clearTimeout(term);+ clearTimeout(kill);+ },+ get active() { return !disposed; },+ };+ }+}diff --git a/src/core/types.ts b/src/core/types.tsindex 4110a945e1..2933c42a5b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -608,6 +608,15 @@ export interface StalePageRow {timeline: string;frontmatter: Record<string, unknown>;updated_at: Date;+ /**+ * Full-precision (microsecond) UTC ISO string of `updated_at`, projected+ * straight from the DB via `to_char(... AT TIME ZONE 'UTC', '...US"Z"')`.+ * `updated_at` (a JS `Date`) is millisecond-truncated, so stamping it back as+ * `links_extracted_at` left the row permanently stale on Postgres (#1768).+ * `extractStaleFromDB` stamps THIS instead, so `links_extracted_at` equals the+ * DB `updated_at` exactly and the staleness predicate clears.+ */+ updated_at_iso: string;}export interface ChunkInput {diff --git a/src/core/utils.ts b/src/core/utils.tsindex 98daff8449..dd348438b6 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -139,6 +139,13 @@ export function rowToStalePage(row: Record<string, unknown>): StalePageRow {timeline: (row.timeline as string | null) ?? '',frontmatter: (fm == null ? {} : (typeof fm === 'string' ? JSON.parse(fm) : fm)) as Record<string, unknown>,updated_at: new Date(row.updated_at as string),+ // #1768: full-µs UTC string projected by the SELECT (`updated_at_iso`).+ // Fallback derives an ISO string from the Date — NEVER String(Date), which+ // yields "Mon Jun 02 2026 …" that `::timestamptz` misparses. Pre-#1768+ // callers that don't project the column still get a valid (ms) ISO value.+ updated_at_iso: row.updated_at_iso != null+ ? String(row.updated_at_iso)+ : new Date(row.updated_at as string).toISOString(),};}diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.tsindex a1209bdbc2..a725e309b4 100644--- a/test/extract-stale.test.ts+++ b/test/extract-stale.test.ts@@ -178,6 +178,37 @@ describe('gbrain extract --stale', () => {expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);});+ test('CRITICAL (#1768): microsecond updated_at clears after --stale (no permanent lag)', async () => {+ // Repro of #1768: extractStaleFromDB used to stamp page.updated_at.toISOString()+ // (a JS Date, millisecond-truncated). The DB updated_at keeps microseconds, so+ // `updated_at > links_extracted_at` stayed true forever and links_extraction_lag+ // was stuck at 100% on Postgres. We inject a microsecond updated_at explicitly so+ // the precision gap is deterministic regardless of the engine's now() granularity.+ await engine.putPage('people/alice', personPage('Alice'));+ await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) advises [Acme](companies/acme).'));+ // Microsecond-precision updated_at, recent (after LINK_EXTRACTOR_VERSION_TS) so the+ // version arm doesn't fire — the edited arm is what must clear.+ await engine.executeRaw(`UPDATE pages SET updated_at = '2026-06-02 08:18:58.999166+00'`);+ expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(2);++ await runExtract(engine, ['--stale']);+ // Fixed: links_extracted_at stamped at the EXACT microsecond updated_at, so the+ // edited arm clears. Pre-fix this stayed at 2 (the bug).+ expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);++ // And it stays cleared on a re-run (the "no matter how many times I re-run" symptom).+ await runExtract(engine, ['--stale']);+ expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);++ // The stamp itself carries microsecond precision (not millisecond-truncated).+ const stamp = await stampOf('companies/acme');+ expect(stamp).not.toBeNull();+ const usRows = await engine.executeRaw<{ eq: boolean }>(+ `SELECT links_extracted_at >= updated_at AS eq FROM pages WHERE slug = 'companies/acme'`,+ );+ expect(usRows[0]?.eq).toBe(true);+ });+test('CDX-4 (D2): a link-flush throw aborts the sweep and leaves pages UNSTAMPED', async () => {await engine.putPage('people/alice', personPage('Alice'));await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) founded [Acme](companies/acme).'));diff --git a/test/fixtures/watchdog-harness.ts b/test/fixtures/watchdog-harness.tsnew file mode 100644index 0000000000..a0ca5bb32f--- /dev/null+++ b/test/fixtures/watchdog-harness.ts@@ -0,0 +1,33 @@+/**+ * Fixture for test/process-watchdog.serial.test.ts. Spawned via `bun`.+ *+ * Usage: bun watchdog-harness.ts <mode> <deadlineMs> <graceMs>+ * starve-with — install the watchdog, then starve the event loop forever.+ * The watchdog must SIGKILL this process by deadline+grace.+ * starve-without — no watchdog, just starve. Proves the busy loop truly hangs+ * (the test kills it). Isolates the watchdog as cause of death.+ * clean-dispose — install with a long deadline, dispose immediately, exit 0.+ * The watchdog must NOT kill a cleanly-disposed process.+ *+ * Safety net: the busy loop self-exits after 8s so a failed test kill can't hang CI.+ */+import { installProcessWatchdog } from '../../src/core/process-watchdog.ts';++const mode = process.argv[2] ?? 'starve-with';+const deadlineMs = Number(process.argv[3] ?? 300);+const graceMs = Number(process.argv[4] ?? 150);++if (mode === 'starve-with' || mode === 'clean-dispose') {+ const handle = installProcessWatchdog({ deadlineMs, graceMs, label: 'test-wd' });+ if (mode === 'clean-dispose') {+ handle.dispose();+ process.stdout.write('DISPOSED\n');+ process.exit(0);+ }+}++// Starve the main event loop with a synchronous busy loop (simulates ReDoS).+const start = Date.now();+while (Date.now() - start < 8000) { /* spin — no await, no yield */ }+process.stdout.write('SURVIVED\n'); // must NOT print under starve-with+process.exit(0);diff --git a/test/process-watchdog.serial.test.ts b/test/process-watchdog.serial.test.tsnew file mode 100644index 0000000000..2c6e8849b9--- /dev/null+++ b/test/process-watchdog.serial.test.ts@@ -0,0 +1,67 @@+/**+ * Bun-pinned integration for the out-of-band watchdog (#1633, plan A4).+ *+ * Bun's worker_threads Worker is flagged "experimental", and the whole #1633+ * fix rests on a worker timer firing + SIGKILLing the process while the MAIN+ * thread is starved by a synchronous loop. These tests spawn a real harness+ * process that starves its own loop and assert the watchdog kills it anyway.+ *+ * Serial because they use real subprocesses + wall-clock timing.+ */+import { describe, test, expect } from 'bun:test';+import { join } from 'node:path';++const HARNESS = join(import.meta.dir, 'fixtures', 'watchdog-harness.ts');++async function runHarness(+ mode: string,+ deadlineMs: number,+ graceMs: number,+ hardCapMs: number,+): Promise<{ exitCode: number | null; signalled: boolean; elapsedMs: number; stdout: string; killedByTest: boolean }> {+ const proc = Bun.spawn(['bun', HARNESS, mode, String(deadlineMs), String(graceMs)], {+ stdout: 'pipe',+ stderr: 'pipe',+ });+ const start = Date.now();+ let killedByTest = false;+ const cap = setTimeout(() => { killedByTest = true; proc.kill('SIGKILL'); }, hardCapMs);+ await proc.exited;+ clearTimeout(cap);+ const elapsedMs = Date.now() - start;+ const stdout = await new Response(proc.stdout).text();+ // Bun surfaces signal death via exitCode === null + signalCode, or a negative+ // exitCode on some platforms. Treat "not a clean 0" as signalled for our purpose.+ const signalled = proc.exitCode !== 0;+ return { exitCode: proc.exitCode, signalled, elapsedMs, stdout, killedByTest };+}++describe('process-watchdog integration (Bun-pinned)', () => {+ test('starved process IS killed by the watchdog around deadline+grace', async () => {+ // deadline 300 + grace 200 = ~500ms expected death. Hard cap 4s: if the+ // watchdog failed, the test's own SIGKILL fires and the assertion catches it.+ const r = await runHarness('starve-with', 300, 200, 4000);+ expect(r.stdout).not.toContain('SURVIVED'); // the bug symptom+ expect(r.killedByTest).toBe(false); // watchdog, not the test, killed it+ expect(r.signalled).toBe(true);+ // Died well before the harness's 8s self-exit safety net, near deadline+grace.+ expect(r.elapsedMs).toBeLessThan(3000);+ }, 15000);++ test('control: a starved process WITHOUT the watchdog does not self-exit', async () => {+ // Proves the busy loop genuinely starves (so the death above is the watchdog).+ // No watchdog installed; the test's hard cap (1.2s) is what kills it.+ const r = await runHarness('starve-without', 300, 200, 1200);+ expect(r.killedByTest).toBe(true); // only the test's SIGKILL stopped it+ expect(r.stdout).not.toContain('SURVIVED');+ }, 15000);++ test('clean dispose: a disposed watchdog never kills the process', async () => {+ // Long deadline, disposed immediately, process exits 0 fast and prints DISPOSED.+ const r = await runHarness('clean-dispose', 60000, 60000, 5000);+ expect(r.exitCode).toBe(0);+ expect(r.killedByTest).toBe(false);+ expect(r.stdout).toContain('DISPOSED');+ expect(r.elapsedMs).toBeLessThan(4000);+ }, 15000);+});diff --git a/test/process-watchdog.test.ts b/test/process-watchdog.test.tsnew file mode 100644index 0000000000..380ae6d338--- /dev/null+++ b/test/process-watchdog.test.ts@@ -0,0 +1,61 @@+/**+ * Pure-function coverage for the watchdog state machine (#1633). No threads, no+ * real timers — the spawn-based integration lives in+ * test/process-watchdog.serial.test.ts (Bun-pinned, real processes).+ */+import { describe, test, expect } from 'bun:test';+import { watchdogDecision, installProcessWatchdog } from '../src/core/process-watchdog.ts';++describe('watchdogDecision', () => {+ const deadline = 1000;+ const grace = 300;++ test('waits before the deadline', () => {+ expect(watchdogDecision(0, deadline, grace)).toBe('wait');+ expect(watchdogDecision(999, deadline, grace)).toBe('wait');+ });++ test('SIGTERM at the deadline boundary (inclusive)', () => {+ expect(watchdogDecision(1000, deadline, grace)).toBe('sigterm');+ expect(watchdogDecision(1299, deadline, grace)).toBe('sigterm');+ });++ test('SIGKILL at deadline+grace boundary (inclusive)', () => {+ expect(watchdogDecision(1300, deadline, grace)).toBe('sigkill');+ expect(watchdogDecision(5000, deadline, grace)).toBe('sigkill');+ });++ test('zero grace goes straight to SIGKILL at the deadline', () => {+ expect(watchdogDecision(999, deadline, 0)).toBe('wait');+ expect(watchdogDecision(1000, deadline, 0)).toBe('sigkill');+ });+});++describe('installProcessWatchdog (handle contract)', () => {+ test('non-positive deadline returns an inert no-op handle', () => {+ const warns: string[] = [];+ const h0 = installProcessWatchdog({ deadlineMs: 0, onWarn: (m) => warns.push(m) });+ expect(h0.active).toBe(false);+ h0.dispose(); // idempotent, no throw+ const hNeg = installProcessWatchdog({ deadlineMs: -5, onWarn: (m) => warns.push(m) });+ expect(hNeg.active).toBe(false);+ });++ test('active handle disposes idempotently without killing the test process', () => {+ // Long deadline so it never fires during the test; dispose tears it down.+ const h = installProcessWatchdog({ deadlineMs: 60_000, graceMs: 60_000, label: 'unit-wd' });+ expect(h.active).toBe(true);+ h.dispose();+ expect(h.active).toBe(false);+ h.dispose(); // second dispose is a no-op+ expect(h.active).toBe(false);+ });++ test('label is sanitized to a safe charset', () => {+ // A nasty label must not throw at construction (it is stripped before the+ // inline worker string). We dispose immediately so nothing fires.+ const h = installProcessWatchdog({ deadlineMs: 60_000, label: "evil'; \n process.exit(1) //" });+ expect(h.active).toBe(true);+ h.dispose();+ });+});diff --git a/test/sync-hard-deadline.test.ts b/test/sync-hard-deadline.test.tsnew file mode 100644index 0000000000..c90e92ccca--- /dev/null+++ b/test/sync-hard-deadline.test.ts@@ -0,0 +1,90 @@+/**+ * #1633 wiring: resolveSyncHardDeadline precedence + composeAbortSignals.+ * Pure (no engine, no env mutation — env is injected per-call).+ */+import { describe, test, expect } from 'bun:test';+import {+ resolveSyncHardDeadline,+ composeAbortSignals,+ HARD_DEADLINE_GRACE_SEC,+} from '../src/commands/sync.ts';++const GRACE_MS = HARD_DEADLINE_GRACE_SEC * 1000;++describe('resolveSyncHardDeadline', () => {+ test('--no-hard-deadline disables everything (even with --timeout)', () => {+ const r = resolveSyncHardDeadline(['--source', 'x', '--timeout', '60', '--no-hard-deadline'], { isTty: false });+ expect(r).toBeNull();+ });++ test('--hard-deadline wins and sets the deadline (with grace)', () => {+ const r = resolveSyncHardDeadline(['--hard-deadline', '120'], { isTty: true });+ expect(r).toEqual({ deadlineMs: 120_000, graceMs: GRACE_MS, reason: 'flag:--hard-deadline' });+ });++ test('--hard-deadline accepts s/m/h suffix', () => {+ expect(resolveSyncHardDeadline(['--hard-deadline', '2m'], { isTty: true })?.deadlineMs).toBe(120_000);+ });++ test('--hard-deadline with a bad value throws (same posture as --timeout)', () => {+ expect(() => resolveSyncHardDeadline(['--hard-deadline', 'nope'], { isTty: true })).toThrow();+ expect(() => resolveSyncHardDeadline(['--hard-deadline', '0'], { isTty: true })).toThrow();+ });++ test('--timeout (single-source) auto-arms the hard backstop', () => {+ const r = resolveSyncHardDeadline(['--source', 'briefings', '--timeout', '480'], { isTty: false });+ expect(r).toEqual({ deadlineMs: 480_000, graceMs: GRACE_MS, reason: 'flag:--timeout' });+ });++ test('--timeout + --all does NOT auto-arm (per-source budgets); falls through', () => {+ // Non-TTY → falls to the default; TTY → null.+ const nonTty = resolveSyncHardDeadline(['--all', '--timeout', '60'], { isTty: false });+ expect(nonTty?.reason).toBe('default:non-tty');+ const tty = resolveSyncHardDeadline(['--all', '--timeout', '60'], { isTty: true });+ expect(tty).toBeNull();+ });++ test('env GBRAIN_SYNC_MAX_RUNTIME_SECONDS sets the deadline', () => {+ const r = resolveSyncHardDeadline([], { isTty: true, env: { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '900' } });+ expect(r).toEqual({ deadlineMs: 900_000, graceMs: GRACE_MS, reason: 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS' });+ });++ test('env 0 disables (overrides the non-TTY default)', () => {+ const r = resolveSyncHardDeadline([], { isTty: false, env: { GBRAIN_SYNC_MAX_RUNTIME_SECONDS: '0' } });+ expect(r).toBeNull();+ });++ test('non-TTY default is 3600s', () => {+ const r = resolveSyncHardDeadline([], { isTty: false });+ expect(r).toEqual({ deadlineMs: 3_600_000, graceMs: GRACE_MS, reason: 'default:non-tty' });+ });++ test('TTY interactive with no flag/env arms nothing', () => {+ expect(resolveSyncHardDeadline([], { isTty: true })).toBeNull();+ });++ test('defaultNonTtySec override is honored', () => {+ const r = resolveSyncHardDeadline([], { isTty: false, defaultNonTtySec: 60 });+ expect(r?.deadlineMs).toBe(60_000);+ });+});++describe('composeAbortSignals', () => {+ test('all-undefined returns undefined', () => {+ expect(composeAbortSignals(undefined, undefined)).toBeUndefined();+ });++ test('single signal is returned directly (no wrapper)', () => {+ const c = new AbortController();+ expect(composeAbortSignals(c.signal, undefined)).toBe(c.signal);+ });++ test('composite aborts when ANY input aborts', () => {+ const a = new AbortController();+ const b = new AbortController();+ const sig = composeAbortSignals(a.signal, b.signal)!;+ expect(sig.aborted).toBe(false);+ b.abort(new Error('boom'));+ expect(sig.aborted).toBe(true);+ });+});