For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Build pnpm dep:refs CLI for symbol-level export reference queries to support the ongoing large refactor — given a file:exportName, list all reference sites (with re-export distinction).
Architecture: Single Node ESM script scripts/dep-refs.mjs (~200 lines) built on ts-morph. Loads workspace sources via globs + tsconfig.base.json, uses getExportedDeclarations() to find target symbol and findReferences() to enumerate usages. Re-exports detected by checking whether the reference node's ancestor is ExportDeclaration/ExportSpecifier.
Tech Stack: Node ESM, ts-morph (new devDep), follows the conventions of the existing scripts/dependency-graph.mjs (no TypeScript, no transpile, kebab-case CLI flags, Chinese-friendly help text).
Testing strategy: Per spec, manual smoke tests only (no automated test suite). Each task has explicit "Verify" steps with expected output. The script is a single-purpose dev tool; auto-tests would couple to the full monorepo compile state for low marginal benefit.
| Path | Action | Purpose |
|---|---|---|
scripts/dep-refs.mjs |
Create | The CLI itself, ~200 lines |
package.json |
Modify | Add dep:refs npm script + ts-morph devDep |
Single file because the script is small and lives next to peer scripts/dependency-graph.mjs. No tests directory.
Files:
package.json (devDependencies + scripts)Create: scripts/dep-refs.mjs
[ ] Step 1: Install ts-morph
pnpm add -D -w ts-morph
Expected: package.json gains "ts-morph": "^<version>" under devDependencies, lockfile updated. No errors.
Edit package.json, in the scripts block right after the existing "dep:graph" line, add:
"dep:refs": "node scripts/dep-refs.mjs",
Create scripts/dep-refs.mjs with shebang, help text, no-op main:
#!/usr/bin/env node
import process from "node:process";
function printHelp() {
console.log(`查询 TypeScript export 的所有引用位置(symbol 级),用于大型重构时安全删代码。
用法:
pnpm dep:refs <file>:<exportName> 查 export 的所有引用
pnpm dep:refs --list-exports <file> 列出文件的所有 export
pnpm dep:refs <file>:<exportName> --json JSON 输出
pnpm dep:refs --scope <glob> <file>:<sym> 缩小扫描范围加速
选项:
--list-exports 切换到 list-exports 模式
--json 以 JSON 输出
--scope <glob> 只加载匹配 glob 的源文件(默认加载所有 workspace 源码 + test)
-h, --help 查看帮助
示例:
pnpm dep:refs packages/services/src/bots/botsService.ts:createBotSession
pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts
`);
}
function main(argv) {
if (argv.length === 0 || argv.includes("-h") || argv.includes("--help")) {
printHelp();
process.exit(0);
}
console.error("not implemented yet");
process.exit(1);
}
main(process.argv.slice(2));
Run: pnpm dep:refs --help
Expected: prints the Chinese help text, exit 0.
Run: pnpm dep:refs
Expected: prints help, exit 0.
Run: pnpm dep:refs foo
Expected: prints not implemented yet to stderr, exit 1.
[ ] Step 5: Commit
git add package.json pnpm-lock.yaml scripts/dep-refs.mjs
git commit -m "feat(scripts): scaffold dep:refs CLI with ts-morph"
Files:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Replace main() with arg parser
Replace the skeleton main() with a parser that builds an options object. Insert these helpers above main:
function parseArgs(argv) {
const options = {
target: null, // "file:name" for refs query, "file" for list-exports
mode: "refs", // "refs" | "list-exports"
json: false,
scope: null, // glob string, null = default
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "-h" || arg === "--help") {
printHelp();
process.exit(0);
}
if (arg === "--json") {
options.json = true;
continue;
}
if (arg === "--list-exports") {
options.mode = "list-exports";
continue;
}
if (arg === "--scope") {
options.scope = argv[i + 1];
i += 1;
if (!options.scope) {
throw new Error("--scope 需要一个 glob 参数");
}
continue;
}
if (arg === "--") {
continue;
}
if (options.target !== null) {
throw new Error(`只能传一个目标参数,已收到 ${options.target},又收到 ${arg}`);
}
options.target = arg;
}
if (options.target === null) {
throw new Error("缺少目标参数。用法: pnpm dep:refs <file>:<exportName> 或 pnpm dep:refs --list-exports <file>");
}
if (options.mode === "refs" && !options.target.includes(":")) {
throw new Error(`refs 模式需要 <file>:<exportName> 格式,收到: ${options.target}`);
}
return options;
}
Then update main:
function main(argv) {
if (argv.length === 0 || argv.includes("-h") || argv.includes("--help")) {
printHelp();
process.exit(0);
}
let options;
try {
options = parseArgs(argv);
} catch (error) {
console.error(`错误: ${error.message}`);
process.exit(1);
}
console.log("parsed options:", options);
process.exit(0);
}
Run: pnpm dep:refs foo.ts:bar
Expected: prints parsed options: { target: 'foo.ts:bar', mode: 'refs', json: false, scope: null }.
Run: pnpm dep:refs --list-exports foo.ts
Expected: mode: 'list-exports', target 'foo.ts'.
Run: pnpm dep:refs foo.ts:bar --json
Expected: json: true.
Run: pnpm dep:refs --scope packages/services foo.ts:bar
Expected: scope: 'packages/services'.
Run: pnpm dep:refs foo.ts
Expected: stderr 错误: refs 模式需要 <file>:<exportName> 格式..., exit 1.
Run: pnpm dep:refs
Expected: prints help, exit 0.
[ ] Step 3: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): parse dep:refs CLI arguments"
Files:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Add project loader
Add at the top of the file (after import process):
import path from "node:path";
import { Project } from "ts-morph";
const ROOT = process.cwd();
const EXCLUDE_GLOBS = [
"!**/node_modules/**",
"!**/dist/**",
"!**/build/**",
"!**/coverage/**",
"!**/out/**",
];
const DEFAULT_GLOBS = [
"packages/*/src/**/*.{ts,tsx,mts,cts}",
"packages/*/test/**/*.{ts,tsx,mts,cts}",
"apps/*/src/**/*.{ts,tsx,mts,cts}",
"apps/*/test/**/*.{ts,tsx,mts,cts}",
"harness/**/*.{ts,tsx,mts,cts}",
...EXCLUDE_GLOBS,
];
function loadProject(scope) {
const project = new Project({
tsConfigFilePath: path.join(ROOT, "tsconfig.base.json"),
skipAddingFilesFromTsConfig: true,
skipFileDependencyResolution: false,
});
const globs = scope
? [
`${scope.replace(/\/$/, "")}/**/*.{ts,tsx,mts,cts}`,
...EXCLUDE_GLOBS,
]
: DEFAULT_GLOBS;
const added = project.addSourceFilesAtPaths(globs);
return { project, addedCount: added.length };
}
Replace the console.log("parsed options:", options) line in main with:
const { project, addedCount } = loadProject(options.scope);
console.log(`loaded ${addedCount} source files (scope: ${options.scope ?? "default"})`);
console.log("options:", options);
process.exit(0);
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:createBotSession
Expected (after ~10-30s): something like loaded 1500 source files (scope: default). Number doesn't need to be exact but should be large (hundreds to thousands).
Run: pnpm dep:refs --scope packages/services foo.ts:bar
Expected: much smaller count (e.g. ~50-200 files), faster startup.
Run: pnpm dep:refs --scope nonexistent foo.ts:bar
Expected: loaded 0 source files. (Not an error — empty scope is valid; later steps will error when symbol can't be resolved.)
[ ] Step 4: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): load workspace sources into ts-morph project"
--list-exports mode (human output)Files:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Add resolveSourceFile helper + list-exports handler
Add after loadProject:
function resolveSourceFile(project, filePath) {
const absolute = path.resolve(ROOT, filePath);
const sourceFile = project.getSourceFile(absolute);
if (!sourceFile) {
throw new Error(`源文件未加载到 project: ${filePath}\n - 确认路径是否正确\n - 如使用了 --scope,检查文件是否在范围内`);
}
return sourceFile;
}
function kindLabel(declaration) {
const kind = declaration.getKindName();
switch (kind) {
case "FunctionDeclaration": return "function";
case "ClassDeclaration": return "class";
case "InterfaceDeclaration": return "interface";
case "TypeAliasDeclaration": return "type";
case "EnumDeclaration": return "enum";
case "VariableDeclaration": return "const";
default: return kind.replace(/Declaration$/, "").toLowerCase();
}
}
function listExports(project, filePath) {
const sourceFile = resolveSourceFile(project, filePath);
const map = sourceFile.getExportedDeclarations();
const rows = [];
for (const [name, declarations] of map) {
for (const decl of declarations) {
rows.push({
name,
kind: kindLabel(decl),
line: decl.getStartLineNumber(),
});
}
}
rows.sort((a, b) => a.line - b.line);
return { file: filePath, exports: rows };
}
function printListExports(result) {
console.log(result.file);
console.log("");
console.log(`Exports (${result.exports.length}):`);
if (result.exports.length === 0) {
console.log(" (none)");
return;
}
const nameWidth = Math.max(...result.exports.map((r) => r.name.length));
const kindWidth = Math.max(...result.exports.map((r) => r.kind.length));
for (const row of result.exports) {
console.log(
` ${row.name.padEnd(nameWidth)} ${row.kind.padEnd(kindWidth)} line ${row.line}`,
);
}
}
Replace the post-load block in main with:
const { project, addedCount } = loadProject(options.scope);
if (addedCount === 0) {
console.error(`警告: scope 内未加载任何源文件 (scope: ${options.scope})`);
}
try {
if (options.mode === "list-exports") {
const result = listExports(project, options.target);
printListExports(result);
process.exit(0);
}
console.error("refs 模式尚未实现");
process.exit(1);
} catch (error) {
console.error(`错误: ${error.message}`);
process.exit(1);
}
Run: pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts
Expected: file path, blank line, Exports (N):, then aligned name/kind/line rows. Numbers and names depend on actual file but should match what's exported from botsService.ts (cross-check with the file content).
Run: pnpm dep:refs --list-exports packages/services/src/does-not-exist.ts
Expected: stderr 错误: 源文件未加载到 project: ..., exit 1.
[ ] Step 4: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): implement dep:refs --list-exports"
--list-exports --json outputFiles:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Branch on options.json in main
In main, replace the list-exports block with:
if (options.mode === "list-exports") {
const result = listExports(project, options.target);
if (options.json) {
console.log(JSON.stringify(result, null, 2));
} else {
printListExports(result);
}
process.exit(0);
}
Run: pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts --json
Expected: valid JSON with shape { "file": "...", "exports": [{ "name": "...", "kind": "...", "line": N }, ...] }. Pipe to jq . to sanity-check.
Run: pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts --json | jq '.exports | length'
Expected: a number > 0.
[ ] Step 3: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): add --json output for list-exports"
findReferences for <file>:<exportName> (human output, no re-export split yet)Files:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Add findReferencesForExport + printer
Add after listExports:
function parseTarget(target) {
const idx = target.lastIndexOf(":");
const filePath = target.slice(0, idx);
const exportName = target.slice(idx + 1);
if (!filePath || !exportName) {
throw new Error(`目标格式错误: ${target}(需 <file>:<exportName>)`);
}
return { filePath, exportName };
}
function toRelative(absolutePath) {
return path.relative(ROOT, absolutePath);
}
function snippetForNode(node) {
const text = node.getSourceFile().getFullText();
const start = node.getStart();
const lineStart = text.lastIndexOf("\n", start - 1) + 1;
let lineEnd = text.indexOf("\n", start);
if (lineEnd === -1) lineEnd = text.length;
return text.slice(lineStart, lineEnd).trim();
}
function findReferencesForExport(project, filePath, exportName) {
const sourceFile = resolveSourceFile(project, filePath);
const declarationsMap = sourceFile.getExportedDeclarations();
const declarations = declarationsMap.get(exportName);
if (!declarations || declarations.length === 0) {
const available = [...declarationsMap.keys()].slice(0, 20).join(", ");
throw new Error(
`${filePath} 没有名为 "${exportName}" 的 export\n 可用 export(前 20 个): ${available || "(无)"}`,
);
}
const symbol = {
name: exportName,
kind: kindLabel(declarations[0]),
file: filePath,
line: declarations[0].getStartLineNumber(),
};
const declLocations = new Set(
declarations.map((d) => `${d.getSourceFile().getFilePath()}:${d.getStartLineNumber()}`),
);
const refs = [];
for (const decl of declarations) {
const nameNode = typeof decl.getNameNode === "function" ? decl.getNameNode() : null;
const target = nameNode ?? decl;
const refSymbols = target.findReferences();
for (const refSymbol of refSymbols) {
for (const ref of refSymbol.getReferences()) {
const node = ref.getNode();
const refSourceFile = node.getSourceFile();
const line = node.getStartLineNumber();
const col = node.getStart() - node.getSourceFile().getLineAndColumnAtPos(node.getStart()).column < 0
? 0
: refSourceFile.getLineAndColumnAtPos(node.getStart()).column;
const filePathAbs = refSourceFile.getFilePath();
const locationKey = `${filePathAbs}:${line}`;
if (declLocations.has(locationKey)) continue;
refs.push({
file: toRelative(filePathAbs),
line,
col,
snippet: snippetForNode(node),
});
}
}
}
const seen = new Set();
const unique = [];
for (const ref of refs) {
const key = `${ref.file}:${ref.line}:${ref.col}`;
if (seen.has(key)) continue;
seen.add(key);
unique.push(ref);
}
unique.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file.localeCompare(b.file)));
return {
symbol,
references: unique,
reExports: [],
notes: ["Static analysis only. Dynamic import() and string-based usage not detected."],
};
}
function printRefs(result) {
const { symbol, references } = result;
console.log(`${symbol.name} (${symbol.kind}, exported at ${symbol.file}:${symbol.line})`);
console.log("");
console.log(`References (${references.length}):`);
if (references.length === 0) {
console.log(" Safe to delete (no static references and no re-exports).");
} else {
for (const ref of references) {
console.log(` ${ref.file}:${ref.line}:${ref.col}`);
console.log(` > ${ref.snippet}`);
}
}
console.log("");
for (const note of result.notes) {
console.log(`Note: ${note}`);
}
}
Replace the "refs 模式尚未实现" branch:
if (options.mode === "refs") {
const { filePath, exportName } = parseTarget(options.target);
const result = findReferencesForExport(project, filePath, exportName);
if (options.json) {
console.log(JSON.stringify(result, null, 2));
} else {
printRefs(result);
}
process.exit(0);
}
First pick a real export to test against. Look at pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts output, then pick a name (e.g. BotsService or similar — use whatever's actually there).
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:<realName>
Expected: header line with kind, References (N): followed by file:line:col rows with snippets. The count and locations should roughly match a grep -rn '<realName>' on the repo (allowing for grep noise — your count will be lower because it's symbol-aware).
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:thisDoesNotExist
Expected: stderr error listing first 20 available exports, exit 1.
[ ] Step 4: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): implement dep:refs symbol reference query"
Files:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Add re-export detection helper
Add above findReferencesForExport:
function isReExportReference(node) {
let current = node.getParent();
while (current) {
const kind = current.getKindName();
if (kind === "ExportSpecifier" || kind === "ExportDeclaration") {
return true;
}
if (kind === "SourceFile") return false;
current = current.getParent();
}
return false;
}
Inside findReferencesForExport, replace the refs.push({...}) block with a split:
const entry = {
file: toRelative(filePathAbs),
line,
col,
snippet: snippetForNode(node),
};
if (isReExportReference(node)) {
reExportsTmp.push(entry);
} else {
refs.push(entry);
}
Add const reExportsTmp = []; next to const refs = []; near the top of the function.
After the dedup block for unique (refs), add the same dedup for reExports:
const reExportSeen = new Set();
const reExportsUnique = [];
for (const ref of reExportsTmp) {
const key = `${ref.file}:${ref.line}:${ref.col}`;
if (reExportSeen.has(key)) continue;
reExportSeen.add(key);
reExportsUnique.push(ref);
}
reExportsUnique.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file.localeCompare(b.file)));
Change the return statement to use the split lists:
return {
symbol,
references: unique,
reExports: reExportsUnique,
notes: ["Static analysis only. Dynamic import() and string-based usage not detected."],
};
Modify printRefs to show re-exports between the References block and notes:
function printRefs(result) {
const { symbol, references, reExports } = result;
console.log(`${symbol.name} (${symbol.kind}, exported at ${symbol.file}:${symbol.line})`);
console.log("");
console.log(`References (${references.length}):`);
if (references.length === 0 && reExports.length === 0) {
console.log(" Safe to delete (no static references and no re-exports).");
} else if (references.length === 0) {
console.log(" (none — only re-exported)");
} else {
for (const ref of references) {
console.log(` ${ref.file}:${ref.line}:${ref.col}`);
console.log(` > ${ref.snippet}`);
}
}
if (reExports.length > 0) {
console.log("");
console.log(`Re-exports (${reExports.length}):`);
for (const ref of reExports) {
console.log(` ${ref.file}:${ref.line}`);
console.log(` > ${ref.snippet}`);
}
}
console.log("");
for (const note of result.notes) {
console.log(`Note: ${note}`);
}
}
Pick a symbol that's known to be re-exported. Check the barrel file (likely packages/services/src/node.ts or index.ts based on the git status):
grep -E "export \{" packages/services/src/node.ts | head -5
Pick one of the names you see (e.g. botsService), then:
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:<reExportedName>
Expected: output now includes a Re-exports (N): section listing the barrel file. The barrel file should no longer appear under References.
Run the same with a symbol you know is NOT re-exported (e.g. a private helper that happens to be exported but only used in tests).
Expected: no Re-exports section, just References.
[ ] Step 5: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): split references into refs and re-exports"
pnpm knipFiles:
Modify: scripts/dep-refs.mjs
[ ] Step 1: Append knip workflow note to help
In printHelp, append before the closing backtick:
推荐用法:
1. 先跑 pnpm knip 拿到 unused exports 列表(瞬秒)
2. 对存疑的 export 用 pnpm dep:refs file:name 看具体引用者
3. 决定能删 / 要先改调用方
说明:
- 仅静态分析,不检测 dynamic import() 和字符串路径引用
- 首次启动约 10-30 秒(加载全 workspace);用 --scope 可显著加速
In findReferencesForExport, the col calculation has a confusing inline fallback. Simplify to:
const { column } = refSourceFile.getLineAndColumnAtPos(node.getStart());
const col = column;
(Remove the original col line and inline math.)
In printRefs, where snippets are printed, wrap with truncation:
function truncateSnippet(s, max = 120) {
if (s.length <= max) return s;
return s.slice(0, max - 1) + "…";
}
And use truncateSnippet(ref.snippet) in both the references and reExports loops. (JSON output keeps full snippet — only the human printer truncates.)
Run: pnpm dep:refs --help
Expected: help text now includes 推荐用法 and 说明 sections.
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:<knownExport>
Expected: output still correct, columns are accurate, long lines truncated with ….
Run: pnpm dep:refs packages/services/src/bots/botsService.ts:<knownExport> --json | jq '.references[0].snippet | length'
Expected: full-length snippet (JSON not truncated).
[ ] Step 5: Commit
git add scripts/dep-refs.mjs
git commit -m "feat(scripts): polish dep:refs help and output formatting"
Files:
None modified — this is a verification task.
[ ] Step 1: Run on a file currently being refactored
The user's current branch is feat/new-agent with modifications under packages/services/src/bots/. Pick an export from botsService.ts:
pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts
[ ] Step 2: Pick one export from the list and query it
pnpm dep:refs packages/services/src/bots/botsService.ts:<pickOne>
Inspect output. Cross-check that:
The count is plausible (not 0 for a clearly-used export, not absurdly high)
[ ] Step 3: Test --scope speedup
Time both:
time pnpm dep:refs --scope packages/services packages/services/src/bots/botsService.ts:<pickOne> >/dev/null
time pnpm dep:refs packages/services/src/bots/botsService.ts:<pickOne> >/dev/null
Expected: the --scope run is meaningfully faster (typically 2-5× depending on monorepo size).
[ ] Step 4: Test JSON output is consumable
pnpm dep:refs packages/services/src/bots/botsService.ts:<pickOne> --json | jq '.references | length'
pnpm dep:refs packages/services/src/bots/botsService.ts:<pickOne> --json | jq '.reExports[].file'
Expected: jq parses without error, returns numbers and file paths.
Run pnpm knip to find an unused export, then verify dep:refs agrees:
pnpm knip 2>&1 | grep "Unused exports" -A 5
# Pick one, e.g.: packages/foo/src/bar.ts: bazFn
pnpm dep:refs packages/foo/src/bar.ts:bazFn
Expected: References (0). Safe to delete (...).
If something is wrong in the script, go back and fix the relevant task. If everything passes, the feature is done.
(Filled in during plan-writing review pass — no action items remained.)
--list-exports: Tasks 4, 5 ✅--scope: Tasks 2, 3 ✅loadProject, findReferencesForExport, printRefs, listExports, printListExports, kindLabel, resolveSourceFile, parseTarget, snippetForNode, isReExportReference, truncateSnippet) used consistently across tasks.