project-graph-mcp 2.1.2 → 2.1.4

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 (70) hide show
  1. package/GUIDE.md +237 -0
  2. package/package.json +2 -1
  3. package/rules/test-rules.json +15 -0
  4. package/src/.project-graph-cache.json +1 -1
  5. package/src/analysis/analysis-cache.js +3 -1
  6. package/src/analysis/complexity.js +9 -13
  7. package/src/analysis/custom-rules.js +16 -35
  8. package/src/analysis/db-analysis.js +2 -6
  9. package/src/analysis/dead-code.js +8 -18
  10. package/src/analysis/full-analysis.js +9 -17
  11. package/src/analysis/jsdoc-checker.js +11 -23
  12. package/src/analysis/jsdoc-generator.js +8 -9
  13. package/src/analysis/similar-functions.js +8 -15
  14. package/src/analysis/test-annotations.js +12 -20
  15. package/src/analysis/type-checker.js +5 -7
  16. package/src/analysis/undocumented.js +10 -13
  17. package/src/cli/cli-handlers.js +4 -3
  18. package/src/compact/ai-context.js +2 -2
  19. package/src/compact/compact-migrate.js +8 -16
  20. package/src/compact/compact.js +3 -5
  21. package/src/compact/compress.js +7 -13
  22. package/src/compact/ctx-resolver.js +5 -0
  23. package/src/compact/ctx-to-jsdoc.js +13 -28
  24. package/src/compact/doc-dialect.js +18 -29
  25. package/src/compact/expand.js +10 -36
  26. package/src/compact/jsdoc-builder.js +5 -0
  27. package/src/compact/mode-config.js +6 -6
  28. package/src/compact/split-declarations.js +2 -0
  29. package/src/compact/validate-pipeline.js +7 -8
  30. package/src/core/event-bus.js +2 -1
  31. package/src/core/file-walker.js +4 -0
  32. package/src/core/filters.js +6 -5
  33. package/src/core/graph-builder.js +4 -11
  34. package/src/core/parser.js +19 -29
  35. package/src/core/utils.js +2 -0
  36. package/src/lang/lang-sql.js +7 -20
  37. package/src/mcp/mcp-server.js +2 -3
  38. package/src/mcp/tool-defs.js +1 -1
  39. package/src/mcp/tools.js +13 -21
  40. package/src/network/backend-lifecycle.js +15 -18
  41. package/src/network/local-gateway.js +10 -22
  42. package/src/network/mdns.js +5 -11
  43. package/src/network/server.js +1 -2
  44. package/src/network/web-server.js +7 -33
  45. package/web/app.js +19 -14
  46. package/web/components/code-block.js +1 -0
  47. package/web/components/quick-open.js +1 -0
  48. package/web/dashboard-state.js +1 -0
  49. package/web/panels/ActionBoard/ActionBoard.css.js +1 -0
  50. package/web/panels/ActionBoard/ActionBoard.js +5 -4
  51. package/web/panels/ActionBoard/ActionBoard.tpl.js +1 -0
  52. package/web/panels/EventItem/EventItem.css.js +1 -0
  53. package/web/panels/EventItem/EventItem.js +4 -4
  54. package/web/panels/EventItem/EventItem.tpl.js +1 -0
  55. package/web/panels/ProjectItem/ProjectItem.css.js +2 -1
  56. package/web/panels/ProjectItem/ProjectItem.js +3 -4
  57. package/web/panels/ProjectItem/ProjectItem.tpl.js +2 -1
  58. package/web/panels/ProjectList/ProjectList.css.js +1 -0
  59. package/web/panels/ProjectList/ProjectList.js +5 -4
  60. package/web/panels/ProjectList/ProjectList.tpl.js +1 -0
  61. package/web/panels/SettingsPanel/SettingsPanel.css.js +1 -0
  62. package/web/panels/SettingsPanel/SettingsPanel.js +2 -3
  63. package/web/panels/SettingsPanel/SettingsPanel.tpl.js +1 -0
  64. package/web/panels/code-viewer.js +1 -0
  65. package/web/panels/ctx-panel.js +1 -0
  66. package/web/panels/dep-graph.js +1 -0
  67. package/web/panels/file-tree.js +4 -188
  68. package/web/panels/health-panel.js +1 -0
  69. package/web/panels/live-monitor.js +1 -0
  70. package/web/state.js +7 -10
