Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(code-intel): member calls never resolve to a same-file top-level function (N13-8)

garrytan9ca54ff0e2d5
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 9e4555a5c7..44e00c4aea 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries. Sanitizes the full body before sentence embedding and boundary detection.
-- `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.
+- `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/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; ledger entries older than the next list window are pruned) → `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`). `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) — 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), 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) + `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/chunkers/edge-extractor.ts b/src/core/chunkers/edge-extractor.ts
index e85875183a..0fa796c30f 100644
--- a/src/core/chunkers/edge-extractor.ts
+++ b/src/core/chunkers/edge-extractor.ts
@@ -62,6 +62,14 @@ export interface ExtractedEdge {
* references (Python's type hints are too sparse to be useful for v0.34).
*/
edgeType: 'calls' | 'imports' | 'references';
+ /**
+ * A `calls` edge whose callee is a member access (`obj.m()`, `self.m()`,
+ * `pkg.F()`) with a receiver the extractor could not type, so `toSymbol`
+ * is the bare `m`. A member call never invokes a same-file top-level
+ * function, so the within-file resolver leaves these unresolved
+ * (gbrain-evals N13-8: `segments.join("/")` resolved to pathe's `join`).
+ */
+ memberCall?: true;
}
/**
@@ -189,6 +197,26 @@ function extractCalleeName(node: any, cfg: CallConfig): string | null {
return null;
}
+const MEMBER_CALLEE_TYPES = new Set([
+ 'member_expression',
+ 'attribute',
+ 'field_expression',
+ 'selector_expression',
+ 'navigation_expression',
+ 'member_access_expression',
+]);
+
+/** True when the call goes through a receiver: `obj.m()`, `self.m()`, Java `o.m()`, Ruby `o.m`. */
+function isMemberCall(node: any, cfg: CallConfig): boolean {
+ if (node.childForFieldName?.('object') || node.childForFieldName?.('receiver')) return true;
+ const callee = cfg.calleeFieldName
+ ? node.childForFieldName(cfg.calleeFieldName)
+ : cfg.calleeFirstNamedChild
+ ? (node.namedChild?.(0) ?? null)
+ : null;
+ return !!callee && MEMBER_CALLEE_TYPES.has(callee.type);
+}
+
function sanitizeIdent(s: string): string | null {
const m = s.match(/^[A-Za-z_][A-Za-z0-9_]*$/);
return m ? s : null;
@@ -452,6 +480,7 @@ export function extractCallEdges(tree: any, language: SupportedCodeLanguage): Ex
callSiteByteOffset: node.startIndex,
toSymbol: qualified ?? callee,
edgeType: 'calls',
+ ...(!qualified && isMemberCall(node, cfg) ? { memberCall: true as const } : {}),
});
}
}
diff --git a/src/core/chunkers/symbol-resolver.ts b/src/core/chunkers/symbol-resolver.ts
index 3a0e79d6b0..7774e2fa2f 100644
--- a/src/core/chunkers/symbol-resolver.ts
+++ b/src/core/chunkers/symbol-resolver.ts
@@ -239,7 +239,9 @@ async function processChunkBatch(
for (const e of edges) {
stats.edges_examined += 1;
const pageId = pageByChunkId.get(e.from_chunk_id);
- if (pageId === undefined) {
+ // A member call with an untyped receiver (`segments.join()`) never
+ // invokes a same-file top-level function (gbrain-evals N13-8).
+ if (pageId === undefined || e.edge_metadata?.member_call === true) {
stats.edges_unmatched += 1;
continue;
}
diff --git a/src/core/code-chunks.ts b/src/core/code-chunks.ts
index 5528088f81..8629de2bbc 100644
--- a/src/core/code-chunks.ts
+++ b/src/core/code-chunks.ts
@@ -37,7 +37,8 @@ export async function installCodeChunkEdges(engine: BrainEngine, slug: string, s
const from = index === null ? undefined : ranges[index];
if (!from?.symbol_name_qualified) continue;
edges.push({ from_chunk_id: from.id, to_chunk_id: null, from_symbol_qualified: from.symbol_name_qualified,
- to_symbol_qualified: edge.toSymbol, edge_type: edge.edgeType, source_id: sourceId });
+ to_symbol_qualified: edge.toSymbol, edge_type: edge.edgeType, source_id: sourceId,
+ ...(edge.memberCall ? { edge_metadata: { member_call: true } } : {}) });
}
if (edges.length) await engine.addCodeEdges(edges);
}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 1e990f18d0..f938962e37 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1603,7 +1603,7 @@ export async function importCodeFile(
to_chunk_id: null,
from_symbol_qualified: from.symbol_name_qualified,
to_symbol_qualified: e.toSymbol,
- edge_type: e.edgeType,
+ edge_type: e.edgeType, ...(e.memberCall ? { edge_metadata: { member_call: true } } : {}),
// Stamp the source: getCallersOf/getCalleesOf add
// `AND source_id = <scoped>` whenever a worktree pin / --source is
// in play, and a NULL here never matches that filter — so every
diff --git a/test/code-intel/n13-edge-resolution.test.ts b/test/code-intel/n13-edge-resolution.test.ts
index 71adcd2680..81be7e4c14 100644
--- a/test/code-intel/n13-edge-resolution.test.ts
+++ b/test/code-intel/n13-edge-resolution.test.ts
@@ -78,6 +78,23 @@ for (const kind of testBackends()) {
expect(edge?.resolved).toBe(false);
});
+ test('N13-8: a member call never resolves to a same-file top-level function of that name', async () => {
+ await importCodeFile(engine, 'src/pathish.ts',
+ 'export function join(...parts: string[]): string {\n return parts.join("/");\n}\n\n'
+ + 'export function dirname(p: string): string {\n const segments = p.split("/");\n return segments.slice(0, -1).join("/");\n}\n\n'
+ + 'export function cwd(): string {\n return process.cwd();\n}\n\n'
+ + 'export function resolve(p: string): string {\n return join(cwd(), p);\n}\n',
+ { noEmbed: true });
+ await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+ const resolvedCallers = async (symbol: string) =>
+ (await engine.getCallersOf(symbol, { sourceId: 'default' })).filter((e) => e.resolved).map((e) => e.from_symbol_qualified).sort();
+ expect(await resolvedCallers('join')).toEqual(['resolve']);
+ expect(await resolvedCallers('cwd')).toEqual(['resolve']);
+ const memberEdge = (await engine.getCallersOf('join', { sourceId: 'default' })).find((e) => e.from_symbol_qualified === 'dirname');
+ expect(memberEdge?.edge_metadata.member_call).toBe(true);
+ expect(memberEdge?.resolved).toBe(false);
+ });
+
test('N13-3: a Python function sharing a Go function name walks; Go callers stay out', async () => {
await importCodeFile(engine, 'gate/shared.go',
'package main\n\nfunc shared_helper() int {\n\treturn 2\n}\n\nfunc go_user() int {\n\treturn shared_helper()\n}\n',
diff --git a/test/edge-extractor.test.ts b/test/edge-extractor.test.ts
index 795534f1e1..06125394b4 100644
--- a/test/edge-extractor.test.ts
+++ b/test/edge-extractor.test.ts
@@ -36,6 +36,18 @@ class Foo {
expect(syms.some((s) => s === 'go' || s === 'Foo::go')).toBe(true);
});
+ test('N13-8: an untyped member call is flagged memberCall; bare and typed calls are not', async () => {
+ const src = `
+import { util } from './util';
+function join(a: string) { return a; }
+function f(xs: string[]) { join('a'); util.go(); return xs.join('/'); }
+`.trim();
+ const result = await chunkCodeTextFull(src, 'src/foo.ts');
+ const flagged = (sym: string) => result.edges.filter(e => e.toSymbol === sym).map(e => e.memberCall === true);
+ expect(flagged('join').sort()).toEqual([false, true]);
+ expect(flagged('./util::go')).toEqual([false]);
+ });
+
test('all edges typed as calls', async () => {
const src = 'function f() { return g(); }';
const result = await chunkCodeTextFull(src, 'src/foo.ts');