@kitelev/exocortex-cli 16.235.3 → 16.235.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// @kitelev/exocortex-cli v16.235.
|
|
2
|
+
// @kitelev/exocortex-cli v16.235.5
|
|
3
3
|
// CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
|
|
4
4
|
// License: MIT
|
|
5
5
|
|
|
@@ -554,7 +554,7 @@ Available prefixes: ${u}`,this.wellKnownPrefixes[n]&&c.push(`Add: PREFIX ${n}: <
|
|
|
554
554
|
`),console.log(i.formatAnalysis(s,"text"))):(console.log(i.formatAnalysis(s,"text")),process.exit(2));return}let n=new wr.ExoQLParser;try{let i=n.parse(r);if(i.type!=="update"){let o=new wr.ExoQLAlgebraTranslator().translate(i);if(!e.noOptimize&&o.type!=="construct")o=new wr.AlgebraOptimizer().optimize(o);else if(!e.noOptimize&&o.type==="construct"){let c=new wr.AlgebraOptimizer,l=o;o={...l,where:c.optimize(l.where)}}}if(t==="json"){let s=ft.success({valid:!0,queryType:p6(i),message:"Query syntax is valid"});console.log(JSON.stringify(s,null,2))}else console.log("\u2705 Query syntax is valid"),console.log(` Query type: ${p6(i)}`)}catch(i){m6(i,r,t)}}a(Rhe,"executeDryRun");function p6(r){return r.type==="update"?"UPDATE":"queryType"in r?r.queryType:"UNKNOWN"}a(p6,"getQueryType");function Che(r,e){switch(e){case"json":let t=new FS;console.log(t.format(r));break;case"csv":let n=new DS;console.log(n.format(r));break;default:let i=new Rd;console.log(i.format(r));break}}a(Che,"formatSelectResults");function xhe(r,e){let t=new Cd;switch(e){case"json":console.log(t.formatJson(r));break;case"ntriples":console.log(t.formatNTriples(r));break;default:console.log(t.formatTable(r));break}}a(xhe,"formatConstructResults");function Ohe(r,e){switch(e){case"json":console.log(JSON.stringify(r,null,2));break;case"csv":if(r.length===0){console.log("");return}let t=Object.keys(r[0]);console.log(t.join(","));for(let i of r){let s=t.map(o=>{let c=i[o];return c==null?"":String(c).includes(",")?`"${c}"`:String(c)});console.log(s.join(","))}break;default:if(r.length===0){console.log("No results.");return}let n=Object.keys(r[0]);console.log(n.join(" ")),console.log(n.map(()=>"---").join(" "));for(let i of r){let s=n.map(o=>String(i[o]??""));console.log(s.join(" "))}break}}a(Ohe,"formatCachedSelectResults");function Phe(r,e){switch(e){case"json":console.log(JSON.stringify(r,null,2));break;case"ntriples":for(let t of r)console.log(`<${t.subject}> <${t.predicate}> ${Fhe(t.object)} .`);break;default:console.log("Subject Predicate Object"),console.log("--- --- ---");for(let t of r)console.log(`${t.subject} ${t.predicate} ${t.object}`);break}}a(Phe,"formatCachedConstructResults");function Fhe(r){return QS.formatObject(r)}a(Fhe,"formatNTriplesObject");function Dhe(r,e){for(let t of r){let n=[`${t.type.toUpperCase()}`];switch(t.inserted!==void 0&&n.push(`inserted: ${t.inserted}`),t.deleted!==void 0&&n.push(`deleted: ${t.deleted}`),n.push(t.success?"OK":"FAILED"),e){case"json":console.log(JSON.stringify(t,null,2));break;case"csv":r.indexOf(t)===0&&console.log("type,inserted,deleted,success"),console.log(`${t.type},${t.inserted??""},${t.deleted??""},${t.success}`);break;default:console.log(`\u2705 ${n.join(" | ")}`);break}}}a(Dhe,"formatUpdateResults");ct();var g6=require("fs"),y6=require("path"),Io=J(We());xd();Pt();qt();Sr();function _6(){return new fe("index").description("Build or refresh the triple cache for faster SPARQL queries").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--output <type>","Response format: text|json (for MCP tools)","text").option("--stats","Show cache statistics after building").option("--force","Force rebuild even if cache is valid").option("--strict","Fail on first invalid IRI instead of skipping").option("--no-inference","Disable RDFS subClassOf inference materialization").action(async r=>{let e=r.output||"text";se.setFormat(e);try{let t=(0,y6.resolve)(r.vault);if(!(0,g6.existsSync)(t))throw new Me(t);let n=new ts(t),i=n.getCachePath();r.force&&(e==="text"&&console.log("\u{1F5D1}\uFE0F Invalidating existing cache..."),await n.invalidate()),e==="text"&&console.log(`\u{1F4E6} Building triple cache for: ${t}...`);let s=Date.now(),o=await n.buildCacheWithValidation({strict:r.strict??!1}),c=0;if(r.inference!==!1){let{triples:u}=await n.loadOrBuild(),f=new Io.InMemoryTripleStore;await f.addAll(u),c=await new Io.RDFSInferenceEngine().materialize(f);let p=new Io.NonInheritablePropertyRegistry;await p.initialize(f);let h=new Io.PropertyCardinalityRegistry;await h.initialize(f);let y=await new Io.PrototypeChainMaterializer(p,h).materialize(f);if(c+=y,c>0){let _=await f.match();await n.saveTriples(_),o.tripleCount+=c}e==="text"&&c>0&&console.log(`\u{1F9E0} Materialized ${c} inferred triples (RDFS + prototype chain)`)}let l=Date.now()-s;if(e==="json"){let u={action:"build",cachePath:i,tripleCount:o.tripleCount,durationMs:o.durationMs},f={summary:o.summary,skippedFiles:o.skippedFiles};if(r.stats){let d=await n.getCacheStats();if(d){let p={tripleCount:d.tripleCount,createdAt:d.createdAt.toISOString(),isValid:d.isValid,sizeBytes:d.sizeBytes,cachePath:i},h=ft.success({cache:u,stats:p,validation:f},{durationMs:l});console.log(JSON.stringify(h,null,2))}}else{let d=ft.success({cache:u,validation:f},{durationMs:l});console.log(JSON.stringify(d,null,2))}}else{if(o.skippedFiles.length>0){console.log(`
|
|
555
555
|
\u26A0\uFE0F Files skipped due to IRI issues:`);for(let u of o.skippedFiles)console.log(` - ${u.path}`),console.log(` ${u.reason}`);console.log("")}if(console.log(`\u2705 Indexed ${o.summary.indexed} files, skipped ${o.summary.skipped} (total: ${o.summary.total})`),console.log(`\u{1F4CA} Created cache with ${o.tripleCount.toLocaleString()} triples at ${i}`),console.log(`\u23F1\uFE0F Build time: ${o.durationMs}ms`),r.stats){let u=await n.getCacheStats();u&&(console.log(`
|
|
556
556
|
\u{1F4CA} Cache Statistics:`),console.log(` Triples: ${u.tripleCount.toLocaleString()}`),console.log(` Created: ${u.createdAt.toISOString()}`),console.log(` Valid: ${u.isValid?"\u2705 Yes":"\u274C No"}`),console.log(` Size: ${Lhe(u.sizeBytes)}`))}}}catch(t){se.handle(t)}})}a(_6,"sparqlIndexCommand");function Lhe(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}a(Lhe,"formatBytes");ct();var tw=require("fs"),Bs=require("path");Pt();qt();Sr();mr();function b6(){return new fe("resolve").description("Resolve UUID to file path").argument("<uuid>","Full or partial UUID to resolve").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: uri|path|json (default: uri)","uri").option("--output <type>","Response format: text|json (for MCP tools)","text").option("--partial","Match partial UUIDs (returns all matches)").action(async(r,e)=>{let t=e.output||"text";se.setFormat(t);try{let n=Date.now();if(!Nhe(r))throw new Xe(`Invalid UUID format: ${r}`,"exocortex resolve <uuid> [--format uri|path|json] [--partial]",{uuid:r});let i=(0,Bs.resolve)(e.vault);if(!(0,tw.existsSync)(i))throw new Me(i);let s=khe(i,r,e.partial??!1),o=Date.now()-n;if(s.length===0){if(t==="json"){let c=ft.error("VALIDATION_FILE_NOT_FOUND",`UUID not found: ${r}`,3,{context:{uuid:r}});console.log(JSON.stringify(c,null,2))}else console.error(`UUID not found: ${r}`);process.exit(1)}e.partial||s.length>1?jhe(s,i,e.format,t,r,o):Mhe(s[0],i,e.format,t,r,o)}catch(n){se.handle(n)}})}a(b6,"resolveCommand");function Nhe(r){if(r.length<4)return!1;let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,t=/^[0-9a-f-]+$/i;return e.test(r)||t.test(r)}a(Nhe,"isValidUuidFormat");function khe(r,e,t){let n=[],i=e.toLowerCase();function s(o){let c=(0,tw.readdirSync)(o,{withFileTypes:!0});for(let l of c){let u=(0,Bs.join)(o,l.name);if(l.isDirectory())!l.name.startsWith(".")&&l.name!=="node_modules"&&s(u);else if(l.isFile()&&l.name.endsWith(".md")){let f=l.name.toLowerCase();t?f.includes(i)&&n.push(u):(f.startsWith(i+".md")||f.startsWith(i+" ")||f.startsWith(i+"-"))&&n.push(u)}}}return a(s,"walk"),s(r),n}a(khe,"findFilesWithUuid");function S6(r){return`obsidian://vault/${encodeURI(r)}`}a(S6,"pathToObsidianUri");function w6(r){let e=r.match(/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);return e?e[1]:(0,Bs.basename)(r,".md")}a(w6,"extractUuidFromFilename");function Mhe(r,e,t,n,i,s){let o=(0,Bs.relative)(e,r),c=S6(o),l=w6((0,Bs.basename)(r));if(n==="json"){let u={uuid:l,path:o,absolutePath:r,uri:c},f=ft.success(u,{durationMs:s,searchUuid:i});console.log(JSON.stringify(f,null,2))}else switch(t){case"path":console.log(r);break;case"json":console.log(JSON.stringify({uuid:l,path:o,absolutePath:r,uri:c},null,2));break;default:console.log(c);break}}a(Mhe,"outputSingleResult");function jhe(r,e,t,n,i,s){let o=r.map(c=>{let l=(0,Bs.relative)(e,c),u=S6(l);return{uuid:w6((0,Bs.basename)(c)),path:l,absolutePath:c,uri:u}});if(n==="json"){let c=ft.success({matches:o,count:o.length},{durationMs:s,searchUuid:i,itemCount:o.length});console.log(JSON.stringify(c,null,2))}else switch(t){case"path":for(let c of o)console.log(c.absolutePath);break;case"json":console.log(JSON.stringify(o,null,2));break;default:for(let c of o)console.log(c.uri);break}}a(jhe,"outputMultipleResults");ct();var Jx=require("fs"),Vs=require("path"),Er=J(We());Pt();qt();mr();Bi();var E6=J(We());function rw(r,e){return t=>{let n=typeof t.filePath=="string"&&t.filePath.length>0?t.filePath:null;if(n===null||n.split("/").includes("09 Templates"))return!1;let i=r.getAbstractFileByPath(n);if(i===null||!("basename"in i))return!1;let s=i,o=r.getFrontmatter(s)??{},c=e.getExpectedFolderSync(s,o),l=typeof t.currentFolder=="string"?t.currentFolder:s.parent?.path??"";return(0,E6.needsFolderRepair)(l,c)}}a(rw,"createIsInWrongFolderHostFunction");var v6=J(We());function nw(r){return e=>{let t=typeof e.filePath=="string"&&e.filePath.length>0?e.filePath:null;if(t===null||t.split("/").includes("09 Templates"))return!1;let n=r.getAbstractFileByPath(t);if(n===null||!("basename"in n))return!1;let i=n,s=r.getFrontmatter(i)??{};return(0,v6.hasEmptyProperties)(s)}}a(nw,"createHasEmptyPropertiesHostFunction");var sw={debug(r,e){process.env.EXOCORTEX_DEBUG&&iw("debug",r,e)},info(r,e){iw("info",r,e)},warn(r,e){iw("warn",r,e)},error(r,e,t){iw("error",e?`${r} \u2014 ${e.message}`:r,t)}};function iw(r,e,t){let n=t&&Object.keys(t).length>0?` ${$he(t)}`:"";process.stderr.write(`[${r}] ${e}${n}
|
|
557
|
-
`)}a(iw,"write");function $he(r){try{return JSON.stringify(r)}catch{return"[uninspectable context]"}}a($he,"safeJson");var Uhe=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.md$/i;function T6(r){if(typeof
|
|
557
|
+
`)}a(iw,"write");function $he(r){try{return JSON.stringify(r)}catch{return"[uninspectable context]"}}a($he,"safeJson");var Uhe=/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.md$/i;function T6(r){let e=Array.isArray(r)?r[0]:r;if(typeof e!="string")return null;let t=e.replace(/["'[\]]/g,"").trim(),n=t.indexOf("|");return n!==-1&&(t=t.slice(0,n).trim()),t.length>0?t:null}a(T6,"cleanRef");function Bhe(r){if(!r)return[];let e=r.exo__Instance_class,t=[],n=a(i=>{let s=T6(i);s&&!t.includes(s)&&t.push(s)},"collect");if(typeof e=="string")n(e);else if(Array.isArray(e))for(let i of e)n(i);return t}a(Bhe,"extractClasses");function Vhe(r){let e=r.match(/\/ontology\/([^#/]+)#(.+)$/);return e?`${e[1]}__${e[2]}`:null}a(Vhe,"ontologyIriToSymbolic");async function Ghe(r,e){let t=await r.match(new Er.IRI(e),Er.Namespace.EXO.term("Instance_class"),void 0),n=[];for(let i of t){let s=typeof i.object.value=="string"?i.object.value:String(i.object),o=Vhe(s);o&&!n.includes(o)&&n.push(o)}return n}a(Ghe,"deriveStoreSymbolicClasses");async function qhe(r){let e=new Er.IRI("https://exocortex.my/ontology/exocmd#Command_cliName"),t=await r.match(void 0,e,void 0),n=new Map;for(let i of t){let s=typeof i.subject.value=="string"?i.subject.value:String(i.subject),o=typeof i.object.value=="string"?i.object.value:String(i.object),c=s.match(Uhe);c&&o.length>0&&n.set(c[1],o)}return n}a(qhe,"buildCliNameMap");async function Whe(r,e,t=(0,Er.liveClock)()){let n=(0,Vs.resolve)(r);if(!(0,Jx.existsSync)(n))throw new Me(n);let i=(0,Vs.resolve)(n,e);if(!(0,Jx.existsSync)(i))throw new Error(`Target file not found: ${e}`);let s=(0,Vs.relative)(n,i);if(s===".."||s.startsWith(`..${Vs.sep}`)||(0,Vs.isAbsolute)(s))throw new Error(`Target is outside the vault: ${e} (vault: ${n})`);let o=new $t(n),l=await new Er.NoteToRDFConverter(o).convertVault(),u=new Er.InMemoryTripleStore;await u.addAll(l);let f=(0,Er.vaultPathToIRI)(s),d=o.getAbstractFileByPath(s),p=d!==null&&"basename"in d?d:null,h=p?o.getFrontmatter(p):null,m=Bhe(h),y=await Ghe(u,f),_=[...new Set([...m,...y])],b=T6(h?.exo__Asset_prototype),T=h?.exo__Asset_uid,I=typeof T=="string"?T:void 0,S=await new Er.CommandResolver(u,sw).resolveForAssetMulti(f,_,b??void 0),R=new Er.FolderRepairService(o),D=new Er.PreconditionEvaluator(u,void 0,{clock:t});(0,Er.registerDefaultHostFunctions)(D),D.registerHostFunction("isInWrongFolder",rw(o,R)),D.registerHostFunction("hasObsoleteProperties",nw(o));let P=(0,Vs.dirname)(s),M={targetIRI:f,filePath:s,fileBasename:p?.basename,currentFolder:P==="."?"":P,assetUid:I},O=await qhe(u),L=await Promise.all(S.map(async K=>{let Se;try{Se=await D.evaluate(K.command.precondition,f,M)}catch{Se=!1}return{rc:K,available:Se}})),te=a(K=>({id:K.command.id,label:K.command.name,cliName:O.get(K.command.id)??null,category:K.command.category??null}),"toEntry"),re=L.filter(K=>K.available).map(K=>te(K.rc)),V=L.filter(K=>!K.available).map(K=>({...te(K.rc),reason:"precondition-false"}));return{target:s,classes:_,prototype:b,visible:re,hidden:V}}a(Whe,"resolveButtons");function Hhe(r,e){let t=a(n=>`${n.label}${n.cliName?` (${n.cliName})`:""}`,"fmt");if(console.log(`Command buttons on "${r.target}" (${r.visible.length} visible):`),r.visible.length===0)console.log(" (none)");else for(let n of r.visible)console.log(` \u2713 ${t(n)}`);if(e)if(console.log(`
|
|
558
558
|
Hidden by precondition (${r.hidden.length}):`),r.hidden.length===0)console.log(" (none)");else for(let n of r.hidden)console.log(` \u2717 ${t(n)} \u2014 precondition not satisfied`)}a(Hhe,"printHuman");function A6(){return new fe("resolve-inline-buttons").alias("resolve-buttons").description("Print the actual command button-set for an asset \u2014 binding-match \u2229 precondition-eval (Issue #3833). The authoritative button-visibility oracle; strictly more complete than `apply --dry-run` (precondition-only).").argument("<target>","Vault-relative path to the target asset").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--json","Emit structured JSON instead of human-readable text").option("--show-hidden","Also list commands that bind but are hidden by their precondition").action(async(r,e)=>{se.setFormat(e.json?"json":"text");try{let t=await Whe(e.vault,r);if(e.json){let n=e.showHidden?t:{...t,hidden:[]};console.log(JSON.stringify(n,null,2))}else Hhe(t,e.showHidden??!1)}catch(t){se.handle(t),process.exit(5)}})}a(A6,"resolveButtonsCommand");ct();var Zx=require("fs"),Gs=require("path"),Dc=J(We());Pt();qt();mr();Bi();var ow=class{constructor(e){this.vault=e}static{a(this,"FsVaultMetadataAdapter")}*listFrontmatter(){for(let e of this.vault.getAllFiles()){let t=this.vault.getFrontmatter(e);t&&(yield t)}}resolveLinkpathFrontmatter(e){let t={allowAliasFallback:!1},n=this.vault.getFirstLinkpathDest(e,"",t);return!n&&!e.endsWith(".md")&&(n=this.vault.getFirstLinkpathDest(`${e}.md`,"",t)),n?this.vault.getFrontmatter(n)??{}:null}};async function zhe(r,e){let t=(0,Gs.resolve)(r);if(!(0,Zx.existsSync)(t))throw new Me(t);let n=(0,Gs.resolve)(t,e);if(!(0,Zx.existsSync)(n))throw new Error(`Target file not found: ${e}`);let i=(0,Gs.relative)(t,n);if(i===".."||i.startsWith(`..${Gs.sep}`)||(0,Gs.isAbsolute)(i))throw new Error(`Target is outside the vault: ${e} (vault: ${t})`);let s=new $t(t),o=new ow(s),c=new Dc.PrintNameRuleService(o,(0,Dc.createDisplayMatcherHostFunctions)(o));c.initialize();let l=new Dc.DisplayNameResolver(Dc.DEFAULT_DISPLAY_NAME_SETTINGS,c,c.createMetadataResolver()),u=s.getAbstractFileByPath(i),f=u!==null&&"basename"in u?u:null,d=(f?s.getFrontmatter(f):null)??{},p=(0,Gs.basename)(i).replace(/\.md$/,""),h=l.resolveWithProvenance({metadata:d,basename:p}),m=h.displayName??p,y=d.exo__Asset_label,_=typeof y=="string"&&y.trim().length>0,b=h.displayName===null?"basename":h.provenance==="default"?_?"label":"basename":h.provenance,T=d.exo__Asset_uid;return{target:i,uid:typeof T=="string"&&T.trim()?T.trim():null,basename:p,displayName:m,source:b}}a(zhe,"resolveDisplayName");function I6(){return new fe("resolve-display-name").description("Print the composed display name an asset renders as \u2014 the same engine the plugin runs, over the same vault exo__DisplayNameSpec assets (req f17f7c57). The authoritative naming oracle outside Obsidian; --json adds `source`, which distinguishes a spec-composed name from a raw exo__Asset_label.").argument("<target>","Vault-relative path to the target asset").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--json","Emit structured JSON instead of the bare name").action(async(r,e)=>{se.setFormat(e.json?"json":"text");try{let t=await zhe(e.vault,r);e.json?console.log(JSON.stringify(t,null,2)):console.log(t.displayName)}catch(t){se.handle(t),process.exit(5)}})}a(I6,"resolveDisplayNameCommand");ct();sO();ct();var aw=require("fs"),j6=require("path"),Lc=J(We());var vr=J(Ta()),Ci=J(require("path"));yx();var Pa=J(We());var ci=class{constructor(e){this.rootPath=e}static{a(this,"NodeFsAdapter")}async readFile(e){let t=this.resolvePath(e);if(!await vr.default.pathExists(t))throw new Pa.FileNotFoundError(e);return vr.default.readFile(t,"utf-8")}async fileExists(e){let t=this.resolvePath(e);return vr.default.pathExists(t)}async getFileMetadata(e){let t=await this.readFile(e);return this.extractFrontmatter(t)}async createFile(e,t){let n=this.resolvePath(e);if(await vr.default.pathExists(n))throw new Pa.FileAlreadyExistsError(e);return await vr.default.ensureDir(Ci.default.dirname(n)),await vr.default.writeFile(n,t,"utf-8"),e}async updateFile(e,t){let n=this.resolvePath(e);if(!await vr.default.pathExists(n))throw new Pa.FileNotFoundError(e);await vr.default.writeFile(n,t,"utf-8")}async writeFile(e,t){let n=this.resolvePath(e);await vr.default.ensureDir(Ci.default.dirname(n)),await vr.default.writeFile(n,t,"utf-8")}async deleteFile(e){let t=this.resolvePath(e);if(!await vr.default.pathExists(t))throw new Pa.FileNotFoundError(e);await vr.default.remove(t)}async renameFile(e,t){let n=this.resolvePath(e),i=this.resolvePath(t);if(!await vr.default.pathExists(n))throw new Pa.FileNotFoundError(e);await vr.default.ensureDir(Ci.default.dirname(i)),await vr.default.move(n,i)}async createDirectory(e){let t=this.resolvePath(e);await vr.default.ensureDir(t)}async directoryExists(e){let t=this.resolvePath(e);return await vr.default.pathExists(t)?(await vr.default.stat(t)).isDirectory():!1}async getMarkdownFiles(e){let t=e?this.resolvePath(e):this.rootPath,n=Ci.default.join(t,"**/*.md");return(await Id(n,{nodir:!0})).map(o=>Ci.default.relative(this.rootPath,o))}async findFilesByMetadata(e){let t=await this.getMarkdownFiles(),n=[];for(let i of t)try{let s=await this.getFileMetadata(i);this.matchesQuery(s,e)&&n.push(i)}catch{continue}return n}async findFileByUID(e){let t=await this.findFilesByMetadata({exo__Asset_uid:e});return t.length>0?t[0]:null}async findFileByLinkpath(e){let t=e.trim();if(t.length===0)return null;let n=await this.findFileByBasename(`${t}.md`);if(n)return n;let i=await this.getMarkdownFiles();for(let s of i){let o;try{o=await this.getFileMetadata(s)}catch{continue}if(o.exo__Asset_label===t)return s;let c=o.aliases;if(Array.isArray(c)&&c.some(l=>l===t)||typeof c=="string"&&c===t)return s}return null}async findFileByBasename(e){let t=a(async n=>{let i;try{i=await vr.default.readdir(n,{withFileTypes:!0})}catch{return null}for(let s of i){let o=Ci.default.join(n,s.name);if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;let c=await t(o);if(c)return c}else if(s.isFile()&&s.name===e)return Ci.default.relative(this.rootPath,o)}return null},"walk");return t(this.rootPath)}async findFileByUidFilename(e){let t=e.toLowerCase(),n=a(async i=>{let s;try{s=await vr.default.readdir(i,{withFileTypes:!0})}catch{return null}for(let o of s){let c=Ci.default.join(i,o.name);if(o.isDirectory()){if(o.name.startsWith(".")||o.name==="node_modules")continue;let l=await n(c);if(l)return l}else if(o.isFile()&&o.name.endsWith(".md")){let l=o.name.toLowerCase();if(l.startsWith(t+".md")||l.startsWith(t+" ")||l.startsWith(t+"-"))return Ci.default.relative(this.rootPath,c)}}return null},"walk");return n(this.rootPath)}resolvePath(e){if(Ci.default.isAbsolute(e))return e;let t=this.rootPath.replace(/[/\\]+$/,""),n=Ci.default.sep+e;return n===t||n.startsWith(t+Ci.default.sep)?n:Ci.default.join(this.rootPath,e)}extractFrontmatter(e){let t=/^---\n([\s\S]*?)\n---/,n=e.match(t);return n?(0,Pa.parseYamlFrontmatterTolerant)(n[1])??{}:{}}matchesQuery(e,t){for(let[n,i]of Object.entries(t)){let s=e[n];if(Array.isArray(s)){if(!s.some(o=>this.normalizeValue(o)===this.normalizeValue(i)))return!1}else if(this.normalizeValue(s)!==this.normalizeValue(i))return!1}return!0}normalizeValue(e){return e==null?"":String(e).replace(/["'[\]]/g,"").trim()}};var xi=class r extends ci{constructor(t,n){super(t);this.indexed=!1;this.uidToPath=new Map;this.basenameToPaths=new Map;this.allPaths=[];this.pathSet=new Set;this.assets=[];this.cacheContent=n?.cacheContent??!1}static{a(this,"CachingNodeFsAdapter")}async buildIndex(){if(this.indexed)return;let t=await super.getMarkdownFiles();for(let n of t){this.allPaths.push(n),this.pathSet.add(n);let i={},s;try{this.cacheContent?(s=await super.readFile(n),i=this.extractFrontmatter(s)):i=await super.getFileMetadata(n)}catch{i={}}let o=i?.exo__Asset_uid,c=Array.isArray(o)?o:[o];for(let f of c){let d=r.normalizeUid(f);d.length>0&&!this.uidToPath.has(d)&&this.uidToPath.set(d,n)}let l=r.basenameOf(n),u=this.basenameToPaths.get(l);u?u.push(n):this.basenameToPaths.set(l,[n]),this.assets.push(this.cacheContent?{path:n,metadata:i,content:s}:{path:n,metadata:i})}this.indexed=!0}async findPathsByBasename(t){return await this.buildIndex(),this.basenameToPaths.get(t)??[]}async hasIndexedPath(t){await this.buildIndex();let n=t.replace(/\\/g,"/").replace(/^\.\//,"");return this.pathSet.has(n)}static basenameOf(t){let n=t.lastIndexOf("/"),i=n===-1?t:t.slice(n+1);return i.endsWith(".md")?i.slice(0,-3):i}async indexedAssets(){return await this.buildIndex(),this.assets}async getMarkdownFiles(t){return t?super.getMarkdownFiles(t):(await this.buildIndex(),this.allPaths)}async findFileByUID(t){return await this.buildIndex(),this.uidToPath.get(r.normalizeUid(t))??null}static normalizeUid(t){return t==null?"":String(t).replace(/["'[\]]/g,"").trim()}async fileExists(t){await this.buildIndex();let n=t.replace(/\\/g,"/").replace(/^\.\//,"");return this.pathSet.has(n)?!0:super.fileExists(t)}};Pt();qt();var oO=class{constructor(e){this.vaultPath=e}static{a(this,"CliFsCheckReader")}async read(){return{assets:(await new xi(this.vaultPath).indexedAssets()).map(i=>({path:i.path,frontmatter:i.metadata}))}}};function $6(){return new fe("vault").description("Run the homoiconic vault-integrity check-runner (enabled-set from validation-check setting__Setting instances; --all runs every check)").requiredOption("--vault <path>","Vault root directory").option("--all","Run ALL known checks, ignoring the vault enabled-set").option("--output <type>","Response format: text|json","text").action(async r=>{let e=r.output??"text";se.setFormat(e);try{let t=(0,j6.resolve)(r.vault);if(!(0,aw.existsSync)(t)||!(0,aw.statSync)(t).isDirectory())throw new Me(t);let i=await new oO(t).read(),s=r.all?[...Lc.KNOWN_CHECK_IDS]:(0,Lc.readEnabledCheckIds)(i.assets),o=await new Lc.VaultCheckRunner((0,Lc.createDefaultCheckRegistry)()).runWithContext(i,s);if(e==="json")console.log(JSON.stringify({vaultPath:t,...o},null,2));else{s.length===0&&console.log(`OK ${t}: no validation checks enabled (scaffold validation-settings to enable some, or pass --all)`);for(let c of o.results){let l=`${c.status==="pass"?"OK":c.status==="fail"?"FAIL":"ERROR"} ${c.label}`;if(c.status==="pass")console.log(`${l} (${i.assets.length} assets)`);else if(c.status==="error")console.error(`${l}: ${c.errorMessage}`);else{console.error(`${l}: ${c.findings.length} violation(s)`);for(let u of c.findings.slice(0,50))console.error(` ${u.path?u.path+" \u2014 ":""}${u.message}`);c.findings.length>50&&console.error(` \u2026and ${c.findings.length-50} more`)}}console.error(o.ok?`
|
|
559
559
|
\u2705 ${t}: all ${s.length} enabled check(s) passed`:`
|
|
560
560
|
\u274C ${t}: validation failed`)}o.ok||(process.exitCode=1)}catch(t){se.handle(t)}})}a($6,"validateVaultCommand");function U6(){let r=new fe("validate").description("Validate vault files (schema linting, homoiconic vault-integrity checks)");return r.addCommand(M6()),r.addCommand($6()),r}a(U6,"validateCommand");ct();var W6=require("fs"),H6=require("path"),lw=J(We());Bi();Pt();mr();Sr();qt();Sr();xd();var B6=J(We());var ns=J(We());var kd=class{constructor(e,t){this.tripleStore=e;this.reader=t}static{a(this,"FsQueryBodyResolver")}async resolveSparql(e){if(!e)return null;let n=(await this.tripleStore.match(void 0,ns.Namespace.EXO.term("Asset_uid"),new ns.Literal(e)))[0]?.subject;if(!(n instanceof ns.IRI))return null;let i=(0,ns.iriToVaultPath)(n.value);if(!i)return null;let s;try{s=await this.reader.readFile(i)}catch{return null}return(0,ns.extractSparqlBlock)((0,ns.stripFrontmatter)(s))}};function cw(r,e){let t=new ci(e);return new B6.NamedQueryRunner(new kd(r,t),r)}a(cw,"buildNamedQueryRunner");var V6="b6aa1da9-96b9-4066-99a9-f81cc8b316aa",G6="5ba1031d-2c6e-4528-ab81-fb768d8e061a",q6="efb7bb79-6378-44b0-b1ca-9a27e3eeb684";function z6(){return new fe("classes").alias("describe-class").description("List RDF classes in vault, or describe a class (predicates + counts). Alias `describe-class` is provided per #3043 RFC \xA7B (schema introspection). Introspection SPARQL is read from vault query__NamedQuery assets (req 2678df55).").argument("[class-name]","Optional class name to show details (e.g., ems__Task)").option("--vault <path>","Path to Obsidian vault",process.cwd()).option("--format <type>","Output format: table|json","table").option("--output <type>","Response format: text|json (for MCP tools)","text").option("--use-cache","Use persistent cache (faster for repeated queries)").action(async(r,e)=>{let t=e.output||"text";se.setFormat(t);try{let n=Date.now(),i=(0,H6.resolve)(e.vault);if(!(0,W6.existsSync)(i))throw new Me(i);t==="text"&&console.log(`\u{1F4E6} Loading vault: ${i}...`);let s=e.useCache??!1,o,c=!1;if(s){let p=await new ts(i).loadOrBuild();o=p.triples,c=p.cacheHit,t==="text"&&c&&console.log("\u{1F680} Cache hit! Loading from persistent cache...")}else{let d=new $t(i);o=await new lw.NoteToRDFConverter(d).convertVault()}let l=new lw.InMemoryTripleStore;await l.addAll(o);let u=Date.now()-n;if(t==="text"){let d=c?" (from cache)":"";console.log(`\u2705 Loaded ${o.length} triples in ${u}ms${d}
|
|
@@ -666,7 +666,7 @@ Next steps:
|
|
|
666
666
|
`).map(n=>n.trim()).filter(n=>n.length>0),t=e[e.length-1];if(t!==void 0)try{return JSON.parse(t)}catch{return}}a(e0e,"parseLastJsonLine");function P7(r,e){return e.filter(t=>{let n=r[t];return typeof n!="string"||n.trim().length===0})}a(P7,"missingStringFields");var Bw=class{constructor(e){this.deps=e}static{a(this,"McpServer")}async handle(e){if(typeof e!="object"||e===null||Array.isArray(e))return{jsonrpc:"2.0",id:null,error:{code:O7,message:"Invalid request: expected a JSON-RPC object"}};let t=e.id,n=t===void 0;if(typeof e.method!="string")return n?null:{jsonrpc:"2.0",id:t??null,error:{code:O7,message:"Invalid request: missing method"}};if(n)return null;let i=t??null;switch(e.method){case"initialize":return{jsonrpc:"2.0",id:i,result:{protocolVersion:Jye,capabilities:{tools:{}},serverInfo:{name:"exocortex",version:this.deps.version}}};case"ping":return{jsonrpc:"2.0",id:i,result:{}};case"tools/list":return{jsonrpc:"2.0",id:i,result:{tools:x7}};case"tools/call":return{jsonrpc:"2.0",id:i,result:await this.callTool(e.params??{})};default:return{jsonrpc:"2.0",id:i,error:{code:Zye,message:`Method not found: ${e.method}`}}}}async callTool(e){let t=e.name,n=e.arguments??{},i;if(t==="create_asset"){let c=P7(n,["vault","class","label"]);if(c.length>0)return Xd(`create_asset: missing required argument(s): ${c.join(", ")}`,!0);let l=I7(n);if(l!==null)return Xd(`create_asset: ${l}`,!0);i=R7(n)}else if(t==="create_effort"){let c=P7(n,["vault","command","target"]);if(c.length>0)return Xd(`create_effort: missing required argument(s): ${c.join(", ")}`,!0);i=C7(n)}else return Xd(`Unknown tool: ${String(t)}`,!0);let s=await this.deps.runCli(i);if(s.exitCode!==0){let c=s.stderr.trim()||s.stdout.trim()||"(no diagnostic output)";return Xd(`exocortex-cli exited ${s.exitCode}
|
|
667
667
|
${c}`,!0)}let o=e0e(s.stdout);return Xd(o===void 0?s.stdout.trim():JSON.stringify(o))}};var L7=require("child_process");var t0e=32*1024*1024;function N7(r){return e=>new Promise(t=>{(0,L7.execFile)(process.execPath,[r,...e],{maxBuffer:t0e},(n,i,s)=>{let o=0;if(n){let c=n.code;o=typeof c=="number"?c:1}t({stdout:i,stderr:s,exitCode:o})})})}a(N7,"createSelfCliRunner");async function r0e(r,e,t){let n=(0,k7.createInterface)({input:e,crlfDelay:1/0});for await(let i of n){let s=i.trim();if(s.length===0)continue;let o;try{o=JSON.parse(s)}catch{t(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:F7,message:"Parse error: invalid JSON"}})+`
|
|
668
668
|
`);continue}let c;try{c=await r.handle(o)}catch(l){c={jsonrpc:"2.0",id:typeof o?.id=="string"||typeof o?.id=="number"?o.id:null,error:{code:D7,message:`Internal error: ${l instanceof Error?l.message:String(l)}`}}}c!==null&&t(JSON.stringify(c)+`
|
|
669
|
-
`)}}a(r0e,"runStdioServer");function M7(r){return new fe("mcp").description("Run an MCP (Model Context Protocol) stdio server exposing create_asset / create_effort tools backed by this CLI").option("--entry <path>","Path to the CLI entry script the tools invoke (defaults to this process's script)").action(async e=>{let t=e.entry??process.argv[1],n=new Bw({runCli:N7(t),version:r??"unknown"});await r0e(n,process.stdin,i=>process.stdout.write(i))})}a(M7,"mcpCommand");function Vw(r){let e=new fe;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more").version(r??"16.235.
|
|
669
|
+
`)}}a(r0e,"runStdioServer");function M7(r){return new fe("mcp").description("Run an MCP (Model Context Protocol) stdio server exposing create_asset / create_effort tools backed by this CLI").option("--entry <path>","Path to the CLI entry script the tools invoke (defaults to this process's script)").action(async e=>{let t=e.entry??process.argv[1],n=new Bw({runCli:N7(t),version:r??"unknown"});await r0e(n,process.stdin,i=>process.stdout.write(i))})}a(M7,"mcpCommand");function Vw(r){let e=new fe;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more").version(r??"16.235.5"),e.addCommand(SB()),e.addCommand(xB()),e.addCommand(h6()),e.addCommand(_6()),e.addCommand(U6()),e.addCommand(b6()),e.addCommand(A6()),e.addCommand(I6()),e.addCommand(z6()),e.addCommand(J6()),e.addCommand(uB()),e.addCommand(pB()),e.addCommand(hB()),e.addCommand(gB()),e.addCommand(yB()),e.addCommand(YB()),e.addCommand(JB()),e.addCommand(p7()),e.addCommand(m7()),e.addCommand(_7()),e.addCommand(b7()),e.addCommand(v7()),e.addCommand(i7()),e.addCommand(u7()),e.addCommand(T7()),e.addCommand(M7(r??"16.235.5")),e}a(Vw,"createProgram");Vw().parse();0&&(module.exports={createProgram});
|
|
670
670
|
/*! Bundled license information:
|
|
671
671
|
|
|
672
672
|
reflect-metadata/Reflect.js:
|
package/package.json
CHANGED