@@ -1,31 +1,21 @@
1
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";
2
+ import{readFileSync as e,readdirSync as s,statSync as t,existsSync as n}from"fs";
3
+ import{join as r,relative as o,resolve as i}from"path";
4
+ import{parse as a}from"../../vendor/acorn.mjs";
5
+ import*as c from"../../vendor/walk.mjs";
6
+ import{shouldExcludeDir as l,shouldExcludeFile as p,parseGitignore as u}from"./filters.js";
7
+ import{parseTypeScript as f}from"../lang/lang-typescript.js";
8
+ import{parsePython as d}from"../lang/lang-python.js";
9
+ import{parseGo as m}from"../lang/lang-go.js";
10
+ import{parseSQL as h,extractSQLFromString as y,isSQLString as g}from"../lang/lang-sql.js";
3
11
  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})}
12
+ export async function parseFile(e,s){const t={file:s,classes:[],functions:[],imports:[],exports:[]},n=[];let r;try{r=a(e,{ecmaVersion:"latest",sourceType:"module",locations:!0,onComment:n})}catch(e){return console.warn(`Parse error in ${s}:`,e.message),t}const o=function(e,s){const t=new Map;for(const n of e){if("Block"!==n.type||!n.value.startsWith("*"))continue;const e="/*"+n.value+"*/",r=s.slice(0,n.end).split("\n").length,o=[],i=/@param\s+\{/g;let a;for(;null!==(a=i.exec(e));){let s=1,t=a.index+a[0].length;for(;t<e.length&&s>0;)"{"===e[t]?s++:"}"===e[t]&&s--,t++;if(0!==s)continue;const n=e.slice(a.index+a[0].length,t-1),r=e.slice(t).match(/^\s+(\[?\w+(?:\.\w+)*\]?)/);if(!r)continue;let i=r[1];i.startsWith("[")&&(i=i.slice(1)),i.endsWith("]")&&(i=i.slice(0,-1)),i.includes(".")||o.push({name:i,type:n})}let c=null;const l=e.match(/@returns?\s+\{([^}]+)\}/);l&&(c=l[1]),(o.length>0||c)&&t.set(r,{params:o,returns:c})}return t}(n,e),i=new Set;c.simple(r,{ImportDeclaration(e){for(const s of e.specifiers)"ImportDefaultSpecifier"===s.type?t.imports.push(s.local.name):"ImportSpecifier"===s.type&&t.imports.push(s.imported.name)},ExportNamedDeclaration(e){if(e.declaration)if(e.declaration.id)i.add(e.declaration.id.name);else if(e.declaration.declarations)for(const s of e.declaration.declarations)i.add(s.id.name);if(e.specifiers)for(const s of e.specifiers)i.add(s.exported.name)},ExportDefaultDeclaration(e){e.declaration&&e.declaration.id&&i.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:s,line:e.loc.start.line};for(const s of e.body.body)if("MethodDefinition"===s.type&&"constructor"!==s.key.name)n.methods.push(s.key.name),j(s.value.body,n.calls,n.dbReads,n.dbWrites);else if("PropertyDefinition"===s.type&&"init$"===s.key.name&&s.value&&"ObjectExpression"===s.value.type)for(const e of s.value.properties)e.key&&e.key.name&&n.properties.push(e.key.name);t.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=function(e,s){for(let t=1;t<=3;t++){const n=e.get(s-t);if(n)return n}return null}(o,e.loc.start.line),i=function(e,s){if(!s||0===s.params.length)return e;const t=new Map;for(const e of s.params)t.set(e.name,e.type);return e.map(e=>{const s=e.startsWith("..."),n=e.endsWith("=");let r=e;s&&(r=r.slice(3)),n&&(r=r.slice(0,-1));let o=t.get(r);return o?(o.startsWith("...")&&(o=o.slice(3)),`${s?"...":""}${r}:${o}${n?"=":""}`):e})}(n,r),a={name:e.id.name,exported:!1,params:i,async:e.async||!1,returns:r?.returns||null,calls:[],dbReads:[],dbWrites:[],file:s,line:e.loc.start.line};j(e.body,a.calls,a.dbReads,a.dbWrites),t.functions.push(a)}}});for(const e of t.functions)e.exported=i.has(e.name);return t.exports=[...i],t}
13
+ const b=new Set(["query","execute","raw","exec","queryFile","none","one","many","any","oneOrNone","manyOrNone","result"]);
14
+ function j(e,s,t,n){e&&c.simple(e,{CallExpression(e){const r=e.callee;if("MemberExpression"===r.type){const e=r.object,t=r.property;if("Identifier"===t.type)if("Identifier"===e.type){const n=`${e.name}.${t.name}`;s.includes(n)||s.push(n)}else if("MemberExpression"===e.type&&"Identifier"===e.property.type){const n=`${e.property.name}.${t.name}`;s.includes(n)||s.push(n)}else if("ThisExpression"===e.type){const e=t.name;s.includes(e)||s.push(e)}}else if("Identifier"===r.type){const e=r.name;s.includes(e)||s.push(e)}if(t&&n){const s=function(e){const s=e.callee;return"MemberExpression"===s.type&&"Identifier"===s.property.type?s.property.name:null}(e);if(s&&b.has(s)&&e.arguments.length>0){const s=function(e){return e?"Literal"===e.type&&"string"==typeof e.value?e.value:"TemplateLiteral"===e.type?S(e):null:null}(e.arguments[0]);if(s&&g(s)){const e=y(s);e.reads.forEach(e=>{t.includes(e)||t.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}}}},TaggedTemplateExpression(e){if(!t||!n)return;const s=function(e){return"Identifier"===e.type?e.name:"MemberExpression"===e.type&&"Identifier"===e.property.type?e.property.name:null}(e.tag);if(s&&/sql/i.test(s)){const s=S(e.quasi);if(s){const e=y(s);e.reads.forEach(e=>{t.includes(e)||t.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}}},TemplateLiteral(e){if(!t||!n)return;const s=S(e);if(s&&g(s)){const e=y(s);e.reads.forEach(e=>{t.includes(e)||t.push(e)}),e.writes.forEach(e=>{n.includes(e)||n.push(e)})}},Literal(e){if(t&&n&&"string"==typeof e.value&&g(e.value)){const s=y(e.value);s.reads.forEach(e=>{t.includes(e)||t.push(e)}),s.writes.forEach(e=>{n.includes(e)||n.push(e)})}}})}
15
+ function S(e){if(!e||!e.quasis)return"";let s="";for(let t=0;t<e.quasis.length;t++)s+=e.quasis[t].value.cooked||e.quasis[t].value.raw||"",t<e.expressions?.length&&(s+="$"+(t+1));return s}
16
+ export function discoverSubProjects(a){const c=i(a),l=[],p=["packages","apps","services","modules","libs","plugins"];for(const i of p){const a=r(c,i);if(n(a))try{for(const i of s(a)){const s=r(a,i),p=r(s,"package.json");if(t(s).isDirectory()&&n(p))try{const t=JSON.parse(e(p,"utf-8"));l.push({name:t.name||i,path:o(c,s),absolutePath:s})}catch{l.push({name:i,path:o(c,s),absolutePath:s})}}}catch{}}return l}
17
+ export async function parseProject(s,t={}){const n={files:[],classes:[],functions:[],imports:[],exports:[],tables:[]},a=i(s),c=findJSFiles(s);for(const s of c)try{const t=e(s,"utf-8"),r=o(a,s),i=await v(t,r);n.files.push(r),n.classes.push(...i.classes),n.functions.push(...i.functions),n.imports.push(...i.imports),n.exports.push(...i.exports),i.tables?.length&&n.tables.push(...i.tables)}catch(e){}if(t.recursive){const e=discoverSubProjects(s);n.subProjects=[];for(const s of e)try{const e=await parseProject(s.absolutePath);for(const t of e.files)n.files.push(r(s.path,t));for(const t of e.classes)t.file=r(s.path,t.file),n.classes.push(t);for(const t of e.functions)t.file=r(s.path,t.file),n.functions.push(t);n.imports.push(...e.imports),n.exports.push(...e.exports),e.tables?.length&&n.tables.push(...e.tables),n.subProjects.push({name:s.name,path:s.path,files:e.files.length})}catch{}}return n.imports=[...new Set(n.imports)],n.exports=[...new Set(n.exports)],n}
18
+ async function v(e,s){return s.endsWith(".sql")?h(e,s):s.endsWith(".py")?d(e,s):s.endsWith(".go")?m(e,s):s.endsWith(".ts")||s.endsWith(".tsx")?f(e,s):parseFile(e,s)}
19
+ function E(e){return!e.endsWith(".css.js")&&!e.endsWith(".tpl.js")&&x.some(s=>e.endsWith(s))}
20
+ export function findJSFiles(e,n=e){e===n&&u(n);const i=[];try{for(const a of s(e)){const s=r(e,a),c=t(s),u=o(n,e);c.isDirectory()?l(a,u)||i.push(...findJSFiles(s,n)):E(a)&&(p(a,u)||i.push(s))}}catch(s){console.warn(`Cannot read directory ${e}:`,s.message)}return i}
21
+ export function findAllProjectFiles(e,n=e){e===n&&u(n);const a=[],c=i(n);try{for(const i of s(e)){const s=r(e,i),u=t(s),f=o(c,e);u.isDirectory()?l(i,f)||a.push(...findAllProjectFiles(s,n)):p(i,f)||a.push(o(c,s))}}catch(s){console.warn(`Cannot read directory ${e}:`,s.message)}return a}
@@ -0,0 +1,2 @@
1
+ // @ctx .context/src/core/utils.ctx
2
+ export function estimateTokens(e){const t="string"==typeof e?e:JSON.stringify(e);return Math.ceil(t.length/4)}
@@ -1,23 +1,10 @@
1
1
  // @ctx .context/src/lang/lang-sql.ctx
2
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
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]}}
4
+ function t(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:[]};const n=new Set,s=new Set,r=e.replace(/--[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim(),a=/\bFROM\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;let o;for(;null!==(o=a.exec(r));){if(r.slice(o.index+o[0].length).trimStart().startsWith("("))continue;const e=o[1].split(".").pop();t(e)&&n.add(e)}const i=/\bJOIN\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(o=i.exec(r));){if(r.slice(o.index+o[0].length).trimStart().startsWith("("))continue;const e=o[1].split(".").pop();t(e)&&n.add(e)}const c=/\bINSERT\s+INTO\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(o=c.exec(r));){const e=o[1].split(".").pop();t(e)&&s.add(e)}const l=/\bUPDATE\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(o=l.exec(r));){const e=o[1].split(".").pop();t(e)&&s.add(e)}const d=/\bDELETE\s+FROM\s+([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)?)/gi;for(;null!==(o=d.exec(r));){const e=o[1].split(".").pop();t(e)&&s.add(e)}for(const e of s)if(/\bDELETE\s+FROM\s+/i.test(r)){const t=r.match(/\bDELETE\s+FROM\s+([a-zA-Z_]\w*)/i);if(t){const s=t[1].split(".").pop();e===s&&n.delete(s)}}return{reads:[...n],writes:[...s]}}
6
+ export function parseSQL(e="",t=""){const s={file:t,classes:[],functions:[],imports:[],exports:[],tables:[]};if(!e)return s;const r=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:[a-zA-Z_]\w*\.)?([a-zA-Z_]\w*)\s*\(([\s\S]*?)\);/gi;let a;for(;null!==(a=r.exec(e));){const r=a[1],o=a[2],i=e.substring(0,a.index).split("\n").length,c=n(o);s.tables.push({name:r,columns:c,file:t,line:i})}return s}
7
+ function n(t){const n=[],s=function(e){const t=[];let n="",s=0;for(let r=0;r<e.length;r++){const a=e[r];if("("===a)s++;else if(")"===a)s--;else if(","===a&&0===s){t.push(n),n="";continue}n+=a}return n.trim()&&t.push(n),t}(t);for(const t of s){const s=t.trim();if(/^\s*(PRIMARY|FOREIGN|UNIQUE|CHECK|CONSTRAINT|EXCLUDE)\b/i.test(s))continue;const r=s.match(/^([a-zA-Z_]\w*)\s+([A-Za-z]\w*(?:\s*\([^)]*\))?(?:\s*\[\])?)/);if(r){const t=r[1],s=r[2].trim();e.has(t.toLowerCase())||n.push({name:t,type:s})}}return n}
8
+ export function extractSQLFromCode(e){const t=new Set,n=new Set;if(!e)return{reads:[],writes:[]};const s=[/"""([\s\S]*?)"""/g,/'''([\s\S]*?)'''/g,/`([\s\S]*?)`/g,/"((?:[^"\\]|\\.)*)"/g,/'((?:[^'\\]|\\.)*)'/g];for(const r of s){let s;for(;null!==(s=r.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 r=extractORMFromCode(e);return r.reads.forEach(e=>t.add(e)),r.writes.forEach(e=>n.add(e)),{reads:[...t],writes:[...n]}}
9
+ const s=new Set(["findmany","findfirst","findunique","findraw","findall","findone","findbypk","findandcountall","count","aggregate","groupby","select","where","first","pluck"]),r=new Set(["create","createmany","update","updatemany","upsert","delete","deletemany","destroy","bulkcreate","insert","del","truncate"]);
10
+ export function extractORMFromCode(e){const n=new Set,a=new Set;if(!e)return{reads:[],writes:[]};const o=/\bprisma\.(\w+)\.(findMany|findFirst|findUnique|findRaw|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate|groupBy)\s*\(/g;let i;for(;null!==(i=o.exec(e));){const e=i[1],t=i[2].toLowerCase();if(e.startsWith("$"))continue;const o=e;s.has(t)?n.add(o):r.has(t)&&a.add(o)}const c=/\b([A-Z][a-zA-Z]+)\.(findAll|findOne|findByPk|findAndCountAll|create|bulkCreate|update|destroy|count|sum|min|max)\s*\(/g;for(;null!==(i=c.exec(e));){const e=i[1],t=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;const o=e.toLowerCase();s.has(t)?n.add(o):r.has(t)&&a.add(o)}const l=/\bknex\s*\(\s*['"](\w+)['"]\s*\)/g;for(;null!==(i=l.exec(e));){const s=i[1];if(t(s)){const t=e.slice(i.index,i.index+200);/\.(insert|update|del|delete|truncate)\s*\(/i.test(t)?a.add(s):n.add(s)}}const d=/\.(from|into|table)\s*\(\s*['"](\w+)['"]\s*\)/g;for(;null!==(i=d.exec(e));){const e=i[1].toLowerCase(),s=i[2];t(s)&&("into"===e?a.add(s):n.add(s))}return{reads:[...n],writes:[...a]}}
@@ -1,12 +1,11 @@
1
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";
2
+ import e from"fs";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
3
  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
4
  const r=new RegExp(`## ${s.topic}`,"i"),n=a.match(r);if(!n)return`Topic '${s.topic}' not found in guide.`;
6
5
  const i=n.index;
7
6
  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
7
  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):[]}};
8
+ 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,fix:e.fix||!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, ${e.summary.astErrors} AST, ${e.summary.styleErrors} style errors.`];return"PASS"===e.status&&t.push(`💡 ${e.summary.jsdocInjected} JSDoc blocks injected. Token savings: ${e.summary.tokenSavings}.`),e.summary.styleErrors>0&&t.push("💡 Run compact({ action: 'validate_pipeline', path: '.', fix: true }) to auto-fix style issues."),e.fix&&t.push(`🔧 Auto-fixed ${e.fix.fixed}/${e.fix.total} files.`),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
9
  export function createServer(s){let n=1;
11
10
  const i=new Map;
12
11
  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)}];
@@ -1,3 +1,3 @@
1
1
  // @ctx .context/src/mcp/tool-defs.ctx
2
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"]}}];
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"},fix:{type:"boolean",description:"For validate_pipeline: auto-fix all style issues — generates .ctx documentation from readable code, then minifies (headers, imports, indentation, long names). Bidirectional: expand restores 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"]}}];
package/src/mcp/tools.js CHANGED
@@ -1,25 +1,17 @@
1
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{}}
2
+ import{parseProject as e,parseFile as t,findJSFiles as n,findAllProjectFiles as r}from"../core/parser.js";
3
+ import{buildGraph as s,createSkeleton as o}from"../core/graph-builder.js";
4
+ import{readFileSync as c,statSync as i,writeFileSync as a,existsSync as l,unlinkSync as f}from"fs";
5
+ import{execSync as u}from"child_process";
6
+ import{join as p}from"path";
7
+ let h=null,d=null,m=new Map;
8
+ export async function getGraph(t){if(h&&d===t){if(!g(t))return h}else if(!h&&function(e){try{const t=p(e,".project-graph-cache.json");if(!l(t))return!1;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,!g(e)||(h=null,d=null,m.clear(),!1)}catch(e){return!1}}(t))return h;const n=await e(t);return h=s(n),d=t,y(t),function(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){}}(t,h),h}
9
+ function g(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}}
10
+ function y(e){m.clear();try{const t=n(e);for(const e of t)try{m.set(e,i(e).mtimeMs)}catch{}}catch{}}
10
11
  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)]}}
12
+ export async function getFocusZone(e={}){const n=e.path||"src/components",r=await getGraph(n);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.`};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=function(e,t){const n=new RegExp(`((?:\\/\\*\\*[\\s\\S]*?\\*\\/\\s*)?)(?:async\\s+)?${t}\\s*\\([^)]*\\)\\s*{`,"g").exec(e);if(!n)return"";const r=n.index;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)}(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}}
14
+ 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.`};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
15
  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}"`}}
