docuvia 1.3.2 → 1.4.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/dist/ast-worker.js +1 -1
- package/dist/ast-worker.js.map +1 -1
- package/dist/{chunk-KZYHFZZS.js → chunk-7IDGG5WR.js} +2 -2
- package/dist/{chunk-EUTMBLVT.js → chunk-UWGOBCTB.js} +2 -2
- package/dist/{chunk-BR2RIZZU.js → chunk-WBNMCSX3.js} +2 -2
- package/dist/{chunk-3WFKL5P6.js → chunk-XIDGZQW2.js} +5 -5
- package/dist/chunk-XIDGZQW2.js.map +1 -0
- package/dist/cli.js +135 -135
- package/dist/cli.js.map +1 -1
- package/dist/fs-utils-4BUVEG2U.js +3 -0
- package/dist/{init-templates-VHTM5VWK.js → init-templates-Y4ZI27FQ.js} +2 -2
- package/dist/migrations/0012_ast_call_sites_callee_fields.sql +28 -0
- package/package.json +1 -1
- package/dist/chunk-3WFKL5P6.js.map +0 -1
- package/dist/fs-utils-4AOXK4SJ.js +0 -3
- /package/dist/{chunk-KZYHFZZS.js.map → chunk-7IDGG5WR.js.map} +0 -0
- /package/dist/{chunk-EUTMBLVT.js.map → chunk-UWGOBCTB.js.map} +0 -0
- /package/dist/{chunk-BR2RIZZU.js.map → chunk-WBNMCSX3.js.map} +0 -0
- /package/dist/{fs-utils-4AOXK4SJ.js.map → fs-utils-4BUVEG2U.js.map} +0 -0
- /package/dist/{init-templates-VHTM5VWK.js.map → init-templates-Y4ZI27FQ.js.map} +0 -0
package/dist/ast-worker.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{c,d as a,e as
|
|
2
|
+
import{c,d as a,e as y,f as _,h as T}from"./chunk-WBNMCSX3.js";import{ca as P,d as L,fa as E}from"./chunk-XIDGZQW2.js";import"./chunk-KVOCOCYJ.js";import{parentPort as N}from"worker_threads";import{Parser as w,Language as U}from"web-tree-sitter";import*as O from"path";import*as D from"fs";import{createHash as H}from"crypto";function h(e){return H(P).update(e.text).digest("hex")}var x=new L(e=>N?.postMessage(e));process.on("uncaughtException",e=>{x.error(a.WORKER_UNCAUGHT_EXCEPTION,{error:e instanceof Error?e.message:String(e)})});process.on("unhandledRejection",e=>{x.error(a.WORKER_UNHANDLED_REJECTION,{error:e instanceof Error?e.message:String(e)})});var S=!1,b=null;function G(){return b??=_(),b}var C=new Map;function K(e){let t=C.get(e);return t||(t=U.load(e),C.set(e,t)),t}function Y(e){let t=[],n=e.matchAll(/import\s+{([^}]+)}\s+from\s+['"]([^'"]+)['"]/g);for(let r of n)t.push({localName:r[1].trim(),originalName:r[1].trim(),modulePath:r[2]});return t}function F(e){return e.childForFieldName("name")?.text||e.descendantsOfType("identifier")[0]?.text||a.ANONYMOUS_NAME}function Q(e){let t=e.childForFieldName("declarator")?.childForFieldName("declarator");if(t)return t.type===c.QUALIFIED_IDENTIFIER?t.childForFieldName("name")?.text??a.ANONYMOUS_NAME:t.text}function V(e){let t=e.childForFieldName("name");if(t)return t.text;let n=Q(e);if(n)return n;let r=new Set([c.VARIABLE_DECLARATOR,c.ASSIGNMENT_EXPRESSION,c.PAIR,c.PUBLIC_FIELD_DEFINITION]),o=e.parent;for(;o&&o.type!==c.ARGUMENTS;){if(r.has(o.type)){let s=o.childForFieldName("name")||o.childForFieldName("key")||o.childForFieldName("left");if(s)return s.text}o=o.parent}return a.ANONYMOUS_NAME}function W(e){return e.childForFieldName("function")||e.childForFieldName("expression")||e.childForFieldName("type")||e.childForFieldName("name")||e.childForFieldName("method")||e}function J(e){let t=W(e),n=t.namedChildren,r=n[n.length-1],o=n.length>=2?n[n.length-2]:void 0;if(!r||!o)return{targetFunction:f(t.text),calleeName:t.text,calleeKind:"bare"};if(!j.has(r.type))return{targetFunction:f(t.text),calleeKind:"computed"};let s=r.text,i=o.text;return i.includes("(")?{targetFunction:f(t.text),calleeName:s,receiverText:i,calleeKind:"arg-chain"}:{targetFunction:f(t.text),calleeName:s,receiverText:i,calleeKind:i==="this"||i==="super"?"this":"member"}}function f(e){return e.replace(/\s+/g,"")}var j=new Set(["identifier","property_identifier","field_identifier","shorthand_property_identifier","attribute"]);function B(e){return((e.childForFieldName("property")||e.childForFieldName("field")||e.childForFieldName("attribute")||e.childForFieldName("name")||e.childForFieldName("method"))??e).startPosition}function g(e,t){let n=e.parent;for(;n;){if(t.has(n.id))return F(n);n=n.parent}return a.ANONYMOUS_NAME}function v(e){return e.type===c.TYPE_IDENTIFIER?e.text:e.descendantsOfType(c.TYPE_IDENTIFIER)[0]?.text}function X(e){let t=e.parent;for(;t;){if(t.type===c.IMPL_ITEM){let n=t.childForFieldName("type");return n?v(n):void 0}t=t.parent}}function z(e){let n=e.childForFieldName("receiver")?.namedChild(0)?.childForFieldName("type");return n?v(n):void 0}function Z(e){let n=e.childForFieldName("declarator")?.childForFieldName("declarator");if(n?.type!==c.QUALIFIED_IDENTIFIER)return;let r=n.childForFieldName("scope");if(r)return r.type===c.QUALIFIED_IDENTIFIER?r.childForFieldName("name")?.text:r.text}function $(e){return X(e)??z(e)??Z(e)}function q(e,t,n){let r=t.extractClasses(e.rootNode);for(let o of r)n.push({name:F(o),startLine:o.startPosition.row,endLine:o.endPosition.row,methods:[],contentHash:h(o)});return r}var ee=new Set(["arrow_function","function_expression"]);function te(e,t,n){let r=t.extractVariables?.(e.rootNode)??[];for(let o of r){let s=o.childForFieldName("value");s&&ee.has(s.type)||n.push({name:F(o),startLine:o.startPosition.row,endLine:o.endPosition.row,contentHash:h(o)})}return r}function ne(e,t,n,r){let o=new Set(r.map(i=>i.id)),s=t.extractFunctions(e.rootNode);for(let i of s){let d=g(i,o),l=d===a.ANONYMOUS_NAME?$(i):d;n.push({name:V(i),startLine:i.startPosition.row,endLine:i.endPosition.row,contentHash:h(i),containerName:l})}return s}function re(e,t,n,r){let o=new Set(n.map(i=>i.id)),s=t.extractCalls(e.rootNode);for(let i of s){if(r.length>=1e3)break;let d=B(i),l=J(i);r.push({sourceFunction:g(i,o),targetFunction:l.targetFunction,startLine:d.row,startColumn:d.column,calleeName:l.calleeName,receiverText:l.receiverText,calleeKind:l.calleeKind})}}function oe(e,t,n,r){if(!t.extractImplements)return;let o=new Set(n.map(s=>s.id));for(let s of t.extractImplements(e.rootNode))r.push({sourceClass:g(s,o),targetInterface:s.text})}function se(e,t,n,r){if(!t.extractExtends)return;let o=new Set(n.map(s=>s.id));for(let s of t.extractExtends(e.rootNode))r.push({sourceClass:g(s,o),targetClass:s.text})}var ie=new Set([E.TYPESCRIPT,E.JAVASCRIPT]),ae="Worker",ce="path",le="resolve",de="join",ue="__dirname";function me(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("function");if(!t||t.type!=="member_expression")return!1;let n=t.childForFieldName("object")?.text,r=t.childForFieldName("property")?.text;return n===ce&&(r===le||r===de)}function ge(e){let t=e.childForFieldName("arguments");return!t||!t.namedChildren.some(o=>o?.type==="identifier"&&o.text===ue)?void 0:t.descendantsOfType("string")[0]?.text.replace(/['"]/g,"")}function pe(e,t){for(let n of e.rootNode.descendantsOfType(c.ASSIGNMENT_EXPRESSION)){if(!n)continue;let r=n.childForFieldName("left"),o=n.childForFieldName("right");if(r?.text!==t||!o||!me(o))continue;let s=ge(o);if(s)return s}}function fe(e,t){if(t.type==="string")return t.text.replace(/['"]/g,"");if(t.type==="identifier"||t.type==="member_expression")return pe(e,t.text)}function Ne(e,t,n,r){if(!ie.has(t))return;let o=new Set(n.map(s=>s.id));for(let s of e.rootNode.descendantsOfType("new_expression")){if(!s||s.childForFieldName("constructor")?.text!==ae)continue;let l=s.childForFieldName("arguments")?.namedChildren.find(p=>p!==null);if(!l)continue;let m=fe(e,l);m&&r.push({sourceFunction:g(s,o),targetPath:m})}}function Ee(e,t,n){let r=[],o=[],s=[],i=[],d=[],l=[],m=[],p=[],A=[],I=[];if(e){r.push(a.parsedViaTreeSitter(e.rootNode.childCount));try{let u=q(e,t,d),R=ne(e,t,i,u),M=t.extractImports(e.rootNode);o.push(...y(M)),te(e,t,l),re(e,t,R,m),oe(e,t,u,p),se(e,t,u,A),Ne(e,n,R,I),r.push(a.QUERIED_VIA_LANGUAGE_PROVIDER)}catch(u){r.push(a.providerQueryFailed(u instanceof Error?u.message:String(u)))}}return{imports:o,exports:s,functions:i,classes:d,variables:l,calls:m,implements:p,extends:A,workerSpawns:I,decisions:r}}function he(e,t){for(let n of e.drainQueryCompileFailures?.()??[])x.error(a.QUERY_COMPILE_FAILED,{language:t,kind:n.kind,pattern:n.pattern,message:n.message})}function xe(e,t,n,r){let o=new w;o.setLanguage(n),t.initQueries?.(n),he(t,r);let s=o.parse(e),i=Ee(s,t,r);return s&&s.delete(),o.delete(),i}async function Fe(e){S||(await w.init(),S=!0);let t=await G(),n=O.extname(e.filePath),r=t.getProviderForExtension(n);if(!r)return{taskId:e.taskId,success:!0,data:{imports:[],exports:[],functions:[],classes:[],calls:[],decisions:[a.noLanguageProviderForExtension(n)]}};let{wasmPath:o,attemptedPaths:s}=T(r.wasm_file);if(!D.existsSync(o))return{taskId:e.taskId,success:!0,data:{imports:Y(e.code),exports:[],functions:[],classes:[],calls:[],decisions:[a.wasmNotFound(e.language,s.join(", "))]}};let i=await K(o),d=xe(e.code,r,i,e.language);return{taskId:e.taskId,success:!0,data:d}}N?.on("message",async e=>{try{let t=await Fe(e);N?.postMessage(t)}catch(t){N?.postMessage({taskId:e.taskId,success:!1,error:t.stack||String(t)})}});export{Fe as buildParseResponse,ne as collectFunctionNodes,Ne as collectWorkerSpawns,J as getCalleeEvidence,he as reportQueryCompileFailures,V as resolveCallableName,T as resolveWasmPath};
|
|
3
3
|
//# sourceMappingURL=ast-worker.js.map
|
package/dist/ast-worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../lib/core/src/ast/ast-worker.ts"],"sourcesContent":["import { parentPort } from \"worker_threads\";\nimport { Parser, Language, type Node, type Tree } from \"web-tree-sitter\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport { createHash } from \"crypto\";\nimport { resolveWasmPath } from \"./resolve-wasm-path.js\";\nimport type { LanguageProvider, LanguageRegistry } from \"@workspace/ast-core\";\nimport {\n parseImportDescriptors,\n loadDefaultRegistry,\n} from \"@workspace/ast-core\";\nimport {\n ENCODING_HEX,\n HASH_ALGO_SHA256,\n IpcLoggerClient,\n SUPPORTED_LANGUAGES,\n type AstExportKind,\n type SupportedLanguage,\n} from \"@workspace/contracts\";\nimport { AstMessages, AstNodeTypes } from \"./ast-constants.js\";\n\n/**\n * Symbol-level feature hash (STOR-005): a hash of the AST node's own exact source span\n * (`node.text`), independent of the containing file's blob hash. Lets a single-symbol edit\n * produce a one-line JSONL diff for that symbol without touching its untouched siblings' hashes.\n *\n * The algorithm/digest constants come from `@workspace/contracts` (issue #211) so the worker's\n * hashes can never drift from the main thread's (`ast-worker-pool.ts`, `file-discovery.service.ts`)\n * or `lib/schema`'s. Package-name imports resolve through node_modules and work fine inside a\n * `worker_threads` Worker (as the existing contracts/ast-core imports above prove) — only bare\n * relative `.js`-to-`.ts` sibling imports needed a tsx resolve hook that doesn't propagate into\n * workers, and even that limitation is moot in dist/ where a fully-compiled worker ships.\n */\nfunction symbolContentHash(node: Node): string {\n return createHash(HASH_ALGO_SHA256).update(node.text).digest(ENCODING_HEX);\n}\n\n/**\n * Worker threads share the host process's stdout/stderr by default, so `console.*` here would\n * corrupt MCP's stdio JSON-RPC stream exactly like it would in the main thread (see\n * docs/gitbook/architecture/logging-architecture.md). A live `ILogger` callback can't cross the\n * `postMessage` structured-clone boundary, so unexpected crashes are reported through the\n * standard IPC Logger Protocol instead (see\n * docs/gitbook/guidelines/playbook-ipc-logging.md) — `AstWorkerPool` routes it back to its own\n * injected logger via `IpcLogRouter`.\n */\nconst logger = new IpcLoggerClient((message) =>\n parentPort?.postMessage(message),\n);\n\nprocess.on(\"uncaughtException\", (err) => {\n logger.error(AstMessages.WORKER_UNCAUGHT_EXCEPTION, {\n error: err instanceof Error ? err.message : String(err),\n });\n});\nprocess.on(\"unhandledRejection\", (err) => {\n logger.error(AstMessages.WORKER_UNHANDLED_REJECTION, {\n error: err instanceof Error ? err.message : String(err),\n });\n});\n\nexport interface AstParseRequest {\n taskId: string;\n filePath: string;\n code: string;\n language: SupportedLanguage;\n}\n\nexport interface ImportDescriptor {\n localName: string;\n originalName: string;\n modulePath: string;\n}\n\nexport interface AstParseResponse {\n taskId: string;\n success: boolean;\n error?: string;\n data?: {\n imports: ImportDescriptor[];\n exports: Array<{ name: string; type: AstExportKind }>;\n functions: Array<{\n name: string;\n startLine: number;\n endLine: number;\n contentHash?: string;\n containerName?: string; // NEW — the enclosing class/struct name, or undefined for a top-level function\n }>;\n classes: Array<{\n name: string;\n startLine: number;\n endLine: number;\n methods: string[];\n contentHash?: string;\n }>;\n /** Exported variable declarators (`export const X = ...`) — TS/JS only today (issue #192\n * gap 1). Function-valued initializers (arrow functions / function expressions) are\n * excluded: they are already indexed as functions via `functions`. */\n variables?: Array<{\n name: string;\n startLine: number;\n endLine: number;\n contentHash?: string;\n }>;\n calls: Array<{\n sourceFunction: string;\n targetFunction: string;\n /** 0-based source position of the call-site's callee expression start (matches Tier A's own\n * `startLine`/`startPosition` convention). The seed Tier B forward resolution (issue #11\n * plan A, Slice 2) issues `textDocument/definition` at this position per call site to\n * resolve the callee precisely -- see\n * forward-tier-b-edge-resolution-plan.md Slice 1. */\n startLine: number;\n startColumn: number;\n }>;\n implements?: Array<{ sourceClass: string; targetInterface: string }>;\n extends?: Array<{ sourceClass: string; targetClass: string }>;\n /**\n * `new Worker(<path>)` spawn sites (TS/JS only — see `WORKER_SPAWN_LANGUAGES`), one per\n * resolved spawn call, attributing it to its enclosing function like `calls` does.\n * `persist-ast-graph.ts` resolves `targetPath` to a real file and inserts a `DEPENDS_ON`\n * edge from it — the fix for the `ast-worker-pool.ts` -> `ast-worker.ts` false-negative\n * blast-radius gap (dynamic `worker_threads` spawns are invisible to the static\n * imports/calls pipeline, since the target script is a runtime path string, not a static\n * `import`).\n */\n workerSpawns?: Array<{ sourceFunction: string; targetPath: string }>;\n decisions?: string[];\n };\n}\n\nlet parserInitialized = false;\nlet registryPromise: Promise<LanguageRegistry> | null = null;\n\nfunction getRegistry(): Promise<LanguageRegistry> {\n registryPromise ??= loadDefaultRegistry();\n return registryPromise;\n}\n\n// Worker-lifetime cache for loaded tree-sitter grammars, keyed by the resolved wasmPath\n// (deterministic per language -- see resolveWasmPath()). Language.load() is a real WASM\n// dynamic-library load (WebAssembly.instantiate + relocation into the shared runtime's\n// Table/Memory), not a cheap call -- reloading the same grammar per file (the pre-existing\n// behavior) is pure waste once a worker has already loaded it once. Mirrors registryPromise's\n// own memoization shape immediately above. web-tree-sitter's Language class has no\n// delete()/dispose method (verified against the installed 0.25.10 type defs), so there is\n// nothing to release even if this cache were bounded -- see\n// docs/ai_plans/implement_wasm-language-load-cache.md §2.1 for the full check.\nconst languageCache = new Map<string, Promise<Language>>();\n\nfunction getLanguage(wasmPath: string): Promise<Language> {\n let cached = languageCache.get(wasmPath);\n if (!cached) {\n cached = Language.load(wasmPath);\n languageCache.set(wasmPath, cached);\n }\n return cached;\n}\n\n/**\n * Re-exported for backward compatibility (existing importer: `ast-worker.fixture.unit.test.ts`)\n * — the real implementation moved to `resolve-wasm-path.ts` so it can also be imported from the\n * main thread (by `SemanticDiffAnalyzerService`) without pulling in this file's\n * `worker_threads`-only side effects (`parentPort?.on(...)`, process-level\n * `uncaughtException`/`unhandledRejection` handlers). See that file's doc comment for why.\n */\nexport { resolveWasmPath };\n\n/** Regex fallback for imports so graph edges still work when WASM fails to load (e.g. in tests). */\nfunction extractFallbackImports(code: string): ImportDescriptor[] {\n const fallbackImports: ImportDescriptor[] = [];\n const importMatches = code.matchAll(\n /import\\s+{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n );\n for (const match of importMatches) {\n fallbackImports.push({\n localName: match[1].trim(),\n originalName: match[1].trim(),\n modulePath: match[2],\n });\n }\n return fallbackImports;\n}\n\nfunction getNodeName(node: Node): string {\n return (\n node.childForFieldName(\"name\")?.text ||\n node.descendantsOfType(\"identifier\")[0]?.text ||\n AstMessages.ANONYMOUS_NAME\n );\n}\n\n/**\n * For anonymous callables (arrow_function/function_expression with no own name), resolve\n * the binding name from the nearest enclosing variable_declarator / assignment_expression /\n * pair (object property) / public_field_definition (class field arrow method). Returns\n * \"anonymous\" for truly unbound cases (IIFEs, bare callback arguments).\n *\n * Named nodes (function_declaration, method_definition) already have a \"name\" field, so the\n * fast path below returns the same result getNodeName() would — safe to use uniformly for\n * every function-kind node, not just anonymous ones.\n *\n * GRPH-006 follow-up: C/C++'s `function_definition` has no direct \"name\" field at all — the name\n * sits two levels down, inside `function_declarator`'s own \"declarator\" field (`identifier` for a\n * free function, `field_identifier` for an inline method, `qualified_identifier` -- scope::name --\n * for an out-of-line one). Verified this was silently returning \"anonymous\" for every C/C++\n * function before this fix (never previously observed for C++ specifically because\n * `cppConfig`'s functions query didn't even extract methods until the GRPH-006 follow-up fix to\n * `cpp.ts` — this pass surfaced both bugs together).\n */\n/** GRPH-006 follow-up: resolves a C/C++ `function_definition`'s name from its declarator-nested\n * shape (see `resolveCallableName`'s own doc comment) -- `identifier`/`field_identifier` return\n * their own text directly, `qualified_identifier` (an out-of-line `Class::method`) returns just\n * its `name` field, not the qualifier. Extracted purely to keep `resolveCallableName`'s own\n * complexity within budget. */\nfunction resolveDeclaratorNestedName(node: Node): string | undefined {\n const declaratorName = node\n .childForFieldName(\"declarator\")\n ?.childForFieldName(\"declarator\");\n if (!declaratorName) return undefined;\n return declaratorName.type === AstNodeTypes.QUALIFIED_IDENTIFIER\n ? (declaratorName.childForFieldName(\"name\")?.text ??\n AstMessages.ANONYMOUS_NAME)\n : declaratorName.text;\n}\n\nexport function resolveCallableName(node: Node): string {\n const ownName = node.childForFieldName(\"name\");\n if (ownName) return ownName.text;\n\n const declaratorName = resolveDeclaratorNestedName(node);\n if (declaratorName) return declaratorName;\n\n const NAME_BEARING_PARENTS = new Set<string>([\n AstNodeTypes.VARIABLE_DECLARATOR,\n AstNodeTypes.ASSIGNMENT_EXPRESSION,\n AstNodeTypes.PAIR,\n AstNodeTypes.PUBLIC_FIELD_DEFINITION,\n ]);\n let current = node.parent;\n while (current) {\n // An \"arguments\" ancestor means this callable is itself passed as a call argument\n // (e.g. arr.map(x => x + 1)) rather than being the direct value of a declarator/\n // assignment/property/field. Stop here — climbing further would misattribute the\n // name of the outer binding the call happens to live inside (e.g. `results` in\n // `const results = arr.map(x => x + 1)`) to this unrelated, unbound callback.\n if (current.type === AstNodeTypes.ARGUMENTS) break;\n if (NAME_BEARING_PARENTS.has(current.type)) {\n const nameNode =\n current.childForFieldName(\"name\") ||\n current.childForFieldName(\"key\") ||\n current.childForFieldName(\"left\");\n if (nameNode) return nameNode.text;\n }\n current = current.parent;\n }\n return AstMessages.ANONYMOUS_NAME;\n}\n\n/**\n * Extracts just the callee (target function/method name) from a call node.\n * The field holding the callee expression is named differently across\n * grammars (\"function\" for TS/JS/Python/Rust/Go/C/C++, \"name\" for Java/PHP,\n * \"method\" for Ruby) — try the common ones, falling back to the whole\n * node's text if none match.\n */\nfunction getCallTargetText(node: Node): string {\n const callee =\n node.childForFieldName(\"function\") ||\n node.childForFieldName(\"name\") ||\n node.childForFieldName(\"method\");\n return callee?.text ?? node.text;\n}\n\n/** Resolves a call-site's *seed position* for Tier B forward resolution (issue #11 plan A,\n * Finding C): for a bare identifier call (`foo()`), `node` already *is* the identifier and its\n * own `startPosition` is correct. But for a compound callee -- JS/TS `member_expression`\n * (`service.doSomething()`), Go `selector_expression`, C++/Rust `field_expression` -- the\n * `calls` tree-sitter query (see `lib/ast-core/src/languages/*.ts`) captures the *whole*\n * expression, whose own `startPosition` sits on the receiver (`service`), not the callee\n * (`doSomething`). `textDocument/definition` must be issued at the callee's own position, or it\n * resolves the receiver's declaration instead -- an invented edge (IMPT-002). Verified against\n * real tree-sitter-typescript output (`property` is the correct field name for\n * `member_expression`, confirmed via a real parse, not assumed) -- see this plan's own\n * instruction not to copy field names blind.\n *\n * No-op (falls through to `node.startPosition`, i.e. itself) for languages whose query already\n * captures the callee identifier directly (Java `name:`, PHP `name:`, Ruby `method:`) or for a\n * bare identifier call. */\nfunction getCallSitePosition(node: Node): { row: number; column: number } {\n const calleeIdentifier =\n node.childForFieldName(\"property\") || // JS/TS member_expression\n node.childForFieldName(\"field\") || // Go selector_expression / C++/Rust field_expression\n node.childForFieldName(\"attribute\") || // Python attribute\n node.childForFieldName(\"name\") || // defensive; Java/PHP already capture this directly\n node.childForFieldName(\"method\"); // defensive; Ruby already captures this directly\n return (calleeIdentifier ?? node).startPosition;\n}\n\n/** Walks up from `node` to find the nearest ancestor present in `containerIds` (function/class nodes already extracted for this file), returning its name, or \"anonymous\" for top-level (file-scoped) call/implements/extends sites. */\nfunction findEnclosingContainerName(\n node: Node,\n containerIds: Set<number>,\n): string {\n let current = node.parent;\n while (current) {\n if (containerIds.has(current.id)) {\n return getNodeName(current);\n }\n current = current.parent;\n }\n return AstMessages.ANONYMOUS_NAME;\n}\n\n/** Resolves the base type name whether `node` is itself a `type_identifier` or wraps one one level\n * deep -- Rust generic impls (`impl<T> Wrapper<T>` -- field is `generic_type`) and Go pointer\n * receivers (`*Receiver` -- field is `pointer_type`) both need the unwrap; a plain `type_identifier`\n * field (the common case) is returned as-is. */\nfunction firstTypeIdentifierText(node: Node): string | undefined {\n return node.type === AstNodeTypes.TYPE_IDENTIFIER\n ? node.text\n : node.descendantsOfType(AstNodeTypes.TYPE_IDENTIFIER)[0]?.text;\n}\n\n/** GRPH-006 follow-up (Rust): a method's lexical parent is `impl_item`, which `rustConfig.classes`\n * deliberately excludes (so `findEnclosingContainerName` over `classIds` always returns\n * \"anonymous\" for a Rust method) -- the target struct/enum's name lives on the impl block's own\n * `type` field instead (the Self type, not `trait` -- `impl Trait for Type` still qualifies by\n * `Type`, the concrete struct, not whichever trait it happens to implement). */\nfunction resolveRustImplContainerName(node: Node): string | undefined {\n let current = node.parent;\n while (current) {\n if (current.type === AstNodeTypes.IMPL_ITEM) {\n const typeField = current.childForFieldName(\"type\");\n return typeField ? firstTypeIdentifierText(typeField) : undefined;\n }\n current = current.parent;\n }\n return undefined;\n}\n\n/** GRPH-006 follow-up (Go): a method's receiver type is referenced through its own `receiver:`\n * field, never as an AST ancestor (`type_declaration` never encloses a `method_declaration`), so\n * `findEnclosingContainerName` over `classIds` always returns \"anonymous\" here too -- resolve the\n * receiver parameter's type directly instead. */\nfunction resolveGoReceiverContainerName(node: Node): string | undefined {\n const receiver = node.childForFieldName(\"receiver\");\n const paramType = receiver?.namedChild(0)?.childForFieldName(\"type\");\n return paramType ? firstTypeIdentifierText(paramType) : undefined;\n}\n\n/** GRPH-006 follow-up (C++): an out-of-line `Ret Class::method(){}` definition is never lexically\n * nested inside its class (inline methods already resolve via the generic ancestor walk once\n * they're extracted at all -- see `cpp.ts`'s functions-query fix), so its declarator is a\n * `qualified_identifier` carrying the class name in its own `scope` field instead. Recurses one\n * level for a nested qualifier (`A::B::method`), taking the innermost (`B`) as the immediate\n * container -- this scheme only ever tracks one level of containment, matching every other\n * language here. */\nfunction resolveCppQualifiedContainerName(node: Node): string | undefined {\n const declarator = node.childForFieldName(\"declarator\");\n const inner = declarator?.childForFieldName(\"declarator\");\n if (inner?.type !== AstNodeTypes.QUALIFIED_IDENTIFIER) return undefined;\n const scope = inner.childForFieldName(\"scope\");\n if (!scope) return undefined;\n return scope.type === AstNodeTypes.QUALIFIED_IDENTIFIER\n ? scope.childForFieldName(\"name\")?.text\n : scope.text;\n}\n\n/** GRPH-006 follow-up: for a function whose enclosing container the generic ancestor walk\n * couldn't find (Rust/Go/C++'s deferred gaps -- see the ADR), try each language-specific\n * resolver in turn. Mutually exclusive by construction (each checks for a node shape only its own\n * grammar produces -- e.g. only Rust ever has an `impl_item` ancestor), so no explicit language\n * tag is needed; a language not covered here (or a function with no enclosing container at all)\n * falls through to `undefined`, unchanged from before this follow-up. */\nfunction resolveDeferredLanguageContainerName(node: Node): string | undefined {\n return (\n resolveRustImplContainerName(node) ??\n resolveGoReceiverContainerName(node) ??\n resolveCppQualifiedContainerName(node)\n );\n}\n\n/** Shape of a fully-populated `AstParseResponse[\"data\"]` (i.e. the non-optional variant produced once parsing has actually run). */\ntype AstExtractionResult = NonNullable<AstParseResponse[\"data\"]>;\n\n/** Extracts class declaration nodes via the provider and appends their summaries to `classes`. Returns the raw nodes so callers can derive id sets for edge extraction. */\nfunction collectClassNodes(\n tree: Tree,\n provider: LanguageProvider,\n classes: AstExtractionResult[\"classes\"],\n): Node[] {\n const classNodes = provider.extractClasses(tree.rootNode);\n for (const node of classNodes) {\n classes.push({\n name: getNodeName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n methods: [],\n contentHash: symbolContentHash(node),\n });\n }\n return classNodes;\n}\n\n/**\n * Extracts exported variable declarators via the provider and appends their summaries to\n * `variables` (issue #192 gap 1: `export const X = ...` must be an indexable symbol so\n * `impact <X>` resolves instead of \"No matching node\"). The query only matches exported\n * `lexical_declaration` declarators with plain identifier names; this collector additionally\n * skips function-valued initializers (arrow_function/function_expression) since those are\n * already indexed as functions by the `functions` query + resolveCallableName path.\n */\nconst FUNCTION_VALUE_NODE_TYPES = new Set<string>([\n \"arrow_function\",\n \"function_expression\",\n]);\n\nfunction collectVariableNodes(\n tree: Tree,\n provider: LanguageProvider,\n variables: NonNullable<AstExtractionResult[\"variables\"]>,\n): Node[] {\n const variableNodes = provider.extractVariables?.(tree.rootNode) ?? [];\n for (const node of variableNodes) {\n const value = node.childForFieldName(\"value\");\n if (value && FUNCTION_VALUE_NODE_TYPES.has(value.type)) continue;\n variables.push({\n name: getNodeName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n contentHash: symbolContentHash(node),\n });\n }\n return variableNodes;\n}\n\n/** Extracts function/method declaration nodes via the provider and appends their summaries to `functions`. Returns the raw nodes so callers can derive id sets for edge extraction.\n *\n * `classNodes` (GRPH-006) lets each function's enclosing class/struct be resolved via the same\n * `findEnclosingContainerName` ancestor walk `collectCallEdges`/`collectImplementsEdges`/\n * `collectExtendsEdges` already use -- `containerName` is what qualifies this symbol's `node_key`\n * down the line (`persist-ast-graph.ts`'s `buildQualifiedBaseKey`). `findEnclosingContainerName`'s\n * \"nothing found\" sentinel is the literal string `AstMessages.ANONYMOUS_NAME` (\"anonymous\") --\n * that means \"top-level, outside any class\" here, a different meaning than its existing use in\n * `collectCallEdges` (\"outside any function\"), so it must be converted to `undefined` rather than\n * stored as-is (storing it as-is would qualify every top-level function as `file#anonymous.name`).\n *\n * When the ancestor walk finds nothing, `resolveDeferredLanguageContainerName` (GRPH-006\n * follow-up) tries Rust/Go/C++'s own non-lexical containment shapes before giving up to\n * `undefined` -- see that function's own doc comment for why each needs a different mechanism. */\nexport function collectFunctionNodes(\n tree: Tree,\n provider: LanguageProvider,\n functions: AstExtractionResult[\"functions\"],\n classNodes: Node[],\n): Node[] {\n const classIds = new Set(classNodes.map((n) => n.id));\n const functionNodes = provider.extractFunctions(tree.rootNode);\n for (const node of functionNodes) {\n const container = findEnclosingContainerName(node, classIds);\n const containerName =\n container === AstMessages.ANONYMOUS_NAME\n ? resolveDeferredLanguageContainerName(node)\n : container;\n functions.push({\n name: resolveCallableName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n contentHash: symbolContentHash(node),\n containerName,\n });\n }\n return functionNodes;\n}\n\n/** Extracts call-site edges via the provider, attributing each call to its enclosing function (or \"anonymous\"), up to the 1000-call circuit breaker. */\nfunction collectCallEdges(\n tree: Tree,\n provider: LanguageProvider,\n functionNodes: Node[],\n calls: AstExtractionResult[\"calls\"],\n): void {\n const functionIds = new Set(functionNodes.map((n) => n.id));\n const callNodes = provider.extractCalls(tree.rootNode);\n for (const node of callNodes) {\n if (calls.length >= 1000) break; // Circuit breaker limit\n const position = getCallSitePosition(node);\n calls.push({\n sourceFunction: findEnclosingContainerName(node, functionIds),\n targetFunction: getCallTargetText(node),\n startLine: position.row,\n startColumn: position.column,\n });\n }\n}\n\n/** Extracts `implements` edges via the provider, if it supports them, attributing each to its enclosing class. */\nfunction collectImplementsEdges(\n tree: Tree,\n provider: LanguageProvider,\n classNodes: Node[],\n implementsList: NonNullable<AstExtractionResult[\"implements\"]>,\n): void {\n if (!provider.extractImplements) return;\n const classIds = new Set(classNodes.map((n) => n.id));\n for (const node of provider.extractImplements(tree.rootNode)) {\n implementsList.push({\n sourceClass: findEnclosingContainerName(node, classIds),\n targetInterface: node.text,\n });\n }\n}\n\n/** Extracts `extends` edges via the provider, if it supports them, attributing each to its enclosing class. */\nfunction collectExtendsEdges(\n tree: Tree,\n provider: LanguageProvider,\n classNodes: Node[],\n extendsList: NonNullable<AstExtractionResult[\"extends\"]>,\n): void {\n if (!provider.extractExtends) return;\n const classIds = new Set(classNodes.map((n) => n.id));\n for (const node of provider.extractExtends(tree.rootNode)) {\n extendsList.push({\n sourceClass: findEnclosingContainerName(node, classIds),\n targetClass: node.text,\n });\n }\n}\n\n/** Languages `collectWorkerSpawns` runs against — the reported gap (a `new Worker(...)` spawn\n * invisible to the static imports/calls pipeline) is TS/JS-specific: `new_expression` is also a\n * real C++ grammar node (the `new` operator), so gating by language avoids misinterpreting an\n * unrelated `new Worker(...)` construction in another language as a worker_threads spawn. */\nconst WORKER_SPAWN_LANGUAGES: ReadonlySet<SupportedLanguage> = new Set([\n SUPPORTED_LANGUAGES.TYPESCRIPT,\n SUPPORTED_LANGUAGES.JAVASCRIPT,\n]);\n\nconst WORKER_CONSTRUCTOR_NAME = \"Worker\";\nconst PATH_MODULE_OBJECT_NAME = \"path\";\nconst PATH_RESOLVE_METHOD_NAME = \"resolve\";\nconst PATH_JOIN_METHOD_NAME = \"join\";\nconst DIRNAME_IDENTIFIER_NAME = \"__dirname\";\n\n/** True when `node` is a `path.resolve(...)`/`path.join(...)` call expression — the exact idiom\n * `ast-worker-pool.ts` uses to build a worker script's path from `__dirname`. */\nfunction isPathJoinOrResolveCall(node: Node): boolean {\n if (node.type !== \"call_expression\") return false;\n const fn = node.childForFieldName(\"function\");\n if (!fn || fn.type !== \"member_expression\") return false;\n const object = fn.childForFieldName(\"object\")?.text;\n const property = fn.childForFieldName(\"property\")?.text;\n return (\n object === PATH_MODULE_OBJECT_NAME &&\n (property === PATH_RESOLVE_METHOD_NAME ||\n property === PATH_JOIN_METHOD_NAME)\n );\n}\n\n/** Extracts the string-literal path segment from a `path.resolve(__dirname, \"<literal>\")` /\n * `path.join(__dirname, \"<literal>\")` call, or undefined if it doesn't reference `__dirname` or\n * carries no string-literal argument. */\nfunction extractDirnameJoinedLiteral(callNode: Node): string | undefined {\n const args = callNode.childForFieldName(\"arguments\");\n if (!args) return undefined;\n const hasDirname = args.namedChildren.some(\n (n) => n?.type === \"identifier\" && n.text === DIRNAME_IDENTIFIER_NAME,\n );\n if (!hasDirname) return undefined;\n const literal = args.descendantsOfType(\"string\")[0];\n return literal?.text.replace(/['\"]/g, \"\");\n}\n\n/** Bounded same-file scan for `<argText> = path.resolve/join(__dirname, \"<literal>\")` — the\n * exact idiom `ast-worker-pool.ts` uses for `this.wPath = path.resolve(__dirname, \"./ast-worker.js\")`,\n * needed because the `new Worker(...)` call site references the field/variable, not the literal,\n * directly. Matches by comparing the assignment's own left-hand-side text against `argText`\n * verbatim (e.g. both \"this.wPath\"), so it works uniformly whether the argument is a bare\n * identifier or a member expression. */\nfunction findDirnameJoinedAssignment(\n tree: Tree,\n argText: string,\n): string | undefined {\n for (const assignment of tree.rootNode.descendantsOfType(\n AstNodeTypes.ASSIGNMENT_EXPRESSION,\n )) {\n if (!assignment) continue;\n const left = assignment.childForFieldName(\"left\");\n const right = assignment.childForFieldName(\"right\");\n if (left?.text !== argText || !right || !isPathJoinOrResolveCall(right)) {\n continue;\n }\n const literal = extractDirnameJoinedLiteral(right);\n if (literal) return literal;\n }\n return undefined;\n}\n\n/** Resolves `new Worker(<arg>)`'s first argument to a literal relative path: a direct string\n * literal, or a same-file `path.resolve/join(__dirname, \"<literal>\")`-assigned field/variable\n * (the `ast-worker-pool.ts` idiom, via `findDirnameJoinedAssignment`). Returns undefined —\n * skip silently, no guessing — when neither shape matches. */\nfunction resolveWorkerArgumentPath(\n tree: Tree,\n argNode: Node,\n): string | undefined {\n if (argNode.type === \"string\") {\n return argNode.text.replace(/['\"]/g, \"\");\n }\n if (argNode.type === \"identifier\" || argNode.type === \"member_expression\") {\n return findDirnameJoinedAssignment(tree, argNode.text);\n }\n return undefined;\n}\n\n/** Extracts `new Worker(<arg>)` spawn sites (TS/JS only, see `WORKER_SPAWN_LANGUAGES`) and\n * appends a `{sourceFunction, targetPath}` descriptor for each one whose argument resolves to a\n * literal relative path (`resolveWorkerArgumentPath`), attributing it to its enclosing function\n * like `collectCallEdges` does. `persist-ast-graph.ts` resolves `targetPath` to a real file and\n * inserts the corresponding `DEPENDS_ON` edge. */\nexport function collectWorkerSpawns(\n tree: Tree,\n language: SupportedLanguage,\n functionNodes: Node[],\n workerSpawns: NonNullable<AstExtractionResult[\"workerSpawns\"]>,\n): void {\n if (!WORKER_SPAWN_LANGUAGES.has(language)) return;\n const functionIds = new Set(functionNodes.map((n) => n.id));\n for (const node of tree.rootNode.descendantsOfType(\"new_expression\")) {\n if (!node) continue;\n const ctor = node.childForFieldName(\"constructor\");\n if (ctor?.text !== WORKER_CONSTRUCTOR_NAME) continue;\n const args = node.childForFieldName(\"arguments\");\n const firstArg = args?.namedChildren.find((n): n is Node => n !== null);\n if (!firstArg) continue;\n const targetPath = resolveWorkerArgumentPath(tree, firstArg);\n if (!targetPath) continue;\n workerSpawns.push({\n sourceFunction: findEnclosingContainerName(node, functionIds),\n targetPath,\n });\n }\n}\n\n/**\n * Runs every provider-driven extraction against a parsed tree (or returns empty results plus a\n * decision note if parsing produced no tree). A single try/catch wraps the whole pass, matching\n * the original inline behavior of recording a `providerQueryFailed` decision instead of throwing\n * when any one extractor misbehaves.\n */\nfunction extractAstData(\n tree: Tree | null,\n provider: LanguageProvider,\n language: SupportedLanguage,\n): AstExtractionResult {\n const decisions: string[] = [];\n const imports: ImportDescriptor[] = [];\n const exports: AstExtractionResult[\"exports\"] = [];\n const functions: AstExtractionResult[\"functions\"] = [];\n const classes: AstExtractionResult[\"classes\"] = [];\n const variables: NonNullable<AstExtractionResult[\"variables\"]> = [];\n const calls: AstExtractionResult[\"calls\"] = [];\n const implementsList: NonNullable<AstExtractionResult[\"implements\"]> = [];\n const extendsList: NonNullable<AstExtractionResult[\"extends\"]> = [];\n const workerSpawns: NonNullable<AstExtractionResult[\"workerSpawns\"]> = [];\n\n if (tree) {\n decisions.push(AstMessages.parsedViaTreeSitter(tree.rootNode.childCount));\n\n try {\n const classNodes = collectClassNodes(tree, provider, classes);\n const functionNodes = collectFunctionNodes(\n tree,\n provider,\n functions,\n classNodes,\n );\n\n const importNodes = provider.extractImports(tree.rootNode);\n imports.push(...parseImportDescriptors(importNodes));\n\n collectVariableNodes(tree, provider, variables);\n\n collectCallEdges(tree, provider, functionNodes, calls);\n collectImplementsEdges(tree, provider, classNodes, implementsList);\n collectExtendsEdges(tree, provider, classNodes, extendsList);\n collectWorkerSpawns(tree, language, functionNodes, workerSpawns);\n\n decisions.push(AstMessages.QUERIED_VIA_LANGUAGE_PROVIDER);\n } catch (e) {\n decisions.push(\n AstMessages.providerQueryFailed(\n e instanceof Error ? e.message : String(e),\n ),\n );\n }\n }\n\n return {\n imports,\n exports,\n functions,\n classes,\n variables,\n calls,\n implements: implementsList,\n extends: extendsList,\n workerSpawns,\n decisions,\n };\n}\n\n/** Logs any query pattern that failed to compile, then clears them so a later file of the same\n * language doesn't re-report the same failure. Drained rather than read because the provider is\n * reused for the worker's whole lifetime.\n *\n * Exported for the wiring test: the module-scoped `logger` posts to `parentPort`, which is\n * null outside a real worker, so this path is otherwise unobservable (same reason\n * `buildParseResponse` is exported). */\nexport function reportQueryCompileFailures(\n provider: LanguageProvider,\n language: SupportedLanguage,\n): void {\n for (const failure of provider.drainQueryCompileFailures?.() ?? []) {\n logger.error(AstMessages.QUERY_COMPILE_FAILED, {\n language,\n kind: failure.kind,\n pattern: failure.pattern,\n message: failure.message,\n });\n }\n}\n\n/** Parses `request.code` with the resolved provider/grammar and runs the full AST extraction pass, releasing the tree-sitter tree/parser handles once done. */\nfunction parseAndExtract(\n code: string,\n provider: LanguageProvider,\n langInstance: Language,\n language: SupportedLanguage,\n): AstExtractionResult {\n const parser = new Parser();\n parser.setLanguage(langInstance);\n\n // initQueries() is idempotent (DefaultProvider caches compiledQueries after the first call)\n // and the provider instance is reused for every file of this language for the worker's whole\n // lifetime (see getRegistry() above), so this only actually compiles once. A field whose\n // pattern fails to compile against the installed grammar degrades to that field's\n // descendantsOfType fallback (DefaultProvider.compileQuery) rather than throwing.\n provider.initQueries?.(langInstance);\n reportQueryCompileFailures(provider, language);\n\n const tree = parser.parse(code);\n const data = extractAstData(tree, provider, language);\n\n if (tree) tree.delete();\n parser.delete();\n\n return data;\n}\n\n/**\n * Resolves a language provider for `request.filePath` and produces the full parse response,\n * short-circuiting with an empty-but-successful result (plus an explanatory decision note) when\n * no provider is registered for the extension or its wasm grammar can't be located on disk.\n */\nexport async function buildParseResponse(\n request: AstParseRequest,\n): Promise<AstParseResponse> {\n if (!parserInitialized) {\n await Parser.init();\n parserInitialized = true;\n }\n\n const registry = await getRegistry();\n const ext = path.extname(request.filePath);\n const provider: LanguageProvider | undefined =\n registry.getProviderForExtension(ext);\n\n if (!provider) {\n return {\n taskId: request.taskId,\n success: true,\n data: {\n imports: [],\n exports: [],\n functions: [],\n classes: [],\n calls: [],\n decisions: [AstMessages.noLanguageProviderForExtension(ext)],\n },\n };\n }\n\n const { wasmPath, attemptedPaths } = resolveWasmPath(provider.wasm_file);\n\n if (!fs.existsSync(wasmPath)) {\n return {\n taskId: request.taskId,\n success: true,\n data: {\n imports: extractFallbackImports(request.code),\n exports: [],\n functions: [],\n classes: [],\n calls: [],\n decisions: [\n AstMessages.wasmNotFound(request.language, attemptedPaths.join(\", \")),\n ],\n },\n };\n }\n\n const langInstance = await getLanguage(wasmPath);\n const data = parseAndExtract(\n request.code,\n provider,\n langInstance,\n request.language,\n );\n\n return {\n taskId: request.taskId,\n success: true,\n data,\n };\n}\n\nparentPort?.on(\"message\", async (request: AstParseRequest) => {\n try {\n const response = await buildParseResponse(request);\n parentPort?.postMessage(response);\n } catch (err: any) {\n parentPort?.postMessage({\n taskId: request.taskId,\n success: false,\n error: err.stack || String(err),\n });\n }\n});\n"],"mappings":";mJAAA,OAAS,cAAAA,MAAkB,iBAC3B,OAAS,UAAAC,EAAQ,YAAAC,MAAsC,kBACvD,UAAYC,MAAU,OACtB,UAAYC,MAAQ,KACpB,OAAS,cAAAC,MAAkB,SA6B3B,SAASC,EAAkBC,EAAoB,CAC7C,OAAOC,EAAWC,CAAgB,EAAE,OAAOF,EAAK,IAAI,EAAE,OAAO,KAAY,CAC3E,CAWA,IAAMG,EAAS,IAAIC,EAAiBC,GAClCC,GAAY,YAAYD,CAAO,CACjC,EAEA,QAAQ,GAAG,oBAAsBE,GAAQ,CACvCJ,EAAO,MAAMK,EAAY,0BAA2B,CAClD,MAAOD,aAAe,MAAQA,EAAI,QAAU,OAAOA,CAAG,CACxD,CAAC,CACH,CAAC,EACD,QAAQ,GAAG,qBAAuBA,GAAQ,CACxCJ,EAAO,MAAMK,EAAY,2BAA4B,CACnD,MAAOD,aAAe,MAAQA,EAAI,QAAU,OAAOA,CAAG,CACxD,CAAC,CACH,CAAC,EAwED,IAAIE,EAAoB,GACpBC,EAAoD,KAExD,SAASC,GAAyC,CAChD,OAAAD,IAAoBE,EAAoB,EACjCF,CACT,CAWA,IAAMG,EAAgB,IAAI,IAE1B,SAASC,EAAYC,EAAqC,CACxD,IAAIC,EAASH,EAAc,IAAIE,CAAQ,EACvC,OAAKC,IACHA,EAASC,EAAS,KAAKF,CAAQ,EAC/BF,EAAc,IAAIE,EAAUC,CAAM,GAE7BA,CACT,CAYA,SAASE,EAAuBC,EAAkC,CAChE,IAAMC,EAAsC,CAAC,EACv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AEvE,GAAI,CAAI,aAAWyE,CAAQ,EACzB,MAAO,CACL,OAAQL,EAAQ,OAChB,QAAS,GACT,KAAM,CACJ,QAASnG,EAAuBmG,EAAQ,IAAI,EAC5C,QAAS,CAAC,EACV,UAAW,CAAC,EACZ,QAAS,CAAC,EACV,MAAO,CAAC,EACR,UAAW,CACT5F,EAAY,aAAa4F,EAAQ,SAAUM,EAAe,KAAK,IAAI,CAAC,CACtE,CACF,CACF,EAGF,IAAMX,EAAe,MAAMa,EAAYH,CAAQ,EACzCP,EAAOJ,GACXM,EAAQ,KACRpE,EACA+D,EACAK,EAAQ,QACV,EAEA,MAAO,CACL,OAAQA,EAAQ,OAChB,QAAS,GACT,KAAAF,CACF,CACF,CAEAW,GAAY,GAAG,UAAW,MAAOT,GAA6B,CAC5D,GAAI,CACF,IAAMU,EAAW,MAAMX,GAAmBC,CAAO,EACjDS,GAAY,YAAYC,CAAQ,CAClC,OAASC,EAAU,CACjBF,GAAY,YAAY,CACtB,OAAQT,EAAQ,OAChB,QAAS,GACT,MAAOW,EAAI,OAAS,OAAOA,CAAG,CAChC,CAAC,CACH,CACF,CAAC","names":["parentPort","Parser","Language","path","fs","createHash","symbolContentHash","node","createHash","HASH_ALGO_SHA256","logger","IpcLoggerClient","message","parentPort","err","AstMessages","parserInitialized","registryPromise","getRegistry","loadDefaultRegistry","languageCache","getLanguage","wasmPath","cached","Language","extractFallbackImports","code","fallbackImports","importMatches","match","getNodeName","node","AstMessages","resolveDeclaratorNestedName","declaratorName","AstNodeTypes","resolveCallableName","ownName","NAME_BEARING_PARENTS","current","nameNode","getCallTargetText","getCallSitePosition","findEnclosingContainerName","containerIds","firstTypeIdentifierText","resolveRustImplContainerName","typeField","resolveGoReceiverContainerName","paramType","resolveCppQualifiedContainerName","inner","scope","resolveDeferredLanguageContainerName","collectClassNodes","tree","provider","classes","classNodes","symbolContentHash","FUNCTION_VALUE_NODE_TYPES","collectVariableNodes","variables","variableNodes","value","collectFunctionNodes","functions","classIds","n","functionNodes","container","containerName","collectCallEdges","calls","functionIds","callNodes","position","collectImplementsEdges","implementsList","collectExtendsEdges","extendsList","WORKER_SPAWN_LANGUAGES","SUPPORTED_LANGUAGES","WORKER_CONSTRUCTOR_NAME","PATH_MODULE_OBJECT_NAME","PATH_RESOLVE_METHOD_NAME","PATH_JOIN_METHOD_NAME","DIRNAME_IDENTIFIER_NAME","isPathJoinOrResolveCall","fn","object","property","extractDirnameJoinedLiteral","callNode","args","findDirnameJoinedAssignment","argText","assignment","left","right","literal","resolveWorkerArgumentPath","argNode","collectWorkerSpawns","language","workerSpawns","firstArg","targetPath","extractAstData","decisions","imports","exports","importNodes","parseImportDescriptors","e","reportQueryCompileFailures","failure","logger","parseAndExtract","langInstance","parser","Parser","data","buildParseResponse","request","parserInitialized","registry","getRegistry","ext","wasmPath","attemptedPaths","resolveWasmPath","getLanguage","parentPort","response","err"]}
|
|
1
|
+
{"version":3,"sources":["../../../lib/core/src/ast/ast-worker.ts"],"sourcesContent":["import { parentPort } from \"worker_threads\";\nimport { Parser, Language, type Node, type Tree } from \"web-tree-sitter\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport { createHash } from \"crypto\";\nimport { resolveWasmPath } from \"./resolve-wasm-path.js\";\nimport type { LanguageProvider, LanguageRegistry } from \"@workspace/ast-core\";\nimport {\n parseImportDescriptors,\n loadDefaultRegistry,\n} from \"@workspace/ast-core\";\nimport {\n ENCODING_HEX,\n HASH_ALGO_SHA256,\n IpcLoggerClient,\n SUPPORTED_LANGUAGES,\n type AstExportKind,\n type SupportedLanguage,\n} from \"@workspace/contracts\";\nimport { AstMessages, AstNodeTypes } from \"./ast-constants.js\";\n\n/**\n * Symbol-level feature hash (STOR-005): a hash of the AST node's own exact source span\n * (`node.text`), independent of the containing file's blob hash. Lets a single-symbol edit\n * produce a one-line JSONL diff for that symbol without touching its untouched siblings' hashes.\n *\n * The algorithm/digest constants come from `@workspace/contracts` (issue #211) so the worker's\n * hashes can never drift from the main thread's (`ast-worker-pool.ts`, `file-discovery.service.ts`)\n * or `lib/schema`'s. Package-name imports resolve through node_modules and work fine inside a\n * `worker_threads` Worker (as the existing contracts/ast-core imports above prove) — only bare\n * relative `.js`-to-`.ts` sibling imports needed a tsx resolve hook that doesn't propagate into\n * workers, and even that limitation is moot in dist/ where a fully-compiled worker ships.\n */\nfunction symbolContentHash(node: Node): string {\n return createHash(HASH_ALGO_SHA256).update(node.text).digest(ENCODING_HEX);\n}\n\n/**\n * Worker threads share the host process's stdout/stderr by default, so `console.*` here would\n * corrupt MCP's stdio JSON-RPC stream exactly like it would in the main thread (see\n * docs/gitbook/architecture/logging-architecture.md). A live `ILogger` callback can't cross the\n * `postMessage` structured-clone boundary, so unexpected crashes are reported through the\n * standard IPC Logger Protocol instead (see\n * docs/gitbook/guidelines/playbook-ipc-logging.md) — `AstWorkerPool` routes it back to its own\n * injected logger via `IpcLogRouter`.\n */\nconst logger = new IpcLoggerClient((message) =>\n parentPort?.postMessage(message),\n);\n\nprocess.on(\"uncaughtException\", (err) => {\n logger.error(AstMessages.WORKER_UNCAUGHT_EXCEPTION, {\n error: err instanceof Error ? err.message : String(err),\n });\n});\nprocess.on(\"unhandledRejection\", (err) => {\n logger.error(AstMessages.WORKER_UNHANDLED_REJECTION, {\n error: err instanceof Error ? err.message : String(err),\n });\n});\n\nexport interface AstParseRequest {\n taskId: string;\n filePath: string;\n code: string;\n language: SupportedLanguage;\n}\n\nexport interface ImportDescriptor {\n localName: string;\n originalName: string;\n modulePath: string;\n}\n\nexport interface AstParseResponse {\n taskId: string;\n success: boolean;\n error?: string;\n data?: {\n imports: ImportDescriptor[];\n exports: Array<{ name: string; type: AstExportKind }>;\n functions: Array<{\n name: string;\n startLine: number;\n endLine: number;\n contentHash?: string;\n containerName?: string; // NEW — the enclosing class/struct name, or undefined for a top-level function\n }>;\n classes: Array<{\n name: string;\n startLine: number;\n endLine: number;\n methods: string[];\n contentHash?: string;\n }>;\n /** Exported variable declarators (`export const X = ...`) — TS/JS only today (issue #192\n * gap 1). Function-valued initializers (arrow functions / function expressions) are\n * excluded: they are already indexed as functions via `functions`. */\n variables?: Array<{\n name: string;\n startLine: number;\n endLine: number;\n contentHash?: string;\n }>;\n calls: Array<{\n sourceFunction: string;\n targetFunction: string;\n /** 0-based source position of the call-site's callee expression start (matches Tier A's own\n * `startLine`/`startPosition` convention). The seed Tier B forward resolution (issue #11\n * plan A, Slice 2) issues `textDocument/definition` at this position per call site to\n * resolve the callee precisely -- see\n * forward-tier-b-edge-resolution-plan.md Slice 1. */\n startLine: number;\n startColumn: number;\n /** Issue #192 decomposition of the callee expression -- see `getCalleeEvidence`. */\n calleeName?: string;\n receiverText?: string;\n calleeKind?: \"bare\" | \"member\" | \"this\" | \"arg-chain\" | \"computed\";\n }>;\n implements?: Array<{ sourceClass: string; targetInterface: string }>;\n extends?: Array<{ sourceClass: string; targetClass: string }>;\n /**\n * `new Worker(<path>)` spawn sites (TS/JS only — see `WORKER_SPAWN_LANGUAGES`), one per\n * resolved spawn call, attributing it to its enclosing function like `calls` does.\n * `persist-ast-graph.ts` resolves `targetPath` to a real file and inserts a `DEPENDS_ON`\n * edge from it — the fix for the `ast-worker-pool.ts` -> `ast-worker.ts` false-negative\n * blast-radius gap (dynamic `worker_threads` spawns are invisible to the static\n * imports/calls pipeline, since the target script is a runtime path string, not a static\n * `import`).\n */\n workerSpawns?: Array<{ sourceFunction: string; targetPath: string }>;\n decisions?: string[];\n };\n}\n\nlet parserInitialized = false;\nlet registryPromise: Promise<LanguageRegistry> | null = null;\n\nfunction getRegistry(): Promise<LanguageRegistry> {\n registryPromise ??= loadDefaultRegistry();\n return registryPromise;\n}\n\n// Worker-lifetime cache for loaded tree-sitter grammars, keyed by the resolved wasmPath\n// (deterministic per language -- see resolveWasmPath()). Language.load() is a real WASM\n// dynamic-library load (WebAssembly.instantiate + relocation into the shared runtime's\n// Table/Memory), not a cheap call -- reloading the same grammar per file (the pre-existing\n// behavior) is pure waste once a worker has already loaded it once. Mirrors registryPromise's\n// own memoization shape immediately above. web-tree-sitter's Language class has no\n// delete()/dispose method (verified against the installed 0.25.10 type defs), so there is\n// nothing to release even if this cache were bounded -- see\n// docs/ai_plans/implement_wasm-language-load-cache.md §2.1 for the full check.\nconst languageCache = new Map<string, Promise<Language>>();\n\nfunction getLanguage(wasmPath: string): Promise<Language> {\n let cached = languageCache.get(wasmPath);\n if (!cached) {\n cached = Language.load(wasmPath);\n languageCache.set(wasmPath, cached);\n }\n return cached;\n}\n\n/**\n * Re-exported for backward compatibility (existing importer: `ast-worker.fixture.unit.test.ts`)\n * — the real implementation moved to `resolve-wasm-path.ts` so it can also be imported from the\n * main thread (by `SemanticDiffAnalyzerService`) without pulling in this file's\n * `worker_threads`-only side effects (`parentPort?.on(...)`, process-level\n * `uncaughtException`/`unhandledRejection` handlers). See that file's doc comment for why.\n */\nexport { resolveWasmPath };\n\n/** Regex fallback for imports so graph edges still work when WASM fails to load (e.g. in tests). */\nfunction extractFallbackImports(code: string): ImportDescriptor[] {\n const fallbackImports: ImportDescriptor[] = [];\n const importMatches = code.matchAll(\n /import\\s+{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n );\n for (const match of importMatches) {\n fallbackImports.push({\n localName: match[1].trim(),\n originalName: match[1].trim(),\n modulePath: match[2],\n });\n }\n return fallbackImports;\n}\n\nfunction getNodeName(node: Node): string {\n return (\n node.childForFieldName(\"name\")?.text ||\n node.descendantsOfType(\"identifier\")[0]?.text ||\n AstMessages.ANONYMOUS_NAME\n );\n}\n\n/**\n * For anonymous callables (arrow_function/function_expression with no own name), resolve\n * the binding name from the nearest enclosing variable_declarator / assignment_expression /\n * pair (object property) / public_field_definition (class field arrow method). Returns\n * \"anonymous\" for truly unbound cases (IIFEs, bare callback arguments).\n *\n * Named nodes (function_declaration, method_definition) already have a \"name\" field, so the\n * fast path below returns the same result getNodeName() would — safe to use uniformly for\n * every function-kind node, not just anonymous ones.\n *\n * GRPH-006 follow-up: C/C++'s `function_definition` has no direct \"name\" field at all — the name\n * sits two levels down, inside `function_declarator`'s own \"declarator\" field (`identifier` for a\n * free function, `field_identifier` for an inline method, `qualified_identifier` -- scope::name --\n * for an out-of-line one). Verified this was silently returning \"anonymous\" for every C/C++\n * function before this fix (never previously observed for C++ specifically because\n * `cppConfig`'s functions query didn't even extract methods until the GRPH-006 follow-up fix to\n * `cpp.ts` — this pass surfaced both bugs together).\n */\n/** GRPH-006 follow-up: resolves a C/C++ `function_definition`'s name from its declarator-nested\n * shape (see `resolveCallableName`'s own doc comment) -- `identifier`/`field_identifier` return\n * their own text directly, `qualified_identifier` (an out-of-line `Class::method`) returns just\n * its `name` field, not the qualifier. Extracted purely to keep `resolveCallableName`'s own\n * complexity within budget. */\nfunction resolveDeclaratorNestedName(node: Node): string | undefined {\n const declaratorName = node\n .childForFieldName(\"declarator\")\n ?.childForFieldName(\"declarator\");\n if (!declaratorName) return undefined;\n return declaratorName.type === AstNodeTypes.QUALIFIED_IDENTIFIER\n ? (declaratorName.childForFieldName(\"name\")?.text ??\n AstMessages.ANONYMOUS_NAME)\n : declaratorName.text;\n}\n\nexport function resolveCallableName(node: Node): string {\n const ownName = node.childForFieldName(\"name\");\n if (ownName) return ownName.text;\n\n const declaratorName = resolveDeclaratorNestedName(node);\n if (declaratorName) return declaratorName;\n\n const NAME_BEARING_PARENTS = new Set<string>([\n AstNodeTypes.VARIABLE_DECLARATOR,\n AstNodeTypes.ASSIGNMENT_EXPRESSION,\n AstNodeTypes.PAIR,\n AstNodeTypes.PUBLIC_FIELD_DEFINITION,\n ]);\n let current = node.parent;\n while (current) {\n // An \"arguments\" ancestor means this callable is itself passed as a call argument\n // (e.g. arr.map(x => x + 1)) rather than being the direct value of a declarator/\n // assignment/property/field. Stop here — climbing further would misattribute the\n // name of the outer binding the call happens to live inside (e.g. `results` in\n // `const results = arr.map(x => x + 1)`) to this unrelated, unbound callback.\n if (current.type === AstNodeTypes.ARGUMENTS) break;\n if (NAME_BEARING_PARENTS.has(current.type)) {\n const nameNode =\n current.childForFieldName(\"name\") ||\n current.childForFieldName(\"key\") ||\n current.childForFieldName(\"left\");\n if (nameNode) return nameNode.text;\n }\n current = current.parent;\n }\n return AstMessages.ANONYMOUS_NAME;\n}\n\n/**\n * Normalizes the many capture shapes the per-language `calls` queries produce into \"the\n * callee expression\":\n * - TS/JS/Go/Rust/C++/Python capture the callee expression *directly* (`@call` sits on the\n * bracketed `[identifier | member_expression]` alternation inside `function:`), so the\n * captured node IS the callee -- it carries none of the fields below and falls through to\n * itself.\n * - Ruby (`method:`), Java (`name:`), PHP (`name:`) capture the bare callee identifier field.\n * - C# captures whole call nodes (`invocation_expression` / `object_creation_expression`),\n * which need unwrapping to their `expression:` / `type:` child.\n */\nfunction unwrapToCalleeExpression(node: Node): Node {\n return (\n node.childForFieldName(\"function\") ||\n node.childForFieldName(\"expression\") || // C# invocation_expression\n node.childForFieldName(\"type\") || // C# object_creation_expression (`new Foo()` -> Foo)\n node.childForFieldName(\"name\") ||\n node.childForFieldName(\"method\") ||\n node\n );\n}\n\n/**\n * Issue #192 root-cause fix: decomposes a call site's callee into the evidence name-based\n * resolution actually needs, instead of persisting one opaque raw string. `target_function`\n * keeps carrying the (whitespace-normalized) full expression for Tier B seeding and #217's\n * impact fallback; the decomposition answers:\n *\n * - `calleeName` — terminal callee identifier (`doSomething` of `service.doSomething()`),\n * what ScopeResolver's bare-name model matches against. Before this change the raw string\n * including the receiver was persisted, making every OOP-style call structurally\n * unmatchable -- the single largest cause of the ~12.8% distinct-target resolution rate.\n * - `receiverText` — receiver expression (`service`, `this.logger`), kept as evidence for\n * import-binding receiver resolution (ScopeResolver.resolveMemberCall).\n * - `calleeKind` — shape classifier. `'arg-chain'` (receiver is itself an invocation result,\n * e.g. `expect(x).toEqual`, `vi.fn().mockResolvedValue`) and `'computed'` (`obj[expr]()`)\n * are structurally unresolvable by name matching; classifying them lets the health-rate\n * denominators exclude them instead of counting them as failures (~51% of the unresolved\n * distinct targets in this repo's own graph were arg-chain junk from mock chains).\n *\n * Language-generic by construction: for any `receiver.callee` shape the callee expression's\n * rightmost named child is the callee identifier and the second-to-last is the receiver\n * (TS/JS nested `member_expression`, Go `selector_expression`, Rust/C++ `field_expression`,\n * Python `attribute`). A bare identifier has no usable second child -> `'bare'`.\n */\nexport function getCalleeEvidence(node: Node): {\n targetFunction: string;\n calleeName?: string;\n receiverText?: string;\n calleeKind?: \"bare\" | \"member\" | \"this\" | \"arg-chain\" | \"computed\";\n} {\n const callee = unwrapToCalleeExpression(node);\n\n const children = callee.namedChildren;\n const terminal = children[children.length - 1];\n const receiver =\n children.length >= 2 ? children[children.length - 2] : undefined;\n\n // Bare identifier call (`foo()`), or a grammar whose query already captured the callee\n // identifier directly (Java `name:`, PHP `name:`, Ruby `method:`).\n if (!terminal || !receiver) {\n return {\n targetFunction: normalizeCallText(callee.text),\n calleeName: callee.text,\n calleeKind: \"bare\",\n };\n }\n\n if (!CALLEE_IDENTIFIER_NODE_TYPES.has(terminal.type)) {\n // Computed access (`obj[expr]()`) -- no static callee name to match on.\n return {\n targetFunction: normalizeCallText(callee.text),\n calleeKind: \"computed\",\n };\n }\n\n const calleeName = terminal.text;\n const receiverText = receiver.text;\n\n // Invocation-result receivers (`expect(x).toEqual`, `vi.fn().mockResolvedValue`,\n // `new Date().toISOString`) -- the receiver's runtime type is the call's return value,\n // unknowable by name matching. A '(' anywhere in the receiver text catches both direct\n // call receivers and deeper chains (`vi.fn().mock.calls[0]`) in one conservative test.\n if (receiverText.includes(\"(\")) {\n return {\n targetFunction: normalizeCallText(callee.text),\n calleeName,\n receiverText,\n calleeKind: \"arg-chain\",\n };\n }\n\n return {\n targetFunction: normalizeCallText(callee.text),\n calleeName,\n receiverText,\n calleeKind:\n receiverText === \"this\" || receiverText === \"super\" ? \"this\" : \"member\",\n };\n}\n\n/** Collapses insignificant whitespace so multi-line call expressions\n * (`vi\\n .fn()`) persist as one comparable string instead of newline-laced junk\n * that no exact-match consumer (#217's impact fallback) could ever hit. */\nfunction normalizeCallText(text: string): string {\n return text.replace(/\\s+/g, \"\");\n}\n\nconst CALLEE_IDENTIFIER_NODE_TYPES = new Set([\n \"identifier\",\n \"property_identifier\",\n \"field_identifier\",\n \"shorthand_property_identifier\",\n \"attribute\",\n]);\n\n/** Resolves a call-site's *seed position* for Tier B forward resolution (issue #11 plan A,\n * Finding C): for a bare identifier call (`foo()`), `node` already *is* the identifier and its\n * own `startPosition` is correct. But for a compound callee -- JS/TS `member_expression`\n * (`service.doSomething()`), Go `selector_expression`, C++/Rust `field_expression` -- the\n * `calls` tree-sitter query (see `lib/ast-core/src/languages/*.ts`) captures the *whole*\n * expression, whose own `startPosition` sits on the receiver (`service`), not the callee\n * (`doSomething`). `textDocument/definition` must be issued at the callee's own position, or it\n * resolves the receiver's declaration instead -- an invented edge (IMPT-002). Verified against\n * real tree-sitter-typescript output (`property` is the correct field name for\n * `member_expression`, confirmed via a real parse, not assumed) -- see this plan's own\n * instruction not to copy field names blind.\n *\n * No-op (falls through to `node.startPosition`, i.e. itself) for languages whose query already\n * captures the callee identifier directly (Java `name:`, PHP `name:`, Ruby `method:`) or for a\n * bare identifier call. */\nfunction getCallSitePosition(node: Node): { row: number; column: number } {\n const calleeIdentifier =\n node.childForFieldName(\"property\") || // JS/TS member_expression\n node.childForFieldName(\"field\") || // Go selector_expression / C++/Rust field_expression\n node.childForFieldName(\"attribute\") || // Python attribute\n node.childForFieldName(\"name\") || // defensive; Java/PHP already capture this directly\n node.childForFieldName(\"method\"); // defensive; Ruby already captures this directly\n return (calleeIdentifier ?? node).startPosition;\n}\n\n/** Walks up from `node` to find the nearest ancestor present in `containerIds` (function/class nodes already extracted for this file), returning its name, or \"anonymous\" for top-level (file-scoped) call/implements/extends sites. */\nfunction findEnclosingContainerName(\n node: Node,\n containerIds: Set<number>,\n): string {\n let current = node.parent;\n while (current) {\n if (containerIds.has(current.id)) {\n return getNodeName(current);\n }\n current = current.parent;\n }\n return AstMessages.ANONYMOUS_NAME;\n}\n\n/** Resolves the base type name whether `node` is itself a `type_identifier` or wraps one one level\n * deep -- Rust generic impls (`impl<T> Wrapper<T>` -- field is `generic_type`) and Go pointer\n * receivers (`*Receiver` -- field is `pointer_type`) both need the unwrap; a plain `type_identifier`\n * field (the common case) is returned as-is. */\nfunction firstTypeIdentifierText(node: Node): string | undefined {\n return node.type === AstNodeTypes.TYPE_IDENTIFIER\n ? node.text\n : node.descendantsOfType(AstNodeTypes.TYPE_IDENTIFIER)[0]?.text;\n}\n\n/** GRPH-006 follow-up (Rust): a method's lexical parent is `impl_item`, which `rustConfig.classes`\n * deliberately excludes (so `findEnclosingContainerName` over `classIds` always returns\n * \"anonymous\" for a Rust method) -- the target struct/enum's name lives on the impl block's own\n * `type` field instead (the Self type, not `trait` -- `impl Trait for Type` still qualifies by\n * `Type`, the concrete struct, not whichever trait it happens to implement). */\nfunction resolveRustImplContainerName(node: Node): string | undefined {\n let current = node.parent;\n while (current) {\n if (current.type === AstNodeTypes.IMPL_ITEM) {\n const typeField = current.childForFieldName(\"type\");\n return typeField ? firstTypeIdentifierText(typeField) : undefined;\n }\n current = current.parent;\n }\n return undefined;\n}\n\n/** GRPH-006 follow-up (Go): a method's receiver type is referenced through its own `receiver:`\n * field, never as an AST ancestor (`type_declaration` never encloses a `method_declaration`), so\n * `findEnclosingContainerName` over `classIds` always returns \"anonymous\" here too -- resolve the\n * receiver parameter's type directly instead. */\nfunction resolveGoReceiverContainerName(node: Node): string | undefined {\n const receiver = node.childForFieldName(\"receiver\");\n const paramType = receiver?.namedChild(0)?.childForFieldName(\"type\");\n return paramType ? firstTypeIdentifierText(paramType) : undefined;\n}\n\n/** GRPH-006 follow-up (C++): an out-of-line `Ret Class::method(){}` definition is never lexically\n * nested inside its class (inline methods already resolve via the generic ancestor walk once\n * they're extracted at all -- see `cpp.ts`'s functions-query fix), so its declarator is a\n * `qualified_identifier` carrying the class name in its own `scope` field instead. Recurses one\n * level for a nested qualifier (`A::B::method`), taking the innermost (`B`) as the immediate\n * container -- this scheme only ever tracks one level of containment, matching every other\n * language here. */\nfunction resolveCppQualifiedContainerName(node: Node): string | undefined {\n const declarator = node.childForFieldName(\"declarator\");\n const inner = declarator?.childForFieldName(\"declarator\");\n if (inner?.type !== AstNodeTypes.QUALIFIED_IDENTIFIER) return undefined;\n const scope = inner.childForFieldName(\"scope\");\n if (!scope) return undefined;\n return scope.type === AstNodeTypes.QUALIFIED_IDENTIFIER\n ? scope.childForFieldName(\"name\")?.text\n : scope.text;\n}\n\n/** GRPH-006 follow-up: for a function whose enclosing container the generic ancestor walk\n * couldn't find (Rust/Go/C++'s deferred gaps -- see the ADR), try each language-specific\n * resolver in turn. Mutually exclusive by construction (each checks for a node shape only its own\n * grammar produces -- e.g. only Rust ever has an `impl_item` ancestor), so no explicit language\n * tag is needed; a language not covered here (or a function with no enclosing container at all)\n * falls through to `undefined`, unchanged from before this follow-up. */\nfunction resolveDeferredLanguageContainerName(node: Node): string | undefined {\n return (\n resolveRustImplContainerName(node) ??\n resolveGoReceiverContainerName(node) ??\n resolveCppQualifiedContainerName(node)\n );\n}\n\n/** Shape of a fully-populated `AstParseResponse[\"data\"]` (i.e. the non-optional variant produced once parsing has actually run). */\ntype AstExtractionResult = NonNullable<AstParseResponse[\"data\"]>;\n\n/** Extracts class declaration nodes via the provider and appends their summaries to `classes`. Returns the raw nodes so callers can derive id sets for edge extraction. */\nfunction collectClassNodes(\n tree: Tree,\n provider: LanguageProvider,\n classes: AstExtractionResult[\"classes\"],\n): Node[] {\n const classNodes = provider.extractClasses(tree.rootNode);\n for (const node of classNodes) {\n classes.push({\n name: getNodeName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n methods: [],\n contentHash: symbolContentHash(node),\n });\n }\n return classNodes;\n}\n\n/**\n * Extracts exported variable declarators via the provider and appends their summaries to\n * `variables` (issue #192 gap 1: `export const X = ...` must be an indexable symbol so\n * `impact <X>` resolves instead of \"No matching node\"). The query only matches exported\n * `lexical_declaration` declarators with plain identifier names; this collector additionally\n * skips function-valued initializers (arrow_function/function_expression) since those are\n * already indexed as functions by the `functions` query + resolveCallableName path.\n */\nconst FUNCTION_VALUE_NODE_TYPES = new Set<string>([\n \"arrow_function\",\n \"function_expression\",\n]);\n\nfunction collectVariableNodes(\n tree: Tree,\n provider: LanguageProvider,\n variables: NonNullable<AstExtractionResult[\"variables\"]>,\n): Node[] {\n const variableNodes = provider.extractVariables?.(tree.rootNode) ?? [];\n for (const node of variableNodes) {\n const value = node.childForFieldName(\"value\");\n if (value && FUNCTION_VALUE_NODE_TYPES.has(value.type)) continue;\n variables.push({\n name: getNodeName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n contentHash: symbolContentHash(node),\n });\n }\n return variableNodes;\n}\n\n/** Extracts function/method declaration nodes via the provider and appends their summaries to `functions`. Returns the raw nodes so callers can derive id sets for edge extraction.\n *\n * `classNodes` (GRPH-006) lets each function's enclosing class/struct be resolved via the same\n * `findEnclosingContainerName` ancestor walk `collectCallEdges`/`collectImplementsEdges`/\n * `collectExtendsEdges` already use -- `containerName` is what qualifies this symbol's `node_key`\n * down the line (`persist-ast-graph.ts`'s `buildQualifiedBaseKey`). `findEnclosingContainerName`'s\n * \"nothing found\" sentinel is the literal string `AstMessages.ANONYMOUS_NAME` (\"anonymous\") --\n * that means \"top-level, outside any class\" here, a different meaning than its existing use in\n * `collectCallEdges` (\"outside any function\"), so it must be converted to `undefined` rather than\n * stored as-is (storing it as-is would qualify every top-level function as `file#anonymous.name`).\n *\n * When the ancestor walk finds nothing, `resolveDeferredLanguageContainerName` (GRPH-006\n * follow-up) tries Rust/Go/C++'s own non-lexical containment shapes before giving up to\n * `undefined` -- see that function's own doc comment for why each needs a different mechanism. */\nexport function collectFunctionNodes(\n tree: Tree,\n provider: LanguageProvider,\n functions: AstExtractionResult[\"functions\"],\n classNodes: Node[],\n): Node[] {\n const classIds = new Set(classNodes.map((n) => n.id));\n const functionNodes = provider.extractFunctions(tree.rootNode);\n for (const node of functionNodes) {\n const container = findEnclosingContainerName(node, classIds);\n const containerName =\n container === AstMessages.ANONYMOUS_NAME\n ? resolveDeferredLanguageContainerName(node)\n : container;\n functions.push({\n name: resolveCallableName(node),\n startLine: node.startPosition.row,\n endLine: node.endPosition.row,\n contentHash: symbolContentHash(node),\n containerName,\n });\n }\n return functionNodes;\n}\n\n/** Extracts call-site edges via the provider, attributing each call to its enclosing function (or \"anonymous\"), up to the 1000-call circuit breaker. */\nfunction collectCallEdges(\n tree: Tree,\n provider: LanguageProvider,\n functionNodes: Node[],\n calls: AstExtractionResult[\"calls\"],\n): void {\n const functionIds = new Set(functionNodes.map((n) => n.id));\n const callNodes = provider.extractCalls(tree.rootNode);\n for (const node of callNodes) {\n if (calls.length >= 1000) break; // Circuit breaker limit\n const position = getCallSitePosition(node);\n const evidence = getCalleeEvidence(node);\n calls.push({\n sourceFunction: findEnclosingContainerName(node, functionIds),\n targetFunction: evidence.targetFunction,\n startLine: position.row,\n startColumn: position.column,\n calleeName: evidence.calleeName,\n receiverText: evidence.receiverText,\n calleeKind: evidence.calleeKind,\n });\n }\n}\n\n/** Extracts `implements` edges via the provider, if it supports them, attributing each to its enclosing class. */\nfunction collectImplementsEdges(\n tree: Tree,\n provider: LanguageProvider,\n classNodes: Node[],\n implementsList: NonNullable<AstExtractionResult[\"implements\"]>,\n): void {\n if (!provider.extractImplements) return;\n const classIds = new Set(classNodes.map((n) => n.id));\n for (const node of provider.extractImplements(tree.rootNode)) {\n implementsList.push({\n sourceClass: findEnclosingContainerName(node, classIds),\n targetInterface: node.text,\n });\n }\n}\n\n/** Extracts `extends` edges via the provider, if it supports them, attributing each to its enclosing class. */\nfunction collectExtendsEdges(\n tree: Tree,\n provider: LanguageProvider,\n classNodes: Node[],\n extendsList: NonNullable<AstExtractionResult[\"extends\"]>,\n): void {\n if (!provider.extractExtends) return;\n const classIds = new Set(classNodes.map((n) => n.id));\n for (const node of provider.extractExtends(tree.rootNode)) {\n extendsList.push({\n sourceClass: findEnclosingContainerName(node, classIds),\n targetClass: node.text,\n });\n }\n}\n\n/** Languages `collectWorkerSpawns` runs against — the reported gap (a `new Worker(...)` spawn\n * invisible to the static imports/calls pipeline) is TS/JS-specific: `new_expression` is also a\n * real C++ grammar node (the `new` operator), so gating by language avoids misinterpreting an\n * unrelated `new Worker(...)` construction in another language as a worker_threads spawn. */\nconst WORKER_SPAWN_LANGUAGES: ReadonlySet<SupportedLanguage> = new Set([\n SUPPORTED_LANGUAGES.TYPESCRIPT,\n SUPPORTED_LANGUAGES.JAVASCRIPT,\n]);\n\nconst WORKER_CONSTRUCTOR_NAME = \"Worker\";\nconst PATH_MODULE_OBJECT_NAME = \"path\";\nconst PATH_RESOLVE_METHOD_NAME = \"resolve\";\nconst PATH_JOIN_METHOD_NAME = \"join\";\nconst DIRNAME_IDENTIFIER_NAME = \"__dirname\";\n\n/** True when `node` is a `path.resolve(...)`/`path.join(...)` call expression — the exact idiom\n * `ast-worker-pool.ts` uses to build a worker script's path from `__dirname`. */\nfunction isPathJoinOrResolveCall(node: Node): boolean {\n if (node.type !== \"call_expression\") return false;\n const fn = node.childForFieldName(\"function\");\n if (!fn || fn.type !== \"member_expression\") return false;\n const object = fn.childForFieldName(\"object\")?.text;\n const property = fn.childForFieldName(\"property\")?.text;\n return (\n object === PATH_MODULE_OBJECT_NAME &&\n (property === PATH_RESOLVE_METHOD_NAME ||\n property === PATH_JOIN_METHOD_NAME)\n );\n}\n\n/** Extracts the string-literal path segment from a `path.resolve(__dirname, \"<literal>\")` /\n * `path.join(__dirname, \"<literal>\")` call, or undefined if it doesn't reference `__dirname` or\n * carries no string-literal argument. */\nfunction extractDirnameJoinedLiteral(callNode: Node): string | undefined {\n const args = callNode.childForFieldName(\"arguments\");\n if (!args) return undefined;\n const hasDirname = args.namedChildren.some(\n (n) => n?.type === \"identifier\" && n.text === DIRNAME_IDENTIFIER_NAME,\n );\n if (!hasDirname) return undefined;\n const literal = args.descendantsOfType(\"string\")[0];\n return literal?.text.replace(/['\"]/g, \"\");\n}\n\n/** Bounded same-file scan for `<argText> = path.resolve/join(__dirname, \"<literal>\")` — the\n * exact idiom `ast-worker-pool.ts` uses for `this.wPath = path.resolve(__dirname, \"./ast-worker.js\")`,\n * needed because the `new Worker(...)` call site references the field/variable, not the literal,\n * directly. Matches by comparing the assignment's own left-hand-side text against `argText`\n * verbatim (e.g. both \"this.wPath\"), so it works uniformly whether the argument is a bare\n * identifier or a member expression. */\nfunction findDirnameJoinedAssignment(\n tree: Tree,\n argText: string,\n): string | undefined {\n for (const assignment of tree.rootNode.descendantsOfType(\n AstNodeTypes.ASSIGNMENT_EXPRESSION,\n )) {\n if (!assignment) continue;\n const left = assignment.childForFieldName(\"left\");\n const right = assignment.childForFieldName(\"right\");\n if (left?.text !== argText || !right || !isPathJoinOrResolveCall(right)) {\n continue;\n }\n const literal = extractDirnameJoinedLiteral(right);\n if (literal) return literal;\n }\n return undefined;\n}\n\n/** Resolves `new Worker(<arg>)`'s first argument to a literal relative path: a direct string\n * literal, or a same-file `path.resolve/join(__dirname, \"<literal>\")`-assigned field/variable\n * (the `ast-worker-pool.ts` idiom, via `findDirnameJoinedAssignment`). Returns undefined —\n * skip silently, no guessing — when neither shape matches. */\nfunction resolveWorkerArgumentPath(\n tree: Tree,\n argNode: Node,\n): string | undefined {\n if (argNode.type === \"string\") {\n return argNode.text.replace(/['\"]/g, \"\");\n }\n if (argNode.type === \"identifier\" || argNode.type === \"member_expression\") {\n return findDirnameJoinedAssignment(tree, argNode.text);\n }\n return undefined;\n}\n\n/** Extracts `new Worker(<arg>)` spawn sites (TS/JS only, see `WORKER_SPAWN_LANGUAGES`) and\n * appends a `{sourceFunction, targetPath}` descriptor for each one whose argument resolves to a\n * literal relative path (`resolveWorkerArgumentPath`), attributing it to its enclosing function\n * like `collectCallEdges` does. `persist-ast-graph.ts` resolves `targetPath` to a real file and\n * inserts the corresponding `DEPENDS_ON` edge. */\nexport function collectWorkerSpawns(\n tree: Tree,\n language: SupportedLanguage,\n functionNodes: Node[],\n workerSpawns: NonNullable<AstExtractionResult[\"workerSpawns\"]>,\n): void {\n if (!WORKER_SPAWN_LANGUAGES.has(language)) return;\n const functionIds = new Set(functionNodes.map((n) => n.id));\n for (const node of tree.rootNode.descendantsOfType(\"new_expression\")) {\n if (!node) continue;\n const ctor = node.childForFieldName(\"constructor\");\n if (ctor?.text !== WORKER_CONSTRUCTOR_NAME) continue;\n const args = node.childForFieldName(\"arguments\");\n const firstArg = args?.namedChildren.find((n): n is Node => n !== null);\n if (!firstArg) continue;\n const targetPath = resolveWorkerArgumentPath(tree, firstArg);\n if (!targetPath) continue;\n workerSpawns.push({\n sourceFunction: findEnclosingContainerName(node, functionIds),\n targetPath,\n });\n }\n}\n\n/**\n * Runs every provider-driven extraction against a parsed tree (or returns empty results plus a\n * decision note if parsing produced no tree). A single try/catch wraps the whole pass, matching\n * the original inline behavior of recording a `providerQueryFailed` decision instead of throwing\n * when any one extractor misbehaves.\n */\nfunction extractAstData(\n tree: Tree | null,\n provider: LanguageProvider,\n language: SupportedLanguage,\n): AstExtractionResult {\n const decisions: string[] = [];\n const imports: ImportDescriptor[] = [];\n const exports: AstExtractionResult[\"exports\"] = [];\n const functions: AstExtractionResult[\"functions\"] = [];\n const classes: AstExtractionResult[\"classes\"] = [];\n const variables: NonNullable<AstExtractionResult[\"variables\"]> = [];\n const calls: AstExtractionResult[\"calls\"] = [];\n const implementsList: NonNullable<AstExtractionResult[\"implements\"]> = [];\n const extendsList: NonNullable<AstExtractionResult[\"extends\"]> = [];\n const workerSpawns: NonNullable<AstExtractionResult[\"workerSpawns\"]> = [];\n\n if (tree) {\n decisions.push(AstMessages.parsedViaTreeSitter(tree.rootNode.childCount));\n\n try {\n const classNodes = collectClassNodes(tree, provider, classes);\n const functionNodes = collectFunctionNodes(\n tree,\n provider,\n functions,\n classNodes,\n );\n\n const importNodes = provider.extractImports(tree.rootNode);\n imports.push(...parseImportDescriptors(importNodes));\n\n collectVariableNodes(tree, provider, variables);\n\n collectCallEdges(tree, provider, functionNodes, calls);\n collectImplementsEdges(tree, provider, classNodes, implementsList);\n collectExtendsEdges(tree, provider, classNodes, extendsList);\n collectWorkerSpawns(tree, language, functionNodes, workerSpawns);\n\n decisions.push(AstMessages.QUERIED_VIA_LANGUAGE_PROVIDER);\n } catch (e) {\n decisions.push(\n AstMessages.providerQueryFailed(\n e instanceof Error ? e.message : String(e),\n ),\n );\n }\n }\n\n return {\n imports,\n exports,\n functions,\n classes,\n variables,\n calls,\n implements: implementsList,\n extends: extendsList,\n workerSpawns,\n decisions,\n };\n}\n\n/** Logs any query pattern that failed to compile, then clears them so a later file of the same\n * language doesn't re-report the same failure. Drained rather than read because the provider is\n * reused for the worker's whole lifetime.\n *\n * Exported for the wiring test: the module-scoped `logger` posts to `parentPort`, which is\n * null outside a real worker, so this path is otherwise unobservable (same reason\n * `buildParseResponse` is exported). */\nexport function reportQueryCompileFailures(\n provider: LanguageProvider,\n language: SupportedLanguage,\n): void {\n for (const failure of provider.drainQueryCompileFailures?.() ?? []) {\n logger.error(AstMessages.QUERY_COMPILE_FAILED, {\n language,\n kind: failure.kind,\n pattern: failure.pattern,\n message: failure.message,\n });\n }\n}\n\n/** Parses `request.code` with the resolved provider/grammar and runs the full AST extraction pass, releasing the tree-sitter tree/parser handles once done. */\nfunction parseAndExtract(\n code: string,\n provider: LanguageProvider,\n langInstance: Language,\n language: SupportedLanguage,\n): AstExtractionResult {\n const parser = new Parser();\n parser.setLanguage(langInstance);\n\n // initQueries() is idempotent (DefaultProvider caches compiledQueries after the first call)\n // and the provider instance is reused for every file of this language for the worker's whole\n // lifetime (see getRegistry() above), so this only actually compiles once. A field whose\n // pattern fails to compile against the installed grammar degrades to that field's\n // descendantsOfType fallback (DefaultProvider.compileQuery) rather than throwing.\n provider.initQueries?.(langInstance);\n reportQueryCompileFailures(provider, language);\n\n const tree = parser.parse(code);\n const data = extractAstData(tree, provider, language);\n\n if (tree) tree.delete();\n parser.delete();\n\n return data;\n}\n\n/**\n * Resolves a language provider for `request.filePath` and produces the full parse response,\n * short-circuiting with an empty-but-successful result (plus an explanatory decision note) when\n * no provider is registered for the extension or its wasm grammar can't be located on disk.\n */\nexport async function buildParseResponse(\n request: AstParseRequest,\n): Promise<AstParseResponse> {\n if (!parserInitialized) {\n await Parser.init();\n parserInitialized = true;\n }\n\n const registry = await getRegistry();\n const ext = path.extname(request.filePath);\n const provider: LanguageProvider | undefined =\n registry.getProviderForExtension(ext);\n\n if (!provider) {\n return {\n taskId: request.taskId,\n success: true,\n data: {\n imports: [],\n exports: [],\n functions: [],\n classes: [],\n calls: [],\n decisions: [AstMessages.noLanguageProviderForExtension(ext)],\n },\n };\n }\n\n const { wasmPath, attemptedPaths } = resolveWasmPath(provider.wasm_file);\n\n if (!fs.existsSync(wasmPath)) {\n return {\n taskId: request.taskId,\n success: true,\n data: {\n imports: extractFallbackImports(request.code),\n exports: [],\n functions: [],\n classes: [],\n calls: [],\n decisions: [\n AstMessages.wasmNotFound(request.language, attemptedPaths.join(\", \")),\n ],\n },\n };\n }\n\n const langInstance = await getLanguage(wasmPath);\n const data = parseAndExtract(\n request.code,\n provider,\n langInstance,\n request.language,\n );\n\n return {\n taskId: request.taskId,\n success: true,\n data,\n };\n}\n\nparentPort?.on(\"message\", async (request: AstParseRequest) => {\n try {\n const response = await buildParseResponse(request);\n parentPort?.postMessage(response);\n } catch (err: any) {\n parentPort?.postMessage({\n taskId: request.taskId,\n success: false,\n error: err.stack || String(err),\n });\n }\n});\n"],"mappings":";mJAAA,OAAS,cAAAA,MAAkB,iBAC3B,OAAS,UAAAC,EAAQ,YAAAC,MAAsC,kBACvD,UAAYC,MAAU,OACtB,UAAYC,MAAQ,KACpB,OAAS,cAAAC,MAAkB,SA6B3B,SAASC,EAAkBC,EAAoB,CAC7C,OAAOC,EAAWC,CAAgB,EAAE,OAAOF,EAAK,IAAI,EAAE,OAAO,KAAY,CAC3E,CAWA,IAAMG,EAAS,IAAIC,EAAiBC,GAClCC,GAAY,YAAYD,CAAO,CAC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,MAAMC,EAAY,EAC7BC,EAAW,UAAQJ,EAAQ,QAAQ,EACnCrE,EACJuE,EAAS,wBAAwBE,CAAG,EAEtC,GAAI,CAACzE,EACH,MAAO,CACL,OAAQqE,EAAQ,OAChB,QAAS,GACT,KAAM,CACJ,QAAS,CAAC,EACV,QAAS,CAAC,EACV,UAAW,CAAC,EACZ,QAAS,CAAC,EACV,MAAO,CAAC,EACR,UAAW,CAACvG,EAAY,+BAA+B2G,CAAG,CAAC,CAC7D,CACF,EAGF,GAAM,CAAE,SAAAC,EAAU,eAAAC,CAAe,EAAIC,EAAgB5E,EAAS,SAAS,EAEvE,GAAI,CAAI,aAAW0E,CAAQ,EACzB,MAAO,CACL,OAAQL,EAAQ,OAChB,QAAS,GACT,KAAM,CACJ,QAAS9G,EAAuB8G,EAAQ,IAAI,EAC5C,QAAS,CAAC,EACV,UAAW,CAAC,EACZ,QAAS,CAAC,EACV,MAAO,CAAC,EACR,UAAW,CACTvG,EAAY,aAAauG,EAAQ,SAAUM,EAAe,KAAK,IAAI,CAAC,CACtE,CACF,CACF,EAGF,IAAMX,EAAe,MAAMa,EAAYH,CAAQ,EACzCP,EAAOJ,GACXM,EAAQ,KACRrE,EACAgE,EACAK,EAAQ,QACV,EAEA,MAAO,CACL,OAAQA,EAAQ,OAChB,QAAS,GACT,KAAAF,CACF,CACF,CAEAW,GAAY,GAAG,UAAW,MAAOT,GAA6B,CAC5D,GAAI,CACF,IAAMU,EAAW,MAAMX,GAAmBC,CAAO,EACjDS,GAAY,YAAYC,CAAQ,CAClC,OAASC,EAAU,CACjBF,GAAY,YAAY,CACtB,OAAQT,EAAQ,OAChB,QAAS,GACT,MAAOW,EAAI,OAAS,OAAOA,CAAG,CAChC,CAAC,CACH,CACF,CAAC","names":["parentPort","Parser","Language","path","fs","createHash","symbolContentHash","node","createHash","HASH_ALGO_SHA256","logger","IpcLoggerClient","message","parentPort","err","AstMessages","parserInitialized","registryPromise","getRegistry","loadDefaultRegistry","languageCache","getLanguage","wasmPath","cached","Language","extractFallbackImports","code","fallbackImports","importMatches","match","getNodeName","node","AstMessages","resolveDeclaratorNestedName","declaratorName","AstNodeTypes","resolveCallableName","ownName","NAME_BEARING_PARENTS","current","nameNode","unwrapToCalleeExpression","getCalleeEvidence","callee","children","terminal","receiver","normalizeCallText","CALLEE_IDENTIFIER_NODE_TYPES","calleeName","receiverText","text","getCallSitePosition","findEnclosingContainerName","containerIds","firstTypeIdentifierText","resolveRustImplContainerName","typeField","resolveGoReceiverContainerName","paramType","resolveCppQualifiedContainerName","inner","scope","resolveDeferredLanguageContainerName","collectClassNodes","tree","provider","classes","classNodes","symbolContentHash","FUNCTION_VALUE_NODE_TYPES","collectVariableNodes","variables","variableNodes","value","collectFunctionNodes","functions","classIds","n","functionNodes","container","containerName","collectCallEdges","calls","functionIds","callNodes","position","evidence","collectImplementsEdges","implementsList","collectExtendsEdges","extendsList","WORKER_SPAWN_LANGUAGES","SUPPORTED_LANGUAGES","WORKER_CONSTRUCTOR_NAME","PATH_MODULE_OBJECT_NAME","PATH_RESOLVE_METHOD_NAME","PATH_JOIN_METHOD_NAME","DIRNAME_IDENTIFIER_NAME","isPathJoinOrResolveCall","fn","object","property","extractDirnameJoinedLiteral","callNode","args","findDirnameJoinedAssignment","argText","assignment","left","right","literal","resolveWorkerArgumentPath","argNode","collectWorkerSpawns","language","workerSpawns","firstArg","targetPath","extractAstData","decisions","imports","exports","importNodes","parseImportDescriptors","e","reportQueryCompileFailures","failure","logger","parseAndExtract","langInstance","parser","Parser","data","buildParseResponse","request","parserInitialized","registry","getRegistry","ext","wasmPath","attemptedPaths","resolveWasmPath","getLanguage","parentPort","response","err"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{C as e,
|
|
2
|
+
import{C as e,E as o,Ea as t,X as n}from"./chunk-XIDGZQW2.js";var _=".github",u=".claude",d="hooks.json",O="settings.json",E=".cursor/mcp.json",h="claude_desktop_config.json",x="docuvia-local",A="copilot-instructions.md",N="CLAUDE.md",R=".cursorrules",r="docuvia:start",g="docuvia:end",S=".windsurfrules",I="llms.txt",L="AGENTS.md",C=".hermes.md",m=".continue/rules",f="docuvia.md",T="Cursor",U="Claude",M="GitHub Copilot",D="Codex",y="Continue",F="Hermes Agent",b="cursor",v="claude",P="copilot",G="codex",w="continue",H="hermes",K="${CLAUDE_PLUGIN_ROOT}/hooks",k="${CURSOR_PLUGIN_ROOT}/hooks",J="${CLAUDE_PROJECT_DIR}/"+t,q="npx",V="-y",$="--no-install",j=["docuvia","mcp"],X="DOCUVIA_WORKSPACE_ROOT",B=`#!/usr/bin/env node
|
|
3
3
|
/**
|
|
4
4
|
* Docuvia Agent Hook
|
|
5
5
|
* Intercepts AI searches and augments with high-density AST context from local SQLite.
|
|
@@ -79,4 +79,4 @@ Run: \`npx --no-install docuvia analyze <file> --agent-authored --stage\`
|
|
|
79
79
|
Pipe a JSON payload on stdin (default) \u2014 \`{"decisions":[{"title":string,"content":string,"nodeType":"change"|"rule"|"decision"|"context","confidence":number}]}\` \u2014 or pass \`--decisions-file=<path>\` instead. Put \`--agent-authored\`/\`--stage\` after the positional \`<file>\`, not before \u2014 a flag preceding the path silently swallows it as the flag's own value. Staged decisions flush into the knowledge graph automatically the next time you commit a change touching that file \u2014 nothing else to run.
|
|
80
80
|
<!-- docuvia:end -->
|
|
81
81
|
`;export{_ as a,u as b,d as c,O as d,E as e,h as f,x as g,A as h,N as i,R as j,r as k,g as l,S as m,I as n,L as o,C as p,m as q,f as r,T as s,U as t,M as u,D as v,y as w,F as x,b as y,v as z,P as A,G as B,w as C,H as D,K as E,k as F,J as G,q as H,V as I,$ as J,j as K,X as L,B as M,s as N,W as O,z as P};
|
|
82
|
-
//# sourceMappingURL=chunk-
|
|
82
|
+
//# sourceMappingURL=chunk-7IDGG5WR.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{ba as c}from"./chunk-
|
|
2
|
+
import{ba as c}from"./chunk-XIDGZQW2.js";import*as _ from"fs/promises";import*as g from"path";import{select as f,confirm as P,input as b,checkbox as H}from"@inquirer/prompts";import Y from"picocolors";import F from"ora";var r={TOP_LEFT:"\u250C",TOP_RIGHT:"\u2510",BOTTOM_LEFT:"\u2514",BOTTOM_RIGHT:"\u2518",HORIZONTAL:"\u2500",VERTICAL:"\u2502",T_DOWN:"\u252C",T_UP:"\u2534",T_RIGHT:"\u251C",T_LEFT:"\u2524",CROSS:"\u253C"},w={PASS:"\u2713",FAIL:"\u2717"},N="\u25C6";var E={SPACE:" ",EMPTY:""};function u(e){return e.replace(/\s+/g,E.SPACE).trim()}function m(e,n){if(e.length<=n)return[e];let t=e.split(E.SPACE),i=[],o=E.EMPTY;for(let s of t){let A=o?`${o}${E.SPACE}${s}`:s;A.length>n&&o?(i.push(o),o=s):o=A}return o&&i.push(o),i}function h(e,n){return e+E.SPACE.repeat(Math.max(0,n-e.length))}function R(e,n,t,i){return n+e.map(o=>r.HORIZONTAL.repeat(o+2)).join(t)+i}function L(e,n){let t=e.map((i,o)=>h(i??E.EMPTY,n[o]));return`${r.VERTICAL} ${t.join(` ${r.VERTICAL} `)} ${r.VERTICAL}`}function U(e,n){return e.map((t,i)=>{let o=Math.max(t.header.length,...n.map(s=>(s[i]??E.EMPTY).length));return t.maxWidth?Math.min(o,t.maxWidth):o})}function C(e,n){let t=e.map(a=>u(a.header)),i=n.map(a=>a.map(d=>u(d??E.EMPTY))),o=U(e.map((a,d)=>({...a,header:t[d]})),i),s=i.map(a=>e.map((d,T)=>m(a[T]??E.EMPTY,o[T]))),A=[R(o,r.TOP_LEFT,r.T_DOWN,r.TOP_RIGHT),L(t,o),R(o,r.T_RIGHT,r.CROSS,r.T_LEFT)];for(let a of s){let d=Math.max(...a.map(T=>T.length));for(let T=0;T<d;T++)A.push(L(a.map(p=>p[T]??E.EMPTY),o))}return A.push(R(o,r.BOTTOM_LEFT,r.T_UP,r.BOTTOM_RIGHT)),A}function D(e){let n=r.HORIZONTAL.repeat(e.length+2);return[`${r.TOP_LEFT}${n}${r.TOP_RIGHT}`,`${r.VERTICAL} ${e} ${r.VERTICAL}`,`${r.BOTTOM_LEFT}${n}${r.BOTTOM_RIGHT}`]}var M="cyan",O={INFO:"\u2139",SUCCESS:"\u2714",WARN:"\u26A0",ERROR:"\u2716"},S=Y.createColors(!!process.stdout.isTTY&&!process.env.NO_COLOR),I={spinner:e=>F({text:e,color:M}),info:e=>console.log(S.cyan(`${O.INFO} ${e}`)),success:e=>console.log(S.green(`${O.SUCCESS} ${e}`)),warn:e=>console.warn(S.yellow(`${O.WARN} ${e}`)),error:e=>console.error(S.red(`${O.ERROR} ${e}`)),log:e=>console.log(e??""),header:e=>{console.log();for(let n of D(e))console.log(S.cyan(n));console.log()},section:e=>{console.log(),console.log(S.bold(S.cyan(`${N} ${e}`)))},table:(e,n)=>{for(let t of C(e,n))console.log(t)},askConfirm:async(e,n=!0)=>await P({message:e,default:n}),askSelect:async(e,n)=>await f({message:e,choices:n}),askCheckbox:async(e,n)=>await H({message:e,choices:n}),askInput:async(e,n)=>await b({message:e,default:n})};var l={CLI_HEADER:"Docuvia Knowledge Graph",CLI_PROMPT_ACTION:"What would you like to do?",CLI_UNKNOWN_COMMAND:"Unknown command: ",CLI_FATAL_ERROR:"Fatal error: ",CLI_INTERACTIVE_NO_TTY:"--interactive requires a real terminal and is disabled under CI -- cannot launch the wizard menu.",CLI_INTERACTIVE_UNAVAILABLE:"--interactive was requested, but this session has no usable TTY (or is running under CI) -- continuing non-interactively.",INIT_HEADER:"Initialize Docuvia",INIT_CONFIRM:"Initialize Docuvia in this workspace?",INIT_ABORTED:"Initialization aborted.",INIT_START:"Starting initialization...",INIT_FAILED:"Initialization failed: ",INIT_AGENT_HOOKS:"Initializing AI Agent integrations for Docuvia...",INIT_LOCK_WAITING:"Another `docuvia init` is already running in this workspace; waiting for it to finish...",INIT_HOOKS_CONFIG_MCP:"Configuring MCP Servers...",INIT_HOOKS_REGISTERED_MCP:"Registered MCP server in: ",INIT_HOOKS_FAIL_CURSOR_MCP:"Could not configure Cursor MCP: ",INIT_HOOKS_SUCCESS:"Docuvia Agent Integrations successfully installed!",INIT_HOOKS_SUPPORTED:"Supported platforms: Claude Code, Cursor, GitHub Copilot, Codex, Continue, Hermes Agent.",INIT_HOOKS_FAIL:"Failed to initialize agent integrations: ",INIT_HOOKS_SELECT:"Which AI Agent integrations would you like to install?",INIT_HOOKS_NONE_SELECTED:"No platforms selected. Skipping agent integrations.",INIT_CLAUDE_MCP_MANUAL_SNIPPET:"To use Docuvia from Claude Desktop, add this to your global MCP config",FS_APPENDED:"Appended instructions to: ",FS_ALREADY_EXISTS:"Instructions already exist in: ",FS_CREATED:"Created: ",FS_READ_ERROR:"Could not read ",FS_READ_ERROR_UNKNOWN_CODE:"unknown error",FS_BLOCK_REMOVED_PREFIX:"Removed block from ",FS_BLOCK_REMOVED_SUFFIX:" (backup created)",FS_UNEXPECTED_SHAPE:(e,n)=>`Unexpected shape for "${e}" in ${n} (expected an array); leaving it untouched`,CLEAN_HEADER:"Clean Docuvia Database",CLEAN_CONFIRM:"This will permanently delete the local Docuvia database. Continue?",CLEAN_ABORTED:"Clean aborted.",CLEAN_START:"Cleaning database...",CLEAN_SUCCESS:"Clean complete. ",CLEAN_FAIL:"Clean failed: ",STATUS_START:"Getting status...",STATUS_SUCCESS:"Status retrieved.",STATUS_FAIL:"Failed to get status: ",STATUS_HEADER:"Docuvia Status",STATUS_COL_METRIC:"Metric",STATUS_COL_VALUE:"Value",STATUS_METRIC_PROJECTS:"Projects",STATUS_METRIC_L2_NODES:"L2 Nodes",STATUS_METRIC_L3_DECISIONS:"L3 Decisions",STATUS_METRIC_TIER_B_COVERAGE:"Tier B Coverage",STATUS_METRIC_TIER_C_QUEUE:"Tier C Queue",PUBLISH_HEADER:"Publish to Docuvia",PUBLISH_MISSING_PROJECT_ID:"Project ID is required when not running interactively.",PUBLISH_NO_PROJECT_ID_PROVIDED:"No project ID provided.",PUBLISH_PROMPT_PROJECT_ID:"Enter the project ID to publish to: ",PUBLISH_PROJECT_ID_REQUIRED:"Project ID is required.",PUBLISH_MISSING_ENV:"DOCUVIA_API_URL and/or MCP_PAT are not set.",PUBLISH_SKIP:"Skipping publish.",PUBLISH_START:"Starting publish for project ",PUBLISH_SUCCESS:"Publish complete.",PUBLISH_FAIL:"Publish failed: ",ANALYZE_HEADER:"Analyze Project",ANALYZE_START:"Analyzing project...",ANALYZE_SUCCESS:"Analysis complete.",ANALYZE_FAIL:"Analysis failed: ",ANALYZE_PROJECT_TYPE:"Project Type: ",ANALYZE_SUGGESTED_TAGS:"Suggested Tags: ",ANALYZE_NONE:"none",ANALYZE_AUTO_FULL_SUCCESS:"Full ingestion complete.",ANALYZE_AUTO_FULL_SUMMARY:(e,n,t)=>`Parsed ${e}/${n} file(s) (${t} failed).`,ANALYZE_AUTO_DELTA_SUCCESS:"Delta ingestion complete.",ANALYZE_AUTO_DELTA_SUMMARY:(e,n,t)=>`Re-parsed ${e} file(s), dropped ${n} deleted file(s)`+(t>0?`, queued ${t} file(s) for Tier B.`:"."),ANALYZE_AUTO_NOOP_SUCCESS:"Already up to date.",ANALYZE_AUTO_NOOP_DIRTY_WORKTREE_SUCCESS:"Already up to date with HEAD -- uncommitted changes in the working tree were not analyzed (commit them, then re-run).",ANALYZE_LLM_MISSING_ENV:"AI_DOCUVIA_INTEGRATIONS_OPENAI_BASE_URL and a model (AI_DOCUVIA_MODEL or AI_DOCUVIA_FAST_MODEL) must be set to analyze a specific path.",ANALYZE_FOCUSED_HEADER:"Analyze Path",ANALYZE_FOCUSED_START:"Extracting decisions from ",ANALYZE_FOCUSED_SUCCESS:"Decision extraction complete.",ANALYZE_FOCUSED_FAIL:"Decision extraction failed: ",ANALYZE_FOCUSED_NONE:"No decision-worthy content found.",ANALYZE_FOCUSED_PERSISTED:(e,n)=>`${e} persisted, ${n} deduplicated`,ANALYZE_DECISION_LINE:(e,n,t)=>`${n} (${e}, confidence: ${t})`,ANALYZE_DECISION_CONTENT_PREFIX:" ",ANALYZE_TIER_B_HEADER:"Analyze -- Tier B (LSP escalation)",ANALYZE_TIER_B_START:"Running the Tier B LSP escalation batch...",ANALYZE_TIER_B_SUCCESS:"Tier B batch complete.",ANALYZE_TIER_B_FAIL:"Tier B batch failed: ",ANALYZE_TIER_B_SUMMARY:(e,n,t,i,o)=>`${e} file(s) processed, ${n} corrected edge(s) applied`+(t>0?`, ${t} file(s) left queued for the next batch`:"")+(i>0?`, ${i} file(s) permanently failed (not re-queued)`:"")+(o?", zero-progress watchdog tripped: no next-batch re-queue remains":"")+".",ANALYZE_TIER_B_DEGRADED:e=>`LSP unavailable -- AST-level edges left untouched (${e})`,ANALYZE_TIER_B_GATE_NOT_READY:e=>`LSP prerequisites are not ready: ${e}`,ANALYZE_TIER_B_GATE_PROMPT:"Continue with AST-only precision (skip the LSP-corrected cross-file edges this batch)?",ANALYZE_TIER_B_GATE_DECLINED:"Aborted -- install typescript-language-server as a project devDependency (or pass --fallback-ast) and try again.",ANALYZE_TIER_B_GATE_FAILED:e=>`LSP prerequisites are not ready: ${e}
|
|
3
3
|
Build/compile the target project (Docuvia's Tier B relies on a working language server), then run 'docuvia doctor' to confirm. Pass --fallback-ast to proceed with AST-only precision instead.`,ANALYZE_TIER_C_SUMMARY:(e,n,t)=>`Tier C: ${e} candidate(s) processed, ${n} decision(s) persisted`+(t>0?`, ${t} left queued for the next run.`:"."),ANALYZE_TIER_C_SKIPPED:e=>`Tier C: drain skipped this run (${e}).`,ANALYZE_AGENT_AUTHORED_MISSING_TARGET:"--agent-authored requires a target path, e.g. docuvia analyze <path> --agent-authored",ANALYZE_AGENT_AUTHORED_MISSING_PAYLOAD:"No decisions payload found -- pipe JSON via stdin or pass --decisions-file=<path>",ANALYZE_AGENT_AUTHORED_INVALID_JSON:e=>`--agent-authored payload is not valid JSON: ${e}`,ANALYZE_AGENT_AUTHORED_INVALID_SHAPE:e=>`--agent-authored payload does not match the expected shape: ${e}`,ANALYZE_LSP_ARGS_INVALID_JSON:e=>`DOCUVIA_LSP_ARGS starts with '[' but is not valid JSON -- use a JSON array of strings, or plain space-separated args: ${e}`,ANALYZE_LSP_ARGS_INVALID_SHAPE:"DOCUVIA_LSP_ARGS JSON array must contain only strings",ANALYZE_STAGE_HEADER:"Stage Decisions",ANALYZE_STAGE_START:"Staging decisions from ",ANALYZE_STAGE_SUCCESS:"Staged.",ANALYZE_STAGE_SUMMARY:e=>`${e} decision(s) staged -- flushed automatically on the next commit that touches this file.`,ANALYZE_FLUSH_STAGED_L3_HEADER:"Flush Staged L3 Decisions",ANALYZE_FLUSH_STAGED_L3_START:"Flushing staged L3 decisions...",ANALYZE_FLUSH_STAGED_L3_SUCCESS:"Flush complete.",ANALYZE_FLUSH_STAGED_L3_DISABLED_SUCCESS:"commit-l3-write is disabled -- nothing flushed.",ANALYZE_FLUSH_STAGED_L3_SUMMARY:(e,n,t)=>`${e} flushed, ${n} deduplicated`+(t>0?`, ${t} left staged for a future commit.`:"."),ANALYZE_FLUSH_STAGED_L3_NO_GRAPH_ADVICE:"Some staged decisions could not be attached: the knowledge graph is empty (or hasn't ingested this file yet). Run `docuvia init` first -- decisions need a graph to attach to. They stay staged and retry on the next flush.",REVIEW_HEADER:"Review Changes",REVIEW_START:"Analyzing changes...",REVIEW_SUCCESS:"Analysis complete.",REVIEW_AGAINST:" against ",REVIEW_FAIL:"Review failed: ",REVIEW_FILES_CHANGED:"Files changed: ",REVIEW_RISK_PREFIX:"Risk level: ",REVIEW_WHY_HEADER:"Why (L3 decisions/context)",REVIEW_WHY_PREFIX:"Decision: ",IMPACT_HEADER:"Impact Analysis",IMPACT_MISSING_TARGET:"A target symbol/module name is required.",IMPACT_START:"Resolving blast radius for ",IMPACT_SUCCESS:"Resolved blast radius for ",IMPACT_FAIL:"Impact analysis failed: ",IMPACT_NOT_FOUND:"No matching node found for ",IMPACT_BLAST_RADIUS_HEADER:"Blast Radius",IMPACT_NO_DEPENDENTS:"No dependents found.",IMPACT_RISK_PREFIX:"Risk level: ",IMPACT_WHY_PREFIX:"Decision: ",IMPACT_COL_NAME:"Name",IMPACT_COL_TYPE:"Type",IMPACT_COL_SOURCE:"Source",IMPACT_EDGE_SOURCE_STATIC:"static",IMPACT_ENTRY_WHY_LABEL:e=>`${e}:`,IMPACT_TIER_B_INCOMPLETE:(e,n)=>`${e} of ${n} tracked file(s) have never been Tier B-processed -- this may be incomplete, not confirmed zero. Run \`docuvia analyze --escalate-to-lsp --full\` to resync.`,IMPACT_RISK_NOTE_PREFIX:"Note: ",UNINSTALL_HEADER:"Uninstall Docuvia2 Integrations",UNINSTALL_START:"Uninstalling Docuvia2 integrations...",UNINSTALL_SUCCESS_CLEAN:"Cleaned Docuvia: ",UNINSTALL_FAIL_CLEAN:"Failed to clean Docuvia directory: ",UNINSTALL_SUCCESS:"Docuvia2 uninstalled successfully. Backup files (.bak) were created for modified Markdown files.",UNINSTALL_FAIL:"Uninstall failed: ",UNINSTALL_HOOKS_SELECT:"Which AI Agent integrations would you like to uninstall?",UNINSTALL_KEEP_DB:"Skipping local database cleanup (--keep-db).",UNINSTALL_INVALID_WORKSPACE_ROOT:"Workspace root must not be empty.",UNINSTALL_PLATFORM_FAIL:"Failed to uninstall hooks for ",UNINSTALL_PLATFORM_FAIL_MID:": ",UNINSTALL_PARTIAL:"Uninstall completed with failures: ",UNINSTALL_DB_CLEANUP_FAILURE_NAME:"local database cleanup",UNINSTALL_HOOKS_FAIL_LOG:"uninstallHooks failed for platform ",UNINSTALL_DB_CLEANUP_FAIL_LOG:"uninstall's database cleanup failed",UNINSTALL_FAIL_LOG:"uninstall failed",UNINSTALL_REMOVED_FILE_PREFIX:"Removed ",UNINSTALL_REMOVED_MCP_SERVER_PREFIX:"Removed MCP server from ",UNINSTALL_REMOVED_HOOK_FROM_SETTINGS_PREFIX:"Removed the Docuvia hook entry from ",UNINSTALL_CLAUDE_MCP_MANUAL_REMINDER:"To finish uninstalling, manually remove the Docuvia MCP server entry from your global MCP config",UNINSTALL_GIT_HOOKS_SUCCESS:(e,n)=>`Removed git hooks (post-commit: ${e?"removed":"not present"}, pre-push: ${n?"removed":"not present"}).`,UNINSTALL_GIT_HOOKS_FAIL:"Failed to remove git hooks: ",UNINSTALL_GIT_HOOKS_FAIL_LOG:"uninstall's git hooks removal failed",UNINSTALL_GIT_HOOKS_FAILURE_NAME:"git hooks removal",UNINSTALL_KNOWLEDGE_BRANCH_DELETED:"Deleted the hidden docuvia-knowledge git branch.",UNINSTALL_DOCUVIA_DIR_REMOVED:"Removed the .docuvia/ directory.",UNINSTALL_DOCUVIA_DIR_FAIL:"Failed to remove the .docuvia/ directory: ",UNINSTALL_DOCUVIA_DIR_FAIL_LOG:"uninstall's .docuvia/ directory removal failed",UNINSTALL_DOCUVIA_DIR_FAILURE_NAME:".docuvia/ directory removal",DOCTOR_HEADER:"Docuvia Doctor Diagnostics",DOCTOR_START:"Running diagnostics...",DOCTOR_FAIL:"Doctor failed: ",DOCTOR_SUMMARY_PASSED:(e,n)=>`Summary: ${e}/${n} checks passed.`,DOCTOR_FIX_HINT:"Tip: run `docuvia doctor --fix` to attempt automatic repair.",DOCTOR_COL_CHECK:"Check",DOCTOR_COL_STATUS:"Status",DOCTOR_COL_MESSAGE:"Message",DOCTOR_COL_FIX:"Suggested Fix",DOCTOR_STATUS_PASS:"PASS",DOCTOR_STATUS_FAIL:"FAIL",DOCTOR_CATEGORY_DATABASE:"Database",DOCTOR_CATEGORY_GIT:"Git",DOCTOR_CATEGORY_GIT_HOOKS:"Git Hooks",DOCTOR_CATEGORY_LOGS:"Logs",DOCTOR_CATEGORY_TIER_B:"Tier B Batch",DOCTOR_CATEGORY_TIER_B_COVERAGE:"Tier B Coverage",DOCTOR_CATEGORY_LLM:"LLM Integration",DOCTOR_CATEGORY_LSP:"LSP Providers",DOCTOR_CATEGORY_AGENT_HOOKS:"AI Agent Hooks",DOCTOR_CATEGORY_AGENT_ADOPTION:"Docuvia-First Workflow",DOCTOR_CATEGORY_OTHER:"Other",QUERY_HEADER:"Query Knowledge Graph",QUERY_PROMPT_TARGET:"What would you like to query? ",QUERY_MISSING_TARGET:"A query target is required (pass it as an argument).",QUERY_MISSING_TARGET_NON_TTY:"A query target is required.",QUERY_START:"Querying local knowledge graph for ",QUERY_FOUND:"Query resolved for ",QUERY_FAIL:"Query failed: ",QUERY_CONTEXT_HEADER:"Query Results",QUERY_L2_PREFIX:"Module: ",QUERY_NO_L2:"No matching module found.",QUERY_L3_PREFIX:"Decision: ",QUERY_L3_PROVENANCE:e=>` (${e.join(", ")})`,QUERY_UNKNOWN_STATUS:"unknown",QUERY_INCOMING_HEADER:"Incoming (callers/dependents)",QUERY_OUTGOING_HEADER:"Outgoing (dependencies)",QUERY_COL_NAME:"Name",QUERY_COL_RELATION:"Relation",QUERY_INVALID_LIMIT:"Ignoring invalid --limit value (must be a positive integer): ",QUERY_TIER_B_INCOMING_UNPROCESSED:(e,n)=>`No callers found, but ${e} of ${n} tracked file(s) have never been Tier B-processed -- this may be incomplete, not confirmed zero. Run \`docuvia analyze --escalate-to-lsp --full\` to resync.`,QUERY_TIER_B_OUTGOING_UNPROCESSED:"No callees found, but this symbol's own file has never been Tier B-processed -- this may be incomplete, not confirmed zero. Run `docuvia analyze --escalate-to-lsp --full` to resync.",QUERY_MATCH_TYPE_EXACT:" (exact match)",QUERY_MATCH_TYPE_KEYWORD:" (keyword match -- verify with Grep/Glob if unsure)",QUERY_MATCH_TYPE_NEIGHBOR:" (neighbor match)",EXPORT_HEADER:"Export Topology",EXPORT_START:"Exporting topology...",EXPORT_SUCCESS:"Exported topology to ",EXPORT_FAIL:"Export failed: ",EXPORT_STATS_LINE:(e,n,t)=>`Nodes: ${e}, Links: ${n}, Groups: ${t}`,EXPORT_COLLAPSED_LINE:"Collapsed: yes (fewer nodes than the raw graph).",EXPORT_FOLDED_LINE:e=>`Folded links: ${e} more relationship(s) folded within files at this granularity; pass --collapse=symbol for the full symbol-level view.`,EXPORT_HTML_PATH_LINE:e=>`HTML viewer: ${e}`,SNAPSHOT_HEADER:"Snapshot Knowledge Graph",SNAPSHOT_START:"Packing knowledge graph snapshot...",SNAPSHOT_SUCCESS:"Snapshot packed onto the knowledge branch.",SNAPSHOT_FAIL:"Snapshot failed: ",SNAPSHOT_NODES_WRITTEN_LINE:e=>`Nodes written: ${e}`,SNAPSHOT_EDGES_WRITTEN_LINE:e=>`Edges written: ${e}`,SNAPSHOT_MARKDOWN_WRITTEN_LINE:e=>`Markdown files written: ${e}`,HYDRATE_HEADER:"Hydrate Local Database",HYDRATE_START:"Hydrating local database from the knowledge branch...",HYDRATE_SUCCESS:"Hydrated local database.",HYDRATE_NOTHING:'Nothing to hydrate from yet \u2014 run "docuvia init" first.',HYDRATE_FAIL:"Hydrate failed: ",HYDRATE_NODES_LOADED_LINE:e=>`Nodes loaded: ${e}`,HYDRATE_EDGES_LOADED_LINE:e=>`Edges loaded: ${e}`,HYDRATE_EDGES_DROPPED_LINE:e=>`Dangling edges dropped: ${e}`,HYDRATE_REFUSED:e=>`Refused to hydrate: ${e==="pending-local-write"?"a knowledge-branch write from this workspace hasn't been confirmed yet":"this would replace local.db's graph with a drastically smaller one"}. Local data was left untouched. Re-run with --force if you're sure.`,SYNC_KNOWLEDGE_HEADER:"Sync Knowledge Branch",SYNC_KNOWLEDGE_START:"Reconciling the knowledge branch with the remote...",SYNC_KNOWLEDGE_NO_REMOTE:"No remote reachable \u2014 nothing to reconcile (offline or no origin configured).",SYNC_KNOWLEDGE_UP_TO_DATE:"Knowledge branch is already up to date with the remote.",SYNC_KNOWLEDGE_FAST_FORWARDED:"Fast-forwarded the local knowledge branch to the remote.",SYNC_KNOWLEDGE_PUSHED:"Pushed the local knowledge branch to the remote.",SYNC_KNOWLEDGE_MERGED:"Merged the diverged knowledge branch and pushed the result.",SYNC_KNOWLEDGE_FAIL:"Knowledge branch sync failed: ",HOOKS_HEADER:"Docuvia Hooks",HOOKS_COL_NAME:"Hook",HOOKS_COL_STATUS:"Status",HOOKS_STATUS_ENABLED:"enabled",HOOKS_STATUS_DISABLED:"disabled",HOOKS_LIST_FAIL:"Failed to list hooks: ",HOOKS_SET_FAIL:"Failed to update hook: ",HOOKS_ENABLED:e=>`Enabled hook: ${e}`,HOOKS_DISABLED:e=>`Disabled hook: ${e}`,HOOKS_INVALID_NAME:(e,n)=>`Unknown hook '${e??""}' -- valid names: ${n.join(", ")}`,HOOKS_UNKNOWN_SUBCOMMAND:e=>`Unknown 'docuvia hooks' subcommand '${e??""}' -- expected list, enable, disable, or check`};var y="ENOENT";async function j(e,n,t){let i;try{i=await _.readFile(e,c)}catch(o){o.code!==y&&I.warn(`${l.FS_READ_ERROR}${e} (${o.code??l.FS_READ_ERROR_UNKNOWN_CODE}); creating a new file instead of appending`)}if(i===void 0){await _.mkdir(g.dirname(e),{recursive:!0}),await _.writeFile(e,n),I.success(l.FS_CREATED+e);return}i.includes(t)?I.info(l.FS_ALREADY_EXISTS+e):(await _.appendFile(e,`
|
|
4
4
|
${n}`),I.success(l.FS_APPENDED+e))}async function G(e){try{let n=await _.readFile(e,c),t=`${e}.bak`;return await _.writeFile(t,n,c),t}catch{return null}}async function J(e,n,t){try{let i=await _.readFile(e,c),o=i.indexOf(n);if(o===-1)return!1;let s=i.indexOf(t,o);if(s===-1)return!1;await G(e);let A=i.slice(0,o),a=i.slice(s+t.length);return await _.writeFile(e,(A+a).trim()+`
|
|
5
5
|
`,c),I.success(`${l.FS_BLOCK_REMOVED_PREFIX}${e}${l.FS_BLOCK_REMOVED_SUFFIX}`),!0}catch{return!1}}export{r as a,w as b,I as c,l as d,j as e,G as f,J as g};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-UWGOBCTB.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{ba as F,fa as u,ga as v,ha as Y,ia as k,ja as G,ka as H,la as B,ma as Q,na as V,oa as j,pa as W,qa as q}from"./chunk-3WFKL5P6.js";var J="anonymous";var Pt="AstWorkerCrashError",Ft={ARGUMENTS:"arguments",VARIABLE_DECLARATOR:"variable_declarator",ASSIGNMENT_EXPRESSION:"assignment_expression",PAIR:"pair",PUBLIC_FIELD_DEFINITION:"public_field_definition",IMPL_ITEM:"impl_item",TYPE_IDENTIFIER:"type_identifier",POINTER_TYPE:"pointer_type",QUALIFIED_IDENTIFIER:"qualified_identifier"},gt={PARSE_FAILURE_NO_DETAIL:"parse returned success=false with no error detail",PARSE_FAILURE_RESULT:"AST parse returned failure result",PARSE_THREW:"AST parse threw (worker crash or rejection)",WORKER_UNCAUGHT_EXCEPTION:"AST worker uncaughtException",QUERY_COMPILE_FAILED:"AST language query failed to compile; using fallback",WORKER_UNHANDLED_REJECTION:"AST worker unhandledRejection",WORKER_EXITED_DURING_SHUTDOWN:"AST worker exited during pool shutdown (expected)",WORKER_CRASHED_EXITED:"AST worker crashed/exited",WORKER_EXITED_UNEXPECTEDLY:"Worker exited unexpectedly",UNKNOWN_FILE:"(unknown file)",PARSE_CACHE_HIT:"AST parse cache hit",CACHE_METRICS_AND_QUEUE_PERFORMANCE:"AST cache metrics and queue performance",TASK_TIMED_OUT_TERMINATING:"AST worker task timed out \u2014 terminating stuck worker",WORKER_TERMINATE_FAILED:"AST worker terminate() rejected \u2014 forced termination did not complete",QUERIED_VIA_LANGUAGE_PROVIDER:"Queried nodes using @workspace/ast-core LanguageProvider",ANONYMOUS_NAME:J,workerCrashWhileParsing:n=>`AST worker crashed while parsing ${n}: `,taskTimedOutAfterMs:(n,e)=>`AST worker task ${n} timed out after ${e}ms`,workerExitedWithCode:n=>`Worker exited with code ${n}`,noLanguageProviderForExtension:n=>`No language provider registered for extension ${n}`,wasmNotFound:(n,e)=>`WASM not found for ${n}, AST parsing skipped (Regex fallback used). Tried paths: ${e}`,parsedViaTreeSitter:n=>`Parsed via web-tree-sitter (nodes: ${n})`,providerQueryFailed:n=>`ast-core provider query failed: ${n}`};var p={FILE:"file",CLASS:"class",FUNCTION:"function",CALL:"call",METHOD_CALL:"method_call",IMPORT:"import",API_CONTRACT:"api_contract"};var N={IDENTIFIER:"identifier",SCOPED_IDENTIFIER:"scoped_identifier",QUALIFIED_IDENTIFIER:"qualified_identifier",DOTTED_NAME:"dotted_name",ALIASED_IMPORT:"aliased_import",USE_AS_CLAUSE:"use_as_clause",USE_WILDCARD:"use_wildcard",SCOPED_USE_LIST:"scoped_use_list",USE_LIST:"use_list",DOT:"dot",BLANK_IDENTIFIER:"blank_identifier",NAMESPACE_USE_DECLARATION:"namespace_use_declaration",INCLUDE_EXPRESSION:"include_expression",INCLUDE_ONCE_EXPRESSION:"include_once_expression",REQUIRE_EXPRESSION:"require_expression",REQUIRE_ONCE_EXPRESSION:"require_once_expression",IMPORT_STATEMENT:"import_statement",IMPORT_FROM_STATEMENT:"import_from_statement",USE_DECLARATION:"use_declaration",IMPORT_DECLARATION:"import_declaration",PREPROC_INCLUDE:"preproc_include",USING_DECLARATION:"using_declaration",CALL:"call",USING_DIRECTIVE:"using_directive",CALL_EXPRESSION:"call_expression",METHOD_INVOCATION:"method_invocation",EXPLICIT_CONSTRUCTOR_INVOCATION:"explicit_constructor_invocation",COMMAND_CALL:"command_call",FUNCTION_CALL_EXPRESSION:"function_call_expression",MEMBER_CALL_EXPRESSION:"member_call_expression",SCOPED_CALL_EXPRESSION:"scoped_call_expression",INVOCATION_EXPRESSION:"invocation_expression",OBJECT_CREATION_EXPRESSION:"object_creation_expression",MEMBER_EXPRESSION:"member_expression",ATTRIBUTE:"attribute",MEMBER_ACCESS_EXPRESSION:"member_access_expression",VARIABLE_DECLARATION:"variable_declaration",LEXICAL_DECLARATION:"lexical_declaration",VARIABLE_DECLARATOR:"variable_declarator",ARROW_FUNCTION:"arrow_function",FUNCTION_DECLARATION:"function_declaration",METHOD_DEFINITION:"method_definition",CLASS_DECLARATION:"class_declaration",INTERFACE_DECLARATION:"interface_declaration",TYPE_ALIAS_DECLARATION:"type_alias_declaration",EXPORT_STATEMENT:"export_statement"};var d="*",_e=["require","require_relative","load"],K="this",Ae="new";function wt(n){let e=[];for(let o of n){let r=o.type,i=pe[r];if(i){i(o,e);continue}if(be(r)){Ye(o,r,e);continue}Ge(o,e)}return e}var pe={[N.IMPORT_STATEMENT]:Ce,[N.EXPORT_STATEMENT]:Oe,[N.IMPORT_FROM_STATEMENT]:Se,[N.USE_DECLARATION]:$e,[N.IMPORT_DECLARATION]:Ue,[N.PREPROC_INCLUDE]:Me,[N.USING_DECLARATION]:ye,[N.CALL]:we,[N.USING_DIRECTIVE]:ke};function Ce(n,e){let o=n.descendantsOfType("string").pop();if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("namespace_import")[0];if(i){let c=i.descendantsOfType("identifier")[0];c&&e.push({localName:c.text,originalName:d,modulePath:r});return}let s=n.descendantsOfType("named_imports")[0];if(s){let c=s.descendantsOfType("import_specifier");for(let I of c){if(!I)continue;let E=I.childForFieldName("name"),f=I.childForFieldName("alias");if(E){let S=E.text,C=f?f.text:S;e.push({localName:C,originalName:S,modulePath:r})}}return}let a=n.descendantsOfType("identifier")[0];a&&e.push({localName:a.text,originalName:d,modulePath:r})}function Oe(n,e){let o=n.childForFieldName("source");if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("export_clause")[0];if(i)for(let s of i.descendantsOfType("export_specifier")){if(!s)continue;let a=s.childForFieldName("name");if(!a)continue;let c=s.childForFieldName("alias");e.push({localName:c?c.text:a.text,originalName:a.text,modulePath:r,viaReexport:!0})}}function Se(n,e){let o=n.childForFieldName("module_name");if(!o)return;let r=o.text;if(n.descendantsOfType("wildcard_import")[0])return;n.childForFieldName("name")&&He(n,r,e)}function Re(n,e){let o=n.childForFieldName("path"),r=n.childForFieldName("alias");o&&r&&e.push({localName:r.text,originalName:d,modulePath:o.text})}function Le(n,e,o){let r=n.childForFieldName("path"),i=n.childForFieldName("alias");r&&i&&o.push({localName:i.text,originalName:d,modulePath:`${e}::${r.text}`})}function he(n,e,o){let r=n.descendantsOfType("identifier").pop();r&&o.push({localName:r.text,originalName:d,modulePath:`${e}::${n.text}`})}function De(n,e,o){if(n.type===N.USE_AS_CLAUSE){Le(n,e,o);return}if(n.type===N.IDENTIFIER){o.push({localName:n.text,originalName:d,modulePath:`${e}::${n.text}`});return}n.type===N.SCOPED_IDENTIFIER&&he(n,e,o)}function Pe(n,e){let o=n.childForFieldName("path"),r=n.childForFieldName("list");if(!o||!r)return;let i=o.text;for(let s of r.namedChildren)s&&De(s,i,e)}function Fe(n,e){let o=n.descendantsOfType("identifier"),r=o[o.length-1];r&&e.push({localName:r.text,originalName:d,modulePath:n.text})}function ge(n,e){for(let o of n.namedChildren)o&&o.type===N.IDENTIFIER&&e.push({localName:o.text,originalName:d,modulePath:o.text})}function $e(n,e){let o=n.childForFieldName("argument");if(o){if(o.type===N.USE_AS_CLAUSE){Re(o,e);return}if(o.type!==N.USE_WILDCARD){if(o.type===N.SCOPED_USE_LIST){Pe(o,e);return}if(o.type===N.SCOPED_IDENTIFIER||o.type===N.IDENTIFIER){Fe(o,e);return}o.type===N.USE_LIST&&ge(o,e)}}}function xe(n,e){let o=n.childForFieldName("path");if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.childForFieldName("name");if(i){if(i.type===N.DOT||i.type===N.BLANK_IDENTIFIER)return;e.push({localName:i.text,originalName:d,modulePath:r})}else{let s=r.split("/"),a=s[s.length-1];e.push({localName:a,originalName:d,modulePath:r})}}function Ue(n,e){let o=n.descendantsOfType("import_spec_list")[0];if(!o)return;let r=o.descendantsOfType("import_spec");for(let i of r)i&&xe(i,e)}function Me(n,e){let o=n.childForFieldName("path");if(o){let r=o.text.replace(/[<>"']/g,"");e.push({localName:r,originalName:d,modulePath:r})}}function ye(n,e){let o=n.namedChildren;for(let r of o)if(r)if(r.type===N.QUALIFIED_IDENTIFIER){let i=r.descendantsOfType("identifier"),s=i[i.length-1];s&&e.push({localName:s.text,originalName:d,modulePath:r.text})}else r.type===N.IDENTIFIER&&e.push({localName:r.text,originalName:d,modulePath:r.text})}function we(n,e){let o=n.childForFieldName("method");if(!o)return;let r=o.text;if(!_e.includes(r))return;let i=n.childForFieldName("arguments");if(!i)return;let s=i.descendantsOfType("string_content")[0]||i.descendantsOfType("string")[0];if(!s)return;let a=s.text.replace(/['"]/g,""),c=a.replace(/\.rb$/,"");e.push({localName:c,originalName:d,modulePath:a})}function be(n){return n===N.NAMESPACE_USE_DECLARATION||n===N.INCLUDE_EXPRESSION||n===N.INCLUDE_ONCE_EXPRESSION||n===N.REQUIRE_EXPRESSION||n===N.REQUIRE_ONCE_EXPRESSION}function Xe(n,e){let o=n.descendantsOfType("qualified_name")[0]||n.descendantsOfType("name")[0];if(o){let r=o.text,i=r.split("\\"),s=i[i.length-1];e.push({localName:s,originalName:d,modulePath:r})}}function ve(n,e){let o=n.descendantsOfType("string")[0]||n.descendantsOfType("string_content")[0];if(o){let r=o.text.replace(/['"]/g,"");e.push({localName:r,originalName:d,modulePath:r})}}function Ye(n,e,o){e===N.NAMESPACE_USE_DECLARATION?Xe(n,o):ve(n,o)}function ke(n,e){let o=n.descendantsOfType("qualified_name")[0]||n.descendantsOfType("identifier")[0];if(o){let r=o.text,i=r.split("."),s=i[i.length-1];e.push({localName:s,originalName:d,modulePath:r})}}function Ge(n,e){let o=n.descendantsOfType("string").pop();if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("identifier");for(let s of i)s&&(e.some(a=>a.localName===s.text)||e.push({localName:s.text,originalName:s.text,modulePath:r}))}function He(n,e,o){if(n.childForFieldName("name")){for(let i of n.namedChildren)if(i)if(i.type===N.ALIASED_IMPORT){let s=i.childForFieldName("name"),a=i.childForFieldName("alias");s&&a&&o.push({localName:a.text,originalName:s.text,modulePath:e})}else if(i.type===N.DOTTED_NAME){let s=i.descendantsOfType("identifier"),a=s[s.length-1];a&&o.push({localName:a.text,originalName:i.text,modulePath:e})}else i.type===N.IDENTIFIER&&o.push({localName:i.text,originalName:i.text,modulePath:e})}}function Be(n){let e=n.childForFieldName("function");if(!e)return{isMethodCall:!1,methodName:""};if(e.type===N.MEMBER_EXPRESSION){let o=e.childForFieldName("property"),r=e.childForFieldName("object");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}return{isMethodCall:!1,methodName:e.text}}function Qe(n){let e=n.childForFieldName("function");if(!e)return{isMethodCall:!1,methodName:""};if(e.type===N.ATTRIBUTE){let o=e.childForFieldName("attribute"),r=e.childForFieldName("object");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}return{isMethodCall:!1,methodName:e.text}}function Ve(n){let e=n.childForFieldName("name"),o=n.childForFieldName("object");if(e)return{isMethodCall:!0,methodName:e.text,objectName:o?.text}}function je(n){return{isMethodCall:!0,methodName:n.childForFieldName("constructor")?.text||K,objectName:K}}function We(n){let e=n.childForFieldName("method");if(!e)return;let o=n.childForFieldName("receiver");return o?{isMethodCall:!0,methodName:e.text,objectName:o.text}:{isMethodCall:!1,methodName:e.text}}function M(n){let e=n.type,r=n.childForFieldName("name")?.text||"";if(e===N.MEMBER_CALL_EXPRESSION){let i=n.childForFieldName("object");return{isMethodCall:!0,methodName:r,objectName:i?.text}}if(e===N.SCOPED_CALL_EXPRESSION){let i=n.childForFieldName("scope");return{isMethodCall:!0,methodName:r,objectName:i?.text}}return{isMethodCall:!1,methodName:r}}function qe(n){let e=n.childForFieldName("function")||n.namedChildren[0];if(e&&e.type===N.MEMBER_ACCESS_EXPRESSION){let o=e.childForFieldName("name"),r=e.childForFieldName("expression");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}if(e)return{isMethodCall:!1,methodName:e.text}}function Je(n){let e=n.childForFieldName("type");return{isMethodCall:!0,methodName:Ae,objectName:e?.text}}var bt={[N.CALL_EXPRESSION]:Be,[N.CALL]:Qe,[N.METHOD_INVOCATION]:Ve,[N.EXPLICIT_CONSTRUCTOR_INVOCATION]:je,[N.COMMAND_CALL]:We,[N.FUNCTION_CALL_EXPRESSION]:M,[N.MEMBER_CALL_EXPRESSION]:M,[N.SCOPED_CALL_EXPRESSION]:M,[N.INVOCATION_EXPRESSION]:qe,[N.OBJECT_CREATION_EXPRESSION]:Je};var Ke=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,L=class n extends Date{#t=!1;#n=!1;#e=null;constructor(e){let o=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(Ke);s?(s[1]||(o=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=o,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let o=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return o=this.#e[0]==="-"?o:-o,new Date(this.getTime()-o*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,o="Z"){let r=new n(e);return r.#e=o,r}static wrapAsLocalDateTime(e){let o=new n(e);return o.#e=null,o}static wrapAsLocalDate(e){let o=new n(e);return o.#n=!1,o.#e=null,o}static wrapAsLocalTime(e){let o=new n(e);return o.#t=!1,o.#e=null,o}};function ze(n,e){let o=n.slice(0,e).split(/\r\n|\n|\r/g);return[o.length,o.pop().length+1]}function Ze(n,e,o){let r=n.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let c=r[a-1];c&&(i+=a.toString().padEnd(s," "),i+=": ",i+=c,i+=`
|
|
2
|
+
import{ba as F,fa as u,ga as v,ha as Y,ia as k,ja as G,ka as H,la as B,ma as Q,na as V,oa as j,pa as W,qa as q}from"./chunk-XIDGZQW2.js";var J="anonymous";var Pt="AstWorkerCrashError",Ft={ARGUMENTS:"arguments",VARIABLE_DECLARATOR:"variable_declarator",ASSIGNMENT_EXPRESSION:"assignment_expression",PAIR:"pair",PUBLIC_FIELD_DEFINITION:"public_field_definition",IMPL_ITEM:"impl_item",TYPE_IDENTIFIER:"type_identifier",POINTER_TYPE:"pointer_type",QUALIFIED_IDENTIFIER:"qualified_identifier"},gt={PARSE_FAILURE_NO_DETAIL:"parse returned success=false with no error detail",PARSE_FAILURE_RESULT:"AST parse returned failure result",PARSE_THREW:"AST parse threw (worker crash or rejection)",WORKER_UNCAUGHT_EXCEPTION:"AST worker uncaughtException",QUERY_COMPILE_FAILED:"AST language query failed to compile; using fallback",WORKER_UNHANDLED_REJECTION:"AST worker unhandledRejection",WORKER_EXITED_DURING_SHUTDOWN:"AST worker exited during pool shutdown (expected)",WORKER_CRASHED_EXITED:"AST worker crashed/exited",WORKER_EXITED_UNEXPECTEDLY:"Worker exited unexpectedly",UNKNOWN_FILE:"(unknown file)",PARSE_CACHE_HIT:"AST parse cache hit",CACHE_METRICS_AND_QUEUE_PERFORMANCE:"AST cache metrics and queue performance",TASK_TIMED_OUT_TERMINATING:"AST worker task timed out \u2014 terminating stuck worker",WORKER_TERMINATE_FAILED:"AST worker terminate() rejected \u2014 forced termination did not complete",QUERIED_VIA_LANGUAGE_PROVIDER:"Queried nodes using @workspace/ast-core LanguageProvider",ANONYMOUS_NAME:J,workerCrashWhileParsing:n=>`AST worker crashed while parsing ${n}: `,taskTimedOutAfterMs:(n,e)=>`AST worker task ${n} timed out after ${e}ms`,workerExitedWithCode:n=>`Worker exited with code ${n}`,noLanguageProviderForExtension:n=>`No language provider registered for extension ${n}`,wasmNotFound:(n,e)=>`WASM not found for ${n}, AST parsing skipped (Regex fallback used). Tried paths: ${e}`,parsedViaTreeSitter:n=>`Parsed via web-tree-sitter (nodes: ${n})`,providerQueryFailed:n=>`ast-core provider query failed: ${n}`};var p={FILE:"file",CLASS:"class",FUNCTION:"function",CALL:"call",METHOD_CALL:"method_call",IMPORT:"import",API_CONTRACT:"api_contract"};var N={IDENTIFIER:"identifier",SCOPED_IDENTIFIER:"scoped_identifier",QUALIFIED_IDENTIFIER:"qualified_identifier",DOTTED_NAME:"dotted_name",ALIASED_IMPORT:"aliased_import",USE_AS_CLAUSE:"use_as_clause",USE_WILDCARD:"use_wildcard",SCOPED_USE_LIST:"scoped_use_list",USE_LIST:"use_list",DOT:"dot",BLANK_IDENTIFIER:"blank_identifier",NAMESPACE_USE_DECLARATION:"namespace_use_declaration",INCLUDE_EXPRESSION:"include_expression",INCLUDE_ONCE_EXPRESSION:"include_once_expression",REQUIRE_EXPRESSION:"require_expression",REQUIRE_ONCE_EXPRESSION:"require_once_expression",IMPORT_STATEMENT:"import_statement",IMPORT_FROM_STATEMENT:"import_from_statement",USE_DECLARATION:"use_declaration",IMPORT_DECLARATION:"import_declaration",PREPROC_INCLUDE:"preproc_include",USING_DECLARATION:"using_declaration",CALL:"call",USING_DIRECTIVE:"using_directive",CALL_EXPRESSION:"call_expression",METHOD_INVOCATION:"method_invocation",EXPLICIT_CONSTRUCTOR_INVOCATION:"explicit_constructor_invocation",COMMAND_CALL:"command_call",FUNCTION_CALL_EXPRESSION:"function_call_expression",MEMBER_CALL_EXPRESSION:"member_call_expression",SCOPED_CALL_EXPRESSION:"scoped_call_expression",INVOCATION_EXPRESSION:"invocation_expression",OBJECT_CREATION_EXPRESSION:"object_creation_expression",MEMBER_EXPRESSION:"member_expression",ATTRIBUTE:"attribute",MEMBER_ACCESS_EXPRESSION:"member_access_expression",VARIABLE_DECLARATION:"variable_declaration",LEXICAL_DECLARATION:"lexical_declaration",VARIABLE_DECLARATOR:"variable_declarator",ARROW_FUNCTION:"arrow_function",FUNCTION_DECLARATION:"function_declaration",METHOD_DEFINITION:"method_definition",CLASS_DECLARATION:"class_declaration",INTERFACE_DECLARATION:"interface_declaration",TYPE_ALIAS_DECLARATION:"type_alias_declaration",EXPORT_STATEMENT:"export_statement"};var d="*",_e=["require","require_relative","load"],K="this",Ae="new";function wt(n){let e=[];for(let o of n){let r=o.type,i=pe[r];if(i){i(o,e);continue}if(be(r)){Ye(o,r,e);continue}Ge(o,e)}return e}var pe={[N.IMPORT_STATEMENT]:Ce,[N.EXPORT_STATEMENT]:Oe,[N.IMPORT_FROM_STATEMENT]:Se,[N.USE_DECLARATION]:$e,[N.IMPORT_DECLARATION]:Ue,[N.PREPROC_INCLUDE]:Me,[N.USING_DECLARATION]:ye,[N.CALL]:we,[N.USING_DIRECTIVE]:ke};function Ce(n,e){let o=n.descendantsOfType("string").pop();if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("namespace_import")[0];if(i){let c=i.descendantsOfType("identifier")[0];c&&e.push({localName:c.text,originalName:d,modulePath:r});return}let s=n.descendantsOfType("named_imports")[0];if(s){let c=s.descendantsOfType("import_specifier");for(let I of c){if(!I)continue;let E=I.childForFieldName("name"),f=I.childForFieldName("alias");if(E){let S=E.text,C=f?f.text:S;e.push({localName:C,originalName:S,modulePath:r})}}return}let a=n.descendantsOfType("identifier")[0];a&&e.push({localName:a.text,originalName:d,modulePath:r})}function Oe(n,e){let o=n.childForFieldName("source");if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("export_clause")[0];if(i)for(let s of i.descendantsOfType("export_specifier")){if(!s)continue;let a=s.childForFieldName("name");if(!a)continue;let c=s.childForFieldName("alias");e.push({localName:c?c.text:a.text,originalName:a.text,modulePath:r,viaReexport:!0})}}function Se(n,e){let o=n.childForFieldName("module_name");if(!o)return;let r=o.text;if(n.descendantsOfType("wildcard_import")[0])return;n.childForFieldName("name")&&He(n,r,e)}function Re(n,e){let o=n.childForFieldName("path"),r=n.childForFieldName("alias");o&&r&&e.push({localName:r.text,originalName:d,modulePath:o.text})}function Le(n,e,o){let r=n.childForFieldName("path"),i=n.childForFieldName("alias");r&&i&&o.push({localName:i.text,originalName:d,modulePath:`${e}::${r.text}`})}function he(n,e,o){let r=n.descendantsOfType("identifier").pop();r&&o.push({localName:r.text,originalName:d,modulePath:`${e}::${n.text}`})}function De(n,e,o){if(n.type===N.USE_AS_CLAUSE){Le(n,e,o);return}if(n.type===N.IDENTIFIER){o.push({localName:n.text,originalName:d,modulePath:`${e}::${n.text}`});return}n.type===N.SCOPED_IDENTIFIER&&he(n,e,o)}function Pe(n,e){let o=n.childForFieldName("path"),r=n.childForFieldName("list");if(!o||!r)return;let i=o.text;for(let s of r.namedChildren)s&&De(s,i,e)}function Fe(n,e){let o=n.descendantsOfType("identifier"),r=o[o.length-1];r&&e.push({localName:r.text,originalName:d,modulePath:n.text})}function ge(n,e){for(let o of n.namedChildren)o&&o.type===N.IDENTIFIER&&e.push({localName:o.text,originalName:d,modulePath:o.text})}function $e(n,e){let o=n.childForFieldName("argument");if(o){if(o.type===N.USE_AS_CLAUSE){Re(o,e);return}if(o.type!==N.USE_WILDCARD){if(o.type===N.SCOPED_USE_LIST){Pe(o,e);return}if(o.type===N.SCOPED_IDENTIFIER||o.type===N.IDENTIFIER){Fe(o,e);return}o.type===N.USE_LIST&&ge(o,e)}}}function xe(n,e){let o=n.childForFieldName("path");if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.childForFieldName("name");if(i){if(i.type===N.DOT||i.type===N.BLANK_IDENTIFIER)return;e.push({localName:i.text,originalName:d,modulePath:r})}else{let s=r.split("/"),a=s[s.length-1];e.push({localName:a,originalName:d,modulePath:r})}}function Ue(n,e){let o=n.descendantsOfType("import_spec_list")[0];if(!o)return;let r=o.descendantsOfType("import_spec");for(let i of r)i&&xe(i,e)}function Me(n,e){let o=n.childForFieldName("path");if(o){let r=o.text.replace(/[<>"']/g,"");e.push({localName:r,originalName:d,modulePath:r})}}function ye(n,e){let o=n.namedChildren;for(let r of o)if(r)if(r.type===N.QUALIFIED_IDENTIFIER){let i=r.descendantsOfType("identifier"),s=i[i.length-1];s&&e.push({localName:s.text,originalName:d,modulePath:r.text})}else r.type===N.IDENTIFIER&&e.push({localName:r.text,originalName:d,modulePath:r.text})}function we(n,e){let o=n.childForFieldName("method");if(!o)return;let r=o.text;if(!_e.includes(r))return;let i=n.childForFieldName("arguments");if(!i)return;let s=i.descendantsOfType("string_content")[0]||i.descendantsOfType("string")[0];if(!s)return;let a=s.text.replace(/['"]/g,""),c=a.replace(/\.rb$/,"");e.push({localName:c,originalName:d,modulePath:a})}function be(n){return n===N.NAMESPACE_USE_DECLARATION||n===N.INCLUDE_EXPRESSION||n===N.INCLUDE_ONCE_EXPRESSION||n===N.REQUIRE_EXPRESSION||n===N.REQUIRE_ONCE_EXPRESSION}function Xe(n,e){let o=n.descendantsOfType("qualified_name")[0]||n.descendantsOfType("name")[0];if(o){let r=o.text,i=r.split("\\"),s=i[i.length-1];e.push({localName:s,originalName:d,modulePath:r})}}function ve(n,e){let o=n.descendantsOfType("string")[0]||n.descendantsOfType("string_content")[0];if(o){let r=o.text.replace(/['"]/g,"");e.push({localName:r,originalName:d,modulePath:r})}}function Ye(n,e,o){e===N.NAMESPACE_USE_DECLARATION?Xe(n,o):ve(n,o)}function ke(n,e){let o=n.descendantsOfType("qualified_name")[0]||n.descendantsOfType("identifier")[0];if(o){let r=o.text,i=r.split("."),s=i[i.length-1];e.push({localName:s,originalName:d,modulePath:r})}}function Ge(n,e){let o=n.descendantsOfType("string").pop();if(!o)return;let r=o.text.replace(/['"]/g,""),i=n.descendantsOfType("identifier");for(let s of i)s&&(e.some(a=>a.localName===s.text)||e.push({localName:s.text,originalName:s.text,modulePath:r}))}function He(n,e,o){if(n.childForFieldName("name")){for(let i of n.namedChildren)if(i)if(i.type===N.ALIASED_IMPORT){let s=i.childForFieldName("name"),a=i.childForFieldName("alias");s&&a&&o.push({localName:a.text,originalName:s.text,modulePath:e})}else if(i.type===N.DOTTED_NAME){let s=i.descendantsOfType("identifier"),a=s[s.length-1];a&&o.push({localName:a.text,originalName:i.text,modulePath:e})}else i.type===N.IDENTIFIER&&o.push({localName:i.text,originalName:i.text,modulePath:e})}}function Be(n){let e=n.childForFieldName("function");if(!e)return{isMethodCall:!1,methodName:""};if(e.type===N.MEMBER_EXPRESSION){let o=e.childForFieldName("property"),r=e.childForFieldName("object");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}return{isMethodCall:!1,methodName:e.text}}function Qe(n){let e=n.childForFieldName("function");if(!e)return{isMethodCall:!1,methodName:""};if(e.type===N.ATTRIBUTE){let o=e.childForFieldName("attribute"),r=e.childForFieldName("object");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}return{isMethodCall:!1,methodName:e.text}}function Ve(n){let e=n.childForFieldName("name"),o=n.childForFieldName("object");if(e)return{isMethodCall:!0,methodName:e.text,objectName:o?.text}}function je(n){return{isMethodCall:!0,methodName:n.childForFieldName("constructor")?.text||K,objectName:K}}function We(n){let e=n.childForFieldName("method");if(!e)return;let o=n.childForFieldName("receiver");return o?{isMethodCall:!0,methodName:e.text,objectName:o.text}:{isMethodCall:!1,methodName:e.text}}function M(n){let e=n.type,r=n.childForFieldName("name")?.text||"";if(e===N.MEMBER_CALL_EXPRESSION){let i=n.childForFieldName("object");return{isMethodCall:!0,methodName:r,objectName:i?.text}}if(e===N.SCOPED_CALL_EXPRESSION){let i=n.childForFieldName("scope");return{isMethodCall:!0,methodName:r,objectName:i?.text}}return{isMethodCall:!1,methodName:r}}function qe(n){let e=n.childForFieldName("function")||n.namedChildren[0];if(e&&e.type===N.MEMBER_ACCESS_EXPRESSION){let o=e.childForFieldName("name"),r=e.childForFieldName("expression");if(o)return{isMethodCall:!0,methodName:o.text,objectName:r?.text}}if(e)return{isMethodCall:!1,methodName:e.text}}function Je(n){let e=n.childForFieldName("type");return{isMethodCall:!0,methodName:Ae,objectName:e?.text}}var bt={[N.CALL_EXPRESSION]:Be,[N.CALL]:Qe,[N.METHOD_INVOCATION]:Ve,[N.EXPLICIT_CONSTRUCTOR_INVOCATION]:je,[N.COMMAND_CALL]:We,[N.FUNCTION_CALL_EXPRESSION]:M,[N.MEMBER_CALL_EXPRESSION]:M,[N.SCOPED_CALL_EXPRESSION]:M,[N.INVOCATION_EXPRESSION]:qe,[N.OBJECT_CREATION_EXPRESSION]:Je};var Ke=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,L=class n extends Date{#t=!1;#n=!1;#e=null;constructor(e){let o=!0,r=!0,i="Z";if(typeof e=="string"){let s=e.match(Ke);s?(s[1]||(o=!1,e=`0000-01-01T${e}`),r=!!s[2],r&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=o,this.#n=r,this.#e=i)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let o=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return o=this.#e[0]==="-"?o:-o,new Date(this.getTime()-o*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,o="Z"){let r=new n(e);return r.#e=o,r}static wrapAsLocalDateTime(e){let o=new n(e);return o.#e=null,o}static wrapAsLocalDate(e){let o=new n(e);return o.#n=!1,o.#e=null,o}static wrapAsLocalTime(e){let o=new n(e);return o.#t=!1,o.#e=null,o}};function ze(n,e){let o=n.slice(0,e).split(/\r\n|\n|\r/g);return[o.length,o.pop().length+1]}function Ze(n,e,o){let r=n.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let a=e-1;a<=e+1;a++){let c=r[a-1];c&&(i+=a.toString().padEnd(s," "),i+=": ",i+=c,i+=`
|
|
3
3
|
`,a===e&&(i+=" ".repeat(s+o+2),i+=`^
|
|
4
4
|
`))}return i}var T=class extends Error{line;column;codeblock;constructor(e,o){let[r,i]=ze(o.toml,o.ptr),s=Ze(o.toml,r,i);super(`Invalid TOML document: ${e}
|
|
5
5
|
|
|
@@ -59,4 +59,4 @@ smol-toml/dist/index.js:
|
|
|
59
59
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
60
60
|
*)
|
|
61
61
|
*/
|
|
62
|
-
//# sourceMappingURL=chunk-
|
|
62
|
+
//# sourceMappingURL=chunk-WBNMCSX3.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
var a={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error"};var u="ipc-log";function
|
|
2
|
+
var a={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error"};var u="ipc-log";function S(t){return typeof t=="object"&&t!==null&&t.type===u}var I=class{constructor(e){this.postMessageFn=e}postMessageFn;debug(e,o){this.send(a.DEBUG,e,o)}info(e,o){this.send(a.INFO,e,o)}warn(e,o){this.send(a.WARN,e,o)}error(e,o){this.send(a.ERROR,e,o)}onLog(){return()=>{}}send(e,o,r){let s=r?{type:u,level:e,message:o,context:r}:{type:u,level:e,message:o};this.postMessageFn(s)}};var _={CONTEXT_INJECTION:"context-injection",COMMIT_L3_WRITE:"commit-l3-write",TIER_B_C_PREPUSH:"tier-b-c-prepush"},Q={[_.CONTEXT_INJECTION]:!0,[_.COMMIT_L3_WRITE]:!0,[_.TIER_B_C_PREPUSH]:!0};var J=".docuvia",q="logs",z="init.log",Z="clean.log",$="status.log",ee="sync.log",te="analyze.log",oe="review.log",re="impact.log",ne="query.log",se="export-topology.log",ie="snapshot.log",ae="hydrate.log",ce="sync-knowledge.log",le="node_modules",pe="local.db",ge="init.lock",de="tierC.lock",ue="sync-state.json",me="hooks-config.json",Ee="pending-l3-decisions.json";var R="utf8";var _e="sha256";var i={TYPESCRIPT:"typescript",JAVASCRIPT:"javascript",PYTHON:"python",RUST:"rust",GO:"go",JAVA:"java",C:"c",CPP:"cpp",RUBY:"ruby",PHP:"php",CSHARP:"csharp"};var fe=".claude/hooks",Te=".cursor/hooks",ye="docuvia-hook.js",Le="docuvia-hook.cjs";var m=class{listeners=new Set;debug(e,o){this.emit(a.DEBUG,e,o)}info(e,o){this.emit(a.INFO,e,o)}warn(e,o){this.emit(a.WARN,e,o)}error(e,o){this.emit(a.ERROR,e,o)}onLog(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e,o,r){let s=r?{level:e,message:o,context:r}:{level:e,message:o};for(let l of this.listeners)l(s)}};function Se(){return new m}var h=class{constructor(e){this.logger=e}logger;handleMessage(e){return S(e)?(this.logger[e.level](e.message,e.context),!0):!1}};var g={GIT_COMMAND_FAILED:"GIT_COMMAND_FAILED",GIT_NETWORK_TIMEOUT:"GIT_NETWORK_TIMEOUT",GIT_NOT_A_REPOSITORY:"GIT_NOT_A_REPOSITORY",GIT_BRANCH_CREATE_FAILED:"GIT_BRANCH_CREATE_FAILED",GIT_HOOK_INSTALL_FAILED:"GIT_HOOK_INSTALL_FAILED",GIT_FAST_IMPORT_FAILED:"GIT_FAST_IMPORT_FAILED",DB_OPEN_FAILED:"DB_OPEN_FAILED",DB_NOT_FOUND:"DB_NOT_FOUND",DB_MIGRATION_FAILED:"DB_MIGRATION_FAILED",DB_QUERY_FAILED:"DB_QUERY_FAILED",DB_LOCKED:"DB_LOCKED",AST_WORKER_CRASHED:"AST_WORKER_CRASHED",AST_PARSE_FAILED:"AST_PARSE_FAILED",FS_READ_FAILED:"FS_READ_FAILED",FS_PATH_TRAVERSAL:"FS_PATH_TRAVERSAL",FACTORY_TOKEN_NOT_REGISTERED:"FACTORY_TOKEN_NOT_REGISTERED",FACTORY_LOCKED:"FACTORY_LOCKED",MEMORY_SCOPE_NOT_FOUND:"MEMORY_SCOPE_NOT_FOUND",SYNC_FETCH_FAILED:"SYNC_FETCH_FAILED",SYNC_PUSH_FAILED:"SYNC_PUSH_FAILED",LLM_NOT_INITIALIZED:"LLM_NOT_INITIALIZED",LLM_CHAT_COMPLETION_FAILED:"LLM_CHAT_COMPLETION_FAILED",LLM_STREAM_FAILED:"LLM_STREAM_FAILED",LLM_INVALID_RESPONSE:"LLM_INVALID_RESPONSE",INIT_WORKFLOW_FAILED:"INIT_WORKFLOW_FAILED",CLEAN_WORKFLOW_FAILED:"CLEAN_WORKFLOW_FAILED",INVALID_INPUT:"INVALID_INPUT"};var Ie="DocuviaError",c=class t extends Error{code;cause;constructor(e,o,r){super(o),this.name=Ie,this.code=e,this.cause=r}static wrap(e,o,r){if(r instanceof t)return r;let s=r instanceof Error?r.message:String(r);return new t(e,`${o}: ${s}`,r)}};var Re={WORKSPACE_ROOT:"workspaceRoot",API_URL:"apiUrl",PAT:"pat",PROJECT_ID:"projectId",COMMIT_SHA:"commitSha",TARGET_PATH:"targetPath",LLM_BASE_URL:"llmBaseUrl",LLM_MODEL:"llmModel",BASE_REF:"baseRef",TARGET:"target",ESCALATE_TO_LSP:"escalateToLsp",TIER_B_FULL_RESYNC:"tierBFullResync",LIMIT:"limit",COLLAPSE:"collapse",KEEP_DB:"keepDb",LSP_BINARY_OVERRIDE:"lspBinaryOverride",LSP_ARGS_OVERRIDE:"lspArgsOverride",LSP_TIMEOUT_MS:"lspTimeoutMs",LSP_MAX_PROCESSES:"lspMaxProcesses",TIER_B_COMMIT_CAP:"tierBCommitCap",TIER_C_DAILY_CALL_CAP:"tierCDailyCallCap",TIER_C_DAILY_TOKEN_CAP:"tierCDailyTokenCap",TIER_C_WALL_CLOCK_MS:"tierCWallClockMs",TIER_C_ITEM_CAP:"tierCItemCap",TIER_C_LOAD_THRESHOLD:"tierCLoadThreshold",GIT_NETWORK_TIMEOUT_MS:"gitNetworkTimeoutMs",FORCE:"force",AGENT_AUTHORED_DECISIONS:"agentAuthoredDecisions",HOOK_NAME:"hookName",HOOK_ENABLED:"hookEnabled",FLUSH_STAGED_L3:"flushStagedL3"},he={SCOPE_NOT_FOUND:(t,e)=>`Cannot set "${t}": memory scope "${e}" was never created`},f=class{scopes=new Map;createScope(e){this.scopes.has(e)||this.scopes.set(e,new Map)}set(e,o,r){let s=this.scopes.get(e);if(!s)throw new c(g.MEMORY_SCOPE_NOT_FOUND,he.SCOPE_NOT_FOUND(o,e));s.set(o,r)}get(e,o){return this.scopes.get(e)?.get(o)}deleteScope(e){this.scopes.delete(e)}hasScope(e){return this.scopes.has(e)}},Ce=new f;var x={REGISTER_LOCKED:t=>`Cannot register "${t}": factory is locked (test isolation)`,PROVIDER_NOT_REGISTERED:t=>`No provider registered for "${t}" \u2014 the implementation library that owns it was never imported for its registration side effect`},T=class{providers=new Map;locked=!1;register(e,o){if(this.locked)throw new c(g.FACTORY_LOCKED,x.REGISTER_LOCKED(String(e.description)));this.providers.set(e,o)}resolve(e,o){let r=this.providers.get(e);if(!r)throw new c(g.FACTORY_TOKEN_NOT_REGISTERED,x.PROVIDER_NOT_REGISTERED(String(e.description)));return r(this,o)}has(e){return this.providers.has(e)}lock(){this.locked=!0}unlock(){this.locked=!1}reset(){this.providers.clear(),this.locked=!1}},D=new T;function n(t){return Symbol(t)}var Ae={GitProvider:n("IGitProvider"),LineBlameProvider:n("ILineBlameProvider"),KnowledgeGitService:n("IKnowledgeGitService"),FileDiscovery:n("IFileDiscovery"),ConfigScanner:n("IConfigScanner"),VcsScanner:n("IVcsScanner"),AstProcessor:n("IAstProcessor"),GraphPersister:n("IGraphPersister"),TempFileManager:n("TempFileManager"),GraphStoreOpener:n("GraphStoreOpener"),RemoteSyncClient:n("RemoteSyncClient"),LlmClient:n("LlmClient"),QueryService:n("IQueryService"),TierBCoverageHintProvider:n("ITierBCoverageHintProvider"),ImpactService:n("IImpactService"),ChangeDetectionService:n("IChangeDetectionService"),TopologyBuilder:n("ITopologyBuilder"),SnapshotRenderer:n("ISnapshotRenderer"),HydrationService:n("IHydrationService"),DiagnosticRunnerDb:n("DiagnosticRunnerDb"),DiagnosticRunnerGit:n("DiagnosticRunnerGit"),SemanticDiffAnalyzer:n("ISemanticDiffAnalyzer"),EdgeResolutionProviders:n("EdgeResolutionProviders")};var Ne={ADDED:"added",MODIFIED:"modified",DELETED:"deleted",RENAMED:"renamed"};var Oe={LSP:"lsp",LLM_INFERRED:"llm-inferred"},Pe={TYPESCRIPT:"typescript",PYTHON:"python",GO:"go",RUST:"rust",JAVA:"java",CPP:"cpp",CSHARP:"csharp",PHP:"php",RUBY:"ruby"};var ve={NO_REMOTE:"no-remote",UP_TO_DATE:"up-to-date",FAST_FORWARDED_LOCAL:"fast-forwarded-local",PUSHED_LOCAL:"pushed-local",MERGED:"merged"};var xe={MODULE:"module",PACKAGE:"package",PCD:"pcd"},De={CONTAINS:"contains",CALLS:"calls",IMPLEMENTS:"implements",EXTENDS:"extends",IMPORTS:"imports",DEPENDS_ON:"depends_on",DECISION:"decision"};var Me={PENDING:"pending",ACTIVE:"active",DRAFT:"draft",GARBAGE:"garbage"},be={ANALYZE:"analyze",AGENT_AUTHORED:"agent-authored"};var ke={CREATE_L3:"CREATE_L3"};var Fe={SYSTEM:"system",USER:"user",ASSISTANT:"assistant",TOOL:"tool"};var we={LOW:"LOW",MEDIUM:"MEDIUM",HIGH:"HIGH",CRITICAL:"CRITICAL",UNKNOWN:"UNKNOWN"},Ge={EXACT:"exact",LOWER_BOUND:"lower-bound"},He={LSP_FALLBACK:"lsp-fallback"};var Be={L2:"l2",L3:"l3"};var Ke={FILE:"file",SYMBOL:"symbol",DECISION:"decision"},Ue={AUTO:"auto",FILE:"file",SYMBOL:"symbol"},je={L1_TAG:"l1_tag",DIRECTORY:"directory"};var Ye={TYPESCRIPT:"typescript",REACT:"react",EXPRESS:"express",VUE:"vue"},Ve={UNKNOWN:"unknown",JAVASCRIPT:"javascript",GENERIC:"generic",RUST:"rust",PYTHON:"python",GO:"go"},We="general",Xe={FRONTEND:"frontend",BACKEND:"backend",NEXTJS:"nextjs",SSR:"ssr",DRIZZLE:"drizzle",DATABASE:"database",TAILWINDCSS:"tailwindcss",CSS:"css",JEST:"jest",TESTING:"testing",VITEST:"vitest",POSTGRES:"postgres",MONOREPO:"monorepo",TOKIO:"tokio",ASYNC:"async",ACTIX:"actix",SERDE:"serde",TAURI:"tauri",DESKTOP:"desktop",DJANGO:"django",FASTAPI:"fastapi",PANDAS:"pandas",DATA:"data",GIN:"gin",STRICT_TS:"strict-ts",VITE:"vite",BUILD_TOOL:"build-tool"};var M="origin",C={KNOWLEDGE_ROOT:"docuvia-knowledge",KNOWLEDGE_DIR_NAME:"knowledge",GRAPH_DIR_NAME:"graph",L3_DIR_NAME:"_l3",NODES_JSONL_NAME:"nodes.jsonl",EDGES_JSONL_NAME:"edges.jsonl",SOURCE_COMMIT_TRAILER_KEY:"Docuvia-Source",POST_COMMIT_HOOK_NAME:"post-commit",POST_COMMIT_HOOK_MARKER:"docuvia analyze",POST_COMMIT_FLUSH_L3_MARKER:"docuvia analyze --flush-staged-l3",POST_COMMIT_NOHUP_MARKER:"nohup npx --no-install docuvia analyze",DOCUVIA_HOOK_HEADER_COMMENT:"# Docuvia Knowledge Graph Evolver Hook",POST_COMMIT_HOOK_CONTENT:`#!/bin/bash
|
|
3
3
|
# Docuvia Knowledge Graph Evolver Hook
|
|
4
4
|
# Non-intrusively extracts AST deltas in the background
|
|
5
5
|
if command -v npx > /dev/null 2>&1; then
|
|
@@ -35,7 +35,7 @@ if command -v npx &> /dev/null; then
|
|
|
35
35
|
# Fire and forget (do not block commit)
|
|
36
36
|
npx --no-install docuvia snapshot > /dev/null 2>&1 &
|
|
37
37
|
fi
|
|
38
|
-
`,LOCAL_REMOTE_URL_SCHEME:"file://",DEFAULT_REMOTE_NAME:M,REMOTE_REF_PREFIX:"refs/remotes/",HEAD_REF:"HEAD",DEFAULT_LOCAL_PROJECT_ID:1,META_KEY_KNOWLEDGE_TIP_SHA:"hydratedKnowledgeSha",META_KEY_LAST_INGESTED_SOURCE_SHA:"lastIngestedSourceSha",META_KEY_NODE_KEY_FORMAT_VERSION:"nodeKeyFormatVersion",META_KEY_TIER_B_QUEUE:"tierBQueue",EMPTY_KNOWLEDGE_TEMP_DIR_PREFIX:"docuvia-empty-knowledge-",META_KEY_LAST_TIER_B_BATCH_SHA:"lastTierBBatchSha",META_KEY_TIER_B_BATCH_PENDING:"tierBBatchPending",META_KEY_KNOWLEDGE_PACK_PENDING:"knowledgePackPending",META_KEY_TIER_B_CHANGED_BYTES:"tierBChangedBytes",DEFAULT_TIER_B_COMMIT_CAP_BYTES:512e3,DEFAULT_TIER_B_COVERAGE_FAIL_THRESHOLD:.5,DEFAULT_L2_SEMANTIC_COVERAGE_FAIL_THRESHOLD:.1,META_KEY_TIER_B_ZERO_PROGRESS_BATCHES:"tierBZeroProgressBatches",DEFAULT_TIER_B_ZERO_PROGRESS_MAX_BATCHES:3,DEFAULT_POST_COMMIT_INGESTION_GRACE_MS:6e5,PRE_PUSH_HOOK_NAME:"pre-push",PRE_PUSH_HOOK_MARKER:"docuvia analyze --escalate-to-lsp",PRE_PUSH_SYNC_KNOWLEDGE_MARKER:"docuvia sync-knowledge",PRE_PUSH_ENV_GATE_MARKER:"--fallback-ast",PRE_PUSH_HOOKS_CHECK_MARKER:"docuvia hooks check",PRE_PUSH_HOOK_CONTENT:`#!/bin/bash
|
|
38
|
+
`,LOCAL_REMOTE_URL_SCHEME:"file://",DEFAULT_REMOTE_NAME:M,REMOTE_REF_PREFIX:"refs/remotes/",HEAD_REF:"HEAD",DEFAULT_LOCAL_PROJECT_ID:1,META_KEY_KNOWLEDGE_TIP_SHA:"hydratedKnowledgeSha",META_KEY_LAST_INGESTED_SOURCE_SHA:"lastIngestedSourceSha",META_KEY_NODE_KEY_FORMAT_VERSION:"nodeKeyFormatVersion",META_KEY_TIER_B_QUEUE:"tierBQueue",EMPTY_KNOWLEDGE_TEMP_DIR_PREFIX:"docuvia-empty-knowledge-",META_KEY_LAST_TIER_B_BATCH_SHA:"lastTierBBatchSha",META_KEY_TIER_B_BATCH_PENDING:"tierBBatchPending",META_KEY_KNOWLEDGE_PACK_PENDING:"knowledgePackPending",META_KEY_TIER_B_CHANGED_BYTES:"tierBChangedBytes",DEFAULT_TIER_B_COMMIT_CAP_BYTES:512e3,DEFAULT_TIER_B_COVERAGE_FAIL_THRESHOLD:.5,DEFAULT_L2_SEMANTIC_COVERAGE_FAIL_THRESHOLD:.1,META_KEY_TIER_B_ZERO_PROGRESS_BATCHES:"tierBZeroProgressBatches",DEFAULT_TIER_B_ZERO_PROGRESS_MAX_BATCHES:3,DEFAULT_POST_COMMIT_INGESTION_GRACE_MS:6e5,META_KEY_CALL_RESOLUTION_STATS:"callResolutionStats",DEFAULT_CALL_RESOLUTION_NOTE_THRESHOLD:.5,DEFAULT_CALL_RESOLUTION_MIN_SAMPLE:5,DEFAULT_CANARY_SAMPLE_SIZE:20,PRE_PUSH_HOOK_NAME:"pre-push",PRE_PUSH_HOOK_MARKER:"docuvia analyze --escalate-to-lsp",PRE_PUSH_SYNC_KNOWLEDGE_MARKER:"docuvia sync-knowledge",PRE_PUSH_ENV_GATE_MARKER:"--fallback-ast",PRE_PUSH_HOOKS_CHECK_MARKER:"docuvia hooks check",PRE_PUSH_HOOK_CONTENT:`#!/bin/bash
|
|
39
39
|
# Docuvia Tier B Batch Hook (LSP escalation + snapshot + knowledge sync)
|
|
40
40
|
# Runs synchronously (generous timeout) so pushed code carries corrected knowledge -- see
|
|
41
41
|
# docs/gitbook/analysis/phase1-decision-integration.md \xA78h and
|
|
@@ -82,6 +82,6 @@ fi
|
|
|
82
82
|
# Never blocks the push on a Tier B failure -- PLAT-007's reliability requirement (failures
|
|
83
83
|
# only ever surface via JSONL logs / doctor, never to the pushing developer).
|
|
84
84
|
exit 0
|
|
85
|
-
`,META_KEY_TIER_C_QUEUE:"tierCQueue",META_KEY_TIER_C_BUDGET:"tierCBudget",DEFAULT_TIER_C_DAILY_CALL_CAP:50,DEFAULT_TIER_C_DAILY_TOKEN_CAP:1e5,DEFAULT_TIER_C_WALL_CLOCK_MS:12e3,DEFAULT_TIER_C_ITEM_CAP:20,DEFAULT_TIER_C_LOAD_THRESHOLD:.8,DEFAULT_TIER_C_MAX_ITEM_FAILURES:3};import
|
|
86
|
-
`)){let o=e.trim();if(o.startsWith(W))return o.slice(W.length).trim()}}function at(t,e,o,r){if(!o&&!r)return;let l=(e?t.files.getTierBFileStatus(e):void 0)?.lastProcessedAt??null,E=r&&l===null,p=t.files.getTierBCoverage(),X=o&&p.processedFiles<p.totalFiles;if(!(!E&&!X))return{ownFileLastProcessedAt:l,workspaceFilesProcessed:p.processedFiles,workspaceFilesTotal:p.totalFiles}}
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
85
|
+
`,META_KEY_TIER_C_QUEUE:"tierCQueue",META_KEY_TIER_C_BUDGET:"tierCBudget",DEFAULT_TIER_C_DAILY_CALL_CAP:50,DEFAULT_TIER_C_DAILY_TOKEN_CAP:1e5,DEFAULT_TIER_C_WALL_CLOCK_MS:12e3,DEFAULT_TIER_C_ITEM_CAP:20,DEFAULT_TIER_C_LOAD_THRESHOLD:.8,DEFAULT_TIER_C_MAX_ITEM_FAILURES:3};import y from"path";var b=[".ts",".tsx",".mts",".cts"],k=[".js",".jsx",".mjs",".cjs"],F=[".py"],w=[".rs"],G=[".go"],H=[".java"],B=[".c",".h"],K=[".cpp",".cxx",".cc",".hpp",".hxx",".hh",".cu",".cuh"],U=[".rb",".rake",".gemspec"],j=[".php",".phtml",".php3",".php4",".php5",".phps"],Y=[".cs"],A=new Set(["Rakefile","Gemfile","Guardfile","Vagrantfile","Brewfile"]),N=(()=>{let t=new Map,e=[[i.TYPESCRIPT,b],[i.JAVASCRIPT,k],[i.PYTHON,F],[i.RUST,w],[i.GO,G],[i.JAVA,H],[i.C,B],[i.CPP,K],[i.RUBY,U],[i.PHP,j],[i.CSHARP,Y]];for(let[o,r]of e)for(let s of r)t.set(s,o);return t})();function Qe(t){let e=N.get(y.extname(t).toLowerCase());return e||(A.has(y.basename(t))?i.RUBY:void 0)}function Je(t){return N.has(y.extname(t).toLowerCase())?!0:A.has(y.basename(t))}function qe(){return Array.from(N.keys()).map(t=>t.replace(/^\./,""))}var O="EEXIST",L="EPERM",P="EACCES",v="EBUSY";import d from"fs/promises";var ze={TIMED_OUT_WAITING:t=>`Timed out waiting for the lock at ${t} \u2014 another process may be stuck`},Ze={maxWaitMs:1e4,retryIntervalMs:100,heartbeatIntervalMs:1e4,staleAfterMs:3e4};function $e(t){return new Promise(e=>setTimeout(e,t))}function et(t){try{return process.kill(t,0),!0}catch(e){return e.code===L}}async function tt(t){try{let e=Number.parseInt(await d.readFile(t,R),10);return Number.isFinite(e)?e:void 0}catch{return}}async function ot(t,e){let o=await d.stat(t).catch(()=>{});if(!o||Date.now()-o.mtimeMs<=e)return!1;let r=await tt(t);return r!==void 0&&et(r)?!1:(await d.rm(t,{force:!0}).catch(()=>{}),!0)}function rt(t){let e=t.code;return e===O||e===L||e===P||e===v}async function nt(t){try{let e=await d.open(t,"wx");return await e.writeFile(String(process.pid)),await e.close(),!0}catch(e){if(!rt(e))throw e;return!1}}async function st(t,e={}){let o={...Ze,...e},r=Date.now()+o.maxWaitMs,s=!1;for(;!await nt(t);)if(s||(s=!0,e.onWaiting?.()),!await ot(t,o.staleAfterMs)){if(Date.now()>r)throw new Error(ze.TIMED_OUT_WAITING(t));await $e(o.retryIntervalMs)}let l=setInterval(()=>{let p=new Date;d.utimes(t,p,p).catch(()=>{})},o.heartbeatIntervalMs);l.unref?.();let E=!1;return{async release(){E||(E=!0,clearInterval(l),await d.rm(t,{force:!0}).catch(()=>{}))}}}var W=`${C.SOURCE_COMMIT_TRAILER_KEY}: `;function it(t){for(let e of t.split(`
|
|
86
|
+
`)){let o=e.trim();if(o.startsWith(W))return o.slice(W.length).trim()}}function at(t,e,o,r){if(!o&&!r)return;let l=(e?t.files.getTierBFileStatus(e):void 0)?.lastProcessedAt??null,E=r&&l===null,p=t.files.getTierBCoverage(),X=o&&p.processedFiles<p.totalFiles;if(!(!E&&!X))return{ownFileLastProcessedAt:l,workspaceFilesProcessed:p.processedFiles,workspaceFilesTotal:p.totalFiles}}function ct(t){let e={total:0,resolved:0,selfDiscarded:0,unresolved:0,unresolvable:0};for(let o of Object.values(t))e.total+=o.total,e.resolved+=o.resolved,e.selfDiscarded+=o.selfDiscarded,e.unresolvable=(e.unresolvable??0)+(o.unresolvable??0),e.unresolved+=o.unresolved;return e}var lt={PASS:"pass",FAIL:"fail"};export{a,m as b,Se as c,I as d,h as e,g as f,c as g,Re as h,Ce as i,D as j,Ae as k,Ne as l,Oe as m,Pe as n,ve as o,xe as p,De as q,Me as r,be as s,ke as t,Fe as u,we as v,Ge as w,He as x,Be as y,Ke as z,Ue as A,je as B,_ as C,Q as D,J as E,q as F,z as G,Z as H,$ as I,ee as J,te as K,oe as L,re as M,ne as N,se as O,ie as P,ae as Q,ce as R,le as S,pe as T,ge as U,de as V,ue as W,me as X,Ee as Y,Ye as Z,Ve as _,We as $,Xe as aa,R as ba,_e as ca,M as da,C as ea,i as fa,b as ga,k as ha,F as ia,w as ja,G as ka,H as la,B as ma,K as na,U as oa,j as pa,Y as qa,A as ra,Qe as sa,Je as ta,qe as ua,O as va,L as wa,P as xa,v as ya,st as za,it as Aa,at as Ba,ct as Ca,lt as Da,fe as Ea,Te as Fa,ye as Ga,Le as Ha};
|
|
87
|
+
//# sourceMappingURL=chunk-XIDGZQW2.js.map
|