project-graph-mcp 1.5.0 → 2.1.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.
Files changed (125) hide show
  1. package/README.md +171 -31
  2. package/docs/img/explorer-compact.jpg +0 -0
  3. package/docs/img/explorer-expanded.jpg +0 -0
  4. package/package.json +12 -8
  5. package/src/.project-graph-cache.json +1 -1
  6. package/src/analysis/analysis-cache.js +7 -0
  7. package/src/analysis/complexity.js +14 -0
  8. package/src/analysis/custom-rules.js +36 -0
  9. package/src/analysis/db-analysis.js +9 -0
  10. package/src/analysis/dead-code.js +19 -0
  11. package/src/analysis/full-analysis.js +18 -0
  12. package/src/analysis/jsdoc-checker.js +24 -0
  13. package/src/analysis/jsdoc-generator.js +10 -0
  14. package/src/analysis/large-files.js +11 -0
  15. package/src/analysis/outdated-patterns.js +12 -0
  16. package/src/analysis/similar-functions.js +16 -0
  17. package/src/analysis/test-annotations.js +21 -0
  18. package/src/analysis/type-checker.js +8 -0
  19. package/src/analysis/undocumented.js +14 -0
  20. package/src/cli/cli-handlers.js +4 -0
  21. package/src/cli/cli.js +5 -0
  22. package/src/compact/.project-graph-cache.json +1 -0
  23. package/src/compact/ai-context.js +7 -0
  24. package/src/compact/compact-migrate.js +17 -0
  25. package/src/compact/compact.js +18 -0
  26. package/src/compact/compress.js +14 -0
  27. package/src/compact/ctx-to-jsdoc.js +29 -0
  28. package/src/compact/doc-dialect.js +30 -0
  29. package/src/compact/expand.js +37 -0
  30. package/src/compact/framework-references.js +5 -0
  31. package/src/compact/instructions.js +3 -0
  32. package/src/compact/mode-config.js +8 -0
  33. package/src/compact/validate-pipeline.js +9 -0
  34. package/src/core/event-bus.js +9 -0
  35. package/src/core/filters.js +14 -0
  36. package/src/core/graph-builder.js +12 -0
  37. package/src/core/parser.js +31 -0
  38. package/src/core/workspace.js +8 -0
  39. package/src/lang/lang-go.js +17 -0
  40. package/src/lang/lang-python.js +12 -0
  41. package/src/lang/lang-sql.js +23 -0
  42. package/src/lang/lang-typescript.js +9 -0
  43. package/src/lang/lang-utils.js +4 -0
  44. package/src/mcp/mcp-server.js +17 -0
  45. package/src/mcp/tool-defs.js +3 -0
  46. package/src/mcp/tools.js +25 -0
  47. package/src/network/backend-lifecycle.js +19 -0
  48. package/src/network/backend.js +5 -0
  49. package/src/network/local-gateway.js +23 -0
  50. package/src/network/mdns.js +13 -0
  51. package/src/network/server.js +10 -0
  52. package/src/network/web-server.js +34 -0
  53. package/web/.project-graph-cache.json +1 -0
  54. package/web/app.js +17 -0
  55. package/web/components/code-block.js +3 -0
  56. package/web/components/quick-open.js +5 -0
  57. package/web/dashboard-state.js +3 -0
  58. package/web/dashboard.html +27 -0
  59. package/web/dashboard.js +8 -0
  60. package/web/highlight.js +13 -0
  61. package/web/index.html +35 -0
  62. package/web/panels/ActionBoard/ActionBoard.css.js +1 -0
  63. package/web/panels/ActionBoard/ActionBoard.js +4 -0
  64. package/web/panels/ActionBoard/ActionBoard.tpl.js +1 -0
  65. package/web/panels/EventItem/EventItem.css.js +1 -0
  66. package/web/panels/EventItem/EventItem.js +4 -0
  67. package/web/panels/EventItem/EventItem.tpl.js +1 -0
  68. package/web/panels/ProjectItem/ProjectItem.css.js +1 -0
  69. package/web/panels/ProjectItem/ProjectItem.js +5 -0
  70. package/web/panels/ProjectItem/ProjectItem.tpl.js +1 -0
  71. package/web/panels/ProjectList/ProjectList.css.js +1 -0
  72. package/web/panels/ProjectList/ProjectList.js +4 -0
  73. package/web/panels/ProjectList/ProjectList.tpl.js +1 -0
  74. package/web/panels/SettingsPanel/.project-graph-cache.json +1 -0
  75. package/web/panels/SettingsPanel/SettingsPanel.css.js +1 -0
  76. package/web/panels/SettingsPanel/SettingsPanel.js +7 -0
  77. package/web/panels/SettingsPanel/SettingsPanel.tpl.js +1 -0
  78. package/web/panels/code-viewer.js +5 -0
  79. package/web/panels/ctx-panel.js +4 -0
  80. package/web/panels/dep-graph.js +6 -0
  81. package/web/panels/file-tree.js +188 -0
  82. package/web/panels/health-panel.js +3 -0
  83. package/web/panels/live-monitor.js +3 -0
  84. package/web/state.js +17 -0
  85. package/web/style.css +157 -0
  86. package/references/symbiote-3x.md +0 -834
  87. package/src/ai-context.js +0 -113
  88. package/src/analysis-cache.js +0 -155
  89. package/src/cli-handlers.js +0 -271
  90. package/src/cli.js +0 -95
  91. package/src/compact.js +0 -207
  92. package/src/complexity.js +0 -237
  93. package/src/compress.js +0 -319
  94. package/src/ctx-to-jsdoc.js +0 -514
  95. package/src/custom-rules.js +0 -584
  96. package/src/db-analysis.js +0 -194
  97. package/src/dead-code.js +0 -468
  98. package/src/doc-dialect.js +0 -716
  99. package/src/filters.js +0 -227
  100. package/src/framework-references.js +0 -177
  101. package/src/full-analysis.js +0 -470
  102. package/src/graph-builder.js +0 -299
  103. package/src/instructions.js +0 -73
  104. package/src/jsdoc-checker.js +0 -351
  105. package/src/jsdoc-generator.js +0 -203
  106. package/src/lang-go.js +0 -285
  107. package/src/lang-python.js +0 -197
  108. package/src/lang-sql.js +0 -309
  109. package/src/lang-typescript.js +0 -190
  110. package/src/lang-utils.js +0 -124
  111. package/src/large-files.js +0 -163
  112. package/src/mcp-server.js +0 -675
  113. package/src/mode-config.js +0 -127
  114. package/src/outdated-patterns.js +0 -296
  115. package/src/parser.js +0 -662
  116. package/src/server.js +0 -28
  117. package/src/similar-functions.js +0 -279
  118. package/src/test-annotations.js +0 -323
  119. package/src/tool-defs.js +0 -793
  120. package/src/tools.js +0 -470
  121. package/src/type-checker.js +0 -188
  122. package/src/undocumented.js +0 -259
  123. package/src/workspace.js +0 -70
  124. /package/{AGENT_ROLE.md → docs/examples/AGENT_ROLE.md} +0 -0
  125. /package/{AGENT_ROLE_MINIMAL.md → docs/examples/AGENT_ROLE_MINIMAL.md} +0 -0
