Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(code-graph): walk and stamp only chunks that own symbol edges in resolve_symbol_edges (#7119)
garrytan08b28c477525
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 600da3e14e..e9644548c2 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -44,7 +44,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The hard cap skips the token count for a chunk whose UTF-8 byte length already fits the token budget (`fitsEmbedTokens` in `token-estimate.ts`: bytes bound both the cl100k count and the weighted CJK estimate), so typical CJK chunks never reach the tiktoken WASM; boundaries are unchanged (`test/chunkers/fits-embed-tokens.test.ts`). The markdown chunker version records the current index format. With `spans: true` each chunk carries `byte_start`/`byte_end`, its exact UTF-8 span in the sanitized, credential-projected text; markdown prose chunks store them as `content_chunks.projected_byte_start/end`.-- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).+- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It walks only chunks that own a `code_edges_symbol` row of their source (`OWNS_EDGE`, checked again under the guards) and returns at once for a source with no such row, so a markdown-only source gets no `edges_backfilled_at` stamps (each is a non-HOT update). It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).- `src/core/code-intel/recursive-walk.ts` (`code_blast` / `code_flow`) + the `chunkId` arm of `getCallersOf` / `getCalleesOf` in `src/core/engine-sql/code-edges.ts` (#5439 item 3, wave 15 P7.8) — the BFS keys its frontier and visited set by source-scoped chunk identity where the hop that reached a node was resolved (a `code_edges_chunk` row's `to_chunk_id`, or `readEdgeResolution(edge_metadata).kind === 'resolved'`), and by qualified name only for unresolved edges; the start is always a name. The next hop from a chunk node reads edges by that chunk (`opts.chunkId`: callees = both tables' `from_chunk_id`; callers = `code_edges_chunk.to_chunk_id` plus `code_edges_symbol` rows whose `edge_metadata.resolved_chunk_id` matches), under the same source filter and current-projection read policy, so two files whose top-level `helper` share the qualified name no longer fan into each other's callers or callees two hops out. `WalkNode.chunk_id` is directional: the caller's chunk on a callers hop, the resolved callee's chunk on a callees hop, absent for an unresolved callee (it used to be the edge's `from_chunk_id` on every hop). SQL lives once in the code-edges domain (SQL-text golden `sql-text/code-edges.json` `chunkId` variants). Pinned on both backends by `test/code-intel/recursive-walk-resolved-ids-5439.test.ts` (`test/e2e/code-intel-walk-resolved-ids-postgres.test.ts`).- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, `redirect: 'manual'` with any 3xx a terminal `auth_required`, browser UA, refresh-once-on-401 that is handed the client itself and never runs on a 403 (terminal, #7515), Retry-After backoff, a per-run ceiling `MAX_CONNECTOR_REQUESTS_PER_RUN` (10,000, lowered by `maxRequests`) and a `deadlineAt` checked before each request and retry wait (`ConnectorRunLimitError`), and `probeFailure`, the one error-to-`ProbeResult` table; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, list pages truncated to the requested size (a truncated page that also ignores offset is drift), Claude's `CLAUDE_MAX_ORGS` (10; more makes the listing incomplete) and `CLAUDE_MAX_REQUESTS_PER_ORG` (5,000) caps, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session` through the shared client and throws its terminal errors; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; `synced` entries older than the next list window are pruned, `failed` entries never are: #6387) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `failed-ledger.ts` (#6387): the `failed` ledger entry (`attempts`, `updatedAt`, `lastAttemptAt`, `nextRetryAt`, Claude `orgId`) kept until the conversation imports, and the pure `planConnectorFetch` — listed work plus due retained failures retried by id (`RETRY_BUDGET` 10 per run, oldest-due first, slots reserved under `--limit`, quarantine backoff from `item-holds.ts` `HOLD_BACKOFF_MS`/`HOLD_DAILY_MS`); on a `routesByOrg` provider an entry without `orgId` is `held` for `--full`. A sync with any entry left reports `partial` + `unresolved`; aborts and auth stops are never strikes; a complete `--full` listing drops entries it no longer contains (`gone`); `connectors status --json` lists `unresolved` and the doctor check warns "archive incomplete" (ask-first `--full` fix for held entries). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state; `portOverride: 0` plus `onListen` binds an OS-assigned port for tests while the authorize and token URLs keep `redirectPort`) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir; `connectors sync` usage errors, a missing `--source` value or a missing/unknown provider, are `invalid_params` exit 2 with the envelope under `--json` and a `fix` whose `<SOURCE_ID>`/`<PROVIDER>` input it names, and `connectors sync --help` prints the usage; `test/connectors-sync-cli.test.ts`), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock; rechecks `auto_sync` and returns `skipped` unless the job is `explicit`, #7515), `connectors sync --all` (only `auto_sync` providers; `--max-requests`/`--deadline` bound the invocation), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle, #6387 retained retries and the `--full` upgrade-state recovery, #6388 long-message tails) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 7f5719bf8a..849b90a1be 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`), and `cjkMatchTerms(query)` (whitespace terms with a trailing Korean particle stripped by `stripKoreanParticle`, longest particle first, stem kept only at 2+ characters; the one term list every CJK keyword builder matches, so the count, the keyword pages and the chunk search agree). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.- `src/core/credential-projection.ts` — `credentialSafeProjection(text)`: the retrieval text of a canonical body. Every private-key span from `privateKeySpans` (`secret-scan.ts`: complete keys and keys cut off at their `BEGIN` or `END` line) becomes `PRIVATE_KEY_PROJECTION_TOKEN` (`<REDACTED:private_key_pem>`) followed by as many newlines as the span held, so line offsets and chunk anchors stay stable. A cheap `PRIVATE KEY-----` substring gate returns the text unchanged otherwise; idempotent (the token holds no marker). Applied after `sanitizeRemoteBody` by the recursive chunker (`chunkers/recursive.ts`, markdown and embed paths), fenced-code extraction (`markdown-chunks.ts`), `prepareCodeChunks` (`code-chunks.ts`) and evidence delivery's `pageEvidenceText` (`window`/`section`/`page` units), so no chunk, embedding input or delivered evidence carries key material, including a mid-key chunk with neither fence. The stored body and the raw page reads are unchanged. Not covered: image OCR chunks, and key material with no `BEGIN`/`END` marker anywhere on the page. Existing pages are re-chunked by `page-state/credential-reseal.ts`. Chunker and safe-fence versions are unchanged (4).-- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the resolver backfill watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.+- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the backfill watermark of edge-owning chunks (`OWNS_EDGE`). Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.- `src/core/config.ts` (cwd `.env` boundary) — the #427 cwd-.env parser (`CWD_DOTENV_FILES`, `dotenvValuesForKey`) lives in `env-trust.ts`; config.ts re-exports both (façade rule — `test/config-env-hijack.test.ts` keeps importing from config) and `effectiveEnvDatabaseUrl` / `envShadowDetected` keep VALUE-match semantics for `DATABASE_URL` (a deliberate export equal to the cwd value would have selected the same database anyway; the value guard never touches `GBRAIN_DATABASE_URL` — the key-presence quarantine in env-trust.ts drops that one when a cwd `.env` assigns it). `loadConfig()` calls `loadGbrainEnvFile(getConfigDir)` (`~/.gbrain/.env`, operator-owned, never overrides a shell export) — `cli-preflight.ts` loads the same file earlier so the guardrails loader sees it.- `src/core/config-db-merge.ts` — the DB-plane read-side merge `loadConfigWithEngine` applies after its per-key merges (env > file > DB): provider API keys, `chat_model`/`expansion_model`, `chat_fallback_chain`/`chat_fallback_on_refusal`, flat `cycle.*`, and (#6290) `provider_chat_options.<selector>` rows, all from one batched, ~30 s memoized read. A chat-options row is one JSON object per selector (`<provider>` or `<provider>:<model>`, model ids may carry dots); the file plane wins per leaf and `__proto__`/`constructor`/`prototype` keys are dropped. A legacy dotted-leaf row is read only when `splitChatOptionsKey` (the path starts at the first dot followed by a non-digit) leaves a dot-free selector, otherwise ignored with a value-free warning. `assertProviderChatOptionsSetValue` backs `gbrain config set`, refusing a dotted leaf or non-object value with the exact JSON-form command. Pinned by `test/loadConfig-merge.test.ts` and `test/config-chat-options-db.test.ts`.diff --git a/src/core/chunkers/symbol-resolver.ts b/src/core/chunkers/symbol-resolver.tsindex b5965bde44..d3fa007e01 100644--- a/src/core/chunkers/symbol-resolver.ts+++ b/src/core/chunkers/symbol-resolver.ts@@ -75,6 +75,9 @@ export const EDGE_EXTRACTOR_VERSION_TS = '2026-05-14T01:00:00Z';export const BATCH_SIZE = 200;+/** #7119: the resolver walks, and edge readiness waits on, only chunks that own a code_edges_symbol row of their page's source. */+export const OWNS_EDGE = 'EXISTS (SELECT 1 FROM code_edges_symbol e WHERE e.from_chunk_id = cc.id AND e.source_id = p.source_id)';+export interface ResolverStats {chunks_walked: number;edges_examined: number;@@ -127,13 +130,22 @@ export async function resolveSymbolEdgesIncremental(ms: 0,};+ const [owned] = await engine.executeRaw<{ e: boolean }>(+ 'SELECT EXISTS(SELECT 1 FROM code_edges_symbol WHERE source_id = $1) AS e', [opts.sourceId]);+ if (!owned?.e) {+ stats.ms = Date.now() - start;+ return stats;+ }+let processed = 0;while (processed < maxChunks) {const remaining = maxChunks - processed;const batchSize = Math.min(BATCH_SIZE, remaining);- // Find chunks that need walking: edges_backfilled_at is NULL OR older- // than the extractor version timestamp. Scoped to source.+ // Find chunks that need walking: they own a code_edges_symbol row of the+ // source and edges_backfilled_at is NULL OR older than the extractor+ // version timestamp. A chunk that owns no edge is never selected or+ // stamped (#7119): each stamp is a non-HOT content_chunks update.const walked = await engine.transaction(async tx => {const chunks = await tx.executeRaw<{ id: number; page_id: number; slug: string }>(`SELECT cc.id, cc.page_id, p.slug@@ -144,6 +156,7 @@ export async function resolveSymbolEdgesIncremental(AND ${chunkVisibleFilter('p', 'cc')}AND (cc.edges_backfilled_at IS NULLOR cc.edges_backfilled_at < $2::timestamptz)+ AND ${OWNS_EDGE}ORDER BY cc.idLIMIT $3`,[opts.sourceId, EDGE_EXTRACTOR_VERSION_TS, batchSize],@@ -157,6 +170,7 @@ export async function resolveSymbolEdgesIncremental(WHERE cc.id=ANY($1::int[]) AND p.source_id=$2 AND p.deleted_at IS NULL AND NOT s.archivedAND ${chunkVisibleFilter('p', 'cc')}AND (cc.edges_backfilled_at IS NULL OR cc.edges_backfilled_at < $3::timestamptz)+ AND ${OWNS_EDGE}ORDER BY cc.id`, [chunks.map(chunk => chunk.id), opts.sourceId, EDGE_EXTRACTOR_VERSION_TS],);const valid = current.filter(chunk => selected.get(chunk.id)?.page_id === chunk.page_iddiff --git a/src/core/code-graph-readiness.ts b/src/core/code-graph-readiness.tsindex 774d1347ad..ff0477866c 100644--- a/src/core/code-graph-readiness.ts+++ b/src/core/code-graph-readiness.ts@@ -1,6 +1,6 @@import type { BrainEngine } from './engine.ts';import type { PageReadScope } from './types.ts';-import { EDGE_EXTRACTOR_VERSION_TS } from './chunkers/symbol-resolver.ts';+import { EDGE_EXTRACTOR_VERSION_TS, OWNS_EDGE } from './chunkers/symbol-resolver.ts';import { codeReadFilter } from './code-intel/read-scope.ts';import { pageReadFilter } from './search/read-policy-sql.ts';import { resolveExcludePrivatePages } from './search/private-visibility.ts';@@ -91,7 +91,7 @@ export async function resolveCodeReadiness(return { status: hasSymbols ? 'ready' : 'no_symbols', ready: hasSymbols, has_code: true, pending_edges: false };}const pending = await currentChunksExist(engine, scope,- '(cc.edges_backfilled_at IS NULL OR cc.edges_backfilled_at < $1::timestamptz)', [EDGE_EXTRACTOR_VERSION_TS]);+ `(cc.edges_backfilled_at IS NULL OR cc.edges_backfilled_at < $1::timestamptz) AND ${OWNS_EDGE}`, [EDGE_EXTRACTOR_VERSION_TS]);return { status: pending ? 'indexing' : 'ready', ready: !pending, has_code: true, pending_edges: pending };} catch {return { status: 'unknown', ready: false, has_code: opts.count > 0, pending_edges: false };diff --git a/test/e2e/symbol-resolver-pglite.test.ts b/test/e2e/symbol-resolver-pglite.test.tsindex a94a95a03b..7c9def7c48 100644--- a/test/e2e/symbol-resolver-pglite.test.ts+++ b/test/e2e/symbol-resolver-pglite.test.ts@@ -5,7 +5,8 @@* - Unambiguous within-file match → edge_metadata.resolved_chunk_id set* - Multi-match within file → edge_metadata.ambiguous=true + candidates* - No match → edge stays untouched- * - chunks_walked watermark advances (edges_backfilled_at = NOW())+ * - chunks_walked watermark advances (edges_backfilled_at = NOW()) on the+ * chunks that own an edge; a chunk that owns none is never walked (#7119)* - Idempotency: re-run on processed chunks is a no-op* - Resume: bumping EDGE_EXTRACTOR_VERSION_TS forces re-walk* - Source isolation: resolver scoped to one source_id; never touches edges@@ -49,7 +50,7 @@ describe('v0.34 W0c symbol-resolver — unambiguous within-file match', () => {const stats = await resolveSymbolEdgesIncremental(engine, { sourceId: 'source-a' });- expect(stats.chunks_walked).toBeGreaterThanOrEqual(2);+ expect(stats.chunks_walked).toBe(1);expect(stats.edges_resolved).toBe(1);expect(stats.edges_ambiguous).toBe(0);expect(stats.edges_unmatched).toBe(0);@@ -126,14 +127,14 @@ describe('v0.34 W0c symbol-resolver — watermark + idempotency', () => {await insertUnresolvedEdge(engine, callerChunk, 'callerInA', 'parseMarkdown', 'source-a');const stats1 = await resolveSymbolEdgesIncremental(engine, { sourceId: 'source-a' });- expect(stats1.chunks_walked).toBeGreaterThanOrEqual(2);+ expect(stats1.chunks_walked).toBe(1);const watermarkAfter = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM content_chunksWHERE edges_backfilled_at IS NOT NULL`,[],);- expect(watermarkAfter[0]!.count).toBeGreaterThanOrEqual(2);+ expect(watermarkAfter[0]!.count).toBe(1);// Second run: every chunk already has edges_backfilled_at >= EDGE_EXTRACTOR_VERSION_TS.const stats2 = await resolveSymbolEdgesIncremental(engine, { sourceId: 'source-a' });diff --git a/test/symbol-resolver-edge-owners-7119.test.ts b/test/symbol-resolver-edge-owners-7119.test.tsnew file mode 100644index 0000000000..388068e333--- /dev/null+++ b/test/symbol-resolver-edge-owners-7119.test.ts@@ -0,0 +1,80 @@+/**+ * #7119: resolve_symbol_edges walks only chunks that own a code_edges_symbol+ * row. A source with no code edges (a markdown-only brain) gets no watermark+ * stamps, because each stamp is a non-HOT content_chunks update that rewrites+ * every index entry of the row. A code source still resolves and stamps the+ * chunks that own edges, and edge readiness reaches `ready` while a code chunk+ * that owns no edge keeps a NULL watermark.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { importCodeFile, importFromContent } from '../src/core/import-file.ts';+import { resolveSymbolEdgesIncremental } from '../src/core/chunkers/symbol-resolver.ts';+import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++const pad = (name: string) => Array.from({ length: 5 }, (_, i) => ` // ${name} line ${i}: padding keeps this chunk above the small-sibling merge threshold so it keeps its own symbol.`).join('\n');+const SAMPLE = `export function alphaExample(x) {+${pad('alpha')}+ return betaExample(x) + 1;+}++export function betaExample(y) {+${pad('beta')}+ return y * 2;+}+`;++async function watermarks(sourceId: string) {+ return engine.executeRaw<{ owns_edge: boolean; stamped: boolean }>(+ `SELECT EXISTS(SELECT 1 FROM code_edges_symbol e WHERE e.from_chunk_id = cc.id) AS owns_edge, cc.edges_backfilled_at IS NOT NULL AS stamped+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.source_id = $1 ORDER BY cc.id`, [sourceId]);+}++test('#7119: a markdown-only source gets no edges_backfilled_at stamps', async () => {+ for (let i = 0; i < 3; i++) {+ await importFromContent(engine, `notes/note-${i}`, `---\ntitle: Note ${i}\ntype: note\n---\nA plain markdown note number ${i}.`, { noEmbed: true });+ }+ expect((await watermarks('default')).length).toBeGreaterThan(0);+ const stats = await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });+ expect(stats.chunks_walked).toBe(0);+ expect((await watermarks('default')).every(row => !row.stamped)).toBe(true);+});++test('#7119: a code source resolves and stamps only the chunks that own edges, and edge readiness reaches ready', async () => {+ await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });+ await importFromContent(engine, 'notes/readme', '---\ntitle: Readme\ntype: note\n---\nA markdown page beside the code.', { noEmbed: true });+ const before = await watermarks('default');+ expect(before.some(row => row.owns_edge)).toBe(true);+ expect(before.some(row => !row.owns_edge)).toBe(true);+ const stats = await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });+ expect(stats.edges_resolved).toBe(1);+ expect((await watermarks('default')).map(row => row.stamped)).toEqual(before.map(row => row.owns_edge));+ expect(await resolveCodeReadiness(engine, { sourceId: 'default', kind: 'edge', count: 0, remote: false }))+ .toMatchObject({ status: 'ready', ready: true, pending_edges: false });+ expect((await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' })).chunks_walked).toBe(0);+});++test('#7119: edge readiness ignores a code chunk that owns no edge', async () => {+ await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });+ await engine.executeRaw('UPDATE content_chunks cc SET edges_backfilled_at = NOW() WHERE EXISTS(SELECT 1 FROM code_edges_symbol e WHERE e.from_chunk_id = cc.id)');+ expect((await watermarks('default')).some(row => !row.owns_edge && !row.stamped)).toBe(true);+ expect(await resolveCodeReadiness(engine, { sourceId: 'default', kind: 'edge', count: 0, remote: false }))+ .toMatchObject({ status: 'ready', ready: true, pending_edges: false });+});diff --git a/test/symbol-resolver-projection-race.test.ts b/test/symbol-resolver-projection-race.test.tsindex 3950745e3d..ddff19d3d5 100644--- a/test/symbol-resolver-projection-race.test.ts+++ b/test/symbol-resolver-projection-race.test.ts@@ -111,7 +111,8 @@ describe('symbol resolver and projection replacement serialization', () => {};return wrapped;});- const resolver = resolveSymbolEdgesIncremental(resolverEngine, { sourceId, maxChunks: snapshot.chunks.length });+ const owners = new Set(originalEdges.map(edge => edge.from_chunk_id)).size;+ const resolver = resolveSymbolEdgesIncremental(resolverEngine, { sourceId, maxChunks: owners });void resolver.catch(() => {});let publisher: Promise<void> | undefined;try {@@ -172,7 +173,7 @@ describe('symbol resolver and projection replacement serialization', () => {expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false })).toMatchObject({ status: 'indexing', ready: false, pending_edges: true });const next = await resolveSymbolEdgesIncremental(engine, { sourceId });- expect(next.chunks_walked).toBe(snapshot.chunks.length);+ expect(next.chunks_walked).toBe(owners);expect(next.edges_resolved).toBe(1);expect(typeof (await edges(engine, sourceId))[0].edge_metadata?.resolved_chunk_id).toBe('number');expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false }))