16
+ 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'};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);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);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
17
  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()}
@@ -1,19 +1,16 @@
1
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)})}
2
+ import{createHash as e,randomBytes as t}from"node:crypto";
3
+ import{existsSync as r,mkdirSync as n,readFileSync as o,writeFileSync as c,unlinkSync as s,readdirSync as i}from"node:fs";
4
+ import{join as a,resolve as l,basename as f}from"node:path";
5
+ import{spawn as u}from"node:child_process";
6
+ import{createInterface as p}from"node:readline";
7
+ import{createConnection as d}from"node:net";
8
+ import{fileURLToPath as h}from"node:url";
9
+ const m=a(h(import.meta.url),".."),g=a(process.env.HOME||process.env.USERPROFILE||"/tmp",".local-gateway","backends");
10
+ function y(t){const r=l(t),n=e("md5").update(r).digest("hex").slice(0,8);return a(g,`${n}.json`)}
11
+ function B(e){const t=y(e);if(!r(t))return null;try{const e=JSON.parse(o(t,"utf8"));try{process.kill(e.pid,0)}catch{try{s(t)}catch{}return null}return e}catch{return null}}
12
+ export function writePortFile(e,t){n(g,{recursive:!0});const r=l(e),o={port:t,pid:process.pid,project:r,name:f(r)||"root",startedAt:Date.now()};c(y(e),JSON.stringify(o,null,2))}
13
+ export function removePortFile(e){try{s(y(e))}catch{}}
14
+ export function listBackends(){if(!r(g))return[];const e=i(g).filter(e=>e.endsWith(".json")),t=[];for(const r of e)try{const e=JSON.parse(o(a(g,r),"utf8"));try{process.kill(e.pid,0),t.push(e)}catch{try{s(a(g,r))}catch{}}}catch{}return t}
15
+ export async function ensureBackend(e){const t=l(e),n=B(t);if(n)return n.port;const o=a(m,"backend.js");u(process.execPath,[o,t],{detached:!0,stdio:"ignore",env:{...process.env,PROJECT_GRAPH_BACKEND:"1"}}).unref();const c=y(t),s=Date.now();for(;Date.now()-s<1e4;)if(await new Promise(e=>setTimeout(e,200)),r(c)){const e=B(t);if(e)return e.port}throw new Error("Backend failed to start within 10s")}
16
+ export function startStdioProxy(e,r=[]){const n=t(16).toString("base64"),o=d({host:"127.0.0.1",port:e},()=>{o.write(`GET /mcp-ws HTTP/1.1\r\nHost: 127.0.0.1:${e}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${n}\r\nSec-WebSocket-Version: 13\r\n\r\n`)});let c=!1,s=Buffer.alloc(0),i=[...r];const a=p({input:process.stdin,terminal:!1});function l(e){const r=Buffer.from(e,"utf8"),n=t(4),o=Buffer.alloc(r.length);for(let e=0;e<r.length;e++)o[e]=r[e]^n[e%4];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,n,o])}function f(e){if(e.length<2)return null;const t=15&e[0];let r=127&e[1],n=2;if(126===r){if(e.length<4)return null;r=e.readUInt16BE(2),n=4}else if(127===r){if(e.length<10)return null;r=Number(e.readBigUInt64BE(2)),n=10}return e.length<n+r?null:{opcode:t,data:e.slice(n,n+r).toString("utf8"),totalLen:n+r}}a.on("line",e=>{if(c)try{o.write(l(e))}catch{}else i.push(e)}),a.on("close",()=>{o.end(),process.exit(0)}),o.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{o.write(l(e))}catch{}i=[]}for(;s.length>=2;){const e=f(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,o.write(e)}}}),o.on("close",()=>process.exit(0)),o.on("error",e=>{console.error(`[project-graph] Proxy connection error: ${e.message}`),process.exit(1)})}
@@ -1,23 +1,11 @@
1
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{}}
2
+ import t from"node:http";import e from"node:net";import r from"node:fs";import o from"node:path";import{registerLocal as n}from"./mdns.js";
3
+ const s=o.join(process.env.HOME||process.env.USERPROFILE||"/tmp",".local-gateway"),c=o.join(s,"services.json"),i=o.join(s,"gateway.pid"),a=o.join(s,"backends");
4
+ function p(){try{return JSON.parse(r.readFileSync(c,"utf8"))}catch{return{}}}
5
+ function l(t){r.mkdirSync(s,{recursive:!0}),r.writeFileSync(c,JSON.stringify(t,null,2))}
6
+ function d(){if(!r.existsSync(a))return;const t=r.readdirSync(a).filter(t=>t.endsWith(".json"));let e=!1;const n=p();for(const s of t)try{const t=JSON.parse(r.readFileSync(o.join(a,s),"utf8"));try{process.kill(t.pid,0)}catch{r.unlinkSync(o.join(a,s));continue}const c=t.name||"root",i=`/${c}`;n["project-graph.local"]=n["project-graph.local"]||{name:"project-graph",routes:{}},n["project-graph.local"].routes[i]||(n["project-graph.local"].routes[i]={port:t.port,pid:t.pid,projectPath:t.project,projectName:c},e=!0)}catch{}e&&l(n)}
7
+ export function registerService(t,e,r={}){const o=`${t}.local`,s=p();if(r.projectName){s[o]||(s[o]={name:t,routes:{}});const n=`/${r.projectName}`;s[o].routes=s[o].routes||{},s[o].routes[n]={port:e,pid:process.pid,projectPath:r.projectPath,projectName:r.projectName}}else s[o]={port:e,pid:process.pid,name:t};l(s);const c=n(o,80);f();const i=()=>{c.cleanup()};process.on("exit",i),process.on("SIGINT",()=>{i(),process.exit()}),process.on("SIGTERM",()=>{i(),process.exit()});const a=getGatewayPort(),d=80===a?"":`:${a}`,u=r.projectName?`http://${o}${d}/${r.projectName}/`:`http://${o}${d}/`;return{cleanup:i,url:u,directUrl:`http://localhost:${e}/`}}
8
+ function u(t,e,r){const o=r[t];if(!o)return null;if(o.routes){const t=Object.keys(o.routes).sort((t,e)=>e.length-t.length);for(const r of t)if(e===r||e.startsWith(r+"/")){const t=o.routes[r];try{process.kill(t.pid,0)}catch{continue}const n=e.slice(r.length)||"/";return{port:t.port,rewritePath:n,prefix:r}}for(const r of t)try{const t=o.routes[r];process.kill(t.pid,0);const n="/"===e||""===e?"/dashboard.html":e;return{port:t.port,rewritePath:n}}catch{continue}}if(o.port){const t="/"===e||""===e?"/dashboard.html":e;return{port:o.port,rewritePath:t}}return null}
9
+ function h(){try{const t=r.readFileSync(i,"utf8");return t.trim().startsWith("{")?JSON.parse(t):{pid:parseInt(t,10),port:80}}catch{return null}}
10
+ export function getGatewayPort(){const t=h();return t?.port||80}
11
+ function f(){if(!function(){const t=h();if(!t)return!1;try{return process.kill(t.pid,0),!0}catch{return!1}}())try{const o=t.createServer((e,r)=>{const o=(e.headers.host||"").split(":")[0];let n=p(),s=u(o,e.url,n);if(!s&&(d(),n=p(),s=u(o,e.url,n),!s))return r.writeHead(404,{"Content-Type":"text/plain"}),void r.end(`Unknown host: ${o}\nRegistered: ${Object.keys(n).join(", ")}`);if("/api/gateway-info"===e.url){const t=JSON.stringify(n["project-graph.local"]||{routes:{}});return r.writeHead(200,{"Content-Type":"application/json"}),void r.end(t)}if("POST"===e.method&&"/api/remove-project"===e.url){let t="";return e.on("data",e=>t+=e),void e.on("end",()=>{try{const e=JSON.parse(t).route,o=p();if(o["project-graph.local"]?.routes?.[e]){const t=o["project-graph.local"].routes[e];try{process.kill(t.pid,9)}catch{}delete o["project-graph.local"].routes[e],l(o)}r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({ok:!0}))}catch(t){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:t.message}))}})}const c=t.request({hostname:"127.0.0.1",port:s.port,path:s.rewritePath,method:e.method,headers:{...e.headers,host:`localhost:${s.port}`}},t=>{if((t.headers["content-type"]||"").includes("text/html")&&s.prefix){const e=[];t.on("data",t=>e.push(t)),t.on("end",()=>{let o=Buffer.concat(e).toString("utf8");const n=`<base href="${s.prefix}/">`;o=o.includes("<head>")?o.replace("<head>",`<head>\n ${n}`):n+"\n"+o;const c=Buffer.from(o,"utf8"),i={...t.headers};i["content-length"]=c.length,delete i["transfer-encoding"],r.writeHead(t.statusCode,i),r.end(c)})}else r.writeHead(t.statusCode,t.headers),t.pipe(r)});c.on("error",()=>{r.writeHead(502,{"Content-Type":"text/plain"}),r.end(`Backend unavailable on port ${s.port}`)}),e.pipe(c)});function n(t){o.listen(t,"0.0.0.0",()=>{const t=o.address().port;r.mkdirSync(s,{recursive:!0}),r.writeFileSync(i,JSON.stringify({pid:process.pid,port:t})),d()})}o.on("upgrade",(t,r,o)=>{const n=(t.headers.host||"").split(":")[0],s=p(),c=u(n,t.url,s);if(!c||c.isDashboard)return void r.destroy();const i=e.createConnection({host:"127.0.0.1",port:c.port},()=>{const e=c.rewritePath,n=`${t.method} ${e} HTTP/1.1\r\n`+Object.entries(t.headers).map(([t,e])=>`${t}: ${e}`).join("\r\n")+"\r\n\r\n";i.write(n),o.length&&i.write(o);let s=Buffer.alloc(0);i.on("data",function t(e){s=Buffer.concat([s,e]),-1!==s.indexOf("\r\n\r\n")&&(r.write(s),i.removeListener("data",t),r.pipe(i),i.pipe(r))})});i.on("error",t=>{console.error("WS PROXY ERROR:",t.message),r.destroy()}),r.on("error",t=>{console.error("WS CLIENT ERROR:",t.message),i.destroy()})}),o.on("error",t=>{"EACCES"===t.code&&!1===o.listening?n(8080):"EADDRINUSE"===t.code&&o.listening}),n(80)}catch{}}
@@ -1,13 +1,7 @@
1
1
  // @ctx .context/src/network/mdns.ctx
