Skip to content

Import Resolution

After every file is parsed, CodeKnife links the files together: each import becomes an edge between two modules, and each call becomes an edge between two functions. The Dead Code, Blast Radius and Architecture blades are only as good as these edges. Read this page when one of those blades reports something that looks wrong, such as a used file marked dead or a caller missing from a blast cone.

A TypeScript package with this tsconfig.json:

{
// JSONC is accepted
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@lib/*": ["src/lib/*"],
"#shared": ["shared/consts.ts"],
},
},
}

and this src/index.ts:

import { add } from "./lib/math";
import { tag } from "@lib/strings";
import { LIMIT } from "#shared";
import { helper } from "src/components/helper";
import React from "react";
export { Button } from "./components/Button";
require("./side-effect");
const legacy = require("./legacy");
export async function main(): Promise<number> {
const mod = await import("./lazy");
return add(LIMIT, 2) + tag("x").length + helper();
}

The Garden Map embeds the resolved module edges. Generate it and list the edges:

Terminal window
codeknife map --no-cache --out map.html --format human
python3 -c 'import json,re; h=open("map.html").read(); d=json.loads(re.search(r"const DATA = (\{.*?\});\n", h, re.S).group(1).replace("<\\/","</")); [print(e["from"], "->", e["to"], e["count"]) for e in d["edges"]]'
note: no coverage file found (running complexity-only mode); generate one with: npx vitest run --coverage
note: no git repository found; skipping churn forensics
note: generated Garden Map at .../ts/map.html (9 module(s), 6 edge(s), 0 red arrow(s))
codeknife map: PASS (9 files, 0 errors, 0 warnings, 0 info, 14ms)
src/index -> shared/consts 1
src/index -> src/components/Button 1
src/index -> src/components/helper 1
src/index -> src/lib/math/index 1
src/index -> src/lib/strings 1
src/index -> src/side-effect 1

Six of the eight imports resolve: the relative import to an index file, both paths aliases, the baseUrl import, the re-export and the bare require statement. react is external. const legacy = require("./legacy") and the dynamic import("./lazy") are not seen at all, so Dead Code reports the required file as an orphan:

Terminal window
codeknife dead --no-cache --format human
warning[CK_DEAD_FILE]: orphan file `src/legacy.js` has no inbound imports or reachable symbols
--> src/legacy.js:1-4 (src/legacy.js)
= fix: Delete this unreferenced file or wire its module into an entrypoint.
codeknife dead: FAIL (9 files, 0 errors, 1 warnings, 0 info, 5ms)

The exit code is 1 because of the warning.

Linking runs once per command, after parsing, in this order:

  1. Owners and fields. Each method and field is attached to its owner type: first a type with that name in the same module, otherwise the first type with that name anywhere in the repository.
  2. Imports. Every recorded import is passed to its language’s resolver. If the resolver returns a module, CodeKnife records an import edge from the importing module to that module. If not, the import is dropped. Imports flagged as external are still tried; the flag only decides whether the path is also listed as a third-party import for Dependencies.
  3. Wrappers. One-statement functions that forward to another function or return a receiver field are linked to their target, so the call graph can see through them.
  4. References. Every call and field read is resolved to an item if possible (rules below). Unresolved references are kept with their target name but no target.
  5. Tests. Test units are attached to their items.

Module names come from file paths. Language Support lists the rules per language; the examples below use them.

Resolution happens in two steps.

At parse time, each non-relative import specifier is checked against the package’s tsconfig.json:

  • The tsconfig.json is the one in the package directory (the directory of the nearest package.json), or the one at the repository root if the package has none. Only that one file is read. extends is not followed.
  • The file may contain // and /* */ comments and trailing commas.
  • compilerOptions.baseUrl is resolved relative to the tsconfig.json directory.
  • Each compilerOptions.paths entry is a pattern with at most one *, or an exact string. Targets are resolved relative to baseUrl if set, else to the tsconfig.json directory.
  • Patterns are tried in sorted key order, not in file order. The first pattern that matches wins. Its targets are tried in order and the first that exists on disk is used; if none exists, the first target is used anyway.
  • If no pattern matches and baseUrl is set, baseUrl/<specifier> is used when that path exists on disk.
  • “Exists on disk” means the exact file, or the path with any of .mts, .cts, .tsx, .ts, .jsx, .js, .mjs, .cjs added, or an index file with one of those extensions inside it.

A mapped import is stored as the mapped repository path and is never external. Files that belong to no package get no alias mapping.

At link time, the stored path is turned into candidate module names:

Import Candidates
starts with . the path joined to the importing file’s directory, with . and .. segments applied
starts with @/ or ~/ (and was not mapped by paths) if the importing file’s path contains /src/: <prefix>/src/<rest> and <prefix>/<rest>, where <prefix> is the part before /src/; then src/<rest> and <rest>
anything else the specifier as a repository-relative path

Each candidate has a known extension removed and is looked up as a module name, first as is and then with /index appended. The first hit wins.

Consequences:

  • A bare specifier that happens to equal a repository path resolves without any configuration. import { n } from "src/util/num" linked to src/util/num.ts in a repository with no tsconfig.json.
  • @/ and ~/ work without a tsconfig.json whenever one of the candidates above names a module. In a demo, import { clamp } from "@/util/num" in src/shapes.ts linked to src/util/num.ts.
  • npm package imports such as react resolve to nothing unless a module with that exact path exists in the repository.
  • A specifier in paths such as @lib/special loses to a wildcard such as @lib/* because @lib/* sorts first. In a demo where the two pointed to different files, the import resolved to the wildcard target.

What is recorded as an import in the first place: import ... from, export ... from, and require("x") when it is part of a top-level expression statement. const x = require("x"), dynamic import() and imports inside functions are not.

The import string is resolved against module names, which are dotted repository paths (app/core/engine.py is app.core.engine, app/core/__init__.py is app.core).

Relative imports. Count the leading dots. Remove that many trailing segments from the importing module’s name, or one fewer when the importing file is an __init__.py (because an __init__.py module already names its package). Then append the rest. From app/core/engine.py, from ..models import Account becomes app.models.

Absolute imports. The import string is used as is.

Longest prefix. If the candidate is not a module, trailing segments are removed one at a time until a module matches. from .core.engine import run resolves to app.core.engine; a candidate of app.core.engine.run would also resolve to app.core.engine.

Sibling fallback. If an absolute import still does not match, CodeKnife tries <importing module's parent>.<import>, and then that string with its last segment removed. This lets import b in scripts/a.py resolve to scripts.b.

What is recorded:

  • import a.b, c records a.b and c.
  • from m import x, y records only m. The imported names are ignored, so from app.core import util links to app.core, not to app.core.util.
  • from . import x, y and from .. import x record one import per name (.x, .y, ..x), so these do link to the submodules.

Limits:

  • Module names always start at the repository root. With a src/ layout (src/pkg/util.py, module src.pkg.util), from pkg.util import util_fn in src/pkg/main.py resolves to nothing. In a demo the whole src/pkg package produced no import edges.
  • Imports inside functions or if TYPE_CHECKING: blocks are not recorded, because only module-level and class-level statements are examined.
  • importlib.import_module(...) and __import__(...) are not imports.

The import path must exactly equal a module name. Go module names are the go.mod module path plus the directory, so import "example.com/shop/store" resolves to the module of every file in store/ when go.mod says module example.com/shop.

Standard-library imports (fmt, net/http) and third-party imports (github.com/google/uuid) never match and are dropped. There is no handling of replace directives, vendored code or go.work workspaces; a repository with several go.mod files resolves imports only when the full path matches another module’s name exactly.

What is an import. Each mod name; declaration and each path from a use statement (after expanding {...} groups and dropping aliases and ::*). Paths starting with std, core or alloc are dropped before resolution.

Candidate path, given the importing module’s name such as core-lib::net:

Import Candidate
crate::a::b <package>::a::b
super::a <parent module>::a (only one super is handled)
self::a <this module>::a
mod a; <this module>::a
anything else, such as serde::Serialize <this module>::serde::Serialize

The candidate is then shortened one :: segment at a time until it names a module. So use crate::util::clamp resolves to the module shapes::util.

A use path whose first segment is a module declared with mod in the same scope is rewritten to start with crate::. That is right in lib.rs or main.rs, but not in a submodule. In src/net.rs with mod wire; use wire::encode;, the use becomes crate::wire::encode, which does not exist, and shortens to the crate root. The edge from mod wire; itself is correct.

Because every candidate starts with the importing module’s own name, an import that matches nothing (for example serde::Serialize) shortens back to the importing module itself and is recorded as an edge from the module to itself. The map and the cycle check ignore such self-edges, but the orphan-file check in Dead Code does not.

Each call reference has a target name and, when the call was written as a.b() or a::b(), a qualifier (a). Resolution uses only names and the import graph. There is no type inference.

  1. Candidates. All items in the repository with exactly the target name, written in the same language as the caller. Of those, keep the callable kinds: functions, methods, constants and tests.
  2. In scope. A candidate is in scope when it is in the caller’s module, in a module the caller’s file imports, or in a file in the same directory as the caller’s file.
  3. Qualifier match. If the call has a qualifier, take the first in-scope candidate whose owner type equals the qualifier or whose qualified name contains the qualifier as a substring. Failing that, take the first candidate anywhere whose module’s short name equals the qualifier or whose module name ends with :: plus the qualifier.
  4. Unique name. If there is exactly one callable with this name in the language, use it if it is in scope. Otherwise the call is unresolved.
  5. Several candidates. Prefer one in the caller’s module, then one in an imported module. Otherwise the call is unresolved.

Field reads use a smaller version: candidates must be fields in the caller’s module or an imported module; if there are several, a field whose owner name equals the qualifier wins, then one in the caller’s module.

implements references (Rust impl Trait for Type, TypeScript implements) are kept by name only and never resolved to an item. Dead Code counts them by trait name.

When two functions share a name, the import graph decides. With src/a/fmt.ts and src/b/fmt.ts both exporting format, src/main.ts importing from ./b/fmt, and src/c/other.ts calling format() without importing anything:

Terminal window
codeknife blast --no-cache --symbol src/a/fmt/format --format human
codeknife blast --no-cache --symbol src/b/fmt/format --format human
info[CK_BLAST_IMPACT]: Blast radius for `src/a/fmt/format`: 0 upstream caller(s) across 1 file(s), 0 entrypoint(s), 0 test(s)
--> src/a/fmt.ts:1-3 (src/a/fmt/format)
blast │ 1 ▓
...
info[CK_BLAST_IMPACT]: Blast radius for `src/b/fmt/format`: 1 upstream caller(s) across 2 file(s), 1 entrypoint(s), 0 test(s)
--> src/b/fmt.ts:1-3 (src/b/fmt/format)
= note: src/main.ts:3 — entrypoint reaches format via caller cone
...

main.ts links to the imported format. The call in other.ts stays unresolved.

The opposite mistake happens when a name is unique in your code. Step 4 ignores the qualifier, so a call to an external function with the same name links to your function if it is in scope. In this Go package, helper calls uuid.New() from github.com/google/uuid, and the package also defines its own New:

Terminal window
codeknife blast --no-cache --symbol example.com/shop/store/New --format human
info[CK_BLAST_IMPACT]: Blast radius for `example.com/shop/store/New`: 2 upstream caller(s) across 2 file(s), 2 entrypoint(s), 3 test(s)
--> store/store.go:33-35 (example.com/shop/store/New)
= note: store/store_test.go:5 — covering test: example.com/shop/store/TestAdd
= note: store/store_test.go:10 — covering test: example.com/shop/store/TestCount
= note: store/store_test.go:16 — covering test: example.com/shop/store/BenchmarkAdd
= note: cmd/server/main.go:5 — entrypoint reaches New via caller cone
= note: store/store.go:46 — entrypoint reaches New via caller cone
...

The caller at store/store.go:46 is helper, linked through uuid.New(). The caller in cmd/server/main.go is real: it calls store.New() and imports the package.

These patterns produce no edge, or a wrong one:

  • Dynamic imports. import("x"), const x = require("x"), importlib, Rust include! and any path built at runtime.
  • Re-exports. A barrel file such as src/lib/index.ts containing export { compute } from "./compute" gets an edge to compute.ts, and a consumer importing from ../lib gets an edge to the barrel. But the consumer’s call compute() is only resolved against modules it imports directly (or files in its own directory), so it stays unresolved. In a demo, blast on compute reported 0 callers.
  • Aliases. Calls through an import alias are recorded under the alias name. use crate::util::double as twice; followed by twice(x), or Python from .core.engine import run as go followed by go(), does not link to double or run.
  • Macros. In Rust, every name( inside a macro invocation’s text is recorded as a call. Macro definitions themselves are not items, and code generated by macros is invisible.
  • Method dispatch. obj.save() resolves by the name save and the qualifier text obj, never by the type of obj. With several save methods in scope, the one in the caller’s module or an imported module wins, regardless of the receiver’s real type. Trait and interface dispatch is not followed.
  • Cross-language calls. A JavaScript file calling a TypeScript function never links (see Language Support). HTTP, SQL and environment-variable links between languages go through boundary tokens instead, in Blast Radius.
  • Test callbacks in TypeScript and JavaScript. it(...) and test(...) bodies record no calls, so they are never callers.
  • Dead Code walks the resolved call edges from a set of roots. The roots include entry-point functions, trait implementations, and public items in entry files or in library-root packages (Rust crates with src/lib.rs, package.json with exports, main or module, every Python package, Go modules without a root main.go). An unresolved call makes its target look unused. A non-test, non-entry file is an orphan when no import edge or resolved reference points at its module and none of its items is reachable, so a missed import makes a used file look dead, as with src/legacy.js above.
  • Blast Radius follows resolved calls backwards. Missed calls shrink a cone; false links (the uuid.New() case) grow it.
  • Architecture finds module cycles from import edges plus resolved references between modules, ignoring edges between a module and its own ancestor or descendant. False edges, such as the Python parent-package edges, can create or hide cycles. Layer rules and the shallow-module check also read these edges.
  • Smart Test Selection picks tests from Blast Radius caller cones and from reverse module imports.

Resolution has no flags, no configuration keys and no exit codes. An import or call that cannot be resolved is dropped or left without a target, with no warning. The tsconfig.json is read silently: if it cannot be read or parsed as JSONC, no aliases are used.

There is no command that prints the import graph directly. The edges show up in codeknife map (the Garden Map), codeknife blast (MCP tool codeknife_blast), codeknife dead and codeknife arch, and the per-item caller counts in codeknife reuse (MCP tool codeknife_reuse). See MCP Tools.