mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-22 00:05:51 +00:00
* fix: harden ACP communication boundaries Harden ACP communication boundaries Remote ACP sessions now cannot widen permission mode through untrusted metadata or client payloads. WebSocket ACP ingress measures payloads by bytes before binary decode, and prompt queue handoff keeps exactly one prompt active while queued prompts are drained FIFO. Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent Constraint: WebSocket payload limits must be byte-based and checked before binary decode Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing Confidence: high Scope-risk: moderate Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build Not-tested: Manual live ACP/RCS session against an external client * fix: restore repository verification gates Keep the full repository test, typecheck, build, and Biome lint gates usable after the ACP fix pass. This commit is intentionally separate from the ACP behavior change: it fixes Windows-safe Langfuse home redaction, removes stale lint suppressions, resolves Biome warning/info diagnostics, and keeps env expansion tests explicit without template-placeholder lint noise. Constraint: The project completion contract requires full typecheck, lint, test, and build evidence Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims Confidence: high Scope-risk: narrow Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build Not-tested: Manual Langfuse export against a real external Langfuse service * fix: harden ACP failure boundaries after review Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter. Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed Confidence: high Scope-risk: moderate Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bunx tsc --noEmit Tested: bunx biome lint src/ packages/acp-link/src/ Tested: bun run test:all Tested: bun run build Not-tested: Manual end-to-end ACP client session over a real editor WebSocket * fix: prevent ACP coverage runs from seeing partial mocks GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module. This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure. Constraint: bun:test mock.module is process-global inside a worker. Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution. Rejected: Keep per-file helper copies | duplication would let restore semantics drift again. Confidence: high Scope-risk: narrow Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests. Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov Tested: bunx tsc --noEmit Tested: bun run lint Tested: git diff --check Not-tested: Linux runner directly before push * fix: normalize ACP bypass requests without warning noise The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path. This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order. Constraint: CI output should not contain expected warning noise for covered policy branches. Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch. Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site. Confidence: high Scope-risk: narrow Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass. Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0 Tested: bun run test:all Tested: bun run lint Tested: bunx tsc --noEmit Tested: git diff --check * fix: harden ACP bypass and CI warning gates ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state. Constraint: CI must stay warning-clean without hiding real ACP permission failures Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path Confidence: high Scope-risk: moderate Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts Tested: bun run test:all Tested: bun run lint Tested: bun run build:vite with zero warning matches Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches Not-tested: GitHub Actions result after this push * fix: remove remaining CI warning noise The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics. Constraint: Do not use shell log filtering to hide warnings after they happen Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find Confidence: high Scope-risk: narrow Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects Tested: bunx tsc --noEmit --pretty false Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts Tested: bun run build:vite with zero warning matches Not-tested: GitHub Actions result after this push * fix: reject unauthorized ACP bypass and harden CI actions ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings. CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token. Constraint: Must not hide warnings with test isolation or log filtering Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope Confidence: high Scope-risk: moderate Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bun run test:all Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0 Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR * fix: resolve dependency audit findings precisely Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified. Constraint: no audit ignores or warning suppression Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution Confidence: high Scope-risk: moderate Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: keep ACP auth tokens out of URLs Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change. Constraint: token must not be embedded in the URL Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs Confidence: high Scope-risk: moderate Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code Tested: targeted ACP/RCS transport tests Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: normalize WebFetch request headers Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline. Constraint: preserve header semantics without widening the fetch surface Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites Confidence: high Scope-risk: narrow Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically Tested: targeted WebFetch header tests Not-tested: unrelated fetch backend behavior beyond header normalization * fix: harden ACP remote auth surfaces Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist. Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string. Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data. Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries. Confidence: high Scope-risk: moderate Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>. Tested: bunx tsc --noEmit --pretty false Tested: bun run typecheck in packages/remote-control-server Tested: bun run build in packages/acp-link Tested: bun run lint Tested: bun audit Tested: focused RCS/acp-link/web tests, 160 pass Tested: Edge headless browser WebSocket subprotocol handshake Tested: bun run test:all, 3669 pass Tested: bun run build:vite Tested: bun run build Not-tested: Manual end-to-end relay with a live external ACP agent * fix: resolve CI dependency override lookup The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating. Constraint: Do not add a new root dependency for a transitive smoke test. Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync. Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface. Confidence: high Scope-risk: narrow Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting. Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check --------- Co-authored-by: unraid <local@unraid.local>
413 lines
13 KiB
TypeScript
413 lines
13 KiB
TypeScript
/**
|
||
* Pure-TypeScript port of vendor/file-index-src (Rust NAPI module).
|
||
*
|
||
* The native module wraps nucleo (https://github.com/helix-editor/nucleo) for
|
||
* high-performance fuzzy file searching. This port reimplements the same API
|
||
* and scoring behavior without native dependencies.
|
||
*
|
||
* Key API:
|
||
* new FileIndex()
|
||
* .loadFromFileList(fileList: string[]): void — dedupe + index paths
|
||
* .search(query: string, limit: number): SearchResult[]
|
||
*
|
||
* Score semantics: lower = better. Score is position-in-results / result-count,
|
||
* so the best match is 0.0. Paths containing "test" get a 1.05× penalty (capped
|
||
* at 1.0) so non-test files rank slightly higher.
|
||
*/
|
||
|
||
export type SearchResult = {
|
||
path: string
|
||
score: number
|
||
}
|
||
|
||
// nucleo-style scoring constants (approximating fzf-v2 / nucleo bonuses)
|
||
const SCORE_MATCH = 16
|
||
const BONUS_BOUNDARY = 8
|
||
const BONUS_CAMEL = 6
|
||
const BONUS_CONSECUTIVE = 4
|
||
const BONUS_FIRST_CHAR = 8
|
||
const PENALTY_GAP_START = 3
|
||
const PENALTY_GAP_EXTENSION = 1
|
||
|
||
const TOP_LEVEL_CACHE_LIMIT = 100
|
||
const MAX_QUERY_LEN = 64
|
||
// Yield to event loop after this many ms of sync work. Chunk sizes are
|
||
// time-based (not count-based) so slow machines get smaller chunks and
|
||
// stay responsive — 5k paths is ~2ms on M-series but could be 15ms+ on
|
||
// older Windows hardware.
|
||
const CHUNK_MS = 4
|
||
|
||
// Reusable buffer: records where each needle char matched during the indexOf scan
|
||
const posBuf = new Int32Array(MAX_QUERY_LEN)
|
||
|
||
export class FileIndex {
|
||
private paths: string[] = []
|
||
private lowerPaths: string[] = []
|
||
private charBits: Int32Array = new Int32Array(0)
|
||
private pathLens: Uint16Array = new Uint16Array(0)
|
||
private topLevelCache: SearchResult[] | null = null
|
||
// During async build, tracks how many paths have bitmap/lowerPath filled.
|
||
// search() uses this to search the ready prefix while build continues.
|
||
// biome-ignore lint/correctness/noUnusedPrivateClassMembers: used via destructuring in search()
|
||
private readyCount = 0
|
||
|
||
/**
|
||
* Load paths from an array of strings.
|
||
* This is the main way to populate the index — ripgrep collects files, we just search them.
|
||
* Automatically deduplicates paths.
|
||
*/
|
||
loadFromFileList(fileList: string[]): void {
|
||
// Deduplicate and filter empty strings (matches Rust HashSet behavior)
|
||
const seen = new Set<string>()
|
||
const paths: string[] = []
|
||
for (const line of fileList) {
|
||
if (line.length > 0 && !seen.has(line)) {
|
||
seen.add(line)
|
||
paths.push(line)
|
||
}
|
||
}
|
||
|
||
this.buildIndex(paths)
|
||
}
|
||
|
||
/**
|
||
* Async variant: yields to the event loop every ~8–12k paths so large
|
||
* indexes (270k+ files) don't block the main thread for >10ms at a time.
|
||
* Identical result to loadFromFileList.
|
||
*
|
||
* Returns { queryable, done }:
|
||
* - queryable: resolves as soon as the first chunk is indexed (search
|
||
* returns partial results). For a 270k-path list this is ~5–10ms of
|
||
* sync work after the paths array is available.
|
||
* - done: resolves when the entire index is built.
|
||
*/
|
||
loadFromFileListAsync(fileList: string[]): {
|
||
queryable: Promise<void>
|
||
done: Promise<void>
|
||
} {
|
||
let markQueryable: () => void = () => {}
|
||
const queryable = new Promise<void>(resolve => {
|
||
markQueryable = resolve
|
||
})
|
||
const done = this.buildAsync(fileList, markQueryable)
|
||
return { queryable, done }
|
||
}
|
||
|
||
private async buildAsync(
|
||
fileList: string[],
|
||
markQueryable: () => void,
|
||
): Promise<void> {
|
||
const seen = new Set<string>()
|
||
const paths: string[] = []
|
||
let chunkStart = performance.now()
|
||
for (let i = 0; i < fileList.length; i++) {
|
||
const line = fileList[i]!
|
||
if (line.length > 0 && !seen.has(line)) {
|
||
seen.add(line)
|
||
paths.push(line)
|
||
}
|
||
// Check every 256 iterations to amortize performance.now() overhead
|
||
if ((i & 0xff) === 0xff && performance.now() - chunkStart > CHUNK_MS) {
|
||
await yieldToEventLoop()
|
||
chunkStart = performance.now()
|
||
}
|
||
}
|
||
|
||
this.resetArrays(paths)
|
||
|
||
chunkStart = performance.now()
|
||
let firstChunk = true
|
||
for (let i = 0; i < paths.length; i++) {
|
||
this.indexPath(i)
|
||
if ((i & 0xff) === 0xff && performance.now() - chunkStart > CHUNK_MS) {
|
||
this.readyCount = i + 1
|
||
if (firstChunk) {
|
||
markQueryable()
|
||
firstChunk = false
|
||
}
|
||
await yieldToEventLoop()
|
||
chunkStart = performance.now()
|
||
}
|
||
}
|
||
this.readyCount = paths.length
|
||
markQueryable()
|
||
}
|
||
|
||
private buildIndex(paths: string[]): void {
|
||
this.resetArrays(paths)
|
||
for (let i = 0; i < paths.length; i++) {
|
||
this.indexPath(i)
|
||
}
|
||
this.readyCount = paths.length
|
||
}
|
||
|
||
private resetArrays(paths: string[]): void {
|
||
const n = paths.length
|
||
this.paths = paths
|
||
this.lowerPaths = new Array(n)
|
||
this.charBits = new Int32Array(n)
|
||
this.pathLens = new Uint16Array(n)
|
||
this.readyCount = 0
|
||
this.topLevelCache = computeTopLevelEntries(paths, TOP_LEVEL_CACHE_LIMIT)
|
||
}
|
||
|
||
// Precompute: lowercase, a–z bitmap, length. Bitmap gives O(1) rejection
|
||
// of paths missing any needle letter (89% survival for broad queries like
|
||
// "test" → still a 10%+ free win; 90%+ rejection for rare chars).
|
||
private indexPath(i: number): void {
|
||
const lp = this.paths[i]!.toLowerCase()
|
||
this.lowerPaths[i] = lp
|
||
const len = lp.length
|
||
this.pathLens[i] = len
|
||
let bits = 0
|
||
for (let j = 0; j < len; j++) {
|
||
const c = lp.charCodeAt(j)
|
||
if (c >= 97 && c <= 122) bits |= 1 << (c - 97)
|
||
}
|
||
this.charBits[i] = bits
|
||
}
|
||
|
||
/**
|
||
* Search for files matching the query using fuzzy matching.
|
||
* Returns top N results sorted by match score.
|
||
*/
|
||
search(query: string, limit: number): SearchResult[] {
|
||
if (limit <= 0) return []
|
||
if (query.length === 0) {
|
||
if (this.topLevelCache) {
|
||
return this.topLevelCache.slice(0, limit)
|
||
}
|
||
return []
|
||
}
|
||
|
||
// Smart case: lowercase query → case-insensitive; any uppercase → case-sensitive
|
||
const caseSensitive = query !== query.toLowerCase()
|
||
const needle = caseSensitive ? query : query.toLowerCase()
|
||
const nLen = Math.min(needle.length, MAX_QUERY_LEN)
|
||
const needleChars: string[] = new Array(nLen)
|
||
let needleBitmap = 0
|
||
for (let j = 0; j < nLen; j++) {
|
||
const ch = needle.charAt(j)
|
||
needleChars[j] = ch
|
||
const cc = ch.charCodeAt(0)
|
||
if (cc >= 97 && cc <= 122) needleBitmap |= 1 << (cc - 97)
|
||
}
|
||
|
||
// Upper bound on score assuming every match gets the max boundary bonus.
|
||
// Used to reject paths whose gap penalties alone make them unable to beat
|
||
// the current top-k threshold, before the charCodeAt-heavy boundary pass.
|
||
const scoreCeiling =
|
||
nLen * (SCORE_MATCH + BONUS_BOUNDARY) + BONUS_FIRST_CHAR + 32
|
||
|
||
// Top-k: maintain a sorted-ascending array of the best `limit` matches.
|
||
// Avoids O(n log n) sort of all matches when we only need `limit` of them.
|
||
const topK: { path: string; fuzzScore: number }[] = []
|
||
let threshold = -Infinity
|
||
|
||
const { paths, lowerPaths, charBits, pathLens, readyCount } = this
|
||
|
||
for (let i = 0; i < readyCount; i++) {
|
||
// O(1) bitmap reject: path must contain every letter in the needle
|
||
if ((charBits[i]! & needleBitmap) !== needleBitmap) continue
|
||
|
||
const haystack = caseSensitive ? paths[i]! : lowerPaths[i]!
|
||
|
||
// Greedy-leftmost indexOf gives fast but suboptimal positions when the
|
||
// first needle char appears early (e.g. 's' in "src/") while the real
|
||
// match lives deeper (e.g. "settings/"). We score from multiple start
|
||
// positions — the leftmost hit plus every word-boundary occurrence of
|
||
// needle[0] — and keep the best. Typical paths have 2–4 boundary starts,
|
||
// so the overhead is minimal.
|
||
|
||
// Collect candidate start positions for needle[0]
|
||
const firstChar = needleChars[0]!
|
||
let startCount = 0
|
||
// startPositions is stack-allocated (reused array would add complexity
|
||
// for marginal gain; paths rarely have >8 boundary starts)
|
||
const startPositions: number[] = []
|
||
|
||
// Always try the leftmost occurrence
|
||
const firstPos = haystack.indexOf(firstChar)
|
||
if (firstPos === -1) continue
|
||
startPositions[startCount++] = firstPos
|
||
|
||
// Also try every word-boundary position where needle[0] occurs
|
||
for (let bp = firstPos + 1; bp < haystack.length; bp++) {
|
||
if (haystack.charCodeAt(bp) !== firstChar.charCodeAt(0)) continue
|
||
// Check if this position is at a word boundary
|
||
const prevCode = haystack.charCodeAt(bp - 1)
|
||
if (
|
||
prevCode === 47 || // /
|
||
prevCode === 92 || // \
|
||
prevCode === 45 || // -
|
||
prevCode === 95 || // _
|
||
prevCode === 46 || // .
|
||
prevCode === 32 // space
|
||
) {
|
||
startPositions[startCount++] = bp
|
||
}
|
||
}
|
||
|
||
const originalPath = paths[i]!
|
||
const hLen = pathLens[i]!
|
||
const lengthBonus = Math.max(0, 32 - (hLen >> 2))
|
||
let bestScore = -Infinity
|
||
|
||
for (let si = 0; si < startCount; si++) {
|
||
posBuf[0] = startPositions[si]!
|
||
let gapPenalty = 0
|
||
let consecBonus = 0
|
||
let prev = posBuf[0]!
|
||
let matched = true
|
||
for (let j = 1; j < nLen; j++) {
|
||
const pos = haystack.indexOf(needleChars[j]!, prev + 1)
|
||
if (pos === -1) { matched = false; break }
|
||
posBuf[j] = pos
|
||
const gap = pos - prev - 1
|
||
if (gap === 0) consecBonus += BONUS_CONSECUTIVE
|
||
else gapPenalty += PENALTY_GAP_START + gap * PENALTY_GAP_EXTENSION
|
||
prev = pos
|
||
}
|
||
if (!matched) continue
|
||
|
||
// Gap-bound reject for this start position
|
||
if (
|
||
topK.length === limit &&
|
||
scoreCeiling + consecBonus - gapPenalty + lengthBonus <= threshold
|
||
) {
|
||
continue
|
||
}
|
||
|
||
// Boundary/camelCase scoring
|
||
let score = nLen * SCORE_MATCH + consecBonus - gapPenalty
|
||
score += scoreBonusAt(originalPath, posBuf[0]!, true)
|
||
for (let j = 1; j < nLen; j++) {
|
||
score += scoreBonusAt(originalPath, posBuf[j]!, false)
|
||
}
|
||
score += lengthBonus
|
||
|
||
if (score > bestScore) bestScore = score
|
||
}
|
||
|
||
if (bestScore === -Infinity) continue
|
||
const score = bestScore
|
||
|
||
if (topK.length < limit) {
|
||
topK.push({ path: originalPath, fuzzScore: score })
|
||
if (topK.length === limit) {
|
||
topK.sort((a, b) => a.fuzzScore - b.fuzzScore)
|
||
threshold = topK[0]!.fuzzScore
|
||
}
|
||
} else if (score > threshold) {
|
||
let lo = 0
|
||
let hi = topK.length
|
||
while (lo < hi) {
|
||
const mid = (lo + hi) >> 1
|
||
if (topK[mid]!.fuzzScore < score) lo = mid + 1
|
||
else hi = mid
|
||
}
|
||
topK.splice(lo, 0, { path: originalPath, fuzzScore: score })
|
||
topK.shift()
|
||
threshold = topK[0]!.fuzzScore
|
||
}
|
||
}
|
||
|
||
// topK is ascending; reverse to descending (best first)
|
||
topK.sort((a, b) => b.fuzzScore - a.fuzzScore)
|
||
|
||
const matchCount = topK.length
|
||
const denom = Math.max(matchCount, 1)
|
||
const results: SearchResult[] = new Array(matchCount)
|
||
|
||
for (let i = 0; i < matchCount; i++) {
|
||
const path = topK[i]!.path
|
||
const positionScore = i / denom
|
||
const finalScore = path.includes('test')
|
||
? Math.min(positionScore * 1.05, 1.0)
|
||
: positionScore
|
||
results[i] = { path, score: finalScore }
|
||
}
|
||
|
||
return results
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Boundary/camelCase bonus for a match at position `pos` in the original-case
|
||
* path. `first` enables the start-of-string bonus (only for needle[0]).
|
||
*/
|
||
function scoreBonusAt(path: string, pos: number, first: boolean): number {
|
||
if (pos === 0) return first ? BONUS_FIRST_CHAR : 0
|
||
const prevCh = path.charCodeAt(pos - 1)
|
||
if (isBoundary(prevCh)) return BONUS_BOUNDARY
|
||
if (isLower(prevCh) && isUpper(path.charCodeAt(pos))) return BONUS_CAMEL
|
||
return 0
|
||
}
|
||
|
||
function isBoundary(code: number): boolean {
|
||
// / \ - _ . space
|
||
return (
|
||
code === 47 || // /
|
||
code === 92 || // \
|
||
code === 45 || // -
|
||
code === 95 || // _
|
||
code === 46 || // .
|
||
code === 32 // space
|
||
)
|
||
}
|
||
|
||
function isLower(code: number): boolean {
|
||
return code >= 97 && code <= 122
|
||
}
|
||
|
||
function isUpper(code: number): boolean {
|
||
return code >= 65 && code <= 90
|
||
}
|
||
|
||
export function yieldToEventLoop(): Promise<void> {
|
||
return new Promise(resolve => setImmediate(resolve))
|
||
}
|
||
|
||
export { CHUNK_MS }
|
||
|
||
/**
|
||
* Extract unique top-level path segments, sorted by (length asc, then alpha asc).
|
||
* Handles both Unix (/) and Windows (\) path separators.
|
||
* Mirrors FileIndex::compute_top_level_entries in lib.rs.
|
||
*/
|
||
function computeTopLevelEntries(
|
||
paths: string[],
|
||
limit: number,
|
||
): SearchResult[] {
|
||
const topLevel = new Set<string>()
|
||
|
||
for (const p of paths) {
|
||
// Split on first / or \ separator
|
||
let end = p.length
|
||
for (let i = 0; i < p.length; i++) {
|
||
const c = p.charCodeAt(i)
|
||
if (c === 47 || c === 92) {
|
||
end = i
|
||
break
|
||
}
|
||
}
|
||
const segment = p.slice(0, end)
|
||
if (segment.length > 0) {
|
||
topLevel.add(segment)
|
||
if (topLevel.size >= limit) break
|
||
}
|
||
}
|
||
|
||
const sorted = Array.from(topLevel)
|
||
sorted.sort((a, b) => {
|
||
const lenDiff = a.length - b.length
|
||
if (lenDiff !== 0) return lenDiff
|
||
return a < b ? -1 : a > b ? 1 : 0
|
||
})
|
||
|
||
return sorted.slice(0, limit).map(path => ({ path, score: 0.0 }))
|
||
}
|
||
|
||
export default FileIndex
|
||
export type { FileIndex as FileIndexType }
|