Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

code-intel: recursive walk follows the resolver's chunk identity (#5439)

garrytandb3c37c75f70
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index d9eeb0d443..1a0a0b4873 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -44,5 +44,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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, browser UA, refresh-once-on-401, Retry-After backoff; `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, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; 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), 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/src/core/code-intel/recursive-walk.ts b/src/core/code-intel/recursive-walk.ts
index 8509b1e49c..d1e7867c1b 100644
--- a/src/core/code-intel/recursive-walk.ts
+++ b/src/core/code-intel/recursive-walk.ts
@@ -16,6 +16,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import type { CodeEdgeResult } from '../types.ts';
+import { readEdgeResolution } from '../chunkers/symbol-resolver.ts';
import { classifySink, type SinkKind } from './sinks/index.ts';
import { codeReadFilter } from './read-scope.ts';
@@ -36,7 +37,11 @@ export interface WalkOpts {
export interface WalkNode {
symbol: string;
- /** Origin chunk for the edge, when known. */
+ /**
+ * The node's own chunk, when known: the caller's chunk on a callers hop,
+ * the resolved callee's chunk on a callees hop (#5439). Absent when the
+ * edge was unresolved (the walk continued by name).
+ */
chunk_id?: number;
/** Sink kind for terminal nodes in code_flow. */
sink_kind?: SinkKind;
@@ -159,6 +164,22 @@ async function supportedChunkIds(engine: BrainEngine, ids: number[]): Promise<Se
return new Set(rows.map((r) => Number(r.id)));
}
+/**
+ * A frontier entry (#5439): a chunk identity when the hop that reached it
+ * was resolved (the next hop is read by that chunk, so a namesake in another
+ * file never fans in), else the qualified name. The start is always a name.
+ */
+interface WalkFrontierNode { symbol: string; chunkId?: number }
+const frontierKey = (n: WalkFrontierNode): string => (n.chunkId === undefined ? `name:${n.symbol}` : `chunk:${n.chunkId}`);
+
+/** The node an edge leads to, in the walk's direction. */
+function nextNode(e: CodeEdgeResult, direction: WalkDirection): WalkFrontierNode {
+ if (direction === 'callers') return { symbol: e.from_symbol_qualified, chunkId: e.from_chunk_id };
+ const resolution = readEdgeResolution(e.edge_metadata);
+ const chunkId = e.to_chunk_id ?? (resolution.kind === 'resolved' ? resolution.chunk_id : undefined);
+ return chunkId === undefined ? { symbol: e.to_symbol_qualified } : { symbol: e.to_symbol_qualified, chunkId };
+}
+
/**
* BFS recursive walk. Returns the depth-grouped result envelope.
*/
@@ -196,8 +217,9 @@ export async function runRecursiveWalk(
}
const mixedLanguages = langs.some((l) => !isSupportedLang(l));
- // Step 3: BFS walk.
- const visited = new Set<string>([qualifiedStart]);
+ // Step 3: BFS walk, keyed by source-scoped chunk identity where the edge
+ // was resolved and by name otherwise (#5439).
+ const visited = new Set<string>([`name:${qualifiedStart}`]);
const depthGroups: DepthGroup[] = [];
let cyclesDetected = false;
let truncation: 'none' | 'max_nodes' | 'depth_cap' | 'both' = 'none';
@@ -205,18 +227,20 @@ export async function runRecursiveWalk(
let freshness: 'fresh' | 'partial' = 'fresh';
const terminalNodes: { symbol: string; sink_kind: SinkKind }[] = [];
- let frontier = [qualifiedStart];
+ let frontier: WalkFrontierNode[] = [{ symbol: qualifiedStart }];
for (let d = 1; d <= depthCap; d++) {
- const nextFrontier: string[] = [];
+ const nextFrontier: WalkFrontierNode[] = [];
const nodesThisDepth: WalkNode[] = [];
- for (const sym of frontier) {
+ for (const cur of frontier) {
+ const sym = cur.symbol;
let edges: CodeEdgeResult[];
try {
+ const hopOpts = { sourceId: opts.sourceId, limit: maxNodes, ...(cur.chunkId === undefined ? {} : { chunkId: cur.chunkId }) };
edges =
opts.direction === 'callers'
- ? await engine.getCallersOf(sym, { sourceId: opts.sourceId, limit: maxNodes })
- : await engine.getCalleesOf(sym, { sourceId: opts.sourceId, limit: maxNodes });
+ ? await engine.getCallersOf(sym, hopOpts)
+ : await engine.getCalleesOf(sym, hopOpts);
} catch {
edges = [];
}
@@ -233,10 +257,11 @@ export async function runRecursiveWalk(
// → partial. v0.34 W3b's getCachedOrCompute will gate this further.
for (const e of edges) {
- const next =
- opts.direction === 'callers' ? e.from_symbol_qualified : e.to_symbol_qualified;
+ const nextEntry = nextNode(e, opts.direction);
+ const next = nextEntry.symbol;
if (!next || next === sym) continue;
- if (visited.has(next)) {
+ // A hop back onto the start symbol is a cycle whichever key reached it.
+ if (visited.has(frontierKey(nextEntry)) || next === qualifiedStart) {
cyclesDetected = true;
continue;
}
@@ -244,9 +269,9 @@ export async function runRecursiveWalk(
truncation = truncation === 'depth_cap' ? 'both' : 'max_nodes';
break;
}
- visited.add(next);
+ visited.add(frontierKey(nextEntry));
totalNodes += 1;
- const node: WalkNode = { symbol: next, chunk_id: e.from_chunk_id };
+ const node: WalkNode = nextEntry.chunkId === undefined ? { symbol: next } : { symbol: next, chunk_id: nextEntry.chunkId };
// Tag sinks for callees direction.
if (opts.direction === 'callees' && lang) {
const kind = classifySink(next, lang);
@@ -256,7 +281,7 @@ export async function runRecursiveWalk(
}
}
nodesThisDepth.push(node);
- nextFrontier.push(next);
+ nextFrontier.push(nextEntry);
}
if (truncation === 'max_nodes' || truncation === 'both') break;
}
diff --git a/src/core/engine-sql/code-edges.ts b/src/core/engine-sql/code-edges.ts
index 95cb6f9f5c..78c5cafa14 100644
--- a/src/core/engine-sql/code-edges.ts
+++ b/src/core/engine-sql/code-edges.ts
@@ -65,26 +65,34 @@ export async function deleteCodeEdgesForChunks(exec: SqlExecutor, chunkIds: numb
(await exec.run(sqlFragment`DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY(${chunkIds}::int[])`)).rows;
}
+/**
+ * #5439: `opts.chunkId` keys the read on chunk identity instead of the name.
+ * Callers of a chunk: code_edges_chunk rows pointing at it plus
+ * code_edges_symbol rows the resolver stamped with that resolved_chunk_id.
+ * The source filter still applies, so a chunk id is only ever read inside
+ * the caller's source.
+ */
export async function getCallersOf(
exec: LegacyUnscopedRead,
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number },
): Promise<CodeEdgeResult[]> {
const limit = Math.min(opts?.limit ?? 100, 500);
const scopedSource: string | null =
!opts?.allSources && opts?.sourceId ? opts.sourceId : null;
+ const byChunk = typeof opts?.chunkId === 'number';
const rows = (await exec.run(sqlFragment`
SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
- WHERE to_symbol_qualified = ${qualifiedName}
+ WHERE ${byChunk ? sqlFragment`to_chunk_id = ${opts!.chunkId as number}::int` : sqlFragment`to_symbol_qualified = ${qualifiedName}`}
AND ${trustedSql(currentCodeEdgeFilter('code_edges_chunk', true))}
${scopedSource ? sqlFragment`AND source_id = ${scopedSource}` : sqlFragment``}
UNION ALL
SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
- WHERE to_symbol_qualified = ${qualifiedName}
+ WHERE ${byChunk ? sqlFragment`(edge_metadata->>'resolved_chunk_id')::int = ${opts!.chunkId as number}::int` : sqlFragment`to_symbol_qualified = ${qualifiedName}`}
AND ${trustedSql(currentCodeEdgeFilter('code_edges_symbol', false))}
${scopedSource ? sqlFragment`AND source_id = ${scopedSource}` : sqlFragment``}
LIMIT ${limit}
@@ -92,10 +100,11 @@ export async function getCallersOf(
return rows.map(r => rowToCodeEdge(r as Record<string, unknown>));
}
+/** #5439: `opts.chunkId` reads the edges leaving that chunk (both tables) instead of the name's. */
export async function getCalleesOf(
exec: LegacyUnscopedRead,
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number },
): Promise<CodeEdgeResult[]> {
const limit = Math.min(opts?.limit ?? 100, 500);
const scopedSource: string | null =
@@ -116,6 +125,9 @@ export async function getCalleesOf(
${scopedSource ? sqlFragment`AND source_id = ${scopedSource}` : sqlFragment``}
LIMIT ${limit}
`)).rows;
+ if (typeof opts?.chunkId === 'number') {
+ return (await run(sqlFragment`from_chunk_id = ${opts.chunkId}::int`)).map(r => rowToCodeEdge(r as Record<string, unknown>));
+ }
let rows = await run(sqlFragment`from_symbol_qualified = ${qualifiedName}`);
// #4670: opt-in bare-name fallback (both engines).
// Opt-in; zero-row exact miss + delimiter-free input re-keys on the bare
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 8be71c7672..d7afd04933 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2663,7 +2663,7 @@ export interface BrainEngine {
*/
getCallersOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number },
): Promise<CodeEdgeResult[]>;
/**
@@ -2673,7 +2673,7 @@ export interface BrainEngine {
*/
getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number },
): Promise<CodeEdgeResult[]>;
/**
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 682b857fa9..b01e79d74a 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2897,14 +2897,14 @@ export class PGLiteEngine implements BrainEngine {
async getCallersOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCallersOf(unscopedExecutor(this.engineSql, 'code-edges: unscoped on master (EO4 inventory)'), qualifiedName, opts);
}
async getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCalleesOf(unscopedExecutor(this.engineSql, 'code-edges: unscoped on master (EO4 inventory)'), qualifiedName, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 33f756b4b8..3cc9556ce7 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2910,14 +2910,14 @@ export class PostgresEngine implements BrainEngine {
async getCallersOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCallersOf(unscopedExecutor(this.engineSql, 'code-edges: unscoped on master (EO4 inventory)'), qualifiedName, opts);
}
async getCalleesOf(
qualifiedName: string,
- opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean },
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
return codeEdgesImpl.getCalleesOf(unscopedExecutor(this.engineSql, 'code-edges: unscoped on master (EO4 inventory)'), qualifiedName, opts);
}
diff --git a/test/code-intel/recursive-walk-resolved-ids-5439.test.ts b/test/code-intel/recursive-walk-resolved-ids-5439.test.ts
new file mode 100644
index 0000000000..6f1a839a74
--- /dev/null
+++ b/test/code-intel/recursive-walk-resolved-ids-5439.test.ts
@@ -0,0 +1,127 @@
+/**
+ * #5439 item 3 (wave 15 P7.8): the recursive walk (code_blast / code_flow)
+ * follows the symbol resolver's outcome instead of re-matching bare names.
+ *
+ * Two files each define a top-level `helper` (qualified name `helper` in
+ * both — chunkers/qualified-names.ts gives a top-level function its bare
+ * name). The resolver stamps each in-file call with resolved_chunk_id.
+ * Before: the walk stepped by `to_symbol_qualified`, so a_caller → helper
+ * fanned into BOTH helpers' callees at hop 2, and every node was labelled
+ * with the edge's from_chunk_id even on a callee hop.
+ * After: a resolved edge steps to that chunk (source-scoped chunk identity
+ * keys the frontier/visited set), the next hop reads edges by that chunk,
+ * and node chunk ids are directional (callee hop: the callee's chunk;
+ * caller hop: the caller's chunk). Names remain the key for unresolved edges.
+ *
+ * Synthetic data only.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importCodeFile } from '../../src/core/import-file.ts';
+import { resolveSymbolEdgesIncremental } from '../../src/core/chunkers/symbol-resolver.ts';
+import { runRecursiveWalk } from '../../src/core/code-intel/recursive-walk.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const A = 'export function a_leaf(): number {\n return 1;\n}\n\n'
+ + 'export function helper(): number {\n return a_leaf() + 1;\n}\n\n'
+ + 'export function a_caller(): number {\n return helper() + 1;\n}\n';
+const B = 'export function b_leaf(): number {\n return 2;\n}\n\n'
+ + 'export function helper(): number {\n return b_leaf() + 2;\n}\n\n'
+ + 'export function b_caller(): number {\n return helper() + 2;\n}\n';
+
+for (const kind of testBackends()) {
+ describe(`recursive walk follows resolved chunk identity (${kind}, #5439)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => {
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'twins-%'`);
+ await importCodeFile(engine, 'twins/a.ts', A, { noEmbed: true });
+ await importCodeFile(engine, 'twins/b.ts', B, { noEmbed: true });
+ const stats = await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+ expect(stats.edges_resolved).toBeGreaterThanOrEqual(4);
+ });
+
+ // importCodeFile slugifies the path: twins/a.ts is stored as twins-a-ts.
+ const chunkIdOf = async (slug: string, symbol: string): Promise<number> => {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `SELECT c.id FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = $1 AND c.symbol_name = $2`,
+ [slug, symbol],
+ );
+ expect(rows).toHaveLength(1);
+ return Number(rows[0]!.id);
+ };
+ const groups = (r: Awaited<ReturnType<typeof runRecursiveWalk>>) => {
+ expect(r.result).toBe('ok');
+ if (r.result !== 'ok') throw new Error('unreachable');
+ return r.depth_groups;
+ };
+
+ test('code_flow from a_caller: hop 1 is the same-file helper chunk, hop 2 only its callee', async () => {
+ const aHelper = await chunkIdOf('twins-a-ts', 'helper');
+ const aLeaf = await chunkIdOf('twins-a-ts', 'a_leaf');
+ const g = groups(await runRecursiveWalk(engine, 'a_caller', { direction: 'callees', sourceId: 'default', depth: 3 }));
+ expect(g.map((x) => x.depth)).toEqual([1, 2]);
+ // The `number` return type is a `references` edge the walk has always
+ // followed; it is unresolved, so it stays a name node without a chunk id.
+ expect(g[0]!.nodes.map((n) => n.symbol).sort()).toEqual(['helper', 'number']);
+ expect(g[0]!.nodes.find((n) => n.symbol === 'helper')).toEqual({ symbol: 'helper', chunk_id: aHelper });
+ expect(g[0]!.nodes.find((n) => n.symbol === 'number')).toEqual({ symbol: 'number' });
+ expect(g[1]!.nodes).toEqual([{ symbol: 'a_leaf', chunk_id: aLeaf }]);
+ });
+
+ test('code_flow from b_caller mirrors it: never a_leaf', async () => {
+ const bHelper = await chunkIdOf('twins-b-ts', 'helper');
+ const g = groups(await runRecursiveWalk(engine, 'b_caller', { direction: 'callees', sourceId: 'default', depth: 3 }));
+ expect(g[0]!.nodes.find((n) => n.symbol === 'helper')).toEqual({ symbol: 'helper', chunk_id: bHelper });
+ expect(g[1]!.nodes.map((n) => n.symbol)).toEqual(['b_leaf']);
+ });
+
+ test('code_blast from a_leaf: hop 1 is the same-file helper chunk, hop 2 only a_caller', async () => {
+ const aHelper = await chunkIdOf('twins-a-ts', 'helper');
+ const aCaller = await chunkIdOf('twins-a-ts', 'a_caller');
+ const g = groups(await runRecursiveWalk(engine, 'a_leaf', { direction: 'callers', sourceId: 'default', depth: 3 }));
+ expect(g.map((x) => x.depth)).toEqual([1, 2]);
+ expect(g[0]!.nodes).toEqual([{ symbol: 'helper', chunk_id: aHelper }]);
+ expect(g[1]!.nodes).toEqual([{ symbol: 'a_caller', chunk_id: aCaller }]);
+ });
+
+ test('code_blast from b_leaf mirrors it: never a_caller', async () => {
+ const g = groups(await runRecursiveWalk(engine, 'b_leaf', { direction: 'callers', sourceId: 'default', depth: 3 }));
+ expect(g[1]!.nodes.map((n) => n.symbol)).toEqual(['b_caller']);
+ });
+
+ test('starting at the shared name itself still reaches both files (the start is a name, not a chunk)', async () => {
+ const g = groups(await runRecursiveWalk(engine, 'helper', { direction: 'callers', sourceId: 'default', depth: 1 }));
+ expect(g[0]!.nodes.map((n) => n.symbol).sort()).toEqual(['a_caller', 'b_caller']);
+ });
+
+ test('an unresolved callee stays a name hop and carries no chunk id', async () => {
+ await importCodeFile(engine, 'twins/c.ts',
+ 'export function c_caller(): number {\n return missingThing() + 1;\n}\n', { noEmbed: true });
+ await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+ const g = groups(await runRecursiveWalk(engine, 'c_caller', { direction: 'callees', sourceId: 'default' }));
+ expect(g[0]!.nodes.find((n) => n.symbol === 'missingThing')).toEqual({ symbol: 'missingThing' });
+ });
+
+ test('the chunk-identity reads are source-scoped: another source sees no edges for the same chunk id', async () => {
+ const aHelper = await chunkIdOf('twins-a-ts', 'helper');
+ expect((await engine.getCallersOf('helper', { sourceId: 'default', chunkId: aHelper })).map((e) => e.from_symbol_qualified)).toEqual(['a_caller']);
+ expect((await engine.getCalleesOf('helper', { sourceId: 'default', chunkId: aHelper })).map((e) => e.to_symbol_qualified).sort()).toEqual(['a_leaf', 'number']);
+ expect(await engine.getCallersOf('helper', { sourceId: 'elsewhere', chunkId: aHelper })).toHaveLength(0);
+ expect(await engine.getCalleesOf('helper', { sourceId: 'elsewhere', chunkId: aHelper })).toHaveLength(0);
+ });
+ });
+}
diff --git a/test/e2e/code-intel-walk-resolved-ids-postgres.test.ts b/test/e2e/code-intel-walk-resolved-ids-postgres.test.ts
new file mode 100644
index 0000000000..82bd3230c1
--- /dev/null
+++ b/test/e2e/code-intel-walk-resolved-ids-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../code-intel/recursive-walk-resolved-ids-5439.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index fa77bba4b3..eeb4f140cc 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -97,8 +97,8 @@
"getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",
"getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>",
"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>",
- "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>",
- "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
"getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>",
"getChunks: (slug: string, opts?: PageReadScope & { includeEmbedding?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
"getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
@@ -1063,8 +1063,8 @@
"getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",
"getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>",
"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>",
- "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>",
- "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
"getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>",
"getChunks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
"getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
@@ -3303,8 +3303,8 @@
"getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",
"getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>",
"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>",
- "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>",
- "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
"getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>",
"getChunks: (slug: string, opts?: PageReadScope & { includeEmbedding?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
"getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
@@ -6322,8 +6322,8 @@
"getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",
"getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>",
"getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>",
- "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>",
- "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
+ "getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; chunkId?: number; }) => Promise<CodeEdgeResult[]>",
"getChunkWindows: (requests: ChunkWindowRequest[], opts: ChunkWindowOpts) => Promise<ChunkWindowPage[]>",
"getChunks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
"getChunksWithEmbeddings: (slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean; }) => Promise<Chunk[]>",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 7cc56b8727..a64b137201 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -1176,6 +1176,17 @@
"via": "unsafe"
}
],
+ "chunkId": [
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
"default": [
{
"paramCount": 3,
@@ -1200,6 +1211,17 @@
]
},
"getCallersOf": {
+ "chunkId": [
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
"default": [
{
"paramCount": 3,
diff --git a/test/fixtures/goldens/sql-text/code-edges.json b/test/fixtures/goldens/sql-text/code-edges.json
index 5844db37e6..1956908a63 100644
--- a/test/fixtures/goldens/sql-text/code-edges.json
+++ b/test/fixtures/goldens/sql-text/code-edges.json
@@ -77,6 +77,20 @@
"textSha256": "8e168723e3839daeec0e83980381f4418b39245a7dac73c11fbe04375bd79d95"
}
],
+ "chunkId": [
+ {
+ "lane": "pool",
+ "params": [
+ "number",
+ "string",
+ "number",
+ "string",
+ "number"
+ ],
+ "sql": "SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id, true as resolved FROM code_edges_chunk WHERE from_chunk_id = $1::int AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_chunk.from_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_chunk.to_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND source_id = $2 UNION ALL SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id, false as resolved FROM code_edges_symbol WHERE from_chunk_id = $3::int AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_symbol.from_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND source_id = $4 LIMIT $5",
+ "textSha256": "c9bfbe76c75e1f0e2879e7ae6396dbbfafa1cb409a633a2f6679497b5f8e5a92"
+ }
+ ],
"default": [
{
"lane": "pool",
@@ -105,6 +119,20 @@
]
},
"getCallersOf": {
+ "chunkId": [
+ {
+ "lane": "pool",
+ "params": [
+ "number",
+ "string",
+ "number",
+ "string",
+ "number"
+ ],
+ "sql": "SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id, true as resolved FROM code_edges_chunk WHERE to_chunk_id = $1::int AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_chunk.from_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_chunk.to_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND source_id = $2 UNION ALL SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id, false as resolved FROM code_edges_symbol WHERE (edge_metadata->>'resolved_chunk_id')::int = $3::int AND EXISTS ( SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id=code_edges_symbol.from_chunk_id AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND TRUE AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ) AND source_id = $4 LIMIT $5",
+ "textSha256": "ac70ef2296e47ecbbbde75fd59f4e0fbea9f77aee36ba46709d1db6a8b4780ba"
+ }
+ ],
"default": [
{
"lane": "pool",
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index e399342b03..ec818438a4 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -734,11 +734,13 @@ export const SQL_CASES: SqlCase[] = [
...variants('getCallersOf', [
['default', (e) => e.getCallersOf('B.g')],
['sourceId', (e) => e.getCallersOf('B.g', { sourceId: SRC })],
+ ['chunkId', (e) => e.getCallersOf('B.g', { sourceId: SRC, chunkId: 2 })],
]),
...variants('getCalleesOf', [
['default', (e) => e.getCalleesOf('A.f')],
['sourceId', (e) => e.getCalleesOf('A.f', { sourceId: SRC })],
['bareFallback', (e) => e.getCalleesOf('f', { bareFallback: true })],
+ ['chunkId', (e) => e.getCalleesOf('A.f', { sourceId: SRC, chunkId: 1 })],
]),
...variants('getEdgesByChunk', [
['default', (e) => e.getEdgesByChunk(1)],