@@ -0,0 +1,37 @@
1
+ // @ctx .context/src/compact/expand.ctx
2
+ import{readFileSync as t,writeFileSync as e,mkdirSync as n,existsSync as s,readdirSync as r,statSync as o}from"fs";import{join as a,basename as i,extname as c,dirname as p,relative as l}from"path";import{minify as m}from"../../vendor/terser.mjs";import{parse as d}from"../../vendor/acorn.mjs";import{simple as f,ancestor as u}from"../../vendor/walk.mjs";function parseCtxSignatures(t){const e=new Map;if(!t)return e;for(const n of t.split("\n")){const t=n.trim();if(!t||t.startsWith("---")||t.startsWith("@")||t.startsWith("CALLS")||t.startsWith("R→")||t.startsWith("W→")||t.startsWith("PATTERNS:")||t.startsWith("EDGE_CASES:")||t.startsWith("Rules:")||t.startsWith("Save this"))continue;
3
+ const s=t.match(/^class\s+([\w]+)([^|]*)\|([^|]*)\|?(.*)$/);if(s){e.set(s[1],{type:"class",extends:s[2].replace(/\s*extends\s*/,"").trim()||null,meta:s[3].trim(),description:s[4]?.trim()||"",exported:!1});continue}const r=t.match(/^\s+\.(\w+)\(([^)]*)\)\|?(.*)$/);if(r){e.set(r[1],{type:"method",params:parseCtxParams(r[2]),description:r[3]?.trim()||""});continue}const o=t.match(/^(export\s+)?(\w+)\(([^)]*)\)(→[^|]*)?\|(.*)$/);if(o){const t=o[2],n=o[3],s=o[4]||"",r=(o[5]||"").split("|"),a=r[0]?.trim()||"";e.set(t,{type:"function",params:parseCtxParams(n),returnType:extractReturnType(s),description:a,exported:!!o[1]});continue}}return e}
4
+ function parseCtxParams(t){return t&&t.trim()?t.split(",").map(t=>{const e=t.trim();if(!e)return null;
5
+ const n=e.match(/^(\w+)(\?)?(?::(\w[\w<>\[\]|.]*))?(\=)?$/);if(n)return{name:n[1],type:n[3]||null,optional:!(!n[2]&&!n[4])};
6
+ const s=e.match(/^(\w+)(=)?$/);return s?{name:s[1],type:null,optional:!!s[2]}:"..."===e?{name:"args",type:null,rest:!0}:{name:e.replace(/[=?:].*/g,""),type:null}}).filter(Boolean):[]}
7
+ function extractReturnType(t){if(!t)return null;
8
+ const e=t.match(/^→([A-Z][\w<>\[\]|]*)/);return e?e[1]:null}
9
+ function sanitizeJSDocText(t){return t.replace(/\*\//g,"*\\/")}
10
+ function generateJSDoc(t){const e=["/**"];if(t.description&&"{DESCRIBE}"!==t.description&&e.push(` * ${sanitizeJSDocText(t.description)}`),t.params&&t.params.length>0)for(const n of t.params){const t=n.type||"*",s=n.optional?`[${n.name}]`:n.name;e.push(` * @param {${t}} ${s}`)}return t.returnType&&e.push(` * @returns {${t.returnType}}`),e.push(" */"),e.join("\n")}
11
+ function parseCtxVars(t){const e=new Map;if(!t)return e;for(const n of t.split("\n")){const t=n.trim();if(t.startsWith("@vars ")){const n=t.slice(6).split(",");for(const t of n){const n=t.trim().split("=");2===n.length&&e.set(n[0].trim(),n[1].trim())}}}return e}
12
+ function parseCtxNames(t){const e=new Map;if(!t)return e;for(const n of t.split("\n")){const t=n.trim();if(t.startsWith("@names ")){const n=t.slice(7).split(/\s+/);for(const t of n){const n=t.indexOf(":");if(-1===n)continue;
13
+ const s=t.slice(0,n),r=t.slice(n+1),o=new Map;for(const t of r.split(",")){const e=t.trim().split("=");2===e.length&&o.set(e[0].trim(),e[1].trim())}o.size>0&&e.set(s,o)}}}return e}
14
+ function restoreNames(t,e,n,s,r){const o=new Map,a=[];for(const t of e.body)if("ImportDeclaration"===t.type)for(const e of t.specifiers)if("ImportSpecifier"===e.type&&e.imported.name!==e.local.name)o.set(e.local.name,e.imported.name),a.push({s:e.start,e:e.end,n:e.imported.name});else if("ImportDefaultSpecifier"===e.type){const n=t.source.value.replace(/^node:/,"").split("/").pop().replace(/\.\w+$/,"").replace(/-(\w)/g,(t,e)=>e.toUpperCase());n&&/^[a-zA-Z_$][\w$]*$/.test(n)&&n!==e.local.name&&(o.set(e.local.name,n),a.push({s:e.start,e:e.end,n:n}))}else if("ImportNamespaceSpecifier"===e.type&&e.local.name.length<=2){const n=t.source.value.replace(/^node:/,"").split("/").pop().replace(/\.\w+$/,"").replace(/-(\w)/g,(t,e)=>e.toUpperCase());n&&/^[a-zA-Z_$][\w$]*$/.test(n)&&n!==e.local.name&&(o.set(e.local.name,n),a.push({s:e.start,e:e.end,n:"* as "+n}))}for(const[t,e]of s)o.set(t,e);if(r.has("__top__"))for(const[t,e]of r.get("__top__"))o.set(t,e);
15
+ const i=new Set(o.values());for(const[t]of[...o])i.has(t)&&o.delete(t);
16
+ const c=[],p=[],l=[];function collectLocals(t){const e=new Set;return f(t,{VariableDeclarator(t){t.id&&"Identifier"===t.id.type&&e.add(t.id.name)},CatchClause(t){t.param&&"Identifier"===t.param.type&&e.add(t.param.name)}}),e}
17
+ function collectLocalDecls(t){const e=[];return f(t,{VariableDeclarator(t){t.id&&"Identifier"===t.id.type&&e.push(t.id)}}),e}const pf=t=>{const e=t.params.map(t=>"Identifier"===t.type?t.name:"AssignmentPattern"===t.type&&"Identifier"===t.left?.type?t.left.name:"RestElement"===t.type&&"Identifier"===t.argument?.type?t.argument.name:null).filter(Boolean),s=new Map;if(t.id?.name){const o=n.get(t.id.name);if(o?.params)for(let t=0;t<Math.min(e.length,o.params.length);t++)e[t]!==o.params[t].name&&s.set(e[t],o.params[t].name);
18
+ const a=r.get(t.id.name);if(a)for(const[t,e]of a)s.has(t)||s.set(t,e);if(s.size>0)for(const e of t.params){const t="Identifier"===e.type?e:"AssignmentPattern"===e.type&&"Identifier"===e.left?.type?e.left:null;t&&s.has(t.name)&&p.push({s:t.start,e:t.end,n:s.get(t.name)})}}const o=collectLocals(t.body);for(const t of e)o.add(t);
19
+ const a=t.id?.name&&r.get(t.id.name);for(const e of collectLocalDecls(t.body)){const t=a?.get(e.name);t&&l.push({s:e.start,e:e.end,n:t})}c.push({s:t.params.length>0?t.params[0].start:t.body.start,e:t.body.end,p:o,r:s})};f(e,{FunctionDeclaration:pf,FunctionExpression:pf,ArrowFunctionExpression:pf});for(const t of e.body)if("VariableDeclaration"===t.type)for(const e of t.declarations)e.id&&"Identifier"===e.id.type&&o.has(e.id.name)&&l.push({s:e.id.start,e:e.id.end,n:o.get(e.id.name)});
20
+ const m=[...a,...p,...l];u(e,{Identifier(t,e,n){const s=n[n.length-2];if("MemberExpression"===s?.type&&s.property===t&&!s.computed)return;if("Property"===s?.type&&s.key===t&&!s.computed&&s.value!==t)return;if("ExportSpecifier"===s?.type)return;
21
+ const r=t.name;
22
+ let a=null;for(const e of c)t.start>=e.s&&t.end<=e.e&&(!a||e.e-e.s<a.e-a.s)&&(a=e);a&&a.p.has(r)?a.r.has(r)&&m.push({s:t.start,e:t.end,n:a.r.get(r)}):o.has(r)&&m.push({s:t.start,e:t.end,n:o.get(r)})}}),m.sort((t,e)=>e.s-t.s);
23
+ let d=t;for(const t of m)d=d.slice(0,t.s)+t.n+d.slice(t.e);return d}
24
+ export async function expandFile(e,n,s={}){const{indentLevel:r=2}=s,o=t(e,"utf-8");if(!o.trim())return{code:"",injected:0,original:0,decompiled:0};
25
+ let a;try{a=(await m(o,{compress:!1,mangle:!1,module:!0,output:{beautify:!0,comments:!1,indent_level:r,semicolons:!0}})).code||o}catch{a=o}{const t=a.split("\n"),e=[];for(let n=0;n<t.length;n++){const s=t[n];if(""===s.trim()){let s=n+1;for(;s<t.length&&""===t[s].trim();)s++;if(n>0&&e.length>0&&e[e.length-1].startsWith("import ")&&s<t.length&&t[s].startsWith("import "))continue}e.push(s)}a=e.join("\n")}a=a.replace(/^( +)/gm,t=>{const e=Math.floor(t.length/r);return"\t".repeat(e)+" ".repeat(t.length%r)});
26
+ const i=parseCtxSignatures(n),c=parseCtxVars(n),p=parseCtxNames(n);
27
+ let l;try{l=d(a,{ecmaVersion:"latest",sourceType:"module",locations:!0})}catch{return{code:a,injected:0,original:o.length,decompiled:a.length}}try{a=restoreNames(a,l,i,c,p),l=d(a,{ecmaVersion:"latest",sourceType:"module",locations:!0})}catch{}if(0===i.size)return{code:a,injected:0,original:o.length,decompiled:a.length};
28
+ const u=[];f(l,{ExportNamedDeclaration(t){const e=t.declaration;if(e){if("FunctionDeclaration"===e.type&&e.id?.name){const n=i.get(e.id.name);n&&u.push({pos:t.start,jsdoc:generateJSDoc(n)})}if("ClassDeclaration"===e.type&&e.id?.name){const n=i.get(e.id.name);n&&n.description&&u.push({pos:t.start,jsdoc:`/**\n * ${n.description}\n */`})}}},FunctionDeclaration(t){if(!t.id?.name)return;
29
+ const e=i.get(t.id.name);e&&!e.exported&&u.push({pos:t.start,jsdoc:generateJSDoc(e)})},ClassDeclaration(t){if(!t.id?.name)return;
30
+ const e=i.get(t.id.name);e&&!e.exported&&e.description&&u.push({pos:t.start,jsdoc:`/**\n * ${e.description}\n */`})}}),u.sort((t,e)=>e.pos-t.pos);
31
+ let h=a,y=0;for(const{pos:t,jsdoc:e}of u){const n=h.lastIndexOf("\n",t-1),s=-1===n?0:n+1,r=h.slice(s,t).match(/^(\s*)/)?.[1]||"",o=e.split("\n").map(t=>r+t).join("\n");h=h.slice(0,t)+o+"\n"+h.slice(t),y++}return{code:h,injected:y,original:o.length,decompiled:h.length}}const h=new Set(["node_modules",".git","vendor",".context","dev-docs",".agent",".agents",".expanded","web"]),y=new Set([".js",".mjs"]);function walkJSFiles(t,e=t){const n=[];try{for(const s of r(t)){if(s.startsWith(".")&&"."!==s)continue;
32
+ const r=a(t,s);o(r).isDirectory()?h.has(s)||n.push(...walkJSFiles(r,e)):y.has(c(s).toLowerCase())&&n.push(r)}}catch{}return n}
33
+ function resolveCtx(e,n){const r=i(n,c(n))+".ctx",o=p(n),l=a(e,o,r);if(s(l))return t(l,"utf-8");
34
+ const m=a(e,".context",o,r);return s(m)?t(m,"utf-8"):null}
35
+ export async function expandProject(t,r={}){const{dryRun:o=!1,outputDir:i}=r,c=i||a(t,".expanded"),m=a(t,"src");if(!s(m))return{error:"No src/ directory found",files:0};
36
+ const d=walkJSFiles(m,t),f=[],u=[];
37
+ let h=0;for(const r of d){const i=l(t,r);try{const l=resolveCtx(t,i),m=await expandFile(r,l);if(!o){const t=a(c,i),r=p(t);s(r)||n(r,{recursive:!0}),e(t,m.code,"utf-8")}f.push({file:i,injected:m.injected,original:m.original,decompiled:m.decompiled}),h+=m.injected}catch(t){u.push({file:i,error:t.message})}}return{outputDir:c,files:f.length,totalJSDocInjected:h,fileDetails:f,errors:u.length>0?u:void 0,dryRun:o}}
@@ -0,0 +1,5 @@
1
+ // @ctx .context/src/compact/framework-references.ctx
2
+ import{readFileSync as e,readdirSync as t,existsSync as r,writeFileSync as n}from"fs";import{join as o,basename as a,dirname as s}from"path";import{fileURLToPath as c}from"url";import{detectProjectRuleSets as i}from"../analysis/custom-rules.js";
3
+ const f=s(c(import.meta.url)),m=o(f,"..","..","docs","references"),l={"symbiote-3x":"https://raw.githubusercontent.com/symbiotejs/symbiote.js/main/AI_REFERENCE.md"},u=new Map;async function fetchReference(t){const a=l[t],s=o(m,`${t}.md`),c=u.get(t);if(c&&Date.now()-c.fetchedAt<36e5)return{content:c.content,source:"cache"};if(a)try{const e=await fetch(a,{signal:AbortSignal.timeout(5e3)});if(e.ok){const r=await e.text();u.set(t,{content:r,fetchedAt:Date.now()});try{n(s,r,"utf-8")}catch(e){}return{content:r,source:`github (${a})`}}}catch(e){}if(r(s)){const r=e(s,"utf-8");return u.set(t,{content:r,fetchedAt:Date.now()}),{content:r,source:"local"}}return{content:"",source:"not_found"}}const d={"symbiote-3x":"symbiote-3x","symbiote-2x":"symbiote-3x"};function listAvailable(){const e=new Set(Object.keys(l));if(r(m))for(const r of t(m))r.endsWith(".md")&&e.add(a(r,".md"));return[...e]}
4
+ export async function getFrameworkReference(e={}){const t=listAvailable();if(e.framework){if(!t.includes(e.framework))return{error:`Framework reference '${e.framework}' not found`,available:t};const{content:r,source:n}=await fetchReference(e.framework);return r?{framework:e.framework,source:n,lines:r.split("\n").length,content:r}:{error:`Failed to load reference '${e.framework}'`,available:t}}if(e.path){const{detected:r,reasons:n}=i(e.path),o=[];for(const e of r){const r=d[e];r&&t.includes(r)&&!o.includes(r)&&o.push(r)}if(0===o.length)return{error:"No framework references found for this project",detected:r,reasons:n,available:t};
5
+ const a=await Promise.all(o.map(fetchReference)),s=a.map(e=>e.content).filter(Boolean);return{frameworks:o,sources:a.map(e=>e.source),detected:{rulesets:r,reasons:n},lines:s.reduce((e,t)=>e+t.split("\n").length,0),content:s.join("\n\n---\n\n")}}return{error:"Specify framework name or path for auto-detection",available:t.map(e=>({name:e,remote:!!l[e],url:l[e]??null}))}}
@@ -0,0 +1,3 @@
1
+ // @ctx .context/src/compact/instructions.ctx
2
+ export const AGENT_INSTRUCTIONS='\n# 🤖 Project Guidelines for AI Agents\n\n## 1. Architecture Standards (Symbiote.js)\n- **Component Structure**: Always use Triple-File Partitioning for components:\n - `MyComponent.js`: Class logic (extends Symbiote)\n - `MyComponent.tpl.js`: HTML template (export template)\n - `MyComponent.css.js`: CSS styles (export rootStyles/shadowStyles)\n- **State Management**: Use `this.init$` for local state and `this.sub()` for reactivity.\n- **Directives**: Use `itemize` for lists, `js-d-kit` for static generation.\n\n## 2. General Coding Rules\n- **ESM Only**: Use `import` / `export`. No `require`.\n- **No Dependencies**: Avoid adding new npm packages unless critical.\n- **Comments**: Write clear JSDoc for all public methods.\n- **Async/Await**: Prefer async/await over promises.\n\n## 3. MCP Tools Usage\n- **Graph**: Use `get_skeleton` first to map the codebase.\n- **Deep Dive**: Use `expand` to read class details.\n- **Tests**: Use `get_pending_tests` to see what needs verification.\n- **Guidelines**: Use `get_agent_instructions` to refresh these rules.\n\n## 4. Custom Rules System\nConfigurable code analysis with auto-detection.\n\n### Available Tools\n- `get_custom_rules`: List all rulesets and their rules\n- `set_custom_rule`: Add or update a rule in a ruleset\n- `check_custom_rules`: Run analysis (auto-detects applicable rulesets)\n\n### Auto-Detection\nRulesets are applied automatically based on:\n1. `package.json` dependencies\n2. Import patterns in source code\n3. Code patterns (e.g., `extends Symbiote`)\n\n### Creating New Rules\nUse `set_custom_rule` to add framework-specific rules:\n```json\n{\n "ruleSet": "my-framework-2x",\n "rule": {\n "id": "my-rule-id",\n "name": "Rule Name",\n "description": "What this rule checks",\n "pattern": "badPattern",\n "patternType": "string",\n "replacement": "Use goodPattern instead",\n "severity": "warning",\n "filePattern": "*.js",\n "docs": "https://docs.example.com/rule"\n }\n}\n```\n\n### Severity Levels\n- `error`: Critical issues that must be fixed\n- `warning`: Important but not blocking\n- `info`: Suggestions and best practices\n';
3
+ export function getInstructions(){return AGENT_INSTRUCTIONS}
@@ -0,0 +1,8 @@
1
+ // @ctx .context/src/compact/mode-config.ctx
2
+ import{readFileSync as e,writeFileSync as t,existsSync as d,mkdirSync as o}from"fs";import{join as a,dirname as n}from"path";
3
+ const r=".context/config.json",c={mode:2,beautify:!0,autoValidate:!1,stripJSDoc:!1};
4
+ export function getConfig(t){const o=a(t,r);if(!d(o))return{...c};try{const t=e(o,"utf-8"),d=JSON.parse(t),s={...c,...d};if(![1,2].includes(s.mode)){s.mode=2}return s}catch{return{...c}}}
5
+ export function setConfig(e,c){const i=a(e,r),s=n(i);d(s)||o(s,{recursive:!0});
6
+ const f={...getConfig(e),...c};if(![1,2].includes(f.mode))throw new Error(`Invalid mode: ${f.mode}. Valid: 1 (compact), 2 (full)`);return t(i,JSON.stringify(f,null,2)+"\n","utf-8"),{saved:!0,path:i,config:f}}
7
+ export function getModeDescription(e){switch(e){case 1:return"Compact — minified source + .expanded/ cache for human review (recommended)";case 2:return"Full — formatted source, agents use compressed view for reading";default:return`Unknown mode: ${e}`}}
8
+ export function getModeWorkflow(e){switch(e){case 1:return{read:"Read .js files directly (compact source = fewer tokens)",write:"Write .js files directly (compact output = cheaper output tokens)",review:".expanded/ cache with restored names + JSDoc for human review",validate:"Run validate_pipeline → contracts + expand + AST verify",expand:"Run expand_project to regenerate .expanded/ from compact + .ctx",migrate:"Run compact-migrate to convert formatted source → compact"};case 2:return{read:"Use get_compressed_file for token-efficient reading",write:"Use edit_compressed(path, symbol, code) for AST-safe editing",review:"Read source files directly (already formatted)",validate:"Run validate-ctx to check .ctx ↔ AST consistency"};default:return{read:"N/A",write:"N/A",review:"N/A",validate:"N/A"}}}
@@ -0,0 +1,9 @@
1
+ // @ctx .context/src/compact/validate-pipeline.ctx
2
+ import{readFileSync as s,readdirSync as e,statSync as t,existsSync as o}from"fs";import{join as r,extname as a,relative as n}from"path";import{parse as i}from"../../vendor/acorn.mjs";import{validateCtxContracts as c}from"./ctx-to-jsdoc.js";import{expandProject as l}from"./expand.js";
3
+ const f=new Set([".js",".mjs"]),d=new Set(["node_modules",".git","vendor",".context","dev-docs",".agent",".agents",".expanded","web"]);function walkJSFiles(s){const o=[];try{for(const n of e(s)){if(n.startsWith(".")&&"."!==n)continue;
4
+ const e=r(s,n);t(e).isDirectory()?d.has(n)||o.push(...walkJSFiles(e)):f.has(a(n).toLowerCase())&&o.push(e)}}catch{}return o}
5
+ function estimateTokens(s){return Math.ceil(s.length/4)}
6
+ export async function validatePipeline(e,t={}){const{strict:a=!1,skipDecompile:f=!1}=t,d=Date.now(),m=c(e,{strict:a});
7
+ let u=null;f||(u=await l(e));
8
+ const p=r(e,".expanded"),S={passed:0,failed:0,errors:[]};if(o(p)){const e=walkJSFiles(p);for(const t of e){const e=n(p,t);try{const e=s(t,"utf-8");i(e,{ecmaVersion:"latest",sourceType:"module"}),S.passed++}catch(s){S.failed++,S.errors.push({file:e,error:s.message,line:s.loc?.line})}}}const j=r(e,"src"),y={compact:0,full:0,savings:"0%"};if(o(j)&&o(p)){const e=walkJSFiles(j);for(const t of e){const e=n(j,t),a=s(t,"utf-8");y.compact+=estimateTokens(a);
9
+ const i=r(p,"src",e);if(o(i)){const e=s(i,"utf-8");y.full+=estimateTokens(e)}else y.full+=estimateTokens(a)}y.full>0&&(y.savings=Math.round(100*(1-y.compact/y.full))+"%")}const w=Date.now()-d,h=m.summary?.errors||0,v=S.failed,g=h+v;return{status:0===g?"PASS":"FAIL",duration:`${w}ms`,contracts:{files:m.files,errors:m.summary?.errors||0,warnings:m.summary?.warnings||0,violations:m.violations?.slice(0,20)},expand:u?{files:u.files,jsdocInjected:u.totalJSDocInjected,errors:u.errors}:null,astVerify:{passed:S.passed,failed:S.failed,errors:S.errors.slice(0,10)},tokens:y,summary:{totalErrors:g,contractErrors:h,astErrors:v,filesProcessed:u?.files||0,jsdocInjected:u?.totalJSDocInjected||0,tokenSavings:y.savings}}}
@@ -0,0 +1,9 @@
1
+ // @ctx .context/src/core/event-bus.ctx
2
+ import{EventEmitter as o}from"node:events";
3
+ const t=new o;t.setMaxListeners(50);
4
+ export function emitToolCall(o,e){t.emit("tool:call",{type:"tool_call",tool:o,args:e,ts:Date.now()})}
5
+ export function emitToolResult(o,e,l,n,s){t.emit("tool:result",{type:"tool_result",tool:o,args:e,duration_ms:n,success:s,result_keys:l?Object.keys(l):[],ts:Date.now()})}
6
+ export function onToolCall(o){t.on("tool:call",o)}
7
+ export function onToolResult(o){t.on("tool:result",o)}
8
+ export function removeToolListener(o,e){t.off(o,e)}
9
+ export default t;
@@ -0,0 +1,14 @@
1
+ // @ctx .context/src/core/filters.ctx
2
+ import{readFileSync as e,existsSync as t}from"fs";import{join as r}from"path";
3
+ const i=["node_modules","dist","build","coverage",".next",".nuxt",".output","__pycache__",".cache",".turbo","out"],n=["*.test.js","*.spec.js","*.min.js","*.bundle.js","*.d.ts",".project-graph-cache.json"];
4
+ let s={excludeDirs:[...i],excludePatterns:[...n],includeHidden:!1,useGitignore:!0,gitignorePatterns:[]};
5
+ export function getFilters(){return{...s}}
6
+ export function setFilters(e){return void 0!==e.excludeDirs&&(s.excludeDirs=e.excludeDirs),void 0!==e.excludePatterns&&(s.excludePatterns=e.excludePatterns),void 0!==e.includeHidden&&(s.includeHidden=e.includeHidden),void 0!==e.useGitignore&&(s.useGitignore=e.useGitignore),getFilters()}
7
+ export function addExcludes(e){return s.excludeDirs=[...new Set([...s.excludeDirs,...e])],getFilters()}
8
+ export function removeExcludes(e){return s.excludeDirs=s.excludeDirs.filter(t=>!e.includes(t)),getFilters()}
9
+ export function resetFilters(){return s={excludeDirs:[...i],excludePatterns:[...n],includeHidden:!1,useGitignore:!0,gitignorePatterns:[]},getFilters()}
10
+ export function parseGitignore(i){const n=r(i,".gitignore");if(!t(n))return[];try{const t=e(n,"utf-8").split("\n").map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.replace(/\/$/,""));return s.gitignorePatterns=t,t}catch(e){return[]}}
11
+ export function shouldExcludeDir(e,t=""){if(!s.includeHidden&&e.startsWith("."))return!0;if(s.excludeDirs.includes(e))return!0;if(s.useGitignore)for(const r of s.gitignorePatterns)if(matchGitignorePattern(r,e,t))return!0;return!1}
12
+ export function shouldExcludeFile(e,t=""){for(const t of s.excludePatterns)if(matchWildcard(t,e))return!0;if(s.useGitignore)for(const r of s.gitignorePatterns)if(matchGitignorePattern(r,e,t))return!0;return!1}
13
+ function matchWildcard(e,t){const r=e.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}
14
+ function matchGitignorePattern(e,t,r){return e===t||(e.includes("*")?matchWildcard(e,t):!!(r?`${r}/${t}`:t).includes(e))}
@@ -0,0 +1,12 @@
1
+ // @ctx .context/src/core/graph-builder.ctx
2
+ export function minifyLegend(e){const s={},t=new Set;for(const o of e){let e=createShortName(o),n=1;for(;t.has(e);)e=createShortName(o)+n,n++;t.add(e),s[o]=e}return s}
3
+ function createShortName(e){const s=e.replace(/[a-z]/g,"");if(s.length>=2)return s.slice(0,3);
4
+ const t=e.match(/[A-Z]/g);return t&&t.length>0?e[0].toLowerCase()+t[0]:e.slice(0,2)}
5
+ export function buildGraph(e){const s=e.classes||[],t=e.functions||[],o=[...s.map(e=>e.name),...t.map(e=>e.name),...s.flatMap(e=>e.methods||[])],n=minifyLegend([...new Set(o)]),c=Object.fromEntries(Object.entries(n).map(([e,s])=>[s,e])),f={v:1,legend:n,reverseLegend:c,stats:{files:(e.files||[]).length,classes:s.length,functions:t.length,tables:(e.tables||[]).length},nodes:{},edges:[],orphans:[],duplicates:{},files:e.files||[]};for(const e of s){const s=n[e.name];f.nodes[s]={t:"C",x:e.extends||void 0,m:(e.methods||[]).map(e=>n[e]||e),$:(e.properties||[]).length?e.properties:void 0,i:e.imports?.length?e.imports:void 0,f:e.file||void 0};for(const t of e.calls||[])if(t.includes(".")){const[e,o]=t.split(".");if(n[e]){const t=[s,"→",`${n[e]}.${n[o]||o}`];f.edges.push(t)}}else if(n[t]){const e=[s,"→",n[t]];f.edges.push(e)}}for(const e of t){const s=n[e.name];f.nodes[s]={t:"F",e:e.exported,f:e.file||void 0};for(const t of e.dbReads||[])f.edges.push([s,"R→",t]);for(const t of e.dbWrites||[])f.edges.push([s,"W→",t])}for(const e of s){const s=n[e.name];for(const t of e.dbReads||[])f.edges.push([s,"R→",t]);for(const t of e.dbWrites||[])f.edges.push([s,"W→",t])}for(const s of e.tables||[])f.nodes[s.name]={t:"T",cols:s.columns.map(e=>e.name),f:s.file||void 0};
6
+ const r=new Set;for(const e of f.edges){const s=e[2].split(".")[0];r.add(s)}for(const e of Object.keys(f.nodes))r.has(e)||"F"!==f.nodes[e].t||f.nodes[e].e||f.orphans.push(c[e]);
7
+ const l=Object.create(null);for(const e of s)for(const s of e.methods||[])l[s]||(l[s]=[]),l[s].push(`${e.name}:${e.line}`);for(const[e,s]of Object.entries(l))s.length>1&&(f.duplicates[e]=s);return f}
8
+ export function createSkeleton(e,s=null){const t={},o={};for(const[s,n]of Object.entries(e.legend)){const c=e.nodes[n];if(c&&"C"===c.t){const e=c.m?.length||0,f=c.$?.length||0;if(0===e&&0===f)continue;t[n]=s;
9
+ const r={m:e};f>0&&(r.$=f),c.f&&(r.f=c.f),o[n]=r}}const n={};for(const[s,o]of Object.entries(e.legend)){const c=e.nodes[o];if("F"===c?.t&&c.e){t[o]=s;
10
+ const e=c.f||"?";n[e]||(n[e]=[]),n[e].push(o)}}const c=new Set;for(const e of Object.values(o))e.f&&c.add(e.f);for(const e of Object.keys(n))c.add(e);
11
+ const f={};for(const s of e.files||[]){if(c.has(s))continue;
12
+ const e=s.lastIndexOf("/"),t=e>=0?s.slice(0,e+1):"./",o=e>=0?s.slice(e+1):s;f[t]||(f[t]=[]),f[t].push(o)}const r={v:e.v,L:t,s:e.stats,n:o,X:n,e:e.edges.length,o:e.orphans.length,d:Object.keys(e.duplicates).length};if(Object.keys(f).length>0&&(r.f=f),s&&s.length>0){const t=new Set(e.files||[]),o=s.filter(e=>!t.has(e));if(o.length>0){const e={};for(const s of o){const t=s.lastIndexOf("/"),o=t>=0?s.slice(0,t+1):"./",n=t>=0?s.slice(t+1):s;e[o]||(e[o]=[]),e[o].push(n)}r.a=e}}return r}
@@ -0,0 +1,31 @@
1
+ // @ctx .context/src/core/parser.ctx
2
+ import{readFileSync as e,readdirSync as t,statSync as s,existsSync as n}from"fs";import{join as r,relative as o,resolve as a}from"path";import{parse as i}from"../../vendor/acorn.mjs";import*as l from"../../vendor/walk.mjs";import{shouldExcludeDir as c,shouldExcludeFile as p,parseGitignore as u}from"./filters.js";import{parseTypeScript as f}from"../lang/lang-typescript.js";import{parsePython as d}from"../lang/lang-python.js";import{parseGo as m}from"../lang/lang-go.js";import{parseSQL as h,extractSQLFromString as y,isSQLString as g}from"../lang/lang-sql.js";
3
+ const x=[".js",".ts",".tsx",".py",".go",".sql"];
4
+ export async function parseFile(e,t){const s={file:t,classes:[],functions:[],imports:[],exports:[]},n=[];
5
+ let r;try{r=i(e,{ecmaVersion:"latest",sourceType:"module",locations:!0,onComment:n})}catch(e){return console.warn(`Parse error in ${t}:`,e.message),s}const o=buildJSDocTypeMap(n,e),a=new Set;l.simple(r,{ImportDeclaration(e){for(const t of e.specifiers)"ImportDefaultSpecifier"===t.type?s.imports.push(t.local.name):"ImportSpecifier"===t.type&&s.imports.push(t.imported.name)},ExportNamedDeclaration(e){if(e.declaration)if(e.declaration.id)a.add(e.declaration.id.name);else if(e.declaration.declarations)for(const t of e.declaration.declarations)a.add(t.id.name);if(e.specifiers)for(const t of e.specifiers)a.add(t.exported.name)},ExportDefaultDeclaration(e){e.declaration&&e.declaration.id&&a.add(e.declaration.id.name)},ClassDeclaration(e){const n={name:e.id.name,extends:e.superClass?e.superClass.name:null,methods:[],properties:[],calls:[],dbReads:[],dbWrites:[],file:t,line:e.loc.start.line};for(const t of e.body.body)if("MethodDefinition"===t.type&&"constructor"!==t.key.name)n.methods.push(t.key.name),extractCallsAndSQL(t.value.body,n.calls,n.dbReads,n.dbWrites);else if("PropertyDefinition"===t.type&&"init$"===t.key.name&&t.value&&"ObjectExpression"===t.value.type)for(const e of t.value.properties)e.key&&e.key.name&&n.properties.push(e.key.name);s.classes.push(n)},FunctionDeclaration(e){if(e.id){const n=e.params.map(e=>"Identifier"===e.type?e.name:"AssignmentPattern"===e.type&&"Identifier"===e.left.type?e.left.name+"=":"RestElement"===e.type&&"Identifier"===e.argument.type?"..."+e.argument.name:"ObjectPattern"===e.type?"options":"?"),r=findJSDocForNode(o,e.loc.start.line),a=enrichParamsWithTypes(n,r),i={name:e.id.name,exported:!1,params:a,async:e.async||!1,returns:r?.returns||null,calls:[],dbReads:[],dbWrites:[],file:t,line:e.loc.start.line};extractCallsAndSQL(e.body,i.calls,i.dbReads,i.dbWrites),s.functions.push(i)}}});for(const e of s.functions)e.exported=a.has(e.name);return s.exports=[...a],s}const S=new Set(["query","execute","raw","exec","queryFile","none","one","many","any","oneOrNone","manyOrNone","result"]);function extractCallsAndSQL(e,t,s,n){e&&l.simple(e,{CallExpression(e){const r=e.callee;if("MemberExpression"===r.type){const e=r.object,s=r.property;if("Identifier"===s.type)if("Identifier"===e.type){const n=`${e.name}.${s.name}`;t.includes(n)||t.push(n)}else if("MemberExpression"===e.type&&"Identifier"===e.property.type){const n=`${e.property.name}.${s.name}`;t.includes(n)||t.push(n)}else if("ThisExpression"===e.type){const e=s.name;t.includes(e)||t.push(e)}}else if("Identifier"===r.type){const e=r.name;t.includes(e)||t.push(e)}if(s&&n){const t=getCallMethodName(e);if(t&&S.has(t)&&e.arguments.length>0){const t=extractStringValue(e.arguments[0]);if(t&&g(t)){const e=y(t);e.reads.forEach(e=>{s.includes(e)||s.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}}}},TaggedTemplateExpression(e){if(!s||!n)return;
6
+ const t=getTagName(e.tag);if(t&&/sql/i.test(t)){const t=templateToString(e.quasi);if(t){const e=y(t);e.reads.forEach(e=>{s.includes(e)||s.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}}},TemplateLiteral(e){if(!s||!n)return;
7
+ const t=templateToString(e);if(t&&g(t)){const e=y(t);e.reads.forEach(e=>{s.includes(e)||s.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}},Literal(e){if(s&&n&&"string"==typeof e.value&&g(e.value)){const t=y(e.value);t.reads.forEach(e=>{s.includes(e)||s.push(e)}),t.writes.forEach(e=>{n.includes(e)||n.push(e)})}}})}
8
+ function getTagName(e){return"Identifier"===e.type?e.name:"MemberExpression"===e.type&&"Identifier"===e.property.type?e.property.name:null}
9
+ function getCallMethodName(e){const t=e.callee;return"MemberExpression"===t.type&&"Identifier"===t.property.type?t.property.name:null}
10
+ function extractStringValue(e){return e?"Literal"===e.type&&"string"==typeof e.value?e.value:"TemplateLiteral"===e.type?templateToString(e):null:null}
11
+ function templateToString(e){if(!e||!e.quasis)return"";
12
+ let t="";for(let s=0;s<e.quasis.length;s++)t+=e.quasis[s].value.cooked||e.quasis[s].value.raw||"",s<e.expressions?.length&&(t+="$"+(s+1));return t}
13
+ export function discoverSubProjects(i){const l=a(i),c=[],p=["packages","apps","services","modules","libs","plugins"];for(const a of p){const i=r(l,a);if(n(i))try{for(const a of t(i)){const t=r(i,a),p=r(t,"package.json");if(s(t).isDirectory()&&n(p))try{const s=JSON.parse(e(p,"utf-8"));c.push({name:s.name||a,path:o(l,t),absolutePath:t})}catch{c.push({name:a,path:o(l,t),absolutePath:t})}}}catch{}}return c}
14
+ export async function parseProject(t,s={}){const n={files:[],classes:[],functions:[],imports:[],exports:[],tables:[]},i=a(t),l=findJSFiles(t);for(const t of l)try{const s=e(t,"utf-8"),r=o(i,t),a=await parseFileByExtension(s,r);n.files.push(r),n.classes.push(...a.classes),n.functions.push(...a.functions),n.imports.push(...a.imports),n.exports.push(...a.exports),a.tables?.length&&n.tables.push(...a.tables)}catch(e){}if(s.recursive){const e=discoverSubProjects(t);n.subProjects=[];for(const t of e)try{const e=await parseProject(t.absolutePath);for(const s of e.files)n.files.push(r(t.path,s));for(const s of e.classes)s.file=r(t.path,s.file),n.classes.push(s);for(const s of e.functions)s.file=r(t.path,s.file),n.functions.push(s);n.imports.push(...e.imports),n.exports.push(...e.exports),e.tables?.length&&n.tables.push(...e.tables),n.subProjects.push({name:t.name,path:t.path,files:e.files.length})}catch{}}return n.imports=[...new Set(n.imports)],n.exports=[...new Set(n.exports)],n}
15
+ async function parseFileByExtension(e,t){return t.endsWith(".sql")?h(e,t):t.endsWith(".py")?d(e,t):t.endsWith(".go")?m(e,t):t.endsWith(".ts")||t.endsWith(".tsx")?f(e,t):parseFile(e,t)}
16
+ function isSourceFile(e){return!e.endsWith(".css.js")&&!e.endsWith(".tpl.js")&&x.some(t=>e.endsWith(t))}
17
+ export function findJSFiles(e,n=e){e===n&&u(n);
18
+ const a=[];try{for(const i of t(e)){const t=r(e,i),l=s(t),u=o(n,e);l.isDirectory()?c(i,u)||a.push(...findJSFiles(t,n)):isSourceFile(i)&&(p(i,u)||a.push(t))}}catch(t){console.warn(`Cannot read directory ${e}:`,t.message)}return a}
19
+ export function findAllProjectFiles(e,n=e){e===n&&u(n);
20
+ const i=[],l=a(n);try{for(const a of t(e)){const t=r(e,a),u=s(t),f=o(l,e);u.isDirectory()?c(a,f)||i.push(...findAllProjectFiles(t,n)):p(a,f)||i.push(o(l,t))}}catch(t){console.warn(`Cannot read directory ${e}:`,t.message)}return i}
21
+ function buildJSDocTypeMap(e,t){const s=new Map;for(const n of e){if("Block"!==n.type||!n.value.startsWith("*"))continue;
22
+ const e="/*"+n.value+"*/",r=t.slice(0,n.end).split("\n").length,o=[],a=/@param\s+\{/g;
23
+ let i;for(;null!==(i=a.exec(e));){let t=1,s=i.index+i[0].length;for(;s<e.length&&t>0;)"{"===e[s]?t++:"}"===e[s]&&t--,s++;if(0!==t)continue;
24
+ const n=e.slice(i.index+i[0].length,s-1),r=e.slice(s).match(/^\s+(\[?\w+(?:\.\w+)*\]?)/);if(!r)continue;
25
+ let a=r[1];a.startsWith("[")&&(a=a.slice(1)),a.endsWith("]")&&(a=a.slice(0,-1)),a.includes(".")||o.push({name:a,type:n})}let l=null;
26
+ const c=e.match(/@returns?\s+\{([^}]+)\}/);c&&(l=c[1]),(o.length>0||l)&&s.set(r,{params:o,returns:l})}return s}
27
+ function findJSDocForNode(e,t){for(let s=1;s<=3;s++){const n=e.get(t-s);if(n)return n}return null}
28
+ function enrichParamsWithTypes(e,t){if(!t||0===t.params.length)return e;
29
+ const s=new Map;for(const e of t.params)s.set(e.name,e.type);return e.map(e=>{const t=e.startsWith("..."),n=e.endsWith("=");
30
+ let r=e;t&&(r=r.slice(3)),n&&(r=r.slice(0,-1));
31
+ let o=s.get(r);return o?(o.startsWith("...")&&(o=o.slice(3)),`${t?"...":""}${r}:${o}${n?"=":""}`):e})}
@@ -0,0 +1,8 @@
1
+ // @ctx .context/src/core/workspace.ctx
2
+ import{resolve as r,isAbsolute as o,dirname as t}from"path";import{fileURLToPath as e}from"url";
3
+ let s=null;
4
+ const a=t(e(import.meta.url)),p=r(a,"..",".."),c=process.argv.find(r=>r.startsWith("--workspace="));c&&(s=c.split("=")[1],console.error(`[project-graph] Workspace from arg: ${s}`));
5
+ export function setRoots(r){if(r&&r.length>0){let o=r[0].uri;o.startsWith("file://")&&(o=o.slice(7)),s=o,console.error(`[project-graph] Workspace root: ${s}`)}}
6
+ export function getWorkspaceRoot(){return s||(process.env.PROJECT_ROOT?process.env.PROJECT_ROOT:p)}
7
+ export function resolvePath(t){if(!t)return getWorkspaceRoot();
8
+ const e=getWorkspaceRoot(),s=o(t)?t:r(e,t);if(!s.startsWith(e))throw new Error(`Path traversal blocked: '${t}' resolves outside workspace root '${e}'`);return s}
@@ -0,0 +1,17 @@
1
+ // @ctx .context/src/lang/lang-go.ctx
2
+ import{stripStringsAndComments as s}from"./lang-utils.js";
3
+ export function parseGo(t,e){const n={file:e,classes:[],functions:[],imports:[],exports:[]},{imports:l,packageNames:o}=extractImports(t);n.imports=l;
4
+ const i=s(t,{singleQuote:!1,backtick:!0,templateInterpolation:!1}),c=new Map,r=/^\s*type\s+([a-zA-Z_]\w*)\s+struct\s*\{/gm;
5
+ let a;for(;null!==(a=r.exec(i));){const s=a[1],n=getBody(i,a.index+a[0].length),l=t.substring(0,a.index).split("\n").length;
6
+ let o=null;
7
+ const r=[],p=n.split("\n").map(s=>s.trim()).filter(s=>s);for(const s of p){const t=s.split(/\s+/);if(1===t.length)o=t[0].replace(/^\*/,"");else if(t.length>=2){const s=t[0].replace(/,$/,"");r.push(s)}}c.set(s,{name:s,extends:o,methods:[],properties:r,calls:[],file:e,line:l})}const p=/^\s*type\s+([a-zA-Z_]\w*)\s+interface\s*\{/gm;for(;null!==(a=p.exec(i));){const s=a[1],n=getBody(i,a.index+a[0].length),l=t.substring(0,a.index).split("\n").length;
8
+ let o=null;
9
+ const r=[],p=n.split("\n").map(s=>s.trim()).filter(s=>s);for(const s of p){const t=s.indexOf("(");if(-1!==t){const e=s.substring(0,t).trim().split(/\s+/),n=e[e.length-1];n&&r.push(n)}else{const t=s.split(/\s+/);1===t.length&&(o=t[0])}}c.set(s,{name:s,extends:o,methods:r,properties:[],calls:[],file:e,line:l})}const u=/^\s*func\s+\(\s*[a-zA-Z_]\w*\s+\*?([a-zA-Z_]\w*)\s*\)\s+([a-zA-Z_]\w*)[^{]*\{/gm;for(;null!==(a=u.exec(i));){const s=a[1],n=a[2],l=getBody(i,a.index+a[0].length),r=t.substring(0,a.index).split("\n").length,p=extractCalls(l,o);c.has(s)||c.set(s,{name:s,extends:null,methods:[],properties:[],calls:[],file:e,line:r});
10
+ const u=c.get(s);u.methods.push(n);for(const s of p)u.calls.includes(s)||u.calls.push(s)}const f=/^\s*func\s+([a-zA-Z_]\w*)\s*\(([^)]*)\)[^{]*\{/gm;for(;null!==(a=f.exec(i));){const s=a[1],l=a[2].split(",").map(s=>s.trim().split(/\s+/)[0]).filter(s=>s),c=/^[A-Z]/.test(s),r=getBody(i,a.index+a[0].length),p=t.substring(0,a.index).split("\n").length,u=extractCalls(r,o);n.functions.push({name:s,exported:c,calls:u,params:l,file:e,line:p})}n.classes=Array.from(c.values());for(const s of n.classes)/^[A-Z]/.test(s.name)&&n.exports.push(s.name);for(const s of n.functions)s.exported&&n.exports.push(s.name);return n}
11
+ function extractImports(s){const t=[],e=new Set,n=s.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),l=/import\s*\(([\s\S]*?)\)/g;
12
+ let o;for(;null!==(o=l.exec(n));){const s=o[1].split("\n");for(const n of s){const s=n.match(/(?:([a-zA-Z_]\w*)\s+)?"([^"]+)"/);if(s){const n=s[1],l=s[2];if(n)t.includes(n)||(t.push(n),e.add(n));else if(!t.includes(l)){t.push(l);
13
+ const s=l.split("/");e.add(s[s.length-1])}}}}const i=/import\s+(?:([a-zA-Z_]\w*)\s+)?"([^"]+)"/g;for(;null!==(o=i.exec(n));){const s=o[1],n=o[2];if(s)t.includes(s)||(t.push(s),e.add(s));else if(!t.includes(n)){t.push(n);
14
+ const s=n.split("/");e.add(s[s.length-1])}}return{imports:t,packageNames:e}}
15
+ function getBody(s,t){let e=1,n=t;for(;n<s.length&&e>0;)"{"===s[n]?e++:"}"===s[n]&&e--,n++;return s.substring(t,n-1)}
16
+ function extractCalls(s,t){const e=[],n=/([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)\s*\(/g;
17
+ let l;for(;null!==(l=n.exec(s));){let s=l[1];if(!["if","for","switch","func","panic","recover","len","cap","make","new","append","copy","delete","close","int","string","bool","byte","rune","float32","float64","int32","int64","uint32","uint64","complex64","complex128"].includes(s)){if(s.includes(".")){const e=s.split(".");t.has(e[0])||(s=e[1])}e.includes(s)||e.push(s)}}return e}
@@ -0,0 +1,12 @@
1
+ // @ctx .context/src/lang/lang-python.ctx
2
+ import{stripStringsAndComments as s}from"./lang-utils.js";
3
+ export function parsePython(t="",n=""){const e={file:n,classes:[],functions:[],imports:[],exports:[]},o=s(t,{singleQuote:!0,hashComment:!0,tripleQuote:!0}).split("\n");
4
+ let l=null,i=null,c=-1;for(let s=0;s<o.length;s++){const t=o[s];if(!t.trim())continue;
5
+ const r=t.match(/^([ \t]*)/),a=r?r[1].length:0;l&&a<=c&&(l=null,c=-1),i&&0===a&&(i=null);
6
+ const u=t.match(/^class\s+([a-zA-Z_]\w*)(?:\s*\((.*?)\))?\s*:/);if(u){l={name:u[1],extends:u[2]?u[2].trim():null,methods:[],properties:[],calls:[],file:n,line:s+1},e.classes.push(l),c=a,i=null;continue}const p=t.match(/^(?:async\s+)?def\s+([a-zA-Z_]\w*)\s*\(([^)]*)\)?/);if(p){const t=(p[2]||"").split(",").map(s=>s.split(/[:=]/)[0].trim()).filter(s=>s&&"self"!==s&&"cls"!==s);i={name:p[1],exported:!0,calls:[],params:t,file:n,line:s+1},e.functions.push(i),l=null;continue}const f=t.match(/^[ \t]+(?:async\s+)?def\s+([a-zA-Z_]\w*)\s*\(/);if(f&&l&&a>c){const s=f[1];"__init__"!==s&&l.methods.push(s),i=null;continue}const m=t.match(/^\s*import\s+(.+)/);if(m){const s=m[1].split(",");for(const t of s){const s=t.trim(),n=s.match(/(?:.+)\s+as\s+([a-zA-Z_]\w*)/);n?e.imports.push(n[1]):e.imports.push(s.split(".")[0])}continue}const h=t.match(/^\s*from\s+([.\w]+)\s+import\s*(.*)/);if(h){let t=h[2];if(t.includes("(")&&!t.includes(")")){let n=s+1;for(;n<o.length;){if(t+=" "+o[n],o[n].includes(")")){s=n;break}n++}}t=t.replace(/[()]/g,"");
7
+ const n=t.split(",");for(const s of n){const t=s.trim();if(!t)continue;
8
+ const n=t.match(/(?:.+)\s+as\s+([a-zA-Z_]\w*)/);n?e.imports.push(n[1]):e.imports.push(t)}continue}const d=/([a-zA-Z_][\w.]*)\s*\(/g;
9
+ let _;
10
+ const x=new Set(["if","while","for","elif","return","yield","def","class","and","or","not","in","is","print"]);for(;null!==(_=d.exec(t));){const s=_[1];if(x.has(s))continue;
11
+ let t=s;t.startsWith("self.")&&(t=t.substring(5)),i?i.calls.includes(t)||i.calls.push(t):l&&(l.calls.includes(t)||l.calls.push(t))}}const r=t.match(/__all__\s*=\s*\[(.*?)\]/s);if(r){const s=r[1],t=/['"]([^'"]+)['"]/g;
12
+ let n;for(;null!==(n=t.exec(s));)e.exports.push(n[1]);for(const s of e.functions)s.exported=e.exports.includes(s.name)}else{for(const s of e.classes)e.exports.push(s.name);for(const s of e.functions)e.exports.push(s.name),s.exported=!0}return e.imports=[...new Set(e.imports)],e}
@@ -0,0 +1,23 @@
1
+ // @ctx .context/src/lang/lang-sql.ctx
2
+ const e=new Set(["select","from","where","and","or","not","in","on","as","join","left","right","inner","outer","cross","full","group","order","by","having","limit","offset","union","all","distinct","case","when","then","else","end","null","true","false","is","between","like","ilike","exists","any","some","set","values","into","table","create","alter","drop","index","primary","key","foreign","references","constraint","default","check","unique","if","begin","commit","rollback","transaction","returning","conflict","nothing","do","update","cascade","restrict","lateral","each","row","with","recursive","only","integer","int","bigint","smallint","serial","bigserial","text","varchar","char","character","boolean","bool","timestamp","timestamptz","date","time","timetz","interval","numeric","decimal","real","float","double","json","jsonb","uuid","bytea","inet","cidr","macaddr","array","point","line","box","circle","polygon","path","count","sum","avg","min","max","coalesce","cast","extract","now","current_timestamp","current_date","generate_series","unnest","string_agg","array_agg","row_number","rank","dense_rank","over","partition","asc","desc","nulls","first","last","filter","columns","rows","tables","schema","schemas","information_schema","pg_catalog","pg_tables","pg_class"]);
3
+ export function isSQLString(e){return!(!e||"string"!=typeof e)&&/^\s*(SELECT|INSERT|UPDATE|DELETE|WITH|CREATE\s+TABLE)\b/i.test(e)}
4
+ function isValidTableName(t){return!(!t||t.length<2||e.has(t.toLowerCase())||!/^[a-zA-Z_]\w*$/.test(t)||/^[A-Z][A-Z_]*$/.test(t)||/^[A-Z][a-z]/.test(t)||/^(pg_|jsonb_|array_|string_|regexp_)/.test(t))}
5
+ export function extractSQLFromString(e){if(!e||"string"!=typeof e)return{reads:[],writes:[]};
6
+ const t=new Set,n=new Set,s=e.replace(/--[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim(),a=/\bFROM\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;
7
+ let r;for(;null!==(r=a.exec(s));){if(s.slice(r.index+r[0].length).trimStart().startsWith("("))continue;
8
+ const e=r[1].split(".").pop();isValidTableName(e)&&t.add(e)}const i=/\bJOIN\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(r=i.exec(s));){if(s.slice(r.index+r[0].length).trimStart().startsWith("("))continue;
9
+ const e=r[1].split(".").pop();isValidTableName(e)&&t.add(e)}const o=/\bINSERT\s+INTO\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(r=o.exec(s));){const e=r[1].split(".").pop();isValidTableName(e)&&n.add(e)}const l=/\bUPDATE\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(r=l.exec(s));){const e=r[1].split(".").pop();isValidTableName(e)&&n.add(e)}const c=/\bDELETE\s+FROM\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(r=c.exec(s));){const e=r[1].split(".").pop();isValidTableName(e)&&n.add(e)}for(const e of n)if(/\bDELETE\s+FROM\s+/i.test(s)){const n=s.match(/\bDELETE\s+FROM\s+([a-zA-Z_]\w*)/i);if(n){const s=n[1].split(".").pop();e===s&&t.delete(s)}}return{reads:[...t],writes:[...n]}}
10
+ export function parseSQL(e="",t=""){const n={file:t,classes:[],functions:[],imports:[],exports:[],tables:[]};if(!e)return n;
11
+ const s=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[a-zA-Z_]\w*\.)?([a-zA-Z_]\w*)\s*\(([\s\S]*?)\);/gi;
12
+ let a;for(;null!==(a=s.exec(e));){const s=a[1],r=a[2],i=e.substring(0,a.index).split("\n").length,o=parseColumns(r);n.tables.push({name:s,columns:o,file:t,line:i})}return n}
13
+ function parseColumns(t){const n=[],s=splitByTopLevelComma(t);for(const t of s){const s=t.trim();if(/^\s*(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT|EXCLUDE)\b/i.test(s))continue;
14
+ const a=s.match(/^([a-zA-Z_]\w*)\s+([A-Za-z]\w*(?:\s*\([^)]*\))?(?:\s*\[\])?)/);if(a){const t=a[1],s=a[2].trim();e.has(t.toLowerCase())||n.push({name:t,type:s})}}return n}
15
+ function splitByTopLevelComma(e){const t=[];
16
+ let n="",s=0;for(let a=0;a<e.length;a++){const r=e[a];if("("===r)s++;else if(")"===r)s--;else if(","===r&&0===s){t.push(n),n="";continue}n+=r}return n.trim()&&t.push(n),t}
17
+ export function extractSQLFromCode(e){const t=new Set,n=new Set;if(!e)return{reads:[],writes:[]};
18
+ const s=[/"""([\s\S]*?)"""/g,/'''([\s\S]*?)'''/g,/`([\s\S]*?)`/g,/"((?:[^"\\]|\\.)*)"/g,/'((?:[^'\\]|\\.)*)'/g];for(const a of s){let s;for(;null!==(s=a.exec(e));){const e=s[1];if(isSQLString(e)){const s=extractSQLFromString(e);s.reads.forEach(e=>t.add(e)),s.writes.forEach(e=>n.add(e))}}}const a=extractORMFromCode(e);return a.reads.forEach(e=>t.add(e)),a.writes.forEach(e=>n.add(e)),{reads:[...t],writes:[...n]}}const t=new Set(["findmany","findfirst","findunique","findraw","findall","findone","findbypk","findandcountall","count","aggregate","groupby","select","where","first","pluck"]),n=new Set(["create","createmany","update","updatemany","upsert","delete","deletemany","destroy","bulkcreate","insert","del","truncate"]);
19
+ export function extractORMFromCode(e){const s=new Set,a=new Set;if(!e)return{reads:[],writes:[]};
20
+ const r=/\bprisma\.(\w+)\.(findMany|findFirst|findUnique|findRaw|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate|groupBy)\s*\(/g;
21
+ let i;for(;null!==(i=r.exec(e));){const e=i[1],r=i[2].toLowerCase();if(e.startsWith("$"))continue;
22
+ const o=e;t.has(r)?s.add(o):n.has(r)&&a.add(o)}const o=/\b([A-Z][a-zA-Z]+)\.(findAll|findOne|findByPk|findAndCountAll|create|bulkCreate|update|destroy|count|sum|min|max)\s*\(/g;for(;null!==(i=o.exec(e));){const e=i[1],r=i[2].toLowerCase();if(["Promise","Object","Array","Map","Set","Date","Error","JSON","Math","Buffer","RegExp","Symbol","String","Number","Boolean","Request","Response","Console"].includes(e))continue;
23
+ const o=e.toLowerCase();t.has(r)?s.add(o):n.has(r)&&a.add(o)}const l=/\bknex\s*\(\s*['"](\w+)['"]\s*\)/g;for(;null!==(i=l.exec(e));){const t=i[1];if(isValidTableName(t)){const n=e.slice(i.index,i.index+200);/\.(insert|update|del|delete|truncate)\s*\(/i.test(n)?a.add(t):s.add(t)}}const c=/\.(from|into|table)\s*\(\s*['"](\w+)['"]\s*\)/g;for(;null!==(i=c.exec(e));){const e=i[1].toLowerCase(),t=i[2];isValidTableName(t)&&("into"===e?a.add(t):s.add(t))}return{reads:[...s],writes:[...a]}}
@@ -0,0 +1,9 @@
1
+ // @ctx .context/src/lang/lang-typescript.ctx
2
+ import{stripStringsAndComments as s}from"./lang-utils.js";
3
+ export function parseTypeScript(t,e){const r={file:e,classes:[],functions:[],imports:[],exports:[]},c=s(t).split("\n");
4
+ let n=null,a=null;for(let s=0;s<c.length;s++){const t=c[s],o=s+1,i=t.match(/^\s*import\s+(?:type\s+)?(?:\{([^}]+)\}|(\w+))\s+from\s/);if(i){i[1]?i[1].split(",").forEach(s=>{const t=s.trim().replace(/\s+as\s+\w+/,"").replace(/^type\s+/,"");t&&r.imports.push(t)}):i[2]&&r.imports.push(i[2]);continue}const l=t.match(/^\s*import\s+\*\s+as\s+(\w+)\s+from\s/);if(l){r.imports.push(l[1]);continue}const p=t.match(/^\s*export\s+(?:default\s+)?(?:class|function|const|let|var|type|interface|enum|abstract)\s+(\w+)/);p&&r.exports.push(p[1]);
5
+ const u=t.match(/^\s*export\s+\{([^}]+)\}/);if(u&&u[1].split(",").forEach(s=>{const t=s.trim().replace(/\s+as\s+\w+/,"");t&&r.exports.push(t)}),/^\s*(type|interface)\s+\w+/.test(t))continue;
6
+ const f=t.match(/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/);if(f){n={name:f[1],extends:f[2]||null,methods:[],properties:[],calls:[],file:e,line:o},r.classes.push(n),a=null;continue}if(/^}/.test(t)){n=null,a=null;continue}if(n){const s=t.match(/^\s+(?:(?:public|private|protected|static|readonly|abstract|override|async)\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/);s&&"if"!==s[1]&&"for"!==s[1]&&"while"!==s[1]&&"switch"!==s[1]&&"catch"!==s[1]&&"return"!==s[1]&&"new"!==s[1]&&"constructor"!==s[1]&&"super"!==s[1]&&n.methods.push(s[1]),/^\s+constructor\s*\(/.test(t)&&n.methods.push("constructor");
7
+ const e=t.match(/^\s+(?:(?:public|private|protected|static|readonly|declare|override|abstract)\s+)*(\w+)\s*[?!]?\s*[:=]/);e&&!s&&"if"!==e[1]&&"const"!==e[1]&&"let"!==e[1]&&"var"!==e[1]&&"return"!==e[1]&&n.properties.push(e[1])}if(!n){const s=t.match(/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)/);if(s){a={name:s[1],exported:/^\s*export\s+/.test(t),calls:[],params:extractParams(t),file:e,line:o},r.functions.push(a);continue}const c=t.match(/^\s*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[a-zA-Z_]\w*)\s*(?::\s*\w+(?:<[^>]*>)?)?\s*=>/);if(c){a={name:c[1],exported:/^\s*export\s+/.test(t),calls:[],params:extractParams(t),file:e,line:o},r.functions.push(a);continue}}const m=/\b([a-zA-Z_$]\w*)\s*(?:<[^>]*>)?\s*\(/g;
8
+ let h;for(;null!==(h=m.exec(t));){const s=h[1];["if","for","while","switch","catch","return","new","throw","typeof","delete","void","import","export","class","function","const","let","var","async","await","super","this","interface","type","enum","declare","abstract"].includes(s)||(n?n.calls.push(s):a&&a.calls.push(s))}}return r}
9
+ function extractParams(s){const t=s.match(/\(([^)]*)\)/);return t?t[1].split(",").map(s=>s.trim().replace(/[?!]?\s*:.*$/,"").replace(/\s*=.*$/,"").trim()).filter(s=>s&&!s.startsWith("...")):[]}
@@ -0,0 +1,4 @@
1
+ // @ctx .context/src/lang/lang-utils.ctx
2
+ export function stripStringsAndComments(n,e={}){const{singleQuote:t=!0,backtick:o=!0,hashComment:i=!1,tripleQuote:l=!1,templateInterpolation:f=!0}=e;
3
+ let r="",s=0;for(;s<n.length;)if(i&&"#"===n[s])for(;s<n.length&&"\n"!==n[s];)r+=" ",s++;else{if(l&&("'"===n[s]&&"'"===n[s+1]&&"'"===n[s+2]||'"'===n[s]&&'"'===n[s+1]&&'"'===n[s+2])){const e=n[s];for(r+=" ",s+=3;s<n.length;)if("\\"!==n[s]){if(n[s]===e&&n[s+1]===e&&n[s+2]===e){r+=" ",s+=3;break}r+="\n"===n[s]?"\n":" ",s++}else r+=" ",s+=2;continue}if(i||"/"!==n[s]||"/"!==n[s+1])if(i||"/"!==n[s]||"*"!==n[s+1]){if('"'===n[s]||t&&"'"===n[s]||o&&"`"===n[s]){const e=n[s];for(r+=" ",s++;s<n.length;)if("\\"!==n[s]){if(n[s]===e){r+=" ",s++;break}if(f&&"`"===e&&"$"===n[s]&&"{"===n[s+1]){r+="${",s+=2;
4
+ let e=1;for(;s<n.length&&e>0;)"{"===n[s]&&e++,"}"===n[s]&&e--,r+=e>0?"\n"===n[s]?"\n":n[s]:"}",s++;continue}r+="\n"===n[s]?"\n":" ",s++}else r+=" ",s+=2;continue}r+=n[s],s++}else{for(s+=2,r+=" ";s<n.length&&("*"!==n[s]||"/"!==n[s+1]);)r+="\n"===n[s]?"\n":" ",s++;s<n.length&&(r+=" ",s+=2)}else for(;s<n.length&&"\n"!==n[s];)r+=" ",s++}return r}
@@ -0,0 +1,17 @@
1
+ // @ctx .context/src/mcp/mcp-server.ctx
2
+ import e from"fs";
3
+ import t from"path";import{fileURLToPath as s}from"url";import{TOOLS as o}from"./tool-defs.js";import{emitToolCall as a,emitToolResult as r}from"../core/event-bus.js";import{getSkeleton as n,getFocusZone as i,expand as c,deps as d,usages as l,invalidateCache as p,getCallChain as u}from"./tools.js";import{getPendingTests as m,markTestPassed as _,markTestFailed as g,getTestSummary as h,resetTestState as f}from"../analysis/test-annotations.js";import{getFilters as y,setFilters as x,addExcludes as j,removeExcludes as w,resetFilters as v}from"../core/filters.js";import{getInstructions as b}from"../compact/instructions.js";import{getUndocumentedSummary as k}from"../analysis/undocumented.js";import{getDeadCode as S}from"../analysis/dead-code.js";import{generateJSDoc as $,generateJSDocFor as R}from"../analysis/jsdoc-generator.js";import{getSimilarFunctions as F}from"../analysis/similar-functions.js";import{getComplexity as E}from"../analysis/complexity.js";import{getLargeFiles as C}from"../analysis/large-files.js";import{getOutdatedPatterns as T}from"../analysis/outdated-patterns.js";import{getFullAnalysis as U,getAnalysisSummaryOnly as D}from"../analysis/full-analysis.js";import{getCustomRules as P,setCustomRule as O,checkCustomRules as I}from"../analysis/custom-rules.js";import{getFrameworkReference as J}from"../compact/framework-references.js";import{setRoots as q,resolvePath as A}from"../core/workspace.js";import{getDBSchema as N,getTableUsage as L,getDBDeadTables as M}from"../analysis/db-analysis.js";import{compressFile as B,editCompressed as z}from"../compact/compress.js";import{getProjectDocs as G,generateContextFiles as V,checkStaleness as W}from"../compact/doc-dialect.js";import{getGraph as Q}from"./tools.js";import{parseProject as Y,discoverSubProjects as H}from"../core/parser.js";import{getAiContext as Z}from"../compact/ai-context.js";import{checkJSDocConsistency as K}from"../analysis/jsdoc-checker.js";import{checkTypes as X}from"../analysis/type-checker.js";import{compactProject as ee,expandProject as te}from"../compact/compact.js";import{expandFile as se,expandProject as oe}from"../compact/expand.js";import{validatePipeline as ae}from"../compact/validate-pipeline.js";import{validateCtxContracts as re}from"../compact/ctx-to-jsdoc.js";import{getConfig as ne,setConfig as ie,getModeDescription as ce,getModeWorkflow as de}from"../compact/mode-config.js";import{readFileSync as le,existsSync as pe}from"fs";
4
+ const ue=t.dirname(s(import.meta.url)),me={get_skeleton:e=>n(A(e.path)),get_focus_zone:e=>i({...e,path:A(e.path)}),expand:e=>c(e.symbol),deps:e=>d(e.symbol),usages:e=>l(e.symbol),get_call_chain:e=>u({from:e.from,to:e.to,path:e.path?A(e.path):void 0}),invalidate_cache:()=>(p(),{success:!0}),get_pending_tests:e=>m(A(e.path)),mark_test_passed:e=>_(e.testId),mark_test_failed:e=>g(e.testId,e.reason),get_test_summary:e=>h(A(e.path)),reset_test_state:()=>f(),get_filters:()=>y(),set_filters:e=>x(e),add_excludes:e=>j(e.dirs),remove_excludes:e=>w(e.dirs),reset_filters:()=>v(),get_usage_guide:s=>{try{const o=t.join(ue,"..","..","GUIDE.md"),a=e.readFileSync(o,"utf8");if(!s.topic)return a;
5
+ const r=new RegExp(`## ${s.topic}`,"i"),n=a.match(r);if(!n)return`Topic '${s.topic}' not found in guide.`;
6
+ const i=n.index;
7
+ let c=a.indexOf("\n## ",i+1);return-1===c&&(c=a.length),a.substring(i,c).trim()}catch(e){return`Failed to read usage guide: ${e.message}`}},get_agent_instructions:()=>b(),get_undocumented:e=>k(A(e.path),e.level||"tests"),get_dead_code:e=>S(A(e.path)),generate_jsdoc:e=>e.name?R(A(e.path),e.name):$(A(e.path)),get_similar_functions:e=>F(A(e.path),{threshold:e.threshold}),get_complexity:e=>E(A(e.path),{minComplexity:e.minComplexity,onlyProblematic:e.onlyProblematic}),get_large_files:e=>C(A(e.path),{onlyProblematic:e.onlyProblematic}),get_outdated_patterns:e=>T(A(e.path),{codeOnly:e.codeOnly,depsOnly:e.depsOnly}),get_full_analysis:e=>U(A(e.path),{includeItems:e.includeItems}),get_custom_rules:()=>P(),set_custom_rule:e=>O(e.ruleSet,e.rule),check_custom_rules:e=>I(A(e.path),{ruleSet:e.ruleSet,severity:e.severity}),get_framework_reference:e=>J({framework:e.framework,path:e.path?A(e.path):void 0}),get_db_schema:e=>N(A(e.path)),get_table_usage:e=>L(A(e.path),e.table),get_db_dead_tables:e=>M(A(e.path)),get_compressed_file:e=>B(A(e.path),{beautify:e.beautify,legend:e.legend}),get_project_docs:async e=>{const t=A(e.path),s=await Q(t),o=G(s,t,{file:e.file});try{const e=await Y(t),s=W(t,e);return{docs:o,staleFiles:s.stale,freshCount:s.fresh}}catch{return{docs:o}}},generate_context_docs:async e=>{const t=A(e.path),s=await Q(t),o=await Y(t);return V(s,t,o,{overwrite:e.overwrite,scope:e.scope})},check_stale_docs:async e=>{const t=A(e.path),s=await Y(t);return W(t,s)},get_ai_context:async e=>{const t=A(e.path),s=await Z(t,{includeFiles:e.includeFiles,includeDocs:e.includeDocs,includeSkeleton:e.includeSkeleton});try{const e=await Y(t),o=W(t,e);s.staleFiles=o.stale}catch{}return s},check_jsdoc_consistency:e=>K(A(e.path)),check_types:async e=>X(A(e.path),{files:e.files,maxDiagnostics:e.maxDiagnostics}),discover_sub_projects:e=>H(A(e.path)),get_analysis_summary:e=>D(A(e.path)),compact_project:e=>ee(A(e.path),{dryRun:e.dryRun||!1}),beautify_project:e=>te(A(e.path),{dryRun:e.dryRun||!1}),validate_ctx_contracts:e=>re(A(e.path),{strict:e.strict||!1}),edit_compressed:e=>z(A(e.path),e.symbol,e.code,{beautify:!1!==e.beautify,dryRun:e.dryRun||!1}),get_mode:e=>{const t=A(e.path),s=ne(t);return{...s,description:ce(s.mode),workflow:de(s.mode)}},set_mode:e=>{const t=A(e.path),s={mode:e.mode};return void 0!==e.beautify&&(s.beautify=e.beautify),void 0!==e.autoValidate&&(s.autoValidate=e.autoValidate),void 0!==e.stripJSDoc&&(s.stripJSDoc=e.stripJSDoc),ie(t,s)},expand_file:async e=>{const s=A(e.path),o=t.dirname(t.dirname(s)),a=t.relative(o,s),r=t.basename(a,t.extname(a))+".ctx",n=t.dirname(a);
8
+ let i=null;
9
+ const c=t.join(o,n,r),d=t.join(o,".context",n,r);return pe(c)?i=le(c,"utf-8"):pe(d)&&(i=le(d,"utf-8")),se(s,i)},expand_project:e=>oe(A(e.path),{dryRun:e.dryRun||!1}),validate_pipeline:e=>ae(A(e.path),{strict:e.strict||!1})},_e={get_skeleton:()=>['💡 Use expand("SYMBOL") to see code for a specific class.','💡 Use deps("SYMBOL") to see architecture dependencies.',"💡 After code changes, run invalidate_cache() to refresh the graph.","🌐 Web explorer: run `npx project-graph-mcp serve .` to browse code visually."],expand:e=>{const t=[];return e.methods?.length>10&&t.push("💡 Large class detected. Run get_complexity() to find refactoring targets."),t.push("💡 Use deps() to see what depends on this symbol."),e.file&&t.push(`📝 No .ctx for ${e.file}? Run generate_context_docs({ scope: ["${e.file}"] }) to create documentation.`),t},deps:()=>["💡 Use usages() for cross-project reference search."],get_call_chain:e=>e.error?[]:["💡 Use expand() on intermediate steps to understand how data is passed along the chain."],invalidate_cache:()=>["✅ Cache cleared. Run get_skeleton() to rebuild the project graph."],get_dead_code:e=>{const t=["💡 Review each item before removing — some may be used dynamically."];return e.unusedExports?.length>20&&t.push('💡 Consider delegating cleanup to agent-pool: delegate_task({ prompt: "Remove dead code..." })'),t},get_full_analysis:()=>['💡 Focus on items with "critical" severity first.',"💡 Run individual tools (get_complexity, get_dead_code) for detailed breakdowns."],get_complexity:()=>["💡 Functions with complexity >10 are candidates for refactoring.","💡 Use expand() to read the function code before refactoring."],get_undocumented:()=>["💡 Use generate_jsdoc() to auto-generate documentation templates."],get_similar_functions:()=>["💡 Consider extracting duplicated logic into a shared utility."],get_pending_tests:()=>["💡 Use mark_test_passed(testId) or mark_test_failed(testId, reason) to track progress."],get_db_schema:e=>{const t=[];return e.totalTables>0?t.push(`💡 Found ${e.totalTables} tables. Use get_table_usage() to see which code reads/writes them.`):t.push("💡 No .sql schema files found. Add schema.sql or migrations/*.sql to your project."),t},get_table_usage:e=>{const t=["💡 Use get_db_dead_tables() to find tables defined in schema but never queried."];return 0===e.totalTables&&t.push("💡 No SQL queries detected. This tool finds SQL in .query(), .execute(), sql`...` patterns."),t},get_db_dead_tables:()=>["💡 Dead columns detection is best-effort — verify before removing."],get_compressed_file:e=>{const t=[`💡 Saved ${e.savings} tokens (${e.original} → ${e.compressed}).`];return t.push("💡 Use get_ai_context() for full project boot: skeleton + docs + compressed files."),e.file&&t.push(`📝 Working on ${e.file}? Run generate_context_docs({ scope: ["${e.file}"] }) to document it.`),t},get_project_docs:e=>{const t=["💡 Enrich docs by editing .context/*.ctx files — they are git-tracked.","💡 Use generate_context_docs() to create initial .ctx stubs."];return e.staleFiles?.length>0&&t.push(`⚠️ ${e.staleFiles.length} .ctx files are STALE: ${e.staleFiles.slice(0,5).join(", ")}. Run generate_context_docs({ scope: ${JSON.stringify(e.staleFiles)}, overwrite: true }) to update (descriptions will be preserved).`),t},check_stale_docs:e=>{const t=[];return e.stale?.length>0?(t.push(`⚠️ ${e.stale.length} stale: ${e.stale.join(", ")}`),t.push(`💡 Run generate_context_docs({ scope: ${JSON.stringify(e.stale)}, overwrite: true }) — existing descriptions will be preserved.`)):t.push("✅ All .ctx docs are up to date."),e.unknown>0&&t.push(`ℹ️ ${e.unknown} .ctx files without @sig header (pre-staleness format).`),t},generate_context_docs:e=>{const t=[];return e.created?.length>0&&t.push(`✅ Created ${e.created.length} .ctx files with @sig hashes.`),e.skipped?.length>0&&t.push(`ℹ️ Skipped ${e.skipped.length} existing files. Use overwrite=true to regenerate (descriptions are preserved via merge).`),e.templates&&Object.keys(e.templates).length>0&&(t.push("📝 .ctx files have {DESCRIBE} markers. To enrich automatically:"),t.push(' delegate_task({ prompt: "Enrich .context/*.ctx files — replace {DESCRIBE} with compact descriptions", skill: "doc-enricher" })'),t.push(" Or enrich manually: read source files and replace {DESCRIBE} markers with pipe-separated descriptions (max 80 chars).")),t},get_ai_context:e=>{const t=[`💡 Context loaded: ${e.totalTokens} tokens (${e.savings} savings vs ${e.vsOriginal} original).`];return t.push("💡 Use expand() to drill into specific symbols. Use get_compressed_file() for additional files."),t.push("📋 Read .context/*.ctx files for typed signatures and documentation. Check .gemini/AGENTS.md for project-specific rules."),e.staleFiles?.length>0&&t.push(`⚠️ ${e.staleFiles.length} .ctx docs are stale. Run generate_context_docs({ scope: ${JSON.stringify(e.staleFiles)}, overwrite: true }) then delegate_task({ skill: "doc-enricher" }) to update.`),t},validate_ctx_contracts:e=>{const t=[];return e.summary?.errors>0?t.push(`⚠️ ${e.summary.errors} contract violations found. Run generate_context_docs({ overwrite: true }) to regenerate .ctx files.`):t.push("✅ All .ctx contracts valid — documentation matches source."),t},edit_compressed:e=>{const t=[];return e.success&&(t.push(`✅ Symbol "${e.symbol}" replaced in ${e.file}.`),t.push("💡 Run invalidate_cache() to refresh the graph after editing."),t.push("💡 Run validate_ctx_contracts() to check if .ctx docs need updating.")),t},get_mode:e=>{const t=[`📋 Current mode: ${e.mode} — ${e.description}`];return 1===e.mode&&(t.push("💡 Compact mode: read/write .js directly. Run expand_project to update .expanded/ for human review."),t.push("🌐 Web explorer: `npx project-graph-mcp serve .` for visual code browsing with compression stats.")),2===e.mode&&(t.push("💡 Full mode: get_compressed_file() → read → edit_compressed() → write."),t.push("🌐 Web explorer: `npx project-graph-mcp serve .` for visual code browsing with compression stats.")),t},set_mode:e=>e.saved?[`✅ Mode set to ${e.config.mode}. Saved to ${e.path}.`]:[],validate_pipeline:e=>{const t=[`${"PASS"===e.status?"✅":"❌"} Pipeline ${e.status} (${e.duration}): ${e.summary.contractErrors} contract errors, ${e.summary.astErrors} AST errors.`];return"PASS"===e.status&&t.push(`💡 ${e.summary.jsdocInjected} JSDoc blocks injected. Token savings: ${e.summary.tokenSavings}.`),e.summary.contractErrors>0&&t.push("⚠️ Fix .ctx contract errors first, then re-run validate_pipeline."),t},expand_project:e=>[`✅ Expanded ${e.files} files → ${e.outputDir}. ${e.totalJSDocInjected} JSDoc blocks injected.`]},ge={navigate:e=>{const t={expand:"expand",deps:"deps",usages:"usages",call_chain:"get_call_chain",sub_projects:"discover_sub_projects"}[e.action];if(!t)throw new Error(`Unknown navigate action: ${e.action}`);return me[t](e)},analyze:e=>{const t={dead_code:"get_dead_code",similar_functions:"get_similar_functions",complexity:"get_complexity",large_files:"get_large_files",outdated_patterns:"get_outdated_patterns",full_analysis:"get_full_analysis",analysis_summary:"get_analysis_summary",undocumented:"get_undocumented"}[e.action];if(!t)throw new Error(`Unknown analyze action: ${e.action}`);return me[t](e)},testing:e=>{const t={pending:"get_pending_tests",pass:"mark_test_passed",fail:"mark_test_failed",summary:"get_test_summary",reset:"reset_test_state"}[e.action];if(!t)throw new Error(`Unknown testing action: ${e.action}`);return me[t](e)},filters:e=>{const t={get:"get_filters",set:"set_filters",add_excludes:"add_excludes",remove_excludes:"remove_excludes",reset:"reset_filters"}[e.action];if(!t)throw new Error(`Unknown filters action: ${e.action}`);return me[t](e)},jsdoc:e=>{const t={check_consistency:"check_jsdoc_consistency",check_types:"check_types",generate:"generate_jsdoc"}[e.action];if(!t)throw new Error(`Unknown jsdoc action: ${e.action}`);return me[t](e)},docs:e=>{const t={get:"get_project_docs",generate:"generate_context_docs",check_stale:"check_stale_docs",validate_contracts:"validate_ctx_contracts"}[e.action];if(!t)throw new Error(`Unknown docs action: ${e.action}`);return me[t](e)},compact:e=>{const t={compact_file:"get_compressed_file",edit:"edit_compressed",compact_all:"compact_project",beautify:"beautify_project",expand_file:"expand_file",expand_project:"expand_project",validate_pipeline:"validate_pipeline",get_mode:"get_mode",set_mode:"set_mode"}[e.action];if(!t)throw new Error(`Unknown compact action: ${e.action}`);return me[t](e)},db:e=>{const t={schema:"get_db_schema",table_usage:"get_table_usage",dead_tables:"get_db_dead_tables"}[e.action];if(!t)throw new Error(`Unknown db action: ${e.action}`);return me[t](e)}},he={navigate:(e,t)=>{const s=_e[{expand:"expand",deps:"deps",call_chain:"get_call_chain"}[t.action]];return s?s(e):[]},analyze:(e,t)=>{const s=_e[{dead_code:"get_dead_code",full_analysis:"get_full_analysis",complexity:"get_complexity",undocumented:"get_undocumented",similar_functions:"get_similar_functions"}[t.action]];return s?s(e):[]},testing:(e,t)=>"pending"===t.action&&_e.get_pending_tests?.(e)||[],docs:(e,t)=>{const s=_e[{get:"get_project_docs",check_stale:"check_stale_docs",generate:"generate_context_docs",validate_contracts:"validate_ctx_contracts"}[t.action]];return s?s(e):[]},compact:(e,t)=>{const s=_e[{compact_file:"get_compressed_file",edit:"edit_compressed",get_mode:"get_mode",set_mode:"set_mode",validate_pipeline:"validate_pipeline",expand_project:"expand_project"}[t.action]];return s?s(e):[]},db:(e,t)=>{const s=_e[{schema:"get_db_schema",table_usage:"get_table_usage",dead_tables:"get_db_dead_tables"}[t.action]];return s?s(e):[]}};
10
+ export function createServer(s){let n=1;
11
+ const i=new Map;
12
+ let c=!1;return{pendingRequests:i,async handleMessage(s){if(void 0!==s.result||void 0!==s.error){const e=i.get(s.id);return e&&(i.delete(s.id),s.error?e.reject(new Error(s.error.message)):e.resolve(s.result)),null}const{method:a,params:r,id:n}=s;if(void 0===n)return await this.handleNotification(a,r),null;try{switch(a){case"initialize":return r?.capabilities?.roots&&(c=!0),r?.roots&&q(r.roots),{jsonrpc:"2.0",id:n,result:{protocolVersion:"2024-11-05",capabilities:{tools:{},resources:{}},serverInfo:{name:"project-graph",version:"2.1.0"}}};case"resources/list":return{jsonrpc:"2.0",id:n,result:{resources:[{uri:"project-graph://guide",name:"Project Graph Usage Guide",description:"Comprehensive guide with workflows and examples",mimeType:"text/markdown"}]}};case"resources/read":return"project-graph://guide"!==r.uri?{jsonrpc:"2.0",id:n,error:{code:-32602,message:`Resource not found: ${r.uri}`}}:{jsonrpc:"2.0",id:n,result:{contents:[{uri:"project-graph://guide",mimeType:"text/markdown",text:e.readFileSync(t.join(ue,"..","..","GUIDE.md"),"utf8")}]}};case"tools/list":return{jsonrpc:"2.0",id:n,result:{tools:o}};case"tools/call":{const e=await this.executeTool(r.name,r.arguments),t=[{type:"text",text:JSON.stringify(e,null,2)}];
13
+ let s=[];
14
+ const o=he[r.name];if(o&&r.arguments?.action)s=o(e,r.arguments);else{const t=_e[r.name];t&&(s=t(e))}return s.length>0&&t.push({type:"text",text:"\n"+s.join("\n")}),{jsonrpc:"2.0",id:n,result:{content:t}}}default:return{jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${a}`}}}}catch(e){return{jsonrpc:"2.0",id:n,error:{code:-32e3,message:e.message}}}},async handleNotification(e,t){switch(e){case"notifications/initialized":if(c)try{const e=await this.requestRoots();e&&e.length>0&&q(e)}catch(e){console.error(`[project-graph] Failed to get roots: ${e.message}`)}break;case"notifications/roots/list_changed":if(c)try{const e=await this.requestRoots();e&&e.length>0&&(q(e),p())}catch(e){console.error(`[project-graph] Failed to refresh roots: ${e.message}`)}}},requestRoots:()=>new Promise((e,t)=>{const o=n++,a=setTimeout(()=>{i.delete(o),t(new Error("roots/list request timed out"))},5e3);i.set(o,{resolve:t=>{clearTimeout(a),e(t.roots||[])},reject:e=>{clearTimeout(a),t(e)}}),s({jsonrpc:"2.0",id:o,method:"roots/list"})}),async executeTool(e,t){a(e,t);
15
+ const s=Date.now();try{const o=ge[e];
16
+ let a;if(o)a=await o(t);else{const s=me[e];if(!s)throw new Error(`Unknown tool: ${e}`);a=await s(t)}return r(e,t,a,Date.now()-s,!0),a}catch(o){throw r(e,t,null,Date.now()-s,!1),o}}}}
17
+ export async function startStdioServer(e=[]){const sendToClient=e=>{console.log(JSON.stringify(e))},t=createServer(sendToClient),s=await import("readline"),processLine=async e=>{try{const s=JSON.parse(e),o=await t.handleMessage(s);null!==o&&sendToClient(o)}catch(e){sendToClient({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}})}};for(const t of e)await processLine(t);s.createInterface({input:process.stdin,output:process.stdout,terminal:!1}).on("line",processLine)}
@@ -0,0 +1,3 @@
1
+ // @ctx .context/src/mcp/tool-defs.ctx
2
+ const e={get_skeleton:{name:"get_skeleton",description:"Get compact minified project overview (10-50x smaller than source). Returns legend, stats, and node summaries.",inputSchema:{type:"object",properties:{path:{type:"string",description:'Path to scan (e.g., "src/components")'}},required:["path"]}},get_focus_zone:{name:"get_focus_zone",description:"Get enriched context for recently modified files. Auto-detects from git or accepts explicit file list.",inputSchema:{type:"object",properties:{path:{type:"string"},useGitDiff:{type:"boolean",description:"Auto-detect from git diff"},recentFiles:{type:"array",items:{type:"string"},description:"Explicit list of files to expand"}}}},get_ai_context:{name:"get_ai_context",description:"Boot AI agent context: skeleton + doc-dialect + optional compressed files in one call. Call FIRST when starting work on a new project. Returns totalTokens and savings vs reading raw source.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Project root path"},includeFiles:{type:"array",items:{type:"string"},description:'Specific files to include compressed (e.g., ["parser.js", "tools.js"])'},includeDocs:{type:"boolean",description:"Include doc-dialect documentation (default: true)"},includeSkeleton:{type:"boolean",description:"Include project skeleton (default: true)"}},required:["path"]}},invalidate_cache:{name:"invalidate_cache",description:"Invalidate the cached graph. Use after making code changes.",inputSchema:{type:"object",properties:{}}},get_usage_guide:{name:"get_usage_guide",description:"Get the comprehensive usage guide for project-graph with examples and best practices.\nCall this FIRST when planning how to analyze, navigate, or audit a codebase.\nReturns practical examples and recommended workflow for each feature area.\n\nAvailable topics: navigation, analysis, testing, documentation, rules, workflow.\nOmit topic to get the full guide.",inputSchema:{type:"object",properties:{topic:{type:"string",description:"Optional topic filter: navigation, analysis, testing, documentation, rules, workflow"}}}},get_agent_instructions:{name:"get_agent_instructions",description:"Get coding guidelines, architectural standards, and JSDoc rules for this project.",inputSchema:{type:"object",properties:{}}},get_custom_rules:{name:"get_custom_rules",description:"List all custom code analysis rules. Rules are stored in JSON files in rules/ directory.",inputSchema:{type:"object",properties:{}}},set_custom_rule:{name:"set_custom_rule",description:"Add or update a custom code analysis rule. Creates ruleset if it does not exist.",inputSchema:{type:"object",properties:{ruleSet:{type:"string",description:'Name of ruleset (e.g., "symbiote", "react", "custom")'},rule:{type:"object",description:"Rule definition with id, name, description, pattern, patternType, replacement, severity, filePattern"}},required:["ruleSet","rule"]}},check_custom_rules:{name:"check_custom_rules",description:"Run custom rules analysis on a directory. Returns violations found.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to scan"},ruleSet:{type:"string",description:"Optional: specific ruleset to use"},severity:{type:"string",description:"Optional: filter by severity (error/warning/info)"}},required:["path"]}},get_framework_reference:{name:"get_framework_reference",description:"Get framework-specific AI reference documentation. Auto-detects framework from project or accepts explicit name. Returns full API reference, patterns, and common mistakes as agent context.",inputSchema:{type:"object",properties:{framework:{type:"string",description:'Framework reference name (e.g., "symbiote-3x"). If omitted, auto-detects from path.'},path:{type:"string",description:'Project path for auto-detection (e.g., "src/")'}}}}};
3
+ export const TOOLS=[e.get_skeleton,e.get_focus_zone,e.get_ai_context,e.invalidate_cache,e.get_usage_guide,e.get_agent_instructions,e.get_custom_rules,e.set_custom_rule,e.check_custom_rules,e.get_framework_reference,{name:"navigate",description:"Navigate the project graph. Actions: expand|deps|usages|call_chain|sub_projects",inputSchema:{type:"object",properties:{action:{type:"string",enum:["expand","deps","usages","call_chain","sub_projects"],description:"Navigation action to perform"},symbol:{type:"string",description:"Symbol name (for expand, deps, usages)"},from:{type:"string",description:"Starting symbol (for call_chain)"},to:{type:"string",description:"Target symbol (for call_chain)"},path:{type:"string",description:"Path to scan (for call_chain, sub_projects)"}},required:["action"]}},{name:"analyze",description:"Code quality analysis. Actions: dead_code|similar_functions|complexity|large_files|outdated_patterns|full_analysis|analysis_summary|undocumented",inputSchema:{type:"object",properties:{action:{type:"string",enum:["dead_code","similar_functions","complexity","large_files","outdated_patterns","full_analysis","analysis_summary","undocumented"],description:"Analysis type to run"},path:{type:"string",description:"Path to scan"},minComplexity:{type:"number",description:"For complexity: minimum threshold (default: 1)"},onlyProblematic:{type:"boolean",description:"For complexity/large_files: only show issues"},threshold:{type:"number",description:"For similar_functions: min similarity % (default: 60)"},includeItems:{type:"boolean",description:"For full_analysis: include individual items"},level:{type:"string",enum:["tests","params","all"],description:"For undocumented: strictness level"},codeOnly:{type:"boolean",description:"For outdated_patterns: only check code"},depsOnly:{type:"boolean",description:"For outdated_patterns: only check deps"}},required:["action","path"]}},{name:"testing",description:"Test checklist management. Actions: pending|pass|fail|summary|reset",inputSchema:{type:"object",properties:{action:{type:"string",enum:["pending","pass","fail","summary","reset"],description:"Test action to perform"},path:{type:"string",description:"Path to scan (for pending, summary)"},testId:{type:"string",description:"Test ID (for pass, fail)"},reason:{type:"string",description:"Failure reason (for fail)"}},required:["action"]}},{name:"filters",description:"Filter configuration. Actions: get|set|add_excludes|remove_excludes|reset",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","add_excludes","remove_excludes","reset"],description:"Filter action to perform"},excludeDirs:{type:"array",items:{type:"string"},description:"For set: directories to exclude"},excludePatterns:{type:"array",items:{type:"string"},description:"For set: file patterns to exclude"},useGitignore:{type:"boolean",description:"For set: use .gitignore patterns"},includeHidden:{type:"boolean",description:"For set: include hidden directories"},dirs:{type:"array",items:{type:"string"},description:"For add_excludes/remove_excludes"}},required:["action"]}},{name:"jsdoc",description:"JSDoc operations. Actions: check_consistency|check_types|generate",inputSchema:{type:"object",properties:{action:{type:"string",enum:["check_consistency","check_types","generate"],description:"JSDoc action to perform"},path:{type:"string",description:"Path to scan"},name:{type:"string",description:"For generate: specific function name"},files:{type:"array",items:{type:"string"},description:"For check_types: specific files"},maxDiagnostics:{type:"number",description:"For check_types: max diagnostics (default: 50)"}},required:["action","path"]}},{name:"docs",description:"Documentation (.ctx) management. Actions: get|generate|check_stale|validate_contracts",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","generate","check_stale","validate_contracts"],description:"Documentation action to perform"},path:{type:"string",description:"Project root path"},file:{type:"string",description:"For get: specific file docs"},overwrite:{type:"boolean",description:"For generate: overwrite existing (merge preserves descriptions)"},scope:{description:'For generate: "all", "focus" (git diff), or array of file paths'},strict:{type:"boolean",description:"For validate_contracts: report functions missing from .ctx"}},required:["action","path"]}},{name:"compact",description:"Compact code operations. Actions: compact_file|edit|compact_all|beautify|expand_file|expand_project|validate_pipeline|get_mode|set_mode",inputSchema:{type:"object",properties:{action:{type:"string",enum:["compact_file","edit","compact_all","beautify","expand_file","expand_project","validate_pipeline","get_mode","set_mode"],description:"Compact action to perform"},path:{type:"string",description:"Path to file or directory"},symbol:{type:"string",description:"For edit: function/class name to replace"},code:{type:"string",description:"For edit: new code for the symbol"},beautify:{type:"boolean",description:"Beautify output (default: true)"},legend:{type:"boolean",description:"For compact_file: include export legend"},dryRun:{type:"boolean",description:"Preview without modifying"},mode:{type:"number",description:"For set_mode: 1 (compact, recommended) or 2 (full)"},autoValidate:{type:"boolean",description:"For set_mode: auto-validate after edits"},stripJSDoc:{type:"boolean",description:"For set_mode: strip JSDoc when compacting"},strict:{type:"boolean",description:"For validate_pipeline: report fns missing from .ctx"}},required:["action"]}},{name:"db",description:"Database analysis. Actions: schema|table_usage|dead_tables",inputSchema:{type:"object",properties:{action:{type:"string",enum:["schema","table_usage","dead_tables"],description:"Database analysis action"},path:{type:"string",description:"Path to scan"},table:{type:"string",description:"For table_usage: filter to specific table"}},required:["action","path"]}}];
@@ -0,0 +1,25 @@
1
+ // @ctx .context/src/mcp/tools.ctx
2
+ import{parseProject as e,parseFile as t,findJSFiles as n,findAllProjectFiles as r}from"../core/parser.js";import{buildGraph as s,createSkeleton as o}from"../core/graph-builder.js";import{readFileSync as c,statSync as i,writeFileSync as a,existsSync as l,unlinkSync as f}from"fs";import{execSync as u}from"child_process";import{join as p}from"path";
3
+ let h=null,d=null,m=new Map;function saveDiskCache(e,t){try{const n=p(e,".project-graph-cache.json"),r={version:1,path:e,mtimes:Object.fromEntries(m),graph:t};a(n,JSON.stringify(r),"utf-8")}catch(e){}}
4
+ function loadDiskCache(e){try{const t=p(e,".project-graph-cache.json");if(!l(t))return!1;
5
+ const n=c(t,"utf-8"),r=JSON.parse(n);if(1!==r.version||r.path!==e)return!1;m.clear();for(const[e,t]of Object.entries(r.mtimes))m.set(e,t);return h=r.graph,d=e,!detectChanges(e)||(h=null,d=null,m.clear(),!1)}catch(e){return!1}}
6
+ export async function getGraph(t){if(h&&d===t){if(!detectChanges(t))return h}else if(!h&&loadDiskCache(t))return h;
7
+ const n=await e(t);return h=s(n),d=t,snapshotMtimes(t),saveDiskCache(t,h),h}
8
+ function detectChanges(e){if(0===m.size)return!0;try{const t=n(e),r=new Set(t),s=new Set(m.keys());if(t.length!==m.size)return!0;for(const e of t)if(!s.has(e))return!0;for(const e of s)if(!r.has(e))return!0;for(const e of t)try{if(i(e).mtimeMs!==m.get(e))return!0}catch{return!0}return!1}catch{return!0}}
9
+ function snapshotMtimes(e){m.clear();try{const t=n(e);for(const e of t)try{m.set(e,i(e).mtimeMs)}catch{}}catch{}}
10
+ export async function getSkeleton(e){const t=await getGraph(e),n=r(e);return o(t,n)}
11
+ export async function getFocusZone(e={}){const n=e.path||"src/components",r=await getGraph(n);
12
+ let s=e.recentFiles||[];if(e.useGitDiff)try{s=u("git diff --name-only HEAD~5",{encoding:"utf-8"}).split("\n").filter(e=>e.endsWith(".js"))}catch(e){}const o={};for(const e of s){const n=c(e,"utf-8"),s=await t(n,e);for(const e of s.classes){const t=r.legend[e.name];t&&r.nodes[t]&&(o[t]={...r.nodes[t],methods:e.methods,properties:e.properties,file:e.file,line:e.line})}}return{focusFiles:s,expanded:o,expandable:Object.keys(r.nodes).filter(e=>!o[e])}}
13
+ export async function expand(t){const n=d||"src/components",r=await getGraph(n),[s,o]=t.split("."),i=r.reverseLegend[s];if(!i)return{error:`Unknown symbol: ${t}. Run get_skeleton on your project first, then use symbols from the L (Legend) field.`};
14
+ const a=await e(n),l=a.classes.find(e=>e.name===i),f=a.functions.find(e=>e.name===i);if(!l&&!f)return{error:`Symbol not found: ${i}`};if(f&&!o)return{symbol:t,fullName:i,type:"function",file:f.file,line:f.line,exported:f.exported,calls:f.calls};if(o&&l){const e=r.reverseLegend[o]||o,n=extractMethod(c(l.file,"utf-8"),e);return{symbol:t,fullName:`${i}.${e}`,file:l.file,line:l.line,code:n}}return{symbol:t,fullName:i,file:l.file,line:l.line,extends:l.extends,methods:l.methods,properties:l.properties,calls:l.calls}}
15
+ export async function deps(e){const t=d||"src/components",n=await getGraph(t),r=n.nodes[e];if(!r)return{error:`Unknown symbol: ${e}. Run get_skeleton on your project first, then use symbols from the L (Legend) field.`};
16
+ const s=n.edges.filter(t=>t[2].startsWith(e)).map(e=>e[0]),o=n.edges.filter(t=>t[0]===e).map(e=>e[2]);return{symbol:e,imports:r.i||[],usedBy:[...new Set(s)],calls:[...new Set(o)]}}
17
+ export async function usages(t){const n=d||"src/components",r=await getGraph(n),s=await e(n),o=r.reverseLegend[t]||t,c=[];for(const e of s.classes)(e.calls?.includes(o)||e.calls?.some(e=>e.includes(o)))&&c.push({file:e.file,line:e.line,context:`${e.name} calls ${o}`});return c}
18
+ function extractMethod(e,t){const n=new RegExp(`((?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)?)(?:async\\s+)?${t}\\s*\\([^)]*\\)\\s*{`,"g").exec(e);if(!n)return"";
19
+ const r=n.index;
20
+ let s=0,o=n.index+n[0].length-1;for(;o<e.length;){if("{"===e[o])s++;else if("}"===e[o]&&(s--,0===s))return e.slice(r,o+1);o++}return e.slice(r)}
21
+ export async function getCallChain(e={}){const{from:t,to:n,path:r}=e;if(!t||!n)return{error:'Both "from" and "to" parameters are required'};
22
+ const s=r||d||"src/components",o=await getGraph(s),c=o.legend[t]||t,i=o.legend[n]||n,a={};for(const[e,t,n]of o.edges)a[e]||(a[e]=[]),a[e].push(n);
23
+ const l=[{current:c,path:[c]}],f=new Set,u=new Set;for(f.add(c);l.length>0;){const{current:e,path:t}=l.shift(),n=e.split(".")[0],r=e.split(".")[1];if(e===i||n===i||r===i)return t.map(e=>{const t=e.split("."),n=o.reverseLegend[t[0]]||t[0];return 2===t.length?`${n}.${o.reverseLegend[t[1]]||t[1]}`:n});if(u.has(n))continue;u.add(n);
24
+ const s=a[n]||[];for(const e of s)f.has(e)||(f.add(e),l.push({current:e,path:[...t,e]}))}return{error:`No call path found from "${t}" to "${n}"`}}
25
+ export function invalidateCache(){if(d)try{const e=p(d,".project-graph-cache.json");l(e)&&f(e)}catch(e){}h=null,d=null,m.clear()}
@@ -0,0 +1,19 @@
1
+ // @ctx .context/src/network/backend-lifecycle.ctx
2
+ import{createHash as e,randomBytes as t}from"node:crypto";import{existsSync as r,mkdirSync as o,readFileSync as n,writeFileSync as c,unlinkSync as s,readdirSync as i}from"node:fs";import{join as a,resolve as l,basename as f}from"node:path";import{spawn as d}from"node:child_process";import{createInterface as u}from"node:readline";import{createConnection as p}from"node:net";import{fileURLToPath as h}from"node:url";
3
+ const m=a(h(import.meta.url),".."),g=a(process.env.HOME||process.env.USERPROFILE||"/tmp",".local-gateway","backends");function getPortFilePath(t){const r=l(t),o=e("md5").update(r).digest("hex").slice(0,8);return a(g,`${o}.json`)}
4
+ function readPortFile(e){const t=getPortFilePath(e);if(!r(t))return null;try{const e=JSON.parse(n(t,"utf8"));try{process.kill(e.pid,0)}catch{try{s(t)}catch{}return null}return e}catch{return null}}
5
+ export function writePortFile(e,t){o(g,{recursive:!0});
6
+ const r=l(e),n={port:t,pid:process.pid,project:r,name:f(r)||"root",startedAt:Date.now()};c(getPortFilePath(e),JSON.stringify(n,null,2))}
7
+ export function removePortFile(e){try{s(getPortFilePath(e))}catch{}}
8
+ export function listBackends(){if(!r(g))return[];
9
+ const e=i(g).filter(e=>e.endsWith(".json")),t=[];for(const r of e)try{const e=JSON.parse(n(a(g,r),"utf8"));try{process.kill(e.pid,0),t.push(e)}catch{try{s(a(g,r))}catch{}}}catch{}return t}
10
+ export async function ensureBackend(e){const t=l(e),o=readPortFile(t);if(o)return o.port;
11
+ const n=a(m,"backend.js");d(process.execPath,[n,t],{detached:!0,stdio:"ignore",env:{...process.env,PROJECT_GRAPH_BACKEND:"1"}}).unref();
12
+ const c=getPortFilePath(t),s=Date.now();for(;Date.now()-s<1e4;)if(await new Promise(e=>setTimeout(e,200)),r(c)){const e=readPortFile(t);if(e)return e.port}throw new Error("Backend failed to start within 10s")}
13
+ export function startStdioProxy(e,r=[]){const o=t(16).toString("base64"),n=p({host:"127.0.0.1",port:e},()=>{n.write(`GET /mcp-ws HTTP/1.1\r\nHost: 127.0.0.1:${e}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${o}\r\nSec-WebSocket-Version: 13\r\n\r\n`)});
14
+ let c=!1,s=Buffer.alloc(0),i=[...r];
15
+ const a=u({input:process.stdin,terminal:!1});function encodeClientFrame(e){const r=Buffer.from(e,"utf8"),o=t(4),n=Buffer.alloc(r.length);for(let e=0;e<r.length;e++)n[e]=r[e]^o[e%4];
16
+ let c;return r.length<126?(c=Buffer.alloc(2),c[0]=129,c[1]=128|r.length):r.length<65536?(c=Buffer.alloc(4),c[0]=129,c[1]=254,c.writeUInt16BE(r.length,2)):(c=Buffer.alloc(10),c[0]=129,c[1]=255,c.writeBigUInt64BE(BigInt(r.length),2)),Buffer.concat([c,o,n])}
17
+ function decodeFrame(e){if(e.length<2)return null;
18
+ const t=15&e[0];
19
+ let r=127&e[1],o=2;if(126===r){if(e.length<4)return null;r=e.readUInt16BE(2),o=4}else if(127===r){if(e.length<10)return null;r=Number(e.readBigUInt64BE(2)),o=10}return e.length<o+r?null:{opcode:t,data:e.slice(o,o+r).toString("utf8"),totalLen:o+r}}a.on("line",e=>{if(c)try{n.write(encodeClientFrame(e))}catch{}else i.push(e)}),a.on("close",()=>{n.end(),process.exit(0)}),n.on("data",e=>{if(c)s=Buffer.concat([s,e]);else{const t=Buffer.concat([s,e]),r=t.indexOf("\r\n\r\n");if(-1===r)return void(s=t);t.slice(0,r).toString().includes("101")||(console.error("[project-graph] WebSocket handshake failed"),process.exit(1)),c=!0,s=t.slice(r+4);for(const e of i)try{n.write(encodeClientFrame(e))}catch{}i=[]}for(;s.length>=2;){const e=decodeFrame(s);if(!e)break;if(s=s.slice(e.totalLen),1===e.opcode)process.stdout.write(e.data+"\n");else if(8===e.opcode)process.exit(0);else if(9===e.opcode){const e=Buffer.alloc(2);e[0]=138,e[1]=0,n.write(e)}}}),n.on("close",()=>process.exit(0)),n.on("error",e=>{console.error(`[project-graph] Proxy connection error: ${e.message}`),process.exit(1)})}
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // @ctx .context/src/network/backend.ctx
3
+ import{resolve as e}from"node:path";import{startWebServer as r}from"./web-server.js";import{writePortFile as s,removePortFile as o}from"./backend-lifecycle.js";
4
+ const t=e(process.argv[2]||".");function cleanup(){o(t)}process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit()}),process.on("SIGTERM",()=>{cleanup(),process.exit()});
5
+ const c=r(t,0),a=setInterval(()=>{const e=c.address();e&&(clearInterval(a),s(t,e.port))},50);
@@ -0,0 +1,23 @@
1
+ // @ctx .context/src/network/local-gateway.ctx
2
+ import e from"node:http";
3
+ import t from"node:net";
4
+ import r from"node:fs";
5
+ import n from"node:path";import{registerLocal as o}from"./mdns.js";
6
+ const s=n.join(process.env.HOME||process.env.USERPROFILE||"/tmp",".local-gateway"),i=n.join(s,"services.json"),a=n.join(s,"gateway.pid");function readRegistry(){try{return JSON.parse(r.readFileSync(i,"utf8"))}catch{return{}}}
7
+ function writeRegistry(e){r.mkdirSync(s,{recursive:!0}),r.writeFileSync(i,JSON.stringify(e,null,2))}
8
+ export function registerService(e,t,r={}){const n=`${e}.local`,s=readRegistry();if(r.projectName){s[n]||(s[n]={name:e,routes:{}});
9
+ const o=`/${r.projectName}`;s[n].routes=s[n].routes||{},s[n].routes[o]={port:t,pid:process.pid,projectPath:r.projectPath,projectName:r.projectName}}else s[n]={port:t,pid:process.pid,name:e};writeRegistry(s);
10
+ const i=o(n,80);ensureGateway();
11
+ const cleanup=()=>{i.cleanup();try{const e=readRegistry();r.projectName&&e[n]?.routes?(delete e[n].routes[`/${r.projectName}`],0===Object.keys(e[n].routes).length&&delete e[n]):delete e[n],writeRegistry(e),0===Object.keys(e).length&&stopGateway()}catch{}};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit()}),process.on("SIGTERM",()=>{cleanup(),process.exit()});
12
+ const a=getGatewayPort(),c=80===a?"":`:${a}`,p=r.projectName?`http://${n}${c}/${r.projectName}/`:`http://${n}${c}/`;return{cleanup:cleanup,url:p,directUrl:`http://localhost:${t}/`}}
13
+ function resolveBackend(e,t,r){const n=r[e];if(!n)return null;if(n.routes){const e=Object.keys(n.routes).sort((e,t)=>t.length-e.length);for(const r of e)if(t===r||t.startsWith(r+"/")){const e=n.routes[r];try{process.kill(e.pid,0)}catch{continue}const o=t.slice(r.length)||"/";return{port:e.port,rewritePath:o,prefix:r}}for(const r of e)try{const e=n.routes[r];process.kill(e.pid,0);
14
+ const o="/"===t||""===t?"/dashboard.html":t;return{port:e.port,rewritePath:o}}catch{continue}}if(n.port){const e="/"===t||""===t?"/dashboard.html":t;return{port:n.port,rewritePath:e}}return null}
15
+ function readGatewayPid(){try{const e=r.readFileSync(a,"utf8");return e.trim().startsWith("{")?JSON.parse(e):{pid:parseInt(e,10),port:80}}catch{return null}}
16
+ function isGatewayRunning(){const e=readGatewayPid();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return!1}}
17
+ export function getGatewayPort(){const e=readGatewayPid();return e?.port||80}
18
+ function ensureGateway(){if(!isGatewayRunning())try{const n=e.createServer((t,r)=>{const n=(t.headers.host||"").split(":")[0],o=readRegistry(),s=resolveBackend(n,t.url,o);if(!s)return r.writeHead(404,{"Content-Type":"text/plain"}),void r.end(`Unknown host: ${n}\nRegistered: ${Object.keys(o).join(", ")}`);if("/api/gateway-info"===t.url){const e=JSON.stringify(o["project-graph.local"]||{routes:{}});return r.writeHead(200,{"Content-Type":"application/json"}),void r.end(e)}const i=e.request({hostname:"127.0.0.1",port:s.port,path:s.rewritePath,method:t.method,headers:{...t.headers,host:`localhost:${s.port}`}},e=>{if((e.headers["content-type"]||"").includes("text/html")&&s.prefix){const t=[];e.on("data",e=>t.push(e)),e.on("end",()=>{let n=Buffer.concat(t).toString("utf8");
19
+ const o=`<base href="${s.prefix}/">`;n=n.includes("<head>")?n.replace("<head>",`<head>\n ${o}`):o+"\n"+n;
20
+ const i=Buffer.from(n,"utf8"),a={...e.headers};a["content-length"]=i.length,delete a["transfer-encoding"],r.writeHead(e.statusCode,a),r.end(i)})}else r.writeHead(e.statusCode,e.headers),e.pipe(r)});i.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Backend unavailable on port ${s.port}`)}),t.pipe(i)});function startListening(e){n.listen(e,"0.0.0.0",()=>{const e=n.address().port;r.mkdirSync(s,{recursive:!0}),r.writeFileSync(a,JSON.stringify({pid:process.pid,port:e}))})}n.on("upgrade",(e,r,n)=>{const o=(e.headers.host||"").split(":")[0],s=readRegistry(),i=resolveBackend(o,e.url,s);if(!i||i.isDashboard)return void r.destroy();
21
+ const a=t.createConnection({host:"127.0.0.1",port:i.port},()=>{const t=i.rewritePath,o=`${e.method} ${t} HTTP/1.1\r\n`+Object.entries(e.headers).map(([e,t])=>`${e}: ${t}`).join("\r\n")+"\r\n\r\n";a.write(o),n.length&&a.write(n);
22
+ let s=Buffer.alloc(0);a.on("data",function onFirstData(e){s=Buffer.concat([s,e]),-1!==s.indexOf("\r\n\r\n")&&(r.write(s),a.removeListener("data",onFirstData),r.pipe(a),a.pipe(r))})});a.on("error",e=>{console.error("WS PROXY ERROR:",e.message),r.destroy()}),r.on("error",e=>{console.error("WS CLIENT ERROR:",e.message),a.destroy()})}),n.on("error",e=>{"EACCES"===e.code&&!1===n.listening?startListening(8080):"EADDRINUSE"===e.code&&n.listening}),startListening(80)}catch{}}
23
+ function stopGateway(){try{r.unlinkSync(a),r.unlinkSync(i)}catch{}}
@@ -0,0 +1,13 @@
1
+ // @ctx .context/src/network/mdns.ctx
2
+ import{spawn as t}from"node:child_process";
3
+ import e from"node:dgram";
4
+ const r="224.0.0.251";
5
+ export function registerLocal(t,e){if("darwin"===process.platform)return registerDnsSd(t,e);if("linux"===process.platform){const e=tryAvahi(t);if(e)return e}return registerMcast(t)}
6
+ function registerDnsSd(e,r){const n=t("dns-sd",["-P","Project Graph","_http._tcp","",String(r),e,"127.0.0.1"],{stdio:"ignore",detached:!1});return n.unref(),{method:"Bonjour (dns-sd)",cleanup:()=>{try{n.kill()}catch{}}}}
7
+ function tryAvahi(e){try{const r=t("avahi-publish-address",["-R",e,"127.0.0.1"],{stdio:"ignore",detached:!1});
8
+ let n=!1;return r.on("error",()=>{n=!0}),r.unref(),n?null:{method:"Avahi",cleanup:()=>{try{r.kill()}catch{}}}}catch{return null}}
9
+ function registerMcast(t){const n=t.split("."),c=Buffer.concat([...n.map(t=>{const e=Buffer.alloc(1+t.length);return e[0]=t.length,e.write(t,1,"ascii"),e}),Buffer.from([0])]);
10
+ let o;try{o=e.createSocket({type:"udp4",reuseAddr:!0})}catch{return{method:"none",cleanup:()=>{}}}o.on("message",t=>{if(t.length<12)return;if(32768&t.readUInt16BE(2))return;if(0===t.readUInt16BE(4))return;if(12+c.length+4>t.length)return;if(0!==t.compare(c,0,c.length,12,12+c.length))return;
11
+ const e=12+c.length,n=t.readUInt16BE(e),i=32767&t.readUInt16BE(e+2);if(1!==n||1!==i)return;
12
+ const s=Buffer.alloc(12+c.length+10+4);
13
+ let a=0;s.writeUInt16BE(0,a),a+=2,s.writeUInt16BE(33792,a),a+=2,s.writeUInt16BE(0,a),a+=2,s.writeUInt16BE(1,a),a+=2,s.writeUInt16BE(0,a),a+=2,s.writeUInt16BE(0,a),a+=2,c.copy(s,a),a+=c.length,s.writeUInt16BE(1,a),a+=2,s.writeUInt16BE(32769,a),a+=2,s.writeUInt32BE(120,a),a+=4,s.writeUInt16BE(4,a),a+=2,s[a++]=127,s[a++]=0,s[a++]=0,s[a++]=1,o.send(s,0,a,5353,r)}),o.on("error",()=>{try{o.close()}catch{}});try{o.bind({port:5353,exclusive:!1},()=>{try{o.addMembership(r),o.setMulticastTTL(255)}catch{try{o.close()}catch{}}})}catch{return{method:"none",cleanup:()=>{}}}return{method:"Node.js mDNS",cleanup:()=>{try{o.close()}catch{}}}}
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ // @ctx .context/src/network/server.ctx
3
+ import e from"node:path";
4
+ import t from"node:fs";if(process.argv[1]&&(process.argv[1].endsWith("server.js")||process.argv[1].endsWith("project-graph-mcp"))){const[,,o,...r]=process.argv;if("serve"===o){const t=r[0]||".",o=r.indexOf("--port"),s=-1!==o?parseInt(r[o+1],10):0;if(s){const{startWebServer:e}=await import("./web-server.js");e(t,s)}else{const{ensureBackend:o}=await import("./backend-lifecycle.js");try{const r=await o(t),s=e.resolve(t);console.log("\n ⬡ project-graph-mcp"),console.log(" ─────────────────────────────"),console.log(` → http://localhost:${r}/`),console.log(` → Project: ${s}`),console.log(` → MCP WebSocket: ws://127.0.0.1:${r}/mcp-ws\n`)}catch(e){console.error(`Failed to start backend: ${e.message}`),process.exit(1)}}}else if(o){const{runCLI:e}=await import("../cli/cli.js");e(o,r)}else if(process.env.PROJECT_GRAPH_BACKEND){const{startStdioServer:e}=await import("../mcp/mcp-server.js");console.error("Starting Project Graph MCP (stdio, direct)..."),e()}else{const{setRoots:e,getWorkspaceRoot:o}=await import("../core/workspace.js"),{ensureBackend:r,startStdioProxy:s}=await import("./backend-lifecycle.js"),{createInterface:i}=await import("node:readline"),n=t.createWriteStream("/tmp/pg-init-debug.log",{flags:"a"});n.write(`\n=== NEW SESSION ${(new Date).toISOString()} ===\n`);
5
+ const c=i({input:process.stdin,terminal:!1}),a=[];
6
+ let l=!1,p=null,d=null;
7
+ const startProxy=async e=>{if(!l){l=!0,c.removeAllListeners("line"),c.close(),n.write(`RESOLVED: ${e}\n`),n.end();try{const t=await r(e);console.error(`[project-graph] Connected to backend on port ${t} (project: ${e})`),s(t,a)}catch(e){console.error(`[project-graph] Singleton failed (${e.message}), falling back to direct stdio`);const{startStdioServer:t}=await import("../mcp/mcp-server.js");t(a)}}};c.on("line",t=>{try{const r=JSON.parse(t);if(n.write(`IN: ${r.method||`response:${r.id}`}\n`),"initialize"===r.method){d=r.id,r.params?.roots?.length>0&&(e(r.params.roots),n.write("ROOTS from initialize.params\n"));
8
+ const t=JSON.stringify({jsonrpc:"2.0",id:r.id,result:{protocolVersion:"2025-06-18",capabilities:{tools:{},resources:{}},serverInfo:{name:"project-graph",version:"2.0.0"}}});return n.write("OUT: initialize response\n"),void process.stdout.write(t+"\n")}if("initialized"===r.method||"notifications/initialized"===r.method){n.write("IN: initialized notification\n"),p=999999;
9
+ const e=JSON.stringify({jsonrpc:"2.0",id:p,method:"roots/list"});return n.write(`OUT: roots/list request id=${p}\n`),process.stdout.write(e+"\n"),void setTimeout(()=>{if(!l){const e=o();n.write(`ROOTS timeout, using: ${e}\n`),startProxy(e)}},2e3)}if(void 0!==r.id&&r.id===p&&(n.write(`IN: roots/list response: ${JSON.stringify(r.result)}\n`),r.result?.roots?.length>0)){e(r.result.roots);
10
+ const t=o();return n.write(`ROOTS resolved: ${t}\n`),void startProxy(t)}a.push(t)}catch{a.push(t)}}),setTimeout(()=>{if(!l){const e=o();n.write(`TIMEOUT: fallback to ${e}\n`),console.error(`[project-graph] No roots received in 5s, using fallback: ${e}`),startProxy(e)}},5e3)}}