mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 17:32:37 +00:00
Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39de1fd649 | ||
|
|
f84bfb57f2 | ||
|
|
ad7114f0ad | ||
|
|
23003a2163 | ||
|
|
4c0ec60275 | ||
|
|
13d95ba0ab | ||
|
|
022a443e9b | ||
|
|
e7439828f1 | ||
|
|
5773736c63 | ||
|
|
56454c6ba8 | ||
|
|
63e79838b9 | ||
|
|
3062859420 | ||
|
|
addf03119d | ||
|
|
dba0ae7b1e | ||
|
|
7376c0266e | ||
|
|
002ac8050f | ||
|
|
f75dbb4ed6 | ||
|
|
437889c0bd | ||
|
|
335e470394 | ||
|
|
7e21e47c15 | ||
|
|
bf7d706bb4 | ||
|
|
bb69aa8b65 | ||
|
|
b4a9c7683d | ||
|
|
3c61e25503 | ||
|
|
c6dc0adf26 | ||
|
|
945fed6105 | ||
|
|
a175dd0047 | ||
|
|
2118f02fc7 | ||
|
|
a12ab5eabc | ||
|
|
e98249a624 | ||
|
|
1057bf4368 | ||
|
|
913d2d7f79 | ||
|
|
f9349ba07f | ||
|
|
e72d93fdb5 | ||
|
|
85286a556c | ||
|
|
a8a3b6df9f | ||
|
|
3aa064bcc6 | ||
|
|
6136e13997 | ||
|
|
b3b43d0f91 | ||
|
|
5b9a87f1a3 | ||
|
|
661f1f05cc | ||
|
|
3fec2123d2 | ||
|
|
176836f84d | ||
|
|
539d015cc5 | ||
|
|
91464564cd | ||
|
|
bd049d2969 | ||
|
|
784358f5fd | ||
|
|
d58bb2b0bb | ||
|
|
b252acfce3 | ||
|
|
894f1dd950 | ||
|
|
f584246dab |
@@ -61,7 +61,10 @@ jobs:
|
||||
- name: Run JSONB double-encode parity tests on real Postgres
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
|
||||
run: bun test test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts
|
||||
# --timeout also raises bun's 5s default hook budget (beforeAll/afterAll
|
||||
# do NOT inherit a test's third-arg timeout; verified on bun 1.3.x).
|
||||
# Every runner script in scripts/ passes it; bare invocations must too.
|
||||
run: bun test --timeout=60000 test/e2e/op-checkpoint-jsonb-parity.test.ts test/e2e/jsonb-roundtrip.test.ts
|
||||
|
||||
tier1:
|
||||
name: Tier 1 (Mechanical)
|
||||
@@ -88,7 +91,7 @@ jobs:
|
||||
bun-version: 1.3.13
|
||||
- run: bun install
|
||||
- name: Run Tier 1 E2E tests
|
||||
run: bun test test/e2e/mechanical.test.ts test/e2e/mcp.test.ts
|
||||
run: bun test --timeout=60000 test/e2e/mechanical.test.ts test/e2e/mcp.test.ts
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
|
||||
|
||||
@@ -155,7 +158,7 @@ jobs:
|
||||
}
|
||||
EOF
|
||||
- name: Run Tier 2 skill tests
|
||||
run: bun test test/e2e/skills.test.ts test/e2e/zeroentropy-live.test.ts
|
||||
run: bun test --timeout=60000 test/e2e/skills.test.ts test/e2e/zeroentropy-live.test.ts
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
@@ -29,7 +29,9 @@ jobs:
|
||||
with:
|
||||
bun-version: 1.3.13
|
||||
- run: bun install
|
||||
- run: bun test
|
||||
# --timeout matches every scripts/ runner and covers hook budgets too
|
||||
# (bunfig.toml's timeout key is ignored by bun; hooks default to 5s).
|
||||
- run: bun test --timeout=60000
|
||||
- run: bun run verify
|
||||
- run: bun build --compile --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts
|
||||
- name: Attest build provenance
|
||||
|
||||
@@ -113,6 +113,11 @@ jobs:
|
||||
key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
- run: bun install
|
||||
- run: bun run verify
|
||||
# Guard: no bare `bun test` in workflows/scripts — bun ignores
|
||||
# bunfig.toml's timeout, and hooks (beforeAll/afterAll) get the 5s
|
||||
# default regardless of per-test third-arg timeouts. Runs directly
|
||||
# (not via verify's CHECKS array) to avoid a package.json edit.
|
||||
- run: bash scripts/check-bun-test-timeout.sh
|
||||
|
||||
serial-tests:
|
||||
# *.serial.test.ts at --max-concurrency=1. Lives in its own runner so
|
||||
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
All notable changes to GBrain will be documented in this file.
|
||||
|
||||
## [0.42.68.1] - 2026-07-30
|
||||
|
||||
**If you run `gbrain reindex-frontmatter` or `gbrain backfill` on the default embedded database, they now work. Until this release both failed every time, after waiting 30 seconds.**
|
||||
|
||||
The embedded database allows one process at a time, and holds a lock to enforce it. These two commands opened a second connection to the same database from inside the process that already held that lock, then waited for a lock that could never be released — because the thing holding it was the waiting process itself. The wait ran its full 30 seconds and the command exited with an error naming a blocking process that was, in fact, itself. Both commands now reuse the connection that is already open.
|
||||
|
||||
Nothing changes for brains on Postgres, where a second connection was always allowed.
|
||||
|
||||
## To take advantage of v0.42.68.1
|
||||
|
||||
Nothing to undo — the commands failed without writing anything. Just run whichever you needed:
|
||||
```bash
|
||||
gbrain reindex-frontmatter
|
||||
```
|
||||
|
||||
## [0.42.67.0] - 2026-07-28
|
||||
|
||||
**If you develop GBrain on Windows, the test and check commands now actually run. Until this release they were quietly doing almost nothing.**
|
||||
|
||||
@@ -67,6 +67,19 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
|
||||
text, the cast parses it). Guarded by `scripts/check-jsonb-pattern.sh` (template grep) +
|
||||
`scripts/check-jsonb-params.mjs` (positional AST scanner); the real backstop is the DATABASE_URL-gated
|
||||
e2e parity tests, since PGLite can't surface the bug. Full rule in `docs/ENGINES.md`.
|
||||
- **Engine-live paths avoid runtime dynamic `import()` for helper dependencies.** In
|
||||
`src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and
|
||||
`src/core/migrate.ts`, dependencies previously reached through runtime dynamic
|
||||
imports use static top-level imports. The only current dynamic-`import()` exceptions
|
||||
are the four `ai/gateway.ts` lookups in both engines'
|
||||
`initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a
|
||||
local `try/catch` because the gateway has a large provider/config closure and,
|
||||
more importantly, eager evaluation would occur before the catch and could
|
||||
turn a recoverable default/config-row fallback into a module-load failure.
|
||||
Every exception carries `engine-dynamic-import-ok` on the import line.
|
||||
`scripts/check-engine-dynamic-import.sh` enforces the rule. For history, use
|
||||
`git log -G'await[[:space:]]+import\\('`, not `git log -S`: a dynamic-to-static
|
||||
rewrite can preserve the searched token while changing its context.
|
||||
- **Engine parity.** `src/core/postgres-engine.ts` and `src/core/pglite-engine.ts` move in
|
||||
lockstep — a new method/SQL shape lands in BOTH, pinned by `test/e2e/engine-parity.test.ts`.
|
||||
Forward-referenced columns/indexes go in the bootstrap probe set (guarded by
|
||||
|
||||
@@ -16,6 +16,13 @@ If you fetched this file by URL without cloning yet, the companion files live at
|
||||
|
||||
## Step 1: Install GBrain
|
||||
|
||||
> **NEVER install from the npm registry.** GBrain is not distributed on npm; the npm
|
||||
> package named `gbrain` is an unrelated package. Do NOT run `npm install -g gbrain` or
|
||||
> `bun add -g gbrain` (note the missing `github:` prefix — that's the trap). The only
|
||||
> supported sources are `github:garrytan/gbrain` and a git clone, exactly as shown below.
|
||||
> If an unrelated npm install is already present, remove it first
|
||||
> (`npm uninstall -g gbrain` / `bun remove -g gbrain`); `gbrain doctor` also detects this.
|
||||
|
||||
Default path (Bun is required — gbrain is a Bun + TypeScript runtime):
|
||||
|
||||
```bash
|
||||
|
||||
@@ -65,6 +65,16 @@ This is the difference between a search engine and a brain. Search finds the pag
|
||||
|
||||
## Install
|
||||
|
||||
> [!WARNING]
|
||||
> **GBrain is NOT distributed on npm.** The npm package named `gbrain` is an unrelated
|
||||
> package with no connection to this project. Do not run `npm install -g gbrain` or
|
||||
> `bun add -g gbrain` — you'll get something else, and it can shadow the real binary on
|
||||
> your PATH. Install and upgrade ONLY via the documented paths below
|
||||
> (`bun install -g github:garrytan/gbrain`, or `git clone` + `bun install && bun link`).
|
||||
> If you already ran the npm install by mistake: `npm uninstall -g gbrain` /
|
||||
> `bun remove -g gbrain`, then reinstall from GitHub. `gbrain doctor` detects a
|
||||
> shadowing npm install and prints the fix.
|
||||
|
||||
GBrain is designed to be installed and operated by an AI agent. The fastest path is to have your agent do it for you. The CLI and MCP paths below are for people who want to wire it up themselves.
|
||||
|
||||
### Have your agent install it (recommended)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -31,7 +31,7 @@ receipt file from disk and re-renders it. The other modes need the brain.
|
||||
| `--budget-usd N` | unset | Abort before next call's projected cost would exceed cap. Models without a `pricing.ts` entry fail loud (codex #4). |
|
||||
| `--source db|fs` | `db` | `fs` is reserved for v0.33+. |
|
||||
| `--slug-prefix P` | unset | Filter takes to pages whose slug starts with P. |
|
||||
| `--models a,b,c` | `openai:gpt-4o,anthropic:claude-opus-4-7,google:gemini-1.5-pro` | Comma-separated panel. |
|
||||
| `--models a,b,c` | `openai:gpt-5.2,anthropic:claude-opus-4-7,google:gemini-2.0-flash` | Comma-separated panel. |
|
||||
| `--json` | off | Emit the full receipt to stdout. |
|
||||
|
||||
## Receipt JSON shape (`schema_version: 1`)
|
||||
@@ -50,7 +50,7 @@ receipt file from disk and re-renders it. The other modes need the brain.
|
||||
},
|
||||
"prompt_sha8": "abcd1234",
|
||||
"models_sha8": "abcd1234",
|
||||
"models": ["openai:gpt-4o", "anthropic:claude-opus-4-7", "google:gemini-1.5-pro"],
|
||||
"models": ["openai:gpt-5.2", "anthropic:claude-opus-4-7", "google:gemini-2.0-flash"],
|
||||
"cycles_run": 3,
|
||||
"successes_per_cycle": [3, 3, 2],
|
||||
"verdict": "pass",
|
||||
|
||||
@@ -59,6 +59,12 @@ streaming progress to stderr. It is idempotent: re-running with the same
|
||||
language produces identical vectors. `--json` prints a machine-readable
|
||||
result envelope but still requires `--yes` (or an interactive confirm).
|
||||
|
||||
No cache purge is needed. The resolved language is part of the query-cache
|
||||
key, so rows written under the previous language are unreachable after the
|
||||
switch — searches read the retokenized index immediately instead of being
|
||||
served pre-switch results for up to `search.cache.ttl_seconds`. Switching
|
||||
back reaches the original rows rather than rebuilding them.
|
||||
|
||||
## Recipe: accent-insensitive Portuguese (`pt_br`)
|
||||
|
||||
Brazilian Portuguese content often mixes accented and unaccented spellings
|
||||
|
||||
@@ -0,0 +1,690 @@
|
||||
# Engine Dynamic-Import Reconciliation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Reconstruct the missing engine-path static-import hardening, preserve the four load-bearing lazy gateway fallbacks, and prevent unreviewed dynamic imports from returning.
|
||||
|
||||
**Architecture:** Make the 13 safe engine/migration import statements static and leave only four line-marked `ai/gateway.ts` imports inside their existing soft-failure `try/catch` boundaries. Enforce that current state with a repository-anchored Bash wrapper delegating to a fail-closed TypeScript AST scanner, a hermetic Bun regression test, package/verify wiring, and current-state architecture documentation.
|
||||
|
||||
**Tech Stack:** TypeScript compiler API, Bun test runner, Bash, Git, generated llms documentation bundles.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Reconstruct directly on branch `claude/kind-meitner-330c90`, based on investigated `origin/master` commit `6136e139972a5449630b4f47f5ed7b4cbe5b811b` plus design commit `d7f52d8c`.
|
||||
- Do not merge or cherry-pick `48ada48f`, `248bfe55`, `ef4cf7a8`, or either historical branch wholesale.
|
||||
- Do not modify `VERSION`, `CHANGELOG.md`, `TODOS.md`, or release metadata; this is a no-version-bump reconciliation.
|
||||
- Keep all four `await import('./ai/gateway.ts')` calls lazy: PGLite and Postgres `initSchema`, plus both `_upsertChunksOnce` methods.
|
||||
- Every allowed lazy gateway line must carry `engine-dynamic-import-ok`; there is no file-level exemption.
|
||||
- Preserve the stronger gateway rationale: the static closure is large, and eager module evaluation would occur outside the local `try/catch`, potentially converting a recoverable configuration/import failure into a module-load-time hard failure.
|
||||
- Describe the hoists as engine-path hardening. Do not claim every dynamic import deterministically causes a Windows crash; system-wide commit exhaustion confounded prior measurements.
|
||||
- Keep shared PGLite/Postgres behavior in parity.
|
||||
- Invoke repository shell scripts through `bash` in `package.json`.
|
||||
- Capture complete test/check output to workspace-local `.context/*.txt` files before inspecting it; never pipe a test command directly through `head` or `tail`.
|
||||
- Use `git log -G`, not `git log -S`, for any additional dynamic-to-static import history work.
|
||||
- Keep every implementation and verification commit local. Do not push, create a PR, comment upstream, or otherwise publish without explicit user approval after local completion.
|
||||
- Before editing any affected function, run GBrain `code_blast` and `code_callers` for that symbol and inspect any disambiguation candidates.
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
- Create `scripts/check-engine-dynamic-import.sh` — repository-anchored Bash wrapper for default and explicit input routing.
|
||||
- Create `scripts/check-engine-dynamic-import.ts` — TypeScript AST policy scanner for runtime `import()` expressions, parse/read failures, and exact-line comment-trivia opt-outs.
|
||||
- Create `test/scripts/check-engine-dynamic-import.test.ts` — 22 hermetic adversarial, CRLF, fail-closed, real-tree, and wiring tests.
|
||||
- Modify `src/core/pglite-engine.ts` — hoist three safe import statements and mark two deliberate gateway imports.
|
||||
- Modify `src/core/postgres-engine.ts` — hoist eight safe import statements and mark two deliberate gateway imports.
|
||||
- Modify `src/core/migrate.ts` — hoist two safe migration helper import statements.
|
||||
- Modify `package.json` — expose `check:engine-dynamic-import` and append it to `check:all` through `bash`.
|
||||
- Modify `scripts/run-verify-parallel.sh` — add the package check to the authoritative verify dispatcher.
|
||||
- Modify `CLAUDE.md` — add the cross-cutting current-state invariant.
|
||||
- Modify `docs/architecture/KEY_FILES.md` — update current-state entries for the three engine-path files.
|
||||
- Regenerate `llms.txt` and `llms-full.txt` — required derived bundles after CLAUDE/reference documentation changes.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Establish and enforce the source invariant
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/check-engine-dynamic-import.sh`
|
||||
- Create: `scripts/check-engine-dynamic-import.ts`
|
||||
- Create: `test/scripts/check-engine-dynamic-import.test.ts`
|
||||
- Modify: `src/core/pglite-engine.ts`
|
||||
- Modify: `src/core/postgres-engine.ts`
|
||||
- Modify: `src/core/migrate.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: shell positional arguments `FILE...`; without arguments, the guard scans the three repository files.
|
||||
- Produces: `scripts/check-engine-dynamic-import.sh [FILE...]`, exit `0` when every runtime dynamic import is allowed and exit `1` after reporting every `file:line:text` violation plus every read/parse error on stderr.
|
||||
- Produces: one line-level opt-out token, `engine-dynamic-import-ok`, accepted only in real comment trivia on the same physical line as the deliberately lazy import.
|
||||
- Fails closed on missing/unreadable inputs, TypeScript parse diagnostics, and scanner/process failures; comments, strings, templates, regex literals, and type-position `import(...)` syntax are not runtime imports.
|
||||
|
||||
- [ ] **Step 1: Record call-graph blast radius before touching functions**
|
||||
|
||||
First call `sources_list` and select the source whose registered path is this gbrain checkout. Then run `code_blast` and `code_callers` for these qualified symbols with that exact `source_id`, following `did_you_mean`/`candidates` when a method name is ambiguous:
|
||||
|
||||
```text
|
||||
src/core/pglite-engine.ts::PGLiteEngine.initSchema
|
||||
src/core/pglite-engine.ts::PGLiteEngine.batchRetry
|
||||
src/core/pglite-engine.ts::PGLiteEngine._upsertChunksOnce
|
||||
src/core/pglite-engine.ts::PGLiteEngine.mergeOntologyFact
|
||||
src/core/pglite-engine.ts::PGLiteEngine.getRecentSalience
|
||||
src/core/postgres-engine.ts::PostgresEngine.disconnect
|
||||
src/core/postgres-engine.ts::PostgresEngine.initSchema
|
||||
src/core/postgres-engine.ts::PostgresEngine.batchRetry
|
||||
src/core/postgres-engine.ts::PostgresEngine._upsertChunksOnce
|
||||
src/core/postgres-engine.ts::PostgresEngine.mergeOntologyFact
|
||||
src/core/postgres-engine.ts::PostgresEngine.reconnect
|
||||
src/core/postgres-engine.ts::PostgresEngine.getRecentSalience
|
||||
src/core/migrate.ts::runMigrationSQLWithRetry
|
||||
src/core/migrate.ts::runMigrations
|
||||
```
|
||||
|
||||
Use `depth: 5`, `max_nodes: 200`, and `limit: 100`. Expected: no caller requires a signature or behavior change; the patch only changes module binding time and retains all local fallback/error handling.
|
||||
|
||||
- [ ] **Step 2: Write the failing guard regression test**
|
||||
|
||||
Create `test/scripts/check-engine-dynamic-import.test.ts` as a hermetic subprocess suite. The completed 22-test surface covers:
|
||||
|
||||
- unmarked runtime `import()` rejection, including bare and trivia-separated forms;
|
||||
- same-line markers in real line or multiline block-comment trivia;
|
||||
- rejection of markers on prior lines or inside strings, templates, and module paths;
|
||||
- comments and comment-like delimiters inside strings, templates, and regex literals;
|
||||
- live code after same-line or multiline block comments close;
|
||||
- CRLF input and complete multi-file violation aggregation;
|
||||
- missing/readable mixed inputs and TypeScript parse diagnostics;
|
||||
- default repository anchoring when invoked from a foreign Git repository;
|
||||
- the reconciled three-file source scan plus package/parallel-verifier wiring.
|
||||
|
||||
Use the TypeScript parser rather than a partial lexical reimplementation. On Windows, set the test default to 30 seconds because each case launches Git Bash and Bun, whose startup can exceed Bun's 5-second per-test default.
|
||||
|
||||
- [ ] **Step 3: Run the test to prove the pre-implementation red state**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-red.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit 0
|
||||
```
|
||||
|
||||
Expected: non-zero Bun result captured inside the log. At minimum, the `exists` assertion fails because `scripts/check-engine-dynamic-import.sh` does not exist. Read `.context/engine-dynamic-import-red.txt`; do not infer the result from a truncated pipeline.
|
||||
|
||||
- [ ] **Step 4: Add the CRLF-safe, fail-closed guard**
|
||||
|
||||
Create `scripts/check-engine-dynamic-import.sh` as a thin LF-terminated wrapper. Resolve its own directory first; when no explicit files are passed, anchor the repository with `git -C "$SCRIPT_DIR/.."` and scan the two engines plus `migrate.ts`. Delegate with `exec bun "$SCRIPT_DIR/check-engine-dynamic-import.ts" "${FILES[@]}"` so scanner failures propagate.
|
||||
|
||||
Create `scripts/check-engine-dynamic-import.ts` using the TypeScript compiler API:
|
||||
|
||||
- read every requested file and aggregate read failures;
|
||||
- parse as TypeScript and aggregate parse diagnostics;
|
||||
- walk the AST for `CallExpression`s whose expression is `ImportKeyword`;
|
||||
- locate all marker occurrences in the full source and use `ts.getTokenAtPosition` to admit only occurrences outside AST tokens (real comment trivia), recording their physical source lines;
|
||||
- require each runtime import's line to have an admitted marker or report its original `file:line:text`;
|
||||
- print every read/parse error and every violation before exiting nonzero.
|
||||
|
||||
This preserves CRLF line accounting, ignores comment/literal/type-only false positives, catches every legal runtime `import()` shape the TypeScript parser recognizes, rejects marker spoofing, and fails closed.
|
||||
|
||||
- [ ] **Step 5: Run the guard test to prove the source-tree midpoint is still red**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-midpoint.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit 0
|
||||
```
|
||||
|
||||
Expected: the synthetic violation, marker, comments, and CRLF cases pass. The default repository scan fails and reports all 17 current imports: 13 unmarked safe candidates plus the four not-yet-marked gateway calls.
|
||||
|
||||
- [ ] **Step 6: Hoist the three safe PGLite import statements**
|
||||
|
||||
Replace the existing `retry.ts` import and add the ontology/recency imports near the top of `src/core/pglite-engine.ts`:
|
||||
|
||||
```ts
|
||||
// Engine-path imports stay static unless a call site carries an explicit
|
||||
// engine-dynamic-import-ok justification. The gateway is the only current
|
||||
// exception because its local try/catch preserves a soft fallback.
|
||||
import {
|
||||
withRetry,
|
||||
BULK_RETRY_OPTS,
|
||||
resolveBulkRetryOpts,
|
||||
computeNextDelay,
|
||||
isRetryableConnError,
|
||||
type BatchAuditSite,
|
||||
} from './retry.ts';
|
||||
import {
|
||||
valueHash,
|
||||
normalizeDimension,
|
||||
isNovelDimension,
|
||||
} from './chronicle/ontology.ts';
|
||||
import {
|
||||
resolveRecencyDecayMap,
|
||||
DEFAULT_FALLBACK,
|
||||
} from './search/recency-decay.ts';
|
||||
```
|
||||
|
||||
Delete only these three in-method destructuring imports, leaving their uses unchanged:
|
||||
|
||||
```ts
|
||||
const { isRetryableConnError } = await import('./retry.ts');
|
||||
const { valueHash, normalizeDimension, isNovelDimension } = await import('./chronicle/ontology.ts');
|
||||
const { resolveRecencyDecayMap, DEFAULT_FALLBACK } = await import('./search/recency-decay.ts');
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Mark both PGLite gateway soft-failure boundaries**
|
||||
|
||||
In `PGLiteEngine.initSchema`, preserve the `try/catch` and accessors, changing only the rationale and import line:
|
||||
|
||||
```ts
|
||||
try {
|
||||
// Keep the gateway lazy: its static closure is large, and evaluation inside
|
||||
// this try/catch preserves the unconfigured-gateway default fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
// Both accessors THROW when the gateway is unconfigured (they never
|
||||
// return falsy), so the catch below is the only fallback path (#3461).
|
||||
dims = gw.getEmbeddingDimensions();
|
||||
model = gw.getEmbeddingModel();
|
||||
} catch { /* gateway not configured — use defaults */ }
|
||||
```
|
||||
|
||||
In `PGLiteEngine._upsertChunksOnce`, preserve the config-row and compile-time fallback chain:
|
||||
|
||||
```ts
|
||||
try {
|
||||
// Keep the gateway lazy so module-load failure remains inside this soft
|
||||
// fallback boundary; eager evaluation would bypass the config-row fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
resolvedModel = gw.getEmbeddingModel();
|
||||
} catch {
|
||||
```
|
||||
|
||||
- [ ] **Step 8: Hoist the eight safe Postgres import statements**
|
||||
|
||||
Replace the existing `retry.ts` import and add these imports near the top of `src/core/postgres-engine.ts`:
|
||||
|
||||
```ts
|
||||
// Engine-path imports stay static unless a call site carries an explicit
|
||||
// engine-dynamic-import-ok justification. The gateway is the only current
|
||||
// exception because its local try/catch preserves a soft fallback.
|
||||
import {
|
||||
withRetry,
|
||||
BULK_RETRY_OPTS,
|
||||
resolveBulkRetryOpts,
|
||||
computeNextDelay,
|
||||
isRetryableConnError,
|
||||
type BatchAuditSite,
|
||||
} from './retry.ts';
|
||||
import { isConnectionEndedError } from './retry-matcher.ts';
|
||||
import {
|
||||
valueHash,
|
||||
normalizeDimension,
|
||||
isNovelDimension,
|
||||
} from './chronicle/ontology.ts';
|
||||
import {
|
||||
resolveRecencyDecayMap,
|
||||
DEFAULT_FALLBACK,
|
||||
} from './search/recency-decay.ts';
|
||||
import { logDbDisconnect } from './audit/db-disconnect-audit.ts';
|
||||
import { logPoolRecovery } from './audit/pool-recovery-audit.ts';
|
||||
```
|
||||
|
||||
Delete the eight safe dynamic-import statements while keeping their surrounding `try/catch` blocks and calls unchanged:
|
||||
|
||||
```ts
|
||||
const { logDbDisconnect } = await import('./audit/db-disconnect-audit.ts');
|
||||
const { isRetryableConnError } = await import('./retry.ts');
|
||||
const { valueHash, normalizeDimension, isNovelDimension } = await import('./chronicle/ontology.ts');
|
||||
const { isConnectionEndedError } = await import('./retry-matcher.ts');
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
const { resolveRecencyDecayMap, DEFAULT_FALLBACK } = await import('./search/recency-decay.ts');
|
||||
```
|
||||
|
||||
Update the stale `batchRetry` comment from “Lazy-import to avoid a circular dep concern” to current truth:
|
||||
|
||||
```ts
|
||||
// retry.ts is already in this module's static graph through withRetry, so
|
||||
// classifying the exhausted error does not need a second runtime import.
|
||||
```
|
||||
|
||||
- [ ] **Step 9: Mark both Postgres gateway soft-failure boundaries**
|
||||
|
||||
In `PostgresEngine.initSchema`, mirror the PGLite rationale and preserve behavior:
|
||||
|
||||
```ts
|
||||
try {
|
||||
// Keep the gateway lazy: its static closure is large, and evaluation inside
|
||||
// this try/catch preserves the unconfigured-gateway default fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
// Both accessors THROW when the gateway is unconfigured (they never
|
||||
// return falsy), so the catch below is the only fallback path (#3461).
|
||||
dims = gw.getEmbeddingDimensions();
|
||||
model = gw.getEmbeddingModel();
|
||||
} catch { /* gateway not yet configured — use defaults */ }
|
||||
```
|
||||
|
||||
In `PostgresEngine._upsertChunksOnce`, preserve the DB-config fallback:
|
||||
|
||||
```ts
|
||||
try {
|
||||
// Keep the gateway lazy so module-load failure remains inside this soft
|
||||
// fallback boundary; eager evaluation would bypass the config-row fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
resolvedModel = gw.getEmbeddingModel();
|
||||
} catch {
|
||||
```
|
||||
|
||||
- [ ] **Step 10: Hoist the two migration helper import statements**
|
||||
|
||||
Add these static imports at the top of `src/core/migrate.ts`:
|
||||
|
||||
```ts
|
||||
// runMigrations executes while an initialized engine is live. Keep its helper
|
||||
// modules in the static graph rather than importing them from async handlers.
|
||||
import {
|
||||
isStatementTimeoutError,
|
||||
isRetryableConnError,
|
||||
} from './retry-matcher.ts';
|
||||
import { repairTimelineDedupIndex } from './timeline-dedup-repair.ts';
|
||||
```
|
||||
|
||||
Delete only these two local destructuring imports:
|
||||
|
||||
```ts
|
||||
const { isStatementTimeoutError, isRetryableConnError } = await import('./retry-matcher.ts');
|
||||
const { repairTimelineDedupIndex } = await import('./timeline-dedup-repair.ts');
|
||||
```
|
||||
|
||||
- [ ] **Step 11: Run the complete guard test and direct guard**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-green.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; the full guard regression suite passes.
|
||||
|
||||
```bash
|
||||
bash scripts/check-engine-dynamic-import.sh > .context/engine-dynamic-import-guard.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; output contains `check-engine-dynamic-import: ok (3 file(s) scanned)`.
|
||||
|
||||
- [ ] **Step 12: Prove the guard leaves exactly four marked dynamic imports**
|
||||
|
||||
```bash
|
||||
git grep -n -F "import('./ai/gateway.ts'); // engine-dynamic-import-ok" -- src/core/pglite-engine.ts src/core/postgres-engine.ts src/core/migrate.ts > .context/engine-dynamic-import-sites.txt; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exactly four lines, all importing `./ai/gateway.ts` and all carrying `engine-dynamic-import-ok`; no match in `src/core/migrate.ts`.
|
||||
|
||||
- [ ] **Step 13: Run focused behavior tests**
|
||||
|
||||
```bash
|
||||
bun test test/chronicle-ontology.test.ts test/chronicle-ontology-ops.test.ts test/recency-decay.test.ts test/core/retry.test.ts test/retry-matcher.test.ts test/audit/pool-recovery-audit.test.ts test/migrate-retry.test.ts test/timeline-dedup-repair.test.ts > .context/engine-dynamic-import-focused.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`. If Windows resource pressure aborts the process, record the exact exit code and rerun the failing file alone; do not relabel an infrastructure abort as a source pass.
|
||||
|
||||
- [ ] **Step 14: Commit the source invariant locally**
|
||||
|
||||
```bash
|
||||
git add scripts/check-engine-dynamic-import.sh scripts/check-engine-dynamic-import.ts test/scripts/check-engine-dynamic-import.test.ts src/core/pglite-engine.ts src/core/postgres-engine.ts src/core/migrate.ts
|
||||
```
|
||||
|
||||
```bash
|
||||
git commit -m "fix(engine): reconcile dynamic import hardening"
|
||||
```
|
||||
|
||||
Expected: one local commit; no version or release files staged.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Wire the guard into repository checks
|
||||
|
||||
**Files:**
|
||||
- Modify: `test/scripts/check-engine-dynamic-import.test.ts`
|
||||
- Modify: `package.json`
|
||||
- Modify: `scripts/run-verify-parallel.sh`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `scripts/check-engine-dynamic-import.sh` from Task 1.
|
||||
- Produces: package script `check:engine-dynamic-import` and verify dry-list entry of the same name.
|
||||
|
||||
- [ ] **Step 1: Add failing wiring assertions**
|
||||
|
||||
Add these imports/constants to `test/scripts/check-engine-dynamic-import.test.ts`:
|
||||
|
||||
```ts
|
||||
const PACKAGE_JSON = resolve(REPO_ROOT, 'package.json');
|
||||
```
|
||||
|
||||
Append this test block:
|
||||
|
||||
```ts
|
||||
describe('engine dynamic-import guard wiring', () => {
|
||||
it('is invoked through bash by check:all', () => {
|
||||
const pkg = JSON.parse(readFileSync(PACKAGE_JSON, 'utf8')) as {
|
||||
scripts: Record<string, string>;
|
||||
};
|
||||
expect(pkg.scripts['check:engine-dynamic-import']).toBe(
|
||||
'bash scripts/check-engine-dynamic-import.sh',
|
||||
);
|
||||
expect(pkg.scripts['check:all']).toContain(
|
||||
'bash scripts/check-engine-dynamic-import.sh',
|
||||
);
|
||||
});
|
||||
|
||||
it('is listed by the authoritative verify dispatcher', () => {
|
||||
const result = spawnSync(BASH, [VERIFY_DISPATCHER, '--dry-list'], {
|
||||
cwd: REPO_ROOT,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(new Set((result.stdout ?? '').trim().split('\n'))).toContain(
|
||||
'check:engine-dynamic-import',
|
||||
);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test and verify both wiring assertions fail**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-wiring-red.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit 0
|
||||
```
|
||||
|
||||
Expected: non-zero Bun result. The source guard tests remain green; package-script and verify-list assertions fail because the wiring is absent.
|
||||
|
||||
- [ ] **Step 3: Add the package scripts**
|
||||
|
||||
In `package.json`, add this script alongside the other `check:*` entries:
|
||||
|
||||
```json
|
||||
"check:engine-dynamic-import": "bash scripts/check-engine-dynamic-import.sh"
|
||||
```
|
||||
|
||||
Append the guard to the existing `check:all` chain, preserving every existing check:
|
||||
|
||||
```text
|
||||
&& bash scripts/check-engine-dynamic-import.sh
|
||||
```
|
||||
|
||||
Do not rewrite any existing shell entry without its `bash` prefix.
|
||||
|
||||
- [ ] **Step 4: Add the authoritative verify entry**
|
||||
|
||||
In `scripts/run-verify-parallel.sh`, add this stable `CHECKS` entry near the other source-shape guards:
|
||||
|
||||
```bash
|
||||
"check:engine-dynamic-import"
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run the regression test and package check**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-wiring-green.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; the full guard regression suite passes.
|
||||
|
||||
```bash
|
||||
bun run check:engine-dynamic-import > .context/engine-dynamic-import-package-check.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0` and three files scanned.
|
||||
|
||||
- [ ] **Step 6: Commit the wiring locally**
|
||||
|
||||
```bash
|
||||
git add package.json scripts/run-verify-parallel.sh test/scripts/check-engine-dynamic-import.test.ts
|
||||
```
|
||||
|
||||
```bash
|
||||
git commit -m "test(engine): guard dynamic import policy"
|
||||
```
|
||||
|
||||
Expected: one local commit with the guard wiring and its regression assertions.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Document the current-state invariant
|
||||
|
||||
**Files:**
|
||||
- Modify: `CLAUDE.md`
|
||||
- Modify: `docs/architecture/KEY_FILES.md`
|
||||
- Regenerate: `llms.txt`
|
||||
- Regenerate: `llms-full.txt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: the four-marked-import source state and the `check:engine-dynamic-import` package surface.
|
||||
- Produces: current-state contributor guidance and fresh generated documentation bundles.
|
||||
|
||||
- [ ] **Step 1: Add the cross-cutting invariant to `CLAUDE.md`**
|
||||
|
||||
Add this bullet under “Cross-cutting invariants” near the other language/filesystem guards:
|
||||
|
||||
```md
|
||||
- **Engine-live paths use static imports by default.** In
|
||||
`src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and
|
||||
`src/core/migrate.ts`, helper modules are top-level imports. The only current
|
||||
exceptions are the four `ai/gateway.ts` lookups in both engines'
|
||||
`initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a
|
||||
local `try/catch` because the gateway has a large provider/config closure and,
|
||||
more importantly, eager evaluation would occur before the catch and could
|
||||
turn a recoverable default/config-row fallback into a module-load failure.
|
||||
Every exception carries `engine-dynamic-import-ok` on the import line.
|
||||
`scripts/check-engine-dynamic-import.sh` enforces the rule. For history, use
|
||||
`git log -G'await[[:space:]]+import\\('`, not `git log -S`: a dynamic-to-static
|
||||
rewrite can preserve the searched token while changing its context.
|
||||
```
|
||||
|
||||
Do not add release tags, Windows-crash certainty, or historical branch names.
|
||||
|
||||
- [ ] **Step 2: Update the PGLite current-state entry in `KEY_FILES.md`**
|
||||
|
||||
Append this current-state sentence to the existing `src/core/pglite-engine.ts` entry, preserving the entry as one bullet:
|
||||
|
||||
```md
|
||||
Engine-path helper dependencies (`retry`, ontology, recency decay) bind statically; the only lazy imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update the Postgres current-state entry in `KEY_FILES.md`**
|
||||
|
||||
Append this sentence to the existing `src/core/postgres-engine.ts` entry:
|
||||
|
||||
```md
|
||||
Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite.
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update the migration current-state entry in `KEY_FILES.md`**
|
||||
|
||||
Append this sentence to the canonical `src/core/migrate.ts` entry (the broad runner entry, not the older v95-specific index note):
|
||||
|
||||
```md
|
||||
`retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations.
|
||||
```
|
||||
|
||||
Keep all three entries current-state only: no `v0.42.x`, branch, commit, “previously,” or “was/now” narration.
|
||||
|
||||
- [ ] **Step 5: Regenerate the llms bundles**
|
||||
|
||||
```bash
|
||||
bun run build:llms > .context/engine-dynamic-import-build-llms.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; `llms.txt` and/or `llms-full.txt` update according to their configured linked/inlined status. Byte-identical output for a linked source is acceptable; the freshness test is authoritative.
|
||||
|
||||
- [ ] **Step 6: Run documentation freshness checks**
|
||||
|
||||
```bash
|
||||
bun test test/build-llms.test.ts > .context/engine-dynamic-import-llms-test.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`.
|
||||
|
||||
```bash
|
||||
bun run check:doc-history > .context/engine-dynamic-import-doc-history.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; no release-history marker is introduced into current-state reference docs.
|
||||
|
||||
- [ ] **Step 7: Confirm prohibited release files remain untouched**
|
||||
|
||||
```bash
|
||||
git diff --name-only d7f52d8c..HEAD -- VERSION CHANGELOG.md TODOS.md
|
||||
```
|
||||
|
||||
Expected: no output.
|
||||
|
||||
- [ ] **Step 8: Commit documentation and generated bundles locally**
|
||||
|
||||
```bash
|
||||
git add CLAUDE.md docs/architecture/KEY_FILES.md llms.txt llms-full.txt
|
||||
```
|
||||
|
||||
```bash
|
||||
git commit -m "docs(engine): record static import invariant"
|
||||
```
|
||||
|
||||
Expected: one local documentation commit. If one generated bundle is byte-identical, Git simply omits it.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Verify and review the complete local reconciliation
|
||||
|
||||
**Files:**
|
||||
- Verify all files changed since `d7f52d8c`.
|
||||
- Do not create or modify release/publication metadata.
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Tasks 1–3.
|
||||
- Produces: full local verification evidence and an implementation diff ready for user review, not publication.
|
||||
|
||||
- [ ] **Step 1: Run the regression test and direct guard again**
|
||||
|
||||
```bash
|
||||
bun test test/scripts/check-engine-dynamic-import.test.ts > .context/engine-dynamic-import-final-test.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; the full guard regression suite passes.
|
||||
|
||||
```bash
|
||||
bash scripts/check-engine-dynamic-import.sh > .context/engine-dynamic-import-final-guard.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; three files scanned.
|
||||
|
||||
- [ ] **Step 2: Run TypeScript checking**
|
||||
|
||||
```bash
|
||||
bun run typecheck > .context/engine-dynamic-import-typecheck.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`. Report exact diagnostics if the branch or current Windows environment has a pre-existing failure.
|
||||
|
||||
- [ ] **Step 3: Run the authoritative verify dispatcher**
|
||||
|
||||
```bash
|
||||
bun run verify > .context/engine-dynamic-import-verify.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`, including `check:engine-dynamic-import`. On Windows, classify any per-check timeout from the complete log instead of treating the aggregate result as a source regression without evidence.
|
||||
|
||||
- [ ] **Step 4: Re-run focused tests as an ownership check**
|
||||
|
||||
```bash
|
||||
bun test test/chronicle-ontology.test.ts test/chronicle-ontology-ops.test.ts test/recency-decay.test.ts test/core/retry.test.ts test/retry-matcher.test.ts test/audit/pool-recovery-audit.test.ts test/migrate-retry.test.ts test/timeline-dedup-repair.test.ts > .context/engine-dynamic-import-final-focused.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`; record any infrastructure abort separately and rerun only the named file before classifying it.
|
||||
|
||||
- [ ] **Step 5: Run the llms freshness test after all documentation settles**
|
||||
|
||||
```bash
|
||||
bun test test/build-llms.test.ts > .context/engine-dynamic-import-final-llms.txt 2>&1; rc=$?; printf 'EXIT=%s\n' "$rc"; exit "$rc"
|
||||
```
|
||||
|
||||
Expected: exit `0`.
|
||||
|
||||
- [ ] **Step 6: Run whitespace and scope checks**
|
||||
|
||||
```bash
|
||||
git diff --check d7f52d8c..HEAD
|
||||
```
|
||||
|
||||
Expected: exit `0`, no output.
|
||||
|
||||
```bash
|
||||
git diff --name-only d7f52d8c..HEAD
|
||||
```
|
||||
|
||||
Expected files only:
|
||||
|
||||
```text
|
||||
CLAUDE.md
|
||||
docs/architecture/KEY_FILES.md
|
||||
docs/superpowers/plans/2026-07-28-engine-dynamic-import-reconciliation.md
|
||||
llms-full.txt
|
||||
llms.txt
|
||||
package.json
|
||||
scripts/check-engine-dynamic-import.sh
|
||||
scripts/check-engine-dynamic-import.ts
|
||||
scripts/run-verify-parallel.sh
|
||||
src/core/migrate.ts
|
||||
src/core/pglite-engine.ts
|
||||
src/core/postgres-engine.ts
|
||||
test/scripts/check-engine-dynamic-import.test.ts
|
||||
```
|
||||
|
||||
Either generated llms file may be absent if regeneration proves it byte-identical. `VERSION`, `CHANGELOG.md`, and `TODOS.md` must be absent.
|
||||
|
||||
- [ ] **Step 7: Review the exact implementation diff**
|
||||
|
||||
```bash
|
||||
git diff --stat d7f52d8c..HEAD && git diff d7f52d8c..HEAD -- src/core/pglite-engine.ts src/core/postgres-engine.ts src/core/migrate.ts scripts/check-engine-dynamic-import.sh test/scripts/check-engine-dynamic-import.test.ts package.json scripts/run-verify-parallel.sh CLAUDE.md docs/architecture/KEY_FILES.md
|
||||
```
|
||||
|
||||
Expected review findings:
|
||||
|
||||
- Exactly 13 safe `await import(...)` statements are removed.
|
||||
- Exactly four `ai/gateway.ts` imports remain, all marked on the same line.
|
||||
- All four gateway imports remain inside their original local `try/catch` fallback boundaries.
|
||||
- No accessor logic, fallback ordering, SQL, public signature, or engine parity behavior changes.
|
||||
- The parser-backed guard reports all violations plus read/parse failures, preserves CRLF line accounting, ignores comments/literals/type-only syntax, detects every runtime `import()` call expression, and accepts opt-outs only from real comment trivia on the same physical line.
|
||||
- The package script invokes the shell guard through Bash; `check:all` invokes that shell guard directly, and the parallel verify dispatcher invokes the package check.
|
||||
- Documentation is current-state and makes no deterministic Windows-crash claim.
|
||||
|
||||
**Observed Windows verification classification:** The authoritative aggregate completed with 25 of 33 checks passing. Individual reruns showed `check:test-names` and `typecheck` green; privacy/isolation exceeded Windows timing budgets; WASM failed in unrelated temporary-symlink setup; eval-glossary was CRLF/LF drift; resolver/brain-first findings predated and did not intersect this branch. The focused aggregate produced 103 pass / 5 fail: three setup-hook timeouts reproduced at the untouched base, and the known `migrate-retry` polling failure reproduced there. Its additional race-status assertion did not reproduce at base, so it remains an unresolved timing-sensitive limitation in untouched code—not evidence of an in-scope defect and not claimed as conclusively pre-existing.
|
||||
|
||||
- [ ] **Step 8: Commit the approved plan document locally**
|
||||
|
||||
The plan is an approved, tracked execution artifact and must not be left as an uncommitted file after implementation:
|
||||
|
||||
```bash
|
||||
git add docs/superpowers/plans/2026-07-28-engine-dynamic-import-reconciliation.md
|
||||
```
|
||||
|
||||
```bash
|
||||
git commit -m "docs: plan engine dynamic-import reconciliation"
|
||||
```
|
||||
|
||||
Expected: one local plan commit; no release metadata staged.
|
||||
|
||||
- [ ] **Step 9: Inspect final status without publishing**
|
||||
|
||||
```bash
|
||||
git status --short --branch
|
||||
```
|
||||
|
||||
Expected: branch `claude/kind-meitner-330c90` with a clean working tree. No push, PR, upstream comment, or other external side effect.
|
||||
|
||||
- [ ] **Step 10: Capture the completed milestone to memory**
|
||||
|
||||
Before writing, search MemPalace wing `gbrain` for this exact reconciliation to avoid duplication. Add a verbatim drawer recording exact base/head commits, the 13 hoists, four gateway opt-outs and rationale, guard/test/docs files, every verification command with exit code, and any environment-owned failures. Add a GBrain project timeline entry only if there is an existing relevant gbrain project page; do not create duplicate release metadata.
|
||||
|
||||
- [ ] **Step 11: Report the local result and ask separately before publication**
|
||||
|
||||
Report:
|
||||
|
||||
- exact local commits;
|
||||
- changed files;
|
||||
- test/check exit codes;
|
||||
- any blocked or pre-existing failures;
|
||||
- confirmation that release files were untouched;
|
||||
- confirmation that nothing was pushed or published.
|
||||
|
||||
Do not run any publication command. Wait for explicit user approval before any push, PR, or upstream interaction.
|
||||
@@ -0,0 +1,175 @@
|
||||
# Scalar-source Backlink Validation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Make backlink validation compare exact `(source_id, slug)` endpoint identities while preserving existing scalar, unscoped, and federated link-read semantics.
|
||||
|
||||
**Architecture:** Enrich every engine link-read row with the source identity of its joined from, to, and visible origin pages. Pass the validated page's scalar or federated scope into validator context; the backlink validator scopes its initial read consistently, groups targets by exact identity, and accepts only an exact reverse endpoint pair. SQL predicates remain unchanged, so trusted scalar cross-source visibility and federated all-endpoint containment remain intact.
|
||||
|
||||
**Tech Stack:** TypeScript, Bun test, PGLite, PostgreSQL/postgres.js.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Use strict red-before-green TDD with duplicate slugs across sources.
|
||||
- Preserve unscoped historical reads, scalar near-endpoint scoping, scalar explicit cross-source visibility, federated all-endpoint containment, and `sourceIds` precedence.
|
||||
- Keep PostgreSQL and PGLite projections in parity.
|
||||
- Do not change schema or conditional-write conflict semantics.
|
||||
- Keep deployment, restart, migration, and push actions outside the implementation tasks; a separately authorized release workflow may perform them after verification.
|
||||
- Capture full test output to files before inspecting it.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Pin the backlink false-negative in PGLite
|
||||
|
||||
**Files:**
|
||||
- Modify: `test/writer.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `backLinkValidator.validate(PageValidationContext)` and source-qualified `putPage`/`addLink`.
|
||||
- Produces: regressions for wrong-source reverse rejection, exact reverse acceptance, cross-source pair acceptance, and exact target deduplication.
|
||||
|
||||
- [ ] **Step 1: Add the minimal failing duplicate-slug regression**
|
||||
|
||||
Create `default` and `team-x` copies of the origin and target, add `(team-x, origin) -> (team-x, target)` plus the wrong reverse `(team-x, target) -> (default, origin)`, validate with `sourceId: 'team-x'`, and require one warning.
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
```bash
|
||||
bun test test/writer.test.ts -t "wrong-source reverse" > "$TEMP/backlink-red.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: assertion failure because current slug-only validation returns zero findings.
|
||||
|
||||
- [ ] **Step 3: Add the remaining behavioral regressions after the first red is recorded**
|
||||
|
||||
Add tests proving that the exact reverse clears the warning, a legitimate cross-source forward/reverse pair passes, and two destinations sharing one slug but differing by source are validated independently.
|
||||
|
||||
### Task 2: Expose exact endpoint identity from both engines
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/types.ts:1204-1229`
|
||||
- Modify: `src/core/postgres-engine.ts:3021-3124`
|
||||
- Modify: `src/core/pglite-engine.ts:2941-3037`
|
||||
- Modify: `test/get-page-federated-scope.test.ts:187-246,289-306`
|
||||
- Modify: `test/e2e/multi-source-bug-class.test.ts:184-205`
|
||||
- Modify: `test/e2e/engine-parity.test.ts:813-875`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `Link.from_source_id: string`, `Link.to_source_id: string`, and `Link.origin_source_id?: string | null`.
|
||||
- Preserves: `getLinks(slug, { sourceId?, sourceIds? })` and `getBacklinks(...)` filtering semantics.
|
||||
|
||||
- [ ] **Step 1: Add engine-contract assertions before implementation**
|
||||
|
||||
Assert scalar cross-source rows expose `beta -> default`, federated rows expose only in-grant endpoint IDs, `sourceIds` still beats scalar `sourceId`, and an out-of-grant origin has both `origin_slug` and `origin_source_id` null.
|
||||
|
||||
- [ ] **Step 2: Run the focused contract tests and verify RED**
|
||||
|
||||
```bash
|
||||
bun test test/get-page-federated-scope.test.ts test/e2e/multi-source-bug-class.test.ts > "$TEMP/link-identity-red.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: source-ID assertions fail because fields are absent.
|
||||
|
||||
- [ ] **Step 3: Extend `Link` and project IDs without changing predicates**
|
||||
|
||||
Use this additive contract:
|
||||
|
||||
```ts
|
||||
export interface Link {
|
||||
from_slug: string;
|
||||
from_source_id: string;
|
||||
to_slug: string;
|
||||
to_source_id: string;
|
||||
link_type: string;
|
||||
context: string;
|
||||
link_source?: string | null;
|
||||
origin_slug?: string | null;
|
||||
origin_source_id?: string | null;
|
||||
origin_field?: string | null;
|
||||
}
|
||||
```
|
||||
|
||||
In all six branches per engine, project:
|
||||
|
||||
```sql
|
||||
f.source_id AS from_source_id,
|
||||
t.source_id AS to_source_id,
|
||||
o.source_id AS origin_source_id
|
||||
```
|
||||
|
||||
Keep every `WHERE` and grant-aware origin `LEFT JOIN` unchanged.
|
||||
|
||||
- [ ] **Step 4: Re-run contract tests and verify GREEN**
|
||||
|
||||
Use the same command and require all focused tests to pass.
|
||||
|
||||
### Task 3: Validate exact reverse identities and propagate scope
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/output/writer.ts:89-96,240-318`
|
||||
- Modify: `src/core/output/post-write.ts:36-41,73-118`
|
||||
- Modify: `src/core/output/validators/back-link.ts:24-47`
|
||||
- Modify: `src/core/operations.ts:1227-1246`
|
||||
- Modify: `test/post-write-lint.test.ts:67-130`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: optional `PageValidationContext.sourceId` and `sourceIds`, with `sourceIds` taking precedence.
|
||||
- `runPostWriteLint(..., opts)` accepts the same optional scope and loads the validated page through it.
|
||||
|
||||
- [ ] **Step 1: Add a post-write nested-read regression and verify RED**
|
||||
|
||||
Validate a non-default page with a wrong-source reverse via `runPostWriteLint(..., { force: true, noLog: true, sourceId: 'team-x' })`; require a backlink warning.
|
||||
|
||||
- [ ] **Step 2: Implement minimal scope propagation**
|
||||
|
||||
Add `sourceId?`/`sourceIds?` to validation context and lint options. Load pages using `sourceIds` when non-empty, otherwise scalar `sourceId`. Pass the same scope into nested validators. In the put-page success hook, call lint with the already-resolved write source ID.
|
||||
|
||||
- [ ] **Step 3: Implement exact backlink matching**
|
||||
|
||||
Initial outbound reads use the validation scope. Deduplicate rows by all four endpoint identity fields so every distinct expected origin remains represented even when targets share a source-qualified identity. Read each target using the federated grant when present, otherwise the target's exact scalar source. Accept only a row matching all four endpoint fields of the expected reverse.
|
||||
|
||||
- [ ] **Step 4: Run writer and post-write tests and verify GREEN**
|
||||
|
||||
```bash
|
||||
bun test test/writer.test.ts test/post-write-lint.test.ts > "$TEMP/backlink-green.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: all tests pass, including the recorded false-negative.
|
||||
|
||||
### Task 4: Verify PostgreSQL/PGLite parity and final scope
|
||||
|
||||
**Files:**
|
||||
- Modify: `test/e2e/engine-parity.test.ts:813-875`
|
||||
- Verify: all files above
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: exact endpoint fields and unchanged filtering semantics.
|
||||
- Produces: parity evidence for scalar cross-source and federated reads.
|
||||
|
||||
- [ ] **Step 1: Compare complete endpoint tuples across engines**
|
||||
|
||||
Compare sorted tuples containing `from_source_id`, `from_slug`, `to_source_id`, `to_slug`, `origin_source_id`, and `origin_slug` for scalar and federated fixtures.
|
||||
|
||||
- [ ] **Step 2: Run focused PGLite/source-isolation tests**
|
||||
|
||||
```bash
|
||||
bun test test/writer.test.ts test/post-write-lint.test.ts test/get-page-federated-scope.test.ts test/e2e/multi-source-bug-class.test.ts > "$TEMP/backlink-focused.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: exit 0.
|
||||
|
||||
- [ ] **Step 3: Run PostgreSQL parity when the test database is available**
|
||||
|
||||
```bash
|
||||
bun test test/e2e/engine-parity.test.ts -t "federated sourceIds" --timeout=300000 > "$TEMP/backlink-parity.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: exit 0; if the configured test database is unavailable, report the exact environmental blocker rather than claiming parity execution.
|
||||
|
||||
- [ ] **Step 4: Typecheck and inspect the final diff**
|
||||
|
||||
```bash
|
||||
bun run typecheck > "$TEMP/backlink-typecheck.txt" 2>&1
|
||||
```
|
||||
|
||||
Expected: exit 0. Then run `git diff --check` and confirm no version, schema, migration, deployment, or conditional-write files changed.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Engine dynamic-import reconciliation design
|
||||
|
||||
**Date:** 2026-07-28
|
||||
|
||||
## Goal
|
||||
|
||||
Reconcile the overlapping engine dynamic-import changes from:
|
||||
|
||||
- `claude/hungry-edison-8bb1cd` at release commits `48ada48f` and `248bfe55`
|
||||
- `claude/elegant-gates-e5275e` at `ef4cf7a8`
|
||||
|
||||
onto a fresh branch from current `origin/master`, without merging or cherry-picking either lineage wholesale and without adding a release/version bump.
|
||||
|
||||
## Established state
|
||||
|
||||
At investigation time:
|
||||
|
||||
- `origin/master` was `6136e139972a5449630b4f47f5ed7b4cbe5b811b`, version `0.42.67.0`.
|
||||
- Upstream PR #3511 was still open, so trunk did not contain its two `chronicle/ontology.ts` hoists.
|
||||
- Neither source branch was an ancestor of trunk.
|
||||
- Trunk contained 17 dynamic imports in the three engine-path files:
|
||||
- 13 safe-hoist candidates: two ontology imports, nine engine helper/audit imports, and two migration imports.
|
||||
- Four `ai/gateway.ts` imports, all inside `try/catch` fallback paths.
|
||||
- `git log -G` showed the separate ontology, helper, migration, and gateway histories. `git log -S` is not suitable for this dynamic-to-static replacement because the relevant token can remain present while its context changes.
|
||||
- The guard from `ef4cf7a8` passed against that commit but failed against trunk. It also knew about only two gateway opt-outs because two `_upsertChunksOnce` gateway lookups landed later in trunk.
|
||||
|
||||
## Selected approach
|
||||
|
||||
Reconstruct the intended current state directly on fresh `origin/master`.
|
||||
|
||||
Do not merge or cherry-pick either old lineage. Selectively reproduce the desired source changes, adapt the guard to the current four gateway call sites, and write current-state documentation. This avoids importing stale release metadata, stale TODO claims, and unrelated lineage changes.
|
||||
|
||||
## Source changes
|
||||
|
||||
### Safe static imports
|
||||
|
||||
Hoist all 13 safe candidates:
|
||||
|
||||
- `src/core/pglite-engine.ts`
|
||||
- `valueHash`, `normalizeDimension`, `isNovelDimension` from `chronicle/ontology.ts`
|
||||
- `isRetryableConnError` through the existing `retry.ts` import
|
||||
- `resolveRecencyDecayMap`, `DEFAULT_FALLBACK` from `search/recency-decay.ts`
|
||||
- `src/core/postgres-engine.ts`
|
||||
- the same ontology, retry, and recency helpers
|
||||
- `isConnectionEndedError` from `retry-matcher.ts`
|
||||
- `logDbDisconnect` from `audit/db-disconnect-audit.ts`
|
||||
- `logPoolRecovery` from `audit/pool-recovery-audit.ts`
|
||||
- `src/core/migrate.ts`
|
||||
- `isStatementTimeoutError`, `isRetryableConnError` from `retry-matcher.ts`
|
||||
- `repairTimelineDedupIndex` from `timeline-dedup-repair.ts`
|
||||
|
||||
The implementation must keep the two engines in parity where the behavior is shared. Comments should describe current invariants, not repeat an unproven causal claim that these hoists fix the Windows test-runner crash.
|
||||
|
||||
### Deliberately lazy gateway imports
|
||||
|
||||
Keep all four `await import('./ai/gateway.ts')` call sites lazy:
|
||||
|
||||
- PGLite `initSchema`
|
||||
- PGLite `_upsertChunksOnce`
|
||||
- Postgres `initSchema`
|
||||
- Postgres `_upsertChunksOnce`
|
||||
|
||||
Each line receives the explicit `engine-dynamic-import-ok` marker and a concise nearby rationale.
|
||||
|
||||
The rationale has two parts:
|
||||
|
||||
1. The gateway's static closure includes the AI SDK, provider packages, and validation/config machinery, so eager loading would tax engine startup paths that do not otherwise need it.
|
||||
2. More importantly, each lookup is inside a `try/catch` that preserves a soft fallback (compiled defaults or the brain's stored embedding-model config). Hoisting the module would evaluate it before that catch can run and could convert a recoverable configuration/import failure into a module-load-time hard failure.
|
||||
|
||||
The guard must not allow unmarked gateway imports or a broad file-level exemption.
|
||||
|
||||
## Guard and wiring
|
||||
|
||||
Add `scripts/check-engine-dynamic-import.sh`, adapted from `ef4cf7a8`, with these properties:
|
||||
|
||||
- Default scan set:
|
||||
- `src/core/pglite-engine.ts`
|
||||
- `src/core/postgres-engine.ts`
|
||||
- `src/core/migrate.ts`
|
||||
- Normalize trailing CR before matching so CRLF checkouts cannot bypass the check.
|
||||
- Ignore comment-only lines.
|
||||
- Ignore only lines carrying `engine-dynamic-import-ok`.
|
||||
- Report every unmarked `await import(` with file and line.
|
||||
- Explain that contributors should prefer a static import and must justify a real opt-out.
|
||||
- Avoid asserting that every dynamic import deterministically crashes Windows; the measured evidence supports treating the pattern as an engine-path hardening invariant, while box-level commit exhaustion remained a confound in prior runs.
|
||||
|
||||
Wire it into:
|
||||
|
||||
- `package.json` as `check:engine-dynamic-import`
|
||||
- `package.json` `check:all`
|
||||
- `scripts/run-verify-parallel.sh`
|
||||
|
||||
Follow trunk's current rule that package scripts invoke repository shell scripts through `bash`.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
Add an automated test for the guard. It must cover:
|
||||
|
||||
- A real dynamic import produces exit 1 and is reported.
|
||||
- A line carrying `engine-dynamic-import-ok` is allowed.
|
||||
- Line comments and block-comment lines do not produce findings.
|
||||
- The same violation is caught with CRLF input.
|
||||
- The default repository scan passes after the source reconciliation.
|
||||
|
||||
Use a temporary fixture rather than mutating tracked source files. Keep assertions path-portable.
|
||||
|
||||
The pre-fix red demonstration is the exact guard from `ef4cf7a8` run against current trunk: it exits 1 and reports the existing unmarked imports. The post-fix guard and test must pass.
|
||||
|
||||
## Documentation policy
|
||||
|
||||
Preserve current behavior, not either old release narrative:
|
||||
|
||||
- Do not modify `VERSION` or add a release `CHANGELOG.md` entry.
|
||||
- Do not copy old version headings or completed release TODO blocks.
|
||||
- Do not retain the old TODO claiming that extracting gateway accessors is necessarily the fix; the lazy imports are deliberately protected by their local soft-failure boundaries.
|
||||
- Add the cross-cutting no-unmarked-dynamic-import invariant to `CLAUDE.md`.
|
||||
- Update the current-state entries for `src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and `src/core/migrate.ts` in `docs/architecture/KEY_FILES.md` where needed.
|
||||
- Regenerate `llms.txt` and `llms-full.txt` after the documentation edits.
|
||||
- Add a TODO only if implementation uncovers a real unresolved action.
|
||||
|
||||
Public documentation must use generic language and must not overstate the historical Windows crash causality.
|
||||
|
||||
## Verification
|
||||
|
||||
Capture full output to files before inspecting summaries. Run, at minimum:
|
||||
|
||||
1. The guard regression test.
|
||||
2. `bash scripts/check-engine-dynamic-import.sh`.
|
||||
3. Focused tests that exercise the touched engine, migration, retry, audit, and recency modules.
|
||||
4. `bun run typecheck`.
|
||||
5. `bun run verify`.
|
||||
6. `bun run build:llms` followed by `bun test test/build-llms.test.ts`.
|
||||
7. `git diff --check` and a final clean-status/diff review.
|
||||
|
||||
If platform contention or existing Windows suite defects block a broad test, report the exact command, exit code, and ownership classification rather than declaring success from a partial run.
|
||||
|
||||
## Git and publication boundary
|
||||
|
||||
- Work on `claude/kind-meitner-330c90`, reset locally to the exact investigated `origin/master` base.
|
||||
- Preserve the previous worktree tip under `claude/kind-meitner-330c90-pre-reconcile`.
|
||||
- Keep implementation and verification commits local.
|
||||
- Do not push, create a PR, comment upstream, or otherwise publish without explicit user approval after the local result is complete.
|
||||
@@ -0,0 +1,184 @@
|
||||
# Scalar-source backlink validation design
|
||||
|
||||
## Problem
|
||||
|
||||
A page identity in a multi-source brain is `(source_id, slug)`, but the back-link validator currently reasons only about `slug`.
|
||||
|
||||
For an outbound edge:
|
||||
|
||||
```text
|
||||
(source-a, concepts/origin) -> (source-a, people/target)
|
||||
```
|
||||
|
||||
the validator accepts any reverse row whose bare slugs are:
|
||||
|
||||
```text
|
||||
people/target -> concepts/origin
|
||||
```
|
||||
|
||||
That can incorrectly accept a row ending at `(default, concepts/origin)` instead of `(source-a, concepts/origin)`.
|
||||
|
||||
The bug is not that scalar `getLinks(slug, { sourceId })` permits cross-source destinations. That behavior is intentional: scalar scope qualifies the near/from endpoint while trusted local callers retain visibility into explicit cross-source edges. The gap is that a returned `Link` does not carry the source identity of either endpoint, so callers cannot distinguish same-slug pages.
|
||||
|
||||
## Reproduction and evidence
|
||||
|
||||
A deterministic PGLite reproduction creates duplicate `concepts/a` and `people/b` pages in `default` and `team-x`, then adds:
|
||||
|
||||
```text
|
||||
(team-x, concepts/a) -> (team-x, people/b)
|
||||
(team-x, people/b) -> (default, concepts/a)
|
||||
```
|
||||
|
||||
The second edge is not a valid reverse of the first. Nevertheless:
|
||||
|
||||
```ts
|
||||
await engine.getLinks('people/b', { sourceId: 'team-x' })
|
||||
```
|
||||
|
||||
returns the second row, and the current validator accepts it because `to_slug === 'concepts/a'`.
|
||||
|
||||
Both engines implement the same scalar rule: filter `f.slug` and `f.source_id`, join the actual destination by `to_page_id`, and do not filter `t.source_id`. Federated `sourceIds` is a separate branch that constrains all visible endpoints and takes precedence over scalar scope.
|
||||
|
||||
## Goals
|
||||
|
||||
1. Validate back-links by exact source-qualified endpoint identity.
|
||||
2. Preserve explicit cross-source links for trusted scalar reads.
|
||||
3. Preserve federated all-endpoint containment and `sourceIds` precedence.
|
||||
4. Keep PostgreSQL and PGLite behavior identical.
|
||||
5. Add strict red-before-green regressions using duplicate slugs across sources.
|
||||
6. Avoid schema migrations and production operational changes.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Changing scalar link reads to same-source-only reads.
|
||||
- Weakening or widening federated reads.
|
||||
- Changing link write identity or database schema.
|
||||
- Refactoring the atomic conditional-write branch.
|
||||
- Coupling deployment, restart, or migration mechanics to the backlink code change. Release operations are handled separately after verification.
|
||||
|
||||
## Chosen approach
|
||||
|
||||
Extend the engine `Link` result with endpoint source identities and use those fields in the validator.
|
||||
|
||||
```ts
|
||||
interface Link {
|
||||
from_slug: string;
|
||||
from_source_id: string;
|
||||
to_slug: string;
|
||||
to_source_id: string;
|
||||
// existing fields
|
||||
origin_slug?: string | null;
|
||||
origin_source_id?: string | null;
|
||||
}
|
||||
```
|
||||
|
||||
All `getLinks` and `getBacklinks` query branches in PostgreSQL and PGLite will project the source IDs from the pages already joined as `f`, `t`, and `o`. No filtering behavior changes.
|
||||
|
||||
This approach is preferred over a dedicated `hasExactLink` method because it keeps source identity attached to the link data everywhere, avoids duplicate engine SQL and per-edge existence queries, and matches existing source-qualified link-write and batch-row contracts.
|
||||
|
||||
Validator-only raw SQL is rejected because validators should consume the `BrainEngine` contract rather than bypass it with engine-specific schema knowledge.
|
||||
|
||||
## Engine semantics
|
||||
|
||||
The existing three read modes remain unchanged.
|
||||
|
||||
### Unscoped
|
||||
|
||||
`getLinks(slug)` returns rows from all same-slug from-pages across sources. Each row identifies the actual source of both endpoints.
|
||||
|
||||
### Scalar source
|
||||
|
||||
`getLinks(slug, { sourceId })` matches exactly `(sourceId, slug)` on the from side. A destination may belong to another source, and `to_source_id` reveals that exact identity.
|
||||
|
||||
The corresponding scalar `getBacklinks` rule continues to match the exact destination/to-page identity while allowing a cross-source referrer.
|
||||
|
||||
### Federated sources
|
||||
|
||||
`getLinks(slug, { sourceIds })` continues to constrain from and to endpoints to the grant. The origin join continues to redact an out-of-grant origin. `sourceIds` continues to take precedence over scalar `sourceId`.
|
||||
|
||||
Adding source IDs to returned in-grant endpoints does not disclose anything new: the existing result already discloses those pages' slugs and edges. An out-of-grant endpoint remains absent.
|
||||
|
||||
## Validator algorithm
|
||||
|
||||
The validator receives the source scope associated with the page being validated.
|
||||
|
||||
For every outbound edge:
|
||||
|
||||
```text
|
||||
(from_source_id, from_slug) -> (to_source_id, to_slug)
|
||||
```
|
||||
|
||||
it requires a reverse row:
|
||||
|
||||
```text
|
||||
(to_source_id, to_slug) -> (from_source_id, from_slug)
|
||||
```
|
||||
|
||||
Duplicate edge rows are deduplicated by the full endpoint pair `(from_source_id, from_slug, to_source_id, to_slug)`, not by bare target slug. This preserves separate reverse requirements when multiple same-slug origin pages point to one exact target.
|
||||
|
||||
For each target:
|
||||
|
||||
1. Read target outbound links using the target's exact scalar source when validation is scalar-scoped.
|
||||
2. Under federated validation, retain the caller's `sourceIds` grant rather than converting it to scalar scope.
|
||||
3. Accept only a returned row whose `from_source_id`, `from_slug`, `to_source_id`, and `to_slug` exactly match the expected reverse identity.
|
||||
4. Emit the existing warning when no exact reverse exists.
|
||||
|
||||
This preserves legitimate cross-source pairs. For example:
|
||||
|
||||
```text
|
||||
(source-a, concepts/origin) -> (source-b, people/target)
|
||||
(source-b, people/target) -> (source-a, concepts/origin)
|
||||
```
|
||||
|
||||
is valid.
|
||||
|
||||
## Validation context propagation
|
||||
|
||||
`PageValidationContext` must carry the relevant scalar or federated source scope. The writer and post-write lint paths must load the page with that scope and pass the same scope to nested validator reads.
|
||||
|
||||
This change is scoped to source routing needed by validation. It does not modify conditional-write revision or conflict semantics and must not be applied to the atomic conditional-write branch.
|
||||
|
||||
## Testing strategy
|
||||
|
||||
### PGLite strict-TDD regression
|
||||
|
||||
Add duplicate pages across `default` and a second source, then prove before the production fix that:
|
||||
|
||||
1. A forward edge in the second source plus a wrong-source reverse produces a warning.
|
||||
2. Adding the exact reverse removes the warning.
|
||||
3. A legitimate cross-source forward/reverse pair passes.
|
||||
4. Two same-slug destination pages are not collapsed into one target identity.
|
||||
|
||||
The first assertion must fail against the pre-fix implementation.
|
||||
|
||||
### Engine contract tests
|
||||
|
||||
For PGLite and PostgreSQL:
|
||||
|
||||
1. Assert link rows expose exact from/to source IDs.
|
||||
2. Assert scalar reads still return explicit cross-source destinations.
|
||||
3. Assert federated reads still exclude out-of-grant endpoints.
|
||||
4. Assert `sourceIds` still takes precedence over scalar `sourceId`.
|
||||
5. Assert origin source identity is null when the origin is redacted by the federated branch.
|
||||
|
||||
### Parity and focused verification
|
||||
|
||||
Run:
|
||||
|
||||
- the focused backlink validator test;
|
||||
- source-isolation and federated link tests;
|
||||
- the Postgres/PGLite parity fixture with a test database;
|
||||
- related writer/post-write tests;
|
||||
- `bun run typecheck`.
|
||||
|
||||
Capture complete command output to files before inspecting summaries. Do not use production databases or restart the live service.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The `Link` change is additive at runtime. Existing consumers that read only slug or provenance fields continue to work. TypeScript object literals typed as complete `Link` values may need source fields; if compatibility pressure is high, the source fields can initially be optional in the public type while engine implementations and validator tests require their presence. The preferred contract is required endpoint source IDs because every persisted link always has both pages and therefore both source IDs.
|
||||
|
||||
No schema migration is required because source IDs already live on the joined `pages` rows.
|
||||
|
||||
## Operational constraints
|
||||
|
||||
The implementation phase does not deploy, restart GBrain, run production migrations, or alter the atomic conditional-write branch. Release, migration, and restart operations are a separate verified workflow and do not change this design's engine or validator semantics.
|
||||
@@ -216,6 +216,19 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
|
||||
text, the cast parses it). Guarded by `scripts/check-jsonb-pattern.sh` (template grep) +
|
||||
`scripts/check-jsonb-params.mjs` (positional AST scanner); the real backstop is the DATABASE_URL-gated
|
||||
e2e parity tests, since PGLite can't surface the bug. Full rule in `docs/ENGINES.md`.
|
||||
- **Engine-live paths avoid runtime dynamic `import()` for helper dependencies.** In
|
||||
`src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and
|
||||
`src/core/migrate.ts`, dependencies previously reached through runtime dynamic
|
||||
imports use static top-level imports. The only current dynamic-`import()` exceptions
|
||||
are the four `ai/gateway.ts` lookups in both engines'
|
||||
`initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a
|
||||
local `try/catch` because the gateway has a large provider/config closure and,
|
||||
more importantly, eager evaluation would occur before the catch and could
|
||||
turn a recoverable default/config-row fallback into a module-load failure.
|
||||
Every exception carries `engine-dynamic-import-ok` on the import line.
|
||||
`scripts/check-engine-dynamic-import.sh` enforces the rule. For history, use
|
||||
`git log -G'await[[:space:]]+import\\('`, not `git log -S`: a dynamic-to-static
|
||||
rewrite can preserve the searched token while changing its context.
|
||||
- **Engine parity.** `src/core/postgres-engine.ts` and `src/core/pglite-engine.ts` move in
|
||||
lockstep — a new method/SQL shape lands in BOTH, pinned by `test/e2e/engine-parity.test.ts`.
|
||||
Forward-referenced columns/indexes go in the bootstrap probe set (guarded by
|
||||
@@ -1006,6 +1019,13 @@ If you fetched this file by URL without cloning yet, the companion files live at
|
||||
|
||||
## Step 1: Install GBrain
|
||||
|
||||
> **NEVER install from the npm registry.** GBrain is not distributed on npm; the npm
|
||||
> package named `gbrain` is an unrelated package. Do NOT run `npm install -g gbrain` or
|
||||
> `bun add -g gbrain` (note the missing `github:` prefix — that's the trap). The only
|
||||
> supported sources are `github:garrytan/gbrain` and a git clone, exactly as shown below.
|
||||
> If an unrelated npm install is already present, remove it first
|
||||
> (`npm uninstall -g gbrain` / `bun remove -g gbrain`); `gbrain doctor` also detects this.
|
||||
|
||||
Default path (Bun is required — gbrain is a Bun + TypeScript runtime):
|
||||
|
||||
```bash
|
||||
@@ -1559,6 +1579,16 @@ This is the difference between a search engine and a brain. Search finds the pag
|
||||
|
||||
## Install
|
||||
|
||||
> [!WARNING]
|
||||
> **GBrain is NOT distributed on npm.** The npm package named `gbrain` is an unrelated
|
||||
> package with no connection to this project. Do not run `npm install -g gbrain` or
|
||||
> `bun add -g gbrain` — you'll get something else, and it can shadow the real binary on
|
||||
> your PATH. Install and upgrade ONLY via the documented paths below
|
||||
> (`bun install -g github:garrytan/gbrain`, or `git clone` + `bun install && bun link`).
|
||||
> If you already ran the npm install by mistake: `npm uninstall -g gbrain` /
|
||||
> `bun remove -g gbrain`, then reinstall from GitHub. `gbrain doctor` detects a
|
||||
> shadowing npm install and prints the fix.
|
||||
|
||||
GBrain is designed to be installed and operated by an AI agent. The fastest path is to have your agent do it for you. The CLI and MCP paths below are for people who want to wire it up themselves.
|
||||
|
||||
### Have your agent install it (recommended)
|
||||
|
||||
+3
-2
@@ -48,7 +48,8 @@
|
||||
"check:system-of-record": "bash scripts/check-system-of-record.sh",
|
||||
"check:admin-scope-drift": "bash scripts/check-admin-scope-drift.sh",
|
||||
"check:cli-exec": "bash scripts/check-cli-executable.sh",
|
||||
"check:all": "bash scripts/check-privacy.sh && bash scripts/check-proposal-pii.sh && bash scripts/check-test-real-names.sh && bash scripts/check-jsonb-pattern.sh && bash scripts/check-source-id-projection.sh && bash scripts/check-source-config-leak.sh && bash scripts/check-progress-to-stdout.sh && bash scripts/check-no-tracked-symlinks.sh && bash scripts/check-no-legacy-getconnection.sh && bash scripts/check-test-isolation.sh && bash scripts/check-trailing-newline.sh && bash scripts/check-wasm-embedded.sh && bash scripts/check-exports-count.sh && bash scripts/check-admin-build.sh && bash scripts/check-admin-scope-drift.sh && bash scripts/check-cli-executable.sh && bash scripts/check-skill-brain-first.sh && bash scripts/check-operations-filter-bypass.sh && bash scripts/check-gateway-routed-no-direct-anthropic.sh && bash scripts/check-worker-pool-atomicity.sh && bash scripts/check-key-files-current-state.sh && bash scripts/check-no-double-retry.sh && bash scripts/check-batch-audit-site.sh",
|
||||
"check:engine-dynamic-import": "bash scripts/check-engine-dynamic-import.sh",
|
||||
"check:all": "bash scripts/check-privacy.sh && bash scripts/check-proposal-pii.sh && bash scripts/check-test-real-names.sh && bash scripts/check-jsonb-pattern.sh && bash scripts/check-source-id-projection.sh && bash scripts/check-source-config-leak.sh && bash scripts/check-progress-to-stdout.sh && bash scripts/check-no-tracked-symlinks.sh && bash scripts/check-no-legacy-getconnection.sh && bash scripts/check-test-isolation.sh && bash scripts/check-trailing-newline.sh && bash scripts/check-wasm-embedded.sh && bash scripts/check-exports-count.sh && bash scripts/check-admin-build.sh && bash scripts/check-admin-scope-drift.sh && bash scripts/check-cli-executable.sh && bash scripts/check-skill-brain-first.sh && bash scripts/check-operations-filter-bypass.sh && bash scripts/check-gateway-routed-no-direct-anthropic.sh && bash scripts/check-worker-pool-atomicity.sh && bash scripts/check-key-files-current-state.sh && bash scripts/check-no-double-retry.sh && bash scripts/check-batch-audit-site.sh && bash scripts/check-engine-dynamic-import.sh",
|
||||
"check:gateway-routed": "bash scripts/check-gateway-routed-no-direct-anthropic.sh",
|
||||
"check:worker-pool-atomicity": "bash scripts/check-worker-pool-atomicity.sh",
|
||||
"check:doc-history": "bash scripts/check-key-files-current-state.sh",
|
||||
@@ -146,7 +147,7 @@
|
||||
"bun": ">=1.3.10"
|
||||
},
|
||||
"license": "MIT",
|
||||
"version": "0.42.67.0",
|
||||
"version": "0.42.68.1",
|
||||
"overrides": {
|
||||
"@hono/node-server": "^2.0.5",
|
||||
"fast-uri": "^3.1.4",
|
||||
|
||||
+15
-7
@@ -1,12 +1,12 @@
|
||||
---
|
||||
id: x-to-brain
|
||||
name: X-to-Brain
|
||||
version: 0.8.2
|
||||
version: 0.8.3
|
||||
description: Twitter timeline, mentions, and keyword monitoring flow into brain pages. Tracks deletions, engagement velocity, OCR on images, and real-time alerts.
|
||||
category: sense
|
||||
requires: []
|
||||
secrets:
|
||||
- name: X_BEARER_TOKEN
|
||||
- name: X_API_BEARER_TOKEN
|
||||
description: X API v2 Bearer token (Basic tier minimum, $200/mo for full archive search)
|
||||
where: https://developer.x.com/en/portal/dashboard — create a project + app, copy the Bearer Token from "Keys and tokens"
|
||||
- name: X_HANDLE
|
||||
@@ -16,7 +16,7 @@ health_checks:
|
||||
- type: http
|
||||
url: "https://api.x.com/2/users/by/username/$X_HANDLE"
|
||||
auth: bearer
|
||||
auth_token: "$X_BEARER_TOKEN"
|
||||
auth_token: "$X_API_BEARER_TOKEN"
|
||||
label: "X API"
|
||||
setup_time: 15 min
|
||||
cost_estimate: "$0-200/mo (Free tier: 1 app, read-only. Basic: $200/mo for search + higher limits)"
|
||||
@@ -118,11 +118,11 @@ Tell the user:
|
||||
Note: Free tier gives read-only access with low limits. Basic tier ($200/mo)
|
||||
gives search/recent endpoint and higher limits. Pro tier gets full archive search."
|
||||
|
||||
Set both `X_BEARER_TOKEN` and `X_HANDLE` in the environment. Validate immediately
|
||||
Set both `X_API_BEARER_TOKEN` and `X_HANDLE` in the environment. Validate immediately
|
||||
(app-only bearer tokens cannot call `/users/me` — that endpoint requires
|
||||
user-context OAuth — so validation uses the by-username lookup):
|
||||
```bash
|
||||
curl -sf -H "Authorization: Bearer $X_BEARER_TOKEN" \
|
||||
curl -sf -H "Authorization: Bearer $X_API_BEARER_TOKEN" \
|
||||
"https://api.x.com/2/users/by/username/$X_HANDLE" \
|
||||
&& echo "PASS: X API connected" \
|
||||
|| echo "FAIL: X API token invalid"
|
||||
@@ -138,7 +138,7 @@ starting with 'AAA...', (3) if you just created the app, the token is valid imme
|
||||
|
||||
```bash
|
||||
# Look up the user's X user ID from their handle
|
||||
curl -sf -H "Authorization: Bearer $X_BEARER_TOKEN" \
|
||||
curl -sf -H "Authorization: Bearer $X_API_BEARER_TOKEN" \
|
||||
"https://api.x.com/2/users/by/username/$X_HANDLE" | grep -o '"id":"[^"]*"'
|
||||
```
|
||||
|
||||
@@ -210,7 +210,7 @@ The agent should review collected data 2-3x daily and run enrichment.
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.gbrain/integrations/x-to-brain
|
||||
echo '{"ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","event":"setup_complete","source_version":"0.8.2","status":"ok","details":{"user_id":"X_USER_ID"}}' >> ~/.gbrain/integrations/x-to-brain/heartbeat.jsonl
|
||||
echo '{"ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","event":"setup_complete","source_version":"0.8.3","status":"ok","details":{"user_id":"X_USER_ID"}}' >> ~/.gbrain/integrations/x-to-brain/heartbeat.jsonl
|
||||
```
|
||||
|
||||
## Production Patterns (v0.8.1)
|
||||
@@ -438,6 +438,14 @@ Free tier works for personal monitoring. Basic tier needed for keyword search.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Upgrading from recipe v0.8.2 or earlier (token shows [missing] after upgrade):**
|
||||
- Older versions of this recipe named the token `X_BEARER_TOKEN`. The canonical
|
||||
name is `X_API_BEARER_TOKEN` — the name the built-in `x_handle_to_tweet`
|
||||
resolver reads. Rename the variable wherever you set it (shell profile, cron
|
||||
environment, `.env`) — same value, new name. A collector installed under the
|
||||
old name keeps running either way; the rename is what makes the integrations
|
||||
dashboard and the resolver see the token.
|
||||
|
||||
**API returns 403:**
|
||||
- Check your app has the right access level (Read or Read+Write)
|
||||
- Free tier apps can only use basic endpoints
|
||||
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# CI guard: every `bun test` invocation in workflows and runner scripts must
|
||||
# pass an explicit --timeout.
|
||||
#
|
||||
# Why: bun ignores bunfig.toml's `timeout` key (verified on 1.3.14), so a bare
|
||||
# `bun test` gets the 5000ms default for BOTH tests and beforeAll/beforeEach/
|
||||
# afterAll/afterEach hooks. Hooks do NOT inherit a test's third-arg timeout —
|
||||
# a file whose tests all declare `}, 30_000)` still has a 5s hook budget, and
|
||||
# slow setup (Postgres connect + migrations, PGLite cold start) flakes on
|
||||
# loaded CI runners with the signature `(unnamed) [5001ms] ... hook timed out`
|
||||
# (the #3545 jsonb-parity failure). The CLI --timeout flag is the one measured
|
||||
# mechanism that raises the hook budget uniformly; per-hook second-arg
|
||||
# timeouts work too but don't scale to ~400 slow hooks.
|
||||
#
|
||||
# Usage: scripts/check-bun-test-timeout.sh
|
||||
# Exit: 0 when clean, 1 when a bare `bun test` invocation is found.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
# Match executable `bun test` invocations. Exclude comment lines (#, //, *)
|
||||
# and lines that already carry --timeout anywhere.
|
||||
# Scope: workflows + runner scripts (the surfaces CI executes). package.json
|
||||
# script bodies route through scripts/ already; editing it is out of scope here.
|
||||
violations="$(grep -rnE '\bbun test\b' .github/workflows scripts 2>/dev/null \
|
||||
| grep -v -- '--timeout' \
|
||||
| grep -vE ':[[:space:]]*(#|//|\*)' \
|
||||
| grep -v 'check-bun-test-timeout' \
|
||||
|| true)"
|
||||
|
||||
if [ -n "$violations" ]; then
|
||||
echo "FAIL: bare 'bun test' without --timeout (5s default kills slow setup hooks):" >&2
|
||||
echo "$violations" >&2
|
||||
echo "" >&2
|
||||
echo "Add --timeout=60000 (see scripts/run-unit-shard.sh for the convention)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "OK: every bun test invocation passes an explicit --timeout."
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# Engine-live paths use static imports by default. A line-level
|
||||
# `engine-dynamic-import-ok` marker is required for a justified lazy import.
|
||||
#
|
||||
# Historical Windows runs associated imports on these paths with abrupt Bun
|
||||
# test-process exits, but system-wide commit exhaustion remained a confound.
|
||||
# This guard therefore enforces a reviewed engine-path hardening invariant; it
|
||||
# does not claim every dynamic import deterministically crashes Windows.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/check-engine-dynamic-import.sh
|
||||
# bash scripts/check-engine-dynamic-import.sh FILE [FILE...]
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" || exit 1
|
||||
|
||||
if [ "$#" -gt 0 ]; then
|
||||
FILES=("$@")
|
||||
else
|
||||
ROOT="$(git -C "$SCRIPT_DIR/.." rev-parse --show-toplevel 2>/dev/null || true)"
|
||||
[ -n "$ROOT" ] || ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$ROOT" || exit 1
|
||||
FILES=(
|
||||
src/core/pglite-engine.ts
|
||||
src/core/postgres-engine.ts
|
||||
src/core/migrate.ts
|
||||
)
|
||||
fi
|
||||
|
||||
exec bun "$SCRIPT_DIR/check-engine-dynamic-import.ts" "${FILES[@]}"
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import ts from 'typescript';
|
||||
|
||||
const MARKER = 'engine-dynamic-import-ok';
|
||||
const MARKER_TOKEN_CHAR = /[\p{ID_Continue}$-]/u;
|
||||
const files = process.argv.slice(2);
|
||||
const violations: string[] = [];
|
||||
const readErrors: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
let sourceText: string;
|
||||
try {
|
||||
sourceText = await readFile(file, 'utf8');
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
readErrors.push(`ERROR: cannot read input file ${file}: ${detail}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const sourceFile = ts.createSourceFile(
|
||||
file,
|
||||
sourceText,
|
||||
ts.ScriptTarget.Latest,
|
||||
true,
|
||||
ts.ScriptKind.TS,
|
||||
);
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const markerLines = new Set<number>();
|
||||
|
||||
if (sourceFile.parseDiagnostics.length > 0) {
|
||||
const diagnostics = sourceFile.parseDiagnostics
|
||||
.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '))
|
||||
.join('; ');
|
||||
readErrors.push(`ERROR: cannot parse input file ${file}: ${diagnostics}`);
|
||||
}
|
||||
|
||||
for (let markerPos = sourceText.indexOf(MARKER); markerPos >= 0; markerPos = sourceText.indexOf(MARKER, markerPos + MARKER.length)) {
|
||||
const before = Array.from(sourceText.slice(0, markerPos)).at(-1);
|
||||
const after = Array.from(sourceText.slice(markerPos + MARKER.length))[0];
|
||||
const standaloneMarker = (!before || !MARKER_TOKEN_CHAR.test(before))
|
||||
&& (!after || !MARKER_TOKEN_CHAR.test(after));
|
||||
const token = ts.getTokenAtPosition(sourceFile, markerPos);
|
||||
const insideToken = token.getStart(sourceFile) <= markerPos && markerPos < token.end;
|
||||
if (standaloneMarker && !insideToken) {
|
||||
markerLines.add(sourceFile.getLineAndCharacterOfPosition(markerPos).line);
|
||||
}
|
||||
}
|
||||
|
||||
function visit(node: ts.Node): void {
|
||||
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
||||
const { line } = sourceFile.getLineAndCharacterOfPosition(node.expression.getStart(sourceFile));
|
||||
const sourceLine = lines[line] ?? '';
|
||||
if (!markerLines.has(line)) {
|
||||
violations.push(` ${file}:${line + 1}:${sourceLine}`);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
|
||||
visit(sourceFile);
|
||||
}
|
||||
|
||||
for (const error of readErrors) console.error(error);
|
||||
|
||||
if (violations.length > 0) {
|
||||
console.error('ERROR: unreviewed dynamic import on an engine-live path:');
|
||||
console.error();
|
||||
console.error(violations.join('\n'));
|
||||
console.error();
|
||||
console.error('Prefer a static top-level import. If lazy loading is load-bearing,');
|
||||
console.error("append 'engine-dynamic-import-ok' to that exact line and document");
|
||||
console.error('the startup or soft-failure boundary that requires it.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (readErrors.length > 0) process.exit(1);
|
||||
|
||||
console.log(`check-engine-dynamic-import: ok (${files.length} file(s) scanned)`);
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Import an envelope-v0 file (a JSON serialization of AI chat history; format
|
||||
* spec: github.com/memvelope/memvelope) into a brain repo as one Markdown page
|
||||
* per conversation, which `gbrain sync` ingests.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/envelope-to-gbrain.mjs <envelope.mve.json> [outDir]
|
||||
*
|
||||
* Zero dependencies. Deterministic. No network. It does NOT call gbrain — it
|
||||
* only writes Markdown files.
|
||||
*
|
||||
* Output layout:
|
||||
* - One page per conversation, filename = date + conversation id (shared
|
||||
* titles cannot collide; the id is the natural key). A duplicate id
|
||||
* overwrites its own filename and warns on stderr; stdout reports DISTINCT
|
||||
* files written, not write calls.
|
||||
* - Frontmatter: `type: conversation` (keeps pages eligible for
|
||||
* conversation-facts extraction and chronicle behavior after sync), the
|
||||
* source provider, the conversation id, and `origin: memvelope/envelope-v0`.
|
||||
* - Page `date` is the first 10 chars of the conversation's ISO-8601
|
||||
* `created_at`. Body keeps message-id citations beside each speaker turn.
|
||||
*
|
||||
* Memory: the whole envelope is held in memory (no streaming); envelopes are
|
||||
* far smaller than the vendor exports they serialize.
|
||||
*
|
||||
* Verify:
|
||||
* node scripts/envelope-to-gbrain.mjs test/fixtures/memvelope/sample.mve.json /tmp/out
|
||||
* -> expect "wrote 1 markdown page(s)"
|
||||
* bun test test/envelope-to-gbrain.test.ts
|
||||
*
|
||||
* STATUS: live-verified against gbrain v0.42.56.0 on 2026-07-03: the sample
|
||||
* fixture -> 1 page; a real 662MB Claude export -> 353 conversations = 353
|
||||
* distinct pages (no collisions), searchable after sync with provenance and
|
||||
* message-id citations intact.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const [, , envelopePath, outDir = './brain/conversations'] = process.argv;
|
||||
if (!envelopePath) {
|
||||
console.error('usage: node envelope-to-gbrain.mjs <envelope.mve.json> [outDir]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const env = JSON.parse(readFileSync(envelopePath, 'utf8'));
|
||||
if (env.memvelope !== 'envelope-v0') {
|
||||
console.error(`not an envelope-v0 file (memvelope field = ${JSON.stringify(env.memvelope)})`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const slug = (s, fallback) =>
|
||||
(String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || fallback).slice(0, 60);
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const filesWritten = new Set();
|
||||
let collisions = 0;
|
||||
const conversations = env.conversations || [];
|
||||
for (const [i, c] of conversations.entries()) {
|
||||
const date = (c.created_at || '').slice(0, 10);
|
||||
// Name the file by the conversation's own id — the natural unique key — so two
|
||||
// conversations that share a date and title can never silently overwrite each
|
||||
// other. The date only leads as a human/chronological sort prefix; the id
|
||||
// carries uniqueness. Positional fallback keeps names unique and deterministic
|
||||
// when an envelope omits an id.
|
||||
// One predicate for "this conversation carries its own id", shared by the
|
||||
// filename and the frontmatter below. Keeping it in a single place is what
|
||||
// stops the two from disagreeing about whether an id exists.
|
||||
const hasId = typeof c.id === 'string' && c.id.trim() !== '';
|
||||
const convId = hasId ? c.id.trim() : `conv-${i + 1}`;
|
||||
const name = `${date || '0000-00-00'}-${slug(convId, `conv-${i + 1}`)}.md`;
|
||||
// gbrain reads YAML frontmatter + markdown body; keep provenance in frontmatter.
|
||||
// Emit `type: conversation` so gbrain stores these as conversation pages rather
|
||||
// than defaulting to the generic `concept`. gbrain is open-typed — it takes an
|
||||
// explicit frontmatter `type` verbatim — and its conversation-aware features
|
||||
// (conversation-facts extraction, the conversation_format_coverage check,
|
||||
// chronicle eligibility) key off `type == 'conversation'`.
|
||||
const front = [
|
||||
'---',
|
||||
'type: conversation',
|
||||
`title: ${JSON.stringify(c.title || 'Untitled conversation')}`,
|
||||
`date: ${date || 'null'}`,
|
||||
// Every interpolated value is quoted. An envelope is a third-party file, so
|
||||
// a provider string carrying a newline would otherwise close this scalar and
|
||||
// inject arbitrary frontmatter keys into the page gbrain ingests.
|
||||
`source: ${JSON.stringify(env.meta?.source_provider || 'unknown')}`,
|
||||
// Omit the key entirely when the envelope carries no id, rather than
|
||||
// emitting the literal `undefined` or a synthesized `conv-N` — the positional
|
||||
// fallback names the file, but it is not a memvelope conversation id and
|
||||
// must not be recorded as one.
|
||||
...(hasId ? [`memvelope_conversation_id: ${JSON.stringify(convId)}`] : []),
|
||||
'origin: memvelope/envelope-v0',
|
||||
'---',
|
||||
'',
|
||||
].join('\n');
|
||||
const body = (c.messages || [])
|
||||
.map((m) => `**${m.role === 'user' ? 'Me' : 'Assistant'}** (${m.ts || 'no timestamp'} · ${m.id}):\n\n${m.text}`)
|
||||
.join('\n\n---\n\n');
|
||||
// Never lose a page silently: if two conversations still map to the same
|
||||
// filename (e.g. an envelope carrying duplicate ids), warn loudly instead of
|
||||
// overwriting in silence, and report the count of DISTINCT files written — not
|
||||
// the number of write calls, which is what hid the old title-collision bug.
|
||||
if (filesWritten.has(name)) {
|
||||
collisions += 1;
|
||||
console.warn(`warning: filename collision on "${name}" — conversation id ${JSON.stringify(c.id)} is not unique; overwriting the earlier page.`);
|
||||
}
|
||||
writeFileSync(join(outDir, name), front + `# ${c.title || 'Conversation'}\n\n` + body + '\n');
|
||||
filesWritten.add(name);
|
||||
}
|
||||
console.log(`wrote ${filesWritten.size} markdown page(s) to ${outDir} — point gbrain's sync at this directory.`);
|
||||
if (collisions) {
|
||||
console.warn(`warning: ${collisions} filename collision(s) — ${collisions} page(s) overwritten. Deduplicate conversation ids in the envelope to avoid data loss.`);
|
||||
}
|
||||
+3
-2
@@ -162,8 +162,9 @@ for f in "${files[@]}"; do
|
||||
if [ -n "${DATABASE_URL:-}" ]; then
|
||||
psql "$DATABASE_URL" -At -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid != pg_backend_pid() AND datname = current_database()" >/dev/null 2>&1 || true
|
||||
fi
|
||||
# Hard outer timeout (180s per file). bun's --timeout is per-test; if a
|
||||
# PGLite WASM call hangs in beforeAll/afterAll, --timeout never fires and
|
||||
# Hard outer timeout (180s per file). bun's --timeout covers tests AND
|
||||
# hooks (measured on 1.3.14), but it's timer-based: a PGLite WASM call
|
||||
# that blocks the event loop synchronously never lets the timer fire and
|
||||
# the file wedges indefinitely. gtimeout/timeout SIGKILLs the file so the
|
||||
# suite advances. gtimeout (macOS via coreutils) preferred; timeout (Linux)
|
||||
# fallback; bare bun (no outer cap) if neither is installed.
|
||||
|
||||
@@ -64,6 +64,7 @@ CHECKS=(
|
||||
"check:source-scope-onboard"
|
||||
"check:no-double-retry"
|
||||
"check:batch-audit-site"
|
||||
"check:engine-dynamic-import"
|
||||
"check:worker-lock-renewal-shape"
|
||||
"typecheck"
|
||||
)
|
||||
|
||||
@@ -139,9 +139,9 @@ edits writes a new receipt).
|
||||
|
||||
| Slot | Default | Provider |
|
||||
|------|---------|----------|
|
||||
| A | `openai:gpt-4o` | OpenAI |
|
||||
| A | `openai:gpt-5.2` | OpenAI |
|
||||
| B | `anthropic:claude-opus-4-7` | Anthropic |
|
||||
| C | `google:gemini-1.5-pro` | Google |
|
||||
| C | `deepseek:deepseek-v4-pro` | DeepSeek |
|
||||
|
||||
**These MUST be frontier models from DIFFERENT providers.** Using a single
|
||||
provider's family or budget models defeats the purpose — different families
|
||||
|
||||
+144
-23
@@ -9,7 +9,7 @@ installSigchldHandler();
|
||||
import { installSignalHandlers as installCleanupSignalHandlers } from './core/process-cleanup.ts';
|
||||
installCleanupSignalHandlers();
|
||||
|
||||
import { readFileSync, existsSync, unlinkSync } from 'fs';
|
||||
import { readFileSync, existsSync, unlinkSync, fstatSync } from 'fs';
|
||||
import { spawn } from 'child_process';
|
||||
import {
|
||||
readUpdateCache,
|
||||
@@ -55,7 +55,7 @@ export function bigintToStringReplacer(_key: string, value: unknown): unknown {
|
||||
}
|
||||
|
||||
// CLI-only commands that bypass the operation layer
|
||||
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector']);
|
||||
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector', 'backfill']);
|
||||
// CLI-only commands whose handlers print their own --help text. These are
|
||||
// excluded from the generic short-circuit so detailed per-command and
|
||||
// per-subcommand usage stays reachable.
|
||||
@@ -344,6 +344,11 @@ async function main() {
|
||||
// them out of the engine try/catch is safe and unlocks routing.
|
||||
const params = parseOpArgs(op, subArgs);
|
||||
|
||||
// #3513: stdin fill moved out of parseOpArgs so a non-TTY stdin with no
|
||||
// piped input can't block the parse forever — the bounded read leaves the
|
||||
// param unset on timeout and the required-param check below fails fast.
|
||||
await applyStdinParam(op, params);
|
||||
|
||||
// v0.27.1 (`gbrain query --image <path>`): swap the `image` param from
|
||||
// a filesystem path into base64 bytes + mime. The op accepts base64; the
|
||||
// CLI accepts a path. Helper is exported so tests can exercise the
|
||||
@@ -804,18 +809,99 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
}
|
||||
}
|
||||
|
||||
// Read stdin for content params
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* #3513: read stdin into an op's stdin-capable param without ever blocking
|
||||
* forever. The old inline `readFileSync(0)` in parseOpArgs assumed non-TTY
|
||||
* implies piped content; a non-TTY stdin with NO input (CI step, cron job,
|
||||
* agent harness holding an unwritten pipe open) blocked the read until kill.
|
||||
*
|
||||
* Strategy by fd kind (fstat):
|
||||
* - TTY: skip, as before (interactive input is not an op-param source).
|
||||
* - regular file / /dev/null / anything not a pipe or socket: readFileSync
|
||||
* returns without blocking (`gbrain put x < file`, `< /dev/null` → '').
|
||||
* - FIFO/socket: stream-read with a deadline on the FIRST byte only. A real
|
||||
* pipe (`echo foo | gbrain put x`, heredocs) delivers its first byte
|
||||
* within milliseconds; once any data arrives the deadline is lifted and
|
||||
* we read to EOF like readFileSync did (slow producers stay supported).
|
||||
* An empty-but-closed pipe (`: | gbrain put x`) EOFs immediately → ''.
|
||||
* A pipe that never delivers a byte times out → param stays unset, so
|
||||
* the existing required-param usage error fires (fail fast, exit 1).
|
||||
*
|
||||
* GBRAIN_STDIN_TIMEOUT_MS overrides the first-byte deadline (default 5000).
|
||||
* Exported for tests; called by the op dispatch right after parseOpArgs.
|
||||
*/
|
||||
export async function applyStdinParam(
|
||||
op: Operation,
|
||||
params: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
// Branch shape (stdin hint + missing param + `!process.stdin.isTTY` gate +
|
||||
// 5MB cap) is pinned by the R4 regression test for PR #1325's Windows fix
|
||||
// (test/cycle/regression-pr-wave-r1-r2-r4.test.ts) — keep the spelling.
|
||||
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
|
||||
const stdinContent = readFileSync(0, 'utf-8');
|
||||
const content = await readStdinBounded();
|
||||
if (content === null) return; // no input arrived — let the required-param check fail fast
|
||||
const MAX_STDIN = 5_000_000; // 5MB
|
||||
if (Buffer.byteLength(stdinContent, 'utf-8') > MAX_STDIN) {
|
||||
if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
|
||||
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[op.cliHints.stdin] = stdinContent;
|
||||
params[op.cliHints.stdin] = content;
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
/** First-byte deadline for pipe/socket stdin (#3513). Env-overridable escape hatch. */
|
||||
function stdinFirstByteTimeoutMs(): number {
|
||||
const n = Number(process.env.GBRAIN_STDIN_TIMEOUT_MS);
|
||||
return Number.isFinite(n) && n > 0 ? n : 5000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full stdin content, '' for a readable-but-empty stdin, or
|
||||
* null when stdin is a pipe/socket that never delivered a byte within the
|
||||
* first-byte deadline (or the fd is closed/unreadable).
|
||||
*/
|
||||
export async function readStdinBounded(): Promise<string | null> {
|
||||
let isPipeOrSocket: boolean;
|
||||
try {
|
||||
const st = fstatSync(0);
|
||||
isPipeOrSocket = st.isFIFO() || st.isSocket();
|
||||
} catch {
|
||||
return null; // closed/invalid fd — treat as no input
|
||||
}
|
||||
if (!isPipeOrSocket) {
|
||||
// Regular file redirect, /dev/null, etc. — read returns without blocking.
|
||||
try {
|
||||
return readFileSync(0, 'utf-8');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return await new Promise<string | null>((resolve) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let gotData = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (!gotData) {
|
||||
process.stdin.destroy();
|
||||
resolve(null);
|
||||
}
|
||||
}, stdinFirstByteTimeoutMs());
|
||||
const finish = () => {
|
||||
clearTimeout(timer);
|
||||
resolve(Buffer.concat(chunks).toString('utf-8'));
|
||||
};
|
||||
process.stdin.on('data', (c: Buffer) => {
|
||||
if (!gotData) {
|
||||
gotData = true;
|
||||
clearTimeout(timer); // deadline applies to the FIRST byte only
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
process.stdin.once('end', finish);
|
||||
process.stdin.once('error', finish);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -872,7 +958,8 @@ export function applyThinClientSourceScope(
|
||||
params.source_id = resolved;
|
||||
}
|
||||
|
||||
async function makeContext(engine: BrainEngine, params: Record<string, unknown>): Promise<OperationContext> {
|
||||
// Exported for tests (same import-safety contract as applyThinClientSourceScope).
|
||||
export async function makeContext(engine: BrainEngine, params: Record<string, unknown>): Promise<OperationContext> {
|
||||
// v0.31.8 (D11): resolve sourceId via the canonical 6-tier chain. Honors
|
||||
// --source / GBRAIN_SOURCE / .gbrain-source / path-match / brain default /
|
||||
// 'default'. Wrapped in try/catch so a doctor / single-source brain that
|
||||
@@ -884,16 +971,21 @@ async function makeContext(engine: BrainEngine, params: Record<string, unknown>)
|
||||
// trusted local boundary) and consumed by federatedSearchScope in
|
||||
// operations.ts, which additionally gates on ctx.remote === false.
|
||||
let localFederated: string[] | undefined;
|
||||
// params.source is set when a CLI flag was parsed for the op (rare; most
|
||||
// CLI ops don't take --source). Falls through to env/dotfile/path-match.
|
||||
const explicit = (params.source as string | undefined) ?? null;
|
||||
try {
|
||||
const { resolveSourceWithTier, localFederatedSourceIds } = await import('./core/source-resolver.ts');
|
||||
// params.source is set when a CLI flag was parsed for the op (rare; most
|
||||
// CLI ops don't take --source). Falls through to env/dotfile/path-match.
|
||||
const explicit = (params.source as string | undefined) ?? null;
|
||||
const resolved = await resolveSourceWithTier(engine, explicit);
|
||||
sourceId = resolved.source_id;
|
||||
localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
|
||||
} catch {
|
||||
// Source resolution failed (e.g. sources table doesn't exist on a fresh
|
||||
} catch (err) {
|
||||
// #1712: an EXPLICIT --source that fails to resolve (invalid id, or a
|
||||
// source that doesn't exist) must error loudly — the blanket swallow
|
||||
// turned `--source __all__` and typos into a silent `default` scope,
|
||||
// which is how three bug reports became debugging sessions.
|
||||
if (explicit) throw err;
|
||||
// Ambient resolution failed (e.g. sources table doesn't exist on a fresh
|
||||
// pre-init brain). Leave sourceId unset; engine read methods fall through
|
||||
// to the cross-source view (D16 back-compat path).
|
||||
sourceId = undefined;
|
||||
@@ -1615,14 +1707,12 @@ async function handleCliOnly(command: string, args: string[]) {
|
||||
// Per-command default: search 30s, sources list 10s. User --timeout=Ns wins.
|
||||
// Other commands (import, embed, doctor, etc.) keep their existing
|
||||
// unbounded connect — destructive / long-running commands shouldn't get
|
||||
// a default kill switch.
|
||||
const readOnlyDefaultTimeoutMs =
|
||||
command === 'search' ? 30_000 :
|
||||
command === 'sources' && (args[0] === 'list' || args[0] === undefined) ? 10_000 :
|
||||
null;
|
||||
// a default kill switch. The gate below is per-command (#3013): only the
|
||||
// commands dispatchReadOnlyCommand handles may enter this path — a
|
||||
// user-supplied --timeout on a write command must never reroute it here.
|
||||
const cliOptsResolved = getCliOptions();
|
||||
const userTimeoutMs = cliOptsResolved.timeoutMs;
|
||||
const readOnlyTimeoutMs = userTimeoutMs ?? readOnlyDefaultTimeoutMs;
|
||||
const readOnlyTimeoutMs = resolveReadOnlyDispatchTimeoutMs(command, args, userTimeoutMs);
|
||||
|
||||
if (readOnlyTimeoutMs !== null) {
|
||||
const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
|
||||
@@ -2161,16 +2251,24 @@ async function handleCliOnly(command: string, args: string[]) {
|
||||
//
|
||||
// v0.30.1: still works; canonical entrypoint is now `gbrain backfill
|
||||
// effective_date`. This command stays as a thin alias for back-compat.
|
||||
//
|
||||
// #1963: pass the already-connected engine. The command used to build
|
||||
// + connect its OWN engine here, which self-deadlocked on the PGLite
|
||||
// data-dir lock (this process already holds it via connectEngine
|
||||
// above) — 30s spin, then exit 1, on every PGLite invocation.
|
||||
const { reindexFrontmatterCli } = await import('./commands/reindex-frontmatter.ts');
|
||||
await reindexFrontmatterCli(args);
|
||||
return; // reindexFrontmatterCli handles its own engine lifecycle
|
||||
await reindexFrontmatterCli(engine, args);
|
||||
break;
|
||||
}
|
||||
case 'backfill': {
|
||||
// v0.30.1: first-class generic backfill command. Subcommand dispatch
|
||||
// is inside runBackfillCommand (kind | list | --help).
|
||||
// #1963: same double-connect class as reindex-frontmatter — reuse the
|
||||
// connected engine instead of building a second one on the same
|
||||
// PGLite data dir.
|
||||
const { runBackfillCommand } = await import('./commands/backfill.ts');
|
||||
await runBackfillCommand(args);
|
||||
return;
|
||||
await runBackfillCommand(engine, args);
|
||||
break;
|
||||
}
|
||||
case 'code-callers': {
|
||||
// v0.20.0 Cathedral II Layer 10 (C4): "who calls <symbol>?"
|
||||
@@ -2213,6 +2311,28 @@ async function handleCliOnly(command: string, args: string[]) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #3013: decide whether an invocation enters the read-only connect+dispatch
|
||||
* timeout path, and with what wallclock. Returns null for every command
|
||||
* dispatchReadOnlyCommand can't handle. The gate used to be "a timeout is
|
||||
* present" — so a user-supplied --timeout on a write command (`sync`,
|
||||
* `embed`, `import`, ...) hijacked dispatch into the read-only path, which
|
||||
* threw and exited 1 before any work ran. Pure; exported for the
|
||||
* regression test.
|
||||
*/
|
||||
export function resolveReadOnlyDispatchTimeoutMs(
|
||||
command: string,
|
||||
subArgs: string[],
|
||||
userTimeoutMs: number | null,
|
||||
): number | null {
|
||||
if (command !== 'search' && command !== 'sources') return null;
|
||||
const defaultMs =
|
||||
command === 'search' ? 30_000 :
|
||||
(subArgs[0] === 'list' || subArgs[0] === undefined) ? 10_000 :
|
||||
null;
|
||||
return userTimeoutMs ?? defaultMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.41.6.0 D3: dispatch helper for the read-only commands that take a
|
||||
* default wallclock timeout (`gbrain search`, `gbrain sources list`).
|
||||
@@ -2448,6 +2568,7 @@ TOOLS
|
||||
publish <page.md> [--password] Shareable HTML (strips private data, optional AES-256)
|
||||
check-backlinks <check|fix> [dir] Find/fix missing back-links across brain
|
||||
lint <dir|file> [--fix] Catch LLM artifacts, placeholder dates, bad frontmatter
|
||||
backfill <kind|list> v0.30.1: run a registered backfill (effective-date, ...)
|
||||
orphans [--json] [--count] Find pages with no inbound wikilinks
|
||||
salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience
|
||||
anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)
|
||||
|
||||
@@ -1,9 +1,42 @@
|
||||
import { defaultTimeoutMsFor } from '../core/minions/handler-timeouts.ts';
|
||||
|
||||
// #2781: the full-cycle floor used to be a literal `1_800_000` that merely
|
||||
// HAPPENED to match the 'autopilot-cycle' / 'autopilot-global-maintenance'
|
||||
// handler anchors (`HANDLER_DEFAULT_TIMEOUT_MS`, #1737) instead of being
|
||||
// derived from them. A duplicated literal can silently drift from the
|
||||
// handler default it's supposed to track — which is exactly the bug class
|
||||
// #2781 reported (an explicit `timeout_ms` stamp permanently overrides the
|
||||
// handler default per `queue.ts`'s `opts?.timeout_ms ?? defaultTimeoutMsFor`,
|
||||
// so a stale/lower literal here would starve a phase the handler default
|
||||
// was sized for). Deriving the floor from `defaultTimeoutMsFor` for both
|
||||
// full-cycle job names keeps the stamp coupled to its anchor by construction.
|
||||
// Fail fast (not `?? 0`) if either handler ever loses its entry in
|
||||
// HANDLER_DEFAULT_TIMEOUT_MS — silently falling back to "no floor" would
|
||||
// reintroduce #2781 rather than surface the drift.
|
||||
function requireHandlerAnchorMs(jobName: string): number {
|
||||
const ms = defaultTimeoutMsFor(jobName);
|
||||
if (ms === null) {
|
||||
throw new Error(
|
||||
`resolveAutopilotDispatchTimeoutMs: '${jobName}' has no entry in HANDLER_DEFAULT_TIMEOUT_MS ` +
|
||||
'(handler-timeouts.ts) — the full-cycle timeout floor can no longer be derived from it. ' +
|
||||
'See #2781: a missing/removed anchor here silently reintroduces the interval-derived stamp ' +
|
||||
'permanently overriding the handler default.',
|
||||
);
|
||||
}
|
||||
return ms;
|
||||
}
|
||||
|
||||
const FULL_CYCLE_TIMEOUT_FLOOR_MS = Math.max(
|
||||
requireHandlerAnchorMs('autopilot-cycle'),
|
||||
requireHandlerAnchorMs('autopilot-global-maintenance'),
|
||||
);
|
||||
|
||||
export function resolveAutopilotDispatchTimeoutMs(
|
||||
baseIntervalSeconds: number,
|
||||
fullCycle: boolean,
|
||||
): number {
|
||||
const intervalDerivedTimeoutMs = Math.max(baseIntervalSeconds * 2 * 1000, 300_000);
|
||||
return fullCycle
|
||||
? Math.max(intervalDerivedTimeoutMs, 1_800_000)
|
||||
? Math.max(intervalDerivedTimeoutMs, FULL_CYCLE_TIMEOUT_FLOOR_MS)
|
||||
: intervalDerivedTimeoutMs;
|
||||
}
|
||||
|
||||
@@ -981,12 +981,21 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
// can't shrink throughput (codex #9/D5). autopilot-cycle jobs run on
|
||||
// the 'default' queue, so that's the concurrency we compare against.
|
||||
const fanoutMax = await resolveEffectiveFanoutMax(engine, 'default');
|
||||
// #2781: both 'autopilot-cycle' (per-source) and 'autopilot-global-
|
||||
// maintenance' carry a 30-min handler anchor (handler-timeouts.ts)
|
||||
// because a full cycle can outlive short daemon intervals — unlike
|
||||
// the lighter interval-derived `timeoutMs` above (sync/freshness,
|
||||
// extract-atoms-drain, targeted small-plan steps), which have no
|
||||
// such anchor and are meant to stay interval-derived. Naming this
|
||||
// separately (rather than reusing the outer `timeoutMs`) avoids
|
||||
// the #2781 bug class: dispatchGlobalMaintenance previously reused
|
||||
// the outer non-full-cycle `timeoutMs` by shorthand, silently
|
||||
// dropping its own handler anchor.
|
||||
const fullCycleTimeoutMs = resolveAutopilotDispatchTimeoutMs(baseInterval, true);
|
||||
const result = await dispatchPerSource(engine, queue, {
|
||||
repoPath,
|
||||
slot,
|
||||
// Full cycles can outlive short daemon intervals. Keep lighter dispatches
|
||||
// interval-derived while giving per-source consolidation enough time.
|
||||
timeoutMs: resolveAutopilotDispatchTimeoutMs(baseInterval, true),
|
||||
timeoutMs: fullCycleTimeoutMs,
|
||||
fanoutMax,
|
||||
jsonMode,
|
||||
});
|
||||
@@ -997,7 +1006,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
// the per-source path (legacy single-source still runs everything).
|
||||
if (!result.legacy_fallback) {
|
||||
try {
|
||||
await dispatchGlobalMaintenance(engine, queue, { repoPath, slot, timeoutMs, jsonMode });
|
||||
await dispatchGlobalMaintenance(engine, queue, { repoPath, slot, timeoutMs: fullCycleTimeoutMs, jsonMode });
|
||||
} catch (e) {
|
||||
if (jsonMode) process.stderr.write(JSON.stringify({ event: 'global_maintenance_dispatch_failed', error: e instanceof Error ? e.message : String(e) }) + '\n');
|
||||
}
|
||||
|
||||
@@ -16,10 +16,10 @@
|
||||
* always reserving 1 connection for HNSW + heartbeat + doctor probes.
|
||||
*/
|
||||
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { resolveDirectPoolSize } from '../core/connection-manager.ts';
|
||||
import { listBackfills, getBackfill } from '../core/backfill-registry.ts';
|
||||
import { runBackfill, clearBackfillCheckpoint } from '../core/backfill-base.ts';
|
||||
import { loadConfig, toEngineConfig } from '../core/config.ts';
|
||||
|
||||
interface BackfillArgs {
|
||||
kind?: string;
|
||||
@@ -114,7 +114,14 @@ function clampConcurrency(requested: number | undefined): { effective: number; w
|
||||
return { effective: requested };
|
||||
}
|
||||
|
||||
export async function runBackfillCommand(args: string[]): Promise<void> {
|
||||
/**
|
||||
* #1963 (same class as reindex-frontmatter): takes the ALREADY-CONNECTED
|
||||
* engine from cli.ts's dispatch. Building a second engine here deadlocked on
|
||||
* the PGLite data-dir lock (cli.ts's `connectEngine()` already holds it in
|
||||
* this same process) — every `gbrain backfill <kind>` on PGLite timed out
|
||||
* after 30s. Engine lifecycle belongs to cli.ts's connect + teardown.
|
||||
*/
|
||||
export async function runBackfillCommand(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
const cli = parseArgs(args);
|
||||
if (cli.help) { printHelp(); return; }
|
||||
|
||||
@@ -144,20 +151,10 @@ export async function runBackfillCommand(args: string[]): Promise<void> {
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const config = loadConfig();
|
||||
if (!config) {
|
||||
console.error('No brain configured. Run: gbrain init');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// X5 admission control — clamp concurrency to direct-pool capacity.
|
||||
const { effective: concurrency, warning } = clampConcurrency(cli.concurrency);
|
||||
if (warning) console.warn(warning);
|
||||
|
||||
const { createEngine } = await import('../core/engine-factory.ts');
|
||||
const engine = await createEngine(toEngineConfig(config));
|
||||
await engine.connect(toEngineConfig(config));
|
||||
|
||||
if (cli.fresh) {
|
||||
await clearBackfillCheckpoint(engine, reg.spec.name);
|
||||
console.log(`Cleared checkpoint for backfill.${reg.spec.name}`);
|
||||
@@ -192,7 +189,6 @@ export async function runBackfillCommand(args: string[]): Promise<void> {
|
||||
if (result.cappedByMaxRows) console.log(` ⚠️ Capped by --max-rows; more remain.`);
|
||||
if (result.cappedByErrors) console.log(` ⚠️ Capped by --max-errors at ${result.errors}.`);
|
||||
|
||||
await engine.disconnect();
|
||||
if (result.cappedByErrors) process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
semverGt,
|
||||
semverLte,
|
||||
} from '../core/semver.ts';
|
||||
import { writeUpdateCache, type UpdateMarker } from '../core/self-upgrade.ts';
|
||||
import { readUpdateCache, writeUpdateCache, type UpdateMarker } from '../core/self-upgrade.ts';
|
||||
|
||||
/** Best-effort cache write — a read-only ~/.gbrain must never make the check throw. */
|
||||
function safeWriteCache(marker: UpdateMarker): void {
|
||||
@@ -45,26 +45,53 @@ function upgradeCommandForMethod(method: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the latest version is resolved from. gbrain publishes NO GitHub
|
||||
* releases (the `releases/latest` API is a permanent 404), so the release
|
||||
* train's source of truth is the `VERSION` file on master — same trusted host
|
||||
* `fetchChangelog` already uses. An npm fallback was rejected: the `gbrain`
|
||||
* package on npm is an unrelated GPU library (#505), so it would produce false
|
||||
* upgrade prompts pointing at a stranger's package. */
|
||||
const VERSION_SOURCE_URL = 'https://raw.githubusercontent.com/garrytan/gbrain/master/VERSION';
|
||||
const RELEASE_NOTES_URL = 'https://github.com/garrytan/gbrain/blob/master/CHANGELOG.md';
|
||||
|
||||
/** Extract a version from the raw VERSION file body: first line, optional `v`
|
||||
* prefix, optional `-suffix` channel tag (`0.31.1.1-fixwave` compares as its
|
||||
* numeric base — fail-safe: a suffix-only bump never prompts). Body is bounded
|
||||
* before parsing so a malformed/huge response can't blow up the check. */
|
||||
export function parseVersionFileBody(body: string): string | null {
|
||||
const firstLine = body.slice(0, 256).trim().split('\n')[0].trim();
|
||||
const m = firstLine.match(/^v?(\d+\.\d+\.\d+(?:\.\d+)?)(?:[-+][0-9A-Za-z.-]+)?$/);
|
||||
return m && isValidVersionString(m[1]) ? m[1] : null;
|
||||
}
|
||||
|
||||
export type LatestReleaseResult =
|
||||
| { ok: true; tag: string; published_at: string; url: string }
|
||||
| { ok: false; reason: 'network_error' | 'no_releases' };
|
||||
|
||||
/**
|
||||
* Fetch the latest GitHub release. Exported (v0.42) so the self-upgrade refresh
|
||||
* path and tests can reuse it. 5s timeout (was 10s) — this runs on the detached
|
||||
* refresh, never the hot path, but a tight bound keeps the refresh cheap.
|
||||
* Resolve the latest published gbrain version (from VERSION on master — see
|
||||
* VERSION_SOURCE_URL). Exported (v0.42) so the self-upgrade refresh path and
|
||||
* tests can reuse it. 5s timeout — this runs on the detached refresh, never the
|
||||
* hot path. Failures are discriminated: `network_error` (offline/timeout) vs
|
||||
* `no_releases` (endpoint answered but no usable version).
|
||||
*/
|
||||
export async function fetchLatestRelease(): Promise<{ tag: string; published_at: string; url: string } | null> {
|
||||
export async function fetchLatestRelease(): Promise<LatestReleaseResult> {
|
||||
let res: Response;
|
||||
try {
|
||||
const res = await fetch('https://api.github.com/repos/garrytan/gbrain/releases/latest', {
|
||||
res = await fetch(VERSION_SOURCE_URL, {
|
||||
headers: { 'User-Agent': `gbrain/${VERSION}` },
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json() as any;
|
||||
return {
|
||||
tag: data.tag_name || '',
|
||||
published_at: data.published_at || '',
|
||||
url: data.html_url || '',
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
return { ok: false, reason: 'network_error' };
|
||||
}
|
||||
try {
|
||||
if (!res.ok) return { ok: false, reason: 'no_releases' };
|
||||
const tag = parseVersionFileBody(await res.text());
|
||||
if (!tag) return { ok: false, reason: 'no_releases' };
|
||||
return { ok: true, tag, published_at: '', url: RELEASE_NOTES_URL };
|
||||
} catch {
|
||||
return { ok: false, reason: 'network_error' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,17 +145,33 @@ export function extractChangelogBetween(changelog: string, from: string, to: str
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the latest release and write the self-upgrade cache (the marker line
|
||||
* read by the CLI startup hook). Fail-open: on any network failure we cache
|
||||
* `UP_TO_DATE <current>` so the TTL prevents hammering GitHub on every
|
||||
* invocation. Returns the resolved marker for callers that want it. This is the
|
||||
* function the detached single-flight refresh (`gbrain check-update
|
||||
* --refresh-cache`) invokes.
|
||||
* A failed check must NEVER write `up_to_date` — that was #486: the fetch
|
||||
* failed permanently (dead releases API) and every user was told "you're
|
||||
* current" forever. Instead, re-write the last-known-good marker (bumping its
|
||||
* mtime so the cache TTL still throttles retries and a network blip can't
|
||||
* erase a pending upgrade_available notice). No prior marker → write nothing;
|
||||
* the next invocation retries.
|
||||
*/
|
||||
function preserveCacheOnFailedCheck(): void {
|
||||
try {
|
||||
const prior = readUpdateCache();
|
||||
if (prior) safeWriteCache(prior.marker);
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the latest version and write the self-upgrade cache (the marker line
|
||||
* read by the CLI startup hook). On fetch failure the last-known-good marker is
|
||||
* preserved (see preserveCacheOnFailedCheck) — never a fabricated `up_to_date`.
|
||||
* This is the function the detached single-flight refresh (`gbrain
|
||||
* check-update --refresh-cache`) invokes.
|
||||
*/
|
||||
export async function refreshUpdateCache(): Promise<void> {
|
||||
const release = await fetchLatestRelease();
|
||||
if (!release) {
|
||||
safeWriteCache({ kind: 'up_to_date', current: VERSION });
|
||||
if (!release.ok) {
|
||||
preserveCacheOnFailedCheck();
|
||||
return;
|
||||
}
|
||||
const latestVersion = release.tag.replace(/^v/, '');
|
||||
@@ -166,9 +209,8 @@ export async function runCheckUpdate(args: string[]) {
|
||||
|
||||
const release = await fetchLatestRelease();
|
||||
|
||||
if (!release) {
|
||||
// Warm the cache fail-open so the startup hook doesn't re-fetch every call.
|
||||
safeWriteCache({ kind: 'up_to_date', current: VERSION });
|
||||
if (!release.ok) {
|
||||
preserveCacheOnFailedCheck();
|
||||
if (json) {
|
||||
console.log(JSON.stringify({
|
||||
current_version: VERSION,
|
||||
@@ -179,10 +221,12 @@ export async function runCheckUpdate(args: string[]) {
|
||||
release_url: '',
|
||||
changelog_diff: '',
|
||||
published_at: '',
|
||||
error: 'no_releases',
|
||||
error: release.reason,
|
||||
}, null, 2));
|
||||
} else if (release.reason === 'network_error') {
|
||||
console.log(`GBrain ${VERSION} — could not check for updates (network unavailable).`);
|
||||
} else {
|
||||
console.log(`GBrain ${VERSION} — could not check for updates (no releases found or network unavailable).`);
|
||||
console.log(`GBrain ${VERSION} — could not determine the latest published version.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
|
||||
}
|
||||
console.log('GBrain config:');
|
||||
for (const [k, v] of Object.entries(config)) {
|
||||
const display = typeof v === 'string' ? redactConfigValue(k, v) : v;
|
||||
// #575: objects interpolated into the template literal printed
|
||||
// `[object Object]` — render them as JSON instead. Sensitive keys
|
||||
// stay redacted whether the value is a string or an object.
|
||||
const display = typeof v === 'string'
|
||||
? redactConfigValue(k, v)
|
||||
: v !== null && typeof v === 'object'
|
||||
? (isSensitiveConfigKey(k) ? '***' : JSON.stringify(v))
|
||||
: v;
|
||||
console.log(` ${k}: ${display}`);
|
||||
}
|
||||
return;
|
||||
|
||||
+48
-2
@@ -4349,8 +4349,18 @@ export async function checkCycleFreshness(
|
||||
: `'${source.id}'`;
|
||||
const raw = source.config?.last_full_cycle_at;
|
||||
if (typeof raw !== 'string') {
|
||||
// #2540: WARN, not FAIL. This check iterates EVERY local_path source,
|
||||
// so on a multi-source install where only some vaults are cycled
|
||||
// (e.g. one nightly `gbrain dream --dir <vault>`), a never-cycled
|
||||
// sibling source turned doctor permanently red — which erodes the
|
||||
// check's signal until real staleness hides inside the noise (the
|
||||
// reporter's install masked genuinely stale sources for weeks this
|
||||
// way). "Never cycled" also fires on a source added minutes ago.
|
||||
// A source that HAS cycled and then went stale still escalates
|
||||
// through the warn/fail age thresholds below — that is the
|
||||
// regression signal this check exists for.
|
||||
issues.push(`Source ${display} has never completed a full cycle`);
|
||||
hasFailures = true;
|
||||
hasWarnings = true;
|
||||
continue;
|
||||
}
|
||||
const last = new Date(raw).getTime();
|
||||
@@ -4386,7 +4396,7 @@ export async function checkCycleFreshness(
|
||||
return {
|
||||
name: 'cycle_freshness',
|
||||
status: 'warn',
|
||||
message: `${issues.join('; ')}.`,
|
||||
message: `${issues.join('; ')}. Run \`gbrain dream --source <id>\` to cycle a source, or start \`gbrain autopilot\`.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -5592,6 +5602,42 @@ export async function buildChecks(
|
||||
// Best-effort filesystem-hygiene check; never block doctor.
|
||||
}
|
||||
|
||||
// 3f. npm_squat (#505). The npm registry name `gbrain` belongs to an
|
||||
// unrelated third-party package — this project is NOT distributed on npm.
|
||||
// A reflexive `npm i -g gbrain` / `bun add -g gbrain` installs something
|
||||
// unrelated that can shadow the real binary on PATH. Classify every
|
||||
// `gbrain` that `which -a` finds (pure helpers in
|
||||
// src/core/npm-squat-check.ts) and warn when an unrelated install wins on
|
||||
// PATH or the entry is broken. Skips silently when gbrain isn't on PATH
|
||||
// at all (e.g. running via `bun src/cli.ts`).
|
||||
try {
|
||||
const { execSync } = await import('node:child_process');
|
||||
let candidates: string[] = [];
|
||||
try {
|
||||
candidates = execSync('which -a gbrain', {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
})
|
||||
.split('\n')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
} catch {
|
||||
// `which` exits non-zero when gbrain isn't on PATH (or is missing
|
||||
// entirely on this platform) — nothing to check.
|
||||
}
|
||||
const { assessGbrainBinaries } = await import('../core/npm-squat-check.ts');
|
||||
const assessment = assessGbrainBinaries(candidates);
|
||||
if (assessment.status !== 'skip') {
|
||||
checks.push({
|
||||
name: 'npm_squat',
|
||||
status: assessment.status,
|
||||
message: assessment.message,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Best-effort environment check; never block doctor.
|
||||
}
|
||||
|
||||
// 3b-multi-source. Multi-source drift (v0.31.8 — D8 + D17 + OV12 + OV13).
|
||||
// Pre-v0.30.3 putPage misrouted multi-source writes to (default, slug).
|
||||
// For each non-default source with local_path set, walk the FS and surface
|
||||
|
||||
+50
-3
@@ -19,6 +19,26 @@ import {
|
||||
} from '../core/pace-mode.ts';
|
||||
import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';
|
||||
import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';
|
||||
import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';
|
||||
import { titleTierCorpusGeneration } from '../core/contextual-retrieval-service.ts';
|
||||
import type { Page } from '../core/types.ts';
|
||||
|
||||
/**
|
||||
* #3507 — after a plain re-embed fully re-embedded a `per_chunk_synopsis`
|
||||
* page at the title-only tier (see wrapChunkTextsForStoredMode), restamp the
|
||||
* page's CR state to 'title' so `contextual_retrieval_mode` keeps describing
|
||||
* the vectors actually in the column. The reindex sweep restores the synopsis
|
||||
* tier later. No-op for every other mode.
|
||||
*/
|
||||
export async function restampIfDemotedToTitleTier(
|
||||
engine: BrainEngine,
|
||||
page: Pick<Page, 'contextual_retrieval_mode'> | null | undefined,
|
||||
slug: string,
|
||||
sourceId: string,
|
||||
): Promise<void> {
|
||||
if (page?.contextual_retrieval_mode !== 'per_chunk_synopsis') return;
|
||||
await engine.updatePageContextualRetrievalState(slug, sourceId, 'title', titleTierCorpusGeneration());
|
||||
}
|
||||
|
||||
export interface EmbedOpts {
|
||||
/** Embed ALL pages (every chunk). */
|
||||
@@ -599,7 +619,11 @@ async function embedPage(
|
||||
return;
|
||||
}
|
||||
|
||||
const embeddings = await embedBatch(toEmbed.map(c => c.chunk_text), { abortSignal: signal });
|
||||
// #3507: embed with the page's STORED wrapping convention (title-tier
|
||||
// contextual prefix when the page was embedded wrapped), not raw
|
||||
// chunk_text — otherwise a re-embed silently strips the contextual
|
||||
// prefixes the sync path applied. fenced_code chunks stay unwrapped.
|
||||
const embeddings = await embedBatch(wrapChunkTextsForStoredMode(page, toEmbed), { abortSignal: signal });
|
||||
const embeddingMap = new Map<number, Float32Array>();
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
@@ -622,6 +646,9 @@ async function embedPage(
|
||||
// such a page and then stamps it.
|
||||
if (toEmbed.length === chunks.length) {
|
||||
await engine.setPageEmbeddingSignature(slug, { sourceId, signature: currentEmbeddingSignature() });
|
||||
// #3507: a fully re-embedded per_chunk_synopsis page landed at the
|
||||
// title tier — keep the stamped mode honest.
|
||||
await restampIfDemotedToTitleTier(engine, page, slug, page.source_id);
|
||||
}
|
||||
result.embedded += toEmbed.length;
|
||||
result.pages_processed++;
|
||||
@@ -763,7 +790,8 @@ async function embedAll(
|
||||
}
|
||||
|
||||
try {
|
||||
const embeddings = await embedBatch(toEmbed.map(c => c.chunk_text));
|
||||
// #3507: reproduce the page's stored wrapping convention (see embedPage).
|
||||
const embeddings = await embedBatch(wrapChunkTextsForStoredMode(page, toEmbed));
|
||||
// Build a map of new embeddings by chunk_index
|
||||
const embeddingMap = new Map<number, Float32Array>();
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
@@ -785,6 +813,11 @@ async function embedAll(
|
||||
await observed(pacer, () =>
|
||||
engine.setPageEmbeddingSignature(page.slug, { sourceId: pageSourceId, signature }),
|
||||
);
|
||||
// #3507: --all fully re-embeds; a per_chunk_synopsis page landed at
|
||||
// the title tier — keep the stamped mode honest.
|
||||
await observed(pacer, () =>
|
||||
restampIfDemotedToTitleTier(engine, page, page.slug, pageSourceId),
|
||||
);
|
||||
result.embedded += toEmbed.length;
|
||||
} catch (e: unknown) {
|
||||
serr(`\n Error embedding ${page.slug}: ${e instanceof Error ? e.message : e}`);
|
||||
@@ -1098,7 +1131,13 @@ async function embedAllStale(
|
||||
const keySourceId = stale[0]?.source_id ?? 'default';
|
||||
const slug = stale[0].slug;
|
||||
try {
|
||||
const embeddings = await embedBatchWithBackoff(stale.map(c => c.chunk_text), { abortSignal: effectiveSignal });
|
||||
// #3507: fetch the page row for its title + stored CR mode so the
|
||||
// re-embed reproduces the page's wrapping convention instead of
|
||||
// silently stripping contextual prefixes — `embed --stale` is the
|
||||
// NORMAL post-model-migration path, so raw-text embedding here
|
||||
// quietly converted whole corpora to the unwrapped convention.
|
||||
const pageRow = await observed(pacer, () => engine.getPage(slug, { sourceId: keySourceId }));
|
||||
const embeddings = await embedBatchWithBackoff(wrapChunkTextsForStoredMode(pageRow, stale), { abortSignal: effectiveSignal });
|
||||
// Re-fetch existing chunks and merge to avoid deleting non-stale chunks.
|
||||
const existing = await observed(pacer, () => engine.getChunks(slug, { sourceId: keySourceId }));
|
||||
const staleIdxToEmbedding = new Map<number, Float32Array>();
|
||||
@@ -1126,6 +1165,14 @@ async function embedAllStale(
|
||||
engine.setPageEmbeddingSignature(slug, { sourceId: keySourceId, signature }),
|
||||
);
|
||||
}
|
||||
// #3507: a FULLY re-embedded per_chunk_synopsis page landed at the
|
||||
// title tier — keep the stamped mode honest. Partially-stale pages
|
||||
// stay stamped as-is (mixed provenance; reindex sweeps fix them).
|
||||
if (stale.length === existing.length) {
|
||||
await observed(pacer, () =>
|
||||
restampIfDemotedToTitleTier(engine, pageRow, slug, keySourceId),
|
||||
);
|
||||
}
|
||||
result.embedded += stale.length;
|
||||
} catch (e: unknown) {
|
||||
// Budget/abort-fired cancellations are expected on the way out; don't
|
||||
|
||||
@@ -78,7 +78,7 @@ FLAGS:
|
||||
cycle is 3 model calls; verdict aggregates over them.
|
||||
--slot-a-model <id> Override default 'openai:gpt-5.2'.
|
||||
--slot-b-model <id> Override default 'anthropic:claude-opus-4-7'.
|
||||
--slot-c-model <id> Override default 'google:gemini-1.5-pro'.
|
||||
--slot-c-model <id> Override default 'deepseek:deepseek-v4-pro'.
|
||||
--receipt-dir <path> Default: gbrainPath('eval-receipts').
|
||||
--max-tokens N Output token budget per call. Default: 4000.
|
||||
--json Emit final aggregate as JSON to stdout (progress to stderr).
|
||||
|
||||
@@ -349,7 +349,13 @@ function inferTypeByDir(fromDir: string, toDir: string, frontmatter?: Record<str
|
||||
const to = toDir.split('/')[0];
|
||||
if (from === 'people' && to === 'companies') {
|
||||
if (Array.isArray(frontmatter?.founded)) return 'founded';
|
||||
return 'works_at';
|
||||
// #3466: bare people/ -> companies/ adjacency is not evidence of
|
||||
// employment, so it gets the neutral 'mentions' verb instead of
|
||||
// 'works_at'. Real works_at edges still come from the two paths that
|
||||
// read actual evidence: the company:/companies: frontmatter fields
|
||||
// (FRONTMATTER_LINK_MAP) and employment phrasing in prose
|
||||
// (inferLinkType in link-extraction.ts).
|
||||
return 'mentions';
|
||||
}
|
||||
if (from === 'people' && to === 'deals') return 'involved_in';
|
||||
if (from === 'deals' && to === 'companies') return 'deal_for';
|
||||
|
||||
@@ -42,7 +42,7 @@ interface FeatureScanResult {
|
||||
const RECIPE_META = [
|
||||
{ id: 'email-to-brain', name: 'Email to Brain', secrets: ['GMAIL_APP_PASSWORD'] },
|
||||
{ id: 'calendar-to-brain', name: 'Calendar Sync', secrets: ['GOOGLE_CALENDAR_API_KEY'] },
|
||||
{ id: 'x-to-brain', name: 'X/Twitter to Brain', secrets: ['X_BEARER_TOKEN'] },
|
||||
{ id: 'x-to-brain', name: 'X/Twitter to Brain', secrets: ['X_API_BEARER_TOKEN'] },
|
||||
{ id: 'twilio-voice-brain', name: 'Voice to Brain', secrets: ['TWILIO_AUTH_TOKEN'] },
|
||||
{ id: 'meeting-sync', name: 'Meeting Sync', secrets: ['CIRCLEBACK_API_KEY'] },
|
||||
{ id: 'credential-gateway', name: 'Credential Gateway', secrets: ['OAUTH_CLIENT_SECRET'] },
|
||||
|
||||
+10
-2
@@ -16,7 +16,7 @@ interface FileRecord {
|
||||
filename: string;
|
||||
storage_path: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
size_bytes: number | bigint | string | null;
|
||||
content_hash: string;
|
||||
metadata: Record<string, unknown>;
|
||||
created_at: string;
|
||||
@@ -42,6 +42,14 @@ function fileHash(filePath: string): string {
|
||||
return createHash('sha256').update(content).digest('hex');
|
||||
}
|
||||
|
||||
export function formatFileSizeKb(rawSizeBytes: number | bigint | string | null): string {
|
||||
if (rawSizeBytes == null) return '?';
|
||||
const sizeBytes = Number(rawSizeBytes);
|
||||
return Number.isFinite(sizeBytes) && sizeBytes >= 0
|
||||
? `${Math.round(sizeBytes / 1024)}KB`
|
||||
: '?';
|
||||
}
|
||||
|
||||
export async function runFiles(engine: BrainEngine, args: string[]) {
|
||||
const subcommand = args[0];
|
||||
|
||||
@@ -116,7 +124,7 @@ async function listFiles(engine: BrainEngine, slug?: string) {
|
||||
|
||||
console.log(`${rows.length} file(s):`);
|
||||
for (const row of rows) {
|
||||
const size = row.size_bytes ? `${Math.round(Number(row.size_bytes) / 1024)}KB` : '?';
|
||||
const size = formatFileSizeKb(row.size_bytes as FileRecord['size_bytes']);
|
||||
console.log(` ${row.page_slug || '(unlinked)'} / ${row.filename} [${size}, ${row.mime_type || '?'}]`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ import matter from 'gray-matter';
|
||||
import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from 'fs';
|
||||
import { join, basename } from 'path';
|
||||
import { homedir } from 'os';
|
||||
import { gbrainPath } from '../core/config.ts';
|
||||
import { gbrainPath, loadConfig } from '../core/config.ts';
|
||||
import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
// --- Types ---
|
||||
@@ -122,9 +123,28 @@ export function isUnsafeHealthCheck(check: string): boolean {
|
||||
return /[;&|`$(){}\\<>\n]/.test(check);
|
||||
}
|
||||
|
||||
/** Expand $VAR references with process.env values */
|
||||
/**
|
||||
* Env view for secret resolution (#2789): apply the same config.json→env
|
||||
* folding the runtime applies via buildGatewayConfig, so a credential stored
|
||||
* only in ~/.gbrain/config.json — which powers a perfectly healthy
|
||||
* integration — is not reported [missing] by show/status. process.env still
|
||||
* wins for non-empty values (buildGatewayConfig spreads it last, dropping
|
||||
* only ''/undefined entries). Falls back to bare process.env before
|
||||
* `gbrain init` (no config file yet). Mirrors the #2728 fix on the
|
||||
* providers command.
|
||||
*/
|
||||
export function secretEnv(): Record<string, string | undefined> {
|
||||
try {
|
||||
const cfg = loadConfig();
|
||||
if (cfg) return buildGatewayConfig(cfg).env;
|
||||
} catch { /* integrations must keep working pre-init — fall through */ }
|
||||
return process.env;
|
||||
}
|
||||
|
||||
/** Expand $VAR references with gateway-env (config-folded) values */
|
||||
export function expandVars(s: string): string {
|
||||
return s.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_, name) => process.env[name] || '');
|
||||
const env = secretEnv();
|
||||
return s.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_, name) => env[name] || '');
|
||||
}
|
||||
|
||||
// --- SSRF Protection ---
|
||||
@@ -249,7 +269,7 @@ export async function executeHealthCheck(
|
||||
}
|
||||
|
||||
case 'env_exists': {
|
||||
const val = process.env[check.name];
|
||||
const val = secretEnv()[check.name];
|
||||
return {
|
||||
...base,
|
||||
status: val ? 'ok' : 'fail',
|
||||
@@ -457,11 +477,12 @@ function readHeartbeat(id: string): HeartbeatEntry[] {
|
||||
|
||||
// --- Secret Checking ---
|
||||
|
||||
function checkSecrets(secrets: RecipeSecret[]): { set: string[]; missing: RecipeSecret[] } {
|
||||
export function checkSecrets(secrets: RecipeSecret[]): { set: string[]; missing: RecipeSecret[] } {
|
||||
const set: string[] = [];
|
||||
const missing: RecipeSecret[] = [];
|
||||
const env = secretEnv();
|
||||
for (const s of secrets) {
|
||||
if (process.env[s.name]) {
|
||||
if (env[s.name]) {
|
||||
set.push(s.name);
|
||||
} else {
|
||||
missing.push(s);
|
||||
@@ -607,8 +628,9 @@ function cmdShow(args: string[]): void {
|
||||
if (f.requires.length > 0) console.log(`Requires: ${f.requires.join(', ')}`);
|
||||
|
||||
console.log('\nSecrets needed:');
|
||||
const env = secretEnv();
|
||||
for (const s of f.secrets) {
|
||||
const isSet = process.env[s.name] ? ' [set]' : ' [missing]';
|
||||
const isSet = env[s.name] ? ' [set]' : ' [missing]';
|
||||
console.log(` ${s.name}${isSet}`);
|
||||
console.log(` ${s.description}`);
|
||||
console.log(` Get it: ${s.where}`);
|
||||
|
||||
+10
-3
@@ -233,7 +233,7 @@ USAGE
|
||||
gbrain jobs get <id>
|
||||
gbrain jobs cancel <id>
|
||||
gbrain jobs retry <id>
|
||||
gbrain jobs prune [--older-than 30d]
|
||||
gbrain jobs prune [--older-than 30d] [--dry-run]
|
||||
gbrain jobs delete <id>
|
||||
gbrain jobs stats
|
||||
gbrain jobs smoke
|
||||
@@ -633,8 +633,15 @@ HANDLER TYPES (built in)
|
||||
try { await queue.ensureSchema(); }
|
||||
catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }
|
||||
|
||||
const count = await queue.prune({ olderThan: new Date(Date.now() - days * 86400000) });
|
||||
console.log(`Pruned ${count} jobs older than ${days} days.`);
|
||||
// #2712: --dry-run previews the count without deleting. It used to be
|
||||
// silently ignored (the destructive default ran anyway).
|
||||
const dryRun = hasFlag(args, '--dry-run');
|
||||
const count = await queue.prune({ olderThan: new Date(Date.now() - days * 86400000), dryRun });
|
||||
if (dryRun) {
|
||||
console.log(`[dry-run] Would prune ${count} jobs older than ${days} days. Nothing deleted.`);
|
||||
} else {
|
||||
console.log(`Pruned ${count} jobs older than ${days} days.`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -151,8 +151,17 @@ export async function runReindexFrontmatter(
|
||||
};
|
||||
}
|
||||
|
||||
/** CLI entrypoint. Argv shape matches reindex-code for consistency. */
|
||||
export async function reindexFrontmatterCli(args: string[]): Promise<void> {
|
||||
/**
|
||||
* CLI entrypoint. Argv shape matches reindex-code for consistency.
|
||||
*
|
||||
* #1963: takes the ALREADY-CONNECTED engine from cli.ts's dispatch instead of
|
||||
* building its own. The old self-managed `createEngine()+connect()` here was a
|
||||
* same-process double-connect: cli.ts's `connectEngine()` already held the
|
||||
* PGLite data-dir lock, so the second `connect()` spun the full 30s lock
|
||||
* timeout waiting on its own process and the command always exited 1 on
|
||||
* PGLite. The engine lifecycle (connect + teardown) belongs to cli.ts.
|
||||
*/
|
||||
export async function reindexFrontmatterCli(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
const opts: ReindexFrontmatterOpts = {};
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i];
|
||||
@@ -173,37 +182,15 @@ export async function reindexFrontmatterCli(args: string[]): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const { createEngine } = await import('../core/engine-factory.ts');
|
||||
const { loadConfig, toEngineConfig } = await import('../core/config.ts');
|
||||
const cfg = loadConfig();
|
||||
if (!cfg) {
|
||||
console.error('No gbrain config; run `gbrain init` first.');
|
||||
process.exit(1);
|
||||
}
|
||||
const engineConfig = toEngineConfig(cfg);
|
||||
const engine = await createEngine(engineConfig);
|
||||
// v0.37.7.0 #1225: createEngine() only constructs; callers MUST connect
|
||||
// before any executeRaw call. Pre-fix, the first query in countAffected
|
||||
// crashed with "PGLite not connected. Call connect() first." even on
|
||||
// --dry-run. initSchema is idempotent on a current schema, costs ~1ms.
|
||||
await engine.connect(engineConfig);
|
||||
await engine.initSchema();
|
||||
|
||||
try {
|
||||
const result = await runReindexFrontmatter(engine, opts);
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
const noun = result.status === 'dry_run' ? 'would update' : 'updated';
|
||||
console.error(
|
||||
`\nReindex ${result.status}: examined=${result.examined} ${noun}=${result.updated} ` +
|
||||
`fallback=${result.fallback} dur=${result.durationSec.toFixed(1)}s`,
|
||||
);
|
||||
}
|
||||
if (result.status === 'cancelled') process.exit(1);
|
||||
} finally {
|
||||
if ('disconnect' in engine && typeof engine.disconnect === 'function') {
|
||||
await engine.disconnect();
|
||||
}
|
||||
const result = await runReindexFrontmatter(engine, opts);
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
const noun = result.status === 'dry_run' ? 'would update' : 'updated';
|
||||
console.error(
|
||||
`\nReindex ${result.status}: examined=${result.examined} ${noun}=${result.updated} ` +
|
||||
`fallback=${result.fallback} dur=${result.durationSec.toFixed(1)}s`,
|
||||
);
|
||||
}
|
||||
if (result.status === 'cancelled') process.exit(1);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {
|
||||
const force = args.includes('--force');
|
||||
const json = args.includes('--json');
|
||||
|
||||
const release = await fetchLatestRelease();
|
||||
const result = await fetchLatestRelease();
|
||||
const release = result.ok ? result : null;
|
||||
const latest = release ? release.tag.replace(/^v/, '') : null;
|
||||
const behind = !!latest && isValidVersionString(latest) && isNewerVersion(VERSION, latest);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
import express from 'express';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
import type { Server as HttpServer } from 'http';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import cors from 'cors';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
type IngestionEvent,
|
||||
} from '../core/ingestion/types.ts';
|
||||
import { resolveOwnerHolder } from '../core/owner-holder.ts';
|
||||
import { registerCleanup } from '../core/process-cleanup.ts';
|
||||
|
||||
/**
|
||||
* /health endpoint timeout. 3s rather than 5s: Fly.io's default
|
||||
@@ -55,6 +57,71 @@ import { resolveOwnerHolder } from '../core/owner-holder.ts';
|
||||
*/
|
||||
export const HEALTH_TIMEOUT_MS = 3000;
|
||||
|
||||
/** Exported so tests can type their structural fakes exactly (#3599). */
|
||||
export type HttpServerLifecycle = Pick<HttpServer, 'listening' | 'once' | 'off' | 'close'>;
|
||||
/** Exported so tests can type their structural fakes exactly (#3599). */
|
||||
export type SignalSource = Pick<NodeJS.Process, 'once' | 'off'>;
|
||||
type CleanupRegistrar = typeof registerCleanup;
|
||||
|
||||
/**
|
||||
* Keep the HTTP server strongly referenced and make the daemon lifetime
|
||||
* explicit instead of relying on runtime-specific event-loop behavior for an
|
||||
* unobserved `app.listen()` return value. The shared abnormal-termination
|
||||
* cleanup pass closes it before process exit.
|
||||
*/
|
||||
export function waitForHttpServerLifecycle(
|
||||
server: HttpServerLifecycle,
|
||||
options: {
|
||||
signals?: SignalSource;
|
||||
register?: CleanupRegistrar;
|
||||
} = {},
|
||||
): Promise<void> {
|
||||
const signals = options.signals ?? process;
|
||||
const register = options.register ?? registerCleanup;
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let closePromise: Promise<void> | null = null;
|
||||
|
||||
const closeServer = (): Promise<void> => {
|
||||
if (closePromise) return closePromise;
|
||||
closePromise = new Promise<void>((closeResolve, closeReject) => {
|
||||
if (!server.listening) {
|
||||
closeResolve();
|
||||
return;
|
||||
}
|
||||
server.close((error?: Error) => {
|
||||
if (error) closeReject(error);
|
||||
else closeResolve();
|
||||
});
|
||||
});
|
||||
return closePromise;
|
||||
};
|
||||
|
||||
const deregister = register('http-server', closeServer);
|
||||
|
||||
const finish = (error?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
server.off('close', onClose);
|
||||
server.off('error', onError);
|
||||
signals.off('SIGINT', onSigint);
|
||||
deregister();
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const onClose = () => finish();
|
||||
const onError = (error: Error) => finish(error);
|
||||
const onSigint = () => {
|
||||
void closeServer().catch(onError);
|
||||
};
|
||||
|
||||
server.once('close', onClose);
|
||||
server.once('error', onError);
|
||||
signals.once('SIGINT', onSigint);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.36.1.x #1024: bootstrap token resolution.
|
||||
*
|
||||
@@ -135,6 +202,25 @@ export type ProbeHealthResult =
|
||||
| { ok: true; status: 200; body: { status: 'ok'; version: string; engine: string; [k: string]: unknown } }
|
||||
| { ok: false; status: 503; body: { error: 'service_unavailable'; error_description: string } };
|
||||
|
||||
/** Exported so tests can type their structural fakes exactly (#3598). */
|
||||
export type AdminSseResponse = Pick<Response, 'setHeader' | 'flushHeaders' | 'write'>;
|
||||
|
||||
/**
|
||||
* Complete the admin EventSource handshake immediately.
|
||||
*
|
||||
* `flushHeaders()` alone can leave reverse proxies and browsers waiting for
|
||||
* the first response body bytes. An SSE comment is protocol-valid, ignored by
|
||||
* EventSource consumers, and makes the stream observable end-to-end without
|
||||
* fabricating an application event.
|
||||
*/
|
||||
export function openAdminSseStream(res: AdminSseResponse): void {
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.flushHeaders();
|
||||
res.write(': connected\n\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure async health probe. Races `engine.getStats()` against a timeout,
|
||||
* returns a tagged result. No Express coupling — easy to unit-test with a
|
||||
@@ -1632,10 +1718,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// SSE live activity feed
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get('/admin/events', requireAdmin, (req: Request, res: Response) => {
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.flushHeaders();
|
||||
openAdminSseStream(res);
|
||||
|
||||
sseClients.add(res);
|
||||
req.on('close', () => sseClients.delete(res));
|
||||
@@ -2410,7 +2493,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// ---------------------------------------------------------------------------
|
||||
const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;
|
||||
|
||||
app.listen(port, bind, () => {
|
||||
const httpServer = app.listen(port, bind, () => {
|
||||
console.error(`
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ GBrain MCP Server v${VERSION.padEnd(37)}║
|
||||
@@ -2435,4 +2518,6 @@ ${bootstrapFromEnv
|
||||
: `║ Admin Token (paste into /admin login): ║\n║ ${bootstrapToken.substring(0, 50)} ║\n║ ${bootstrapToken.substring(50).padEnd(50)} ║\n╚══════════════════════════════════════════════════════╝`}
|
||||
`);
|
||||
});
|
||||
|
||||
await waitForHttpServerLifecycle(httpServer);
|
||||
}
|
||||
|
||||
+81
-4
@@ -2874,10 +2874,17 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
: await resolveSlugByPathOrSourcePath(engine, from, undefined);
|
||||
// The new path doesn't yet have a row, so resolve from path only.
|
||||
const newSlug = resolveSlugForPath(to);
|
||||
// #3056: the cheap rename is OBSERVED, not assumed. A zero-row UPDATE
|
||||
// doesn't throw, and a thrown collision used to be swallowed by an
|
||||
// empty catch — both fell through to importFile, which created/updated
|
||||
// the row at the new path while the old row stayed behind live. Both
|
||||
// shapes now fall through to the reconcile below.
|
||||
let renameApplied = false;
|
||||
try {
|
||||
await engine.updateSlug(oldSlug, newSlug, renameOpts);
|
||||
renameApplied = (await engine.updateSlug(oldSlug, newSlug, renameOpts)) > 0;
|
||||
} catch {
|
||||
// Slug doesn't exist or collision, treat as add
|
||||
// Destination slug occupied or invalid — treat as add; the reconcile
|
||||
// below removes the stale old row once the destination materialized.
|
||||
}
|
||||
// Reimport at new path (picks up content changes). Wrapped to match the
|
||||
// deletes/adds loops: a malformed renamed file is recorded to failedFiles
|
||||
@@ -2890,9 +2897,11 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
// NAV-1 TOCTOU: refuse a destination that realpath-resolves outside the
|
||||
// repo (committed symlink pointing out).
|
||||
const filePath = join(gitContextRoot, to);
|
||||
let importResult: Awaited<ReturnType<typeof importFile>> | undefined;
|
||||
if (existsSync(filePath) && isPathSafe(filePath, gitContextRoot)) {
|
||||
try {
|
||||
const result = await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack });
|
||||
importResult = result;
|
||||
if (result.status === 'imported') chunksCreated += result.chunks;
|
||||
else if (result.status === 'skipped' && (result as { error?: string }).error) {
|
||||
failedFiles.push({ path: to, error: String((result as { error?: string }).error) });
|
||||
@@ -2901,9 +2910,68 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
failedFiles.push({ path: to, error: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
// #3056 reconcile: the rename fell back to add semantics, so the row
|
||||
// that still represents the OLD path is the stale half of the rename
|
||||
// (git reported the old path gone; a plain delete of that path would
|
||||
// remove this row). Two safety rails, both from the #3252 review:
|
||||
//
|
||||
// 1. Delete only after the destination demonstrably materialized —
|
||||
// `imported`, or an errorless `skipped` AT the new slug. Identity
|
||||
// dedup can skip against the OLD row (result.slug === oldSlug),
|
||||
// in which case nothing landed at newSlug and deleting the old
|
||||
// row would destroy the only copy.
|
||||
// 2. Locate the stale row POSITIVELY by `source_path = from`, never
|
||||
// by the oldSlug guess — after a collision, a path-derived
|
||||
// fallback slug could name an unrelated (e.g. manually curated)
|
||||
// row. No source_path match → nothing is deleted (this also means
|
||||
// code-strategy imports, which don't populate source_path, fall
|
||||
// back safely to leaving the old row rather than guessing).
|
||||
//
|
||||
// A failed delete records a `<rename:…>` SENTINEL (not an ordinary
|
||||
// path failure): the gate hard-blocks the bookmark, and — unlike a
|
||||
// plain path row — the auto-skip valve can never chronic-skip it after
|
||||
// N attempts, which would advance the bookmark and make a transient
|
||||
// delete outage a permanent duplicate. The sentinel clears through the
|
||||
// ordinary success path once the rename converges on a later run.
|
||||
let reconcileFailed = false;
|
||||
if (!renameApplied && importResult !== undefined) {
|
||||
const destMaterialized = importResult.status === 'imported' ||
|
||||
(importResult.status === 'skipped' && !importResult.error && importResult.slug === newSlug);
|
||||
if (destMaterialized) {
|
||||
try {
|
||||
const staleMap = await engine.resolveSlugsByPaths([from], { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID });
|
||||
const staleSlug = staleMap.get(from);
|
||||
if (staleSlug !== undefined && staleSlug !== newSlug) {
|
||||
await engine.deletePage(staleSlug, renameOpts);
|
||||
deletedSlugs.add(staleSlug); // never hand a deleted slug to auto-embed
|
||||
serr(` [sync] rename reconciled: removed stale row ${staleSlug} (${from} -> ${to} fell back to add).`);
|
||||
} else if (staleSlug === undefined) {
|
||||
serr(` [sync] rename fallback: no row has source_path ${from}; stale row (if any) left in place.`);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
reconcileFailed = true;
|
||||
failedFiles.push({
|
||||
path: `<rename:${to}>`,
|
||||
error: `rename reconcile failed (stale row for ${from} not removed): ` +
|
||||
`${e instanceof Error ? e.message : String(e)}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
serr(
|
||||
` [sync] rename fallback: ${from} -> ${to} did not materialize at ${newSlug} ` +
|
||||
`(import ${importResult.status}); old row left in place.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Converged (cheap rename, clean reconcile, or nothing to reconcile):
|
||||
// clear any `<rename:…>` sentinel a previous failing run recorded.
|
||||
if (!reconcileFailed) succeededPaths.push(`<rename:${to}>`);
|
||||
pagesAffected.push(newSlug);
|
||||
deletedSlugs.delete(newSlug); // #1284: rename landed on a previously-deleted slug → embeddable again
|
||||
await markCompleted(to);
|
||||
// A failed reconcile must NOT checkpoint: banking `to` would make the
|
||||
// resume filter skip this rename on the retry run, turning a transient
|
||||
// delete failure into a permanent duplicate — the exact bug being fixed.
|
||||
if (!reconcileFailed) await markCompleted(to);
|
||||
progress.tick(1, newSlug);
|
||||
}
|
||||
progress.finish();
|
||||
@@ -3362,7 +3430,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
|
||||
if (!gate.advanced) {
|
||||
const codeBreakdown = formatCodeBreakdown(failedFiles);
|
||||
if (gate.sentinelBlocked) {
|
||||
// Two sentinel classes block here: `<head>` (pin ancestry broken) and
|
||||
// `<rename:…>` (#3056 — a rename-reconcile delete failed and advancing
|
||||
// would permanently bank the duplicate). Pick the message by which fired.
|
||||
if (gate.sentinelBlocked && failedFiles.some(f => f.path === '<head>')) {
|
||||
serr(
|
||||
`\nSync blocked: repository history changed during sync (force-push / reset).\n` +
|
||||
`${codeBreakdown}\n\n` +
|
||||
@@ -3370,6 +3441,12 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
|
||||
`a commit that doesn't match the indexed tree. Re-run sync to re-pin against ` +
|
||||
`current HEAD.`,
|
||||
);
|
||||
} else if (gate.sentinelBlocked) {
|
||||
serr(
|
||||
`\nSync blocked: a rename left a stale duplicate that could not be removed:\n` +
|
||||
`${codeBreakdown}\n\n` +
|
||||
`The next 'gbrain sync' retries the reconcile from the same diff.`,
|
||||
);
|
||||
} else {
|
||||
const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;
|
||||
serr(
|
||||
|
||||
+15
-8
@@ -3,6 +3,7 @@
|
||||
*
|
||||
* Subcommands:
|
||||
* takes <slug> — list takes for a page
|
||||
* takes list — list all active takes (#2079)
|
||||
* takes search "<query>" [--who h] — keyword search across all takes
|
||||
* takes add <slug> ...flags — append a take (markdown + DB)
|
||||
* takes update <slug> --row N ...flags — update mutable fields
|
||||
@@ -129,11 +130,10 @@ function writeBody(path: string, body: string): void {
|
||||
// --- Subcommands ---
|
||||
|
||||
async function cmdList(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
const slug = args[0];
|
||||
if (!slug) {
|
||||
console.error('Usage: gbrain takes <slug> [--json]');
|
||||
process.exit(1);
|
||||
}
|
||||
// #2079: slug is optional. `gbrain takes list` (no slug) lists ALL active
|
||||
// takes — CLI parity with the takes_list operation. A leading flag is not
|
||||
// a slug.
|
||||
const slug = args[0] && !args[0].startsWith('-') ? args[0] : undefined;
|
||||
const json = flagPresent(args, '--json');
|
||||
const holder = flagValue(args, '--who');
|
||||
const kind = flagValue(args, '--kind') as string | undefined;
|
||||
@@ -153,17 +153,19 @@ async function cmdList(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const scope = slug ?? 'this brain';
|
||||
if (takes.length === 0) {
|
||||
console.log(`No takes on ${slug}.`);
|
||||
console.log(`No takes on ${scope}.`);
|
||||
return;
|
||||
}
|
||||
console.log(`# Takes on ${slug}\n`);
|
||||
console.log(`# Takes on ${scope}\n`);
|
||||
for (const t of takes) {
|
||||
const tag = t.active ? '' : ' [superseded]';
|
||||
const w = Number(t.weight).toFixed(2);
|
||||
const since = t.since_date ?? '';
|
||||
const src = t.source ? ` — ${t.source}` : '';
|
||||
console.log(`#${t.row_num} [${t.kind} • ${t.holder} • w=${w}${since ? ` • ${since}` : ''}]${tag}\n ${t.claim}${src}\n`);
|
||||
const where = slug ? '' : `${t.page_slug} `;
|
||||
console.log(`${where}#${t.row_num} [${t.kind} • ${t.holder} • w=${w}${since ? ` • ${since}` : ''}]${tag}\n ${t.claim}${src}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,6 +557,8 @@ export async function runTakes(engine: BrainEngine, args: string[]): Promise<voi
|
||||
Subcommands:
|
||||
takes <slug> [--json] [--who h] [--kind k] [--sort weight|since_date|created_at] [--expired]
|
||||
List takes for a page
|
||||
takes list [--json] [--who h] [--kind k] [--sort ...] [--expired]
|
||||
List all active takes across the brain (#2079)
|
||||
takes search "<query>" [--limit N] [--json]
|
||||
Keyword search across all takes
|
||||
takes add <slug> --claim "..." --kind <fact|take|bet|hunch> --who <holder>
|
||||
@@ -584,6 +588,9 @@ Common flags:
|
||||
const rest = args.slice(1);
|
||||
|
||||
switch (sub) {
|
||||
// #2079: `takes list` used to be parsed as page slug "list" and printed
|
||||
// "No takes on list." — reading exactly like an empty takes table.
|
||||
case 'list': return cmdList(engine, rest);
|
||||
case 'search': return cmdSearch(engine, rest);
|
||||
case 'add': return cmdAdd(engine, rest, await resolveTakesSourceId(engine));
|
||||
case 'update': return cmdUpdate(engine, rest, await resolveTakesSourceId(engine));
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* import it from `../../src/cli.ts`.
|
||||
*
|
||||
* The single ownership site for: (a) folding file-plane API keys
|
||||
* (openai/anthropic/zeroentropy/openrouter/voyage) into the gateway env, and (b) threading
|
||||
* (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/google) into the gateway env, and (b) threading
|
||||
* local-server `*_BASE_URL` env vars into base_urls. Both matter for the
|
||||
* init-time embedding-key probe — without (a) it would false-warn on
|
||||
* config.json-keyed users, and without (b) a live probe could hit the wrong
|
||||
@@ -44,6 +44,18 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
|
||||
// multimodal/image embeds despite config.json looking complete. process.env
|
||||
// still wins via the later spread.
|
||||
if (c.voyage_api_key) envFromConfig.VOYAGE_API_KEY = c.voyage_api_key;
|
||||
// #3500: same seam for DashScope. The dashscope + dashscope-rerank recipes
|
||||
// require DASHSCOPE_API_KEY, but the config-plane key was never folded, so
|
||||
// daemon/launchd/MCP contexts with no process-env export failed auth
|
||||
// despite config.json looking complete. process.env still wins via the
|
||||
// later spread.
|
||||
if (c.dashscope_api_key) envFromConfig.DASHSCOPE_API_KEY = c.dashscope_api_key;
|
||||
// #3500: same seam for Google Gemini. The google recipe reads
|
||||
// GOOGLE_GENERATIVE_AI_API_KEY; before this fold, the ONLY way to
|
||||
// configure Gemini was exporting that exact env var. (This closes the
|
||||
// deferral noted in src/core/brain-score-recommendations.ts, whose
|
||||
// HOSTED_EMBED_KEY_CONFIG entry lands in the same change.)
|
||||
if (c.google_api_key) envFromConfig.GOOGLE_GENERATIVE_AI_API_KEY = c.google_api_key;
|
||||
// Azure OpenAI (keyless/Entra): fold the non-secret endpoint/deployment + the
|
||||
// Entra opt-in into the gateway env so the azure-openai recipe works in any
|
||||
// shell (incl. non-interactive agent shells). The bearer token is minted at
|
||||
@@ -86,11 +98,26 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
|
||||
// every gateway op then throws NO_ANTHROPIC_API_KEY. Drop empty-string /
|
||||
// undefined entries before the merge. Only '' and undefined are dropped —
|
||||
// '0' and 'false' are legitimate values and survive.
|
||||
env: {
|
||||
...envFromConfig,
|
||||
...Object.fromEntries(
|
||||
Object.entries(process.env).filter(([, v]) => v !== undefined && v !== ''),
|
||||
),
|
||||
},
|
||||
env: buildEnv(envFromConfig),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge config-plane fallbacks with process.env (env wins for keys carrying a
|
||||
* real value — see #1249 note above), then apply the GEMINI_API_KEY alias:
|
||||
* Google's own docs/SDKs export GEMINI_API_KEY, but the google recipe (and
|
||||
* every gateway read site) uses GOOGLE_GENERATIVE_AI_API_KEY. Precedence:
|
||||
* env GOOGLE_GENERATIVE_AI_API_KEY > env GEMINI_API_KEY > config
|
||||
* google_api_key — i.e. the alias is still process-env, so it beats the
|
||||
* config-plane fallback, but never the canonical env name.
|
||||
*/
|
||||
function buildEnv(envFromConfig: Record<string, string>): Record<string, string> {
|
||||
const envReal = Object.fromEntries(
|
||||
Object.entries(process.env).filter(([, v]) => v !== undefined && v !== ''),
|
||||
) as Record<string, string>;
|
||||
const merged = { ...envFromConfig, ...envReal };
|
||||
if (!envReal.GOOGLE_GENERATIVE_AI_API_KEY && envReal.GEMINI_API_KEY) {
|
||||
merged.GOOGLE_GENERATIVE_AI_API_KEY = envReal.GEMINI_API_KEY;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
+63
-2
@@ -642,8 +642,42 @@ function warnRecipesMissingBatchTokens(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset (for tests). */
|
||||
export function resetGateway(): void {
|
||||
/**
|
||||
* Test-only reset baseline (#3554). The bunfig preload
|
||||
* (`test/helpers/legacy-embedding-preload.ts`) pins the gateway to the legacy
|
||||
* OpenAI/1536 config at process start, but `resetGateway()` used to wipe that
|
||||
* pin to `_config = null`. The next test file's engine connect then
|
||||
* reconfigured from the SHIPPED default (zembed-1 @ 1280) and every 1536-d
|
||||
* fixture in that file exploded with `expected 1280 dimensions, not 1536` —
|
||||
* a cross-file mine whose placement depended on shard bin-packing.
|
||||
*
|
||||
* When a baseline factory is registered, `resetGateway()` means "back to the
|
||||
* test baseline" instead of "unconfigured": it clears everything as before,
|
||||
* then re-applies the factory's config via `configureGateway()`. A factory
|
||||
* (not a frozen config) so each re-application captures fresh
|
||||
* `process.env`, matching the preload's original `applyLegacy()` semantics.
|
||||
*
|
||||
* Production is untouched: nothing in `src/` calls `resetGateway()` or this
|
||||
* setter, so in production the baseline is never registered and
|
||||
* `resetGateway()` still fully unconfigures. Same `__*ForTests` seam
|
||||
* convention as `__setEmbedTransportForTests` above.
|
||||
*/
|
||||
let _resetBaseline: (() => AIGatewayConfig) | null = null;
|
||||
|
||||
/**
|
||||
* Register (or clear, with `null`) the config factory that `resetGateway()`
|
||||
* re-applies. Called once by the bunfig test preload.
|
||||
*
|
||||
* @internal exported for tests; not part of the public gateway API.
|
||||
*/
|
||||
export function __setGatewayResetBaselineForTests(
|
||||
factory: (() => AIGatewayConfig) | null,
|
||||
): void {
|
||||
_resetBaseline = factory;
|
||||
}
|
||||
|
||||
/** Clear every piece of module state. Shared by both reset flavors. */
|
||||
function clearGatewayState(): void {
|
||||
_config = null;
|
||||
_modelCache.clear();
|
||||
_shrinkState.clear();
|
||||
@@ -655,6 +689,33 @@ export function resetGateway(): void {
|
||||
_extendedModels.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset (for tests). Clears all module state (config, model cache, shrink
|
||||
* state, transports, warned recipes, extended models), then — if a test
|
||||
* baseline is registered — re-applies it so the gateway returns to the
|
||||
* process-wide test default instead of an unconfigured limbo (#3554).
|
||||
*/
|
||||
export function resetGateway(): void {
|
||||
clearGatewayState();
|
||||
// configureGateway re-clears _modelCache/_shrinkState/_extendedModels and
|
||||
// registers the baseline's models; transports are NOT touched by it, so a
|
||||
// stale test transport can never leak back in through this path.
|
||||
if (_resetBaseline) configureGateway(_resetBaseline());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset AND stay unconfigured, ignoring any registered baseline. For the
|
||||
* handful of tests that assert genuine no-gateway behavior
|
||||
* (`no_gateway_config` diagnosis, `isAvailable() === false`, graceful
|
||||
* degradation paths). The preload's per-test beforeEach restores the
|
||||
* baseline before the next test, so this cannot leak across tests.
|
||||
*
|
||||
* @internal exported for tests; not part of the public gateway API.
|
||||
*/
|
||||
export function __unconfigureGatewayForTests(): void {
|
||||
clearGatewayState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only seam. Replaces the function the gateway calls to embed a
|
||||
* sub-batch. Pass `null` to restore the real `embedMany` from the AI SDK.
|
||||
|
||||
@@ -16,6 +16,17 @@ export const google: Recipe = {
|
||||
dims_options: [768, 1536, 3072],
|
||||
cost_per_1m_tokens_usd: 0.15,
|
||||
price_last_verified: '2026-04-20',
|
||||
// Gemini's embedding endpoint has a low per-request cap relative to
|
||||
// Voyage. Declaring max_batch_tokens makes the gateway pre-split bulk
|
||||
// batches proactively (splitByTokenBudget) instead of relying solely on
|
||||
// the recursive-halving retry on a token-limit rejection. Conservative
|
||||
// value: each gemini-embedding-001 input tops out at 2048 tokens, so a
|
||||
// 20k budget × 0.8 safety keeps a batch well within request limits while
|
||||
// staying efficient. chars_per_token ~4 matches Gemini's SentencePiece
|
||||
// density on English. Tunable; recursion stays the backstop.
|
||||
max_batch_tokens: 20_000,
|
||||
chars_per_token: 4,
|
||||
safety_factor: 0.8,
|
||||
},
|
||||
expansion: {
|
||||
models: ['gemini-2.0-flash', 'gemini-2.0-flash-lite'],
|
||||
@@ -23,11 +34,14 @@ export const google: Recipe = {
|
||||
price_last_verified: '2026-04-20',
|
||||
},
|
||||
chat: {
|
||||
models: ['gemini-2.0-flash-exp', 'gemini-2.0-flash', 'gemini-1.5-pro'],
|
||||
// gemini-1.5-pro was retired by Google (#3510) — deliberately NOT
|
||||
// listed. Default-slot guard tests validate hardcoded defaults against
|
||||
// this list, so re-adding a dead model here masks dead defaults.
|
||||
models: ['gemini-2.0-flash-exp', 'gemini-2.0-flash'],
|
||||
supports_tools: true,
|
||||
supports_subagent_loop: true,
|
||||
supports_prompt_cache: false,
|
||||
max_context_tokens: 1000000, // Gemini 1.5 Pro
|
||||
max_context_tokens: 1000000, // Gemini 2.0 Flash
|
||||
cost_per_1m_input_usd: 0.30,
|
||||
cost_per_1m_output_usd: 1.20,
|
||||
price_last_verified: '2026-04-20',
|
||||
|
||||
@@ -59,10 +59,24 @@ const ALL: Recipe[] = [
|
||||
/** Map from `provider:id` key to recipe. */
|
||||
export const RECIPES: Map<string, Recipe> = new Map(ALL.map(r => [r.id, r]));
|
||||
|
||||
/**
|
||||
* Test-only seam. Synthetic recipes appended to the registry so tests can
|
||||
* exercise registry-walking logic — notably gateway.ts's missing-batch-cap
|
||||
* startup warning — against a recipe that intentionally omits a field,
|
||||
* without editing the shipped `ALL` array. Every real embedding recipe now
|
||||
* declares a cap (token budget, `no_batch_cap`, or item cap), so a synthetic
|
||||
* cap-less recipe is the only way to cover the warn-fires path. Empty in
|
||||
* production (nothing in `src/` calls the setter); pass `[]` to reset.
|
||||
*/
|
||||
let _testRecipes: Recipe[] = [];
|
||||
export function __setTestRecipesForTests(recipes: Recipe[]): void {
|
||||
_testRecipes = recipes;
|
||||
}
|
||||
|
||||
export function getRecipe(id: string): Recipe | undefined {
|
||||
return RECIPES.get(id);
|
||||
return RECIPES.get(id) ?? _testRecipes.find(r => r.id === id);
|
||||
}
|
||||
|
||||
export function listRecipes(): Recipe[] {
|
||||
return [...ALL];
|
||||
return _testRecipes.length > 0 ? [...ALL, ..._testRecipes] : [...ALL];
|
||||
}
|
||||
|
||||
@@ -37,8 +37,10 @@ export const voyage: Recipe = {
|
||||
'voyage-multimodal-3',
|
||||
],
|
||||
default_dims: 1024,
|
||||
cost_per_1m_tokens_usd: 0.18,
|
||||
price_last_verified: '2026-04-20',
|
||||
// Display hint for `gbrain providers` only (billing math goes through
|
||||
// src/core/embedding-pricing.ts). Rate for the default voyage-4-large.
|
||||
cost_per_1m_tokens_usd: 0.12,
|
||||
price_last_verified: '2026-07-28',
|
||||
// Voyage enforces 120K tokens per batch. Voyage's tokenizer runs
|
||||
// ~3-4× denser than OpenAI tiktoken on mixed content (code/JSON/CJK),
|
||||
// so the per-recipe pre-split uses 1 char ≈ 1 token at 0.5 utilization
|
||||
|
||||
@@ -37,7 +37,13 @@ export function readRecentParserProbeEvents(
|
||||
days = 7,
|
||||
now: Date = new Date(),
|
||||
): ParserProbeAuditEvent[] {
|
||||
return writer.readRecent(days, now);
|
||||
// Chronological order (oldest → newest). The shared reader walks the
|
||||
// CURRENT week's file first, then the previous week's, so without sorting
|
||||
// the array tail is the OLDEST in-window event whenever last week's file
|
||||
// has entries — and doctor's "latest" (which reads the tail) reported a
|
||||
// days-old run while counts included the newest one.
|
||||
return writer.readRecent(days, now)
|
||||
.sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts));
|
||||
}
|
||||
|
||||
/** Exposed for tests pinning the rotation edge cases. */
|
||||
|
||||
@@ -118,5 +118,10 @@ export function readRecentQualityProbeEvents(
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
// Chronological order (oldest → newest). Events accumulate across two
|
||||
// week files read current-week-FIRST, so without sorting the array tail
|
||||
// is the OLDEST in-window event whenever last week's file has entries —
|
||||
// and doctor's "Latest:" (which reads the tail) reported a days-old run
|
||||
// while the counts included the newest one.
|
||||
return out.sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts));
|
||||
}
|
||||
|
||||
@@ -13,17 +13,13 @@ import { parseModelId } from './ai/model-resolver.ts';
|
||||
*
|
||||
* Only keys that `buildGatewayConfig` (src/core/ai/build-gateway-config.ts)
|
||||
* actually folds from config into the gateway env may appear here.
|
||||
* GOOGLE_GENERATIVE_AI_API_KEY is deliberately absent: its config field is NOT
|
||||
* threaded to the gateway today, so the producer closures fall through to
|
||||
* checking `process.env` ONLY for it. That matches what the gateway can
|
||||
* actually use (the recipe reads that key from env). Counting a config-plane
|
||||
* google_api_key here would be a false positive: doctor/autopilot would call
|
||||
* the provider "configured" and dispatch an embed.stale job that then fails
|
||||
* auth at the gateway. When a future change threads google_api_key into
|
||||
* buildGatewayConfig, re-add the matching entry here in the same change.
|
||||
*
|
||||
* VOYAGE_API_KEY → voyage_api_key was the same kind of gap (#2662) until
|
||||
* buildGatewayConfig started folding it — now safe to list here too.
|
||||
* GOOGLE_GENERATIVE_AI_API_KEY → google_api_key and DASHSCOPE_API_KEY →
|
||||
* dashscope_api_key joined for the same reason (#3500): both are folded by
|
||||
* buildGatewayConfig now, so a config-plane key is genuinely usable by the
|
||||
* gateway and counting it here is no longer a false positive.
|
||||
*
|
||||
* Caveat inherited from the existing OPENAI_API_KEY/ZEROENTROPY_API_KEY
|
||||
* entries (unchanged by #2662, noted here for anyone extending this map):
|
||||
@@ -40,6 +36,8 @@ export const HOSTED_EMBED_KEY_CONFIG: Record<string, string> = {
|
||||
OPENAI_API_KEY: 'openai_api_key',
|
||||
ZEROENTROPY_API_KEY: 'zeroentropy_api_key',
|
||||
VOYAGE_API_KEY: 'voyage_api_key',
|
||||
GOOGLE_GENERATIVE_AI_API_KEY: 'google_api_key',
|
||||
DASHSCOPE_API_KEY: 'dashscope_api_key',
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+28
-5
@@ -21,12 +21,35 @@ export const CJK_SLUG_CHARS = '一-鿿-ゟ゠-ヿ가-';
|
||||
export const CJK_RANGES_REGEX = new RegExp(`[${CJK_SLUG_CHARS}]`);
|
||||
|
||||
/**
|
||||
* Page-slug segment grammar (no anchors): alnum-or-CJK lead char, then
|
||||
* alnum/CJK/hyphen continuation. Single source for validatePageSlug
|
||||
* (operations.ts), SlugRegistry's SLUG_RE, and the dream-cycle
|
||||
* SUMMARY_SLUG_RE so every slug validator shares one grammar (#738).
|
||||
* Slug "word" character class (#3417): every script's letters, not just
|
||||
* Latin + CJK. Unicode property escapes — REQUIRES the `u` flag on any
|
||||
* regex composed from this string (without `u`, `\p{Ll}` silently matches
|
||||
* the literal chars `p`, `L`, `l`, `{`, `}`).
|
||||
*
|
||||
* \p{Ll} lowercase letters (a-z, Cyrillic/Greek lowercase, đ, …)
|
||||
* \p{Lm} modifier letters
|
||||
* \p{Lo} caseless-script letters (Hebrew, Arabic, Thai, CJK, Devanagari, …)
|
||||
* \p{M} combining marks that survive the Latin accent-strip pass
|
||||
* (Hebrew niqqud, Arabic harakat, Thai/Devanagari vowel signs)
|
||||
* \p{N} numbers (0-9, Arabic-Indic digits, …)
|
||||
*
|
||||
* Uppercase (\p{Lu}/\p{Lt}) is deliberately excluded: slugifySegment()
|
||||
* lowercases before filtering, so validators stay lowercase-canonical.
|
||||
*
|
||||
* Distinct from CJK_SLUG_CHARS above, which also drives the
|
||||
* countCJKAwareWords density heuristic — do NOT merge the two, or slug
|
||||
* grammar changes silently change chunking behavior.
|
||||
*/
|
||||
export const PAGE_SLUG_SEG = `[a-z0-9${CJK_SLUG_CHARS}][a-z0-9${CJK_SLUG_CHARS}\\-]*`;
|
||||
export const SLUG_WORD_CHARS = '\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}\\p{N}';
|
||||
|
||||
/**
|
||||
* Page-slug segment grammar (no anchors): word-char lead, then word-char or
|
||||
* hyphen continuation. Single source for validatePageSlug (operations.ts),
|
||||
* SlugRegistry's SLUG_RE, and the dream-cycle SUMMARY_SLUG_RE so every slug
|
||||
* validator shares one grammar (#738). Compose with the `u` flag — see
|
||||
* SLUG_WORD_CHARS.
|
||||
*/
|
||||
export const PAGE_SLUG_SEG = `[${SLUG_WORD_CHARS}][${SLUG_WORD_CHARS}\\-]*`;
|
||||
|
||||
export const CJK_SENTENCE_DELIMITERS = ['。', '!', '?']; // 。!?
|
||||
export const CJK_CLAUSE_DELIMITERS = [';', ':', ',', '、']; // ;:,、
|
||||
|
||||
+72
-20
@@ -51,9 +51,29 @@ export const DEFAULT_CLI_OPTIONS: CliOptions = {
|
||||
*
|
||||
* Unknown flags are passed through unchanged — per-command parsers see them.
|
||||
*/
|
||||
/**
|
||||
* #3013: commands that parse their own `--timeout` flag out of argv.
|
||||
* `sync` reads a seconds-based graceful-abort budget (src/commands/sync.ts +
|
||||
* resolveSyncHardDeadline); `remote` reads a ms-based request budget
|
||||
* (src/commands/remote.ts). For these commands the global parser must hand
|
||||
* the flag back: claiming it stripped the flag before the per-command parser
|
||||
* could read it, and — for `sync` — a non-null global timeoutMs flipped the
|
||||
* read-only dispatch gate in cli.ts, rerouting a write command into
|
||||
* dispatchReadOnlyCommand (exit 1 before any work ran).
|
||||
*/
|
||||
export const TIMEOUT_OWNING_COMMANDS = new Set(['sync', 'remote']);
|
||||
|
||||
export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: string[] } {
|
||||
const cliOpts: CliOptions = { ...DEFAULT_CLI_OPTIONS };
|
||||
const rest: string[] = [];
|
||||
// #3013: --timeout can't be resolved inline — whether the GLOBAL parser
|
||||
// claims it depends on which command is running, and the command token is
|
||||
// only known once the whole argv has been scanned (global flags may precede
|
||||
// it). The scan collects positional slots; --timeout slots are resolved in
|
||||
// a second pass below.
|
||||
type Slot =
|
||||
| { plain: string }
|
||||
| { timeoutValue: string; equalsForm: boolean };
|
||||
const slots: Slot[] = [];
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
@@ -74,7 +94,7 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
|
||||
continue;
|
||||
}
|
||||
// not a number — let per-command parser handle; pass through
|
||||
rest.push(a);
|
||||
slots.push({ plain: a });
|
||||
continue;
|
||||
}
|
||||
if (a.startsWith('--progress-interval=')) {
|
||||
@@ -84,29 +104,20 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
|
||||
cliOpts.progressInterval = parsed;
|
||||
continue;
|
||||
}
|
||||
rest.push(a);
|
||||
slots.push({ plain: a });
|
||||
continue;
|
||||
}
|
||||
// v0.31.1: --timeout=Ns or --timeout Ns. Accepts plain ms, "30s", "2m".
|
||||
if (a === '--timeout' && i + 1 < argv.length) {
|
||||
const next = argv[i + 1];
|
||||
const parsed = parseTimeout(next);
|
||||
if (parsed !== null) {
|
||||
cliOpts.timeoutMs = parsed;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
rest.push(a);
|
||||
// A following token that is itself a flag is NOT a value — leave it for
|
||||
// its own iteration (pre-#3013 behavior: an unparseable next token was
|
||||
// never consumed).
|
||||
if (a === '--timeout' && i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
|
||||
slots.push({ timeoutValue: argv[i + 1], equalsForm: false });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (a.startsWith('--timeout=')) {
|
||||
const val = a.slice('--timeout='.length);
|
||||
const parsed = parseTimeout(val);
|
||||
if (parsed !== null) {
|
||||
cliOpts.timeoutMs = parsed;
|
||||
continue;
|
||||
}
|
||||
rest.push(a);
|
||||
slots.push({ timeoutValue: a.slice('--timeout='.length), equalsForm: true });
|
||||
continue;
|
||||
}
|
||||
// v0.40.4 — --explain for `gbrain search/query` per-stage attribution.
|
||||
@@ -114,9 +125,50 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
|
||||
cliOpts.explain = true;
|
||||
continue;
|
||||
}
|
||||
rest.push(a);
|
||||
slots.push({ plain: a });
|
||||
}
|
||||
|
||||
// The command is the first plain token (matches `command = rest[0]` in
|
||||
// cli.ts). If it owns --timeout, every --timeout is handed back in the
|
||||
// space-separated spelling (the only form the owning parsers read; this
|
||||
// also normalizes `--timeout=60s`), value verbatim so the owning command
|
||||
// applies its own unit + validity rules (`sync`: bare integers are
|
||||
// SECONDS, `ms`/fractional rejected loudly; `remote` accepts `h`).
|
||||
// Handed-back flags are APPENDED after every other token: both owning
|
||||
// commands treat leading args as positional subcommands (`sync trigger`,
|
||||
// `remote ping`) and locate --timeout by scanning args, so appending can't
|
||||
// shadow a subcommand while duplicate flags keep their argv order (the
|
||||
// owning parsers' first-occurrence-wins precedence matches what the user
|
||||
// typed). Non-owning commands keep the pre-#3013 global behavior:
|
||||
// parseable values are claimed into cliOpts.timeoutMs (last one wins),
|
||||
// unparseable ones pass through in their original spelling for the
|
||||
// per-command parser.
|
||||
const commandSlot = slots.find((s): s is { plain: string } => 'plain' in s);
|
||||
const commandOwnsTimeout =
|
||||
commandSlot !== undefined && TIMEOUT_OWNING_COMMANDS.has(commandSlot.plain);
|
||||
|
||||
const rest: string[] = [];
|
||||
const handback: string[] = [];
|
||||
for (const s of slots) {
|
||||
if ('plain' in s) {
|
||||
rest.push(s.plain);
|
||||
continue;
|
||||
}
|
||||
if (commandOwnsTimeout) {
|
||||
handback.push('--timeout', s.timeoutValue);
|
||||
continue;
|
||||
}
|
||||
const parsed = parseTimeout(s.timeoutValue);
|
||||
if (parsed !== null) {
|
||||
cliOpts.timeoutMs = parsed;
|
||||
} else if (s.equalsForm) {
|
||||
rest.push(`--timeout=${s.timeoutValue}`);
|
||||
} else {
|
||||
rest.push('--timeout', s.timeoutValue);
|
||||
}
|
||||
}
|
||||
rest.push(...handback);
|
||||
|
||||
return { cliOpts, rest };
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,23 @@ export interface GBrainConfig {
|
||||
* config.json file-plane route is wired through today.
|
||||
*/
|
||||
voyage_api_key?: string;
|
||||
/**
|
||||
* Alibaba DashScope API key (#3500). File-plane slot so config.json's
|
||||
* `dashscope_api_key` reaches the dashscope / dashscope-rerank recipes:
|
||||
* file plane → buildGatewayConfig env dict → recipe reads
|
||||
* DASHSCOPE_API_KEY. Same fold pattern (and same DB-plane caveat) as
|
||||
* voyage_api_key above.
|
||||
*/
|
||||
dashscope_api_key?: string;
|
||||
/**
|
||||
* Google Gemini API key (#3500). File-plane slot folded into the gateway
|
||||
* env as GOOGLE_GENERATIVE_AI_API_KEY (the name the google recipe reads).
|
||||
* buildGatewayConfig also accepts process-env GEMINI_API_KEY — the name
|
||||
* Google's own docs/SDKs use — as an alias for
|
||||
* GOOGLE_GENERATIVE_AI_API_KEY. Same fold pattern (and same DB-plane
|
||||
* caveat) as voyage_api_key above.
|
||||
*/
|
||||
google_api_key?: string;
|
||||
/** Azure OpenAI (keyless/Entra). Non-secret endpoint + deployment + Entra opt-in,
|
||||
* folded into the gateway env so the azure-openai recipe works in any shell.
|
||||
* The bearer token is minted at request time via `az` — no secret stored here. */
|
||||
@@ -919,6 +936,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
|
||||
'zeroentropy_api_key',
|
||||
'openrouter_api_key',
|
||||
'voyage_api_key',
|
||||
'dashscope_api_key',
|
||||
'google_api_key',
|
||||
'azure_openai_endpoint',
|
||||
'azure_openai_deployment',
|
||||
'azure_openai_use_entra',
|
||||
|
||||
@@ -145,6 +145,19 @@ export function computeCorpusGeneration(args: {
|
||||
return h.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* #3507 — the corpus_generation a page lands on when a plain re-embed path
|
||||
* (`embed --stale` and friends) re-embeds a `per_chunk_synopsis` page at the
|
||||
* title-only tier (the D14 fallback tier; synopsis re-generation is a paid
|
||||
* backfill concern). Callers restamp
|
||||
* `updatePageContextualRetrievalState(slug, sourceId, 'title', titleTierCorpusGeneration())`
|
||||
* so the stamped mode keeps describing the vectors actually in the column.
|
||||
* Matches what the inline import path writes for its title-tier pages.
|
||||
*/
|
||||
export function titleTierCorpusGeneration(): string {
|
||||
return computeCorpusGeneration({ crMode: 'title', haikuModel: DEFAULT_HAIKU_MODEL });
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute source_text_hash for D27 P1-4 cache key composition. The
|
||||
* synopsis cache invalidates correctly when adjacent text changes (page
|
||||
|
||||
@@ -51,7 +51,11 @@ export const DEFAULT_SLOTS: SlotConfig[] = [
|
||||
// 2-model quorum without a Google key (verdict: permanently inconclusive).
|
||||
{ id: 'A', model: 'openai:gpt-5.2' },
|
||||
{ id: 'B', model: 'anthropic:claude-opus-4-7' },
|
||||
{ id: 'C', model: 'google:gemini-1.5-pro' },
|
||||
// gemini-1.5-pro was retired by Google (#3510), so slot C failed even with
|
||||
// a Google key configured. deepseek:deepseek-v4-pro preserves the
|
||||
// three-distinct-provider contract with a model registered in both the
|
||||
// recipe and canonical pricing tables (same replacement as PR #3501).
|
||||
{ id: 'C', model: 'deepseek:deepseek-v4-pro' },
|
||||
];
|
||||
|
||||
export interface SlotConfig {
|
||||
|
||||
+14
-3
@@ -895,8 +895,17 @@ export async function resolveSourceForDir(
|
||||
// (the cycleSourceId precedence) or 'default'.
|
||||
if (brainDir === null) return undefined;
|
||||
try {
|
||||
// #2540: exclude archived rows (dream's --source guard refuses to stamp
|
||||
// them, so an archived alias winning here means the stamp silently never
|
||||
// lands and doctor's cycle_freshness stays red on a healthy install) and
|
||||
// order deterministically so a duplicate registration of the same path
|
||||
// can't shadow the active source on whichever row the engine scans first.
|
||||
// Ordering matches listAllSources/sources-ops for operator-output parity.
|
||||
const rows = await engine.executeRaw<{ id: string }>(
|
||||
`SELECT id FROM sources WHERE local_path = $1 LIMIT 1`,
|
||||
`SELECT id FROM sources
|
||||
WHERE local_path = $1 AND archived = false
|
||||
ORDER BY (id = 'default') DESC, id
|
||||
LIMIT 1`,
|
||||
[brainDir],
|
||||
);
|
||||
if (rows[0]) return rows[0].id;
|
||||
@@ -1179,7 +1188,9 @@ async function runPhaseExtractFacts(
|
||||
summary: `extract_facts skipped: ${result.legacyRowsPending} legacy v0.31 facts pending fence backfill`,
|
||||
details: {
|
||||
legacyRowsPending: result.legacyRowsPending,
|
||||
hint: 'gbrain apply-migrations --yes',
|
||||
// A bare `apply-migrations --yes` no-ops once the v0.32.2 ledger
|
||||
// entry is complete; the retry marker is what re-runs Phase B.
|
||||
hint: 'gbrain apply-migrations --force-retry 0.32.2 && gbrain apply-migrations --yes',
|
||||
warnings: result.warnings,
|
||||
},
|
||||
};
|
||||
@@ -2430,7 +2441,7 @@ export async function runCycle(
|
||||
try {
|
||||
const { runSchemaSuggestPhase } = await import('./cycle/schema-suggest.ts');
|
||||
const { result, duration_ms } = await timePhase(async () => {
|
||||
const r = await runSchemaSuggestPhase(engine, { dryRun: !!opts.dryRun });
|
||||
const r = await runSchemaSuggestPhase(engine, { sourceId: cycleSourceId, dryRun: !!opts.dryRun });
|
||||
return {
|
||||
phase: 'schema-suggest' as const,
|
||||
status: (r.skipped ? 'skipped' : 'ok') as PhaseStatus,
|
||||
|
||||
@@ -482,24 +482,52 @@ export async function runPhaseExtractAtoms(
|
||||
}
|
||||
|
||||
// 3. Dual-source merge: transcripts + pages, dedup by contentHash.
|
||||
// Transcripts win on collision (origin attribution stays with the
|
||||
// raw transcript file even if the same content was later imported
|
||||
// as a brain page).
|
||||
// Transcripts win on COLLISION (origin attribution stays with the raw
|
||||
// transcript file even if the same content was later imported as a
|
||||
// brain page) — that's decided by the two loops below, which register
|
||||
// every transcript hash into `seenHashes` before any page is checked,
|
||||
// same as before this fix. It's independent of the FINAL work-item
|
||||
// ORDER built after them.
|
||||
//
|
||||
// Order is page-item-first, interleaved 1-for-1 with transcripts (NOT
|
||||
// concatenated transcripts-then-pages). The per-call budget cap (step
|
||||
// 4 below) stops processing `work` in list order once
|
||||
// budgetTracker.totalSpent >= budgetCap, skipping everything after
|
||||
// that point. Two failure modes this avoids:
|
||||
// - Concatenation (old code): a transcript corpus that alone
|
||||
// exceeds the budget cap starves the page pool completely, no
|
||||
// matter how many drain batches run.
|
||||
// - Interleaving with transcripts first: still starves ALL pages
|
||||
// whenever the budget only covers exactly one call (item 0 is a
|
||||
// transcript, item 1 — the first page — never gets attempted).
|
||||
// Pages are the ONLY pool `countExtractAtomsBacklog`/doctor's
|
||||
// extract_atoms_backlog check measures (see that function's
|
||||
// docstring), so page-first guarantees the doctor-visible backlog
|
||||
// makes forward progress on every budget-capped call, however tight
|
||||
// the cap — `--drain` can no longer report the same backlog number
|
||||
// forever while atoms keep getting extracted from transcripts.
|
||||
type WorkItem =
|
||||
| { kind: 'transcript'; filePath: string; content: string; contentHash: string }
|
||||
| { kind: 'page'; slug: string; content: string; contentHash: string };
|
||||
|
||||
const seenHashes = new Set<string>();
|
||||
const work: WorkItem[] = [];
|
||||
const transcriptItems: WorkItem[] = [];
|
||||
for (const t of transcriptsLive) {
|
||||
if (seenHashes.has(t.contentHash)) { duplicatesSkipped++; continue; }
|
||||
seenHashes.add(t.contentHash);
|
||||
work.push({ kind: 'transcript', ...t });
|
||||
transcriptItems.push({ kind: 'transcript', ...t });
|
||||
}
|
||||
const pageItems: WorkItem[] = [];
|
||||
for (const p of pages) {
|
||||
if (seenHashes.has(p.contentHash)) { duplicatesSkipped++; continue; }
|
||||
seenHashes.add(p.contentHash);
|
||||
work.push({ kind: 'page', ...p });
|
||||
pageItems.push({ kind: 'page', ...p });
|
||||
}
|
||||
const work: WorkItem[] = [];
|
||||
const maxPoolLen = Math.max(transcriptItems.length, pageItems.length);
|
||||
for (let i = 0; i < maxPoolLen; i++) {
|
||||
if (i < pageItems.length) work.push(pageItems[i]);
|
||||
if (i < transcriptItems.length) work.push(transcriptItems[i]);
|
||||
}
|
||||
|
||||
// Phase-level no-op: nothing to extract today.
|
||||
|
||||
@@ -26,13 +26,17 @@
|
||||
*
|
||||
* Empty-fence guard (Codex R2-#7; #2484; #2646): the phase refuses to do
|
||||
* its destructive reconciliation pass when genuinely-backfillable legacy
|
||||
* rows still exist — `row_num IS NULL` (never fenced) AND `entity_slug`
|
||||
* resolves to a live page in this source (so the v0_32_2 migration's
|
||||
* Phase B could fence them) AND the row is not soft-expired
|
||||
* (`expired_at IS NULL`). Status returns `warn` with a hint to run
|
||||
* `gbrain apply-migrations --yes`. Without the guard, an interrupted
|
||||
* upgrade where v0_32_2 hasn't run could leave the cycle silently
|
||||
* misreporting "0 facts on people/alice" while legacy rows linger.
|
||||
* rows still exist — in THIS run's source only (`source_id = sourceId`;
|
||||
* a pending row in source A must not jam extraction for source B — the
|
||||
* source-isolation invariant) — `row_num IS NULL` (never fenced) AND
|
||||
* `entity_slug` resolves to a live page in this source (so the v0_32_2
|
||||
* migration's Phase B could fence them) AND the row is not soft-expired
|
||||
* (`expired_at IS NULL`). Status returns `warn` with a hint to re-run
|
||||
* the v0.32.2 fence backfill (`apply-migrations --force-retry 0.32.2`
|
||||
* then `--yes` — a bare `--yes` is a no-op once the ledger says
|
||||
* complete). Without the guard, an interrupted upgrade where v0_32_2
|
||||
* hasn't run could leave the cycle silently misreporting "0 facts on
|
||||
* people/alice" while legacy rows linger.
|
||||
*
|
||||
* The live-page requirement (#2484) is load-bearing: the inline facts
|
||||
* writer keeps producing `row_num IS NULL, entity_slug IS NOT NULL`
|
||||
@@ -225,10 +229,17 @@ export async function runExtractFacts(
|
||||
// soft-expires legacy rows rather than deleting them, so counting
|
||||
// expired rows would leave the guard permanently stuck with no
|
||||
// supported way to drain the backlog.
|
||||
//
|
||||
// Source isolation (#3526): the count is scoped to THIS run's
|
||||
// sourceId. The pre-fix query counted brain-wide, so a single pending
|
||||
// legacy row in any mounted source jammed extract_facts for every
|
||||
// source — a cross-source leak of one source's migration state into
|
||||
// another's cycle (CLAUDE.md source-isolation invariant).
|
||||
const legacy = await engine.executeRaw<{ n: string }>(
|
||||
`SELECT COUNT(*) AS n
|
||||
FROM facts f
|
||||
WHERE f.row_num IS NULL
|
||||
WHERE f.source_id = $1
|
||||
AND f.row_num IS NULL
|
||||
AND f.entity_slug IS NOT NULL
|
||||
AND f.expired_at IS NULL
|
||||
AND EXISTS (
|
||||
@@ -237,15 +248,25 @@ export async function runExtractFacts(
|
||||
AND p.slug = f.entity_slug
|
||||
AND p.deleted_at IS NULL
|
||||
)`,
|
||||
[sourceId],
|
||||
);
|
||||
const legacyCount = parseInt(legacy[0]?.n ?? '0', 10);
|
||||
result.legacyRowsPending = legacyCount;
|
||||
if (legacyCount > 0) {
|
||||
result.guardTriggered = true;
|
||||
// Drain advice must actually work: a bare `apply-migrations --yes`
|
||||
// is a no-op once the v0.32.2 ledger entry says complete (the
|
||||
// runner classifies it as already-applied), so the sanctioned
|
||||
// re-run path is the explicit retry marker first. Phase B is
|
||||
// idempotent — it only touches `row_num IS NULL` rows and de-dupes
|
||||
// against the existing fence — so the re-run is safe. Individual
|
||||
// rows can instead be drained through `forget_fact` (soft-expired
|
||||
// rows stop counting).
|
||||
result.warnings.push(
|
||||
`extract_facts: ${legacyCount} legacy v0.31 fact rows (entity page present, not yet ` +
|
||||
`fenced) pending fence backfill. Run \`gbrain apply-migrations --yes\` to complete ` +
|
||||
`v0_32_2 before this phase can safely reconcile fence → DB.`,
|
||||
`extract_facts: ${legacyCount} legacy v0.31 fact rows in source "${sourceId}" ` +
|
||||
`(entity page present, not yet fenced) pending fence backfill. Re-run the v0.32.2 ` +
|
||||
`fence backfill: \`gbrain apply-migrations --force-retry 0.32.2\` then ` +
|
||||
`\`gbrain apply-migrations --yes\`. Or drain individual rows via \`forget_fact\`.`,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ export interface GradeTakesOpts extends BasePhaseOpts {
|
||||
/**
|
||||
* E2 ensemble judges. When useEnsemble=true and the single-model verdict
|
||||
* is borderline, all three judges are called in parallel via Promise.allSettled.
|
||||
* Defaults to [openai:gpt-4o, anthropic:claude-sonnet-4-6, google:gemini-1.5-pro]
|
||||
* Defaults to [openai:gpt-5.2, anthropic:claude-sonnet-4-6, google:gemini-2.0-flash]
|
||||
* via defaultJudge with model-string overrides. Tests inject deterministic
|
||||
* judges.
|
||||
*/
|
||||
|
||||
@@ -48,8 +48,9 @@ import { safeSplitIndex } from '../text-safe.ts';
|
||||
import { PAGE_SLUG_SEG } from '../cjk.ts';
|
||||
|
||||
// Slug grammar from validatePageSlug — shared via PAGE_SLUG_SEG (#738).
|
||||
// Used for the orchestrator-written summary index slug.
|
||||
const SUMMARY_SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`);
|
||||
// Used for the orchestrator-written summary index slug. `u` flag required
|
||||
// by PAGE_SLUG_SEG's \p{...} classes (#3417).
|
||||
const SUMMARY_SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'u');
|
||||
|
||||
// ── Model context budget (D1, D5, D7, D9) ─────────────────────────────
|
||||
|
||||
|
||||
@@ -145,6 +145,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
|
||||
'federation_health',
|
||||
'home_dir_in_worktree',
|
||||
'index_audit',
|
||||
'npm_squat',
|
||||
'oauth_confidential_client_health',
|
||||
'orphan_clones',
|
||||
'pgbouncer_prepare',
|
||||
|
||||
+17
-2
@@ -19,7 +19,8 @@
|
||||
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput } from './types.ts';
|
||||
import { embedBatchWithBackoff } from '../commands/embed.ts';
|
||||
import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from '../commands/embed.ts';
|
||||
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
|
||||
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
|
||||
import { AbortError } from './abort-check.ts';
|
||||
|
||||
@@ -189,8 +190,15 @@ export async function embedStaleForSource(
|
||||
const keySourceId = stale[0]?.source_id ?? sourceId;
|
||||
const slug = stale[0].slug;
|
||||
try {
|
||||
// #3507: fetch the page row for its title + stored CR mode so the
|
||||
// re-embed reproduces the page's wrapping convention instead of
|
||||
// silently stripping contextual prefixes (mirrors
|
||||
// src/commands/embed.ts:embedAllStale).
|
||||
const pageRow = await observed(pacer, () =>
|
||||
engine.getPage(slug, { sourceId: keySourceId }),
|
||||
);
|
||||
const embeddings = await embedFn(
|
||||
stale.map((c) => c.chunk_text),
|
||||
wrapChunkTextsForStoredMode(pageRow, stale),
|
||||
{ abortSignal: signal },
|
||||
);
|
||||
const existing = await observed(pacer, () =>
|
||||
@@ -233,6 +241,13 @@ export async function embedStaleForSource(
|
||||
engine.setPageEmbeddingSignature(slug, { sourceId: keySourceId, signature }),
|
||||
);
|
||||
}
|
||||
// #3507: a FULLY re-embedded per_chunk_synopsis page landed at the
|
||||
// title tier — keep the stamped mode honest (mixed pages stay as-is).
|
||||
if (stale.length === existing.length) {
|
||||
await observed(pacer, () =>
|
||||
restampIfDemotedToTitleTier(engine, pageRow, slug, keySourceId),
|
||||
);
|
||||
}
|
||||
result.embedded += stale.length;
|
||||
result.pagesProcessed += 1;
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -186,3 +186,41 @@ export function modeRequiresHaiku(mode: CRMode): boolean {
|
||||
export function modeRequiresWrapper(mode: CRMode): boolean {
|
||||
return mode !== 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* #3507 — build the embedding inputs for a re-embed of EXISTING chunk rows,
|
||||
* reproducing the wrapping convention the page's vectors were originally
|
||||
* built under (recorded in `pages.contextual_retrieval_mode`).
|
||||
*
|
||||
* Used by every plain re-embed path (`embed <slug>`, `embed --all`,
|
||||
* `embed --stale`, the embed-backfill Minion loop). Before this helper those
|
||||
* paths embedded raw `chunk_text`, so any re-embed — including the NORMAL
|
||||
* post-model-migration `embed --stale` — silently replaced context-wrapped
|
||||
* vectors with unwrapped ones, degrading retrieval with no signature change
|
||||
* to show for it.
|
||||
*
|
||||
* Convention rules (embed PRESERVES conventions; changing them is
|
||||
* sync/reindex's job):
|
||||
* - mode NULL/undefined/'none' → raw chunk_text (status quo).
|
||||
* - mode 'title' → title-only prefix (pure string concat).
|
||||
* - mode 'per_chunk_synopsis' → title-only prefix. Re-generating Haiku
|
||||
* synopses is a paid backfill concern; title-only is the service's own
|
||||
* documented fallback tier (D14). Callers that fully re-embed a page
|
||||
* this way should restamp the page to 'title' so the column stays
|
||||
* honest (see contextual-retrieval-service.ts:titleTierCorpusGeneration).
|
||||
* - `fenced_code` chunks are NEVER wrapped (D20-T4), same as sync.
|
||||
*/
|
||||
export function wrapChunkTextsForStoredMode(
|
||||
page:
|
||||
| { title?: string | null; contextual_retrieval_mode?: CRMode | null }
|
||||
| null
|
||||
| undefined,
|
||||
chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null }>,
|
||||
): string[] {
|
||||
const mode = page?.contextual_retrieval_mode;
|
||||
if (mode == null || !modeRequiresWrapper(mode)) {
|
||||
return chunks.map((c) => c.chunk_text);
|
||||
}
|
||||
const prefix = buildContextualPrefix(page?.title ?? '', null);
|
||||
return chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source));
|
||||
}
|
||||
|
||||
@@ -5,12 +5,15 @@
|
||||
* cost-estimate prompt so users with large brains see a dollar figure
|
||||
* before the chunker-version sweep re-embeds.
|
||||
*
|
||||
* Prices in USD per 1M tokens. Numbers as of 2026-05-11. Verify alongside
|
||||
* the Anthropic-pricing refresh cycle; drift here produces estimates
|
||||
* that mislead operators.
|
||||
* Prices in USD per 1M tokens. Every entry carries the official page it came
|
||||
* from plus the date it was last read against that page — re-verify alongside
|
||||
* the Anthropic-pricing refresh cycle; drift here produces estimates that
|
||||
* mislead operators. This table is for EMBEDDINGS only; chat/completion
|
||||
* pricing lives in `model-pricing.ts` (different unit) and must never be
|
||||
* mixed in here.
|
||||
*
|
||||
* Codex outside-voice C3 fold: non-OpenAI embedding providers (Voyage,
|
||||
* Hunyuan, Dashscope, etc.) return UNKNOWN_PROVIDER from `lookupPrice`
|
||||
* Codex outside-voice C3 fold: embedding providers with no entry below
|
||||
* (Hunyuan, Dashscope, etc.) return UNKNOWN_PROVIDER from `lookupPrice`
|
||||
* so the cost-estimate prompt can fall back to a "estimate unavailable
|
||||
* for <provider>; press Ctrl-C in 10s to abort" message rather than
|
||||
* fabricate numbers.
|
||||
@@ -26,25 +29,33 @@ export interface EmbeddingPricing {
|
||||
* gateway model strings (e.g. 'openai:text-embedding-3-large').
|
||||
*/
|
||||
export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
|
||||
// OpenAI (https://openai.com/api/pricing/, verified 2026-05-11)
|
||||
// OpenAI (https://developers.openai.com/api/docs/pricing, verified 2026-07-28)
|
||||
'openai:text-embedding-3-large': { pricePerMTok: 0.13 },
|
||||
'openai:text-embedding-3-small': { pricePerMTok: 0.02 },
|
||||
// Legacy OpenAI ada (still common in older brains)
|
||||
'openai:text-embedding-ada-002': { pricePerMTok: 0.10 },
|
||||
// Voyage (https://www.voyageai.com/pricing)
|
||||
// Voyage (https://docs.voyageai.com/docs/pricing, verified 2026-07-28)
|
||||
'voyage:voyage-4-large': { pricePerMTok: 0.12 },
|
||||
'voyage:voyage-4': { pricePerMTok: 0.06 },
|
||||
'voyage:voyage-4-lite': { pricePerMTok: 0.02 },
|
||||
// voyage-4-nano is deliberately absent: it's the open-weight variant (see
|
||||
// src/core/ai/recipes/voyage.ts) and Voyage's pricing page lists no hosted
|
||||
// rate for it. A 0 entry would under-estimate anyone paying for it via the
|
||||
// hosted API; no entry means lookupEmbeddingPrice returns `unknown` and the
|
||||
// caller prints "estimate unavailable" instead of a wrong number.
|
||||
// Legacy Voyage models (same page, "older models" section — no free tokens):
|
||||
'voyage:voyage-3-large': { pricePerMTok: 0.18 },
|
||||
'voyage:voyage-3': { pricePerMTok: 0.06 },
|
||||
'voyage:voyage-4-large': { pricePerMTok: 0.18 },
|
||||
// ZeroEntropy (https://zeroentropy.dev/pricing — zembed-1)
|
||||
// ZeroEntropy (https://www.zeroentropy.dev/pricing, verified 2026-07-28)
|
||||
'zeroentropyai:zembed-1': { pricePerMTok: 0.05 },
|
||||
// ZeroEntropy reranker (docs/ai-providers/zeroentropy.md — $0.025/1M tokens).
|
||||
// Reused here (not a separate rerank table) because budget-tracker.ts's
|
||||
// rerank-kind lookup falls back to this same table for paid providers.
|
||||
'zeroentropyai:zerank-2': { pricePerMTok: 0.025 },
|
||||
// Mistral (https://mistral.ai/pricing/api/, verified 2026-07-19)
|
||||
// Mistral (https://mistral.ai/pricing/api/, verified 2026-07-28)
|
||||
'mistral:mistral-embed': { pricePerMTok: 0.10 },
|
||||
'mistral:mistral-embed-2312': { pricePerMTok: 0.10 },
|
||||
// Perplexity (https://docs.perplexity.ai/getting-started/pricing, verified 2026-07-21)
|
||||
// Perplexity (https://docs.perplexity.ai/getting-started/pricing, verified 2026-07-28)
|
||||
'perplexity:pplx-embed-v1-0.6b': { pricePerMTok: 0.004 },
|
||||
'perplexity:pplx-embed-v1-4b': { pricePerMTok: 0.03 },
|
||||
};
|
||||
|
||||
+6
-1
@@ -1951,8 +1951,13 @@ export interface BrainEngine {
|
||||
* preserved via stable page_id). `opts.sourceId` scopes the UPDATE — without
|
||||
* it, the bare `WHERE slug = old` matches every row across every source and
|
||||
* would either rename them all OR violate the (source_id, slug) UNIQUE.
|
||||
*
|
||||
* Returns the number of rows moved. 0 means the old slug had no row in the
|
||||
* scoped source — an UPDATE that matches nothing does NOT throw, so callers
|
||||
* that need to know whether the rename actually happened (the sync rename
|
||||
* path, #3056) must check the return value rather than rely on the catch.
|
||||
*/
|
||||
updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<void>;
|
||||
updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<number>;
|
||||
rewriteLinks(oldSlug: string, newSlug: string): Promise<void>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -85,11 +85,21 @@ const RUN_ID_SHORT_LEN = 8;
|
||||
/**
|
||||
* Truncate a run id to the standard 8-char short form used in slug
|
||||
* paths. Idempotent — passing an already-short id returns it unchanged.
|
||||
* Non-hex / non-alphanumeric chars survive (op-checkpoint ids may
|
||||
* include dashes or other separators).
|
||||
* Non-hex / non-alphanumeric chars survive INSIDE the short form
|
||||
* (op-checkpoint ids may include dashes or other separators), but
|
||||
* boundary hyphens are trimmed (#3443): `slugifySegment()` strips
|
||||
* leading/trailing hyphens during repo sync, so a short form like
|
||||
* 'propose-' (from propose-<timestamp> run ids) made the DB receipt
|
||||
* slug and its Git-backed slug disagree — writing the receipt through
|
||||
* to the repo created a normalized sibling instead of materializing
|
||||
* the existing page. Invariant: slugifySegment(shortRunId(x)) ===
|
||||
* shortRunId(x) for slug-safe run ids.
|
||||
*/
|
||||
export function shortRunId(runId: string): string {
|
||||
return runId.slice(0, RUN_ID_SHORT_LEN);
|
||||
// ponytail: truncation-based discrimination is only as good as the run id's
|
||||
// first 8 chars; families that need per-run uniqueness must front-load it.
|
||||
const short = runId.slice(0, RUN_ID_SHORT_LEN).replace(/^-+|-+$/g, '');
|
||||
return short || (runId ? 'run' : '');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+51
-5
@@ -39,6 +39,7 @@ import { normalizeAliasList } from './search/alias-normalize.ts';
|
||||
import { isUndefinedTableError, warnOncePerProcess, validateSlug } from './utils.ts';
|
||||
import { computeCorpusGeneration } from './contextual-retrieval-service.ts';
|
||||
import { runGuardrails } from './guardrails.ts';
|
||||
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from './facts-fence.ts';
|
||||
|
||||
/**
|
||||
* v0.20.0 Cathedral II Layer 8 D2 — markdown fence extraction helper.
|
||||
@@ -104,6 +105,27 @@ function fenceTagToPseudoPath(lang: string | undefined): string | null {
|
||||
*/
|
||||
const MAX_FENCES_PER_PAGE = Number.parseInt(process.env.GBRAIN_MAX_FENCES_PER_PAGE || '100', 10);
|
||||
|
||||
function extractFactsFenceBlock(body: string): string | null {
|
||||
const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
|
||||
if (beginIdx === -1) return null;
|
||||
const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
|
||||
if (endIdx === -1) return null;
|
||||
return body.slice(beginIdx, endIdx + FACTS_FENCE_END.length);
|
||||
}
|
||||
|
||||
function replaceOrAppendFactsFence(body: string, fenceBlock: string): string {
|
||||
const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
|
||||
if (beginIdx !== -1) {
|
||||
const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
|
||||
if (endIdx !== -1) {
|
||||
return body.slice(0, beginIdx) + fenceBlock + body.slice(endIdx + FACTS_FENCE_END.length);
|
||||
}
|
||||
}
|
||||
|
||||
const sep = body.endsWith('\n') ? '\n' : '\n\n';
|
||||
return `${body}${sep}## Facts\n\n${fenceBlock}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the marked lexer output and extract recognizable code fences.
|
||||
* Returns one ChunkInput per fence whose language tag maps to a grammar
|
||||
@@ -548,6 +570,26 @@ export async function importFromContent(
|
||||
// hash-match skip) and (b) the hash short-circuit below reuses this row.
|
||||
const existing = await engine.getPage(slug, sourceId ? { sourceId } : undefined);
|
||||
|
||||
// #2044: remote get_page intentionally strips private facts rows. A
|
||||
// documented get_page -> edit -> put_page round-trip can therefore arrive
|
||||
// with an empty/missing Facts fence even though the existing page still has
|
||||
// canonical fence rows. Preserve the old fence in that narrow case so the
|
||||
// system-of-record markdown is not truncated by the privacy boundary.
|
||||
if (opts.remote === true && existing?.compiled_truth) {
|
||||
const incomingFacts = parseFactsFence(parsed.compiled_truth);
|
||||
const existingFacts = parseFactsFence(existing.compiled_truth);
|
||||
const existingFenceBlock = extractFactsFenceBlock(existing.compiled_truth);
|
||||
if (
|
||||
incomingFacts.facts.length === 0 &&
|
||||
incomingFacts.warnings.length === 0 &&
|
||||
existingFacts.warnings.length === 0 &&
|
||||
existingFacts.facts.length > 0 &&
|
||||
existingFenceBlock
|
||||
) {
|
||||
parsed.compiled_truth = replaceOrAppendFactsFence(parsed.compiled_truth, existingFenceBlock);
|
||||
}
|
||||
}
|
||||
|
||||
// #1035: absence of an explicit frontmatter `type:` on an EXISTING page
|
||||
// means "preserve the stored type", not "re-infer". Pre-fix, a round-trip
|
||||
// put (get_page → edit body → put_page without `type:`) silently regressed
|
||||
@@ -1092,8 +1134,8 @@ export async function importFromFile(
|
||||
chunks: 0,
|
||||
error:
|
||||
`Filename "${relativePath}" produces no usable slug. ` +
|
||||
`Add a "slug:" to the frontmatter, or rename the file to use ` +
|
||||
`ASCII / Chinese / Japanese / Korean characters.`,
|
||||
`Add a "slug:" to the frontmatter, or rename the file to include ` +
|
||||
`at least one letter or number (any script).`,
|
||||
};
|
||||
}
|
||||
} else if (parsed.slug !== expectedSlug) {
|
||||
@@ -1161,6 +1203,10 @@ export async function importCodeFile(
|
||||
const title = `${relativePath} (${lang})`;
|
||||
const sourceId = opts.sourceId;
|
||||
const txOpts = sourceId ? { sourceId } : undefined;
|
||||
// PostgreSQL text columns reject U+0000 even though source files may
|
||||
// legitimately contain it inside string/regex fixtures. Preserve a visible,
|
||||
// searchable representation instead of dropping the entire code page.
|
||||
const storageContent = content.replaceAll('\0', '\\0');
|
||||
|
||||
const byteLength = Buffer.byteLength(content, 'utf-8');
|
||||
if (byteLength > MAX_FILE_SIZE) {
|
||||
@@ -1202,7 +1248,7 @@ export async function importCodeFile(
|
||||
// from the chunker (nested methods carry ['ClassName'] etc.) so the
|
||||
// chunk-grain FTS trigger picks up scope for ranking and downstream
|
||||
// Layer 5 edge resolution can use scope-qualified identity.
|
||||
const { chunks: codeChunks, edges: extractedEdges } = await chunkCodeTextFull(content, relativePath);
|
||||
const { chunks: codeChunks, edges: extractedEdges } = await chunkCodeTextFull(storageContent, relativePath);
|
||||
const chunks: ChunkInput[] = codeChunks.map((c, i) => ({
|
||||
chunk_index: i,
|
||||
chunk_text: c.text,
|
||||
@@ -1270,7 +1316,7 @@ export async function importCodeFile(
|
||||
type: 'code' as string,
|
||||
page_kind: 'code',
|
||||
title,
|
||||
compiled_truth: content,
|
||||
compiled_truth: storageContent,
|
||||
timeline: '',
|
||||
frontmatter: { language: lang, file: relativePath },
|
||||
content_hash: hash,
|
||||
@@ -1342,7 +1388,7 @@ export async function importCodeFile(
|
||||
|
||||
const edgeInputs: import('./types.ts').CodeEdgeInput[] = [];
|
||||
for (const e of extractedEdges) {
|
||||
const idx = findChunkForOffset(e.callSiteByteOffset, content, rangeList);
|
||||
const idx = findChunkForOffset(e.callSiteByteOffset, storageContent, rangeList);
|
||||
if (idx == null) continue;
|
||||
const from = rangeList[idx]!;
|
||||
if (!from.id || !from.symbol_name_qualified) continue;
|
||||
|
||||
@@ -28,10 +28,11 @@ import { ensureWellFormed } from './text-safe.ts';
|
||||
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
|
||||
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
|
||||
*/
|
||||
// 2026-07-10: bumped for the #2576 --stale nullResolver fix — sweeps before it
|
||||
// stamped pages with their bare wikilinks silently dropped; the bump re-flags
|
||||
// them so the fixed sweep re-extracts.
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-07-10T00:00:00Z';
|
||||
// 2026-07-30: bumped for the #3466 inferTypeByDir fix — unevidenced
|
||||
// people/ -> companies/ adjacency now infers 'mentions' instead of
|
||||
// 'works_at'; the bump re-flags stamped pages so the next --stale sweep
|
||||
// re-extracts them under the corrected inference.
|
||||
export const LINK_EXTRACTOR_VERSION_TS = '2026-07-30T00:00:00Z';
|
||||
|
||||
// ─── Entity references ──────────────────────────────────────────
|
||||
|
||||
|
||||
+17
-125
@@ -2,6 +2,13 @@ import type { BrainEngine } from './engine.ts';
|
||||
import { slugifyPath } from './sync.ts';
|
||||
import { getFtsLanguage } from './fts-language.ts';
|
||||
import { hnswMaxDimsForType } from './vector-index.ts';
|
||||
// runMigrations executes while an initialized engine is live. Keep its helper
|
||||
// modules in the static graph rather than importing them from async handlers.
|
||||
import {
|
||||
isStatementTimeoutError,
|
||||
isRetryableConnError,
|
||||
} from './retry-matcher.ts';
|
||||
import { repairTimelineDedupIndex } from './timeline-dedup-repair.ts';
|
||||
|
||||
/**
|
||||
* Schema migrations — run automatically on initSchema().
|
||||
@@ -539,18 +546,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
sql: '',
|
||||
handler: async (engine) => {
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
14,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'idx_pages_updated_at_desc' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS idx_pages_updated_at_desc';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 14, 'idx_pages_updated_at_desc');
|
||||
await engine.runMigration(
|
||||
14,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_pages_updated_at_desc
|
||||
@@ -1656,18 +1652,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
// 3. Partial index for the autopilot purge sweep. Postgres CONCURRENTLY
|
||||
// avoids the SHARE lock on `pages`; PGLite has no concurrent writers.
|
||||
if (engine.kind === 'postgres') {
|
||||
// Pre-drop any invalid index from a prior CONCURRENTLY failure (matches v14 pattern).
|
||||
await engine.runMigration(34, `
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_deleted_at_purge_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_deleted_at_purge_idx';
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
await dropInvalidConcurrentIndex(engine, 34, 'pages_deleted_at_purge_idx');
|
||||
await engine.runMigration(34, `
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_deleted_at_purge_idx
|
||||
ON pages (deleted_at) WHERE deleted_at IS NOT NULL;
|
||||
@@ -2004,18 +1989,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
|
||||
// 2. Expression index for since/until date-range filters.
|
||||
if (engine.kind === 'postgres') {
|
||||
// Pre-drop any invalid index from a prior CONCURRENTLY failure.
|
||||
await engine.runMigration(38, `
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_coalesce_date_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_coalesce_date_idx';
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
await dropInvalidConcurrentIndex(engine, 38, 'pages_coalesce_date_idx');
|
||||
await engine.runMigration(38, `
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_coalesce_date_idx
|
||||
ON pages ((COALESCE(effective_date, updated_at)));
|
||||
@@ -3577,19 +3551,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
sql: '',
|
||||
handler: async (engine) => {
|
||||
if (engine.kind === 'postgres') {
|
||||
// Pre-drop invalid remnant from a failed CONCURRENTLY attempt.
|
||||
await engine.runMigration(
|
||||
71,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'takes_resolved_at_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS takes_resolved_at_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 71, 'takes_resolved_at_idx');
|
||||
await engine.runMigration(
|
||||
71,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS takes_resolved_at_idx
|
||||
@@ -4249,20 +4211,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
await engine.runMigration(91, columnsAndTrigger);
|
||||
|
||||
if (engine.kind === 'postgres') {
|
||||
// Pre-drop any invalid index from a prior CONCURRENTLY failure
|
||||
// (matches v14 pattern).
|
||||
await engine.runMigration(
|
||||
91,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_generation_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_generation_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 91, 'pages_generation_idx');
|
||||
await engine.runMigration(
|
||||
91,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_generation_idx ON pages (generation);`
|
||||
@@ -4516,18 +4465,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
sql: '',
|
||||
handler: async (engine) => {
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
96,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'idx_facts_extract_conversation_session' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS idx_facts_extract_conversation_session';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 96, 'idx_facts_extract_conversation_session');
|
||||
await engine.runMigration(
|
||||
96,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_facts_extract_conversation_session
|
||||
@@ -4569,18 +4507,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
transaction: false,
|
||||
handler: async (engine) => {
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
97,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_dedup_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_dedup_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 97, 'pages_dedup_idx');
|
||||
await engine.runMigration(
|
||||
97,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_dedup_idx
|
||||
@@ -4748,18 +4675,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
);
|
||||
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
103,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'content_chunks_stale_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS content_chunks_stale_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 103, 'content_chunks_stale_idx');
|
||||
await engine.runMigration(
|
||||
103,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS content_chunks_stale_idx
|
||||
@@ -4793,18 +4709,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
sql: '',
|
||||
handler: async (engine) => {
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
104,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_atom_source_hash_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_atom_source_hash_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 104, 'pages_atom_source_hash_idx');
|
||||
await engine.runMigration(
|
||||
104,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_atom_source_hash_idx
|
||||
@@ -5105,18 +5010,7 @@ export const MIGRATIONS: Migration[] = [
|
||||
`ALTER TABLE pages ADD COLUMN IF NOT EXISTS links_extracted_at TIMESTAMPTZ;`
|
||||
);
|
||||
if (engine.kind === 'postgres') {
|
||||
await engine.runMigration(
|
||||
112,
|
||||
`DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
WHERE c.relname = 'pages_links_extracted_at_idx' AND NOT i.indisvalid
|
||||
) THEN
|
||||
EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_links_extracted_at_idx';
|
||||
END IF;
|
||||
END $$;`
|
||||
);
|
||||
await dropInvalidConcurrentIndex(engine, 112, 'pages_links_extracted_at_idx');
|
||||
await engine.runMigration(
|
||||
112,
|
||||
`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_links_extracted_at_idx
|
||||
@@ -5801,7 +5695,6 @@ async function runMigrationSQLWithRetry(
|
||||
m: Migration,
|
||||
sql: string,
|
||||
): Promise<void> {
|
||||
const { isStatementTimeoutError, isRetryableConnError } = await import('./retry-matcher.ts');
|
||||
// GBRAIN_MIGRATE_BACKOFF_MS lets tests skip the 5s/15s/45s backoff. In
|
||||
// production the env var is unset and the default cadence applies.
|
||||
const fastBackoff = process.env.GBRAIN_MIGRATE_BACKOFF_MS;
|
||||
@@ -6071,7 +5964,6 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
|
||||
// reach the loop below). Best-effort + idempotent: a no-op on a healthy
|
||||
// index; `doctor` surfaces it independently if this ever fails.
|
||||
try {
|
||||
const { repairTimelineDedupIndex } = await import('./timeline-dedup-repair.ts');
|
||||
const r = await repairTimelineDedupIndex(engine);
|
||||
if (r.repaired) {
|
||||
console.error(
|
||||
|
||||
@@ -43,6 +43,11 @@ export const HANDLER_DEFAULT_TIMEOUT_MS: Readonly<Record<string, number>> = {
|
||||
// few writes. Generous 10-min budget (vs the tight null-default) covers a
|
||||
// slow gateway without the 30-min loop budget.
|
||||
chronicle_extract: TEN_MIN_MS,
|
||||
// #3207 — same shape as chronicle_extract: one page = one LLM extraction
|
||||
// call + a few writes. Was missing from this map, so it inherited the tight
|
||||
// null-default and got dead-lettered mid-generation on slow chat providers
|
||||
// (facts silently lost) — exactly the failure this file exists to prevent.
|
||||
'facts-absorb': TEN_MIN_MS,
|
||||
// Per-page contextual reindex jobs process chunks sequentially with one
|
||||
// rate-leased LLM synopsis call per chunk; large transcript pages need more
|
||||
// than the standard 30-min long-job budget.
|
||||
|
||||
@@ -534,10 +534,21 @@ export class MinionQueue {
|
||||
}
|
||||
|
||||
/** Prune old jobs in terminal statuses. Returns count of deleted rows. */
|
||||
async prune(opts?: { olderThan?: Date; status?: MinionJobStatus[] }): Promise<number> {
|
||||
async prune(opts?: { olderThan?: Date; status?: MinionJobStatus[]; dryRun?: boolean }): Promise<number> {
|
||||
const statuses = opts?.status ?? ['completed', 'dead', 'cancelled'];
|
||||
const olderThan = opts?.olderThan ?? new Date(Date.now() - 30 * 86400000);
|
||||
|
||||
// #2712: dryRun counts the would-be-pruned rows without deleting.
|
||||
// Silent-ignoring a safety flag on a delete path is data loss.
|
||||
if (opts?.dryRun) {
|
||||
const rows = await this.engine.executeRaw<{ count: string }>(
|
||||
`SELECT count(*)::text as count FROM minion_jobs
|
||||
WHERE status = ANY($1) AND updated_at < $2`,
|
||||
[statuses, olderThan.toISOString()]
|
||||
);
|
||||
return parseInt(rows[0]?.count ?? '0', 10);
|
||||
}
|
||||
|
||||
const rows = await this.engine.executeRaw<{ count: string }>(
|
||||
`WITH pruned AS (
|
||||
DELETE FROM minion_jobs
|
||||
|
||||
@@ -84,6 +84,9 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {
|
||||
'openai:gpt-5.5': { input: 4.00, output: 16.00 },
|
||||
|
||||
// ── Google ─────────────────────────────────────────────────────────────
|
||||
// `gemini-1.5-pro` was retired by Google (#3510); kept so historical
|
||||
// usage/audit rows still price. Not a valid default — it's deliberately
|
||||
// absent from the google recipe's chat list.
|
||||
'google:gemini-1.5-pro': { input: 1.25, output: 5.00 },
|
||||
// Gemini 2.0 Flash: $0.10 in / $0.40 out (verified 2026-06-03). Reconciled
|
||||
// from a stale $0.30/$1.20 entry that had drifted in takes-quality-eval.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* npm-squat-check — classify `gbrain` binaries found on PATH (#505).
|
||||
*
|
||||
* The npm registry name `gbrain` belongs to an unrelated third-party package;
|
||||
* this project is NOT distributed on npm. A reflexive `npm i -g gbrain` /
|
||||
* `bun add -g gbrain` therefore installs something that is not this project
|
||||
* and can shadow the real binary on PATH.
|
||||
*
|
||||
* Pure classification helpers (filesystem-only, no network, no shelling out)
|
||||
* so `gbrain doctor` can warn with receipts. The caller supplies the candidate
|
||||
* paths (typically the output of `which -a gbrain`).
|
||||
*/
|
||||
import { closeSync, openSync, readFileSync, readSync, realpathSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
export type GbrainBinaryKind = 'real' | 'foreign' | 'broken' | 'unknown';
|
||||
|
||||
export interface ClassifiedGbrainBinary {
|
||||
/** The candidate path as given (PATH entry / symlink). */
|
||||
path: string;
|
||||
kind: GbrainBinaryKind;
|
||||
/** Human-readable evidence for the classification. */
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface NpmSquatAssessment {
|
||||
status: 'ok' | 'warn' | 'skip';
|
||||
message: string;
|
||||
binaries: ClassifiedGbrainBinary[];
|
||||
}
|
||||
|
||||
/** Repository marker identifying this project's package.json. */
|
||||
const REAL_REPO_MARKER = 'garrytan/gbrain';
|
||||
|
||||
/** The documented install/remediation path, reused in doctor output. */
|
||||
export const NPM_SQUAT_REMEDIATION =
|
||||
`Remove the unrelated package (\`bun remove -g gbrain\` or \`npm uninstall -g gbrain\`) ` +
|
||||
`and install/upgrade only via the documented path: \`bun install -g github:${REAL_REPO_MARKER}\` ` +
|
||||
`(or \`git clone https://github.com/${REAL_REPO_MARKER}.git && bun install && bun link\`).`;
|
||||
|
||||
/**
|
||||
* A `bun build --compile` gbrain binary is a native executable, not a script.
|
||||
* Sniff the magic bytes: ELF, Mach-O (thin + fat), PE.
|
||||
*/
|
||||
function isNativeExecutable(path: string): boolean {
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
fd = openSync(path, 'r');
|
||||
const buf = Buffer.alloc(4);
|
||||
if (readSync(fd, buf, 0, 4, 0) < 4) return false;
|
||||
const be = buf.readUInt32BE(0);
|
||||
const le = buf.readUInt32LE(0);
|
||||
return (
|
||||
be === 0x7f454c46 || // ELF
|
||||
be === 0xcafebabe || be === 0xcafebabf || // fat Mach-O
|
||||
le === 0xfeedface || le === 0xfeedfacf || // Mach-O 32/64
|
||||
(buf[0] === 0x4d && buf[1] === 0x5a) // PE ("MZ")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/** Walk up from `start` to the nearest parseable package.json. */
|
||||
function nearestPackageJson(start: string): { dir: string; pkg: Record<string, any> } | null {
|
||||
let cur = start;
|
||||
for (let depth = 0; depth < 64; depth++) {
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(cur, 'package.json'), 'utf8'));
|
||||
if (pkg && typeof pkg === 'object') return { dir: cur, pkg };
|
||||
} catch {
|
||||
// Missing or unparseable at this level; keep walking.
|
||||
}
|
||||
const parent = dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this package.json THIS project? Two markers, either suffices:
|
||||
* - repository field pointing at garrytan/gbrain (string or { url }), or
|
||||
* - this repo's known bin shape (`"bin": { "gbrain": "src/cli.ts" }` — a
|
||||
* git checkout / `bun install -g github:...` install carries it verbatim;
|
||||
* a registry-published package ships built JS, not a bare .ts bin).
|
||||
*/
|
||||
function isRealGbrainPackage(pkg: Record<string, any>): boolean {
|
||||
const repo = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url;
|
||||
if (typeof repo === 'string' && repo.includes(REAL_REPO_MARKER)) return true;
|
||||
if (pkg.bin && typeof pkg.bin === 'object' && pkg.bin.gbrain === 'src/cli.ts') return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one candidate `gbrain` path:
|
||||
* - 'broken' : symlink that doesn't resolve / unreadable path.
|
||||
* - 'real' : compiled gbrain binary, or a script whose nearest
|
||||
* package.json is this project's (repo checkout / bun link /
|
||||
* `bun install -g github:garrytan/gbrain`).
|
||||
* - 'foreign' : nearest package.json is named "gbrain" but is NOT this
|
||||
* project — an unrelated registry install.
|
||||
* - 'unknown' : can't tell (no gbrain package.json above the resolved file).
|
||||
*/
|
||||
export function classifyGbrainBinary(path: string): ClassifiedGbrainBinary {
|
||||
let resolved: string;
|
||||
try {
|
||||
resolved = realpathSync(path);
|
||||
} catch {
|
||||
return { path, kind: 'broken', detail: 'broken symlink or unreadable path' };
|
||||
}
|
||||
if (isNativeExecutable(resolved)) {
|
||||
return { path, kind: 'real', detail: `compiled gbrain binary at ${resolved}` };
|
||||
}
|
||||
const found = nearestPackageJson(dirname(resolved));
|
||||
if (!found || found.pkg.name !== 'gbrain') {
|
||||
return { path, kind: 'unknown', detail: `no gbrain package.json found above ${resolved}` };
|
||||
}
|
||||
if (isRealGbrainPackage(found.pkg)) {
|
||||
return { path, kind: 'real', detail: `this project's install at ${found.dir}` };
|
||||
}
|
||||
return {
|
||||
path,
|
||||
kind: 'foreign',
|
||||
detail: `unrelated npm package named "gbrain" at ${found.dir}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Assess candidate paths in PATH precedence order (first entry wins when the
|
||||
* shell runs `gbrain`).
|
||||
*
|
||||
* - skip : no candidates (gbrain not on PATH — nothing to check).
|
||||
* - warn : the winning entry is broken, or an unrelated npm package shadows
|
||||
* (appears before) the real binary — including when no real binary
|
||||
* is on PATH at all.
|
||||
* - ok : the winning entry is the real binary (an unrelated install
|
||||
* sitting BEHIND it is noted but not a warn).
|
||||
*/
|
||||
export function assessGbrainBinaries(candidates: string[]): NpmSquatAssessment {
|
||||
const unique = [...new Set(candidates.map((c) => c.trim()).filter(Boolean))];
|
||||
if (unique.length === 0) {
|
||||
return { status: 'skip', message: 'gbrain not found on PATH', binaries: [] };
|
||||
}
|
||||
const binaries = unique.map(classifyGbrainBinary);
|
||||
const first = binaries[0]!;
|
||||
const realIdx = binaries.findIndex((b) => b.kind === 'real');
|
||||
const foreignIdx = binaries.findIndex((b) => b.kind === 'foreign');
|
||||
|
||||
if (first.kind === 'broken') {
|
||||
return {
|
||||
status: 'warn',
|
||||
message:
|
||||
`\`gbrain\` on PATH is a broken link (${first.path}). ` +
|
||||
`Note: gbrain is NOT distributed on npm — the npm package named "gbrain" is unrelated. ` +
|
||||
NPM_SQUAT_REMEDIATION,
|
||||
binaries,
|
||||
};
|
||||
}
|
||||
if (foreignIdx !== -1 && (realIdx === -1 || foreignIdx < realIdx)) {
|
||||
const foreign = binaries[foreignIdx]!;
|
||||
return {
|
||||
status: 'warn',
|
||||
message:
|
||||
`\`gbrain\` on PATH resolves to an unrelated npm package, not this project ` +
|
||||
`(${foreign.path} — ${foreign.detail}). gbrain is NOT distributed on npm. ` +
|
||||
NPM_SQUAT_REMEDIATION,
|
||||
binaries,
|
||||
};
|
||||
}
|
||||
if (foreignIdx !== -1) {
|
||||
return {
|
||||
status: 'ok',
|
||||
message:
|
||||
`real gbrain wins on PATH (${first.path}), but an unrelated npm package named ` +
|
||||
`"gbrain" is also installed (${binaries[foreignIdx]!.path}). Consider removing it: ` +
|
||||
`\`bun remove -g gbrain\` / \`npm uninstall -g gbrain\`.`,
|
||||
binaries,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 'ok',
|
||||
message:
|
||||
first.kind === 'real'
|
||||
? `gbrain on PATH is the real binary (${first.path}).`
|
||||
: `no unrelated npm "gbrain" install detected on PATH (${first.path}).`,
|
||||
binaries,
|
||||
};
|
||||
}
|
||||
+42
-98
@@ -28,6 +28,7 @@ import { isSearchMode } from './search/mode.ts';
|
||||
import { stampEvidence } from './search/evidence.ts';
|
||||
import type { SearchResult } from './types.ts';
|
||||
import { CJK_SLUG_CHARS, PAGE_SLUG_SEG } from './cjk.ts';
|
||||
import { ALL_SOURCES } from './source-id.ts';
|
||||
import * as db from './db.ts';
|
||||
import { VERSION } from '../version.ts';
|
||||
import {
|
||||
@@ -162,10 +163,11 @@ export function validatePageSlug(slug: string): void {
|
||||
if (slug.length > 255) {
|
||||
throw new OperationError('invalid_params', 'page_slug exceeds 255 characters');
|
||||
}
|
||||
// v0.32.7: CJK ranges (Han / Hiragana / Katakana / Hangul Syllables) allowed
|
||||
// in segments. ASCII shape rules (lead char, hyphen continuation) preserved.
|
||||
if (!new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'i').test(slug)) {
|
||||
throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: alphanumeric, CJK, hyphens, forward-slash separated segments)`);
|
||||
// #3417: letters/numbers from any script allowed in segments (u flag required
|
||||
// for the \p{...} classes in PAGE_SLUG_SEG). Shape rules (lead char, hyphen
|
||||
// continuation) preserved.
|
||||
if (!new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {
|
||||
throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, hyphens, forward-slash separated segments)`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -486,6 +488,14 @@ export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sou
|
||||
// value of `[]` MUST NOT widen scope to "all sources" by being interpreted
|
||||
// as "no filter."
|
||||
if (allowed && allowed.length > 0) return { sourceIds: allowed };
|
||||
// #1712: the __all__ sentinel spans the brain — but ONLY for trusted local
|
||||
// callers (strictly `remote === false`). For remote/untrusted callers the
|
||||
// literal stays as-is: it can never match a real source id (underscores are
|
||||
// rejected at creation), so the read fail-closes to empty rather than
|
||||
// widening past the caller's grant. Do NOT "simplify" this to `{}`.
|
||||
if (ctx.sourceId === ALL_SOURCES) {
|
||||
return ctx.remote === false ? {} : { sourceId: ctx.sourceId };
|
||||
}
|
||||
if (ctx.sourceId) return { sourceId: ctx.sourceId };
|
||||
return {};
|
||||
}
|
||||
@@ -553,7 +563,7 @@ export function resolveRequestedScope(
|
||||
sourceIdParam: string | undefined,
|
||||
allSourcesParam = false,
|
||||
): { sourceId?: string; sourceIds?: string[] } {
|
||||
const wantsAll = allSourcesParam || sourceIdParam === '__all__';
|
||||
const wantsAll = allSourcesParam || sourceIdParam === ALL_SOURCES;
|
||||
if (wantsAll) {
|
||||
return ctx.remote === false ? {} : sourceScopeOpts(ctx);
|
||||
}
|
||||
@@ -1186,7 +1196,9 @@ const put_page: Operation = {
|
||||
let writerLint: { error_count: number; warning_count: number } | { skipped: string } | undefined;
|
||||
try {
|
||||
const { runPostWriteLint } = await import('./output/post-write.ts');
|
||||
const lint = await runPostWriteLint(ctx.engine, result.slug);
|
||||
const lint = await runPostWriteLint(ctx.engine, result.slug, {
|
||||
sourceId: ctx.sourceId ?? 'default',
|
||||
});
|
||||
if (lint.ran) {
|
||||
writerLint = {
|
||||
error_count: lint.findings.filter(f => f.severity === 'error').length,
|
||||
@@ -5031,7 +5043,7 @@ const schema_review_orphans: Operation = {
|
||||
|
||||
const schema_apply_mutations: Operation = {
|
||||
name: 'schema_apply_mutations',
|
||||
description: 'v0.40.7.0: batched schema pack mutation. ATOMIC: all mutations succeed or all roll back. Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.',
|
||||
description: 'v0.40.7.0: batched schema pack mutation. ATOMIC: every mutation is validated against an in-memory manifest first, and the pack file is written to disk at most once, after the FULL batch has proven valid — so a failure at any point leaves the pack file byte-identical to its pre-batch state (never a partial write). Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.',
|
||||
params: {
|
||||
pack: { type: 'string', required: true, description: 'Pack to mutate (must not be bundled)' },
|
||||
mutations: {
|
||||
@@ -5054,92 +5066,20 @@ const schema_apply_mutations: Operation = {
|
||||
const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const actor = ctx.auth?.clientId ? `mcp:${ctx.auth.clientId.slice(0, 8)}` : 'cli';
|
||||
const sourceId = ctx.sourceId; // codex C5: write-side scoping
|
||||
// Compose every mutation inside ONE withPackLock so the batch is
|
||||
// truly atomic. The withMutation skeleton handles audit / cache
|
||||
// invalidation per operation; we orchestrate the lock + iteration.
|
||||
const { withPackLock } = await import('./schema-pack/pack-lock.ts');
|
||||
const {
|
||||
addTypeToPack, removeTypeFromPack, updateTypeOnPack,
|
||||
addAliasToType, removeAliasFromType, addPrefixToType, removePrefixFromType,
|
||||
addLinkTypeToPack, removeLinkTypeFromPack,
|
||||
setExtractableOnType, setExpertRoutingOnType,
|
||||
SchemaPackMutationError,
|
||||
} = await import('./schema-pack/mutate.ts');
|
||||
const baseMutateOpts = {
|
||||
actor: actor as 'cli' | `mcp:${string}`,
|
||||
batchId,
|
||||
engine: ctx.engine,
|
||||
...(sourceId ? { sourceId } : {}),
|
||||
...(force ? { force: true } : {}),
|
||||
};
|
||||
const results: unknown[] = [];
|
||||
// `applyMutationsAtomic` (issue #2581) owns the lock + single read +
|
||||
// single write for the whole batch: every mutation is validated
|
||||
// in-memory first, and the pack file is written at most once, only
|
||||
// after the FULL batch checks out. That is what makes this actually
|
||||
// atomic (a failure at any index can never leave earlier mutations on
|
||||
// disk), vs. the old per-mutation-writes-as-it-goes shape.
|
||||
const { applyMutationsAtomic } = await import('./schema-pack/mutate.ts');
|
||||
try {
|
||||
// Outer lock: hold the pack for the whole batch so other writers
|
||||
// can't slip in between mutations.
|
||||
await withPackLock(pack, { force, lockDir: undefined }, async () => {
|
||||
for (let i = 0; i < mutations.length; i++) {
|
||||
const m = mutations[i]!;
|
||||
// Each primitive acquires the lock internally; the outer
|
||||
// withPackLock makes that re-entrant via fast-stale-detect
|
||||
// (--force option for the inner call). To keep semantics
|
||||
// simple, we pass {force:true} to the inner calls because
|
||||
// they're nested inside our outer lock — we already own it.
|
||||
const innerOpts = { ...baseMutateOpts, force: true };
|
||||
let r: unknown;
|
||||
switch (m.op) {
|
||||
case 'add_type':
|
||||
r = await addTypeToPack(pack, {
|
||||
name: m.name as string,
|
||||
primitive: m.primitive as never,
|
||||
prefix: m.prefix as string,
|
||||
extractable: m.extractable as boolean | undefined,
|
||||
expertRouting: m.expert_routing as boolean | undefined,
|
||||
aliases: m.aliases as string[] | undefined,
|
||||
}, innerOpts);
|
||||
break;
|
||||
case 'remove_type':
|
||||
r = await removeTypeFromPack(pack, m.name as string, innerOpts);
|
||||
break;
|
||||
case 'update_type':
|
||||
r = await updateTypeOnPack(pack, { name: m.name as string, patch: (m.patch as object) ?? {} }, innerOpts);
|
||||
break;
|
||||
case 'add_alias':
|
||||
r = await addAliasToType(pack, m.type as string, m.alias as string, innerOpts);
|
||||
break;
|
||||
case 'remove_alias':
|
||||
r = await removeAliasFromType(pack, m.type as string, m.alias as string, innerOpts);
|
||||
break;
|
||||
case 'add_prefix':
|
||||
r = await addPrefixToType(pack, m.type as string, m.prefix as string, innerOpts);
|
||||
break;
|
||||
case 'remove_prefix':
|
||||
r = await removePrefixFromType(pack, m.type as string, m.prefix as string, innerOpts);
|
||||
break;
|
||||
case 'add_link_type':
|
||||
r = await addLinkTypeToPack(pack, {
|
||||
name: m.name as string,
|
||||
inverse: m.inverse as string | undefined,
|
||||
inference: m.inference as { regex?: string; page_type?: string; target_type?: string } | undefined,
|
||||
}, innerOpts);
|
||||
break;
|
||||
case 'remove_link_type':
|
||||
r = await removeLinkTypeFromPack(pack, m.name as string, innerOpts);
|
||||
break;
|
||||
case 'set_extractable':
|
||||
r = await setExtractableOnType(pack, m.type as string, m.value as boolean, innerOpts);
|
||||
break;
|
||||
case 'set_expert_routing':
|
||||
r = await setExpertRoutingOnType(pack, m.type as string, m.value as boolean, innerOpts);
|
||||
break;
|
||||
default:
|
||||
throw new SchemaPackMutationError(
|
||||
'INVALID_RESULT',
|
||||
`unknown mutation op: '${m.op}' at index ${i}`,
|
||||
{ index: i, op: m.op },
|
||||
);
|
||||
}
|
||||
results.push({ index: i, op: m.op, ...(r as object) });
|
||||
}
|
||||
const results = await applyMutationsAtomic(pack, mutations, {
|
||||
actor: actor as 'cli' | `mcp:${string}`,
|
||||
batchId,
|
||||
engine: ctx.engine,
|
||||
...(sourceId ? { sourceId } : {}),
|
||||
...(force ? { force: true } : {}),
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
@@ -5150,17 +5090,21 @@ const schema_apply_mutations: Operation = {
|
||||
};
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code ?? 'UNKNOWN';
|
||||
const failedAtIndex = (e as { details?: { index?: number } }).details?.index;
|
||||
return {
|
||||
error: 'mutation_failed',
|
||||
code,
|
||||
message: (e as Error).message,
|
||||
batch_id: batchId,
|
||||
// Partial results recorded so the agent can inspect which
|
||||
// mutations landed before the failure (the atomic guarantee
|
||||
// is at the LOCK level — individual mutations are sequential
|
||||
// and each is atomic; pack state reflects everything up to the
|
||||
// failed mutation).
|
||||
partial_results: results,
|
||||
// Nothing was written to disk — applyMutationsAtomic only writes
|
||||
// once, after every mutation in the batch has validated cleanly.
|
||||
// (Pre-fix, this field was `partial_results` and listed mutations
|
||||
// that HAD already landed on disk, because the old implementation
|
||||
// wrote as it went — that shape is gone; a failed batch can no
|
||||
// longer imply partial application.)
|
||||
mutations_applied: 0,
|
||||
pack_unchanged: true,
|
||||
...(failedAtIndex !== undefined ? { failed_at_index: failedAtIndex } : {}),
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -38,6 +38,10 @@ export interface PostWriteLintOpts {
|
||||
force?: boolean;
|
||||
/** Skip file writes; used by tests. */
|
||||
noLog?: boolean;
|
||||
/** Exact scalar source for the page and nested validation reads. */
|
||||
sourceId?: string;
|
||||
/** Federated read scope; when non-empty, takes precedence over sourceId. */
|
||||
sourceIds?: string[];
|
||||
}
|
||||
|
||||
export interface PostWriteLintResult {
|
||||
@@ -80,7 +84,12 @@ export async function runPostWriteLint(
|
||||
return { ran: false, slug, findings: [], skippedReason: 'flag_disabled' };
|
||||
}
|
||||
|
||||
const page = await engine.getPage(slug);
|
||||
const sourceOpts = opts.sourceIds && opts.sourceIds.length > 0
|
||||
? { sourceIds: opts.sourceIds }
|
||||
: opts.sourceId
|
||||
? { sourceId: opts.sourceId }
|
||||
: undefined;
|
||||
const page = await engine.getPage(slug, sourceOpts);
|
||||
if (!page) {
|
||||
return { ran: false, slug, findings: [], skippedReason: 'page_not_found' };
|
||||
}
|
||||
@@ -97,6 +106,8 @@ export async function runPostWriteLint(
|
||||
timeline: page.timeline,
|
||||
frontmatter: page.frontmatter ?? {},
|
||||
engine,
|
||||
sourceId: opts.sourceId,
|
||||
sourceIds: opts.sourceIds,
|
||||
};
|
||||
|
||||
const findings: ValidationFinding[] = [];
|
||||
|
||||
@@ -72,9 +72,10 @@ export class SlugRegistryError extends Error {
|
||||
// SlugRegistry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Shares the page-slug segment grammar (incl. CJK ranges, #738) with
|
||||
// Shares the page-slug segment grammar (all scripts, #738/#3417) with
|
||||
// validatePageSlug; keeps this site's dir/name shape (>= 2 segments).
|
||||
const SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})+$`);
|
||||
// `u` flag required by PAGE_SLUG_SEG's \p{...} classes.
|
||||
const SLUG_RE = new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})+$`, 'u');
|
||||
|
||||
export class SlugRegistry {
|
||||
constructor(private engine: BrainEngine) {}
|
||||
|
||||
@@ -23,25 +23,46 @@ export const backLinkValidator: PageValidator = {
|
||||
|
||||
async validate(ctx: PageValidationContext): Promise<ValidationFinding[]> {
|
||||
const findings: ValidationFinding[] = [];
|
||||
const federatedSourceIds = ctx.sourceIds && ctx.sourceIds.length > 0
|
||||
? ctx.sourceIds
|
||||
: undefined;
|
||||
const outboundOpts = federatedSourceIds
|
||||
? { sourceIds: federatedSourceIds }
|
||||
: ctx.sourceId
|
||||
? { sourceId: ctx.sourceId }
|
||||
: undefined;
|
||||
|
||||
const outbound = await ctx.engine.getLinks(ctx.slug);
|
||||
const outbound = await ctx.engine.getLinks(ctx.slug, outboundOpts);
|
||||
if (outbound.length === 0) return findings;
|
||||
|
||||
// Iron Law: if ctx.slug → target, target must ALSO link back to ctx.slug.
|
||||
// We check target's outbound links; if none of them point at ctx.slug,
|
||||
// the back-link is missing.
|
||||
const uniqueTargets = new Set<string>();
|
||||
for (const link of outbound) uniqueTargets.add(link.to_slug);
|
||||
// A federated lookup can return same-slug origins and targets from several
|
||||
// sources. Deduplicate only identical endpoint pairs; every distinct origin
|
||||
// still needs its own exact reverse.
|
||||
const uniqueEdges = new Map<string, typeof outbound[number]>();
|
||||
for (const link of outbound) {
|
||||
uniqueEdges.set(
|
||||
`${link.from_source_id}\0${link.from_slug}\0${link.to_source_id}\0${link.to_slug}`,
|
||||
link,
|
||||
);
|
||||
}
|
||||
|
||||
for (const target of uniqueTargets) {
|
||||
const targetOutbound = await ctx.engine.getLinks(target);
|
||||
const hasReverse = targetOutbound.some(l => l.to_slug === ctx.slug);
|
||||
for (const target of uniqueEdges.values()) {
|
||||
const targetOpts = federatedSourceIds
|
||||
? { sourceIds: federatedSourceIds }
|
||||
: { sourceId: target.to_source_id };
|
||||
const targetOutbound = await ctx.engine.getLinks(target.to_slug, targetOpts);
|
||||
const hasReverse = targetOutbound.some(link =>
|
||||
link.from_source_id === target.to_source_id
|
||||
&& link.from_slug === target.to_slug
|
||||
&& link.to_source_id === target.from_source_id
|
||||
&& link.to_slug === target.from_slug
|
||||
);
|
||||
if (!hasReverse) {
|
||||
findings.push({
|
||||
slug: ctx.slug,
|
||||
validator: 'back-link',
|
||||
severity: 'warning',
|
||||
message: `Outbound link to ${target} has no back-link (${target} does not reference ${ctx.slug}). runAutoLink should reconcile this on next put_page; flag for inspection.`,
|
||||
message: `Outbound link to ${target.to_slug} has no back-link (${target.to_slug} does not reference ${ctx.slug}). runAutoLink should reconcile this on next put_page; flag for inspection.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,9 +62,14 @@ export const linkValidator: PageValidator = {
|
||||
linkPositions.set(slug, list);
|
||||
}
|
||||
|
||||
// Batch-check which targets exist.
|
||||
// Batch-check which targets exist within the validation read scope.
|
||||
const sourceOpts = ctx.sourceIds && ctx.sourceIds.length > 0
|
||||
? { sourceIds: ctx.sourceIds }
|
||||
: ctx.sourceId
|
||||
? { sourceId: ctx.sourceId }
|
||||
: undefined;
|
||||
for (const slug of internalTargets) {
|
||||
const page = await ctx.engine.getPage(slug);
|
||||
const page = await ctx.engine.getPage(slug, sourceOpts);
|
||||
if (page) continue;
|
||||
const positions = linkPositions.get(slug) ?? [];
|
||||
for (const pos of positions) {
|
||||
|
||||
@@ -93,6 +93,10 @@ export interface PageValidationContext {
|
||||
timeline: string;
|
||||
frontmatter: Record<string, unknown>;
|
||||
engine: BrainEngine;
|
||||
/** Exact scalar source for source-qualified validation reads. */
|
||||
sourceId?: string;
|
||||
/** Federated read scope; when non-empty, takes precedence over sourceId. */
|
||||
sourceIds?: string[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -249,7 +253,9 @@ export class BrainWriter {
|
||||
|
||||
// Validators run before the outer transaction commits.
|
||||
if (strict !== 'off') {
|
||||
report = await runValidators(txEngine, validators, tx.touchedSlugs);
|
||||
report = await runValidators(txEngine, validators, tx.touchedSlugs, {
|
||||
sourceId: 'default',
|
||||
});
|
||||
// `ctx.logger.info` would be nice but keep validator behavior uniform
|
||||
// regardless of strict/lint mode. Caller inspects the report.
|
||||
if (strict === 'strict' && report.errorCount > 0) {
|
||||
@@ -281,11 +287,17 @@ async function runValidators(
|
||||
engine: BrainEngine,
|
||||
validators: PageValidator[],
|
||||
touchedSlugs: Set<string>,
|
||||
scope: { sourceId?: string; sourceIds?: string[] } = {},
|
||||
): Promise<ValidationReport> {
|
||||
const findings: ValidationFinding[] = [];
|
||||
const sourceOpts = scope.sourceIds && scope.sourceIds.length > 0
|
||||
? { sourceIds: scope.sourceIds }
|
||||
: scope.sourceId
|
||||
? { sourceId: scope.sourceId }
|
||||
: undefined;
|
||||
|
||||
for (const slug of touchedSlugs) {
|
||||
const page = await engine.getPage(slug);
|
||||
const page = await engine.getPage(slug, sourceOpts);
|
||||
if (!page) continue; // could have been deleted in this tx
|
||||
|
||||
// Grandfather opt-out
|
||||
@@ -298,6 +310,8 @@ async function runValidators(
|
||||
timeline: page.timeline,
|
||||
frontmatter: page.frontmatter ?? {},
|
||||
engine,
|
||||
sourceId: scope.sourceId,
|
||||
sourceIds: scope.sourceIds,
|
||||
};
|
||||
|
||||
for (const v of validators) {
|
||||
|
||||
+106
-34
@@ -17,7 +17,26 @@ import type {
|
||||
SourceRow,
|
||||
} from './engine.ts';
|
||||
import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts';
|
||||
import { withRetry, BULK_RETRY_OPTS, resolveBulkRetryOpts, computeNextDelay, type BatchAuditSite } from './retry.ts';
|
||||
// Engine-path imports stay static unless a call site carries an explicit
|
||||
// engine-dynamic-import-ok justification. The gateway is the only current
|
||||
// exception because its local try/catch preserves a soft fallback.
|
||||
import {
|
||||
withRetry,
|
||||
BULK_RETRY_OPTS,
|
||||
resolveBulkRetryOpts,
|
||||
computeNextDelay,
|
||||
isRetryableConnError,
|
||||
type BatchAuditSite,
|
||||
} from './retry.ts';
|
||||
import {
|
||||
valueHash,
|
||||
normalizeDimension,
|
||||
isNovelDimension,
|
||||
} from './chronicle/ontology.ts';
|
||||
import {
|
||||
resolveRecencyDecayMap,
|
||||
DEFAULT_FALLBACK,
|
||||
} from './search/recency-decay.ts';
|
||||
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
|
||||
import { runMigrations } from './migrate.ts';
|
||||
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
|
||||
@@ -419,9 +438,13 @@ export class PGLiteEngine implements BrainEngine {
|
||||
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
|
||||
let model: string = DEFAULT_EMBEDDING_MODEL;
|
||||
try {
|
||||
const gw = await import('./ai/gateway.ts');
|
||||
// Keep the gateway lazy: its static closure is large, and evaluation inside
|
||||
// this try/catch preserves the unconfigured-gateway default fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
// Both accessors THROW when the gateway is unconfigured (they never
|
||||
// return falsy), so the catch below is the only fallback path (#3461).
|
||||
dims = gw.getEmbeddingDimensions();
|
||||
model = gw.getEmbeddingModel() || model;
|
||||
model = gw.getEmbeddingModel();
|
||||
} catch { /* gateway not configured — use defaults */ }
|
||||
|
||||
await this.db.exec(getPGLiteSchema(dims, model));
|
||||
@@ -979,7 +1002,8 @@ export class PGLiteEngine implements BrainEngine {
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,
|
||||
effective_date, effective_date_source,
|
||||
source_kind, source_uri, ingested_via, ingested_at
|
||||
source_kind, source_uri, ingested_via, ingested_at,
|
||||
contextual_retrieval_mode
|
||||
FROM pages WHERE ${where.join(' AND ')} LIMIT 1`,
|
||||
params
|
||||
);
|
||||
@@ -2261,7 +2285,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === 'RetryAbortError') throw err;
|
||||
const { isRetryableConnError } = await import('./retry.ts');
|
||||
if (isRetryableConnError(err)) {
|
||||
auditLogBatchExhausted(auditSite, batchSize, opts.maxRetries + 1, err);
|
||||
}
|
||||
@@ -2320,15 +2343,28 @@ export class PGLiteEngine implements BrainEngine {
|
||||
|
||||
// Provenance fallback for chunks without an explicit `model`: resolve the
|
||||
// gateway's runtime model, not the compile-time DEFAULT_EMBEDDING_MODEL.
|
||||
// See postgres-engine.ts _upsertChunksOnce for the full rationale — pglite
|
||||
// mirrors it for parity.
|
||||
let resolvedModel: string = DEFAULT_EMBEDDING_MODEL;
|
||||
// #3461: getEmbeddingModel() THROWS when unconfigured (never returns
|
||||
// falsy) — on the throw path fall back to the brain's own
|
||||
// `config.embedding_model` row, then the compile-time default as the
|
||||
// last resort. See postgres-engine.ts _upsertChunksOnce for the full
|
||||
// rationale — pglite mirrors it for parity.
|
||||
let resolvedModel: string | null = null;
|
||||
try {
|
||||
const gw = await import('./ai/gateway.ts');
|
||||
resolvedModel = gw.getEmbeddingModel() || resolvedModel;
|
||||
// Keep the gateway lazy so module-load failure remains inside this soft
|
||||
// fallback boundary; eager evaluation would bypass the config-row fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
resolvedModel = gw.getEmbeddingModel();
|
||||
} catch {
|
||||
// Gateway unconfigured (unit tests / pre-connect): keep the default.
|
||||
try {
|
||||
const cfg = await this.db.query(
|
||||
`SELECT value FROM config WHERE key = 'embedding_model'`,
|
||||
);
|
||||
resolvedModel = ((cfg.rows[0] as { value?: string } | undefined)?.value) ?? null;
|
||||
} catch {
|
||||
// config table unreadable — fall through to the compile-time default.
|
||||
}
|
||||
}
|
||||
if (!resolvedModel) resolvedModel = DEFAULT_EMBEDDING_MODEL;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const embeddingStr = chunk.embedding
|
||||
@@ -2381,6 +2417,9 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// Code-chunk metadata columns follow the same chunk_text-gated CASE pattern as `embedding`
|
||||
// (#769). Re-chunk trusts EXCLUDED outright; pure re-embed COALESCEs so a caller carrying
|
||||
// only embedding-shaped fields doesn't clobber metadata to NULL.
|
||||
//
|
||||
// #3461: `model` mirrors the `embedding` CASE branch-for-branch so the label always
|
||||
// describes whichever vector wins the upsert. See postgres-engine.ts for rationale.
|
||||
await this.db.query(
|
||||
`INSERT INTO content_chunks ${cols} VALUES ${rowParts.join(', ')}
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
@@ -2394,7 +2433,14 @@ export class PGLiteEngine implements BrainEngine {
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
END,
|
||||
model = COALESCE(EXCLUDED.model, content_chunks.model),
|
||||
model = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.model
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.model
|
||||
ELSE content_chunks.model
|
||||
END,
|
||||
token_count = EXCLUDED.token_count,
|
||||
embedded_at = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL
|
||||
@@ -2855,9 +2901,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// Remote MCP clients always land here.
|
||||
if (opts?.sourceIds && opts.sourceIds.length > 0) {
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -2873,9 +2921,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// opts.sourceId, scope to that source (D20).
|
||||
if (opts?.sourceId) {
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -2886,9 +2936,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return rows as unknown as Link[];
|
||||
}
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -2905,9 +2957,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// foreign referrer nor a foreign origin slug is disclosed to the caller.
|
||||
if (opts?.sourceIds && opts.sourceIds.length > 0) {
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -2920,9 +2974,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks.
|
||||
if (opts?.sourceId) {
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -2933,9 +2989,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return rows as unknown as Link[];
|
||||
}
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
`SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3818,7 +3876,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
|
||||
async mergeOntologyFact(obs: OntologyObservationInput): Promise<OntologyMergeResult> {
|
||||
const sourceId = obs.sourceId ?? 'default';
|
||||
const { valueHash, normalizeDimension, isNovelDimension } = await import('./chronicle/ontology.ts');
|
||||
const dimension = normalizeDimension(obs.dimension);
|
||||
const vh = valueHash(obs.value);
|
||||
const conf = obs.confidence ?? 0.7;
|
||||
@@ -4252,7 +4309,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
$14, $15,
|
||||
$16, $17, $18, $19,
|
||||
$20
|
||||
) RETURNING id`
|
||||
)
|
||||
ON CONFLICT (source_id, source_markdown_slug, row_num)
|
||||
WHERE row_num IS NOT NULL
|
||||
DO NOTHING
|
||||
RETURNING id`
|
||||
: `INSERT INTO facts (
|
||||
source_id, entity_slug, fact, kind, visibility, notability, context,
|
||||
valid_from, valid_until, source, source_session, confidence,
|
||||
@@ -4266,12 +4327,16 @@ export class PGLiteEngine implements BrainEngine {
|
||||
$15, $16,
|
||||
$17, $18, $19, $20,
|
||||
$21
|
||||
) RETURNING id`,
|
||||
)
|
||||
ON CONFLICT (source_id, source_markdown_slug, row_num)
|
||||
WHERE row_num IS NOT NULL
|
||||
DO NOTHING
|
||||
RETURNING id`,
|
||||
embedStr === null
|
||||
? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
|
||||
: [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
|
||||
);
|
||||
out.push(ins.rows[0].id);
|
||||
if (ins.rows[0]) out.push(ins.rows[0].id);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
@@ -5308,12 +5373,16 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// pages_with_timeline) and v0.10.3 graph layer (link_coverage, timeline_coverage,
|
||||
// most_connected). Both coexist: master's brain_score is the composite
|
||||
// dashboard, v0.10.3 metrics give entity-page-level granularity.
|
||||
// #1305: every page-scoped count here excludes soft-deleted rows — same
|
||||
// posture as getStats — so brain_score moves when the user deletes pages.
|
||||
// Chunk/link counts stay raw (storage until the purge phase), matching
|
||||
// getStats, and destructive-removal counts elsewhere deliberately stay raw.
|
||||
const { rows: [h] } = await this.db.query(`
|
||||
WITH entity_pages AS (
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company')
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company') AND deleted_at IS NULL
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM pages) as page_count,
|
||||
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
|
||||
(SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
|
||||
GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
|
||||
0 as stale_pages,
|
||||
@@ -5338,7 +5407,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
SELECT p.slug,
|
||||
(SELECT count(*) FROM links l WHERE l.from_page_id = p.id OR l.to_page_id = p.id)::int as link_count
|
||||
FROM pages p
|
||||
WHERE p.type IN ('entity', 'person', 'company')
|
||||
WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
|
||||
ORDER BY link_count DESC
|
||||
LIMIT 5
|
||||
`);
|
||||
@@ -5357,6 +5426,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)) as islanded,
|
||||
EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
|
||||
FROM pages p
|
||||
WHERE p.deleted_at IS NULL
|
||||
`);
|
||||
|
||||
const r = h as Record<string, unknown>;
|
||||
@@ -5451,15 +5521,18 @@ export class PGLiteEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Sync
|
||||
async updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<void> {
|
||||
async updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<number> {
|
||||
newSlug = validateSlug(newSlug);
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// Source-qualify so a rename in source A doesn't sweep up same-slug rows
|
||||
// in sources B/C/D (mirrors postgres-engine.ts).
|
||||
await this.db.query(
|
||||
const result = await this.db.query(
|
||||
`UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3`,
|
||||
[newSlug, oldSlug, sourceId]
|
||||
);
|
||||
// #3056: rows moved — a zero-row UPDATE does not throw, so the count is
|
||||
// the only way callers can see the no-op.
|
||||
return result.affectedRows ?? 0;
|
||||
}
|
||||
|
||||
async rewriteLinks(_oldSlug: string, _newSlug: string): Promise<void> {
|
||||
@@ -5973,7 +6046,6 @@ export class PGLiteEngine implements BrainEngine {
|
||||
const recencyBias = opts.recency_bias ?? 'flat';
|
||||
let recencySql: string;
|
||||
if (recencyBias === 'on') {
|
||||
const { resolveRecencyDecayMap, DEFAULT_FALLBACK } = await import('./search/recency-decay.ts');
|
||||
recencySql = buildRecencyComponentSql({
|
||||
slugColumn: 'p.slug',
|
||||
dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
|
||||
|
||||
+110
-38
@@ -13,7 +13,29 @@ import type {
|
||||
NewFact, FactListOpts, FactsHealth,
|
||||
SourceRow,
|
||||
} from './engine.ts';
|
||||
import { withRetry, BULK_RETRY_OPTS, resolveBulkRetryOpts, computeNextDelay, type BatchAuditSite } from './retry.ts';
|
||||
// Engine-path imports stay static unless a call site carries an explicit
|
||||
// engine-dynamic-import-ok justification. The gateway is the only current
|
||||
// exception because its local try/catch preserves a soft fallback.
|
||||
import {
|
||||
withRetry,
|
||||
BULK_RETRY_OPTS,
|
||||
resolveBulkRetryOpts,
|
||||
computeNextDelay,
|
||||
isRetryableConnError,
|
||||
type BatchAuditSite,
|
||||
} from './retry.ts';
|
||||
import { isConnectionEndedError } from './retry-matcher.ts';
|
||||
import {
|
||||
valueHash,
|
||||
normalizeDimension,
|
||||
isNovelDimension,
|
||||
} from './chronicle/ontology.ts';
|
||||
import {
|
||||
resolveRecencyDecayMap,
|
||||
DEFAULT_FALLBACK,
|
||||
} from './search/recency-decay.ts';
|
||||
import { logDbDisconnect } from './audit/db-disconnect-audit.ts';
|
||||
import { logPoolRecovery } from './audit/pool-recovery-audit.ts';
|
||||
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
|
||||
import type {
|
||||
DomainBankSampleOpts, CorpusSampleOpts, DomainBankRow,
|
||||
@@ -331,7 +353,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
// even a no-op disconnect (engine that was never connected) is
|
||||
// recorded — that case may itself be a caller-side bug worth seeing.
|
||||
try {
|
||||
const { logDbDisconnect } = await import('./audit/db-disconnect-audit.ts');
|
||||
logDbDisconnect('postgres', this._connectionStyle ?? 'unknown');
|
||||
} catch { /* best-effort; never block disconnect on audit failure */ }
|
||||
// v0.30.1: tear down the direct pool first if the manager owns one.
|
||||
@@ -381,9 +402,13 @@ export class PostgresEngine implements BrainEngine {
|
||||
let dims: number = DEFAULT_EMBEDDING_DIMENSIONS;
|
||||
let model: string = DEFAULT_EMBEDDING_MODEL;
|
||||
try {
|
||||
const gw = await import('./ai/gateway.ts');
|
||||
// Keep the gateway lazy: its static closure is large, and evaluation inside
|
||||
// this try/catch preserves the unconfigured-gateway default fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
// Both accessors THROW when the gateway is unconfigured (they never
|
||||
// return falsy), so the catch below is the only fallback path (#3461).
|
||||
dims = gw.getEmbeddingDimensions();
|
||||
model = gw.getEmbeddingModel() || model;
|
||||
model = gw.getEmbeddingModel();
|
||||
} catch { /* gateway not yet configured — use defaults */ }
|
||||
|
||||
const sqlText = getPostgresSchema(dims, model);
|
||||
@@ -1031,7 +1056,8 @@ export class PostgresEngine implements BrainEngine {
|
||||
const rows = await tx`
|
||||
SELECT id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, deleted_at,
|
||||
effective_date, effective_date_source,
|
||||
source_kind, source_uri, ingested_via, ingested_at
|
||||
source_kind, source_uri, ingested_via, ingested_at,
|
||||
contextual_retrieval_mode
|
||||
FROM pages
|
||||
WHERE slug = ${slug} ${sourceCondition} ${deletedCondition}
|
||||
LIMIT 1
|
||||
@@ -2378,8 +2404,8 @@ export class PostgresEngine implements BrainEngine {
|
||||
if (err instanceof Error && err.name === 'RetryAbortError') throw err;
|
||||
// Best-effort exhausted-retry log. If the error wasn't retryable in
|
||||
// the first place, isRetryableConnError(err) is false and we skip.
|
||||
// Lazy-import to avoid a circular dep concern.
|
||||
const { isRetryableConnError } = await import('./retry.ts');
|
||||
// retry.ts is already in this module's static graph through withRetry, so
|
||||
// classifying the exhausted error does not need a second runtime import.
|
||||
if (isRetryableConnError(err)) {
|
||||
auditLogBatchExhausted(auditSite, batchSize, opts.maxRetries + 1, err);
|
||||
}
|
||||
@@ -2437,14 +2463,30 @@ export class PostgresEngine implements BrainEngine {
|
||||
// hardcoded default (e.g. zeroentropyai:zembed-1) onto rows whose vectors
|
||||
// were produced by a different, config-resolved model — corrupting the
|
||||
// provenance that signature-drift staleness + dim-migration logic trust.
|
||||
// Mirrors the resolve-then-fallback pattern used for schema sizing above.
|
||||
let resolvedModel: string = DEFAULT_EMBEDDING_MODEL;
|
||||
//
|
||||
// #3461: getEmbeddingModel() THROWS when the gateway is unconfigured —
|
||||
// it never returns falsy — so an `||` guard here is dead code and the
|
||||
// catch path used to stamp the compile-time default onto rows whose
|
||||
// vectors came from the config-resolved provider. On the throw path we
|
||||
// now fall back to the brain's own `config.embedding_model` row (kept
|
||||
// current by init / migrate / retrieval-upgrade), which names the model
|
||||
// that actually produced this brain's vectors. The compile-time default
|
||||
// is the LAST resort (fresh brain whose config row doesn't exist yet).
|
||||
let resolvedModel: string | null = null;
|
||||
try {
|
||||
const gw = await import('./ai/gateway.ts');
|
||||
resolvedModel = gw.getEmbeddingModel() || resolvedModel;
|
||||
// Keep the gateway lazy so module-load failure remains inside this soft
|
||||
// fallback boundary; eager evaluation would bypass the config-row fallback.
|
||||
const gw = await import('./ai/gateway.ts'); // engine-dynamic-import-ok
|
||||
resolvedModel = gw.getEmbeddingModel();
|
||||
} catch {
|
||||
// Gateway unconfigured (unit tests / pre-connect): keep the default.
|
||||
try {
|
||||
const cfg = await sql`SELECT value FROM config WHERE key = 'embedding_model'`;
|
||||
resolvedModel = (cfg[0]?.value as string | undefined) ?? null;
|
||||
} catch {
|
||||
// config table unreadable — fall through to the compile-time default.
|
||||
}
|
||||
}
|
||||
if (!resolvedModel) resolvedModel = DEFAULT_EMBEDDING_MODEL;
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const embeddingStr = chunk.embedding
|
||||
@@ -2508,6 +2550,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
// pure re-embed (chunk_text unchanged) COALESCEs so a caller that only carries embedding
|
||||
// doesn't clobber metadata to NULL. Without this, every embed --stale pass nuked code-def's
|
||||
// primary index for thousands of chunks at once.
|
||||
//
|
||||
// #3461: `model` mirrors the `embedding` CASE branch-for-branch — the label must
|
||||
// describe whichever vector WINS the upsert. The old COALESCE(EXCLUDED.model, …)
|
||||
// relabeled preserved (older-model) vectors with the current gateway model on every
|
||||
// partial re-embed, corrupting provenance without changing the vector.
|
||||
await sql.unsafe(
|
||||
`INSERT INTO content_chunks ${cols} VALUES ${rows.join(', ')}
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
@@ -2521,7 +2568,14 @@ export class PostgresEngine implements BrainEngine {
|
||||
THEN EXCLUDED.embedding
|
||||
ELSE content_chunks.embedding
|
||||
END,
|
||||
model = COALESCE(EXCLUDED.model, content_chunks.model),
|
||||
model = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model
|
||||
WHEN content_chunks.embedding IS NULL THEN EXCLUDED.model
|
||||
WHEN EXCLUDED.embedded_at IS NOT NULL
|
||||
AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)
|
||||
THEN EXCLUDED.model
|
||||
ELSE content_chunks.model
|
||||
END,
|
||||
token_count = EXCLUDED.token_count,
|
||||
embedded_at = CASE
|
||||
WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.embedding IS NULL THEN NULL
|
||||
@@ -2998,9 +3052,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
if (opts?.sourceIds && opts.sourceIds.length > 0) {
|
||||
const ids = opts.sourceIds;
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3015,9 +3071,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
// opts.sourceId, scope the from-page lookup.
|
||||
if (opts?.sourceId) {
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3027,9 +3085,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
return rows as unknown as Link[];
|
||||
}
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3051,9 +3111,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
if (opts?.sourceIds && opts.sourceIds.length > 0) {
|
||||
const ids = opts.sourceIds;
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3065,9 +3127,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
// v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks.
|
||||
if (opts?.sourceId) {
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3077,9 +3141,11 @@ export class PostgresEngine implements BrainEngine {
|
||||
return rows as unknown as Link[];
|
||||
}
|
||||
const rows = await tx`
|
||||
SELECT f.slug as from_slug, t.slug as to_slug,
|
||||
SELECT f.slug as from_slug, f.source_id as from_source_id,
|
||||
t.slug as to_slug, t.source_id as to_source_id,
|
||||
l.link_type, l.context, l.link_source,
|
||||
o.slug as origin_slug, l.origin_field
|
||||
o.slug as origin_slug, o.source_id as origin_source_id,
|
||||
l.origin_field
|
||||
FROM links l
|
||||
JOIN pages f ON f.id = l.from_page_id
|
||||
JOIN pages t ON t.id = l.to_page_id
|
||||
@@ -3954,7 +4020,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
async mergeOntologyFact(obs: OntologyObservationInput): Promise<OntologyMergeResult> {
|
||||
const sql = this.sql;
|
||||
const sourceId = obs.sourceId ?? 'default';
|
||||
const { valueHash, normalizeDimension, isNovelDimension } = await import('./chronicle/ontology.ts');
|
||||
const dimension = normalizeDimension(obs.dimension);
|
||||
const vh = valueHash(obs.value);
|
||||
const conf = obs.confidence ?? 0.7;
|
||||
@@ -4426,9 +4491,13 @@ export class PostgresEngine implements BrainEngine {
|
||||
${input.row_num}, ${input.source_markdown_slug},
|
||||
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
|
||||
${eventType}
|
||||
) RETURNING id
|
||||
)
|
||||
ON CONFLICT (source_id, source_markdown_slug, row_num)
|
||||
WHERE row_num IS NOT NULL
|
||||
DO NOTHING
|
||||
RETURNING id
|
||||
`;
|
||||
out.push(Number(ins[0].id));
|
||||
if (ins[0]) out.push(Number(ins[0].id));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
@@ -5403,12 +5472,16 @@ export class PostgresEngine implements BrainEngine {
|
||||
// no outbound links). The raw islanded list is filtered through the same
|
||||
// policy as `gbrain orphans` so convention pages do not count against
|
||||
// dashboard health.
|
||||
// #1305: every page-scoped count here excludes soft-deleted rows — same
|
||||
// posture as getStats — so brain_score moves when the user deletes pages.
|
||||
// Chunk/link counts stay raw (storage until the purge phase), matching
|
||||
// getStats, and destructive-removal counts elsewhere deliberately stay raw.
|
||||
const [h] = await sql`
|
||||
WITH entity_pages AS (
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company')
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company') AND deleted_at IS NULL
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM pages) as page_count,
|
||||
(SELECT count(*) FROM pages WHERE deleted_at IS NULL) as page_count,
|
||||
(SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
|
||||
GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
|
||||
0 as stale_pages,
|
||||
@@ -5430,7 +5503,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
SELECT p.slug,
|
||||
(SELECT count(*) FROM links l WHERE l.from_page_id = p.id OR l.to_page_id = p.id)::int as link_count
|
||||
FROM pages p
|
||||
WHERE p.type IN ('entity', 'person', 'company')
|
||||
WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
|
||||
ORDER BY link_count DESC
|
||||
LIMIT 5
|
||||
`;
|
||||
@@ -5449,6 +5522,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)) as islanded,
|
||||
EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
|
||||
FROM pages p
|
||||
WHERE p.deleted_at IS NULL
|
||||
`;
|
||||
|
||||
const pageCount = Number(h.page_count);
|
||||
@@ -5540,14 +5614,17 @@ export class PostgresEngine implements BrainEngine {
|
||||
}
|
||||
|
||||
// Sync
|
||||
async updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<void> {
|
||||
async updateSlug(oldSlug: string, newSlug: string, opts?: { sourceId?: string }): Promise<number> {
|
||||
newSlug = validateSlug(newSlug);
|
||||
const sql = this.sql;
|
||||
const sourceId = opts?.sourceId ?? 'default';
|
||||
// Source-qualify so a rename in source A doesn't sweep up same-slug rows
|
||||
// in sources B/C/D (which would either rename them all OR fail the
|
||||
// (source_id, slug) UNIQUE if the new slug already exists in another source).
|
||||
await sql`UPDATE pages SET slug = ${newSlug}, updated_at = now() WHERE slug = ${oldSlug} AND source_id = ${sourceId}`;
|
||||
const result = await sql`UPDATE pages SET slug = ${newSlug}, updated_at = now() WHERE slug = ${oldSlug} AND source_id = ${sourceId}`;
|
||||
// #3056: rows moved — a zero-row UPDATE does not throw, so the count is
|
||||
// the only way callers can see the no-op.
|
||||
return result.count ?? 0;
|
||||
}
|
||||
|
||||
async rewriteLinks(_oldSlug: string, _newSlug: string): Promise<void> {
|
||||
@@ -5786,12 +5863,10 @@ export class PostgresEngine implements BrainEngine {
|
||||
let isReap = false;
|
||||
if (ctx?.error !== undefined) {
|
||||
try {
|
||||
const { isConnectionEndedError } = await import('./retry-matcher.ts');
|
||||
isReap = isConnectionEndedError(ctx.error);
|
||||
} catch { /* classification is best-effort */ }
|
||||
}
|
||||
try {
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
logPoolRecovery(isReap ? 'reap_detected' : 'reconnect_other', ctx?.error);
|
||||
} catch { /* audit is best-effort */ }
|
||||
|
||||
@@ -5815,7 +5890,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
// New pool is live — discard the old one best-effort.
|
||||
if (oldSql) { try { await oldSql.end({ timeout: 5 }); } catch { /* swallow */ } }
|
||||
try {
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
logPoolRecovery('reconnect_succeeded');
|
||||
} catch { /* best-effort */ }
|
||||
} catch (err) {
|
||||
@@ -5827,7 +5901,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
this._sql = oldSql;
|
||||
this.connectionManager = oldManager;
|
||||
try {
|
||||
const { logPoolRecovery } = await import('./audit/pool-recovery-audit.ts');
|
||||
logPoolRecovery('reconnect_failed', err);
|
||||
} catch { /* best-effort */ }
|
||||
throw err; // let batchRetry's backoff handle the retry
|
||||
@@ -6264,7 +6337,6 @@ export class PostgresEngine implements BrainEngine {
|
||||
const recencyBias = opts.recency_bias ?? 'flat';
|
||||
let recencySql: string;
|
||||
if (recencyBias === 'on') {
|
||||
const { resolveRecencyDecayMap, DEFAULT_FALLBACK } = await import('./search/recency-decay.ts');
|
||||
recencySql = buildRecencyComponentSql({
|
||||
slugColumn: 'p.slug',
|
||||
dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
|
||||
|
||||
@@ -186,6 +186,9 @@ export {
|
||||
removeLinkTypeFromPack,
|
||||
setExtractableOnType,
|
||||
setExpertRoutingOnType,
|
||||
type BatchMutationRequest,
|
||||
type BatchMutationResult,
|
||||
applyMutationsAtomic,
|
||||
} from './mutate.ts';
|
||||
|
||||
export { invalidateQueryCache } from './query-cache-invalidator.ts';
|
||||
|
||||
+286
-27
@@ -497,11 +497,18 @@ export interface AddTypeOpts {
|
||||
aliases?: string[];
|
||||
}
|
||||
|
||||
export async function addTypeToPack(packName: string, opts: AddTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
// Each `build*Mutator` below does the primitive's up-front (file-free,
|
||||
// lock-free) shape validation and returns the pure `(current) => next`
|
||||
// transform. The public async functions wrap the builder with
|
||||
// `withMutation` for the single-mutation (CLI) path; `applyMutationsAtomic`
|
||||
// (batch path, below) reuses the SAME builders so single-call and batched
|
||||
// mutations can never drift in what they accept or reject.
|
||||
|
||||
function buildAddTypeMutator(opts: AddTypeOpts): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(opts.name);
|
||||
validatePrimitive(opts.primitive);
|
||||
validatePrefix(opts.prefix);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
if (m.page_types.some((pt) => pt.name === opts.name)) {
|
||||
throw new SchemaPackMutationError(
|
||||
'TYPE_EXISTS',
|
||||
@@ -518,16 +525,24 @@ export async function addTypeToPack(packName: string, opts: AddTypeOpts, mutateO
|
||||
expert_routing: opts.expertRouting ?? false,
|
||||
};
|
||||
return { ...m, page_types: [...m.page_types, newType] };
|
||||
}, 'add_type', { type: opts.name, prefix: opts.prefix });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeTypeFromPack(packName: string, name: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
export async function addTypeToPack(packName: string, opts: AddTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildAddTypeMutator(opts), 'add_type', { type: opts.name, prefix: opts.prefix });
|
||||
}
|
||||
|
||||
function buildRemoveTypeMutator(name: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(name);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
findType(m, name); // throws TYPE_NOT_FOUND if missing
|
||||
checkNoReferences(m, name); // codex C14
|
||||
return { ...m, page_types: m.page_types.filter((t) => t.name !== name) };
|
||||
}, 'remove_type', { type: name });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeTypeFromPack(packName: string, name: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildRemoveTypeMutator(name), 'remove_type', { type: name });
|
||||
}
|
||||
|
||||
export interface UpdateTypeOpts {
|
||||
@@ -535,56 +550,76 @@ export interface UpdateTypeOpts {
|
||||
patch: Partial<Omit<PackPageType, 'name'>>;
|
||||
}
|
||||
|
||||
export async function updateTypeOnPack(packName: string, opts: UpdateTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
function buildUpdateTypeMutator(opts: UpdateTypeOpts): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(opts.name);
|
||||
if (opts.patch.primitive !== undefined) validatePrimitive(opts.patch.primitive);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
const existing = findType(m, opts.name);
|
||||
const updated: PackPageType = { ...existing, ...opts.patch, name: existing.name };
|
||||
return { ...m, page_types: m.page_types.map((t) => (t.name === opts.name ? updated : t)) };
|
||||
}, 'update_type', { type: opts.name });
|
||||
};
|
||||
}
|
||||
|
||||
export async function addAliasToType(packName: string, typeName: string, alias: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
export async function updateTypeOnPack(packName: string, opts: UpdateTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildUpdateTypeMutator(opts), 'update_type', { type: opts.name });
|
||||
}
|
||||
|
||||
function buildAddAliasMutator(typeName: string, alias: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(typeName);
|
||||
validateTypeName(alias);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
const t = findType(m, typeName);
|
||||
if (t.aliases.includes(alias)) return m; // idempotent
|
||||
const next: PackPageType = { ...t, aliases: [...t.aliases, alias] };
|
||||
return { ...m, page_types: m.page_types.map((pt) => (pt.name === typeName ? next : pt)) };
|
||||
}, 'add_alias', { type: typeName });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeAliasFromType(packName: string, typeName: string, alias: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
export async function addAliasToType(packName: string, typeName: string, alias: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildAddAliasMutator(typeName, alias), 'add_alias', { type: typeName });
|
||||
}
|
||||
|
||||
function buildRemoveAliasMutator(typeName: string, alias: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(typeName);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
const t = findType(m, typeName);
|
||||
if (!t.aliases.includes(alias)) return m; // idempotent
|
||||
const next: PackPageType = { ...t, aliases: t.aliases.filter((a) => a !== alias) };
|
||||
return { ...m, page_types: m.page_types.map((pt) => (pt.name === typeName ? next : pt)) };
|
||||
}, 'remove_alias', { type: typeName });
|
||||
};
|
||||
}
|
||||
|
||||
export async function addPrefixToType(packName: string, typeName: string, prefix: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
export async function removeAliasFromType(packName: string, typeName: string, alias: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildRemoveAliasMutator(typeName, alias), 'remove_alias', { type: typeName });
|
||||
}
|
||||
|
||||
function buildAddPrefixMutator(typeName: string, prefix: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(typeName);
|
||||
validatePrefix(prefix);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
const t = findType(m, typeName);
|
||||
if (t.path_prefixes.includes(prefix)) return m;
|
||||
const next: PackPageType = { ...t, path_prefixes: [...t.path_prefixes, prefix] };
|
||||
return { ...m, page_types: m.page_types.map((pt) => (pt.name === typeName ? next : pt)) };
|
||||
}, 'add_prefix', { type: typeName, prefix });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removePrefixFromType(packName: string, typeName: string, prefix: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
export async function addPrefixToType(packName: string, typeName: string, prefix: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildAddPrefixMutator(typeName, prefix), 'add_prefix', { type: typeName, prefix });
|
||||
}
|
||||
|
||||
function buildRemovePrefixMutator(typeName: string, prefix: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
validateTypeName(typeName);
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
const t = findType(m, typeName);
|
||||
if (!t.path_prefixes.includes(prefix)) return m;
|
||||
const next: PackPageType = { ...t, path_prefixes: t.path_prefixes.filter((p) => p !== prefix) };
|
||||
return { ...m, page_types: m.page_types.map((pt) => (pt.name === typeName ? next : pt)) };
|
||||
}, 'remove_prefix', { type: typeName, prefix });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removePrefixFromType(packName: string, typeName: string, prefix: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildRemovePrefixMutator(typeName, prefix), 'remove_prefix', { type: typeName, prefix });
|
||||
}
|
||||
|
||||
export interface AddLinkTypeOpts {
|
||||
@@ -593,11 +628,11 @@ export interface AddLinkTypeOpts {
|
||||
inference?: { regex?: string; page_type?: string; target_type?: string };
|
||||
}
|
||||
|
||||
export async function addLinkTypeToPack(packName: string, opts: AddLinkTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
function buildAddLinkTypeMutator(opts: AddLinkTypeOpts): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
if (typeof opts.name !== 'string' || opts.name.length === 0) {
|
||||
throw new SchemaPackMutationError('INVALID_RESULT', `link_type.name is required`);
|
||||
}
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
return (m) => {
|
||||
if (m.link_types.some((lt) => lt.name === opts.name)) {
|
||||
throw new SchemaPackMutationError(
|
||||
'TYPE_EXISTS',
|
||||
@@ -611,11 +646,15 @@ export async function addLinkTypeToPack(packName: string, opts: AddLinkTypeOpts,
|
||||
...(opts.inference ? { inference: opts.inference } : {}),
|
||||
} as PackLinkType;
|
||||
return { ...m, link_types: [...m.link_types, newLink] };
|
||||
}, 'add_link_type', { type: opts.name });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeLinkTypeFromPack(packName: string, linkName: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, (m) => {
|
||||
export async function addLinkTypeToPack(packName: string, opts: AddLinkTypeOpts, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildAddLinkTypeMutator(opts), 'add_link_type', { type: opts.name });
|
||||
}
|
||||
|
||||
function buildRemoveLinkTypeMutator(linkName: string): (m: SchemaPackManifest) => SchemaPackManifest {
|
||||
return (m) => {
|
||||
if (!m.link_types.some((lt) => lt.name === linkName)) {
|
||||
throw new SchemaPackMutationError(
|
||||
'TYPE_NOT_FOUND',
|
||||
@@ -633,7 +672,11 @@ export async function removeLinkTypeFromPack(packName: string, linkName: string,
|
||||
);
|
||||
}
|
||||
return { ...m, link_types: m.link_types.filter((lt) => lt.name !== linkName) };
|
||||
}, 'remove_link_type', { type: linkName });
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeLinkTypeFromPack(packName: string, linkName: string, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return withMutation(packName, mutateOpts, buildRemoveLinkTypeMutator(linkName), 'remove_link_type', { type: linkName });
|
||||
}
|
||||
|
||||
export async function setExtractableOnType(packName: string, typeName: string, value: boolean, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
@@ -643,3 +686,219 @@ export async function setExtractableOnType(packName: string, typeName: string, v
|
||||
export async function setExpertRoutingOnType(packName: string, typeName: string, value: boolean, mutateOpts: MutateOpts = {}): Promise<MutateResult> {
|
||||
return updateTypeOnPack(packName, { name: typeName, patch: { expert_routing: value } }, { ...mutateOpts });
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// Atomic batch application (issue #2581) — one lock, one file read, one
|
||||
// write. `schema_apply_mutations` used to loop over these same primitives
|
||||
// and let each one independently read/validate/WRITE the pack file, so a
|
||||
// batch that failed partway left every earlier mutation permanently on
|
||||
// disk even though the op is documented as all-or-nothing. Here every
|
||||
// mutation in the batch is applied + lint-validated against an IN-MEMORY
|
||||
// manifest only; `writePackManifest` is called at most once, after every
|
||||
// mutation in the batch has been proven valid. A failure at any index
|
||||
// therefore leaves the pack file byte-identical to its pre-batch state —
|
||||
// partial application is structurally impossible, not just cleaned up
|
||||
// after the fact.
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface BatchMutationRequest {
|
||||
op: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BatchMutationResult {
|
||||
index: number;
|
||||
op: string;
|
||||
pack: string;
|
||||
path: string;
|
||||
format: PackFileFormat;
|
||||
/** sha8 of the manifest immediately before this mutation (chained). */
|
||||
prev_sha8: string;
|
||||
/** sha8 of the manifest immediately after this mutation (chained). */
|
||||
new_sha8: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one batch entry to its pure mutator + audit context, reusing the
|
||||
* exact same `build*Mutator` a single-mutation call would use. Throws
|
||||
* `SchemaPackMutationError('INVALID_RESULT', ...)` for an unrecognized
|
||||
* `op`, matching the pre-existing single-mutation shape-validation
|
||||
* contract: this runs before the file is touched, so it is deliberately
|
||||
* NOT audit-logged here (mirrors `addTypeToPack` etc. throwing from their
|
||||
* own up-front `validate*` calls, before `withMutation` ever starts).
|
||||
*/
|
||||
function buildBatchMutator(
|
||||
m: BatchMutationRequest,
|
||||
index: number,
|
||||
): { mutate: (current: SchemaPackManifest) => SchemaPackManifest; auditContext: { type?: string; prefix?: string } } {
|
||||
switch (m.op) {
|
||||
case 'add_type':
|
||||
return {
|
||||
mutate: buildAddTypeMutator({
|
||||
name: m.name as string,
|
||||
primitive: m.primitive as never,
|
||||
prefix: m.prefix as string,
|
||||
extractable: m.extractable as boolean | undefined,
|
||||
expertRouting: m.expert_routing as boolean | undefined,
|
||||
aliases: m.aliases as string[] | undefined,
|
||||
}),
|
||||
auditContext: { type: m.name as string, prefix: m.prefix as string },
|
||||
};
|
||||
case 'remove_type':
|
||||
return { mutate: buildRemoveTypeMutator(m.name as string), auditContext: { type: m.name as string } };
|
||||
case 'update_type':
|
||||
return {
|
||||
mutate: buildUpdateTypeMutator({ name: m.name as string, patch: (m.patch as object) ?? {} }),
|
||||
auditContext: { type: m.name as string },
|
||||
};
|
||||
case 'add_alias':
|
||||
return { mutate: buildAddAliasMutator(m.type as string, m.alias as string), auditContext: { type: m.type as string } };
|
||||
case 'remove_alias':
|
||||
return { mutate: buildRemoveAliasMutator(m.type as string, m.alias as string), auditContext: { type: m.type as string } };
|
||||
case 'add_prefix':
|
||||
return {
|
||||
mutate: buildAddPrefixMutator(m.type as string, m.prefix as string),
|
||||
auditContext: { type: m.type as string, prefix: m.prefix as string },
|
||||
};
|
||||
case 'remove_prefix':
|
||||
return {
|
||||
mutate: buildRemovePrefixMutator(m.type as string, m.prefix as string),
|
||||
auditContext: { type: m.type as string, prefix: m.prefix as string },
|
||||
};
|
||||
case 'add_link_type':
|
||||
return {
|
||||
mutate: buildAddLinkTypeMutator({
|
||||
name: m.name as string,
|
||||
inverse: m.inverse as string | undefined,
|
||||
inference: m.inference as { regex?: string; page_type?: string; target_type?: string } | undefined,
|
||||
}),
|
||||
auditContext: { type: m.name as string },
|
||||
};
|
||||
case 'remove_link_type':
|
||||
return { mutate: buildRemoveLinkTypeMutator(m.name as string), auditContext: { type: m.name as string } };
|
||||
case 'set_extractable':
|
||||
return {
|
||||
mutate: buildUpdateTypeMutator({ name: m.type as string, patch: { extractable: m.value as boolean } }),
|
||||
auditContext: { type: m.type as string },
|
||||
};
|
||||
case 'set_expert_routing':
|
||||
return {
|
||||
mutate: buildUpdateTypeMutator({ name: m.type as string, patch: { expert_routing: m.value as boolean } }),
|
||||
auditContext: { type: m.type as string },
|
||||
};
|
||||
default:
|
||||
throw new SchemaPackMutationError('INVALID_RESULT', `unknown mutation op: '${m.op}' at index ${index}`, { index, op: m.op });
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyMutationsAtomic(
|
||||
packName: string,
|
||||
mutations: BatchMutationRequest[],
|
||||
opts: MutateOpts,
|
||||
): Promise<BatchMutationResult[]> {
|
||||
const actor: MutationActor = opts.actor ?? 'cli';
|
||||
const firstOp = (mutations[0]?.op as MutationOp) ?? 'add_type';
|
||||
|
||||
// Bundled-pack guard, same as withMutation step 1 — happens once for
|
||||
// the whole batch since `pack` is constant across mutations.
|
||||
let path: string;
|
||||
let format: PackFileFormat;
|
||||
try {
|
||||
({ path, format } = locateMutablePackFile(packName));
|
||||
} catch (e) {
|
||||
if (e instanceof SchemaPackMutationError) {
|
||||
await logMutationFailure({ op: firstOp, pack: packName, actor, reason: e.code, batch_id: opts.batchId });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
return withPackLock(packName, opts, async () => {
|
||||
let current: SchemaPackManifest;
|
||||
let batchPrevSha8: string;
|
||||
try {
|
||||
current = loadPackFromFile(path);
|
||||
batchPrevSha8 = await computeManifestSha8(current);
|
||||
} catch (e) {
|
||||
const err = new SchemaPackMutationError(
|
||||
'PACK_CORRUPT',
|
||||
`cannot read or parse pack file at ${path}: ${(e as Error).message}`,
|
||||
{ path },
|
||||
);
|
||||
await logMutationFailure({ op: firstOp, pack: packName, actor, reason: err.code, batch_id: opts.batchId });
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Phase 1: apply + lint-validate every mutation against the IN-MEMORY
|
||||
// manifest only. Nothing here touches disk — a throw at any index
|
||||
// propagates straight out (lock released by withPackLock's finally)
|
||||
// and `path` is left completely untouched.
|
||||
const pending: Array<{ index: number; op: string; auditContext: { type?: string; prefix?: string }; prevSha8: string; newSha8: string }> = [];
|
||||
let runningPrevSha8 = batchPrevSha8;
|
||||
for (let i = 0; i < mutations.length; i++) {
|
||||
const m = mutations[i]!;
|
||||
const opForAudit = (m.op as MutationOp) ?? firstOp;
|
||||
const built = buildBatchMutator(m, i); // shape validation — unaudited, matches single-mutation contract
|
||||
let next: SchemaPackManifest;
|
||||
try {
|
||||
next = built.mutate(current);
|
||||
} catch (e) {
|
||||
const base = e instanceof SchemaPackMutationError ? e : new SchemaPackMutationError('INVALID_RESULT', (e as Error).message);
|
||||
// Re-wrap so `details.index` is always present for the batch
|
||||
// caller (operations.ts) to report which mutation failed,
|
||||
// without losing the primitive's own code/message/details.
|
||||
const wrapped = new SchemaPackMutationError(base.code, base.message, { ...base.details, index: i });
|
||||
await logMutationFailure({
|
||||
op: opForAudit, pack: packName, actor, ...built.auditContext,
|
||||
reason: wrapped.code, prev_sha8: runningPrevSha8, batch_id: opts.batchId,
|
||||
});
|
||||
throw wrapped;
|
||||
}
|
||||
const lintReport = await runFilePlaneLintRules(next);
|
||||
if (!lintReport.ok) {
|
||||
const msg = lintReport.errors.map((iss) => `${iss.rule}: ${iss.message}`).join('; ');
|
||||
const err = new SchemaPackMutationError('INVALID_RESULT', `mutation would produce invalid pack: ${msg}`, { index: i, errors: lintReport.errors });
|
||||
await logMutationFailure({
|
||||
op: opForAudit, pack: packName, actor, ...built.auditContext,
|
||||
reason: err.code, prev_sha8: runningPrevSha8, batch_id: opts.batchId,
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
const newSha8 = await computeManifestSha8(next);
|
||||
pending.push({ index: i, op: m.op, auditContext: built.auditContext, prevSha8: runningPrevSha8, newSha8 });
|
||||
current = next;
|
||||
runningPrevSha8 = newSha8;
|
||||
}
|
||||
|
||||
// Phase 2: every mutation validated clean — write ONCE.
|
||||
try {
|
||||
writePackManifest(path, current, format);
|
||||
} catch (e) {
|
||||
const err = e instanceof SchemaPackMutationError ? e : new SchemaPackMutationError('IO_ERROR', (e as Error).message, { path });
|
||||
const last = pending[pending.length - 1];
|
||||
await logMutationFailure({
|
||||
op: (last?.op as MutationOp) ?? firstOp, pack: packName, actor, ...(last?.auditContext ?? {}),
|
||||
reason: err.code, prev_sha8: batchPrevSha8, batch_id: opts.batchId,
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Step 7 equivalent: best-effort post-hooks, once for the whole batch.
|
||||
try { invalidatePackCache(packName); } catch { /* swallow — cache invalidation must not block mutation success */ }
|
||||
if (opts.engine) {
|
||||
try { await invalidateQueryCache(opts.engine, opts.sourceId); } catch { /* swallow */ }
|
||||
}
|
||||
|
||||
// Only now — after the single write has actually landed on disk — do
|
||||
// we log success and report results. Nothing above this point may
|
||||
// ever be reported as applied.
|
||||
const results: BatchMutationResult[] = [];
|
||||
for (const p of pending) {
|
||||
await logMutationSuccess({
|
||||
op: p.op as MutationOp, pack: packName, actor, ...p.auditContext,
|
||||
prev_sha8: p.prevSha8, new_sha8: p.newSha8, batch_id: opts.batchId,
|
||||
});
|
||||
results.push({ index: p.index, op: p.op, pack: packName, path, format, prev_sha8: p.prevSha8, new_sha8: p.newSha8 });
|
||||
}
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -48,6 +48,32 @@ import {
|
||||
|
||||
export const RRF_K = 60;
|
||||
const COMPILED_TRUTH_BOOST = 2.0;
|
||||
|
||||
/**
|
||||
* Which detail levels get the compiled_truth boost (#3430).
|
||||
*
|
||||
* ONLY `low`. The documented contract (`src/core/operations.ts`) is
|
||||
* "low (compiled truth only), medium (default, all with dedup), high (all
|
||||
* chunks)" — so `low` is the level that privileges compiled truth, and both
|
||||
* `medium` and `high` are supposed to see everything on equal footing.
|
||||
*
|
||||
* This was previously spelled `detail !== 'high'`, i.e. written as though
|
||||
* `high` were the special case. Because COMPILED_TRUTH_BOOST is applied AFTER
|
||||
* RRF normalization, and RRF's whole range over a 100-deep pool is 1/60 → 1/160,
|
||||
* a 2.0x multiplier is not a tilt — break-even is `2/(60+r) >= 1/60`, so any
|
||||
* boosted chunk inside the first 60 ranks outranks an unboosted rank-1 chunk.
|
||||
* At the default detail that made search categorically compiled-truth-only:
|
||||
* a page whose answer lived in a `fenced_code` chunk returned the prose chunk,
|
||||
* and the code chunk fell out of the window entirely.
|
||||
*
|
||||
* Extracted as a named predicate rather than left inline at three call sites so
|
||||
* the detail→boost mapping is directly testable. An inline expression can only
|
||||
* be covered through a full `hybridSearch` round trip, which is why the
|
||||
* original inversion went unnoticed.
|
||||
*/
|
||||
export function shouldBoostCompiledTruth(detail: string | null | undefined): boolean {
|
||||
return detail === 'low';
|
||||
}
|
||||
const pendingCacheWrites = new Set<Promise<unknown>>();
|
||||
|
||||
/**
|
||||
@@ -841,11 +867,12 @@ export async function embedQueryBounded(
|
||||
embedOpts: { embeddingModel?: string; dimensions?: number } | undefined,
|
||||
dl: QueryEmbedDeadline,
|
||||
): Promise<Float32Array> {
|
||||
const p = embedQuery(text, { ...(embedOpts ?? {}), abortSignal: dl.signal });
|
||||
p.catch(() => { /* swallow the loser's late rejection */ });
|
||||
// Floor the budget so a healthy embed isn't starved when the shared absolute
|
||||
// deadline was mostly consumed by prior work (codex). Still bounded overall.
|
||||
const remaining = Math.max(MIN_QUERY_EMBED_BUDGET_MS, dl.deadlineAt - Date.now());
|
||||
const signal = AbortSignal.timeout(remaining);
|
||||
const p = embedQuery(text, { ...(embedOpts ?? {}), abortSignal: signal });
|
||||
p.catch(() => { /* swallow the loser's late rejection */ });
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
@@ -1169,7 +1196,7 @@ export async function hybridSearch(
|
||||
const noEmbedLists = [{ list: keywordResults, k: fk }];
|
||||
if (titleResults.length > 0) noEmbedLists.push({ list: titleResults, k: fk });
|
||||
if (relationalList.length > 0) noEmbedLists.push({ list: relationalList, k: fk });
|
||||
noEmbedResults = rrfFusionWeighted(noEmbedLists, detailResolved !== 'high');
|
||||
noEmbedResults = rrfFusionWeighted(noEmbedLists, shouldBoostCompiledTruth(detailResolved));
|
||||
}
|
||||
if (noEmbedResults.length > 0) {
|
||||
await runPostFusionStages(engine, noEmbedResults, postFusionOpts);
|
||||
@@ -1413,7 +1440,7 @@ export async function hybridSearch(
|
||||
const fallbackLists = [{ list: keywordResults, k: fk }];
|
||||
if (titleResults.length > 0) fallbackLists.push({ list: titleResults, k: fk });
|
||||
if (relationalList.length > 0) fallbackLists.push({ list: relationalList, k: fk });
|
||||
fallbackResults = rrfFusionWeighted(fallbackLists, detail !== 'high');
|
||||
fallbackResults = rrfFusionWeighted(fallbackLists, shouldBoostCompiledTruth(detail));
|
||||
}
|
||||
if (fallbackResults.length > 0) {
|
||||
await runPostFusionStages(engine, fallbackResults, postFusionOpts);
|
||||
@@ -1500,7 +1527,7 @@ export async function hybridSearch(
|
||||
// arms BEFORE fusion so the compiled-truth authority boost skips them.
|
||||
await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list));
|
||||
|
||||
let fused = rrfFusionWeighted(allLists, detail !== 'high');
|
||||
let fused = rrfFusionWeighted(allLists, shouldBoostCompiledTruth(detail));
|
||||
|
||||
// Cosine re-scoring before dedup so semantically better chunks survive.
|
||||
// v0.36 (D9): hydrate from the active embedding column so rescore happens
|
||||
|
||||
+24
-1
@@ -25,6 +25,7 @@
|
||||
|
||||
import { createHash } from 'crypto';
|
||||
import { CR_MODES, type CRMode } from '../types.ts';
|
||||
import { getFtsLanguage } from '../fts-language.ts';
|
||||
import { getRecipe } from '../ai/recipes/index.ts';
|
||||
|
||||
/**
|
||||
@@ -766,7 +767,19 @@ export function attributeKnob<K extends keyof ModeBundle>(
|
||||
// written between the #3391 stale-fix (which changes which chunks count as
|
||||
// current) and the operator's migration run. Same one-time global cold-miss
|
||||
// pattern as the bumps above.
|
||||
export const KNOBS_HASH_VERSION = 13;
|
||||
//
|
||||
// bump 14→15: the FTS configuration name (GBRAIN_FTS_LANGUAGE, resolved by
|
||||
// getFtsLanguage()) folds into the key via the `fts=` part. It reaches BOTH
|
||||
// engines' keyword SQL (websearch_to_tsquery/to_tsvector in postgres-engine
|
||||
// and pglite-engine) and the two search_vector trigger functions, so it
|
||||
// changes which rows the keyword arm returns — but it only applied at
|
||||
// DB-query build time (cache miss). Switching language and running
|
||||
// `gbrain reindex-search-vector` therefore left every pre-switch query_cache
|
||||
// row reachable: the freshly retokenized index was silently bypassed for up
|
||||
// to cache.ttl_seconds, with no warning and no way for an operator to tell.
|
||||
// Same one-time global cold-miss pattern as the bumps above; refills within
|
||||
// cache.ttl_seconds (3600s default).
|
||||
export const KNOBS_HASH_VERSION = 15;
|
||||
|
||||
/**
|
||||
* v0.36 (D8 / CDX-2) — second-arg context for the cache key. The
|
||||
@@ -898,6 +911,16 @@ export function knobsHash(
|
||||
// across processes. Sorted copy so ['a/','b/'] and ['b/','a/'] hash
|
||||
// identically; undefined falls back to 'none' for legacy callers.
|
||||
`hx=${ctx?.hardExcludes ? [...ctx.hardExcludes].sort().join(',') : 'none'}`,
|
||||
// v=15 addition (append-only): the resolved FTS configuration name. Read
|
||||
// from getFtsLanguage() rather than threaded through KnobsHashContext on
|
||||
// purpose — the language is a process-global env read with no per-call
|
||||
// dimension, and the `prov=` bump note above records what threading costs:
|
||||
// a ctx field only isolates callers that pass it, so legacy callers keep
|
||||
// hashing the fallback literal on both sides of a switch. Reading it here
|
||||
// covers every knobsHash() caller, present and future. getFtsLanguage()
|
||||
// memoizes and validates against /^[a-z][a-z0-9_]*$/, so this stays a
|
||||
// cheap, bounded string.
|
||||
`fts=${getFtsLanguage()}`,
|
||||
];
|
||||
const h = createHash('sha256');
|
||||
h.update(parts.join('|'));
|
||||
|
||||
@@ -96,7 +96,7 @@ const ENTITY_PATTERNS = [
|
||||
/\boverview\b/i,
|
||||
/\bbackground\b/i,
|
||||
/\bprofile\b/i,
|
||||
/\bwhat\s+do\s+(you|we)\s+know\b/i,
|
||||
/\bwhat\s+do\s+(i|you|we)\s+know\b/i,
|
||||
];
|
||||
|
||||
const FULL_CONTEXT_PATTERNS = [
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import { existsSync, readFileSync, statSync, readdirSync } from 'fs';
|
||||
import { join, dirname, isAbsolute, resolve } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { parseMarkdown } from '../markdown.ts';
|
||||
|
||||
@@ -38,19 +39,45 @@ export class BundleError extends Error {
|
||||
/**
|
||||
* Walk up from `start` (default cwd) looking for an `openclaw.plugin.json`
|
||||
* sibling to `src/cli.ts`. That pair identifies a gbrain repo root.
|
||||
*
|
||||
* When no explicit `start` is given and the cwd walk fails (e.g. gbrain was
|
||||
* installed globally via `bun install -g` and the user is in an unrelated
|
||||
* directory, #1917), fall back to walking up from this module's own location
|
||||
* and from the running entrypoint (`process.argv[1]`). Both resolve the
|
||||
* bun-global layout (~/.bun/install/global/node_modules/gbrain/) and the
|
||||
* in-repo compiled binary (bin/gbrain).
|
||||
*/
|
||||
export function findGbrainRoot(start: string = process.cwd()): string | null {
|
||||
let dir = resolve(start);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
if (
|
||||
existsSync(join(dir, 'openclaw.plugin.json')) &&
|
||||
existsSync(join(dir, 'src', 'cli.ts'))
|
||||
) {
|
||||
return dir;
|
||||
export function findGbrainRoot(start?: string): string | null {
|
||||
const walkUp = (from: string): string | null => {
|
||||
let dir = resolve(from);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
if (
|
||||
existsSync(join(dir, 'openclaw.plugin.json')) &&
|
||||
existsSync(join(dir, 'src', 'cli.ts'))
|
||||
) {
|
||||
return dir;
|
||||
}
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
return null;
|
||||
};
|
||||
|
||||
const found = walkUp(start ?? process.cwd());
|
||||
if (found !== null || start !== undefined) return found;
|
||||
|
||||
const fallbacks: string[] = [];
|
||||
try {
|
||||
// Not a file:// URL inside a compiled binary; skip on error.
|
||||
fallbacks.push(dirname(fileURLToPath(import.meta.url)));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (process.argv[1]) fallbacks.push(dirname(resolve(process.argv[1])));
|
||||
for (const candidate of fallbacks) {
|
||||
const root = walkUp(candidate);
|
||||
if (root !== null) return root;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,17 @@
|
||||
|
||||
export const SOURCE_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
|
||||
|
||||
/**
|
||||
* Sentinel meaning "span every source" (#1712). Deliberately NOT a valid
|
||||
* source id (underscores are rejected by SOURCE_ID_RE), so it can never
|
||||
* collide with a real source, be created via `sources add`, or leak into
|
||||
* lock ids / path joins. The resolver's explicit/env tiers pass it through
|
||||
* verbatim; `sourceScopeOpts` translates it to an unscoped read for trusted
|
||||
* local callers and keeps it as an unsatisfiable literal for remote callers
|
||||
* (fail-closed).
|
||||
*/
|
||||
export const ALL_SOURCES = '__all__';
|
||||
|
||||
/** Returns true if the string matches the canonical source_id regex. */
|
||||
export function isValidSourceId(s: unknown): s is string {
|
||||
return typeof s === 'string' && SOURCE_ID_RE.test(s);
|
||||
|
||||
@@ -17,9 +17,13 @@ import { readFileSync, lstatSync, type Stats } from 'fs';
|
||||
import { join, dirname, resolve } from 'path';
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import { isSourceFederated } from './sources-load.ts';
|
||||
import { SOURCE_ID_RE, isValidSourceId } from './source-id.ts';
|
||||
import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';
|
||||
import { isTrustedDotfile, realpathOrResolve } from './path-confine.ts';
|
||||
|
||||
// Re-export so scope-resolution call sites can import the sentinel from
|
||||
// either module (#1712).
|
||||
export { ALL_SOURCES };
|
||||
|
||||
const DOTFILE = '.gbrain-source';
|
||||
// Canonical SOURCE_ID_RE imported from `source-id.ts` (single source of truth).
|
||||
// Re-exported below as `__testing.SOURCE_ID_RE` for legacy test imports.
|
||||
@@ -83,8 +87,11 @@ export async function resolveSourceId(
|
||||
explicit: string | null | undefined,
|
||||
cwd: string = process.cwd(),
|
||||
): Promise<string> {
|
||||
// 1. Explicit flag wins.
|
||||
// 1. Explicit flag wins. The __all__ sentinel passes through verbatim
|
||||
// (#1712) — it is not a source id, so it skips both the regex and
|
||||
// assertSourceExists; sourceScopeOpts gives it span-everything semantics.
|
||||
if (explicit) {
|
||||
if (explicit === ALL_SOURCES) return ALL_SOURCES;
|
||||
if (!SOURCE_ID_RE.test(explicit)) {
|
||||
throw new Error(`Invalid --source value "${explicit}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
@@ -92,9 +99,10 @@ export async function resolveSourceId(
|
||||
return explicit;
|
||||
}
|
||||
|
||||
// 2. Env var.
|
||||
// 2. Env var. Same __all__ pass-through (#2140).
|
||||
const env = process.env.GBRAIN_SOURCE;
|
||||
if (env && env.length > 0) {
|
||||
if (env === ALL_SOURCES) return ALL_SOURCES;
|
||||
if (!SOURCE_ID_RE.test(env)) {
|
||||
throw new Error(`Invalid GBRAIN_SOURCE value "${env}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
@@ -173,6 +181,7 @@ export function resolveSourceIdEngineFree(
|
||||
cwd: string = process.cwd(),
|
||||
): string | null {
|
||||
if (explicit) {
|
||||
if (explicit === ALL_SOURCES) return ALL_SOURCES; // #1712 sentinel pass-through
|
||||
if (!SOURCE_ID_RE.test(explicit)) {
|
||||
throw new Error(`Invalid --source value "${explicit}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
@@ -180,6 +189,7 @@ export function resolveSourceIdEngineFree(
|
||||
}
|
||||
const env = process.env.GBRAIN_SOURCE;
|
||||
if (env && env.length > 0) {
|
||||
if (env === ALL_SOURCES) return ALL_SOURCES; // #2140 sentinel pass-through
|
||||
if (!SOURCE_ID_RE.test(env)) {
|
||||
throw new Error(`Invalid GBRAIN_SOURCE value "${env}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
@@ -315,8 +325,11 @@ export async function resolveSourceWithTier(
|
||||
explicit: string | null | undefined,
|
||||
cwd: string = process.cwd(),
|
||||
): Promise<{ source_id: string; tier: SourceTier; detail?: string }> {
|
||||
// 1. Explicit flag wins.
|
||||
// 1. Explicit flag wins. __all__ sentinel passes through verbatim (#1712).
|
||||
if (explicit) {
|
||||
if (explicit === ALL_SOURCES) {
|
||||
return { source_id: ALL_SOURCES, tier: 'flag', detail: `--source ${ALL_SOURCES} (spans all sources)` };
|
||||
}
|
||||
if (!SOURCE_ID_RE.test(explicit)) {
|
||||
throw new Error(`Invalid --source value "${explicit}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
@@ -324,9 +337,12 @@ export async function resolveSourceWithTier(
|
||||
return { source_id: explicit, tier: 'flag', detail: `--source ${explicit}` };
|
||||
}
|
||||
|
||||
// 2. Env var.
|
||||
// 2. Env var. Same __all__ pass-through (#2140).
|
||||
const env = process.env.GBRAIN_SOURCE;
|
||||
if (env && env.length > 0) {
|
||||
if (env === ALL_SOURCES) {
|
||||
return { source_id: ALL_SOURCES, tier: 'env', detail: `GBRAIN_SOURCE=${ALL_SOURCES} (spans all sources)` };
|
||||
}
|
||||
if (!SOURCE_ID_RE.test(env)) {
|
||||
throw new Error(`Invalid GBRAIN_SOURCE value "${env}". Must match [a-z0-9-]{1,32}.`);
|
||||
}
|
||||
|
||||
+13
-8
@@ -11,7 +11,7 @@
|
||||
* pathToSlug() → convert file paths to page slugs
|
||||
*/
|
||||
|
||||
import { CJK_SLUG_CHARS } from './cjk.ts';
|
||||
import { SLUG_WORD_CHARS } from './cjk.ts';
|
||||
// v0.37.7.0 #1169 submodule-detection helpers. Bottom-of-file already
|
||||
// aliases existsSync as `_existsSync` for other purposes; the top-of-file
|
||||
// import keeps the pruneDir helper's deps near its callsite.
|
||||
@@ -396,8 +396,10 @@ export function unsyncableReason(path: string, opts: SyncableOptions = {}): Sync
|
||||
|
||||
/**
|
||||
* Character class for the lowercase-canonical form of a slug segment after
|
||||
* slugifySegment() has run. Lowercase letters, digits, dots, underscores,
|
||||
* hyphens. Exposed so adjacent code (e.g. takes-fence holder validation,
|
||||
* slugifySegment() has run. Letters/numbers in any script (lowercase where
|
||||
* the script has case — #3417), dots, underscores, hyphens. Uses \p{...}
|
||||
* classes, so composed regexes need the `u` flag (this one carries it).
|
||||
* Exposed so adjacent code (e.g. takes-fence holder validation,
|
||||
* v0.32 EXP-4) can reuse the actual repo slug grammar instead of inventing
|
||||
* a stricter parallel one and emitting false-positive warnings on legitimate
|
||||
* `companies/acme.io` / `people/foo_bar` slugs (codex review #3).
|
||||
@@ -405,15 +407,18 @@ export function unsyncableReason(path: string, opts: SyncableOptions = {}): Sync
|
||||
* Pattern is the inner character class only (no anchors); callers wrap it
|
||||
* in `^...$` or compose it with prefixes like `(?:people|companies)/...`.
|
||||
*/
|
||||
export const SLUG_SEGMENT_PATTERN = new RegExp(`[a-z0-9._\\-${CJK_SLUG_CHARS}]+`);
|
||||
export const SLUG_SEGMENT_PATTERN = new RegExp(`[${SLUG_WORD_CHARS}._\\-]+`, 'u');
|
||||
|
||||
/**
|
||||
* Slugify a single path segment: lowercase, strip special chars, spaces → hyphens.
|
||||
* CJK ranges (Han / Hiragana / Katakana / Hangul Syllables) are preserved (v0.32.7).
|
||||
* NFC re-normalize after the NFD-strip-accents pass so Hangul Jamo recomposes back
|
||||
* into precomposed syllables that fall inside the whitelist.
|
||||
* Letters and numbers from EVERY script are preserved (#3417): previously only
|
||||
* Latin + CJK survived, so Hebrew/Arabic/Cyrillic/Greek/Thai/... filenames
|
||||
* collapsed to empty segments and distinct files silently merged onto one slug.
|
||||
* NFC re-normalize after the NFD-strip-accents pass so Hangul Jamo recomposes
|
||||
* back into precomposed syllables, and so NFD filenames (macOS) and NFC
|
||||
* filenames (Linux/git) of the same name produce the SAME slug.
|
||||
*/
|
||||
const SLUGIFY_KEEP_RE = new RegExp(`[^a-z0-9.\\s_\\-${CJK_SLUG_CHARS}]`, 'g');
|
||||
const SLUGIFY_KEEP_RE = new RegExp(`[^${SLUG_WORD_CHARS}.\\s_\\-]`, 'gu');
|
||||
|
||||
export function slugifySegment(segment: string): string {
|
||||
return segment
|
||||
|
||||
@@ -134,6 +134,7 @@ export const TAKES_FENCE_END = '<!--- gbrain:takes:end -->';
|
||||
import { SLUG_SEGMENT_PATTERN } from './sync.ts';
|
||||
export const HOLDER_REGEX = new RegExp(
|
||||
`^(?:world|brain|(?:people|companies)/${SLUG_SEGMENT_PATTERN.source}|${SLUG_SEGMENT_PATTERN.source})$`,
|
||||
'u', // required by SLUG_SEGMENT_PATTERN's \p{...} classes (#3417)
|
||||
);
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface ModelPricing {
|
||||
const SUPPORTED_MODELS = [
|
||||
'openai:gpt-4o',
|
||||
'openai:gpt-5',
|
||||
'openai:gpt-5.2',
|
||||
'openai:gpt-5.5',
|
||||
'anthropic:claude-opus-5',
|
||||
'anthropic:claude-opus-4-8',
|
||||
@@ -41,7 +42,9 @@ const SUPPORTED_MODELS = [
|
||||
'anthropic:claude-sonnet-5',
|
||||
'anthropic:claude-sonnet-4-6',
|
||||
'anthropic:claude-haiku-4-5',
|
||||
'google:gemini-1.5-pro',
|
||||
// gemini-1.5-pro was retired by Google (#3510); gemini-2.0-flash replaces
|
||||
// it in DEFAULT_MODEL_PANEL. `gemini-2-flash` stays as the legacy alias.
|
||||
'google:gemini-2.0-flash',
|
||||
'google:gemini-2-flash',
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -33,10 +33,17 @@ import type { TakesQualityReceipt } from './receipt.ts';
|
||||
import { estimateCost, getPricing, PricingNotFoundError } from './pricing.ts';
|
||||
import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';
|
||||
|
||||
/**
|
||||
* Three distinct providers (uncorrelated judge blind spots). Every entry MUST
|
||||
* be listed in its recipe's chat touchpoint AND in the SUPPORTED_MODELS
|
||||
* pricing allowlist — pinned by test/default-model-panels.test.ts.
|
||||
* google:gemini-1.5-pro (retired by Google) and openai:gpt-4o (dropped from
|
||||
* the OpenAI recipe's chat list) sat here dead until #3510.
|
||||
*/
|
||||
export const DEFAULT_MODEL_PANEL = [
|
||||
'openai:gpt-4o',
|
||||
'openai:gpt-5.2',
|
||||
'anthropic:claude-opus-4-7',
|
||||
'google:gemini-1.5-pro',
|
||||
'google:gemini-2.0-flash',
|
||||
] as const;
|
||||
|
||||
export interface RunOpts {
|
||||
|
||||
@@ -1203,7 +1203,11 @@ export interface CodeEdgeResult {
|
||||
// Links
|
||||
export interface Link {
|
||||
from_slug: string;
|
||||
/** Exact source identity of the from-page joined by from_page_id. */
|
||||
from_source_id: string;
|
||||
to_slug: string;
|
||||
/** Exact source identity of the to-page joined by to_page_id. */
|
||||
to_source_id: string;
|
||||
link_type: string;
|
||||
context: string;
|
||||
/**
|
||||
@@ -1221,6 +1225,8 @@ export interface Link {
|
||||
* multiple pages reference the same (from, to, type) tuple.
|
||||
*/
|
||||
origin_slug?: string | null;
|
||||
/** Exact source identity of origin_slug; null when absent or grant-redacted. */
|
||||
origin_source_id?: string | null;
|
||||
/**
|
||||
* The frontmatter field name that created this edge (e.g. 'key_people',
|
||||
* 'investors'). Used for debug output and the `unresolved` response list.
|
||||
|
||||
@@ -110,6 +110,12 @@ export function rowToPage(row: Record<string, unknown>): Page {
|
||||
const sourceUri = row.source_uri === undefined ? undefined : (row.source_uri as string | null);
|
||||
const ingestedVia = row.ingested_via === undefined ? undefined : (row.ingested_via as string | null);
|
||||
const ingestedAt = readOptionalDate(row.ingested_at);
|
||||
// #3507: the CR tier the page was last embedded under (three-state, same
|
||||
// pattern as the provenance columns above). Re-embed paths (`embed --stale`
|
||||
// and friends) read this to reproduce the page's stored wrapping convention.
|
||||
const contextualRetrievalMode = row.contextual_retrieval_mode === undefined
|
||||
? undefined
|
||||
: (row.contextual_retrieval_mode as Page['contextual_retrieval_mode']);
|
||||
return {
|
||||
id: row.id as number,
|
||||
slug: row.slug as string,
|
||||
@@ -135,6 +141,7 @@ export function rowToPage(row: Record<string, unknown>): Page {
|
||||
...(sourceUri !== undefined && { source_uri: sourceUri }),
|
||||
...(ingestedVia !== undefined && { ingested_via: ingestedVia }),
|
||||
...(ingestedAt !== undefined && { ingested_at: ingestedAt }),
|
||||
...(contextualRetrievalMode !== undefined && { contextual_retrieval_mode: contextualRetrievalMode }),
|
||||
// v0.31.12: propagate source_id so downstream callers (embed, reconcile-links)
|
||||
// can thread it through getChunks / upsertChunks without defaulting to 'default'.
|
||||
// v0.32.8: Page.source_id is required. Every SELECT feeding rowToPage now
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { openAdminSseStream, type AdminSseResponse } from '../src/commands/serve-http.ts';
|
||||
|
||||
describe('admin SSE handshake', () => {
|
||||
test('flushes a protocol-valid comment immediately after the headers', () => {
|
||||
const calls: string[] = [];
|
||||
const headers = new Map<string, string>();
|
||||
|
||||
openAdminSseStream({
|
||||
setHeader(name: string, value: string | number | readonly string[]) {
|
||||
headers.set(name, String(value));
|
||||
calls.push(`header:${name}`);
|
||||
return this;
|
||||
},
|
||||
flushHeaders() {
|
||||
calls.push('flush');
|
||||
},
|
||||
write(chunk: unknown) {
|
||||
calls.push(`write:${String(chunk)}`);
|
||||
return true;
|
||||
},
|
||||
} as unknown as AdminSseResponse);
|
||||
|
||||
expect(headers).toEqual(new Map([
|
||||
['Content-Type', 'text/event-stream'],
|
||||
['Cache-Control', 'no-cache'],
|
||||
['Connection', 'keep-alive'],
|
||||
]));
|
||||
expect(calls).toEqual([
|
||||
'header:Content-Type',
|
||||
'header:Cache-Control',
|
||||
'header:Connection',
|
||||
'flush',
|
||||
'write:: connected\n\n',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
__getShrinkStateForTests,
|
||||
} from '../../src/core/ai/gateway.ts';
|
||||
import { AIConfigError, AITransientError } from '../../src/core/ai/errors.ts';
|
||||
import { __setTestRecipesForTests } from '../../src/core/ai/recipes/index.ts';
|
||||
import type { Recipe } from '../../src/core/ai/types.ts';
|
||||
|
||||
// The last test in this file leaves the gateway configured with a remote
|
||||
// provider + fake key and a REAL embed transport. Without a final reset,
|
||||
@@ -94,6 +96,31 @@ function configureGoogle(): void {
|
||||
});
|
||||
}
|
||||
|
||||
// A recipe that declares an embedding touchpoint but omits every batch cap.
|
||||
// Every shipped recipe now declares one (google gained max_batch_tokens), so
|
||||
// the startup warning is exercised against this synthetic cap-less recipe —
|
||||
// injected into the registry only for the duration of the test that needs it.
|
||||
const CAPLESS_RECIPE: Recipe = {
|
||||
id: 'synthetic-capless',
|
||||
name: 'Synthetic cap-less (test fixture)',
|
||||
tier: 'openai-compat',
|
||||
implementation: 'openai-compatible',
|
||||
touchpoints: {
|
||||
embedding: {
|
||||
models: ['synthetic-embed-1'],
|
||||
default_dims: 768,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function configureCapless(): void {
|
||||
configureGateway({
|
||||
embedding_model: 'synthetic-capless:synthetic-embed-1',
|
||||
embedding_dimensions: 768,
|
||||
env: {},
|
||||
});
|
||||
}
|
||||
|
||||
// --------- 1. Pure helpers ---------
|
||||
|
||||
describe('splitByTokenBudget (pure helper)', () => {
|
||||
@@ -429,20 +456,22 @@ describe('startup warning for recipes missing max_batch_tokens', () => {
|
||||
beforeEach(() => resetGateway());
|
||||
|
||||
test('configured missing-cap recipe warns once; unrelated recipes stay quiet', () => {
|
||||
__setTestRecipesForTests([CAPLESS_RECIPE]);
|
||||
const warnings: string[] = [];
|
||||
const original = console.warn;
|
||||
console.warn = (msg: string) => warnings.push(String(msg));
|
||||
try {
|
||||
configureOpenAI();
|
||||
expect(warnings.length).toBe(0);
|
||||
configureGoogle();
|
||||
configureCapless();
|
||||
const firstCallCount = warnings.length;
|
||||
// Reconfigure: the warning should NOT re-fire for the same recipes
|
||||
// Reconfigure: the warning should NOT re-fire for the same recipe
|
||||
// within one process (we already told the operator).
|
||||
configureGoogle();
|
||||
configureCapless();
|
||||
expect(warnings.length).toBe(firstCallCount);
|
||||
} finally {
|
||||
console.warn = original;
|
||||
__setTestRecipesForTests([]);
|
||||
}
|
||||
|
||||
// The warning text should match the documented contract.
|
||||
@@ -451,11 +480,12 @@ describe('startup warning for recipes missing max_batch_tokens', () => {
|
||||
);
|
||||
expect(contractMatch.length).toBe(1);
|
||||
|
||||
// Voyage declares max_batch_tokens → suppressed. OpenAI is the
|
||||
// canonical fast-path recipe → also suppressed by id. Both must be
|
||||
// absent from the warnings.
|
||||
// Voyage + google declare max_batch_tokens → suppressed. OpenAI is the
|
||||
// canonical fast-path recipe → also suppressed by id. Only the synthetic
|
||||
// cap-less recipe warns.
|
||||
expect(warnings.find(w => w.includes('"voyage"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"openai"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"google"'))).toBeDefined();
|
||||
expect(warnings.find(w => w.includes('"google"'))).toBeUndefined();
|
||||
expect(warnings.find(w => w.includes('"synthetic-capless"'))).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { buildGatewayConfig } from '../../src/cli.ts';
|
||||
import type { GBrainConfig } from '../../src/core/config.ts';
|
||||
import { KNOWN_CONFIG_KEYS, type GBrainConfig } from '../../src/core/config.ts';
|
||||
import { withEnv } from '../helpers/with-env.ts';
|
||||
|
||||
const PASSTHROUGHS: Array<{ envVar: string; recipeId: string }> = [
|
||||
@@ -139,6 +139,105 @@ describe('buildGatewayConfig config-plane API-key folding', () => {
|
||||
expect(cfg.env.VOYAGE_API_KEY).toBe('pa-env-plane');
|
||||
});
|
||||
});
|
||||
|
||||
// #3500: dashscope_api_key was accepted at the file plane but never folded,
|
||||
// so the dashscope/dashscope-rerank recipes (required: DASHSCOPE_API_KEY)
|
||||
// could only be keyed via a process-env export.
|
||||
test('dashscope_api_key folds into gateway env as DASHSCOPE_API_KEY', async () => {
|
||||
await withEnv({ DASHSCOPE_API_KEY: undefined }, async () => {
|
||||
const cfg = buildGatewayConfig({
|
||||
dashscope_api_key: 'sk-ds-config-plane',
|
||||
} as unknown as GBrainConfig);
|
||||
expect(cfg.env.DASHSCOPE_API_KEY).toBe('sk-ds-config-plane');
|
||||
});
|
||||
});
|
||||
|
||||
test('a real DASHSCOPE_API_KEY process.env value wins over the config-plane fallback', async () => {
|
||||
await withEnv({ DASHSCOPE_API_KEY: 'sk-ds-env-plane' }, async () => {
|
||||
const cfg = buildGatewayConfig({
|
||||
dashscope_api_key: 'sk-ds-config-plane',
|
||||
} as unknown as GBrainConfig);
|
||||
expect(cfg.env.DASHSCOPE_API_KEY).toBe('sk-ds-env-plane');
|
||||
});
|
||||
});
|
||||
|
||||
// #3500: the google recipe reads GOOGLE_GENERATIVE_AI_API_KEY; before this
|
||||
// fold the ONLY configuration route was exporting that exact env name.
|
||||
test('google_api_key folds into gateway env as GOOGLE_GENERATIVE_AI_API_KEY', async () => {
|
||||
await withEnv(
|
||||
{ GOOGLE_GENERATIVE_AI_API_KEY: undefined, GEMINI_API_KEY: undefined },
|
||||
async () => {
|
||||
const cfg = buildGatewayConfig({
|
||||
google_api_key: 'AIza-config-plane',
|
||||
} as unknown as GBrainConfig);
|
||||
expect(cfg.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('AIza-config-plane');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// Recurring-class guard: EVERY *_api_key field declared in
|
||||
// KNOWN_CONFIG_KEYS must reach the gateway env dict. Adding a new
|
||||
// provider key field to GBrainConfig without folding it in
|
||||
// buildGatewayConfig fails here — the #121/#2662/#3500 bug class.
|
||||
test('every KNOWN_CONFIG_KEYS *_api_key field reaches the gateway env', async () => {
|
||||
const keyFields = KNOWN_CONFIG_KEYS.filter((k) => k.endsWith('_api_key'));
|
||||
expect(keyFields.length).toBeGreaterThanOrEqual(7);
|
||||
for (const field of keyFields) {
|
||||
const sentinel = `sentinel-${field}`;
|
||||
// Clear the two env names the field could map to so config must win.
|
||||
await withEnv(
|
||||
{
|
||||
[field.replace(/_api_key$/, '').toUpperCase() + '_API_KEY']: undefined,
|
||||
GOOGLE_GENERATIVE_AI_API_KEY: undefined,
|
||||
GEMINI_API_KEY: undefined,
|
||||
},
|
||||
async () => {
|
||||
const cfg = buildGatewayConfig({ [field]: sentinel } as unknown as GBrainConfig);
|
||||
expect(
|
||||
Object.values(cfg.env).includes(sentinel),
|
||||
`config field "${field}" never reaches the gateway env — add a fold in buildGatewayConfig`,
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildGatewayConfig GEMINI_API_KEY alias (#3500)', () => {
|
||||
// GEMINI_API_KEY is the env name Google's own docs and SDKs use; the
|
||||
// recipe/gateway read GOOGLE_GENERATIVE_AI_API_KEY. Precedence:
|
||||
// env GOOGLE_GENERATIVE_AI_API_KEY > env GEMINI_API_KEY > config google_api_key.
|
||||
test('GEMINI_API_KEY aliases to GOOGLE_GENERATIVE_AI_API_KEY', async () => {
|
||||
await withEnv(
|
||||
{ GOOGLE_GENERATIVE_AI_API_KEY: undefined, GEMINI_API_KEY: 'AIza-gemini-env' },
|
||||
async () => {
|
||||
const cfg = buildGatewayConfig(baseConfig);
|
||||
expect(cfg.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('AIza-gemini-env');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('canonical GOOGLE_GENERATIVE_AI_API_KEY env wins over the GEMINI_API_KEY alias', async () => {
|
||||
await withEnv(
|
||||
{ GOOGLE_GENERATIVE_AI_API_KEY: 'AIza-canonical', GEMINI_API_KEY: 'AIza-alias' },
|
||||
async () => {
|
||||
const cfg = buildGatewayConfig(baseConfig);
|
||||
expect(cfg.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('AIza-canonical');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('GEMINI_API_KEY (process env) wins over the config-plane google_api_key', async () => {
|
||||
await withEnv(
|
||||
{ GOOGLE_GENERATIVE_AI_API_KEY: undefined, GEMINI_API_KEY: 'AIza-gemini-env' },
|
||||
async () => {
|
||||
const cfg = buildGatewayConfig({
|
||||
google_api_key: 'AIza-config-plane',
|
||||
} as unknown as GBrainConfig);
|
||||
expect(cfg.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('AIza-gemini-env');
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildGatewayConfig env empty-string clobber guard (#1249)', () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user