@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IDE content search (#6474, epic #6469) — find-in-project / codebase grep.
|
|
3
|
+
*
|
|
4
|
+
* A self-contained, dependency-free recursive content search over the session
|
|
5
|
+
* workspace: case-insensitive substring match, returning file/line/column plus
|
|
6
|
+
* the matched line as a preview. Powers the dashboard Cmd+Shift+F palette; it
|
|
7
|
+
* also gives find-references (#6477) a reverse-lookup primitive.
|
|
8
|
+
*
|
|
9
|
+
* SECURITY — the walk mirrors collectWorkspaceSymbols (ide/symbols.js): the root
|
|
10
|
+
* is realpath-resolved and an optional scope `path` is REAL-path confined to it
|
|
11
|
+
* (a `..`-escape, an absolute path, or a symlink whose real target lands outside
|
|
12
|
+
* is refused), ignored/dot dirs are skipped, and files are lstat'd so a symlink
|
|
13
|
+
* is never followed. Keep the two confinement blocks in sync — both are the
|
|
14
|
+
* attacker-reachable WS surface's boundary; the regression tests
|
|
15
|
+
* (ide-search.test.js) assert the symlink-escape cases on both.
|
|
16
|
+
*/
|
|
17
|
+
import { readdir, readFile, stat, realpath, lstat } from 'fs/promises'
|
|
18
|
+
import { join, resolve, relative, extname, sep } from 'path'
|
|
19
|
+
|
|
20
|
+
// Directories never worth walking (mirrors symbols.js IGNORED_DIRS).
|
|
21
|
+
const IGNORED_DIRS = new Set([
|
|
22
|
+
'node_modules', '.git', 'dist', 'build', 'out', 'target', 'coverage',
|
|
23
|
+
'.next', '.nuxt', '.expo', '.turbo', '.cache', 'vendor', '__pycache__',
|
|
24
|
+
'.venv', 'venv', '.tox', '.gradle', '.idea', '.vscode-test',
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
// Text file extensions we grep. Broader than symbols' EXT_LANG (which only
|
|
28
|
+
// parses js/py) — a codebase search should cover configs, docs, and other
|
|
29
|
+
// source languages — but still an allowlist so binaries/assets are skipped
|
|
30
|
+
// without a read.
|
|
31
|
+
const TEXT_EXT = new Set([
|
|
32
|
+
'.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts',
|
|
33
|
+
'.py', '.pyi', '.rb', '.go', '.rs', '.java', '.kt', '.swift', '.c', '.h',
|
|
34
|
+
'.cc', '.cpp', '.hpp', '.cs', '.php', '.lua', '.sh', '.bash', '.zsh',
|
|
35
|
+
'.json', '.jsonc', '.yml', '.yaml', '.toml', '.ini', '.env', '.xml',
|
|
36
|
+
'.html', '.htm', '.css', '.scss', '.less', '.svg', '.vue', '.svelte',
|
|
37
|
+
'.md', '.mdx', '.txt', '.rst', '.sql', '.graphql', '.gql', '.proto',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
// Extensionless / dotfile basenames worth grepping. Matched by FULL basename
|
|
41
|
+
// (lowercased) — `extname()` returns '' for a leading-dot file like `.env`, so
|
|
42
|
+
// these can't be caught by TEXT_EXT.
|
|
43
|
+
const TEXT_BASENAMES = new Set([
|
|
44
|
+
'.env', '.gitignore', '.editorconfig', '.npmrc', '.nvmrc', '.babelrc',
|
|
45
|
+
'.prettierrc', '.eslintrc', 'dockerfile', 'makefile', 'procfile', 'gemfile',
|
|
46
|
+
])
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Shared confined walk (#6474 search + #6477 find-references). Walks `rootDir`
|
|
50
|
+
* (or a confined sub-path), reads each text file, and calls `matchLine(text)` per
|
|
51
|
+
* line; `matchLine` returns an array of 1-indexed column positions where a match
|
|
52
|
+
* starts. Each match becomes a `{file,line,column,text}` row, honouring the caps.
|
|
53
|
+
*
|
|
54
|
+
* SECURITY — this is the single confinement boundary for BOTH callers: the root
|
|
55
|
+
* is realpath-resolved, an optional scope `path` is REAL-path confined (a
|
|
56
|
+
* `..`-escape, an absolute path, or a symlink whose real target lands outside is
|
|
57
|
+
* refused), ignored/dot dirs are skipped, and files are lstat'd so a symlink is
|
|
58
|
+
* never followed. The regression tests in ide-search.test.js assert the
|
|
59
|
+
* symlink-escape cases for both entry points.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
62
|
+
* @param {(line: string) => number[]} matchLine Per-line matcher → 1-indexed columns.
|
|
63
|
+
* @param {object} [opts] path, maxFiles(2000), maxResults(500), maxFileSize(512KB),
|
|
64
|
+
* maxDepth(12), maxLineLength(1000), isCancelled.
|
|
65
|
+
* @param {() => boolean} [opts.isCancelled] #6506 — polled at each walk boundary
|
|
66
|
+
* (dir entry, per-dirent, file entry); when it returns true the walk aborts
|
|
67
|
+
* promptly. Lets a caller supersede an in-flight walk (single-flight search).
|
|
68
|
+
* @returns {Promise<{results: Array<{file:string,line:number,column:number,text:string}>, truncated: boolean}>}
|
|
69
|
+
*/
|
|
70
|
+
async function collectMatches(rootDir, matchLine, opts = {}) {
|
|
71
|
+
const {
|
|
72
|
+
path = null,
|
|
73
|
+
maxFiles = 2000,
|
|
74
|
+
maxResults = 500,
|
|
75
|
+
maxFileSize = 512 * 1024,
|
|
76
|
+
maxDepth = 12,
|
|
77
|
+
maxLineLength = 1000,
|
|
78
|
+
isCancelled = null,
|
|
79
|
+
} = opts
|
|
80
|
+
|
|
81
|
+
// Realpath-confine the root (symlink-safe base) — see the security note above.
|
|
82
|
+
let root
|
|
83
|
+
try {
|
|
84
|
+
root = await realpath(resolve(rootDir))
|
|
85
|
+
} catch {
|
|
86
|
+
return { results: [], truncated: false }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let target = root
|
|
90
|
+
if (path) {
|
|
91
|
+
let realTarget
|
|
92
|
+
try {
|
|
93
|
+
realTarget = await realpath(resolve(root, path))
|
|
94
|
+
} catch {
|
|
95
|
+
return { results: [], truncated: false }
|
|
96
|
+
}
|
|
97
|
+
const rel = relative(root, realTarget)
|
|
98
|
+
if (rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget) {
|
|
99
|
+
return { results: [], truncated: false }
|
|
100
|
+
}
|
|
101
|
+
if (rel.split(sep).some((s) => IGNORED_DIRS.has(s) || s.startsWith('.'))) {
|
|
102
|
+
return { results: [], truncated: false }
|
|
103
|
+
}
|
|
104
|
+
target = realTarget
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const results = []
|
|
108
|
+
let filesRead = 0
|
|
109
|
+
let truncated = false
|
|
110
|
+
|
|
111
|
+
/** Grep one file into the accumulator, honouring the caps. */
|
|
112
|
+
async function grepFile(absPath) {
|
|
113
|
+
if (isCancelled && isCancelled()) return
|
|
114
|
+
if (filesRead >= maxFiles) { truncated = true; return }
|
|
115
|
+
const base = absPath.split(sep).pop().toLowerCase()
|
|
116
|
+
const ext = extname(base)
|
|
117
|
+
// Match by extension (foo.ts) OR by full basename for dotfiles / extensionless
|
|
118
|
+
// well-known files (.env, .gitignore, Dockerfile, Makefile) — extname() is ''
|
|
119
|
+
// for those, so the TEXT_EXT check alone would miss them.
|
|
120
|
+
if (!TEXT_EXT.has(ext) && !TEXT_BASENAMES.has(base)) return
|
|
121
|
+
let st
|
|
122
|
+
try {
|
|
123
|
+
// lstat (not stat) so a symlink is never followed — defence-in-depth; the
|
|
124
|
+
// scoped target is realpath-confined and walk() skips symlink dirents.
|
|
125
|
+
st = await lstat(absPath)
|
|
126
|
+
} catch { return }
|
|
127
|
+
if (!st.isFile()) return
|
|
128
|
+
if (st.size > maxFileSize) return
|
|
129
|
+
filesRead++
|
|
130
|
+
let content
|
|
131
|
+
try {
|
|
132
|
+
content = await readFile(absPath, 'utf-8')
|
|
133
|
+
} catch { return }
|
|
134
|
+
// Skip a file that looks binary (a NUL in the first chunk) despite its ext.
|
|
135
|
+
if (content.indexOf(String.fromCharCode(0)) !== -1) return
|
|
136
|
+
const rel = relative(root, absPath).split(sep).join('/')
|
|
137
|
+
const lines = content.split('\n')
|
|
138
|
+
for (let i = 0; i < lines.length; i++) {
|
|
139
|
+
const cols = matchLine(lines[i])
|
|
140
|
+
for (let c = 0; c < cols.length; c++) {
|
|
141
|
+
if (results.length >= maxResults) { truncated = true; return }
|
|
142
|
+
results.push({
|
|
143
|
+
file: rel,
|
|
144
|
+
line: i + 1,
|
|
145
|
+
column: cols[c],
|
|
146
|
+
text: lines[i].length > maxLineLength ? lines[i].slice(0, maxLineLength) : lines[i],
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Recursively walk a directory. */
|
|
153
|
+
async function walk(dir, depth) {
|
|
154
|
+
if (isCancelled && isCancelled()) return
|
|
155
|
+
if (depth > maxDepth || filesRead >= maxFiles || results.length >= maxResults) {
|
|
156
|
+
if (filesRead >= maxFiles || results.length >= maxResults) truncated = true
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
let dirents
|
|
160
|
+
try {
|
|
161
|
+
dirents = await readdir(dir, { withFileTypes: true })
|
|
162
|
+
} catch { return }
|
|
163
|
+
dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
164
|
+
for (const ent of dirents) {
|
|
165
|
+
if (isCancelled && isCancelled()) break
|
|
166
|
+
if (filesRead >= maxFiles || results.length >= maxResults) { truncated = true; break }
|
|
167
|
+
const abs = join(dir, ent.name)
|
|
168
|
+
if (ent.isDirectory()) {
|
|
169
|
+
if (IGNORED_DIRS.has(ent.name) || ent.name.startsWith('.')) continue
|
|
170
|
+
await walk(abs, depth + 1)
|
|
171
|
+
} else if (ent.isFile()) {
|
|
172
|
+
await grepFile(abs)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let tstat
|
|
178
|
+
try {
|
|
179
|
+
tstat = await stat(target)
|
|
180
|
+
} catch {
|
|
181
|
+
return { results, truncated }
|
|
182
|
+
}
|
|
183
|
+
if (tstat.isFile()) {
|
|
184
|
+
await grepFile(target)
|
|
185
|
+
} else if (tstat.isDirectory()) {
|
|
186
|
+
await walk(target, 0)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return { results, truncated }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Search the workspace (or a confined sub-path) for a case-insensitive substring
|
|
194
|
+
* (#6474). One result per matching line (the first occurrence), matching the
|
|
195
|
+
* find-in-project palette's expectation.
|
|
196
|
+
*
|
|
197
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
198
|
+
* @param {string} query Needle (min 2 chars after trim; else no-op).
|
|
199
|
+
* @param {object} [opts] See collectMatches.
|
|
200
|
+
* @returns {Promise<{results: Array<{file:string,line:number,column:number,text:string}>, truncated: boolean}>}
|
|
201
|
+
*/
|
|
202
|
+
export async function searchContent(rootDir, query, opts = {}) {
|
|
203
|
+
const needle = typeof query === 'string' ? query.trim() : ''
|
|
204
|
+
// A 1-char search would match almost everything and swamp the result cap; the
|
|
205
|
+
// dashboard also requires 2+ chars, so this is a cheap server-side guard too.
|
|
206
|
+
if (needle.length < 2) return { results: [], truncated: false }
|
|
207
|
+
const lowerNeedle = needle.toLowerCase()
|
|
208
|
+
return collectMatches(rootDir, (line) => {
|
|
209
|
+
const idx = line.toLowerCase().indexOf(lowerNeedle)
|
|
210
|
+
return idx === -1 ? EMPTY_COLS : [idx + 1]
|
|
211
|
+
}, opts)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const EMPTY_COLS = []
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Find all references to a symbol NAME (#6477) — reverse-lookup for the
|
|
218
|
+
* find-all-references panel. Unlike searchContent this is a WORD-BOUNDARY,
|
|
219
|
+
* case-SENSITIVE match (an identifier reference is exact + whole-word: `go`
|
|
220
|
+
* matches `go()` but not `goHome` or `Cargo`), and it returns EVERY occurrence on
|
|
221
|
+
* a line, not just the first. Regex-based over the same confined walk — ~80%
|
|
222
|
+
* accurate with zero new deps (no scope/type analysis; a string literal or
|
|
223
|
+
* comment mentioning the name is still a "reference").
|
|
224
|
+
*
|
|
225
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
226
|
+
* @param {string} symbol Identifier to find references to.
|
|
227
|
+
* @param {object} [opts] See collectMatches.
|
|
228
|
+
* @returns {Promise<{results: Array<{file:string,line:number,column:number,text:string}>, truncated: boolean}>}
|
|
229
|
+
*/
|
|
230
|
+
export async function findReferences(rootDir, symbol, opts = {}) {
|
|
231
|
+
const name = typeof symbol === 'string' ? symbol.trim() : ''
|
|
232
|
+
// Only real identifiers — a non-identifier can't be word-boundary-matched
|
|
233
|
+
// meaningfully and would risk a runaway regex.
|
|
234
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) return { results: [], truncated: false }
|
|
235
|
+
// Escape `$` (the only regex-special an identifier can contain) so a
|
|
236
|
+
// `$`-prefixed name doesn't turn into an end-of-line anchor.
|
|
237
|
+
const escaped = name.replace(/\$/g, '\\$&')
|
|
238
|
+
// Explicit identifier boundaries — a plain `\b` is `\w`-relative and mishandles
|
|
239
|
+
// `$`-names (`$` isn't a `\w` char): it MISSES a real `$store` and FALSE-matches
|
|
240
|
+
// the `$store` tail inside `my$store`. `(?<![\w$])…(?![\w$])` treats `$` as part
|
|
241
|
+
// of the identifier, so a reference must be flanked by non-identifier chars.
|
|
242
|
+
const re = new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, 'g')
|
|
243
|
+
const out = await collectMatches(rootDir, (line) => {
|
|
244
|
+
const cols = []
|
|
245
|
+
re.lastIndex = 0
|
|
246
|
+
let m
|
|
247
|
+
while ((m = re.exec(line)) !== null) {
|
|
248
|
+
cols.push(m.index + 1)
|
|
249
|
+
if (m.index === re.lastIndex) re.lastIndex++ // zero-width guard (defensive)
|
|
250
|
+
}
|
|
251
|
+
return cols
|
|
252
|
+
}, opts)
|
|
253
|
+
|
|
254
|
+
// Rank references in the ORIGINATING file first (#6516) — the file the symbol
|
|
255
|
+
// was alt+clicked in is usually where you want to look, mirroring how
|
|
256
|
+
// resolveSymbol uses `fromFile` as a tie-break. Normalize a Windows-style path
|
|
257
|
+
// to the forward-slash workspace-relative form collectMatches emits, then a
|
|
258
|
+
// stable partition floats origin rows to the front (Array.sort is stable since
|
|
259
|
+
// ES2019, so the deterministic walk order is preserved within each group).
|
|
260
|
+
// Post-collection, so it never changes which rows survive the cap — only order.
|
|
261
|
+
const fromFile = typeof opts.fromFile === 'string' && opts.fromFile.trim()
|
|
262
|
+
? opts.fromFile.trim().replace(/\\/g, '/')
|
|
263
|
+
: null
|
|
264
|
+
if (fromFile) {
|
|
265
|
+
out.results.sort((a, b) => (b.file === fromFile ? 1 : 0) - (a.file === fromFile ? 1 : 0))
|
|
266
|
+
}
|
|
267
|
+
return out
|
|
268
|
+
}
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IDE symbol parser (#6471, epic #6469).
|
|
3
|
+
*
|
|
4
|
+
* A self-contained, dependency-free regex parser that extracts top-level symbol
|
|
5
|
+
* declarations from workspace source files. The backbone for the symbol panel
|
|
6
|
+
* (#6472), go-to-definition (#6475), and symbol search (#6476).
|
|
7
|
+
*
|
|
8
|
+
* WHY REGEX, NOT REPO-MEMORY / TREE-SITTER / LSP
|
|
9
|
+
* ----------------------------------------------
|
|
10
|
+
* The epic's original scoping pointed at the repo-memory AST index, but that is
|
|
11
|
+
* an AGENT-facing MCP cache — the chroxy daemon has no verified runtime path to
|
|
12
|
+
* it, and coupling the daemon to an MCP at request time is a heavy dependency.
|
|
13
|
+
* So the daemon parses for itself: line-anchored regexes for the common
|
|
14
|
+
* `export` / `function` / `class` / `const` / `interface` / `type` / `enum`
|
|
15
|
+
* declaration forms. Deliberately ~80%-accurate and language-agnostic (a
|
|
16
|
+
* data-driven rule table, easy to extend) — tree-sitter / LSP is the Phase-4
|
|
17
|
+
* upgrade (#6479). No new binaries, no per-language servers, fully unit-testable.
|
|
18
|
+
*
|
|
19
|
+
* This module is PURE and side-effect-free except for reading files off disk in
|
|
20
|
+
* `collectWorkspaceSymbols`. The opt-in `features.ide` gate lives at the handler
|
|
21
|
+
* layer (handlers/ide-handlers.js); nothing here reads config or a socket.
|
|
22
|
+
*
|
|
23
|
+
* @typedef {Object} SymbolEntry
|
|
24
|
+
* @property {string} name Declared identifier.
|
|
25
|
+
* @property {string} kind One of: function, class, const, variable, interface, type, enum, method.
|
|
26
|
+
* @property {string} file Workspace-relative POSIX path of the declaring file.
|
|
27
|
+
* @property {number} line 1-indexed line of the declaration.
|
|
28
|
+
* @property {boolean} exported Whether the declaration is exported / public.
|
|
29
|
+
*/
|
|
30
|
+
import { readdir, readFile, stat, realpath, lstat } from 'fs/promises'
|
|
31
|
+
import { join, resolve, relative, extname, sep } from 'path'
|
|
32
|
+
|
|
33
|
+
// Directories never worth walking — build output, vendored deps, VCS metadata,
|
|
34
|
+
// language caches. Keeps the scan bounded and the symbol table signal-rich.
|
|
35
|
+
const IGNORED_DIRS = new Set([
|
|
36
|
+
'node_modules', '.git', 'dist', 'build', 'out', 'target', 'coverage',
|
|
37
|
+
'.next', '.nuxt', '.expo', '.turbo', '.cache', 'vendor', '__pycache__',
|
|
38
|
+
'.venv', 'venv', '.tox', '.gradle', '.idea', '.vscode-test',
|
|
39
|
+
])
|
|
40
|
+
|
|
41
|
+
// Extension → language id. Only these files are parsed; everything else
|
|
42
|
+
// (binaries, assets, lockfiles) is skipped without a read.
|
|
43
|
+
const EXT_LANG = {
|
|
44
|
+
'.js': 'js', '.jsx': 'js', '.mjs': 'js', '.cjs': 'js',
|
|
45
|
+
'.ts': 'js', '.tsx': 'js', '.mts': 'js', '.cts': 'js',
|
|
46
|
+
'.py': 'py', '.pyi': 'py',
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Per-language ordered rule tables. Each rule is applied in order to a line and
|
|
50
|
+
// the FIRST match wins (so `const enum X` resolves to `enum`, not `const`). The
|
|
51
|
+
// `name` group index is the capture holding the identifier; `exported` derives
|
|
52
|
+
// the visibility flag from the raw line + captured name.
|
|
53
|
+
//
|
|
54
|
+
// JS/TS notes: `const` whose right-hand side is an arrow or `function`
|
|
55
|
+
// expression is reported as a `function` (it is one, for navigation purposes);
|
|
56
|
+
// other `const`s are `const`, and `let`/`var` are `variable`. Only top-level-ish
|
|
57
|
+
// declarations are captured — the regexes are anchored at start-of-line allowing
|
|
58
|
+
// leading `export`/`default`/`async`/`abstract`, so indented class members are
|
|
59
|
+
// intentionally NOT matched (that is the ~80% line; #6479 raises it).
|
|
60
|
+
const JS_EXPORT = /^\s*export\b/
|
|
61
|
+
const RULES = {
|
|
62
|
+
js: [
|
|
63
|
+
{
|
|
64
|
+
kind: 'function',
|
|
65
|
+
re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/,
|
|
66
|
+
name: 1,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
kind: 'class',
|
|
70
|
+
re: /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/,
|
|
71
|
+
name: 1,
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
kind: 'interface',
|
|
75
|
+
re: /^\s*(?:export\s+)?(?:declare\s+)?interface\s+([A-Za-z_$][\w$]*)/,
|
|
76
|
+
name: 1,
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
kind: 'type',
|
|
80
|
+
re: /^\s*(?:export\s+)?(?:declare\s+)?type\s+([A-Za-z_$][\w$]*)\s*[=<]/,
|
|
81
|
+
name: 1,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
kind: 'enum',
|
|
85
|
+
re: /^\s*(?:export\s+)?(?:declare\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/,
|
|
86
|
+
name: 1,
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
// const/let/var. Kind is refined below from the right-hand side.
|
|
90
|
+
kind: 'const',
|
|
91
|
+
re: /^\s*(?:export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)\s*=([^=].*)?$/,
|
|
92
|
+
name: 2,
|
|
93
|
+
refine: (m) => {
|
|
94
|
+
const decl = m[1]
|
|
95
|
+
const rhs = (m[3] || '').trim()
|
|
96
|
+
// Arrow function or function-expression RHS ⇒ it's a function.
|
|
97
|
+
if (/^(?:async\s+)?(?:function\b|(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/.test(rhs)) {
|
|
98
|
+
return 'function'
|
|
99
|
+
}
|
|
100
|
+
return decl === 'const' ? 'const' : 'variable'
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
py: [
|
|
105
|
+
{
|
|
106
|
+
kind: 'class',
|
|
107
|
+
re: /^(\s*)class\s+([A-Za-z_]\w*)/,
|
|
108
|
+
name: 2,
|
|
109
|
+
indent: 1,
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
// Top-level `def` ⇒ function; indented `def` ⇒ method.
|
|
113
|
+
kind: 'function',
|
|
114
|
+
re: /^(\s*)(?:async\s+)?def\s+([A-Za-z_]\w*)/,
|
|
115
|
+
name: 2,
|
|
116
|
+
indent: 1,
|
|
117
|
+
refine: (m) => (m[1].length > 0 ? 'method' : 'function'),
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Parse a single source string into symbol entries. Pure — no I/O.
|
|
124
|
+
*
|
|
125
|
+
* @param {string} content File contents.
|
|
126
|
+
* @param {string} file Workspace-relative POSIX path recorded on each entry.
|
|
127
|
+
* @returns {SymbolEntry[]}
|
|
128
|
+
*/
|
|
129
|
+
export function parseSymbols(content, file) {
|
|
130
|
+
if (typeof content !== 'string' || !content) return []
|
|
131
|
+
const lang = EXT_LANG[extname(file).toLowerCase()]
|
|
132
|
+
const rules = RULES[lang]
|
|
133
|
+
if (!rules) return []
|
|
134
|
+
|
|
135
|
+
const out = []
|
|
136
|
+
const lines = content.split('\n')
|
|
137
|
+
for (let i = 0; i < lines.length; i++) {
|
|
138
|
+
const line = lines[i]
|
|
139
|
+
// Cheap skip for blank / comment-only lines (covers // # /* * leading forms).
|
|
140
|
+
const trimmed = line.trimStart()
|
|
141
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#')) {
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
for (const rule of rules) {
|
|
145
|
+
const m = line.match(rule.re)
|
|
146
|
+
if (!m) continue
|
|
147
|
+
const name = m[rule.name]
|
|
148
|
+
if (!name) break
|
|
149
|
+
const kind = rule.refine ? rule.refine(m) : rule.kind
|
|
150
|
+
let exported
|
|
151
|
+
if (lang === 'py') {
|
|
152
|
+
// Top-level (indent 0) and not underscore-prefixed ⇒ public.
|
|
153
|
+
exported = (rule.indent ? m[rule.indent].length === 0 : true) && !name.startsWith('_')
|
|
154
|
+
} else {
|
|
155
|
+
exported = JS_EXPORT.test(line)
|
|
156
|
+
}
|
|
157
|
+
out.push({ name, kind, file, line: i + 1, exported })
|
|
158
|
+
break // first matching rule wins for a line
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return out
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Walk a workspace (or a sub-path of it) and collect symbols from every source
|
|
166
|
+
* file, bounded so a huge tree can't exhaust memory or time. Returns the symbol
|
|
167
|
+
* table plus a `truncated` flag set when any cap was hit.
|
|
168
|
+
*
|
|
169
|
+
* `path` (optional) scopes the scan to a single file or directory inside
|
|
170
|
+
* `rootDir`; it is resolved to its REAL path and CONFINED to `rootDir` — a
|
|
171
|
+
* `..`-escape, an absolute path, OR a symlink whose real target lands outside is
|
|
172
|
+
* rejected, and scoping into ignored/dot dirs (node_modules, `.git`, …) is
|
|
173
|
+
* refused for parity with the full scan. `rootDir` itself is trusted (the handler
|
|
174
|
+
* passes the session's already home-validated cwd).
|
|
175
|
+
*
|
|
176
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
177
|
+
* @param {object} [opts]
|
|
178
|
+
* @param {string|null} [opts.path] Workspace-relative file/dir to scope to.
|
|
179
|
+
* @param {number} [opts.maxFiles] Cap on files read (default 2000).
|
|
180
|
+
* @param {number} [opts.maxSymbols] Cap on symbols returned (default 5000).
|
|
181
|
+
* @param {number} [opts.maxFileSize] Skip files larger than this (default 512KB).
|
|
182
|
+
* @param {number} [opts.maxDepth] Directory recursion depth (default 12).
|
|
183
|
+
* @returns {Promise<{symbols: SymbolEntry[], truncated: boolean}>}
|
|
184
|
+
*/
|
|
185
|
+
export async function collectWorkspaceSymbols(rootDir, opts = {}) {
|
|
186
|
+
const {
|
|
187
|
+
path = null,
|
|
188
|
+
maxFiles = 2000,
|
|
189
|
+
maxSymbols = 5000,
|
|
190
|
+
maxFileSize = 512 * 1024,
|
|
191
|
+
maxDepth = 12,
|
|
192
|
+
} = opts
|
|
193
|
+
|
|
194
|
+
// Use the REAL (symlink-resolved) workspace root as the confinement base and
|
|
195
|
+
// for displayed relative paths. A lexical resolve()/relative() alone is fooled
|
|
196
|
+
// by a symlink INSIDE the workspace that points out — which, on this
|
|
197
|
+
// attacker-reachable WS surface, would leak arbitrary host files.
|
|
198
|
+
let root
|
|
199
|
+
try {
|
|
200
|
+
root = await realpath(resolve(rootDir))
|
|
201
|
+
} catch {
|
|
202
|
+
return { symbols: [], truncated: false }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Resolve + confine the optional scope path against the REAL workspace root.
|
|
206
|
+
let target = root
|
|
207
|
+
if (path) {
|
|
208
|
+
let realTarget
|
|
209
|
+
try {
|
|
210
|
+
realTarget = await realpath(resolve(root, path))
|
|
211
|
+
} catch {
|
|
212
|
+
// Absolute / `..` paths resolve outside root (rejected below); a missing or
|
|
213
|
+
// broken-symlink path simply has nothing to enumerate. Either way, refuse.
|
|
214
|
+
return { symbols: [], truncated: false }
|
|
215
|
+
}
|
|
216
|
+
const rel = relative(root, realTarget)
|
|
217
|
+
if (rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget) {
|
|
218
|
+
// The REAL path escapes the workspace (e.g. via a symlink) — refuse.
|
|
219
|
+
return { symbols: [], truncated: false }
|
|
220
|
+
}
|
|
221
|
+
// Honour the same ignored-dir / dot-dir policy as the full-tree walk for the
|
|
222
|
+
// scoped path, so scoping can't enumerate node_modules/.git/.venv symbols the
|
|
223
|
+
// whole scan deliberately hides (e.g. `.git` hook scripts).
|
|
224
|
+
if (rel.split(sep).some((s) => IGNORED_DIRS.has(s) || s.startsWith('.'))) {
|
|
225
|
+
return { symbols: [], truncated: false }
|
|
226
|
+
}
|
|
227
|
+
target = realTarget
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const symbols = []
|
|
231
|
+
let filesRead = 0
|
|
232
|
+
let truncated = false
|
|
233
|
+
|
|
234
|
+
/** Parse one file into the accumulator, honouring the caps. */
|
|
235
|
+
async function parseFile(absPath) {
|
|
236
|
+
if (filesRead >= maxFiles) { truncated = true; return }
|
|
237
|
+
let st
|
|
238
|
+
try {
|
|
239
|
+
// lstat (not stat) so a symlink is never followed here. The scoped target
|
|
240
|
+
// is already realpath-confined and walk() skips symlink dirents, so this is
|
|
241
|
+
// defence-in-depth that keeps parseFile symlink-blind for any future caller.
|
|
242
|
+
st = await lstat(absPath)
|
|
243
|
+
} catch { return }
|
|
244
|
+
if (!st.isFile()) return
|
|
245
|
+
if (st.size > maxFileSize) return
|
|
246
|
+
if (!(extname(absPath).toLowerCase() in EXT_LANG)) return
|
|
247
|
+
filesRead++
|
|
248
|
+
let content
|
|
249
|
+
try {
|
|
250
|
+
content = await readFile(absPath, 'utf-8')
|
|
251
|
+
} catch { return }
|
|
252
|
+
const rel = relative(root, absPath).split(sep).join('/')
|
|
253
|
+
for (const s of parseSymbols(content, rel)) {
|
|
254
|
+
if (symbols.length >= maxSymbols) { truncated = true; return }
|
|
255
|
+
symbols.push(s)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Recursively walk a directory. */
|
|
260
|
+
async function walk(dir, depth) {
|
|
261
|
+
if (depth > maxDepth || filesRead >= maxFiles || symbols.length >= maxSymbols) {
|
|
262
|
+
if (filesRead >= maxFiles || symbols.length >= maxSymbols) truncated = true
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
let dirents
|
|
266
|
+
try {
|
|
267
|
+
dirents = await readdir(dir, { withFileTypes: true })
|
|
268
|
+
} catch { return }
|
|
269
|
+
// Stable ordering so output (and tests) are deterministic.
|
|
270
|
+
dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
271
|
+
for (const ent of dirents) {
|
|
272
|
+
if (filesRead >= maxFiles || symbols.length >= maxSymbols) { truncated = true; break }
|
|
273
|
+
const abs = join(dir, ent.name)
|
|
274
|
+
if (ent.isDirectory()) {
|
|
275
|
+
// Skip vendored/build/cache dirs and all dot-directories (config, VCS,
|
|
276
|
+
// tool caches) — noisy and rarely source.
|
|
277
|
+
if (IGNORED_DIRS.has(ent.name) || ent.name.startsWith('.')) continue
|
|
278
|
+
await walk(abs, depth + 1)
|
|
279
|
+
} else if (ent.isFile()) {
|
|
280
|
+
await parseFile(abs)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
let tstat
|
|
286
|
+
try {
|
|
287
|
+
tstat = await stat(target)
|
|
288
|
+
} catch {
|
|
289
|
+
return { symbols, truncated }
|
|
290
|
+
}
|
|
291
|
+
if (tstat.isFile()) {
|
|
292
|
+
await parseFile(target)
|
|
293
|
+
} else if (tstat.isDirectory()) {
|
|
294
|
+
await walk(target, 0)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return { symbols, truncated }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
// Workspace symbol-index cache (#6499)
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
//
|
|
304
|
+
// resolveSymbol and the whole-workspace list_symbols both do a FULL bounded walk
|
|
305
|
+
// on every call — a burst of cmd/ctrl+clicks over a tunnel re-parses the whole
|
|
306
|
+
// tree each time. This short-lived, invalidatable cache holds the full-walk
|
|
307
|
+
// result (`collectWorkspaceSymbols(rootDir)` with no `path`) keyed by the REAL
|
|
308
|
+
// (symlink-resolved) workspace root, so a second lookup within the TTL filters
|
|
309
|
+
// the cached table instead of re-walking. Scoped (`path`-bearing) scans are NOT
|
|
310
|
+
// cached — they are cheap and varied; only the expensive no-path full walk is.
|
|
311
|
+
//
|
|
312
|
+
// Invalidation is TTL-based (a newly-added declaration resolves once the entry
|
|
313
|
+
// expires); `invalidateWorkspaceSymbolIndex()` clears everything for a future
|
|
314
|
+
// file-change signal or test teardown. The cached object is treated as READ-ONLY
|
|
315
|
+
// by every consumer (resolveSymbol reads, the handler serializes) — do not mutate
|
|
316
|
+
// it, or you corrupt the shared entry.
|
|
317
|
+
const DEFAULT_INDEX_TTL_MS = 5000
|
|
318
|
+
const MAX_INDEX_CACHE_ENTRIES = 16
|
|
319
|
+
const _indexCache = new Map() // realpath(root) → { result, expires }
|
|
320
|
+
let _indexHits = 0
|
|
321
|
+
let _indexMisses = 0
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Full-workspace symbol index with a short TTL cache (#6499). Same return shape
|
|
325
|
+
* as `collectWorkspaceSymbols(rootDir)` (no path). Keyed by the realpath of the
|
|
326
|
+
* root so two workspaces never share an entry, and so an in-workspace symlink
|
|
327
|
+
* can't poison another root's key.
|
|
328
|
+
*
|
|
329
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
330
|
+
* @param {object} [opts]
|
|
331
|
+
* @param {number} [opts.ttlMs] Entry lifetime (default 5000ms).
|
|
332
|
+
* @param {number} [opts.now] Injectable clock for deterministic tests.
|
|
333
|
+
* @returns {Promise<{symbols: SymbolEntry[], truncated: boolean}>}
|
|
334
|
+
*/
|
|
335
|
+
export async function getWorkspaceSymbolIndex(rootDir, opts = {}) {
|
|
336
|
+
const { ttlMs = DEFAULT_INDEX_TTL_MS, now = Date.now() } = opts
|
|
337
|
+
// Key by the REAL root — same base collectWorkspaceSymbols confines against. An
|
|
338
|
+
// unresolvable root can't be cached safely; fall back to the (also-guarded,
|
|
339
|
+
// empty-on-error) uncached walk.
|
|
340
|
+
let key
|
|
341
|
+
try {
|
|
342
|
+
key = await realpath(resolve(rootDir))
|
|
343
|
+
} catch {
|
|
344
|
+
return collectWorkspaceSymbols(rootDir)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const hit = _indexCache.get(key)
|
|
348
|
+
if (hit && hit.expires > now) {
|
|
349
|
+
_indexHits++
|
|
350
|
+
return hit.result
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
_indexMisses++
|
|
354
|
+
const result = await collectWorkspaceSymbols(rootDir)
|
|
355
|
+
// Bounded FIFO eviction — the daemon usually has one workspace, but never let a
|
|
356
|
+
// long-lived process accumulate unbounded entries.
|
|
357
|
+
_indexCache.delete(key) // drop any stale entry so re-insert lands as newest
|
|
358
|
+
if (_indexCache.size >= MAX_INDEX_CACHE_ENTRIES) {
|
|
359
|
+
const oldest = _indexCache.keys().next().value
|
|
360
|
+
if (oldest !== undefined) _indexCache.delete(oldest)
|
|
361
|
+
}
|
|
362
|
+
_indexCache.set(key, { result, expires: now + ttlMs })
|
|
363
|
+
return result
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Clear the workspace symbol-index cache (#6499) — every entry and the hit/miss
|
|
368
|
+
* counters. No-arg / coarse by design: a hook for a future file-change signal or
|
|
369
|
+
* a test teardown. TTL expiry is the routine invalidation path.
|
|
370
|
+
*/
|
|
371
|
+
export function invalidateWorkspaceSymbolIndex() {
|
|
372
|
+
_indexCache.clear()
|
|
373
|
+
_indexHits = 0
|
|
374
|
+
_indexMisses = 0
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Cache hit/miss/size counters (#6499) — for tests and diagnostics. */
|
|
378
|
+
export function _symbolIndexCacheStats() {
|
|
379
|
+
return { hits: _indexHits, misses: _indexMisses, size: _indexCache.size }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Resolve a symbol NAME to a single declaration location — the backbone of
|
|
384
|
+
* go-to-definition (#6475, epic #6469). Reuses collectWorkspaceSymbols so the
|
|
385
|
+
* same realpath confinement + bounded walk apply, filters the table to
|
|
386
|
+
* declarations whose name matches exactly, and ranks the candidates:
|
|
387
|
+
* - an exported declaration outranks a local one (+2), so a cmd/ctrl+click on
|
|
388
|
+
* an imported symbol lands on its public definition, and
|
|
389
|
+
* - a declaration in the originating file outranks one elsewhere (+1), so a
|
|
390
|
+
* click on a locally-declared helper resolves in place.
|
|
391
|
+
* Regex-parsed, so ~80% accurate with zero new deps — a genuine miss (name not
|
|
392
|
+
* found, or only a usage exists) returns null and the caller reports a graceful
|
|
393
|
+
* 'not found'. On a score tie the FIRST (walk-order-earliest, deterministic)
|
|
394
|
+
* candidate wins.
|
|
395
|
+
*
|
|
396
|
+
* @param {string} rootDir Absolute workspace root (session cwd).
|
|
397
|
+
* @param {string} symbolName Exact declared identifier to resolve.
|
|
398
|
+
* @param {object} [opts]
|
|
399
|
+
* @param {string|null} [opts.fromFile] Workspace-relative POSIX path the click
|
|
400
|
+
* came from; used only to break ranking ties.
|
|
401
|
+
* @returns {Promise<{file: string, line: number}|null>}
|
|
402
|
+
*/
|
|
403
|
+
export async function resolveSymbol(rootDir, symbolName, opts = {}) {
|
|
404
|
+
const name = typeof symbolName === 'string' ? symbolName.trim() : ''
|
|
405
|
+
if (!name) return null
|
|
406
|
+
const { fromFile = null } = opts
|
|
407
|
+
// Route through the TTL cache (#6499) so a burst of clicks doesn't re-walk the
|
|
408
|
+
// tree each time. Forward ONLY the cache knobs explicitly (not the whole opts
|
|
409
|
+
// bag) — `fromFile` is a resolveSymbol-only ranking hint the index ignores, so
|
|
410
|
+
// passing it through would be silent coupling.
|
|
411
|
+
const { symbols } = await getWorkspaceSymbolIndex(rootDir, { ttlMs: opts.ttlMs, now: opts.now })
|
|
412
|
+
let best = null
|
|
413
|
+
let bestScore = -1
|
|
414
|
+
for (const s of symbols) {
|
|
415
|
+
if (s.name !== name) continue
|
|
416
|
+
const score = (s.exported ? 2 : 0) + (fromFile && s.file === fromFile ? 1 : 0)
|
|
417
|
+
if (score > bestScore) {
|
|
418
|
+
best = s
|
|
419
|
+
bestScore = score
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return best ? { file: best.file, line: best.line } : null
|
|
423
|
+
}
|