Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(key-files): miner per-job fetch; drain scheduler tick promise
time-attackc70da8d27795
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex dab22b8667..3d2cda8c39 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -86,7 +86,7 @@ rejection of serve-only flags before a brain opens.- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).-- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.+- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), the timer callback returns the tick's promise (a test awaits it), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes keep the 0.95 drop; capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex 058df2b972..48a74ed8f1 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -80,7 +80,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/select-e2e.ts` + `scripts/ci-changed-files.sh` + `scripts/ci-doc-checks.sh` — E2E selection. `select-e2e.ts` classifies the changed files (git: committed `origin/master...HEAD`, working tree and untracked-unignored files; or `--changed-files <path|->`) as EMPTY / DOC_ONLY / SRC: DOC_ONLY (root `*.md`, `docs/`, LICENSE, VERSION) selects nothing, everything else selects every `test/e2e/*.test.ts` and prints "E2E narrowing is retired" (a diff map selected all files on 40 of 40 merged PRs). `ci-changed-files.sh` lists a PR's or merge-group entry's files from the GitHub API for `prepare-e2e` and exits 1 on a capped (3000 PR / 300 compare), short or failed list or with no PR context, so the workflow falls back to the whole corpus. `ci-doc-checks.sh` is the doc-only gate `ci:local:diff` and `ci:ubicloud:diff` run (llms freshness, `check:doc-history`, `test/docs-repo-paths.test.ts`, skill refs, privacy guards). Tests: `test/select-e2e.test.ts`, `test/scripts/e2e-wiring.test.ts`, `test/scripts/ci-local-rendering.test.ts`.-- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. On a failed run under Actions it appends the last 50 failures to the step summary: file, test, backend arm, the first error block and a reproduction command (or the last log lines when no `(fail)` line was printed). Unit and E2E artifact retention is 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight entry naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; otherwise the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.+- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. A GitHub refresh reads one job at a time (a whole-run `gh run view --log` is refused above gh's job cap): unit from each shard's `timings-unit-N` capture artifact, which must record one capture start and a final `complete exit=0`; serial from `gh run view --job <id> --log`. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. On a failed run under Actions it appends the last 50 failures to the step summary: file, test, backend arm, the first error block and a reproduction command (or the last log lines when no `(fail)` line was printed). Unit and E2E artifact retention is 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight entry naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; otherwise the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).