mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 18:02:30 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08f2397615 |
@@ -79,7 +79,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
|
||||
- `docs/architecture/RETRIEVAL.md` + `docs/architecture/RETRIEVAL_MAXPOOL_INCIDENT.md` — retrieval-pipeline architecture reference + the named-thing-miss incident write-up (root cause, the five-layer fix, the eval that pins it).
|
||||
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval cathedral. `SearchResult` gains `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` adds the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` extends the rollup with the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
|
||||
- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).
|
||||
- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider frontier models score the OUTPUT against the TASK on a 5-dim list. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses `src/core/ai/gateway.ts:chat()` so config/auth/aliasing comes from the gateway recipe registry — no parallel provider stack. Self-configures the gateway via `buildGatewayConfig(loadConfig() ?? {})` since the cli.ts dispatch bypasses `connectEngine()`, so file-plane keys, env base URLs, and provider_chat_options follow the same adapter path as runtime. Default cycles 3 in TTY, 1 in non-TTY (partial cost guardrail) via the shared `resolveCycleDefault(explicit, isTty)` in `src/core/eval/cycle-default.ts`; the cost-estimate banner appends `cycleDefaultSuffix(...)` (`for 1 cycle(s) (non-interactive default; --cycles N for more)`) when the value is the silent non-TTY fallback, so the 1-vs-3 difference isn't hidden. Receipts land at `gbrainPath('eval-receipts')/<slug>-<sha8-of-output>.json`. `--batch <jsonl> [--limit N] [--concurrent N] [--max-usd FLOAT] [--yes]` fans out cross-modal scoring across a LongMemEval-shape JSONL; mutually exclusive with `--task` (fail-fast usage error if both set); filters `kind: "by_type_summary"` rows; pre-flight cost estimate refuses if `> --max-usd` without `--yes` (default cap 5.00 USD). Semaphore-bounded fan-out via inline `runWithLimit<T>(items, limit, fn)` (exported for unit tests): max N questions in-flight × 3 model slots = ceiling of 3N parallel API calls (default `--concurrent 3` → 9). Per-question receipts land in a per-batch tempdir and are deleted at end of run; the summary receipt inlines per-question verdicts as JSON, not file paths. Exit precedence (batch-level policy, NOT inherited from aggregate.ts): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `runEvalCrossModal(args, opts?: {runEval?: typeof runEval})` mirrors `runEvalLongMemEval(args, {client?})`; tests pass `opts.runEval` to bypass real LLM calls AND the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.
|
||||
- `src/commands/eval-cross-modal.ts` — multi-model quality gate. Three different-provider frontier models score the OUTPUT against the TASK on a 5-dim list. Verdict `pass` (exit 0) / `fail` (exit 1) / `inconclusive` (exit 2; <2/3 model successes). Reuses `src/core/ai/gateway.ts:chat()` so config/auth/aliasing comes from the gateway recipe registry — no parallel provider stack. Self-configures the gateway (`configureGateway(loadConfig() + process.env)`) since the cli.ts dispatch bypasses `connectEngine()`. Default cycles 3 in TTY, 1 in non-TTY (partial cost guardrail) via the shared `resolveCycleDefault(explicit, isTty)` in `src/core/eval/cycle-default.ts`; the cost-estimate banner appends `cycleDefaultSuffix(...)` (`for 1 cycle(s) (non-interactive default; --cycles N for more)`) when the value is the silent non-TTY fallback, so the 1-vs-3 difference isn't hidden. Receipts land at `gbrainPath('eval-receipts')/<slug>-<sha8-of-output>.json`. `--batch <jsonl> [--limit N] [--concurrent N] [--max-usd FLOAT] [--yes]` fans out cross-modal scoring across a LongMemEval-shape JSONL; mutually exclusive with `--task` (fail-fast usage error if both set); filters `kind: "by_type_summary"` rows; pre-flight cost estimate refuses if `> --max-usd` without `--yes` (default cap 5.00 USD). Semaphore-bounded fan-out via inline `runWithLimit<T>(items, limit, fn)` (exported for unit tests): max N questions in-flight × 3 model slots = ceiling of 3N parallel API calls (default `--concurrent 3` → 9). Per-question receipts land in a per-batch tempdir and are deleted at end of run; the summary receipt inlines per-question verdicts as JSON, not file paths. Exit precedence (batch-level policy, NOT inherited from aggregate.ts): ERROR > FAIL > INCONCLUSIVE > PASS. DI seam: `runEvalCrossModal(args, opts?: {runEval?: typeof runEval})` mirrors `runEvalLongMemEval(args, {client?})`; tests pass `opts.runEval` to bypass real LLM calls AND the gateway availability check. Pinned by `test/eval-cross-modal-batch.test.ts`.
|
||||
- `src/core/eval/cycle-default.ts` — single source of truth for the eval cycle-count default. Exports `DEFAULT_CYCLES_TTY = 3`, `DEFAULT_CYCLES_NONTTY = 1`, `resolveCycleDefault(explicit, isTty): {cycles, usedNonTtyDefault}`, and `cycleDefaultSuffix(r)` (returns ` (non-interactive default; --cycles N for more)` only when the non-TTY default was applied, else `''`). Consumed by `eval-cross-modal.ts`, `eval-takes-quality.ts` (run + regress), and `takes-quality-eval/runner.ts` (core uses only the constant — library stays TTY-agnostic; the CLI owns the TTY=3 upgrade + banner annotation). `eval-suspected-contradictions.ts` applies the same transparency to its `$5`/`$1` budget default via a `budgetUsdExplicit` flag (the budget is overwritten in-place so explicitness can't be inferred post-hoc). Not shared with `resolveWorkersWithClamp` (different domain, no engine, no dedup). Pinned by `test/eval/cycle-default.test.ts`, `test/eval-suspected-contradictions-budget-default.test.ts`.
|
||||
- `src/core/cross-modal-eval/json-repair.ts` — `parseModelJSON(raw)` named export with a 4-strategy fallback chain (direct parse → fence-strip → trailing-comma + single-quote + embedded-newline repair → regex nuclear option). Adversarial input throws rather than fabricating scores — the aggregator treats a throw as "this model contributed nothing this cycle" so the gate stays correct at >=2/3 successes.
|
||||
- `src/core/cross-modal-eval/aggregate.ts` — pure verdict logic. Pass criterion: `(successes >= 2) AND (every dim mean >= 7) AND (every dim min across models >= 5)`. Inconclusive when <2/3 models returned parseable scores (regression guard for the v1 `Object.values({}).every(...) === true` empty-array PASS bug).
|
||||
@@ -138,7 +138,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
|
||||
- `src/core/minions/queue.ts` extension — `MinionQueue.add()` rejects `subagent` jobs whose `data.model` resolves via `isAnthropicProvider()` to a non-Anthropic provider. Lazy-imports `model-config.ts` to avoid pulling engine types into queue's eager-load surface. Layer 1 of the three-layer subagent provider enforcement (layers 2+3: `model-config.ts:enforceSubagentAnthropic` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`.
|
||||
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (11 `PER_TASK_KEYS`: `models.dream.synthesize`, `models.dream.patterns`, `models.drift`, `models.auto_think`, `models.think`, `models.subagent`, `facts.extraction_model`, `models.eval.longmemeval`, `models.expansion`, `models.chat`, `models.dream.synthesize_verdict`), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
|
||||
- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + file-plane `openai/anthropic/zeroentropy_api_key` from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
|
||||
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Single owner of translating stored config into gateway config — consumed by CLI runtime, init (`gbrain init`'s three configureGateway sites), `init-embed-check.ts`, the eval commands (cross-modal, takes-quality), provider diagnostics, and the in-process migration path. Folds file-plane API keys (openai/anthropic/zeroentropy/openrouter) into the gateway env and threads local-server `*_BASE_URL` env vars into base_urls; caller-provided `provider_base_urls` config wins over env base URLs. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
|
||||
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Single owner of folding file-plane API keys (openai/anthropic/zeroentropy) into the gateway env and threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
|
||||
- `src/commands/doctor.ts` extension — `subagent_provider` check (layer 3 of 3). Warns when `models.tier.subagent` is explicitly set non-Anthropic (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`.
|
||||
- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries, `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts` (regex-based, not full YAML). Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.
|
||||
- `src/core/skill-catalog.ts` — host-repo skill catalog backing the MCP `list_skills` / `get_skill` ops. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `crossReferenceTools(declared, ctx)` splits a skill's declared `tools:` into `usable_tools` vs `unavailable_tools`; `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. Skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). Two ops register in `src/core/operations.ts` (`list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` + `cliHints:{name:'skill', positional:['name']}`) and dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
|
||||
|
||||
@@ -21,8 +21,7 @@ import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
import { gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';
|
||||
import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
|
||||
import { gbrainPath, loadConfig } from '../core/config.ts';
|
||||
import { configureGateway, isAvailable } from '../core/ai/gateway.ts';
|
||||
import { runWithLimit } from '../core/worker-pool.ts';
|
||||
import { resolveCycleDefault, cycleDefaultSuffix } from '../core/eval/cycle-default.ts';
|
||||
@@ -265,11 +264,32 @@ function isTTY(): boolean {
|
||||
* Returns true on success; false (and prints a hint) when no config is found.
|
||||
*/
|
||||
function configureGatewayForCli(): boolean {
|
||||
// Route through buildGatewayConfig (the single adapter seam) so file-plane
|
||||
// API keys, env base URLs, and provider_chat_options follow the same
|
||||
// precedence as the runtime path. No config file is fine — env alone serves.
|
||||
const config = loadConfig();
|
||||
configureGateway(buildGatewayConfig(config ?? ({} as GBrainConfig)));
|
||||
if (!config) {
|
||||
// No config file is fine for the eval command — env vars alone may serve.
|
||||
// We still call configureGateway so gateway recipes can read the env map.
|
||||
configureGateway({
|
||||
embedding_model: undefined,
|
||||
embedding_dimensions: undefined,
|
||||
expansion_model: undefined,
|
||||
chat_model: undefined,
|
||||
chat_fallback_chain: undefined,
|
||||
base_urls: undefined,
|
||||
provider_chat_options: undefined,
|
||||
env: { ...process.env },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
configureGateway({
|
||||
embedding_model: config.embedding_model,
|
||||
embedding_dimensions: config.embedding_dimensions,
|
||||
expansion_model: config.expansion_model,
|
||||
chat_model: config.chat_model,
|
||||
chat_fallback_chain: config.chat_fallback_chain,
|
||||
base_urls: config.provider_base_urls,
|
||||
provider_chat_options: config.provider_chat_options,
|
||||
env: { ...process.env },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,8 +21,7 @@
|
||||
*/
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { configureGateway } from '../core/ai/gateway.ts';
|
||||
import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
|
||||
import { loadConfig, type GBrainConfig } from '../core/config.ts';
|
||||
import { loadConfig } from '../core/config.ts';
|
||||
import { runEval, DEFAULT_MODEL_PANEL } from '../core/takes-quality-eval/runner.ts';
|
||||
import { resolveCycleDefault, cycleDefaultSuffix } from '../core/eval/cycle-default.ts';
|
||||
import { writeReceipt } from '../core/takes-quality-eval/receipt-write.ts';
|
||||
@@ -128,12 +127,8 @@ export async function runReplayNoBrain(argv: string[]): Promise<number> {
|
||||
export async function runEvalTakesQuality(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
// Self-configure the AI gateway (mirrors eval-cross-modal pattern). The
|
||||
// gateway needs config.ai_gateway + env vars; configureGateway reads both.
|
||||
// Route through buildGatewayConfig: the old `{ ...cfg, ...process.env }`
|
||||
// spread never populated the gateway's `env` field (the gateway NEVER reads
|
||||
// process.env at call time), so availability checks saw no keys at all and
|
||||
// file-plane API keys / provider base URLs were dropped.
|
||||
const cfg = loadConfig();
|
||||
configureGateway(buildGatewayConfig(cfg ?? ({} as GBrainConfig)));
|
||||
configureGateway({ ...cfg, ...(process.env as Record<string, string>) } as any);
|
||||
|
||||
const { subcmd, argv, json } = parseSubcmd(args);
|
||||
|
||||
|
||||
@@ -1651,7 +1651,7 @@ async function extractTimelineFromDB(
|
||||
* make re-extraction idempotent). EVERY processed page is stamped, including
|
||||
* zero-link pages — they WERE processed.
|
||||
*/
|
||||
async function extractStaleFromDB(
|
||||
export async function extractStaleFromDB(
|
||||
engine: BrainEngine,
|
||||
opts: {
|
||||
dryRun: boolean;
|
||||
|
||||
+14
-12
@@ -7,7 +7,6 @@ import { homedir } from 'os';
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
import { saveConfig, loadConfig, loadConfigFileOnly, toEngineConfig, gbrainPath, configPath, isThinClient, effectiveEnvDatabaseUrl, type GBrainConfig } from '../core/config.ts';
|
||||
import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
|
||||
import { createEngine } from '../core/engine-factory.ts';
|
||||
import { discoverOAuth, mintClientCredentialsToken, smokeTestMcp } from '../core/remote-mcp-probe.ts';
|
||||
import { runInitEmbedCheck } from '../core/init-embed-check.ts';
|
||||
@@ -723,8 +722,7 @@ async function configureGatewayWithMergedPrecedence(
|
||||
// pollutes config.json.
|
||||
const envOverlay = loadConfig() ?? ({} as GBrainConfig);
|
||||
|
||||
const merged: GBrainConfig = {
|
||||
...envOverlay,
|
||||
const merged = {
|
||||
embedding_model: aiOpts?.embedding_model ?? envOverlay.embedding_model ?? existingFile.embedding_model,
|
||||
embedding_dimensions: aiOpts?.embedding_dimensions ?? envOverlay.embedding_dimensions ?? existingFile.embedding_dimensions,
|
||||
expansion_model: aiOpts?.expansion_model ?? envOverlay.expansion_model ?? existingFile.expansion_model,
|
||||
@@ -732,9 +730,13 @@ async function configureGatewayWithMergedPrecedence(
|
||||
};
|
||||
|
||||
const { configureGateway, getEmbeddingModel, getEmbeddingDimensions, getExpansionModel, getChatModel } = await import('../core/ai/gateway.ts');
|
||||
// buildGatewayConfig (the single adapter seam) so file-plane API keys and
|
||||
// env base URLs reach the gateway — a hand-rolled config here dropped them.
|
||||
configureGateway(buildGatewayConfig(merged));
|
||||
configureGateway({
|
||||
embedding_model: merged.embedding_model,
|
||||
embedding_dimensions: merged.embedding_dimensions,
|
||||
expansion_model: merged.expansion_model,
|
||||
chat_model: merged.chat_model,
|
||||
env: { ...process.env },
|
||||
});
|
||||
|
||||
// Read back resolved values — gateway applies internal defaults for unset
|
||||
// fields, so these are the values that actually shaped the schema.
|
||||
@@ -829,13 +831,13 @@ async function initPGLite(opts: {
|
||||
// resolveAIOptions above: CLI flags > env vars > existing file > gateway
|
||||
// defaults.
|
||||
const { configureGateway } = await import('../core/ai/gateway.ts');
|
||||
configureGateway(buildGatewayConfig({
|
||||
...(loadConfig() ?? ({} as GBrainConfig)),
|
||||
configureGateway({
|
||||
embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
|
||||
embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
|
||||
expansion_model: opts.aiOpts?.expansion_model,
|
||||
chat_model: opts.aiOpts?.chat_model,
|
||||
} as GBrainConfig));
|
||||
env: { ...process.env },
|
||||
});
|
||||
if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
|
||||
if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
|
||||
if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
|
||||
@@ -1044,13 +1046,13 @@ async function initPostgres(opts: {
|
||||
|
||||
// T6: unconditional configureGateway BEFORE initSchema.
|
||||
const { configureGateway } = await import('../core/ai/gateway.ts');
|
||||
configureGateway(buildGatewayConfig({
|
||||
...(loadConfig() ?? ({} as GBrainConfig)),
|
||||
configureGateway({
|
||||
embedding_model: resolvedModel ?? opts.aiOpts?.embedding_model,
|
||||
embedding_dimensions: resolvedDim ?? opts.aiOpts?.embedding_dimensions,
|
||||
expansion_model: opts.aiOpts?.expansion_model,
|
||||
chat_model: opts.aiOpts?.chat_model,
|
||||
} as GBrainConfig));
|
||||
env: { ...process.env },
|
||||
});
|
||||
if (resolvedModel) console.log(` Embedding: ${resolvedModel} (${resolvedDim}d)`);
|
||||
if (opts.aiOpts?.expansion_model) console.log(` Expansion: ${opts.aiOpts.expansion_model}`);
|
||||
if (opts.aiOpts?.chat_model) console.log(` Chat: ${opts.aiOpts.chat_model}`);
|
||||
|
||||
+39
-1
@@ -1479,7 +1479,31 @@ export async function registerBuiltinHandlers(
|
||||
embedSkipReason = 'auto_embed_disabled';
|
||||
}
|
||||
|
||||
return { ...result, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason };
|
||||
// #2849: large-sync extract deferral follow-up. performSync skips inline
|
||||
// link/timeline extraction when totalChanges > 100, leaving
|
||||
// links_extracted_at unstamped. A standalone sync job (webhook push,
|
||||
// sync trigger) has no autopilot extract phase behind it, so the pages
|
||||
// would stay extraction-stale until a manual `gbrain extract --stale`.
|
||||
// Queue a source-scoped stale sweep instead. Best-effort + idempotent:
|
||||
// a duplicate sweep finds 0 stale pages and no-ops.
|
||||
let extractJobId: number | null = null;
|
||||
if (result.extractDeferred) {
|
||||
try {
|
||||
const { MinionQueue } = await import('../core/minions/queue.ts');
|
||||
const queue = new MinionQueue(engine);
|
||||
const followUp = await queue.add(
|
||||
'extract',
|
||||
{ stale: true, ...(sourceId ? { sourceId } : {}) },
|
||||
{
|
||||
idempotency_key: `sync-extract-stale:${sourceId ?? 'default'}:${Math.floor(Date.now() / 30_000)}`,
|
||||
maxWaiting: 1,
|
||||
},
|
||||
);
|
||||
extractJobId = followUp.id;
|
||||
} catch { /* best-effort: extract --stale sweeps it later */ }
|
||||
}
|
||||
|
||||
return { ...result, embed_job_id: embedJobId, embed_skip_reason: embedSkipReason, extract_stale_job_id: extractJobId };
|
||||
});
|
||||
|
||||
registerBuiltinJob(worker, engine, 'embed', async (job) => {
|
||||
@@ -1652,6 +1676,20 @@ export async function registerBuiltinHandlers(
|
||||
});
|
||||
|
||||
worker.register('extract', async (job) => {
|
||||
// #2849: stale-sweep mode — the sync handler's large-sync deferral
|
||||
// follow-up. DB-source (reads page content from the DB, so it runs on
|
||||
// checkout-less brains), source-scopable, idempotent. Same core as
|
||||
// `gbrain extract --stale`.
|
||||
if (job.data.stale === true) {
|
||||
const { extractStaleFromDB } = await import('./extract.ts');
|
||||
return await extractStaleFromDB(engine, {
|
||||
dryRun: !!job.data.dryRun,
|
||||
jsonMode: false,
|
||||
includeFrontmatter: false,
|
||||
sourceIdFilter: typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined,
|
||||
catchUp: false,
|
||||
});
|
||||
}
|
||||
const { runExtractCore } = await import('./extract.ts');
|
||||
const mode = (typeof job.data.mode === 'string' && ['links', 'timeline', 'all'].includes(job.data.mode))
|
||||
? (job.data.mode as 'links' | 'timeline' | 'all')
|
||||
|
||||
@@ -66,11 +66,15 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise
|
||||
|
||||
// configureGateway BEFORE initSchema (init.ts B.3): a schema bump on a brain
|
||||
// whose file config is missing embedding fields must not fall through to
|
||||
// stale hardcoded fallbacks. Route through buildGatewayConfig so file-plane
|
||||
// API keys and provider base URLs follow the same precedence as runtime.
|
||||
// stale hardcoded fallbacks. loadConfig already merged env; propagate it.
|
||||
const { configureGateway } = await import('../../core/ai/gateway.ts');
|
||||
const { buildGatewayConfig } = await import('../../core/ai/build-gateway-config.ts');
|
||||
configureGateway(buildGatewayConfig(config));
|
||||
configureGateway({
|
||||
embedding_model: config.embedding_model,
|
||||
embedding_dimensions: config.embedding_dimensions,
|
||||
expansion_model: config.expansion_model,
|
||||
chat_model: config.chat_model,
|
||||
env: { ...process.env },
|
||||
});
|
||||
|
||||
const timeoutMs = opts?.timeoutMs ?? MIGRATE_ONLY_TIMEOUT_MS;
|
||||
const engine = await createEngine(toEngineConfig(config));
|
||||
|
||||
@@ -2146,8 +2146,13 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// Other event types (ping, pull_request, etc.) return 202 'ignored'
|
||||
// so GitHub doesn't retry.
|
||||
// D15.5: HMAC compare uses the shared safeHexEqual helper.
|
||||
// D18: submits 'sync' job with auto_embed_backfill=true and priority -10
|
||||
// (above autopilot's 0).
|
||||
// D18: submits 'sync' job with extraction + auto_embed_backfill enabled and
|
||||
// priority -10 (above autopilot's 0). noExtract:false opts normal
|
||||
// incremental pushes into sync's inline link/timeline extraction (#2849
|
||||
// — the standalone sync handler defaults noExtract to TRUE, which left
|
||||
// webhook-imported pages permanently stale). Large (>100 file) pushes
|
||||
// defer inline extract; the sync handler queues an extract --stale
|
||||
// follow-up job for that branch.
|
||||
// ---------------------------------------------------------------------------
|
||||
const githubWebhookLimiter = rateLimit({
|
||||
windowMs: 60_000,
|
||||
@@ -2267,6 +2272,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
'sync',
|
||||
{
|
||||
sourceId: source.id,
|
||||
noExtract: false,
|
||||
auto_embed_backfill: true,
|
||||
embed_reason: 'webhook',
|
||||
},
|
||||
|
||||
+19
-1
@@ -222,6 +222,14 @@ export interface SyncResult {
|
||||
* everything," the exact misdiagnosis in the #1794 recurrence report.
|
||||
*/
|
||||
bankedFiles?: number;
|
||||
/**
|
||||
* #2849: true when extraction was REQUESTED (noExtract false) but this sync
|
||||
* skipped inline link/timeline extraction because totalChanges > 100 (the
|
||||
* #1794 large-sync deferral). links_extracted_at stays unstamped for the
|
||||
* imported pages. The standalone `sync` job handler queues a source-scoped
|
||||
* `extract --stale` follow-up when set; CLI runs print the manual hint.
|
||||
*/
|
||||
extractDeferred?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1379,6 +1387,10 @@ See also:
|
||||
{
|
||||
sourceId: sourceIdArg,
|
||||
repoPath: source.local_path,
|
||||
// #2849: opt in to inline extraction — the standalone sync handler
|
||||
// defaults noExtract to TRUE (dedupe for doctor's [sync, extract]
|
||||
// remediation plan), which would leave triggered syncs extraction-stale.
|
||||
noExtract: false,
|
||||
auto_embed_backfill: true,
|
||||
embed_reason: 'sync_trigger',
|
||||
},
|
||||
@@ -3287,11 +3299,16 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
// the stale sweep scans the whole source, so banked-across-runs pages are
|
||||
// covered regardless.
|
||||
const extractOpts = opts.sourceId ? { sourceId: opts.sourceId } : undefined;
|
||||
let extractDeferred = false;
|
||||
if (!opts.noExtract && totalChanges > 100 && pagesAffected.length > 0) {
|
||||
// #2849: surface the deferral to callers. A standalone sync job (webhook
|
||||
// push, sync trigger) has no autopilot extract phase behind it, so the
|
||||
// job handler queues an `extract --stale` follow-up off this flag.
|
||||
extractDeferred = true;
|
||||
slog(
|
||||
` Large sync: deferring link/timeline extraction. ` +
|
||||
`Run 'gbrain extract --stale${opts.sourceId ? ` --source-id ${opts.sourceId}` : ''}' ` +
|
||||
`(or let the autopilot cycle's extract phase sweep it).`,
|
||||
`(sync jobs queue this follow-up automatically).`,
|
||||
);
|
||||
}
|
||||
if (!opts.noExtract && totalChanges <= 100 && pagesAffected.length > 0) {
|
||||
@@ -3400,6 +3417,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
chunksCreated,
|
||||
embedded,
|
||||
pagesAffected,
|
||||
extractDeferred,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ import { parseModelId } from './ai/model-resolver.ts';
|
||||
* `resolveKey` closure without re-parsing recipes.
|
||||
*
|
||||
* Only OPENAI_API_KEY and ZEROENTROPY_API_KEY appear here because those are the
|
||||
* only embedding keys `buildGatewayConfig` (src/core/ai/build-gateway-config.ts)
|
||||
* folds from config into the gateway env. VOYAGE_API_KEY / GOOGLE_GENERATIVE_AI_API_KEY are deliberately
|
||||
* only embedding keys `buildGatewayConfig` (src/cli.ts) folds from config into
|
||||
* the gateway env. VOYAGE_API_KEY / GOOGLE_GENERATIVE_AI_API_KEY are deliberately
|
||||
* absent: their config fields are NOT threaded to the gateway today, so the
|
||||
* producer closures fall through to checking `process.env` ONLY for them. That
|
||||
* matches what the gateway can actually use (the recipes read those keys from
|
||||
|
||||
@@ -25,7 +25,6 @@ import { withEnv } from '../helpers/with-env.ts';
|
||||
|
||||
const PASSTHROUGHS: Array<{ envVar: string; recipeId: string }> = [
|
||||
{ envVar: 'LLAMA_SERVER_BASE_URL', recipeId: 'llama-server' },
|
||||
{ envVar: 'LLAMA_SERVER_RERANKER_BASE_URL', recipeId: 'llama-server-reranker' },
|
||||
{ envVar: 'OLLAMA_BASE_URL', recipeId: 'ollama' },
|
||||
{ envVar: 'LMSTUDIO_BASE_URL', recipeId: 'lmstudio' },
|
||||
{ envVar: 'LITELLM_BASE_URL', recipeId: 'litellm' },
|
||||
|
||||
@@ -11,13 +11,32 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
|
||||
import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';
|
||||
import {
|
||||
configureGateway,
|
||||
getEmbeddingModel,
|
||||
getMultimodalModel,
|
||||
resetGateway,
|
||||
} from '../src/core/ai/gateway.ts';
|
||||
import type { AIGatewayConfig } from '../src/core/ai/types.ts';
|
||||
|
||||
// Mirror the cli.ts buildGatewayConfig helper exactly. Keeping a copy here
|
||||
// (instead of exporting from cli.ts) is intentional: the test asserts the
|
||||
// shape of the contract, not the helper's identity. If cli.ts drifts, the
|
||||
// e2e behavior these tests care about (DB-set value lands in gateway) still
|
||||
// holds, but a helper-shape test would also catch the drift in PR review.
|
||||
function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
|
||||
return {
|
||||
embedding_model: c.embedding_model,
|
||||
embedding_dimensions: c.embedding_dimensions,
|
||||
embedding_multimodal_model: c.embedding_multimodal_model,
|
||||
expansion_model: c.expansion_model,
|
||||
chat_model: c.chat_model,
|
||||
chat_fallback_chain: c.chat_fallback_chain,
|
||||
base_urls: c.provider_base_urls,
|
||||
provider_chat_options: c.provider_chat_options,
|
||||
env: { ...process.env },
|
||||
};
|
||||
}
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
@@ -28,7 +47,6 @@ beforeAll(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
resetGateway(); // don't leak this file's gateway config into shard siblings
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* eval-takes-quality gateway self-config — adapter-boundary regression
|
||||
* (takeover of PR #2430).
|
||||
*
|
||||
* The old callsite spread `{ ...cfg, ...process.env }` straight into
|
||||
* configureGateway. The gateway NEVER reads process.env at call time — it
|
||||
* reads `_config.env` — and that spread never populated an `env` field at
|
||||
* all, so every availability/diagnose check dereferenced `undefined.env[k]`
|
||||
* and file-plane API keys (config.json `openai_api_key` etc.) were dropped.
|
||||
* Routing through buildGatewayConfig fixes both. This test fails (throws)
|
||||
* on the old code path.
|
||||
*/
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { runEvalTakesQuality } from '../src/commands/eval-takes-quality.ts';
|
||||
import { isAvailable, resetGateway } from '../src/core/ai/gateway.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
import type { BrainEngine } from '../src/core/engine.ts';
|
||||
|
||||
afterAll(() => {
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
describe('runEvalTakesQuality — gateway self-config routes through buildGatewayConfig', () => {
|
||||
test('file-plane openai_api_key reaches the gateway env (help path, engine untouched)', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-etq-gw-'));
|
||||
try {
|
||||
mkdirSync(join(home, '.gbrain'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(home, '.gbrain', 'config.json'),
|
||||
JSON.stringify({
|
||||
engine: 'pglite',
|
||||
database_path: join(home, '.gbrain', 'brain'),
|
||||
openai_api_key: 'sk-file-plane-test',
|
||||
}),
|
||||
);
|
||||
await withEnv(
|
||||
{
|
||||
GBRAIN_HOME: home,
|
||||
OPENAI_API_KEY: undefined,
|
||||
DATABASE_URL: undefined,
|
||||
GBRAIN_DATABASE_URL: undefined,
|
||||
},
|
||||
async () => {
|
||||
// 'help' returns before touching the engine, but the gateway is
|
||||
// configured first — exactly the seam under test.
|
||||
await runEvalTakesQuality({} as BrainEngine, ['--help']);
|
||||
expect(isAvailable('embedding', 'openai:text-embedding-3-small')).toBe(true);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { safeHexEqual } from '../src/core/timing-safe.ts';
|
||||
|
||||
const GITHUB_SECRET = 'super-secret-webhook-key';
|
||||
@@ -123,3 +124,25 @@ describe('Branch ref construction (D5)', () => {
|
||||
expect(pushedRef === `refs/heads/${trackedBranch}`).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Webhook sync job extraction contract (#2849)', () => {
|
||||
test('opts into extraction before the pushed commit is consumed', () => {
|
||||
const serveSource = readFileSync(
|
||||
new URL('../src/commands/serve-http.ts', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const routeStart = serveSource.indexOf("'/webhooks/github'");
|
||||
const queueStart = serveSource.indexOf('const job = await queue.add(', routeStart);
|
||||
const responseStart = serveSource.indexOf('res.status(202)', queueStart);
|
||||
expect(routeStart).toBeGreaterThanOrEqual(0);
|
||||
expect(queueStart).toBeGreaterThan(routeStart);
|
||||
expect(responseStart).toBeGreaterThan(queueStart);
|
||||
|
||||
const routeSource = serveSource.slice(queueStart, responseStart);
|
||||
const payload = routeSource.match(
|
||||
/queue\.add\(\s*'sync',\s*\{([\s\S]*?)\}\s*,\s*\{/,
|
||||
);
|
||||
expect(payload).not.toBeNull();
|
||||
expect(payload?.[1]).toMatch(/\bnoExtract:\s*false\b/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* #2849 — large-sync extract deferral queues an `extract --stale` follow-up.
|
||||
*
|
||||
* performSync's incremental path skips inline link/timeline extraction when
|
||||
* totalChanges > 100 (the #1794 large-sync deferral), leaving
|
||||
* links_extracted_at unstamped. Pre-fix, a standalone sync job (webhook push,
|
||||
* `gbrain sync trigger`) had NOTHING behind it to sweep those pages — the
|
||||
* autopilot cycle's extract phase only walks that cycle's changedSlugs — so a
|
||||
* large webhook push left extraction permanently stale until a manual
|
||||
* `gbrain extract --stale`.
|
||||
*
|
||||
* Pins:
|
||||
* (a) performSync surfaces `extractDeferred: true` on the >100 branch and
|
||||
* leaves the pages unstamped/unlinked.
|
||||
* (b) the `sync` job handler queues an `extract` job with
|
||||
* { stale: true, sourceId? } when extractDeferred is set.
|
||||
* (c) the `extract` handler's stale mode actually sweeps: links created +
|
||||
* watermark stamped (end-to-end recovery, no manual step).
|
||||
*
|
||||
* Marked .serial.test.ts — spawns git subprocesses + shares one PGLite engine.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';
|
||||
import { execSync } from 'child_process';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { MinionWorker } from '../src/core/minions/worker.ts';
|
||||
import { MinionQueue } from '../src/core/minions/queue.ts';
|
||||
import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
let worker: MinionWorker;
|
||||
let repoPath: string;
|
||||
|
||||
function git(cmd: string): void { execSync(cmd, { cwd: repoPath, stdio: 'pipe' }); }
|
||||
|
||||
describe('#2849 — large sync defers extract and queues a stale sweep', () => {
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
worker = new MinionWorker(engine, { queue: 'test' });
|
||||
await registerBuiltinHandlers(worker, engine, { quiet: true });
|
||||
|
||||
repoPath = mkdtempSync(join(tmpdir(), 'gbrain-large-defer-'));
|
||||
git('git init');
|
||||
git('git config user.email "t@t.com"');
|
||||
git('git config user.name "T"');
|
||||
mkdirSync(join(repoPath, 'people'), { recursive: true });
|
||||
mkdirSync(join(repoPath, 'notes'), { recursive: true });
|
||||
writeFileSync(join(repoPath, 'people/alice.md'), [
|
||||
'---', 'type: person', 'title: Alice', '---', '', 'Alice is a founder.',
|
||||
].join('\n'));
|
||||
git('git add -A && git commit -m "initial"');
|
||||
|
||||
// Seed: full first sync imports the anchor page + sets last_commit.
|
||||
const { performSync } = await import('../src/commands/sync.ts');
|
||||
await performSync(engine, { repoPath, full: true, noPull: true, noEmbed: true });
|
||||
|
||||
// Second commit: 101 new pages → incremental totalChanges > 100.
|
||||
for (let i = 0; i < 101; i++) {
|
||||
writeFileSync(join(repoPath, `notes/n${i}.md`), [
|
||||
'---', 'type: note', `title: Note ${i}`, '---', '',
|
||||
`[Alice](people/alice) appears in note ${i}.`,
|
||||
].join('\n'));
|
||||
}
|
||||
git('git add -A && git commit -m "add 101 pages"');
|
||||
}, 120_000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (repoPath) rmSync(repoPath, { recursive: true, force: true });
|
||||
if (engine) await engine.disconnect();
|
||||
}, 60_000);
|
||||
|
||||
test('sync handler defers inline extract and queues extract{stale} follow-up; stale sweep recovers', async () => {
|
||||
const syncHandler = (worker as unknown as { handlers: Map<string, (job: unknown) => Promise<unknown>> })
|
||||
.handlers.get('sync');
|
||||
expect(syncHandler).toBeDefined();
|
||||
|
||||
// Same payload shape the webhook submits (minus embed backfill noise).
|
||||
const result = await syncHandler!({
|
||||
data: { repoPath, noExtract: false, noPull: true, auto_embed_backfill: false },
|
||||
signal: { aborted: false },
|
||||
updateProgress: async () => {},
|
||||
}) as { status: string; extractDeferred?: boolean; extract_stale_job_id?: number | null };
|
||||
|
||||
expect(result.status).toBe('synced');
|
||||
// (a) inline extract was deferred, pages left stale.
|
||||
expect(result.extractDeferred).toBe(true);
|
||||
const staleBefore = await engine.countStalePagesForExtraction();
|
||||
expect(staleBefore).toBeGreaterThan(100);
|
||||
expect(await engine.getLinks('notes/n0')).toHaveLength(0);
|
||||
|
||||
// (b) a follow-up extract job with stale:true was queued.
|
||||
expect(result.extract_stale_job_id).toBeGreaterThan(0);
|
||||
const queue = new MinionQueue(engine);
|
||||
const extractJobs = await queue.getJobs({ name: 'extract', limit: 5 });
|
||||
expect(extractJobs.length).toBe(1);
|
||||
expect((extractJobs[0].data as { stale: boolean }).stale).toBe(true);
|
||||
|
||||
// (c) running the extract handler's stale mode recovers: links + stamps.
|
||||
const extractHandler = (worker as unknown as { handlers: Map<string, (job: unknown) => Promise<unknown>> })
|
||||
.handlers.get('extract');
|
||||
await extractHandler!({
|
||||
data: extractJobs[0].data,
|
||||
signal: { aborted: false },
|
||||
updateProgress: async () => {},
|
||||
});
|
||||
const links = await engine.getLinks('notes/n0');
|
||||
expect(links.some(l => l.to_slug === 'people/alice')).toBe(true);
|
||||
const rows = await engine.executeRaw<{ links_extracted_at: string | null }>(
|
||||
`SELECT links_extracted_at FROM pages WHERE slug = 'notes/n0'`,
|
||||
);
|
||||
expect(rows[0]?.links_extracted_at).not.toBeNull();
|
||||
}, 180_000);
|
||||
|
||||
test('sub-threshold sync does NOT set extractDeferred (no spurious follow-up)', async () => {
|
||||
// One more small commit → inline extract path, no deferral.
|
||||
writeFileSync(join(repoPath, 'notes/small.md'), [
|
||||
'---', 'type: note', 'title: Small', '---', '', 'No big deal.',
|
||||
].join('\n'));
|
||||
git('git add -A && git commit -m "one small page"');
|
||||
const { performSync } = await import('../src/commands/sync.ts');
|
||||
const result = await performSync(engine, { repoPath, noPull: true, noEmbed: true });
|
||||
expect(result.status).toBe('synced');
|
||||
expect(result.extractDeferred).toBeFalsy();
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -100,6 +100,10 @@ describe('runSyncTrigger', () => {
|
||||
const job = jobs[0];
|
||||
expect(job.priority).toBe(-10);
|
||||
expect((job.data as { sourceId: string }).sourceId).toBe('default');
|
||||
// #2849: opt in to inline extraction — the standalone sync handler
|
||||
// defaults noExtract to TRUE, which would leave triggered syncs
|
||||
// extraction-stale.
|
||||
expect((job.data as { noExtract: boolean }).noExtract).toBe(false);
|
||||
expect((job.data as { auto_embed_backfill: boolean }).auto_embed_backfill).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user