2
- import{spawn as t}from"node:child_process";
3
- import e from"node:dgram";
2
+ import{spawn as t}from"node:child_process";import e from"node:dgram";
4
3
  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{}}}}
4
+ export function registerLocal(t,e){if("darwin"===process.platform)return n(t,e);if("linux"===process.platform){const e=c(t);if(e)return e}return o(t)}
5
+ function n(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{}}}}
6
+ function c(e){try{const r=t("avahi-publish-address",["-R",e,"127.0.0.1"],{stdio:"ignore",detached:!1});let n=!1;return r.on("error",()=>{n=!0}),r.unref(),n?null:{method:"Avahi",cleanup:()=>{try{r.kill()}catch{}}}}catch{return null}}
7
+ function o(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])]);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;const e=12+c.length,n=t.readUInt16BE(e),i=32767&t.readUInt16BE(e+2);if(1!==n||1!==i)return;const a=Buffer.alloc(12+c.length+10+4);let l=0;a.writeUInt16BE(0,l),l+=2,a.writeUInt16BE(33792,l),l+=2,a.writeUInt16BE(0,l),l+=2,a.writeUInt16BE(1,l),l+=2,a.writeUInt16BE(0,l),l+=2,a.writeUInt16BE(0,l),l+=2,c.copy(a,l),l+=c.length,a.writeUInt16BE(1,l),l+=2,a.writeUInt16BE(32769,l),l+=2,a.writeUInt32BE(120,l),l+=4,a.writeUInt16BE(4,l),l+=2,a[l++]=127,a[l++]=0,a[l++]=0,a[l++]=1,o.send(a,0,l,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{}}}}
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
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`);
3
+ import e from"node:path";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
4
  const c=i({input:process.stdin,terminal:!1}),a=[];
6
5
  let l=!1,p=null,d=null;
7
6
  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"));