@kitelev/exocortex-cli 16.235.5 → 16.235.7
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.7
|
|
3
3
|
// CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
|
|
4
4
|
// License: MIT
|
|
5
5
|
|
|
@@ -69,7 +69,7 @@ ${n}}`}default:throw new lf(`Unsupported operation type for SPARQL generation: $
|
|
|
69
69
|
`)}generateTriple(e){let t=this.generateElement(e.subject),n=this.generatePredicate(e.predicate),i=this.generateElement(e.object);return`${t} ${n} ${i}`}generatePredicate(e){return"pathType"in e?this.generatePropertyPath(e):this.generateElement(e)}generatePropertyPath(e){let t=e.items.map(n=>"pathType"in n?`(${this.generatePropertyPath(n)})`:`<${n.value}>`);switch(e.pathType){case"/":return t.join("/");case"|":return t.join("|");case"^":return`^${t[0]}`;case"+":return`${t[0]}+`;case"*":return`${t[0]}*`;case"?":return`${t[0]}?`}}generateElement(e){switch(e.type){case"variable":return`?${e.value}`;case"iri":return`<${e.value}>`;case"literal":{let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}case"blank":return`_:${e.value}`;default:throw new lf(`Unknown element type: ${e.type}`)}}generateValues(e,t){let n=" ".repeat(t);if(e.variables.length===0||e.bindings.length===0)return"";if(e.variables.length===1){let o=e.variables[0],c=e.bindings.map(l=>{let u=l[o];return u?this.generateValuesTerm(u):"UNDEF"}).join(" ");return`${n}VALUES ?${o} { ${c} }`}let i=e.variables.map(o=>`?${o}`).join(" "),s=e.bindings.map(o=>`(${e.variables.map(l=>{let u=o[l];return u?this.generateValuesTerm(u):"UNDEF"}).join(" ")})`);return`${n}VALUES (${i}) {
|
|
70
70
|
${s.map(o=>`${n} ${o}`).join(`
|
|
71
71
|
`)}
|
|
72
|
-
${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new lf(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};uf.SPARQLGenerator=aT});var df=v(bi=>{"use strict";var IH=bi&&bi.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:a(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),RH=bi&&bi.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wD=bi&&bi.__importStar||(function(){var r=a(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&IH(t,e,n[i]);return RH(t,e),t}})();Object.defineProperty(bi,"__esModule",{value:!0});bi.QueryExecutor=bi.ExoQLQueryExecutor=bi.QueryExecutorError=void 0;var CH=x1(),xH=u0(),OH=K1(),PH=Q1(),FH=oD(),DH=cD(),LH=dD(),NH=iT(),kH=hD(),MH=gD(),jH=bD(),$H=SD(),UH=Le(),BH=Ye(),VH=n0(),yn="http://www.w3.org/2001/XMLSchema#",GH=new Set([`${yn}integer`,`${yn}decimal`,`${yn}float`,`${yn}double`,`${yn}nonPositiveInteger`,`${yn}negativeInteger`,`${yn}long`,`${yn}int`,`${yn}short`,`${yn}byte`,`${yn}nonNegativeInteger`,`${yn}unsignedLong`,`${yn}unsignedInt`,`${yn}unsignedShort`,`${yn}unsignedByte`,`${yn}positiveInteger`]),ff=class extends Error{static{a(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};bi.QueryExecutorError=ff;var _0=class{static{a(this,"ExoQLQueryExecutor")}constructor(e,t={}){let n=t.resolveClassHierarchy===!1?e:new jH.ClassHierarchyResolvingStore(e);this.tripleStore=n,this.bgpExecutor=new CH.BGPExecutor(n),this.filterExecutor=new xH.FilterExecutor,this.optionalExecutor=new OH.OptionalExecutor,this.unionExecutor=new PH.UnionExecutor,this.minusExecutor=new FH.MinusExecutor,this.valuesExecutor=new DH.ValuesExecutor,this.aggregateExecutor=new LH.AggregateExecutor,this.constructExecutor=new NH.ConstructExecutor,this.serviceExecutor=new kH.ServiceExecutor(t.serviceConfig),this.graphExecutor=new MH.GraphExecutor(n),this.sparqlGenerator=new $H.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(i,s)=>this.evaluateExistsPattern(i,s)),this.filterExecutor.setTripleStore(n)}async evaluateExistsPattern(e,t){let n=this.substituteVariables(e,t);for await(let i of this.execute(n))if(t.merge(i)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new ff(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let o of this.execute(e.left))t.push(o);if(t.length===0)return;let n=new Set;for(let o of t)for(let c of o.variables())n.add(c);let i=this.collectOperationVariables(e.right);if([...n].some(o=>i.has(o)))for(let o of t){let c=this.substituteVariables(e.right,o);for await(let l of this.execute(c)){let u=o.merge(l);u!==null&&(yield u)}}else{let o=[];for await(let c of this.execute(e.right))o.push(c);for(let c of t)for(let l of o){let u=c.merge(l);u!==null&&(yield u)}}}async*executeLeftJoin(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){let{SolutionMapping:t}=await Promise.resolve().then(()=>wD(Ko())),n=new Set(e.variables);for await(let i of this.execute(e.input)){let s=new t;for(let o of i.variables())if(n.has(o)){let c=i.get(o);c!==void 0&&s.set(o,c)}yield s}}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let o=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),l=0;if(o===void 0&&c===void 0?l=0:o===void 0?l=1:c===void 0?l=-1:typeof o=="number"&&typeof c=="number"?l=o-c:l=String(o).localeCompare(String(c)),s.descending&&(l=-l),l!==0)return l}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeReduced(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);if(e.having&&e.having.length>0)for(let i of n)e.having.every(o=>this.filterExecutor.evaluateExpression(o,i)===!0)&&(yield i);else for(let i of n)yield i}async*executeExtend(e){let t=e.expression.type!=="aggregate"&&this.filterExecutor.expressionContainsExists(e.expression);for await(let n of this.execute(e.input)){let i=n.clone(),s=t?await this.evaluateExtendExpressionAsync(e.expression,n):this.evaluateExtendExpression(e.expression,n);s!==void 0&&i.set(e.variable,s),yield i}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let o=n.merge(s);o!==null&&(yield o)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){if(!e||typeof e!="object")return e;let n=e;return e.type==="bgp"&&e.triples?(e.triples=e.triples.map(i=>this.substituteInTriple(i,t)),e):(n.input&&(n.input=this.substituteInOperation(n.input,t)),n.left&&(n.left=this.substituteInOperation(n.left,t)),n.right&&(n.right=this.substituteInOperation(n.right,t)),n.pattern&&(n.pattern=this.substituteInOperation(n.pattern,t)),n.query&&(n.query=this.substituteInOperation(n.query,t)),n.where&&(n.where=this.substituteInOperation(n.where,t)),n.expression&&this.substituteInExpression(n.expression,t),e)}substituteInExpression(e,t){if(!(!e||typeof e!="object")){if(e.type==="exists"&&e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.type==="variable"&&typeof e.name=="string"){let n=this.termToAlgebraNode(t.get(e.name));if(n!==null){delete e.name;for(let[i,s]of Object.entries(n))e[i]=s}}if(e.left&&this.substituteInExpression(e.left,t),e.right&&this.substituteInExpression(e.right,t),e.operands)for(let n of e.operands)this.substituteInExpression(n,t);if(e.args)for(let n of e.args)this.substituteInExpression(n,t);if(e.expression&&this.substituteInExpression(e.expression,t),e.list)for(let n of e.list)this.substituteInExpression(n,t)}}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=this.termToAlgebraNode(t.get(e.value));if(n!==null)return n}return e}termToAlgebraNode(e){if(e==null)return null;let t=e;return e instanceof UH.IRI||t.termType==="NamedNode"?{type:"iri",value:e.value}:t.termType==="Literal"||typeof t.value=="string"?{type:"literal",value:t.value,datatype:t.datatype?.value??t._datatype?.value,language:t.language??t._language}:null}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>wD(Ko()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}async evaluateExtendExpressionAsync(e,t){if(e.type!=="aggregate")try{return await this.filterExecutor.evaluateExpressionAsync(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);if(!n)return;if(n instanceof BH.Literal){let i=n.datatype?.value;if(i===`${yn}dayTimeDuration`)try{return VH.DateTimeFunctions.parseDayTimeDuration(n.value)}catch{return n.value}if(i&&GH.has(i)){let s=parseFloat(n.value);if(!Number.isNaN(s))return s}return n.value}return n.value??n.id??String(n)}if(e.type==="literal")return e.value}collectOperationVariables(e){let t=new Set;return this.collectVarsFromOperation(e,t),t}collectVarsFromOperation(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="bgp"&&n.triples)for(let i of n.triples)this.collectVarsFromElement(i.subject,t),i.predicate?.type!=="path"&&this.collectVarsFromElement(i.predicate,t),this.collectVarsFromElement(i.object,t);if(n.type==="values"&&n.variables)for(let i of n.variables)t.add(i);n.expression&&this.collectVarsFromExpressionTree(n.expression,t),n.type==="extend"&&n.variable&&t.add(n.variable),n.input&&this.collectVarsFromOperation(n.input,t),n.left&&this.collectVarsFromOperation(n.left,t),n.right&&this.collectVarsFromOperation(n.right,t),n.pattern&&this.collectVarsFromOperation(n.pattern,t),n.query&&this.collectVarsFromOperation(n.query,t),n.where&&this.collectVarsFromOperation(n.where,t)}collectVarsFromElement(e,t){if(!e||typeof e!="object")return;let n=e;n.type==="variable"&&t.add(n.value),n.type==="quoted"&&(this.collectVarsFromElement(n.subject,t),this.collectVarsFromElement(n.predicate,t),this.collectVarsFromElement(n.object,t))}collectVarsFromExpressionTree(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="variable"&&n.name&&t.add(n.name),n.type==="exists"&&n.pattern&&this.collectVarsFromOperation(n.pattern,t),n.left&&this.collectVarsFromExpressionTree(n.left,t),n.right&&this.collectVarsFromExpressionTree(n.right,t),n.operands)for(let i of n.operands)this.collectVarsFromExpressionTree(i,t);if(n.args)for(let i of n.args)this.collectVarsFromExpressionTree(i,t);if(n.expression&&this.collectVarsFromExpressionTree(n.expression,t),n.list)for(let i of n.list)this.collectVarsFromExpressionTree(i,t)}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new ff("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new ff("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};bi.ExoQLQueryExecutor=_0;bi.QueryExecutor=_0});var PD=v(Yo=>{"use strict";var qH=Yo&&Yo.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},WH=Yo&&Yo.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)};Object.defineProperty(Yo,"__esModule",{value:!0});Yo.CommandResolver=void 0;var HH=at(),zH=Dp(),KH=Cu(),fr=Le(),Xt=Ye(),B=Yt(),ED=qa(),vD=pp(),YH=Ou(),TD=Lp(),QH=/^[a-z][a-z0-9+.-]*:\/\//i,pf=yE(),AD=fF(),XH=Uu(),JH=Hu(),ZH=df(),wl=10,b0="exo__Asset",ez=wl+1,ID="08cec529-90eb-4d43-88de-ceecccea12b0",tz=B.Namespace.EXOCMD.term("SubstitutionToken").value,RD=new Set(["today","tomorrow","todayStart","targetFolder","target","randomUUIDv4","nowTimestamp","nowDate","nowYear","nowMonth","userInputLabel","userInput","targetProperty","targetRefProperty","labelAsArray","groundingTargetClass","targetClassSelf"]);function rz(r,e){return`__SUBSTITUTE__${r}__${e}__`}a(rz,"buildSubstitutionMarker");function nz(r,e,t){let n=(0,YH.utf8ToBase64)(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`__SUBSTITUTE_P__${r}__${e}__${n}__`}a(nz,"buildParameterisedMarker");var CD="3f28af98-c031-4718-8ba2-44ad0b012c52",iz=B.Namespace.EXOCMD.term("TokenInvocation").value,xD="29e2c8f8-2d27-4e58-b467-2e85d46f8122",OD="universal-default-template",cT=class{static{a(this,"CommandResolver")}clearUniversalCache(){this._universalCacheReady=!1,this._universalCacheValue=null}constructor(e,t=zH.NullLogger){this.tripleStore=e,this.logger=t,this.cache=new Map,this.multiCache=new Map,this._ancestorDepthCache=new Map,this._legacyPropertyDefaultsWarnedGroundings=new Set,this._fallbackWarnedKeys=new Set,this._universalCacheReady=!1,this._universalCacheValue=null}async resolveForAssetMulti(e,t,n){if(t.length===0)return[];let i=[...t].sort().join(","),s=`${e}::${i}::${n??""}`,o=this.multiCache.get(s);if(o)return o;let c=n?await this.expandPrototypeChain(n):void 0,l=await this.expandClassHierarchy(t),u=new Map;for(let[h,m]of l){let y=await this.resolveForAsset(e,h,c);for(let _ of y){let b=this.getBindingPriority(_.binding)===2?m:0,T=u.get(_.binding.id);(!T||b<T.depth)&&u.set(_.binding.id,{rc:_,depth:b})}}let f=new Set;for(let{rc:h}of u.values())if(h.binding.overrides)for(let m of h.binding.overrides)f.add(m);let d=Array.from(u.entries()).filter(([h])=>!f.has(h)).map(([,h])=>h);d.sort((h,m)=>{let y=this.getBindingPriority(h.rc.binding),_=this.getBindingPriority(m.rc.binding);return y!==_?y-_:h.depth!==m.depth?h.depth-m.depth:(h.rc.binding.order??100)-(m.rc.binding.order??100)});let p=d.map(h=>h.rc);return this.multiCache.set(s,p),p}async expandClassHierarchy(e){let t=new Map;for(let c of e){if(c===b0){t.set(c,new Set);continue}let l=[];try{l=await this.getClassAncestors(c)}catch{l=[]}t.set(c,new Set(l))}let n=a(c=>{for(let l of e)if(l!==c&&t.get(l)?.has(c)&&!t.get(c)?.has(l))return!0;return!1},"isAncestorOfSibling"),i=e.filter(c=>!n(c)),s=new Map,o=a((c,l)=>{let u=s.get(c);(u===void 0||l<u)&&s.set(c,l)},"setMin");for(let c of i){if(o(c,0),this.looksLikeUUID(c))try{let u=await this.resolveLabelByUID(c);u&&o(u,0)}catch{}if(c===b0)continue;let l=[];try{l=await this.getClassAncestorsWithDepth(c)}catch{l=[]}for(let{ref:u,depth:f}of l)o(u,f)}return s.has(b0)||s.set(b0,ez),s}async resolveForAsset(e,t,n){let i=typeof n=="string"?`s:${n}`:n?`c:${n.join("\0")}`:"",s=`${e}:${t}:${i}`,o=this.cache.get(s);if(o)return o;let c=typeof n=="string"?await this.expandPrototypeChain(n):n,l=await this.findBindings(t,c,e),u=[];for(let f of l){let d=await this.loadCommand(f.commandRef,{targetClass:f.targetClass});if(!d)continue;let p=f.precondition?{...d,precondition:f.precondition}:d;u.push({command:p,binding:f})}return u.sort((f,d)=>{let p=this.getBindingPriority(f.binding),h=this.getBindingPriority(d.binding);return p!==h?p-h:(f.binding.order??100)-(d.binding.order??100)}),this.cache.set(s,u),u}async loadCommand(e,t){let n=await this.findSubjectByUID(e);if(!n||(await this.tripleStore.match(n,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("Command"))).length===0)return null;let s=await this.getLiteralValue(n,B.Namespace.EXO.term("Asset_label"))??"Unknown Command",o=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_labelTemplate")),c=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_icon")),l=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_confirmMessage")),u=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_successMessage")),f=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_category")),d=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_openInSameTab")),p=d!==null&&String(d).trim().toLowerCase()==="true",h=await this.loadLinkedPrecondition(n),m=await this.loadLinkedGrounding(n,0,t);return m?{id:e,name:s,labelTemplate:o??void 0,icon:c??void 0,precondition:h??void 0,grounding:m,confirmMessage:l??void 0,successMessage:u??void 0,category:f??void 0,openInSameTab:p||void 0}:null}async findBindings(e,t,n){let i=typeof t=="string"?await this.expandPrototypeChain(t):t,s=await this.tripleStore.match(void 0,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("CommandBinding")),o=[];for(let c of s){let l=c.subject,u=await this.loadBindingDefinition(l);u&&this.bindingMatches(u,e,i,n)&&o.push(u)}return o}async findPaletteEnabledCommands(){let e=await this.tripleStore.match(void 0,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("Command")),t=[],n=new Set;for(let i of e){let s=i.subject;if((await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_paletteEnabled")))?.toLowerCase()!=="true")continue;let c=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_uid"));if(!c){this.logger.warn(`[CommandResolver] paletteEnabled command at ${s.value} has no exo__Asset_uid \u2014 skipped`);continue}let l=await this.loadCommand(c);if(!l){this.logger.warn(`[CommandResolver] paletteEnabled command ${c} could not be loaded (missing grounding?) \u2014 skipped`);continue}let u=await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_paletteId")),f=await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_cliName")),d=u??f??c;if(n.has(d)){this.logger.warn(`[CommandResolver] duplicate paletteId "${d}" \u2014 first registration wins, dropping ${c}`);continue}n.add(d),t.push({command:l,paletteId:d})}return t}invalidateCache(){this.cache.clear(),this.multiCache.clear(),this._ancestorDepthCache.clear(),this.clearUniversalCache()}async resolveLabel(e,t){if(!e.labelTemplate)return e.name;let n=e.labelTemplate,i=this.extractPlaceholders(e.labelTemplate);for(let{full:s,body:o}of i){let c=await this.evaluateSelectSnippet(o,t);n=n.replace(s,c)}return n}extractPlaceholders(e){let t=[],n=0;for(;n<e.length;)if(e[n]==="{"){let i=1,s=n+1;for(;s<e.length&&i>0;)e[s]==="{"?i++:e[s]==="}"&&i--,s++;if(i===0){let o=e.slice(n,s),c=e.slice(n+1,s-1);t.push({full:o,body:c})}n=s}else n++;return t}async evaluateSelectSnippet(e,t){try{let n=e.replace(/\$target/g,`<${t}>`),s=new XH.ExoQLParser().parse(n),c=new JH.ExoQLAlgebraTranslator().translate(s),u=await new ZH.ExoQLQueryExecutor(this.tripleStore).executeAll(c);if(u.length===0)return"";let f=u[0],d=f.variables();if(d.length===0)return"";let p=f.get(d[0]);return p?p instanceof Xt.Literal||p instanceof fr.IRI?p.value:String(p):""}catch{return""}}async loadBindingDefinition(e){let t=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!t)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",i=await this.getLinkedUID(e,B.Namespace.EXOCMD.term("CommandBinding_command"));if(!i)return null;let s=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetClass")),o=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetPrototype")),c=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetAsset"));if(!s&&!o&&!c)return null;let l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_position")),u=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_order")),f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_variant")),d=f!==null?this.coerceVariant(f,t):void 0,p=await this.loadLinkedPreconditionFromProperty(e,B.Namespace.EXOCMD.term("CommandBinding_precondition")),h=await this.loadLinkedStyle(e,t),m=await this.getLinkedUIDs(e,B.Namespace.EXOCMD.term("CommandBinding_overrides"));return{id:t,label:n,commandRef:i,targetClass:s??void 0,targetPrototype:o??void 0,targetAsset:c??void 0,position:l??void 0,order:u?parseInt(u,10):void 0,variant:d,precondition:p??void 0,style:h??void 0,overrides:m.length>0?m:void 0}}async loadLinkedStyle(e,t){let n=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("CommandBinding_style"),void 0);if(n.length>0){let s=n[0].object,o=null;if(s instanceof fr.IRI)o=s;else if(s instanceof Xt.Literal){let c=this.normalizeWikilink(s.value);o=await this.findSubjectByUID(c)}if(o){let c=await this.loadStyleAsset(o);if(c)return c}this.logger.warn(this.capWarning(`CommandBinding ${t}: style reference unresolved, falling back to inline variant`))}let i=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_variant"));if(i!==null){let s=this.coerceVariant(i,t);if(s!==void 0)return{id:`inline:${t}`,label:"",variant:s,inline:!0}}return null}async loadStyleAsset(e){let t=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!t)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",i=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_variant")),s=i!==null?this.coerceVariant(i,t):void 0,o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_showIcon")),c=this.coerceBoolean(o),l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_labelClass")),u=l!==null?this.coerceLabelClass(l,t):void 0,f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_ariaLabel")),d=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_tooltip")),p=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_keyboardShortcut")),h=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_source")),m=h!==null?this.coerceStyleSource(h,t):void 0;return{id:t,label:n,variant:s,showIcon:c,labelClass:u,ariaLabel:f??void 0,tooltip:d??void 0,keyboardShortcut:p??void 0,source:m,inline:!1}}coerceVariant(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.COMMAND_VARIANT_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle variant "${n}" not in whitelist [${pf.COMMAND_VARIANT_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceLabelClass(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.LABEL_CLASS_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle labelClass "${n}" not in whitelist [${pf.LABEL_CLASS_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceStyleSource(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.STYLE_SOURCE_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle source "${n}" not in whitelist [${pf.STYLE_SOURCE_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceBoolean(e){if(e===null)return;let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}capWarning(e){return e.length<=200?e:e.slice(0,197)+"..."}bindingMatches(e,t,n,i){if(e.targetAsset&&i&&this.matchesReference(e.targetAsset,i))return!0;if(e.targetPrototype&&n){for(let s of n)if(this.matchesReference(e.targetPrototype,s))return!0}return!!(e.targetClass&&t&&this.matchesReference(e.targetClass,t))}matchesReference(e,t){let n=this.normalizeWikilink(e),i=this.normalizeWikilink(t);if(n===i)return!0;let s=this.extractPathBasename(i);if(s&&s===n)return!0;let o=this.extractPathBasename(n);if(o&&o===i)return!0;let c=this.extractAlias(t);if(c&&n===c)return!0;let l=this.extractAlias(e);return!!(l&&l===i)}extractPathBasename(e){let t=e.match(/\/([^/]+)\.md$/);return t?t[1]:null}extractAlias(e){let t=e.replace(/["'[\]]/g,"").trim(),n=t.indexOf("|");return n>=0?t.substring(n+1).trim():null}getBindingPriority(e){return e.targetAsset?0:e.targetPrototype?1:2}async loadLinkedPrecondition(e){return this.loadLinkedPreconditionFromProperty(e,B.Namespace.EXOCMD.term("Command_precondition"))}async loadLinkedPreconditionFromProperty(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=await this.resolvePreconditionRef(n[0].object);return i?this.loadPreconditionSubject(i,new Set,0):null}async resolvePreconditionRef(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return await this.findSubjectByUID(t)}return null}async loadPreconditionSubject(e,t,n){let i=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid")),s=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"";if(i&&t.has(i))return this.brokenPreconditionNode(i,s);if(n>=wl)return this.brokenPreconditionNode(i??"",s);let o=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("AllPrecondition_preconditions"),void 0),c=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("AnyPrecondition_preconditions"),void 0),l=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("NotPrecondition_precondition"),void 0);if(o.length>0||c.length>0||l.length>0){let p=new Set(t);if(i&&p.add(i),o.length>0||c.length>0){let m=o.length>0?"all":"any",y=o.length>0?o:c,_=[];for(let b of y)_.push(await this.loadChildPrecondition(b.object,p,n+1));return{id:i??"",label:s,composite:{op:m,children:_}}}let h=await this.loadChildPrecondition(l[0].object,p,n+1);return{id:i??"",label:s,not:h}}let u=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Precondition_sparqlAsk")),f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Precondition_hostFunction")),d=await this.loadPreconditionQueryRef(e);return!i||!u&&!f&&!d?null:{id:i,label:s,...u&&{sparqlAsk:u},...f&&{hostFunction:f},...d&&{query:d}}}async loadChildPrecondition(e,t,n){let i=await this.resolvePreconditionRef(e);if(!i){let c=e instanceof Xt.Literal?this.normalizeWikilink(e.value):"";return this.brokenPreconditionNode(c,"")}let s=await this.loadPreconditionSubject(i,t,n);if(s)return s;let o=await this.getLiteralValue(i,B.Namespace.EXO.term("Asset_uid"));return this.brokenPreconditionNode(o??"","")}async loadPreconditionQueryRef(e){let t=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Precondition_query"),void 0);if(t.length===0)return;let n=t[0].object;if(n instanceof fr.IRI)return await this.getLiteralValue(n,B.Namespace.EXO.term("Asset_uid"))??void 0;if(n instanceof Xt.Literal)return this.normalizeWikilink(n.value)}brokenPreconditionNode(e,t){return{id:e,label:t,broken:!0}}async loadLinkedGrounding(e,t,n){if(t>=wl)return null;let i=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Command_grounding"),void 0);if(i.length===0)return null;if(i.length===1||!n?.targetClass){let o=await this.resolveGroundingRef(i[0].object);return o?this.loadGroundingDefinition(o,t):null}for(let o of i){let c=await this.resolveGroundingRef(o.object);if(!c)continue;let l=await this.getObsidianName(c,B.Namespace.EXOCMD.term("Grounding_targetPrototype"));if(l&&this.matchesReference(l,n.targetClass))return this.loadGroundingDefinition(c,t)}this.logger.warn(`Command ${e.value}: ${i.length} groundings declared, none matched context.targetClass='${n.targetClass}' via Grounding_targetPrototype \u2014 falling back to first grounding by iteration order (legacy behaviour). Check that one grounding's Grounding_targetPrototype references this targetClass.`);let s=await this.resolveGroundingRef(i[0].object);return s?this.loadGroundingDefinition(s,t):null}async resolveGroundingRef(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return await this.findSubjectByUID(t)}return null}async loadGroundingByUid(e){let t=await this.findSubjectByUID(e);return t?this.loadGroundingDefinition(t,0):null}async loadGroundingDefinition(e,t){if(t>=wl)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!n)return null;let i=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",s=await this.resolveGroundingTypeReference(e);if(!s)return null;let o=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetProperty"));if(o&&this.looksLikeUUID(o)){let k=await this.resolveLabelByUID(o);if(!k)return this.logger.warn(`Grounding ${n}: targetProperty wikilink UID '${o}' is not resolvable to exo__Asset_label \u2014 grounding skipped (would otherwise write a UUID-named frontmatter key).`),null;o=k}if(s===ED.GroundingType.SERVICE_CALL){let k=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_serviceId"));k&&(o=k)}let c=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueRef")),l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetValueLiteral")),u=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueSubstitution")),f=null;if(u&&this.looksLikeUUID(u)){let k=await this.resolveLabelByUID(u);if(!k)return this.logger.warn(`Grounding ${n}: targetValueSubstitution UID '${u}' is not resolvable to exo__Asset_label (SubstitutionToken instance missing or unlabelled) \u2014 grounding skipped.`),null;f=k}else u&&(f=u);let d=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueQuery")),p=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetQuery")),h=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_serviceCallPayload")),m=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_appendExpression")),y=await this.getObsidianWikilinkValue(e,B.Namespace.EXOCMD.term("Grounding_isDefinedBy")),_=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_sparqlUpdate")),b=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetClass"));if(b&&!this.looksLikeUUID(b)){let k=await this.findUidByLabel(b);k&&(b=k)}let T=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetPrototype")),I=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetFolder")),E=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_linkBackProperty")),S=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_inputSchema")),R=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_incrementBy")),D=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_shiftDelta")),P;if(R!=null&&R!==""){let k=Number.parseInt(String(R),10);Number.isFinite(k)&&(P=k)}let M=await this.resolvePropertyDefaults(e,n),O=await this.resolveInheritanceRules(e,n),L=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_propertyDefaults"));L!==null&&L!==""&&!this._legacyPropertyDefaultsWarnedGroundings.has(n)&&(this.logger.warn(`Grounding ${n}: deprecated exocmd__Grounding_propertyDefaults (plural) JSON predicate detected \u2014 the parser was removed in RFC v2 Phase 5 (#3167); value is ignored. Migrate to ref-form exocmd__Grounding_propertyDefault (singular) pointing to exocmd__PropertyDefault assets. See vault TBox c8f87363-d39c-45cb-9d4d-1be96d70f892 for the canonical replacement.`),this._legacyPropertyDefaultsWarnedGroundings.add(n));let te;s===ED.GroundingType.COMPOSITE&&(te=await this.loadCompositeSteps(e,t+1));let re;if(S)try{let k=JSON.parse(S);k?.properties&&(re=Object.entries(k.properties).map(([oe,de])=>{let Ae=de.type,we=Ae==="string"?"text":Ae,ve=de.defaultValue!==void 0?de.defaultValue:de.default,Te={name:oe,type:we,label:de.title??oe,required:Array.isArray(k.required)&&k.required.includes(oe)};return ve!=null&&(Te.defaultValue=String(ve)),typeof de.targetClassUid=="string"&&(Te.targetClassUid=de.targetClassUid),Te}))}catch{}let V=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_prefillLabelWithDate")),K=V!==null&&String(V).trim().toLowerCase()==="true",Se=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_labelTemplate")),ce=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_direction")),q;if(ce!=null){let k=String(ce).trim().toLowerCase();k==="forward"||k==="rollback"?q=k:k!==""&&this.logger.warn(`Grounding ${n}: exocmd__Grounding_direction value '${ce}' is not 'forward' or 'rollback' \u2014 treating as undefined (will default to 'forward' at dispatch).`)}let W=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_bodyTemplate")),ne=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_templateRef")),xe=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_cloneTargetBody")),X=xe!==null&&String(xe).trim().toLowerCase()==="true",ee=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetsCreatedInstance")),Z=ee!==null&&String(ee).trim().toLowerCase()==="true",H=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_omitLabel")),ie=H!==null&&String(H).trim().toLowerCase()==="true",$e={id:n,label:i,type:s,targetProperty:o??void 0,targetValueRef:c??void 0,targetValueLiteral:l??void 0,targetValueSubstitution:f??void 0,targetValueQuery:d??void 0,targetQuery:p??void 0,serviceCallPayload:h??void 0,appendExpression:m??void 0,sparqlUpdate:_??void 0,steps:te,targetClass:b??void 0,targetPrototype:T??void 0,targetFolder:I??void 0,linkBackProperty:E??void 0,incrementBy:P,shiftDelta:D??void 0,propertyDefault:M.length>0?M:void 0,inheritanceRule:O.length>0?O:void 0,isDefinedBy:y??void 0,prefillLabelWithDate:K||void 0,labelTemplate:Se??void 0,direction:q,bodyTemplate:W??void 0,templateRef:ne??void 0,cloneTargetBody:X||void 0,targetsCreatedInstance:Z||void 0,omitLabel:ie||void 0};return re&&($e.inputSchema=re),$e}async loadCompositeSteps(e,t){if(t>=wl)return[];let n=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Grounding_steps"),void 0),i=[];for(let s of n){let o=null;if(s.object instanceof fr.IRI)o=s.object;else if(s.object instanceof Xt.Literal){let l=this.normalizeWikilink(s.object.value);o=await this.findSubjectByUID(l)}if(!o)continue;let c=await this.loadGroundingDefinition(o,t);c&&i.push(c)}return i}async resolvePropertyDefaults(e,t){let n=await this.resolvePropertyDefaultsForSubject(e,t,B.Namespace.EXOCMD.term("Grounding_propertyDefault")),i=await this.getUniversalCache();return i&&i.propertyDefaults.length>0?(0,AD.mergePropertyDefaults)(i.propertyDefaults,n):n}async resolvePropertyDefaultsForSubject(e,t,n){let i=await this.tripleStore.match(e,n,void 0),s=[];for(let o of i){let c=await this.resolveRefTripleObject(o.object);if(!c)continue;let l=await this.getObsidianName(c,B.Namespace.EXOCMD.term("PropertyDefault_property"));if(!l){this.logger.warn(`Grounding ${t}: PropertyDefault asset missing exocmd__PropertyDefault_property \u2014 entry skipped.`);continue}let u=this.looksLikeUUID(l)?await this.resolveLabelByUID(l):l;if(!u){this.logger.warn(`Grounding ${t}: PropertyDefault property UID '${l}' is not resolvable to exo__Asset_label \u2014 entry skipped.`);continue}let f=await this.getObsidianName(c,B.Namespace.EXOCMD.term("PropertyDefault_value"));if(!f){this.logger.warn(`Grounding ${t}: PropertyDefault '${u}' missing exocmd__PropertyDefault_value \u2014 entry skipped.`);continue}let d=await this.resolvePropertyDefaultValue(f,t,u);d!==null&&s.push({propertyName:u,value:d})}return s}async getUniversalCache(){if(this._universalCacheReady)return this._universalCacheValue;this._universalCacheReady=!0;let e=await this.findUniversalSingleton();if(!e)return this.logger.debug("[CommandResolver] No exocmd__UniversalDefaultTemplate instance found in the store; universal property-defaults and inheritance-rules will not be applied. This verdict is cached until invalidateCache() is called \u2014 if the store was still warming up, the next invalidation re-resolves it."),this._universalCacheValue=null,null;let t=await this.resolvePropertyDefaultsForSubject(e,OD,B.Namespace.EXOCMD.term("Template_propertyDefault")),n=await this.resolveInheritanceRulesForSubject(e,OD,B.Namespace.EXOCMD.term("Template_inheritanceRule"));return this._universalCacheValue={propertyDefaults:t,inheritanceRules:n},this._universalCacheValue}async findUniversalSingleton(){let e=B.Namespace.EXOCMD.term("UniversalDefaultTemplate"),t=e.value,i=(await this.tripleStore.match(void 0,B.Namespace.EXO.term("Instance_class"),e)).map(c=>c.subject).filter(c=>c instanceof fr.IRI);if(i.length>0)return this.pickUniversalSingleton(i);let s=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Instance_class"),void 0),o=[];for(let c of s){let l=!1;if(c.object instanceof fr.IRI)l=c.object.value===t||c.object.value.includes(xD);else if(c.object instanceof Xt.Literal){let u=this.unwrapWikilink(c.object.value);l=u==="exocmd__UniversalDefaultTemplate"||u===xD}l&&c.subject instanceof fr.IRI&&o.push(c.subject)}return this.pickUniversalSingleton(o)}pickUniversalSingleton(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=[...e].sort((n,i)=>n.value.localeCompare(i.value));return this.logger.warn(`Multiple UniversalDefaultTemplate singletons found (${t.length}); selecting deterministically by lexicographic UID order: ${t[0].value}`),t[0]}async resolveInheritanceRules(e,t){let n=await this.resolveInheritanceRulesForSubject(e,t,B.Namespace.EXOCMD.term("Grounding_inheritanceRule")),i=await this.getUniversalCache();return i&&i.inheritanceRules.length>0?(0,AD.mergeInheritanceRules)(i.inheritanceRules,n):n}async resolveInheritanceRulesForSubject(e,t,n){let i=await this.tripleStore.match(e,n,void 0),s=[],o=t;for(let c of i){let l=await this.resolveRefTripleObject(c.object);if(!l)continue;let u=await this.resolveLabelRef(l,B.Namespace.EXOCMD.term("InheritanceRule_sourceProperty"));if(!u){this.logger.warn(`Grounding ${o}: InheritanceRule missing/unresolvable exocmd__InheritanceRule_sourceProperty \u2014 entry skipped.`);continue}let f=await this.resolveLabelRef(l,B.Namespace.EXOCMD.term("InheritanceRule_targetProperty"));if(!f){this.logger.warn(`Grounding ${o}: InheritanceRule missing/unresolvable exocmd__InheritanceRule_targetProperty \u2014 entry skipped.`);continue}let d=await this.tripleStore.match(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassCondition"),void 0),p,h;if(d.length>0){let E=await this.getObsidianName(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassCondition"));if(!E||!E.trim()){this.logger.warn(`Grounding ${o}: InheritanceRule has exocmd__InheritanceRule_targetClassCondition triple but ref is unresolvable \u2014 entire rule skipped (would otherwise apply unconditionally, broadening scope).`);continue}this.looksLikeUUID(E)?(h=E,p=await this.resolveLabelByUID(E)??void 0):p=E}let m=await this.tripleStore.match(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassExclusion"),void 0),y=[],_=[],b=!1;for(let E of m){let S=null;if(E.object instanceof fr.IRI?S=this.iriToObsidianName(E.object.value)??E.object.value:E.object instanceof Xt.Literal&&(S=this.unwrapWikilink(E.object.value)),!S){b=!0;continue}if(this.looksLikeUUID(S)){_.push(S);let R=await this.resolveLabelByUID(S);R&&y.push(R)}else y.push(S)}if(b){this.logger.warn(`Grounding ${o}: InheritanceRule has unresolvable exocmd__InheritanceRule_targetClassExclusion entry \u2014 entire rule skipped (would otherwise expand scope by silently dropping the excluded class).`);continue}let T=await this.getLiteralValue(l,B.Namespace.EXOCMD.term("InheritanceRule_priority")),I=50;if(T!==null&&T!==""){let E=Number.parseInt(String(T),10);Number.isFinite(E)&&(I=E)}s.push({sourcePropertyName:u,targetPropertyName:f,targetClassCondition:p,targetClassConditionUid:h,targetClassExclusion:y,targetClassExclusionUids:_,priority:I})}return s}async resolveRefTripleObject(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return t?this.findSubjectByUID(t):null}return null}async resolveLabelRef(e,t){let n=await this.getObsidianName(e,t);return n?this.looksLikeUUID(n)?this.resolveLabelByUID(n):n:null}async resolvePropertyDefaultValue(e,t,n){if(!this.looksLikeUUID(e))return`"[[${e}]]"`;let i=await this.findSubjectByUID(e);if(!i){let c=`${t}|${e}`;return this._fallbackWarnedKeys.has(c)||(this._fallbackWarnedKeys.add(c),this.logger.warn(this.capWarning(`Grounding ${t}: PropertyDefault '${n}' \u2192 value asset ${e} not in store; SKIPPING the property (the executor's own default applies). Previously this emitted a wikilink, i.e. a link written where a value belongs.`))),KH.STRING_SCALAR_PROPERTIES.has(n)?null:`"[[${e}]]"`}return await this.assetIsTokenInvocation(i)?this.resolveTokenInvocation(i,e,t,n):await this.assetIsSubstitutionToken(i)?this.dispatchSubstitutionToken(i,e,t,n,void 0):(this.logger.debug(`Grounding ${t}: PropertyDefault '${n}' value '${e}' is not a SubstitutionToken \u2014 emitting wikilink form.`),`"[[${e}]]"`)}async dispatchSubstitutionToken(e,t,n,i,s){let o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("SubstitutionToken_resolver"));if(!o||!o.trim())return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' references SubstitutionToken '${t}' with no exocmd__SubstitutionToken_resolver \u2014 falling back to wikilink form.`),`"[[${t}]]"`;let c=o.trim();return RD.has(c)?s!==void 0?nz(c,t,s):rz(c,t):(this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' SubstitutionToken '${t}' declares unknown resolver-id '${c}' \u2014 falling back to wikilink form. Known ids: ${Array.from(RD).join(", ")}.`),`"[[${t}]]"`)}async resolveTokenInvocation(e,t,n,i){let s=await this.getObsidianName(e,B.Namespace.EXOCMD.term("TokenInvocation_token"));if(!s)return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' missing exocmd__TokenInvocation_token \u2014 entry skipped.`),null;let o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("TokenInvocation_parameter"))??"";if(!this.looksLikeUUID(s))return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' references non-UUID token '${s}' \u2014 entry skipped.`),null;let c=await this.findSubjectByUID(s);return c?this.dispatchSubstitutionToken(c,s,n,i,o):(this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' token ref '${s}' not found in store \u2014 entry skipped.`),null)}async assetIsTokenInvocation(e){let t=await this.tripleStore.match(e,B.Namespace.EXO.term("Instance_class"),void 0);for(let i of t)if(i.object instanceof fr.IRI){if(i.object.value===iz||i.object.value.includes(CD))return!0}else if(i.object instanceof Xt.Literal){let s=this.unwrapWikilink(i.object.value);if(s==="exocmd__TokenInvocation"||s===CD)return!0}return(await this.tripleStore.match(e,B.Namespace.EXOCMD.term("TokenInvocation_token"),void 0)).length>0?(this.logger.debug(`Asset ${e.value} classified as TokenInvocation via its exocmd__TokenInvocation_token property; exo__Instance_class was absent or unresolved.`),!0):!1}async assetIsSubstitutionToken(e){let t=await this.tripleStore.match(e,B.Namespace.EXO.term("Instance_class"),void 0);for(let i of t)if(i.object instanceof fr.IRI){if(i.object.value===tz||i.object.value.includes(ID))return!0}else if(i.object instanceof Xt.Literal){let s=this.unwrapWikilink(i.object.value);if(s==="exocmd__SubstitutionToken"||s===ID)return!0}return(await this.tripleStore.match(e,B.Namespace.EXOCMD.term("SubstitutionToken_resolver"),void 0)).length>0?(this.logger.debug(`Asset ${e.value} classified as SubstitutionToken via its resolver property; exo__Instance_class was absent or unresolved.`),!0):!1}async resolveGroundingTypeReference(e){let t=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Grounding_type"),void 0);if(t.length===0)return null;let n=t[0].object;if(n instanceof fr.IRI)return(0,vD.resolveGroundingTypeFromIRI)(n.value);if(n instanceof Xt.Literal){let i=n.value,s=i.match(/^\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\|[^\]]*)?\]\]$/i);return s?(0,vD.resolveGroundingTypeFromIRI)(`obsidian://vault/${s[1].toLowerCase()}.md`):(this.logger.warn(`[exocmd-grounding-type-literal-form] legacy literal-string form '${i}' for exocmd__Grounding_type on <${e.value}>. Migrate to wikilink form per RFC 9d20c91f Phase 3.`),null)}return null}async expandPrototypeChain(e){if(!e||!this.normalizeWikilink(e))return[];let t=[e],n=new Set([this.normalizeWikilink(e).toLowerCase()]),i=e;for(let s=0;s<wl;s++){let o=this.extractUuidFromRef(i);if(!o)break;let c=null;try{let u=await this.findSubjectByUID(o);if(!u)break;c=await this.getLinkedValue(u,B.Namespace.EXO.term("Asset_prototype"))}catch(u){this.logger.debug(this.capWarning(`[expandPrototypeChain] store lookup failed at hop ${s} for '${i}': ${String(u)}`));break}if(!c)break;let l=this.normalizeWikilink(c).toLowerCase();if(n.has(l))break;n.add(l),t.push(c),i=c}return t}extractUuidFromRef(e){let t=this.normalizeWikilink(e);if(this.looksLikeUUID(t))return t;let n=this.extractPathBasename(t);return n&&this.looksLikeUUID(n)?n:null}async findSubjectByUID(e){if(this.tripleStore.findSubjectsByUUID){let n=await this.tripleStore.findSubjectsByUUID(e);if(n.length>0)return n[0]}let t=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Asset_uid"),void 0);for(let n of t)if(n.object instanceof Xt.Literal&&n.object.value===e)return n.subject;return null}async getLiteralValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal||i instanceof fr.IRI?i.value:null}looksLikeUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}async resolveLabelByUID(e){let t=await this.findSubjectByUID(e);if(!t)return null;let n=await this.getLiteralValue(t,B.Namespace.EXO.term("Asset_label"));return n===null?null:QH.test(n)?(0,TD.iriToObsidianName)(n)??n:n}async getClassAncestors(e){return(await this.getClassAncestorsWithDepth(e)).map(n=>n.ref)}async getClassAncestorsWithDepth(e){let t=this._ancestorDepthCache.get(e);if(t)return t;let n=new Map,i=new Set,s=await this.resolveClassFileIRI(e);if(!s)return[];let o=new Set([e]),c=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_uid"));c&&o.add(c);let l=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_label"));l&&o.add(l);let u=a((p,h)=>{if(o.has(p))return;let m=n.get(p);(m===void 0||h<m)&&n.set(p,h)},"setMin"),f=[{fileIRI:s,depth:0}];for(;f.length>0;){let p=f.shift();if(!p)break;let{fileIRI:h,depth:m}=p;if(m>=wl||i.has(h.value))continue;i.add(h.value);let y=await this.tripleStore.match(h,B.Namespace.EXO.term("Class_superClass"),void 0);for(let _ of y){let b=_.object;if(!(b instanceof fr.IRI))continue;let T=m+1,I=b.value.startsWith("obsidian://vault/"),E=this.iriToObsidianName(b.value);E&&u(E,T);let S=null;if(I?S=b:E&&(S=await this.resolveClassFileIRI(E)),!S)continue;let R=await this.getLiteralValue(S,B.Namespace.EXO.term("Asset_uid"));R&&u(R,T),i.has(S.value)||f.push({fileIRI:S,depth:T})}}let d=Array.from(n.entries()).map(([p,h])=>({ref:p,depth:h}));return this._ancestorDepthCache.set(e,d),d}async resolveClassFileIRI(e){if(this.looksLikeUUID(e))return this.findSubjectByUID(e);let t=await this.findUidByLabel(e);return t?this.findSubjectByUID(t):null}async findUidByLabel(e){let t=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Asset_label"),void 0);for(let n of t)if(n.object instanceof Xt.Literal&&n.object.value===e&&n.subject instanceof fr.IRI){let i=await this.tripleStore.match(n.subject,B.Namespace.EXO.term("Asset_uid"),void 0);if(i.length>0&&i[0].object instanceof Xt.Literal)return i[0].object.value}return null}async getLinkedUID(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;if(i instanceof fr.IRI){let s=await this.tripleStore.match(i,B.Namespace.EXO.term("Asset_uid"),void 0);return s.length>0&&s[0].object instanceof Xt.Literal?s[0].object.value:i.value.split("/").pop()?.replace(".md","")??null}return i instanceof Xt.Literal?this.normalizeWikilink(i.value):null}async getLinkedUIDs(e,t){let n=await this.tripleStore.match(e,t,void 0),i=[];for(let s of n){let o=s.object;if(o instanceof fr.IRI){let c=await this.tripleStore.match(o,B.Namespace.EXO.term("Asset_uid"),void 0);if(c.length>0&&c[0].object instanceof Xt.Literal)i.push(c[0].object.value);else{let l=o.value.split("/").pop()?.replace(".md","");l&&i.push(l)}}else if(o instanceof Xt.Literal){let c=this.normalizeWikilink(o.value);c&&i.push(c)}}return i}async getLinkedValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal?this.normalizeWikilink(i.value):i instanceof fr.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianName(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal?this.unwrapWikilink(i.value):i instanceof fr.IRI?this.iriToObsidianName(i.value)??i.value:null}unwrapWikilink(e){if(!e)return e;let t=e.trim().replace(/^"|"$/g,"");if(t.startsWith("http://")||t.startsWith("https://"))return this.iriToObsidianName(t)??t;let n=t.match(/^\[\[([^\]|]+)\|([^\]]+)\]\]$/);if(n)return n[2].trim();let i=t.match(/^\[\[([^\]|]+)\]\]$/);if(i){let s=i[1].trim();return s.startsWith("http://")||s.startsWith("https://")?this.iriToObsidianName(s)??s:s}return t}async getObsidianWikilinkValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;if(i instanceof Xt.Literal)return this.resolveWikilinkAlias(i.value);if(i instanceof fr.IRI){let s=this.iriToObsidianName(i.value);return s?`"[[${s}]]"`:i.value}return null}async resolveWikilinkAlias(e){let t=e.match(/\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]\]/);if(!t)return e;let n=t[1],i=await this.findSubjectByUID(n);if(!i)return e;let s=await this.getLiteralValue(i,B.Namespace.EXO.term("Asset_label"));return s?e.replace(`[[${n}]]`,`[[${n}|${s}]]`):e}iriToObsidianName(e){return(0,TD.iriToObsidianName)(e)}normalizeWikilink(e){let t=e.replace(/["'[\]]/g,"").trim(),n=t.indexOf("|");return n>=0?t.substring(0,n):t}};Yo.CommandResolver=cT;Yo.CommandResolver=cT=qH([(0,HH.injectable)(),WH("design:paramtypes",[Object,Object])],cT)});var uT=v(lT=>{"use strict";Object.defineProperty(lT,"__esModule",{value:!0});lT.validateExoQLAllowlist=sz;var S0=Vp();function sz(r){if(!r||typeof r!="object")return;let e=r;if(e.type==="update"){let t=r.updates??[];for(let n of t)if(n?.type==="load")throw new S0.ExoQLForbiddenKeywordError("LOAD");throw new S0.ExoQLForbiddenKeywordError("UPDATE")}if(e.type==="query"){if(e.from){let t=Array.isArray(e.from.default)&&e.from.default.length>0,n=Array.isArray(e.from.named)&&e.from.named.length>0;if(t||n)throw new S0.ExoQLForbiddenKeywordError("FROM")}if(Array.isArray(e.where))for(let t of e.where)w0(t);if(Array.isArray(e.template))for(let t of e.template)w0(t)}}a(sz,"validateExoQLAllowlist");function w0(r){if(!r||typeof r!="object")return;if(r.type==="service")throw new S0.ExoQLForbiddenKeywordError("SERVICE");if(Array.isArray(r.patterns))for(let t of r.patterns)w0(t);let e=r.where;if(Array.isArray(e))for(let t of e)w0(t)}a(w0,"walkPatternForBannedKeywords")});var fT=v(E0=>{"use strict";Object.defineProperty(E0,"__esModule",{value:!0});E0.DEFAULT_EVAL_CONFIG=void 0;E0.DEFAULT_EVAL_CONFIG=Object.freeze({enabled:!0,maxNestedEvalCount:100,maxAggregateEvalMillis:1e4})});var v0=v(dT=>{"use strict";Object.defineProperty(dT,"__esModule",{value:!0});dT.evaluateWithExoEval=dz;var oz=Uu(),az=Hu(),cz=df(),lz=uT(),uz=fT(),fz=Vp();async function dz(r,e={}){if(typeof r!="string")throw new TypeError("evaluateWithExoEval: sparql must be a string");let n=new oz.ExoQLParser().parse(r);if((0,lz.validateExoQLAllowlist)(n),!{...uz.DEFAULT_EVAL_CONFIG,...e.config??{}}.enabled)throw new fz.ExoQLEvalDisabledError;let s="queryType"in n&&typeof n.queryType=="string"?n.queryType:"SELECT";if(!e.store)return s==="ASK"?{kind:"ask",result:!1}:s==="CONSTRUCT"?{kind:"construct",triples:[]}:{kind:"select",rows:[]};let c=new az.ExoQLAlgebraTranslator().translate(n),l=new cz.ExoQLQueryExecutor(e.store);return l.isAskQuery(c)?{kind:"ask",result:await l.executeAsk(c)}:l.isConstructQuery(c)?{kind:"construct",triples:await l.executeConstruct(c)}:{kind:"select",rows:await l.executeAll(c)}}a(dz,"evaluateWithExoEval")});var ps=v(T0=>{"use strict";Object.defineProperty(T0,"__esModule",{value:!0});T0.DateFormatter=void 0;var pT=class r{static{a(this,"DateFormatter")}static toISOTimestamp(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toLocalTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0");return`${t}-${n}-${i}T${s}:${o}:${c}`}static toDateWikilink(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`"[[${t}-${n}-${i}]]"`}static getTodayWikilink(){return r.toDateWikilink(new Date)}static toDateString(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}static parseWikilink(e){let n=e.replace(/^["']|["']$/g,"").match(/\[\[(\d{4}-\d{2}-\d{2})\]\]/);return n?n[1]:null}static addDays(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static getTodayStartTimestamp(){let e=new Date;return e.setHours(0,0,0,0),r.toLocalTimestamp(e)}static toTimestampAtStartOfDay(e){let t=e.split("-").map(Number);if(t.length!==3||t.some(isNaN))throw new Error(`Invalid date format: ${e}. Expected YYYY-MM-DD`);let[n,i,s]=t,o=new Date(n,i-1,s,0,0,0,0);if(isNaN(o.getTime()))throw new Error(`Invalid date values: ${e}`);return r.toLocalTimestamp(o)}static normalizeTimestamp(e){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e))return e;let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp format: ${e}`);return r.toISOTimestamp(t)}static isISOTimestamp(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e)}};T0.DateFormatter=pT});var qp=v(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});A0.liveClock=pz;A0.frozenClock=hz;function pz(){return{now:a(()=>new Date,"now")}}a(pz,"liveClock");function hz(r){let e=new Date(r);return{now:a(()=>new Date(e.getTime()),"now")}}a(hz,"frozenClock")});var DD=v(Qo=>{"use strict";var mz=Qo&&Qo.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},gz=Qo&&Qo.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Hp;Object.defineProperty(Qo,"__esModule",{value:!0});Qo.PreconditionEvaluator=void 0;var yz=at(),_z=Uu(),bz=Hu(),FD=df(),Sz=v0(),Wp=ps(),wz=qp(),zp=Hp=class{static{a(this,"PreconditionEvaluator")}constructor(e,t,n){this.hostFunctions=new Map,this.askCache=new Map,this.tripleStore=e,this.queryBodyResolver=t,this.clock=n?.clock??(0,wz.liveClock)()}async evaluate(e,t,n){if(!e)return!0;let i=new Map;return await this.evaluateNode(e,t,n,i)==="yes"}async evaluateNode(e,t,n,i){if(e.broken)return"unknown";if(e.composite){let{op:s,children:o}=e.composite;if(o.length===0)return"unknown";let c=await Promise.all(o.map(l=>this.evaluateNode(l,t,n,i)));return s==="all"?c.includes("no")?"no":c.includes("unknown")?"unknown":"yes":c.includes("yes")?"yes":c.includes("unknown")?"unknown":"no"}if(e.not){let s=await this.evaluateNode(e.not,t,n,i);return s==="unknown"?"unknown":s==="yes"?"no":"yes"}return e.sparqlAsk?await this.evaluateSparqlAskMemoized(e.sparqlAsk,t,i)?"yes":"no":e.query?await this.evaluateQueryRef(e.query,t)?"yes":"no":e.hostFunction?this.evaluateHostFunction(e.hostFunction,t,n)?"yes":"no":"yes"}evaluateSparqlAskMemoized(e,t,n){let i=n.get(e);if(i!==void 0)return i;let s=this.evaluateSparqlAsk(e,t);return n.set(e,s),s}async evaluateQueryRef(e,t){if(!this.queryBodyResolver)return!1;try{let n=await this.queryBodyResolver.resolveSparql(e);if(!n)return!1;let i=this.substituteVariables(n,t),s=await(0,Sz.evaluateWithExoEval)(i,{store:this.tripleStore});return s.kind!=="ask"?!1:s.result}catch{return!1}}registerHostFunction(e,t){this.hostFunctions.set(e,t)}hasHostFunction(e){return this.hostFunctions.has(e)}evaluateHostFunctionSync(e,t,n){return this.hostFunctions.has(e)?this.evaluateHostFunction(e,t,n):null}invalidateCache(){this.askCache.clear()}compileAsk(e){let t=this.substituteVariables(e,Hp.SENTINEL_IRI),i=new _z.ExoQLParser().parse(t),o=new bz.ExoQLAlgebraTranslator().translate(i);return new FD.ExoQLQueryExecutor(this.tripleStore).isAskQuery(o)?o:null}evaluateHostFunction(e,t,n){let i=this.hostFunctions.get(e);if(!i)return!0;let s=n?{...n,targetIRI:t}:{targetIRI:t};try{return i(s)}catch{return!1}}async evaluateSparqlAsk(e,t){try{let n=Hp.TEMPORAL_TOKEN.test(e),i=n?Wp.DateFormatter.toDateString(this.clock.now()):null,s=this.askCache.get(e);if(s===void 0||n&&s.day!==i){let l=this.compileAsk(e);if(!l)return!1;s={day:i,compiled:l},this.askCache.set(e,s)}let o=JSON.parse(JSON.stringify(s.compiled).replaceAll(Hp.SENTINEL_IRI,t));return await new FD.ExoQLQueryExecutor(this.tripleStore).executeAsk(o)}catch{return!1}}substituteVariables(e,t){let n=this.clock.now(),i=n.toISOString(),s=n.getFullYear(),o=n.getMonth(),c=n.getDate(),l=n.getDay(),u=Wp.DateFormatter.toDateString(n),f=Wp.DateFormatter.toDateString(new Date(s,o,c-1)),d=(l+6)%7,p=Wp.DateFormatter.toDateString(new Date(s,o,c-d)),h=Wp.DateFormatter.toDateString(new Date(s,o,c-d-7)),m=`${s}-${String(o+1).padStart(2,"0")}-01`,y=o===0?11:o-1,b=`${o===0?s-1:s}-${String(y+1).padStart(2,"0")}-01`,T=`${s}-01-01`;return e.replace(/\$target\b/g,`<${t}>`).replace(/\$now\b/g,`"${i}"^^xsd:dateTime`).replace(/\$yesterday\b/g,`"${f}"^^xsd:date`).replace(/\$thisWeekStart\b/g,`"${p}"^^xsd:date`).replace(/\$lastWeekStart\b/g,`"${h}"^^xsd:date`).replace(/\$thisMonthStart\b/g,`"${m}"^^xsd:date`).replace(/\$lastMonthStart\b/g,`"${b}"^^xsd:date`).replace(/\$thisYearStart\b/g,`"${T}"^^xsd:date`).replace(/\$today\b/g,`"${u}"^^xsd:date`)}};Qo.PreconditionEvaluator=zp;zp.SENTINEL_IRI="urn:exocortex:cache-sentinel:target";zp.TEMPORAL_TOKEN=/\$(?:now|today|yesterday|thisWeekStart|lastWeekStart|thisMonthStart|lastMonthStart|thisYearStart)\b/;Qo.PreconditionEvaluator=zp=Hp=mz([(0,yz.injectable)(),gz("design:paramtypes",[Object,Object,Object])],zp)});var LD=v(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.hasUidFilename=Xo.hasNonUidFilename=void 0;Xo.registerDefaultHostFunctions=Tz;var Ez=a(r=>{let e=r.assetUid;if(typeof e!="string"||e.trim()==="")return!1;let t=r.fileBasename;return typeof t!="string"?!1:t!==e},"hasNonUidFilename");Xo.hasNonUidFilename=Ez;var vz=a(r=>{let e=r.assetUid;if(typeof e!="string"||e.trim()==="")return!1;let t=r.fileBasename;return typeof t!="string"?!1:t===e},"hasUidFilename");Xo.hasUidFilename=vz;function Tz(r){r.registerHostFunction("hasNonUidFilename",Xo.hasNonUidFilename),r.registerHostFunction("hasUidFilename",Xo.hasUidFilename)}a(Tz,"registerDefaultHostFunctions")});var R0=v(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.liveUidGenerator=Az;I0.seededUidGenerator=Rz;var hT=il();function Az(){return{next:a(()=>(0,hT.v4)(),"next")}}a(Az,"liveUidGenerator");var Iz="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Rz(r){let e=0,t=(0,hT.v5)(r,Iz);return{next:a(()=>{let n=`${r}#${e}`;return e+=1,(0,hT.v5)(n,t)},"next")}}a(Rz,"seededUidGenerator")});var O0=v(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.registerResolver=yr;tc.getResolver=xz;tc.isResolverModifierAware=Oz;tc.getRegisteredResolverIds=Pz;tc.clearResolvers=Fz;tc.installDefaultResolvers=Vz;var Cz=ps(),x0=new Map,mT=new Set;function yr(r,e,t=!1){x0.set(r,e),t&&mT.add(r)}a(yr,"registerResolver");function xz(r){return x0.get(r)}a(xz,"getResolver");function Oz(r){return mT.has(r)}a(Oz,"isResolverModifierAware");function Pz(){return Array.from(x0.keys())}a(Pz,"getRegisteredResolverIds");function Fz(){x0.clear(),mT.clear()}a(Fz,"clearResolvers");function _n(r){return r<10?`0${r}`:String(r)}a(_n,"pad2");var Dz=["January","February","March","April","May","June","July","August","September","October","November","December"],Lz=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Nz=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],kz=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Mz(r){let e=["th","st","nd","rd"],t=r%100;return`${r}${e[(t-20)%10]||e[t]||e[0]}`}a(Mz,"ordinalDay");var jz=/YYYY|YY|MMMM|MMM|MM|M|Do|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|A|a/g;function $z(r,e){let t=(r.getHours()+11)%12+1;return e.replace(jz,n=>{switch(n){case"YYYY":return String(r.getFullYear());case"YY":return _n(r.getFullYear()%100);case"MMMM":return Dz[r.getMonth()];case"MMM":return Lz[r.getMonth()];case"MM":return _n(r.getMonth()+1);case"M":return String(r.getMonth()+1);case"Do":return Mz(r.getDate());case"DD":return _n(r.getDate());case"D":return String(r.getDate());case"dddd":return Nz[r.getDay()];case"ddd":return kz[r.getDay()];case"HH":return _n(r.getHours());case"H":return String(r.getHours());case"hh":return _n(t);case"h":return String(t);case"mm":return _n(r.getMinutes());case"m":return String(r.getMinutes());case"ss":return _n(r.getSeconds());case"s":return String(r.getSeconds());case"A":return r.getHours()<12?"AM":"PM";case"a":return r.getHours()<12?"am":"pm";default:return n}})}a($z,"formatDate");function ND(r,e,t){let n=r.getDate(),i=new Date(r.getTime());i.setDate(1),t==="M"?i.setMonth(i.getMonth()+e):i.setFullYear(i.getFullYear()+e);let s=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(n,s)),i}a(ND,"addMonthsClamped");function Uz(r,e){if(!e)return r;let t=e.match(/^([+-])(\d+)([dwMy])?$/);if(!t)return r;let n=(t[1]==="-"?-1:1)*parseInt(t[2],10),i=t[3]??"d",s=new Date(r.getTime());switch(i){case"d":s.setDate(s.getDate()+n);break;case"w":s.setDate(s.getDate()+n*7);break;case"M":s=ND(s,n,"M");break;case"y":s=ND(s,n,"y");break}return isNaN(s.getTime())?r:s}a(Uz,"applyDateOffset");function Bz(r){if(!r)return{offset:null,format:null};let e=r.indexOf(":");if(e<0)return{offset:r,format:null};let t=r.slice(0,e),n=r.slice(e+1);return{offset:t||null,format:n||null}}a(Bz,"parseDateModifier");function C0(r,e){return(t,n)=>{let{offset:i,format:s}=Bz(n),o=new Date;return r!==0&&o.setDate(o.getDate()+r),o=Uz(o,i),$z(o,s??e)}}a(C0,"makeDateResolver");function Vz(){yr("today",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}`}),yr("todayStart",()=>Cz.DateFormatter.getTodayStartTimestamp()),yr("date",C0(0,"YYYY-MM-DD"),!0),yr("now",C0(0,"YYYY-MM-DDTHH:mm:ss"),!0),yr("tomorrow",C0(1,"YYYY-MM-DD"),!0),yr("yesterday",C0(-1,"YYYY-MM-DD"),!0),yr("target",r=>r.targetIRI?`"[[${r.targetIRI}]]"`:""),yr("targetFolder",r=>{if(!r.targetFilePath)return"";let e=r.targetFilePath.replace(/^\/+/,""),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}),yr("randomUUIDv4",()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();throw new Error("randomUUIDv4 resolver requires crypto.randomUUID() \u2014 runtime is missing Node crypto / Web Crypto API.")}),yr("nowTimestamp",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}T${_n(r.getHours())}:${_n(r.getMinutes())}:${_n(r.getSeconds())}`}),yr("nowDate",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}`}),yr("nowYear",()=>String(new Date().getFullYear())),yr("nowMonth",()=>_n(new Date().getMonth()+1)),yr("userInputLabel",r=>{let e=r.userInput?.label;return typeof e=="string"?e:""}),yr("userInput",(r,e)=>{if(!e)return null;let t=r.userInput?.[e];return typeof t=="string"?t:t==null?null:String(t)}),yr("targetProperty",(r,e)=>{if(!e||!r.targetFm)return null;let t=r.targetFm[e];return t==null?null:Array.isArray(t)?t.map(String):String(t)}),yr("targetRefProperty",(r,e)=>{if(!e)return null;let t=e.indexOf("|");if(t<0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!n||!i)return null;let s=r.targetRefFm?.[n];if(!s)return null;let o=s[i];return o==null?null:Array.isArray(o)?o.length>0?String(o[0]):null:String(o)}),yr("labelAsArray",r=>{let e=r.userInput?.label;return typeof e=="string"&&e.length>0?[e]:[]}),yr("groundingTargetClass",r=>r.groundingTargetClassUid?`"[[${r.groundingTargetClassUid}]]"`:null),yr("targetClassSelf",r=>{if(!r.targetFilePath)return null;let e=r.targetFilePath.replace(/^\/+/,""),n=e.slice(e.lastIndexOf("/")+1).replace(/\.md$/i,"");return n.length>0?`"[[${n}]]"`:null})}a(Vz,"installDefaultResolvers")});var yT=v(P0=>{"use strict";Object.defineProperty(P0,"__esModule",{value:!0});P0.resolveTemplateBody=qz;P0.stripTemplateFrontmatter=Wz;var gT=O0();(0,gT.installDefaultResolvers)();var Gz=/\$([A-Za-z][A-Za-z0-9_]*)((?:[+-]\d+[dwMy])?(?::[A-Za-z0-9:./-]+)?)/g;function qz(r,e={}){return r.replace(Gz,(t,n,i)=>{let s=(0,gT.getResolver)(n);if(s===void 0)return t;let o=s(e,i.length>0?i:void 0);return typeof o!="string"||o.length===0?t:(0,gT.isResolverModifierAware)(n)?o:o+i})}a(qz,"resolveTemplateBody");function Wz(r){let e=r.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return e?r.slice(e[0].length):r}a(Wz,"stripTemplateFrontmatter")});var L0=v(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});hf.registerOrderSpecLoader=Hz;hf.clearOrderSpecLoader=zz;hf.loadDefaultSpec=Kz;hf.orderProperties=Yz;var F0=null,rc,D0=!1;function Hz(r){F0=r,rc=void 0,D0=!1}a(Hz,"registerOrderSpecLoader");function zz(){F0=null,rc=void 0,D0=!1}a(zz,"clearOrderSpecLoader");function Kz(){if(rc!==void 0)return rc;if(!F0)return rc=null,null;try{rc=F0()}catch(r){D0||(console.warn("[OrderSpecResolver] loader threw, falling back to insertion order:",r),D0=!0),rc=null}return rc}a(Kz,"loadDefaultSpec");function Yz(r,e){if(!e||e.head.length===0&&e.tail.length===0)return r;let t=Object.keys(r),n=new Set(e.head),i=new Set(e.tail),s=e.head.filter(u=>Object.prototype.hasOwnProperty.call(r,u)),o=e.tail.filter(u=>Object.prototype.hasOwnProperty.call(r,u)),c=t.filter(u=>!n.has(u)&&!i.has(u));e.middleStrategy==="alphabetical"&&c.sort((u,f)=>u.localeCompare(f));let l={};for(let u of s)l[u]=r[u];for(let u of c)l[u]=r[u];for(let u of o)l[u]=r[u];return l}a(Yz,"orderProperties")});var Qn=v(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});N0.DI_TOKENS=void 0;N0.DI_TOKENS={IFileSystemAdapter:Symbol.for("IFileSystemAdapter"),IVaultAdapter:Symbol.for("IVaultAdapter"),IVaultContext:Symbol.for("IVaultContext"),IMultiVaultManager:Symbol.for("IMultiVaultManager"),ILogger:Symbol.for("ILogger"),IEventBus:Symbol.for("IEventBus"),IConfiguration:Symbol.for("IConfiguration"),INotificationService:Symbol.for("INotificationService"),ClassCreationService:Symbol.for("ClassCreationService"),ConceptCreationService:Symbol.for("ConceptCreationService"),GenericAssetCreationService:Symbol.for("GenericAssetCreationService"),TaskStatusService:Symbol.for("TaskStatusService"),EffortStatusWorkflow:Symbol.for("EffortStatusWorkflow"),StatusTimestampService:Symbol.for("StatusTimestampService"),PropertyCleanupService:Symbol.for("PropertyCleanupService"),FolderRepairService:Symbol.for("FolderRepairService"),RenameToUidService:Symbol.for("RenameToUidService"),NoteToRDFConverter:Symbol.for("NoteToRDFConverter"),IVaultSettings:Symbol.for("IVaultSettings"),AreaHierarchyBuilder:Symbol.for("AreaHierarchyBuilder"),ClassHierarchyResolver:Symbol.for("ClassHierarchyResolver")}});var bT=v(k0=>{"use strict";Object.defineProperty(k0,"__esModule",{value:!0});k0.RDFVocabularyMapper=void 0;var Rr=hi(),kD=Le(),_e=Yt(),_T=class{static{a(this,"RDFVocabularyMapper")}constructor(){this.propertyMappings=new Map([["exo__Instance_class",_e.Namespace.RDF.term("type")],["exo__Asset_isDefinedBy",_e.Namespace.RDFS.term("isDefinedBy")],["exo__Class_superClass",_e.Namespace.RDFS.term("subClassOf")],["exo__Property_range",_e.Namespace.RDFS.term("range")],["exo__Property_domain",_e.Namespace.RDFS.term("domain")],["exo__Property_superProperty",_e.Namespace.RDFS.term("subPropertyOf")]])}generateClassHierarchyTriples(){let e=[];return e.push(new Rr.Triple(_e.Namespace.EXO.term("Asset"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDFS.term("Resource"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Class"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDFS.term("Class"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDF.term("Property"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Task"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Project"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Area"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Workflow"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("WorkflowState"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("WorkflowTransition"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Command"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Precondition"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Grounding"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("CommandBinding"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e}generatePropertyHierarchyTriples(){let e=[];return e.push(new Rr.Triple(_e.Namespace.EXO.term("Instance_class"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDF.term("type"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Asset_isDefinedBy"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("isDefinedBy"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Class_superClass"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("subClassOf"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_range"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("range"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_domain"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("domain"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_superProperty"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("subPropertyOf"))),e}generateMappedTriple(e,t,n){let i=this.propertyMappings.get(t);if(!i)return null;let s;if(n instanceof kD.IRI)s=n;else{let o=n.match(/^(ems|exo|exocmd)__(.+)$/);if(o){let[,c,l]=o;s=(c==="ems"?_e.Namespace.EMS:c==="exocmd"?_e.Namespace.EXOCMD:_e.Namespace.EXO).term(l)}else s=new kD.IRI(n)}return new Rr.Triple(e,i,s)}hasMappingFor(e){return this.propertyMappings.has(e)}};k0.RDFVocabularyMapper=_T});var M0=v(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.OBSIDIAN_VAULT_SCHEME=void 0;Jo.vaultPathToIRI=Qz;Jo.iriToVaultPath=Xz;Jo.OBSIDIAN_VAULT_SCHEME="obsidian://vault/";function Qz(r){let e=r.startsWith("./")?r.slice(2):r;return`${Jo.OBSIDIAN_VAULT_SCHEME}${encodeURI(e)}`}a(Qz,"vaultPathToIRI");function Xz(r){if(!r.startsWith(Jo.OBSIDIAN_VAULT_SCHEME))return null;let e=r.slice(Jo.OBSIDIAN_VAULT_SCHEME.length);try{return decodeURI(e)}catch{return null}}a(Xz,"iriToVaultPath")});var $0=v(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.derivePath=MD;Kp.deriveUrl=Jz;Kp.deriveLegacyFlatPath=Zz;var ST="assetspaces",j0=/^[A-Za-z0-9._-]+$/;function MD(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0||/^file:\/\//i.test(e))return null;e=e.replace(/\/+$/,""),e=e.replace(/\.git$/i,"");let t=null;if(!e.includes("://")){let o=/^[^/@\s]+@[^/:\s]+:(.+)$/.exec(e);o&&(t=o[1])}if(t===null){let o=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");o=o.replace(/^[^/@]+@/,"");let c=o.indexOf("/");if(c<0)return null;t=o.slice(c+1)}let n=t.split("/").filter(o=>o.length>0);if(n.length<2)return null;let i=n[0],s=n[1];return i==="."||i===".."||s==="."||s===".."||!j0.test(i)||!j0.test(s)?null:`${ST}/${i}/${s}`}a(MD,"derivePath");function Jz(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0)return null;e=e.replace(/^\/+/,"").replace(/\/+$/,"");let t=`${ST}/`;if(!e.startsWith(t))return null;let n=e.slice(t.length).split("/").filter(o=>o.length>0);if(n.length<2)return null;let i=n[0],s=n[1];return i==="."||i===".."||s==="."||s===".."||!j0.test(i)||!j0.test(s)?null:`https://github.com/${i}/${s}`}a(Jz,"deriveUrl");function Zz(r){let e=MD(r);if(e===null)return null;let t=e.split("/")[2];if(t===void 0||t.length===0)return null;let n=t.startsWith("exoas-")?t.slice(6):t;return n.length===0?null:`${ST}/${n}`}a(Zz,"deriveLegacyFlatPath")});var U0=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.FILE_SPACE_CLASS_UID=void 0;hs.frontmatterDeclaresFileSpace=tK;hs.discoverFileSpaceExclusions=nK;var eK=$0();hs.FILE_SPACE_CLASS_UID="aad8913e-5e9f-4047-879d-93cc46befd52";var jD=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,wT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function UD(r){let e=Array.isArray(r)?r:[r],t=[];for(let n of e){if(typeof n!="string")continue;jD.lastIndex=0;let i;for(;(i=jD.exec(n))!==null;)t.push(i[1].trim())}return t}a(UD,"wikilinkTargets");function tK(r){return r?UD(r.exo__Instance_class).some(e=>wT.test(e)&&e.toLowerCase()===hs.FILE_SPACE_CLASS_UID):!1}a(tK,"frontmatterDeclaresFileSpace");function $D(r,e){try{return r.getFrontmatter(e)}catch{return null}}a($D,"readFrontmatterSafe");function rK(r){let e=r.exo__AssetSpace_source;if(typeof e=="string"&&e.length>0)return e;let t=r.exo__AssetSpace_git;return typeof t=="string"&&t.length>0?t:null}a(rK,"readSource");function nK(r){let e=[],t=[],n=[],i=new Map,s=a((c,l)=>{if(wT.test(c))return c.toLowerCase()===hs.FILE_SPACE_CLASS_UID;let u=r.getFirstLinkpathDest(c,l);if(u==null)return!1;let f=i.get(u.path);if(f!==void 0)return f;let p=$D(r,u)?.exo__Asset_uid,h=typeof p=="string"&&p.toLowerCase()===hs.FILE_SPACE_CLASS_UID;return i.set(u.path,h),h},"isFileSpaceClassRef"),o=a(c=>c.some(l=>wT.test(l)&&l.toLowerCase()===hs.FILE_SPACE_CLASS_UID),"hasUuidFormRef");for(let c of r.getAllFiles()){let l=$D(r,c);if(!l)continue;let u=UD(l.exo__Instance_class);if(!u.some(h=>s(h,c.path)))continue;t.push(c.path),o(u)||n.push(`FileSpace declaration ${c.path} references the class via a label-form link only \u2014 the sync layer will not pick it up; use the UUID-form wikilink [[${hs.FILE_SPACE_CLASS_UID}]] (UID-canon)`);let f=rK(l);if(f===null){n.push(`FileSpace declaration ${c.path} has no exo__AssetSpace_source/_git \u2014 mount path underivable, content NOT excluded from the index`);continue}let d=(0,eK.derivePath)(f);if(d===null){n.push(`FileSpace declaration ${c.path}: cannot derive mount path from source "${f}" \u2014 content NOT excluded from the index`);continue}let p=`${d}/`;c.path.startsWith(p)&&n.push(`FileSpace declaration ${c.path} lies INSIDE its own mount ${p} \u2014 it will be excluded from the index together with the content; move the declaration outside the mount folder`),e.push(p)}return{prefixes:e,declarationPaths:t,warnings:n}}a(nK,"discoverFileSpaceExclusions")});var vl=v(Br=>{"use strict";var iK=Br&&Br.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},sK=Br&&Br.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},BD=Br&&Br.__param||function(r,e){return function(t,n){e(t,n,r)}},TT;Object.defineProperty(Br,"__esModule",{value:!0});Br.NoteToRDFConverter=Br.UNPREFIXED_ASSET_FIELDS=void 0;Br.canonicalYamlKey=uK;Br.normaliseExcludedFolders=qD;Br.isPathExcluded=WD;var ET=at(),Cr=hi(),ms=Le(),Cn=Ye(),VD=rr(),dr=Yt(),GD=Qn(),oK=bT(),aK=Dp(),vT=M0(),Si=tv(),cK=U0();Br.UNPREFIXED_ASSET_FIELDS=new Set(["archived","draft","pinned","aliases"]);var lK=/^exo__Asset_(.+)$/;function uK(r){let e=lK.exec(r);return e&&Br.UNPREFIXED_ASSET_FIELDS.has(e[1])?e[1]:r}a(uK,"canonicalYamlKey");function qD(r){return Array.isArray(r)?r.map(e=>String(e).replace(/\\/g,"/").trim()).filter(e=>e.length>0).map(e=>e.endsWith("/")?e:`${e}/`):[]}a(qD,"normaliseExcludedFolders");function WD(r,e){if(e.length===0)return!1;let t=r.replace(/\\/g,"/");for(let n of e)if(t.startsWith(n))return!0;return!1}a(WD,"isPathExcluded");function fK(r){if(!r)return"";let e=r.replace(/\\/g,"/");for(;e.startsWith("/");)e=e.slice(1);for(;e.endsWith("/");)e=e.slice(0,-1);return e.length>0?`${e}/`:""}a(fK,"normaliseSubjectIriPrefix");var El=TT=class{static{a(this,"NoteToRDFConverter")}constructor(e,t=aK.NullLogger,n={}){this.vault=e,this.logger=t,this.BODY_WIKILINK_PATTERN=/(?<!!)\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,this.pendingExtraTriples=[],this.vocabularyMapper=new oK.RDFVocabularyMapper,this.subjectIriPrefix=fK(n.subjectIriPrefix),this.emitInstanceClassAsUid=n.emitInstanceClassAsUid??!1}async convertNote(e){let t=this.vault.getFrontmatterWithFallback?await this.vault.getFrontmatterWithFallback(e):this.vault.getFrontmatter(e);return this.convertNoteFromFrontmatter(e,t)}async convertNoteFromFrontmatter(e,t){if(!t)return[];let n=this.notePathToIRI(e.path),i=dr.Namespace.EXO.term("Asset_filename"),s=new Cr.Triple(n,i,new Cn.Literal(e.basename));if(Si.Exo003Parser.isExo003Format(t)){let o=await this.convertExo003Note(e,t);return[s,...o]}return this.convertLegacyNote(e,t,s)}async convertLegacyNote(e,t,n){this.pendingExtraTriples=[];let i=[n],s=this.notePathToIRI(e.path),o,c,l,u=!1,f=dr.Namespace.EXO.term("Statement").value;for(let[y,_]of Object.entries(t)){let b=Br.UNPREFIXED_ASSET_FIELDS.has(y)?`exo__Asset_${y}`:y;if(!this.isExocortexProperty(b))continue;let T=this.propertyKeyToIRI(b),I=Array.isArray(_)?_:[_];for(let E of I)if(!((y==="exo__Asset_label"||Br.UNPREFIXED_ASSET_FIELDS.has(y))&&(E==null||typeof E=="string"&&E.trim()==="")))if(y==="exo__Instance_class"){let S=this.valueToClassURI(E);i.push(new Cr.Triple(s,T,S))}else{let S=await this.valueToRDFObject(E,e,T);if(b==="exo__Statement_subject"&&o===void 0){let R=S.find(D=>D instanceof ms.IRI);R&&(o=R)}else if(b==="exo__Statement_predicate"&&c===void 0){let R=S.find(D=>D instanceof ms.IRI);R&&(c=R)}else b==="exo__Statement_object"&&l===void 0&&(l=S[0]);for(let R of S)if(i.push(new Cr.Triple(s,T,R)),this.vocabularyMapper.hasMappingFor(y)&&R instanceof ms.IRI){let D=this.vocabularyMapper.generateMappedTriple(s,y,R);D&&i.push(D)}}if(y==="exo__Instance_class")for(let E of I){let S=this.valueToClassURI(E);if(S instanceof ms.IRI){let R=dr.Namespace.RDF.term("type");i.push(new Cr.Triple(s,R,S)),S.value===f&&(u=!0)}}if(y==="exo__Asset_label"){let E=dr.Namespace.RDFS.term("label");for(let S of I)typeof S=="string"&&S.length>0&&i.push(new Cr.Triple(s,E,new Cn.Literal(S)))}}let d="exo__Instance_class"in t||"exo__Asset_uid"in t,p=t.exo__Asset_label,h="exo__Asset_label"in t&&p!==null&&p!==void 0&&!(typeof p=="string"&&p.trim()==="")&&!(Array.isArray(p)&&p.length===0);if(d&&!h){let y=dr.Namespace.RDFS.term("label"),_=dr.Namespace.EXO.term("Asset_label"),b=new Cn.Literal(e.basename);i.push(new Cr.Triple(s,y,b)),i.push(new Cr.Triple(s,_,b))}i.push(...this.pendingExtraTriples),this.pendingExtraTriples=[],u&&o&&c&&l&&i.push(new Cr.Triple(o,c,l));let m=await this.convertBodyWikilinks(e,s);return i.push(...m),i}async convertExo003Note(e,t){let n=Si.Exo003Parser.parse(t);if(!n.success||!n.metadata)return[];let i=n.metadata,s=[];switch(i.metadata){case Si.Exo003MetadataType.Namespace:break;case Si.Exo003MetadataType.Anchor:s.push(...this.convertExo003Anchor(e,i));break;case Si.Exo003MetadataType.BlankNode:s.push(...this.convertExo003BlankNode(e,i));break;case Si.Exo003MetadataType.Statement:s.push(...this.convertExo003Statement(e,i));break;case Si.Exo003MetadataType.Body:s.push(...await this.convertExo003Body(e,i));break}return s}convertExo003Anchor(e,t){let n=this.notePathToIRI(e.path),i=new ms.IRI(t.uri);return[new Cr.Triple(n,dr.Namespace.OWL.term("sameAs"),i),new Cr.Triple(i,dr.Namespace.OWL.term("sameAs"),n)]}convertExo003BlankNode(e,t){let n=this.notePathToIRI(e.path),i=t.uri.replace(/[^a-zA-Z0-9_-]/g,"_");return[new Cr.Triple(n,dr.Namespace.OWL.term("sameAs"),new VD.BlankNode(i))]}convertExo003Statement(e,t){let n=[];try{let i=this.createExo003ReferenceResolver(e),s=Si.Exo003Parser.toTriple(t,i);n.push(s);let o=this.notePathToIRI(e.path);n.push(new Cr.Triple(o,dr.Namespace.RDF.term("value"),s.subject))}catch{}return n}async convertExo003Body(e,t){let n=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),o=this.createExo003ReferenceResolver(e),c=o(t.subject),l=o(t.predicate);if(c.type==="literal")throw new Error("Body subject cannot be a literal");if(l.type!=="iri")throw new Error("Body predicate must be an IRI");let u=c.type==="iri"?new ms.IRI(c.value):new VD.BlankNode(c.value),f=new ms.IRI(l.value),d=Si.Exo003Parser.toLiteral(t,s.trim());n.push(new Cr.Triple(u,f,d));let p=this.notePathToIRI(e.path);n.push(new Cr.Triple(p,dr.Namespace.RDF.term("value"),u))}catch{}return n}createExo003ReferenceResolver(e){return t=>{let n=this.extractWikilink(t),i=n||t,s=this.vault.getFirstLinkpathDest(i,e.path);if(s){let o=this.vault.getFrontmatter(s);if(o&&Si.Exo003Parser.isExo003Format(o)){let c=Si.Exo003Parser.parse(o);if(c.success&&c.metadata){let l=c.metadata;if(l.metadata===Si.Exo003MetadataType.Anchor||l.metadata===Si.Exo003MetadataType.Namespace)return{type:"iri",value:l.uri};if(l.metadata===Si.Exo003MetadataType.BlankNode)return{type:"blank",value:l.uri.replace(/[^a-zA-Z0-9_-]/g,"_")}}}return{type:"iri",value:this.notePathToIRI(s.path).value}}return!n&&t.includes("://")?{type:"iri",value:t}:{type:"literal",value:t}}}async convertVault(e={}){return(await this.convertVaultWithValidation({strict:!1,excludedFolders:e.excludedFolders})).triples}async convertVaultWithValidation(e={}){let t=this.vault.getAllFiles(),n=[],i=[],s=e.strict??!1,o=0,c=0,l=(0,cK.discoverFileSpaceExclusions)(this.vault);for(let y of l.warnings)this.logger.warn(`FileSpace discovery: ${y}`);let u=[...qD(e.excludedFolders),...l.prefixes],f=u.length===0?t:t.filter(y=>!WD(y.path,u)),d=e.onProgress,p=e.progressIntervalFiles&&e.progressIntervalFiles>0?e.progressIntervalFiles:TT.INDEX_PROGRESS_INTERVAL,h=f.length,m=0;for(let y of f){if(m++,d&&m%p===0&&m<h)try{d(m,h)}catch{}try{let _=this.vault.getFrontmatter(y),b=_?this.validateExocortexAsset(_,y.basename):null;if(b){if(s)throw new Error(`Invariant violation in "${y.path}": ${b.message}`);i.push({path:y.path,reason:`Invariant violation: ${b.message}`}),o++,this.logger.info(`Skipping file with invariant violation: ${y.path}`,{code:b.code,property:b.property,reason:b.message});continue}let T=await this.convertNote(y);n.push(...T)}catch(_){let b=_ instanceof Error?_.message:String(_);if(s)throw new Error(`Invalid IRI for file "${y.path}": ${b}`);i.push({path:y.path,reason:`Invalid IRI: ${b}`}),c++,this.logger.info(`Skipping file with invalid IRI: ${y.path}`,{reason:b})}}return o>0&&this.logger.warn(`Skipped ${o} file${o===1?"":"s"} with invariant violations during indexing (paths in developer console)`,{count:o}),c>0&&this.logger.warn(`Skipped ${c} file${c===1?"":"s"} with invalid IRI during indexing (paths in developer console)`,{count:c}),{triples:n,skippedFiles:i,summary:{total:f.length,indexed:f.length-i.length,skipped:i.length},fileSpaces:l}}static inferLabelFromBasename(e){return dr.Namespace.fromPropertyKey(e)!==null?e:null}validateExocortexAsset(e,t){let n=a(d=>d==null?!0:typeof d=="string"?d.trim()==="":Array.isArray(d)?d.length===0||d.every(n):!1,"isEmpty");if(!("exo__Instance_class"in e||"exo__Asset_uid"in e))return null;let s=["exo__Asset_uid","exo__Instance_class"];for(let d of s){if(!(d in e))return{code:"MISSING_PROPERTY",property:d,message:`Required property "${d}" is missing`};if(n(e[d]))return{code:"EMPTY_PROPERTY",property:d,message:`Required property "${d}" is empty`}}let o=["ems__Effort_status","ems__Effort_parent","ems__Effort_lockedBy","ems__Effort_lockExpires","exo__Asset_updatedAt","ems__Effort_startTimestamp"];for(let d of o)if(d in e&&n(e[d]))return{code:"EMPTY_OPTIONAL_PROPERTY",property:d,message:`Optional property "${d}" is present but empty`};let c=e.exo__Instance_class,l=Array.isArray(c)?c:[c],u=null,f=!1;for(let d of l){if(typeof d!="string")continue;let p=this.removeQuotes(d),m=(this.extractWikilink(p)??p).trim();/^[a-z][a-zA-Z0-9]*__/.test(m)&&/[\s()]/.test(m)?u||(u={candidate:d}):f=!0}return u&&!f?{code:"INVALID_INSTANCE_CLASS_IRI",property:"exo__Instance_class",message:`Invalid Instance_class IRI: "${u.candidate}"`}:null}async validateVault(){let e=this.vault.getAllFiles(),t=[];for(let n of e){let i=(0,vT.vaultPathToIRI)(n.path);ms.IRI.isValidIRI(i)||t.push({path:n.path,reason:`Path "${n.path}" cannot be converted to a valid IRI`})}return t}notePathToIRI(e){return new ms.IRI((0,vT.vaultPathToIRI)(`${this.subjectIriPrefix}${e}`))}synthesizeWikilinkTargetIRI(e){return new ms.IRI((0,vT.vaultPathToIRI)(e))}isExocortexProperty(e){return dr.Namespace.fromPropertyKey(e)!==null}propertyKeyToIRI(e){let t=dr.Namespace.fromPropertyKey(e);if(!t)throw new Error(`Invalid property key: ${e}`);return t.namespace.term(t.localName)}emitTypeTripleForEnumInstance(e,t){let n=this.vault.getFrontmatter(t);if(!n)return;let i=n.exo__Instance_class,s=Array.isArray(i)?i[0]:i;if(typeof s!="string")return;let o=this.valueToClassURI(s);o instanceof ms.IRI&&(this.pendingExtraTriples.push(new Cr.Triple(e,dr.Namespace.RDF.term("type"),o)),this.pendingExtraTriples.push(new Cr.Triple(e,dr.Namespace.EXO.term("Instance_class"),o)))}async valueToRDFObject(e,t,n){if(typeof e=="string"){let i=this.removeQuotes(e);if(n?.value.endsWith("#TokenInvocation_parameter"))return[new Cn.Literal(i)];let s=this.extractWikilink(i);if(s){let o=this.vault.getFirstLinkpathDest(s,t.path);if(o){let l=this.notePathToIRI(o.path),u=s.includes("|")?s.split("|")[0]:s;if(this.isUUID(u)){let d=new Cn.Literal(u);if(n?.value.endsWith("#Grounding_targetValueRef")||n?.value.endsWith("#Grounding_targetValueSubstitution")||n?.value.endsWith("#Grounding_targetClass")||n?.value.endsWith("#Grounding_type")||n?.value.endsWith("#PropertyDefault_value"))return[l];let h=this.expandClassValue(o.basename);if(h)return this.emitTypeTripleForEnumInstance(h,o),[h];let m=this.vault.getFrontmatter(o);if(m){let I=m.exo__Asset_label;if(typeof I=="string"){let E=this.expandClassValue(I);if(E)return this.emitTypeTripleForEnumInstance(E,o),[E]}}let y=n?.value.endsWith("#Asset_prototype")||n?.value.endsWith("/Asset_prototype"),b=((typeof process<"u"?process.env:void 0)?.EXOCORTEX_DUAL_STORAGE_PREDICATES??"").split(",").map(I=>I.trim()).filter(Boolean),T=b.length>0&&b.some(I=>n?.value.endsWith(`#${I}`));return y||T?[l,d]:[l]}let f=this.expandClassValue(o.basename);return f?(this.emitTypeTripleForEnumInstance(f,o),[f]):[l]}if(this.isClassReference(s)){let l=this.expandClassValue(s);if(l)return[l]}let c=s.includes("|")?s.split("|")[0]:s;return this.isUUID(c)?[this.synthesizeWikilinkTargetIRI(`${c}.md`)]:[new Cn.Literal(i)]}if(this.isClassReference(i)){let o=this.expandClassValue(i);if(o)return[o]}return this.isISO8601DateTime(i)?[new Cn.Literal(i,dr.Namespace.XSD.term("dateTime"))]:[new Cn.Literal(i)]}return typeof e=="boolean"?[new Cn.Literal(e.toString())]:typeof e=="number"?[new Cn.Literal(e.toString(),dr.Namespace.XSD.term("decimal"))]:e instanceof Date?[new Cn.Literal(e.toISOString(),dr.Namespace.XSD.term("dateTime"))]:[new Cn.Literal(String(e))]}isISO8601DateTime(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})?$/.test(e)}removeQuotes(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.substring(1,t.length-1):e}extractWikilink(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let n=t[1];return n.includes("|")?n.split("|")[0]:n}extractWikilinkAlias(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let n=t[1],i=n.indexOf("|");return i>=0?n.substring(i+1).trim():null}valueToClassURI(e){if(typeof e!="string")return new Cn.Literal(String(e));let t=this.removeQuotes(e),i=this.extractWikilink(t)||t,s=this.expandClassValue(i);if(s)return s;let o=this.extractWikilinkAlias(t);if(o){let c=this.expandClassValue(o);if(c)return c}if(this.isUUID(i)){let c=this.vault.getFirstLinkpathDest(i,"");if(c){let l=this.expandClassValue(c.basename);if(l)return this.emitInstanceClassAsUid?this.notePathToIRI(c.path):l;let u=this.vault.getFrontmatter(c);if(u){let f=u.exo__Asset_label;if(typeof f=="string"){let d=this.expandClassValue(f);if(d)return this.emitInstanceClassAsUid?this.notePathToIRI(c.path):d}}return this.notePathToIRI(c.path)}}return new Cn.Literal(t)}isClassReference(e){return/\s/.test(e)?!1:dr.Namespace.fromPropertyKey(e)!==null}isUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}expandClassValue(e){let t=this.removeQuotes(e),n=dr.Namespace.fromPropertyKey(t);return!n||/[\s()]/.test(n.localName)?null:n.namespace.term(n.localName)}extractBodyContent(e){let t=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;return e.replace(t,"")}extractBodyWikilinks(e){let t=new Set,n,i=new RegExp(this.BODY_WIKILINK_PATTERN.source,"g");for(;(n=i.exec(e))!==null;)n[1]&&t.add(n[1]);return Array.from(t)}async convertBodyWikilinks(e,t){let n=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),o=this.extractBodyWikilinks(s),c=dr.Namespace.EXO.term("Asset_bodyLink");for(let l of o){let u=this.vault.getFirstLinkpathDest(l,e.path);if(u){let f=this.notePathToIRI(u.path);n.push(new Cr.Triple(t,c,f))}else if(this.isClassReference(l)){let f=this.expandClassValue(l);f?n.push(new Cr.Triple(t,c,f)):n.push(new Cr.Triple(t,c,new Cn.Literal(l)))}else n.push(new Cr.Triple(t,c,new Cn.Literal(l)))}}catch{}return n}};Br.NoteToRDFConverter=El;El.INDEX_PROGRESS_INTERVAL=200;El.SkippedFileInfo=class{constructor(r,e){this.path=r,this.reason=e}};El.VaultValidationResult=class{constructor(r,e,t){this.triples=r,this.skippedFiles=e,this.summary=t}};El.VaultValidationOptions=class{constructor(r=!1){this.strict=r}};Br.NoteToRDFConverter=El=TT=iK([(0,ET.injectable)(),BD(0,(0,ET.inject)(GD.DI_TOKENS.IVaultAdapter)),BD(1,(0,ET.inject)(GD.DI_TOKENS.ILogger)),sK("design:paramtypes",[Object,Object,Object])],El)});var Tl=v(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});B0.FrontmatterService=void 0;var HD=L0(),AT=Cu(),IT=vl(),Yp=class r{static{a(this,"FrontmatterService")}parse(e){let t=e.match(r.FRONTMATTER_REGEX);return t?{exists:!0,content:t[1],originalContent:e}:{exists:!1,content:"",originalContent:e}}parseObject(e){let t=this.parse(e);if(!t.exists)return null;let n={},i=t.content.split(/\r?\n/),s=null,o=null,c=a(()=>{s!==null&&o!==null&&(n[s]=o),s=null,o=null},"flushArray");for(let l of i){let u=/^ {2}- (.*)$/.exec(l);if(u){s!==null&&o!==null&&o.push(u[1].trim());continue}c();let f=/^([^:\s][^:]*):\s*(.*)$/.exec(l);if(!f)continue;let d=f[1].trim(),p=f[2].trim();p===""?(s=d,o=[]):n[d]=p}return c(),n}updateProperty(e,t,n){t=(0,IT.canonicalYamlKey)(r.normalizeIRI(t)),typeof n=="string"&&(n=r.normalizeIRIValue(n));let i=this.parse(e),s=this.serializeValue(t,n);if(!i.exists)return`---
|
|
72
|
+
${n}}`}generateValuesTerm(e){if(e.type==="iri")return`<${e.value}>`;let n=`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return e.language?n+=`@${e.language}`:e.datatype&&(n+=`^^<${e.datatype}>`),n}generateExpression(e){switch(e.type){case"variable":return`?${e.name}`;case"literal":return typeof e.value=="string"?`"${e.value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:typeof e.value=="boolean"?e.value?"true":"false":String(e.value);case"comparison":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"logical":return e.operator==="!"?`!(${this.generateExpression(e.operands[0])})`:`(${e.operands.map(t=>this.generateExpression(t)).join(` ${e.operator} `)})`;case"arithmetic":return`(${this.generateExpression(e.left)} ${e.operator} ${this.generateExpression(e.right)})`;case"function":return`${e.function.toUpperCase()}(${e.args.map(t=>this.generateExpression(t)).join(", ")})`;case"functionCall":return`${(typeof e.function=="string"?e.function:e.function.value).toUpperCase()}(${e.args.map(n=>this.generateExpression(n)).join(", ")})`;case"exists":return`${e.negated?"NOT EXISTS":"EXISTS"} { ${this.generateWhereClause(e.pattern,0)} }`;case"in":{let t=this.generateExpression(e.expression),n=e.list.map(i=>this.generateExpression(i)).join(", ");return e.negated?`${t} NOT IN (${n})`:`${t} IN (${n})`}default:throw new lf(`Unknown expression type: ${e.type}`)}}collectVariablesFromOperation(e,t){switch(e.type){case"bgp":for(let n of e.triples)this.collectVariablesFromTriple(n,t);break;case"filter":this.collectVariablesFromOperation(e.input,t),this.collectVariablesFromExpression(e.expression,t);break;case"join":case"leftjoin":case"union":case"minus":this.collectVariablesFromOperation(e.left,t),this.collectVariablesFromOperation(e.right,t);break;case"values":for(let n of e.variables)t.add(n);break;case"project":for(let n of e.variables)t.add(n);this.collectVariablesFromOperation(e.input,t);break;case"extend":t.add(e.variable),this.collectVariablesFromOperation(e.input,t);break;case"orderby":case"slice":case"distinct":case"reduced":this.collectVariablesFromOperation(e.input,t);break;case"group":for(let n of e.variables)t.add(n);for(let n of e.aggregates)t.add(n.variable);this.collectVariablesFromOperation(e.input,t);break;case"subquery":this.collectVariablesFromOperation(e.query,t);break}}collectVariablesFromTriple(e,t){e.subject.type==="variable"&&t.add(e.subject.value),"type"in e.predicate&&e.predicate.type==="variable"&&t.add(e.predicate.value),e.object.type==="variable"&&t.add(e.object.value)}collectVariablesFromExpression(e,t){switch(e.type){case"variable":t.add(e.name);break;case"comparison":case"arithmetic":this.collectVariablesFromExpression(e.left,t),this.collectVariablesFromExpression(e.right,t);break;case"logical":for(let n of e.operands)this.collectVariablesFromExpression(n,t);break;case"function":case"functionCall":for(let n of e.args)this.collectVariablesFromExpression(n,t);break;case"exists":this.collectVariablesFromOperation(e.pattern,t);break;case"in":this.collectVariablesFromExpression(e.expression,t);for(let n of e.list)this.collectVariablesFromExpression(n,t);break}}};uf.SPARQLGenerator=aT});var df=v(bi=>{"use strict";var IH=bi&&bi.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:a(function(){return e[t]},"get")}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),RH=bi&&bi.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),wD=bi&&bi.__importStar||(function(){var r=a(function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)},"ownKeys");return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&IH(t,e,n[i]);return RH(t,e),t}})();Object.defineProperty(bi,"__esModule",{value:!0});bi.QueryExecutor=bi.ExoQLQueryExecutor=bi.QueryExecutorError=void 0;var CH=x1(),xH=u0(),OH=K1(),PH=Q1(),FH=oD(),DH=cD(),LH=dD(),NH=iT(),kH=hD(),MH=gD(),jH=bD(),$H=SD(),UH=Le(),BH=Ye(),VH=n0(),yn="http://www.w3.org/2001/XMLSchema#",GH=new Set([`${yn}integer`,`${yn}decimal`,`${yn}float`,`${yn}double`,`${yn}nonPositiveInteger`,`${yn}negativeInteger`,`${yn}long`,`${yn}int`,`${yn}short`,`${yn}byte`,`${yn}nonNegativeInteger`,`${yn}unsignedLong`,`${yn}unsignedInt`,`${yn}unsignedShort`,`${yn}unsignedByte`,`${yn}positiveInteger`]),ff=class extends Error{static{a(this,"QueryExecutorError")}constructor(e,t){super(e,t?{cause:t}:void 0),this.name="QueryExecutorError"}};bi.QueryExecutorError=ff;var _0=class{static{a(this,"ExoQLQueryExecutor")}constructor(e,t={}){let n=t.resolveClassHierarchy===!1?e:new jH.ClassHierarchyResolvingStore(e);this.tripleStore=n,this.bgpExecutor=new CH.BGPExecutor(n),this.filterExecutor=new xH.FilterExecutor,this.optionalExecutor=new OH.OptionalExecutor,this.unionExecutor=new PH.UnionExecutor,this.minusExecutor=new FH.MinusExecutor,this.valuesExecutor=new DH.ValuesExecutor,this.aggregateExecutor=new LH.AggregateExecutor,this.constructExecutor=new NH.ConstructExecutor,this.serviceExecutor=new kH.ServiceExecutor(t.serviceConfig),this.graphExecutor=new MH.GraphExecutor(n),this.sparqlGenerator=new $H.SPARQLGenerator,this.filterExecutor.setExistsEvaluator(async(i,s)=>this.evaluateExistsPattern(i,s)),this.filterExecutor.setTripleStore(n)}async evaluateExistsPattern(e,t){let n=this.substituteVariables(e,t);for await(let i of this.execute(n))if(t.merge(i)!==null)return!0;return!1}async executeAll(e){let t=[];for await(let n of this.execute(e))t.push(n);return t}async*execute(e){switch(e.type){case"bgp":yield*this.executeBGP(e);break;case"filter":yield*this.executeFilter(e);break;case"join":yield*this.executeJoin(e);break;case"leftjoin":yield*this.executeLeftJoin(e);break;case"union":yield*this.executeUnion(e);break;case"minus":yield*this.executeMinus(e);break;case"values":yield*this.executeValues(e);break;case"project":yield*this.executeProject(e);break;case"orderby":yield*this.executeOrderBy(e);break;case"slice":yield*this.executeSlice(e);break;case"distinct":yield*this.executeDistinct(e);break;case"reduced":yield*this.executeReduced(e);break;case"group":yield*this.executeGroup(e);break;case"extend":yield*this.executeExtend(e);break;case"subquery":yield*this.executeSubquery(e);break;case"lateraljoin":yield*this.executeLateralJoin(e);break;case"service":yield*this.executeService(e);break;case"graph":yield*this.executeGraph(e);break;default:throw new ff(`Unknown operation type: ${e.type}`)}}async*executeBGP(e){yield*this.bgpExecutor.execute(e)}async*executeFilter(e){let t=this.execute(e.input);yield*this.filterExecutor.execute(e,t)}async*executeJoin(e){let t=[];for await(let o of this.execute(e.left))t.push(o);if(t.length===0)return;let n=new Set;for(let o of t)for(let c of o.variables())n.add(c);let i=this.collectOperationVariables(e.right);if([...n].some(o=>i.has(o)))for(let o of t){let c=this.substituteVariables(e.right,o);for await(let l of this.execute(c)){let u=o.merge(l);u!==null&&(yield u)}}else{let o=[];for await(let c of this.execute(e.right))o.push(c);for(let c of t)for(let l of o){let u=c.merge(l);u!==null&&(yield u)}}}async*executeLeftJoin(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.optionalExecutor.execute(i(),s())}async*executeUnion(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.unionExecutor.execute(i(),s())}async*executeMinus(e){let t=[];for await(let o of this.execute(e.left))t.push(o);let n=[];for await(let o of this.execute(e.right))n.push(o);async function*i(){for(let o of t)yield o}a(i,"leftGen");async function*s(){for(let o of n)yield o}a(s,"rightGen"),yield*this.minusExecutor.execute(i(),s())}async*executeValues(e){yield*this.valuesExecutor.execute(e)}async*executeProject(e){let{SolutionMapping:t}=await Promise.resolve().then(()=>wD(Ko())),n=new Set(e.variables);for await(let i of this.execute(e.input)){let s=new t;for(let o of i.variables())if(n.has(o)){let c=i.get(o);c!==void 0&&s.set(o,c)}yield s}}async*executeOrderBy(e){let t=[];for await(let n of this.execute(e.input))t.push(n);t.sort((n,i)=>{for(let s of e.comparators){let o=this.getExpressionValue(s.expression,n),c=this.getExpressionValue(s.expression,i),l=0;if(o===void 0&&c===void 0?l=0:o===void 0?l=1:c===void 0?l=-1:typeof o=="number"&&typeof c=="number"?l=o-c:l=String(o).localeCompare(String(c)),s.descending&&(l=-l),l!==0)return l}return 0});for(let n of t)yield n}async*executeSlice(e){let t=0,n=e.offset??0,i=e.limit;for await(let s of this.execute(e.input)){if(t>=n){if(i!==void 0&&t-n>=i)break;yield s}t++}}async*executeDistinct(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeReduced(e){let t=new Set;for await(let n of this.execute(e.input)){let i=this.getSolutionKey(n);t.has(i)||(t.add(i),yield n)}}async*executeGroup(e){let t=[];for await(let i of this.execute(e.input))t.push(i);let n=this.aggregateExecutor.execute(e,t);if(e.having&&e.having.length>0)for(let i of n)e.having.every(o=>this.filterExecutor.evaluateExpression(o,i)===!0)&&(yield i);else for(let i of n)yield i}async*executeExtend(e){let t=e.expression.type!=="aggregate"&&this.filterExecutor.expressionContainsExists(e.expression);for await(let n of this.execute(e.input)){let i=n.clone(),s=t?await this.evaluateExtendExpressionAsync(e.expression,n):this.evaluateExtendExpression(e.expression,n);s!==void 0&&i.set(e.variable,s),yield i}}async*executeSubquery(e){yield*this.execute(e.query)}async*executeLateralJoin(e){let t=[];for await(let n of this.execute(e.left))t.push(n);for(let n of t){let i=this.substituteVariables(e.right,n);for await(let s of this.execute(i)){let o=n.merge(s);o!==null&&(yield o)}}}substituteVariables(e,t){let n=JSON.parse(JSON.stringify(e));return this.substituteInOperation(n,t)}substituteInOperation(e,t){if(!e||typeof e!="object")return e;let n=e;return e.type==="bgp"&&e.triples?(e.triples=e.triples.map(i=>this.substituteInTriple(i,t)),e):(n.input&&(n.input=this.substituteInOperation(n.input,t)),n.left&&(n.left=this.substituteInOperation(n.left,t)),n.right&&(n.right=this.substituteInOperation(n.right,t)),n.pattern&&(n.pattern=this.substituteInOperation(n.pattern,t)),n.query&&(n.query=this.substituteInOperation(n.query,t)),n.where&&(n.where=this.substituteInOperation(n.where,t)),n.expression&&this.substituteInExpression(n.expression,t),e)}substituteInExpression(e,t){if(!(!e||typeof e!="object")){if(e.type==="exists"&&e.pattern&&(e.pattern=this.substituteInOperation(e.pattern,t)),e.type==="variable"&&typeof e.name=="string"){let n=this.termToAlgebraNode(t.get(e.name));if(n!==null){delete e.name;for(let[i,s]of Object.entries(n))e[i]=s}}if(e.left&&this.substituteInExpression(e.left,t),e.right&&this.substituteInExpression(e.right,t),e.operands)for(let n of e.operands)this.substituteInExpression(n,t);if(e.args)for(let n of e.args)this.substituteInExpression(n,t);if(e.expression&&this.substituteInExpression(e.expression,t),e.list)for(let n of e.list)this.substituteInExpression(n,t)}}substituteInTriple(e,t){return{subject:this.substituteInTripleElement(e.subject,t),predicate:e.predicate,object:this.substituteInTripleElement(e.object,t)}}substituteInTripleElement(e,t){if(e&&e.type==="variable"){let n=this.termToAlgebraNode(t.get(e.value));if(n!==null)return n}return e}termToAlgebraNode(e){if(e==null)return null;let t=e;return e instanceof UH.IRI||t.termType==="NamedNode"?{type:"iri",value:e.value}:t.termType==="Literal"||typeof t.value=="string"?{type:"literal",value:t.value,datatype:t.datatype?.value??t._datatype?.value,language:t.language??t._language}:null}async*executeService(e){yield*this.serviceExecutor.execute(e,t=>this.sparqlGenerator.generateSelect(t))}async*executeGraph(e){let t=async function*(n,i){let s=this.currentGraphContext;this.currentGraphContext=i;try{n.type==="bgp"&&i&&this.tripleStore.matchInGraph?yield*this.executeBGPInGraph(n,i):yield*this.execute(n)}finally{this.currentGraphContext=s}}.bind(this);yield*this.graphExecutor.execute(e,t)}async*executeBGPInGraph(e,t){if(e.triples.length===0){let{SolutionMapping:n}=await Promise.resolve().then(()=>wD(Ko()));yield new n;return}yield*this.bgpExecutor.executeInGraph(e,t)}evaluateExtendExpression(e,t){if(e.type!=="aggregate")try{return this.filterExecutor.evaluateExpression(e,t)}catch{return}}async evaluateExtendExpressionAsync(e,t){if(e.type!=="aggregate")try{return await this.filterExecutor.evaluateExpressionAsync(e,t)}catch{return}}getExpressionValue(e,t){if(e.type==="variable"){let n=t.get(e.name);if(!n)return;if(n instanceof BH.Literal){let i=n.datatype?.value;if(i===`${yn}dayTimeDuration`)try{return VH.DateTimeFunctions.parseDayTimeDuration(n.value)}catch{return n.value}if(i&&GH.has(i)){let s=parseFloat(n.value);if(!Number.isNaN(s))return s}return n.value}return n.value??n.id??String(n)}if(e.type==="literal")return e.value}collectOperationVariables(e){let t=new Set;return this.collectVarsFromOperation(e,t),t}collectVarsFromOperation(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="bgp"&&n.triples)for(let i of n.triples)this.collectVarsFromElement(i.subject,t),i.predicate?.type!=="path"&&this.collectVarsFromElement(i.predicate,t),this.collectVarsFromElement(i.object,t);if(n.type==="values"&&n.variables)for(let i of n.variables)t.add(i);n.expression&&this.collectVarsFromExpressionTree(n.expression,t),n.type==="extend"&&n.variable&&t.add(n.variable),n.input&&this.collectVarsFromOperation(n.input,t),n.left&&this.collectVarsFromOperation(n.left,t),n.right&&this.collectVarsFromOperation(n.right,t),n.pattern&&this.collectVarsFromOperation(n.pattern,t),n.query&&this.collectVarsFromOperation(n.query,t),n.where&&this.collectVarsFromOperation(n.where,t)}collectVarsFromElement(e,t){if(!e||typeof e!="object")return;let n=e;n.type==="variable"&&t.add(n.value),n.type==="quoted"&&(this.collectVarsFromElement(n.subject,t),this.collectVarsFromElement(n.predicate,t),this.collectVarsFromElement(n.object,t))}collectVarsFromExpressionTree(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="variable"&&n.name&&t.add(n.name),n.type==="exists"&&n.pattern&&this.collectVarsFromOperation(n.pattern,t),n.left&&this.collectVarsFromExpressionTree(n.left,t),n.right&&this.collectVarsFromExpressionTree(n.right,t),n.operands)for(let i of n.operands)this.collectVarsFromExpressionTree(i,t);if(n.args)for(let i of n.args)this.collectVarsFromExpressionTree(i,t);if(n.expression&&this.collectVarsFromExpressionTree(n.expression,t),n.list)for(let i of n.list)this.collectVarsFromExpressionTree(i,t)}getSolutionKey(e){let t=e.toJSON();return Object.keys(t).sort().map(i=>`${i}=${t[i]}`).join("|")}isConstructQuery(e){return e.type==="construct"}async executeConstruct(e){if(e.type!=="construct")throw new ff("executeConstruct requires a CONSTRUCT operation");let t=await this.executeAll(e.where);return this.constructExecutor.execute(e.template,t)}isAskQuery(e){return e.type==="ask"}async executeAsk(e){if(e.type!=="ask")throw new ff("executeAsk requires an ASK operation");for await(let t of this.execute(e.where))return!0;return!1}};bi.ExoQLQueryExecutor=_0;bi.QueryExecutor=_0});var PD=v(Yo=>{"use strict";var qH=Yo&&Yo.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},WH=Yo&&Yo.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)};Object.defineProperty(Yo,"__esModule",{value:!0});Yo.CommandResolver=void 0;var HH=at(),zH=Dp(),KH=Cu(),fr=Le(),Xt=Ye(),B=Yt(),ED=qa(),vD=pp(),YH=Ou(),TD=Lp(),QH=/^[a-z][a-z0-9+.-]*:\/\//i,pf=yE(),AD=fF(),XH=Uu(),JH=Hu(),ZH=df(),wl=10,b0="exo__Asset",ez=wl+1,ID="08cec529-90eb-4d43-88de-ceecccea12b0",tz=B.Namespace.EXOCMD.term("SubstitutionToken").value,RD=new Set(["today","tomorrow","todayStart","targetFolder","target","randomUUIDv4","nowTimestamp","nowDate","nowYear","nowMonth","userInputLabel","userInput","targetProperty","targetRefProperty","labelAsArray","groundingTargetClass","targetClassSelf"]);function rz(r,e){return`__SUBSTITUTE__${r}__${e}__`}a(rz,"buildSubstitutionMarker");function nz(r,e,t){let n=(0,YH.utf8ToBase64)(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`__SUBSTITUTE_P__${r}__${e}__${n}__`}a(nz,"buildParameterisedMarker");var CD="3f28af98-c031-4718-8ba2-44ad0b012c52",iz=B.Namespace.EXOCMD.term("TokenInvocation").value,xD="29e2c8f8-2d27-4e58-b467-2e85d46f8122",OD="universal-default-template",cT=class{static{a(this,"CommandResolver")}clearUniversalCache(){this._universalCacheReady=!1,this._universalCacheValue=null}constructor(e,t=zH.NullLogger){this.tripleStore=e,this.logger=t,this.cache=new Map,this.multiCache=new Map,this._ancestorDepthCache=new Map,this._legacyPropertyDefaultsWarnedGroundings=new Set,this._fallbackWarnedKeys=new Set,this._universalCacheReady=!1,this._universalCacheValue=null}async resolveForAssetMulti(e,t,n){if(t.length===0)return[];let i=[...t].sort().join(","),s=`${e}::${i}::${n??""}`,o=this.multiCache.get(s);if(o)return o;let c=n?await this.expandPrototypeChain(n):void 0,l=await this.expandClassHierarchy(t),u=new Map;for(let[h,m]of l){let y=await this.resolveForAsset(e,h,c);for(let _ of y){let b=this.getBindingPriority(_.binding)===2?m:0,T=u.get(_.binding.id);(!T||b<T.depth)&&u.set(_.binding.id,{rc:_,depth:b})}}let f=new Set;for(let{rc:h}of u.values())if(h.binding.overrides)for(let m of h.binding.overrides)f.add(m);let d=Array.from(u.entries()).filter(([h])=>!f.has(h)).map(([,h])=>h);d.sort((h,m)=>{let y=this.getBindingPriority(h.rc.binding),_=this.getBindingPriority(m.rc.binding);return y!==_?y-_:h.depth!==m.depth?h.depth-m.depth:(h.rc.binding.order??100)-(m.rc.binding.order??100)});let p=d.map(h=>h.rc);return this.multiCache.set(s,p),p}async expandClassHierarchy(e){let t=new Map;for(let c of e){if(c===b0){t.set(c,new Set);continue}let l=[];try{l=await this.getClassAncestors(c)}catch{l=[]}t.set(c,new Set(l))}let n=a(c=>{for(let l of e)if(l!==c&&t.get(l)?.has(c)&&!t.get(c)?.has(l))return!0;return!1},"isAncestorOfSibling"),i=e.filter(c=>!n(c)),s=new Map,o=a((c,l)=>{let u=s.get(c);(u===void 0||l<u)&&s.set(c,l)},"setMin");for(let c of i){if(o(c,0),this.looksLikeUUID(c))try{let u=await this.resolveLabelByUID(c);u&&o(u,0)}catch{}if(c===b0)continue;let l=[];try{l=await this.getClassAncestorsWithDepth(c)}catch{l=[]}for(let{ref:u,depth:f}of l)o(u,f)}return s.has(b0)||s.set(b0,ez),s}async resolveForAsset(e,t,n){let i=typeof n=="string"?`s:${n}`:n?`c:${n.join("\0")}`:"",s=`${e}:${t}:${i}`,o=this.cache.get(s);if(o)return o;let c=typeof n=="string"?await this.expandPrototypeChain(n):n,l=await this.findBindings(t,c,e),u=[];for(let f of l){let d=await this.loadCommand(f.commandRef,{targetClass:f.targetClass});if(!d)continue;let p=f.precondition?{...d,precondition:f.precondition}:d;u.push({command:p,binding:f})}return u.sort((f,d)=>{let p=this.getBindingPriority(f.binding),h=this.getBindingPriority(d.binding);return p!==h?p-h:(f.binding.order??100)-(d.binding.order??100)}),this.cache.set(s,u),u}async loadCommand(e,t){let n=await this.findSubjectByUID(e);if(!n||(await this.tripleStore.match(n,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("Command"))).length===0)return null;let s=await this.getLiteralValue(n,B.Namespace.EXO.term("Asset_label"))??"Unknown Command",o=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_labelTemplate")),c=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_icon")),l=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_confirmMessage")),u=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_successMessage")),f=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_category")),d=await this.getLiteralValue(n,B.Namespace.EXOCMD.term("Command_openInSameTab")),p=d!==null&&String(d).trim().toLowerCase()==="true",h=await this.loadLinkedPrecondition(n),m=await this.loadLinkedGrounding(n,0,t);return m?{id:e,name:s,labelTemplate:o??void 0,icon:c??void 0,precondition:h??void 0,grounding:m,confirmMessage:l??void 0,successMessage:u??void 0,category:f??void 0,openInSameTab:p||void 0}:null}async findBindings(e,t,n){let i=typeof t=="string"?await this.expandPrototypeChain(t):t,s=await this.tripleStore.match(void 0,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("CommandBinding")),o=[];for(let c of s){let l=c.subject,u=await this.loadBindingDefinition(l);u&&this.bindingMatches(u,e,i,n)&&o.push(u)}return o}async findPaletteEnabledCommands(){let e=await this.tripleStore.match(void 0,B.Namespace.RDF.term("type"),B.Namespace.EXOCMD.term("Command")),t=[],n=new Set;for(let i of e){let s=i.subject;if((await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_paletteEnabled")))?.toLowerCase()!=="true")continue;let c=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_uid"));if(!c){this.logger.warn(`[CommandResolver] paletteEnabled command at ${s.value} has no exo__Asset_uid \u2014 skipped`);continue}let l=await this.loadCommand(c);if(!l){this.logger.warn(`[CommandResolver] paletteEnabled command ${c} could not be loaded (missing grounding?) \u2014 skipped`);continue}let u=await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_paletteId")),f=await this.getLiteralValue(s,B.Namespace.EXOCMD.term("Command_cliName")),d=u??f??c;if(n.has(d)){this.logger.warn(`[CommandResolver] duplicate paletteId "${d}" \u2014 first registration wins, dropping ${c}`);continue}n.add(d),t.push({command:l,paletteId:d})}return t}invalidateCache(){this.cache.clear(),this.multiCache.clear(),this._ancestorDepthCache.clear(),this.clearUniversalCache()}async resolveLabel(e,t){if(!e.labelTemplate)return e.name;let n=e.labelTemplate,i=this.extractPlaceholders(e.labelTemplate);for(let{full:s,body:o}of i){let c=await this.evaluateSelectSnippet(o,t);n=n.replace(s,c)}return n}extractPlaceholders(e){let t=[],n=0;for(;n<e.length;)if(e[n]==="{"){let i=1,s=n+1;for(;s<e.length&&i>0;)e[s]==="{"?i++:e[s]==="}"&&i--,s++;if(i===0){let o=e.slice(n,s),c=e.slice(n+1,s-1);t.push({full:o,body:c})}n=s}else n++;return t}async evaluateSelectSnippet(e,t){try{let n=e.replace(/\$target/g,`<${t}>`),s=new XH.ExoQLParser().parse(n),c=new JH.ExoQLAlgebraTranslator().translate(s),u=await new ZH.ExoQLQueryExecutor(this.tripleStore).executeAll(c);if(u.length===0)return"";let f=u[0],d=f.variables();if(d.length===0)return"";let p=f.get(d[0]);return p?p instanceof Xt.Literal||p instanceof fr.IRI?p.value:String(p):""}catch{return""}}async loadBindingDefinition(e){let t=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!t)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",i=await this.getLinkedUID(e,B.Namespace.EXOCMD.term("CommandBinding_command"));if(!i)return null;let s=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetClass")),o=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetPrototype")),c=await this.getLinkedValue(e,B.Namespace.EXOCMD.term("CommandBinding_targetAsset"));if(!s&&!o&&!c)return null;let l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_position")),u=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_order")),f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_variant")),d=f!==null?this.coerceVariant(f,t):void 0,p=await this.loadLinkedPreconditionFromProperty(e,B.Namespace.EXOCMD.term("CommandBinding_precondition")),h=await this.loadLinkedStyle(e,t),m=await this.getLinkedUIDs(e,B.Namespace.EXOCMD.term("CommandBinding_overrides"));return{id:t,label:n,commandRef:i,targetClass:s??void 0,targetPrototype:o??void 0,targetAsset:c??void 0,position:l??void 0,order:u?parseInt(u,10):void 0,variant:d,precondition:p??void 0,style:h??void 0,overrides:m.length>0?m:void 0}}async loadLinkedStyle(e,t){let n=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("CommandBinding_style"),void 0);if(n.length>0){let s=n[0].object,o=null;if(s instanceof fr.IRI)o=s;else if(s instanceof Xt.Literal){let c=this.normalizeWikilink(s.value);o=await this.findSubjectByUID(c)}if(o){let c=await this.loadStyleAsset(o);if(c)return c}this.logger.warn(this.capWarning(`CommandBinding ${t}: style reference unresolved, falling back to inline variant`))}let i=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBinding_variant"));if(i!==null){let s=this.coerceVariant(i,t);if(s!==void 0)return{id:`inline:${t}`,label:"",variant:s,inline:!0}}return null}async loadStyleAsset(e){let t=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!t)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",i=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_variant")),s=i!==null?this.coerceVariant(i,t):void 0,o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_showIcon")),c=this.coerceBoolean(o),l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_labelClass")),u=l!==null?this.coerceLabelClass(l,t):void 0,f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_ariaLabel")),d=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_tooltip")),p=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_keyboardShortcut")),h=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("CommandBindingStyle_source")),m=h!==null?this.coerceStyleSource(h,t):void 0;return{id:t,label:n,variant:s,showIcon:c,labelClass:u,ariaLabel:f??void 0,tooltip:d??void 0,keyboardShortcut:p??void 0,source:m,inline:!1}}coerceVariant(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.COMMAND_VARIANT_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle variant "${n}" not in whitelist [${pf.COMMAND_VARIANT_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceLabelClass(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.LABEL_CLASS_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle labelClass "${n}" not in whitelist [${pf.LABEL_CLASS_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceStyleSource(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==""){if(pf.STYLE_SOURCE_VALUES.includes(n))return n;this.logger.warn(this.capWarning(`CommandBindingStyle source "${n}" not in whitelist [${pf.STYLE_SOURCE_VALUES.join(",")}]; dropped (asset ${t})`))}}coerceBoolean(e){if(e===null)return;let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}capWarning(e){return e.length<=200?e:e.slice(0,197)+"..."}bindingMatches(e,t,n,i){if(e.targetAsset&&i&&this.matchesReference(e.targetAsset,i))return!0;if(e.targetPrototype&&n){for(let s of n)if(this.matchesReference(e.targetPrototype,s))return!0}return!!(e.targetClass&&t&&this.matchesReference(e.targetClass,t))}matchesReference(e,t){let n=this.normalizeWikilink(e),i=this.normalizeWikilink(t);if(n===i)return!0;let s=this.extractPathBasename(i);if(s&&s===n)return!0;let o=this.extractPathBasename(n);if(o&&o===i)return!0;let c=this.extractAlias(t);if(c&&n===c)return!0;let l=this.extractAlias(e);return!!(l&&l===i)}extractPathBasename(e){let t=e.match(/\/([^/]+)\.md$/);return t?t[1]:null}extractAlias(e){let t=e.replace(/["'[\]]/g,"").trim(),n=t.indexOf("|");return n>=0?t.substring(n+1).trim():null}getBindingPriority(e){return e.targetAsset?0:e.targetPrototype?1:2}async loadLinkedPrecondition(e){return this.loadLinkedPreconditionFromProperty(e,B.Namespace.EXOCMD.term("Command_precondition"))}async loadLinkedPreconditionFromProperty(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=await this.resolvePreconditionRef(n[0].object);return i?this.loadPreconditionSubject(i,new Set,0):null}async resolvePreconditionRef(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return await this.findSubjectByUID(t)}return null}async loadPreconditionSubject(e,t,n){let i=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid")),s=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"";if(i&&t.has(i))return this.brokenPreconditionNode(i,s);if(n>=wl)return this.brokenPreconditionNode(i??"",s);let o=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("AllPrecondition_preconditions"),void 0),c=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("AnyPrecondition_preconditions"),void 0),l=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("NotPrecondition_precondition"),void 0);if(o.length>0||c.length>0||l.length>0){let p=new Set(t);if(i&&p.add(i),o.length>0||c.length>0){let m=o.length>0?"all":"any",y=o.length>0?o:c,_=[];for(let b of y)_.push(await this.loadChildPrecondition(b.object,p,n+1));return{id:i??"",label:s,composite:{op:m,children:_}}}let h=await this.loadChildPrecondition(l[0].object,p,n+1);return{id:i??"",label:s,not:h}}let u=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Precondition_sparqlAsk")),f=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Precondition_hostFunction")),d=await this.loadPreconditionQueryRef(e);return!i||!u&&!f&&!d?null:{id:i,label:s,...u&&{sparqlAsk:u},...f&&{hostFunction:f},...d&&{query:d}}}async loadChildPrecondition(e,t,n){let i=await this.resolvePreconditionRef(e);if(!i){let c=e instanceof Xt.Literal?this.normalizeWikilink(e.value):"";return this.brokenPreconditionNode(c,"")}let s=await this.loadPreconditionSubject(i,t,n);if(s)return s;let o=await this.getLiteralValue(i,B.Namespace.EXO.term("Asset_uid"));return this.brokenPreconditionNode(o??"","")}async loadPreconditionQueryRef(e){let t=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Precondition_query"),void 0);if(t.length===0)return;let n=t[0].object;if(n instanceof fr.IRI)return await this.getLiteralValue(n,B.Namespace.EXO.term("Asset_uid"))??void 0;if(n instanceof Xt.Literal)return this.normalizeWikilink(n.value)}brokenPreconditionNode(e,t){return{id:e,label:t,broken:!0}}async loadLinkedGrounding(e,t,n){if(t>=wl)return null;let i=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Command_grounding"),void 0);if(i.length===0)return null;if(i.length===1||!n?.targetClass){let o=await this.resolveGroundingRef(i[0].object);return o?this.loadGroundingDefinition(o,t):null}for(let o of i){let c=await this.resolveGroundingRef(o.object);if(!c)continue;let l=await this.getObsidianName(c,B.Namespace.EXOCMD.term("Grounding_targetPrototype"));if(l&&this.matchesReference(l,n.targetClass))return this.loadGroundingDefinition(c,t)}this.logger.warn(`Command ${e.value}: ${i.length} groundings declared, none matched context.targetClass='${n.targetClass}' via Grounding_targetPrototype \u2014 falling back to first grounding by iteration order (legacy behaviour). Check that one grounding's Grounding_targetPrototype references this targetClass.`);let s=await this.resolveGroundingRef(i[0].object);return s?this.loadGroundingDefinition(s,t):null}async resolveGroundingRef(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return await this.findSubjectByUID(t)}return null}async loadGroundingByUid(e){let t=await this.findSubjectByUID(e);return t?this.loadGroundingDefinition(t,0):null}async loadGroundingDefinition(e,t){if(t>=wl)return null;let n=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_uid"));if(!n)return null;let i=await this.getLiteralValue(e,B.Namespace.EXO.term("Asset_label"))??"",s=await this.resolveGroundingTypeReference(e);if(!s)return null;let o=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetProperty"));if(o&&this.looksLikeUUID(o)){let k=await this.resolveLabelByUID(o);if(!k)return this.logger.warn(`Grounding ${n}: targetProperty wikilink UID '${o}' is not resolvable to exo__Asset_label \u2014 grounding skipped (would otherwise write a UUID-named frontmatter key).`),null;o=k}if(s===ED.GroundingType.SERVICE_CALL){let k=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_serviceId"));k&&(o=k)}let c=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueRef")),l=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetValueLiteral")),u=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueSubstitution")),f=null;if(u&&this.looksLikeUUID(u)){let k=await this.resolveLabelByUID(u);if(!k)return this.logger.warn(`Grounding ${n}: targetValueSubstitution UID '${u}' is not resolvable to exo__Asset_label (SubstitutionToken instance missing or unlabelled) \u2014 grounding skipped.`),null;f=k}else u&&(f=u);let d=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetValueQuery")),p=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetQuery")),h=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_serviceCallPayload")),m=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_appendExpression")),y=await this.getObsidianWikilinkValue(e,B.Namespace.EXOCMD.term("Grounding_isDefinedBy")),_=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_sparqlUpdate")),b=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetClass"));if(b&&!this.looksLikeUUID(b)){let k=await this.findUidByLabel(b);k&&(b=k)}let T=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_targetPrototype")),I=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetFolder")),E=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_linkBackProperty")),S=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_inputSchema")),R=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_incrementBy")),D=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_shiftDelta")),P;if(R!=null&&R!==""){let k=Number.parseInt(String(R),10);Number.isFinite(k)&&(P=k)}let M=await this.resolvePropertyDefaults(e,n),O=await this.resolveInheritanceRules(e,n),L=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_propertyDefaults"));L!==null&&L!==""&&!this._legacyPropertyDefaultsWarnedGroundings.has(n)&&(this.logger.warn(`Grounding ${n}: deprecated exocmd__Grounding_propertyDefaults (plural) JSON predicate detected \u2014 the parser was removed in RFC v2 Phase 5 (#3167); value is ignored. Migrate to ref-form exocmd__Grounding_propertyDefault (singular) pointing to exocmd__PropertyDefault assets. See vault TBox c8f87363-d39c-45cb-9d4d-1be96d70f892 for the canonical replacement.`),this._legacyPropertyDefaultsWarnedGroundings.add(n));let te;s===ED.GroundingType.COMPOSITE&&(te=await this.loadCompositeSteps(e,t+1));let re;if(S)try{let k=JSON.parse(S);k?.properties&&(re=Object.entries(k.properties).map(([oe,de])=>{let Ae=de.type,we=Ae==="string"?"text":Ae,ve=de.defaultValue!==void 0?de.defaultValue:de.default,Te={name:oe,type:we,label:de.title??oe,required:Array.isArray(k.required)&&k.required.includes(oe)};return ve!=null&&(Te.defaultValue=String(ve)),typeof de.targetClassUid=="string"&&(Te.targetClassUid=de.targetClassUid),Te}))}catch{}let V=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_prefillLabelWithDate")),K=V!==null&&String(V).trim().toLowerCase()==="true",Se=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_labelTemplate")),ce=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_direction")),q;if(ce!=null){let k=String(ce).trim().toLowerCase();k==="forward"||k==="rollback"?q=k:k!==""&&this.logger.warn(`Grounding ${n}: exocmd__Grounding_direction value '${ce}' is not 'forward' or 'rollback' \u2014 treating as undefined (will default to 'forward' at dispatch).`)}let W=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_bodyTemplate")),ne=await this.getObsidianName(e,B.Namespace.EXOCMD.term("Grounding_templateRef")),xe=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_cloneTargetBody")),X=xe!==null&&String(xe).trim().toLowerCase()==="true",ee=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_targetsCreatedInstance")),Z=ee!==null&&String(ee).trim().toLowerCase()==="true",H=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("Grounding_omitLabel")),ie=H!==null&&String(H).trim().toLowerCase()==="true",$e={id:n,label:i,type:s,targetProperty:o??void 0,targetValueRef:c??void 0,targetValueLiteral:l??void 0,targetValueSubstitution:f??void 0,targetValueQuery:d??void 0,targetQuery:p??void 0,serviceCallPayload:h??void 0,appendExpression:m??void 0,sparqlUpdate:_??void 0,steps:te,targetClass:b??void 0,targetPrototype:T??void 0,targetFolder:I??void 0,linkBackProperty:E??void 0,incrementBy:P,shiftDelta:D??void 0,propertyDefault:M.length>0?M:void 0,inheritanceRule:O.length>0?O:void 0,isDefinedBy:y??void 0,prefillLabelWithDate:K||void 0,labelTemplate:Se??void 0,direction:q,bodyTemplate:W??void 0,templateRef:ne??void 0,cloneTargetBody:X||void 0,targetsCreatedInstance:Z||void 0,omitLabel:ie||void 0};return re&&($e.inputSchema=re),$e}async loadCompositeSteps(e,t){if(t>=wl)return[];let n=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Grounding_steps"),void 0),i=[];for(let s of n){let o=null;if(s.object instanceof fr.IRI)o=s.object;else if(s.object instanceof Xt.Literal){let l=this.normalizeWikilink(s.object.value);o=await this.findSubjectByUID(l)}if(!o)continue;let c=await this.loadGroundingDefinition(o,t);c&&i.push(c)}return i}async resolvePropertyDefaults(e,t){let n=await this.resolvePropertyDefaultsForSubject(e,t,B.Namespace.EXOCMD.term("Grounding_propertyDefault")),i=await this.getUniversalCache();return i&&i.propertyDefaults.length>0?(0,AD.mergePropertyDefaults)(i.propertyDefaults,n):n}async resolvePropertyDefaultsForSubject(e,t,n){let i=await this.tripleStore.match(e,n,void 0),s=[];for(let o of i){let c=await this.resolveRefTripleObject(o.object);if(!c)continue;let l=await this.getObsidianName(c,B.Namespace.EXOCMD.term("PropertyDefault_property"));if(!l){this.logger.warn(`Grounding ${t}: PropertyDefault asset missing exocmd__PropertyDefault_property \u2014 entry skipped.`);continue}let u=this.looksLikeUUID(l)?await this.resolveLabelByUID(l):l;if(!u){this.logger.warn(`Grounding ${t}: PropertyDefault property UID '${l}' is not resolvable to exo__Asset_label \u2014 entry skipped.`);continue}let f=await this.getObsidianName(c,B.Namespace.EXOCMD.term("PropertyDefault_value"));if(!f){this.logger.warn(`Grounding ${t}: PropertyDefault '${u}' missing exocmd__PropertyDefault_value \u2014 entry skipped.`);continue}let d=await this.resolvePropertyDefaultValue(f,t,u);d!==null&&s.push({propertyName:u,value:d})}return s}async getUniversalCache(){if(this._universalCacheReady)return this._universalCacheValue;this._universalCacheReady=!0;let e=await this.findUniversalSingleton();if(!e)return this.logger.debug("[CommandResolver] No exocmd__UniversalDefaultTemplate instance found in the store; universal property-defaults and inheritance-rules will not be applied. This verdict is cached until invalidateCache() is called \u2014 if the store was still warming up, the next invalidation re-resolves it."),this._universalCacheValue=null,null;let t=await this.resolvePropertyDefaultsForSubject(e,OD,B.Namespace.EXOCMD.term("Template_propertyDefault")),n=await this.resolveInheritanceRulesForSubject(e,OD,B.Namespace.EXOCMD.term("Template_inheritanceRule"));return this._universalCacheValue={propertyDefaults:t,inheritanceRules:n},this._universalCacheValue}async findUniversalSingleton(){let e=B.Namespace.EXOCMD.term("UniversalDefaultTemplate"),t=e.value,i=(await this.tripleStore.match(void 0,B.Namespace.EXO.term("Instance_class"),e)).map(c=>c.subject).filter(c=>c instanceof fr.IRI);if(i.length>0)return this.pickUniversalSingleton(i);let s=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Instance_class"),void 0),o=[];for(let c of s){let l=!1;if(c.object instanceof fr.IRI)l=c.object.value===t||c.object.value.includes(xD);else if(c.object instanceof Xt.Literal){let u=this.unwrapWikilink(c.object.value);l=u==="exocmd__UniversalDefaultTemplate"||u===xD}l&&c.subject instanceof fr.IRI&&o.push(c.subject)}return this.pickUniversalSingleton(o)}pickUniversalSingleton(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=[...e].sort((n,i)=>n.value.localeCompare(i.value));return this.logger.warn(`Multiple UniversalDefaultTemplate singletons found (${t.length}); selecting deterministically by lexicographic UID order: ${t[0].value}`),t[0]}async resolveInheritanceRules(e,t){let n=await this.resolveInheritanceRulesForSubject(e,t,B.Namespace.EXOCMD.term("Grounding_inheritanceRule")),i=await this.getUniversalCache();return i&&i.inheritanceRules.length>0?(0,AD.mergeInheritanceRules)(i.inheritanceRules,n):n}async resolveInheritanceRulesForSubject(e,t,n){let i=await this.tripleStore.match(e,n,void 0),s=[],o=t;for(let c of i){let l=await this.resolveRefTripleObject(c.object);if(!l)continue;let u=await this.resolveLabelRef(l,B.Namespace.EXOCMD.term("InheritanceRule_sourceProperty"));if(!u){this.logger.warn(`Grounding ${o}: InheritanceRule missing/unresolvable exocmd__InheritanceRule_sourceProperty \u2014 entry skipped.`);continue}let f=await this.resolveLabelRef(l,B.Namespace.EXOCMD.term("InheritanceRule_targetProperty"));if(!f){this.logger.warn(`Grounding ${o}: InheritanceRule missing/unresolvable exocmd__InheritanceRule_targetProperty \u2014 entry skipped.`);continue}let d=await this.tripleStore.match(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassCondition"),void 0),p,h;if(d.length>0){let E=await this.getObsidianName(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassCondition"));if(!E||!E.trim()){this.logger.warn(`Grounding ${o}: InheritanceRule has exocmd__InheritanceRule_targetClassCondition triple but ref is unresolvable \u2014 entire rule skipped (would otherwise apply unconditionally, broadening scope).`);continue}this.looksLikeUUID(E)?(h=E,p=await this.resolveLabelByUID(E)??void 0):p=E}let m=await this.tripleStore.match(l,B.Namespace.EXOCMD.term("InheritanceRule_targetClassExclusion"),void 0),y=[],_=[],b=!1;for(let E of m){let S=null;if(E.object instanceof fr.IRI?S=this.iriToObsidianName(E.object.value)??E.object.value:E.object instanceof Xt.Literal&&(S=this.unwrapWikilink(E.object.value)),!S){b=!0;continue}if(this.looksLikeUUID(S)){_.push(S);let R=await this.resolveLabelByUID(S);R&&y.push(R)}else y.push(S)}if(b){this.logger.warn(`Grounding ${o}: InheritanceRule has unresolvable exocmd__InheritanceRule_targetClassExclusion entry \u2014 entire rule skipped (would otherwise expand scope by silently dropping the excluded class).`);continue}let T=await this.getLiteralValue(l,B.Namespace.EXOCMD.term("InheritanceRule_priority")),I=50;if(T!==null&&T!==""){let E=Number.parseInt(String(T),10);Number.isFinite(E)&&(I=E)}s.push({sourcePropertyName:u,targetPropertyName:f,targetClassCondition:p,targetClassConditionUid:h,targetClassExclusion:y,targetClassExclusionUids:_,priority:I})}return s}async resolveRefTripleObject(e){if(e instanceof fr.IRI)return e;if(e instanceof Xt.Literal){let t=this.normalizeWikilink(e.value);return t?this.findSubjectByUID(t):null}return null}async resolveLabelRef(e,t){let n=await this.getObsidianName(e,t);return n?this.looksLikeUUID(n)?this.resolveLabelByUID(n):n:null}async resolvePropertyDefaultValue(e,t,n){if(!this.looksLikeUUID(e))return`"[[${e}]]"`;let i=await this.findSubjectByUID(e);if(!i){let c=`${t}|${e}`;return this._fallbackWarnedKeys.has(c)||(this._fallbackWarnedKeys.add(c),this.logger.warn(this.capWarning(`Grounding ${t}: PropertyDefault '${n}' \u2192 value asset ${e} not in store; SKIPPING the property (the executor's own default applies). Previously this emitted a wikilink, i.e. a link written where a value belongs.`))),KH.STRING_SCALAR_PROPERTIES.has(n)?null:`"[[${e}]]"`}return await this.assetIsTokenInvocation(i)?this.resolveTokenInvocation(i,e,t,n):await this.assetIsSubstitutionToken(i)?this.dispatchSubstitutionToken(i,e,t,n,void 0):(this.logger.debug(`Grounding ${t}: PropertyDefault '${n}' value '${e}' is not a SubstitutionToken \u2014 emitting wikilink form.`),`"[[${e}]]"`)}async dispatchSubstitutionToken(e,t,n,i,s){let o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("SubstitutionToken_resolver"));if(!o||!o.trim())return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' references SubstitutionToken '${t}' with no exocmd__SubstitutionToken_resolver \u2014 falling back to wikilink form.`),`"[[${t}]]"`;let c=o.trim();return RD.has(c)?s!==void 0?nz(c,t,s):rz(c,t):(this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' SubstitutionToken '${t}' declares unknown resolver-id '${c}' \u2014 falling back to wikilink form. Known ids: ${Array.from(RD).join(", ")}.`),`"[[${t}]]"`)}async resolveTokenInvocation(e,t,n,i){let s=await this.getObsidianName(e,B.Namespace.EXOCMD.term("TokenInvocation_token"));if(!s)return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' missing exocmd__TokenInvocation_token \u2014 entry skipped.`),null;let o=await this.getLiteralValue(e,B.Namespace.EXOCMD.term("TokenInvocation_parameter"))??"";if(!this.looksLikeUUID(s))return this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' references non-UUID token '${s}' \u2014 entry skipped.`),null;let c=await this.findSubjectByUID(s);return c?this.dispatchSubstitutionToken(c,s,n,i,o):(this.logger.warn(`Grounding ${n}: PropertyDefault '${i}' TokenInvocation '${t}' token ref '${s}' not found in store \u2014 entry skipped.`),null)}async assetIsTokenInvocation(e){let t=await this.tripleStore.match(e,B.Namespace.EXO.term("Instance_class"),void 0);for(let i of t)if(i.object instanceof fr.IRI){if(i.object.value===iz||i.object.value.includes(CD))return!0}else if(i.object instanceof Xt.Literal){let s=this.unwrapWikilink(i.object.value);if(s==="exocmd__TokenInvocation"||s===CD)return!0}return(await this.tripleStore.match(e,B.Namespace.EXOCMD.term("TokenInvocation_token"),void 0)).length>0?(this.logger.debug(`Asset ${e.value} classified as TokenInvocation via its exocmd__TokenInvocation_token property; exo__Instance_class was absent or unresolved.`),!0):!1}async assetIsSubstitutionToken(e){let t=await this.tripleStore.match(e,B.Namespace.EXO.term("Instance_class"),void 0);for(let i of t)if(i.object instanceof fr.IRI){if(i.object.value===tz||i.object.value.includes(ID))return!0}else if(i.object instanceof Xt.Literal){let s=this.unwrapWikilink(i.object.value);if(s==="exocmd__SubstitutionToken"||s===ID)return!0}return(await this.tripleStore.match(e,B.Namespace.EXOCMD.term("SubstitutionToken_resolver"),void 0)).length>0?(this.logger.debug(`Asset ${e.value} classified as SubstitutionToken via its resolver property; exo__Instance_class was absent or unresolved.`),!0):!1}async resolveGroundingTypeReference(e){let t=await this.tripleStore.match(e,B.Namespace.EXOCMD.term("Grounding_type"),void 0);if(t.length===0)return null;let n=t[0].object;if(n instanceof fr.IRI)return(0,vD.resolveGroundingTypeFromIRI)(n.value);if(n instanceof Xt.Literal){let i=n.value,s=i.match(/^\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\|[^\]]*)?\]\]$/i);return s?(0,vD.resolveGroundingTypeFromIRI)(`obsidian://vault/${s[1].toLowerCase()}.md`):(this.logger.warn(`[exocmd-grounding-type-literal-form] legacy literal-string form '${i}' for exocmd__Grounding_type on <${e.value}>. Migrate to wikilink form per RFC 9d20c91f Phase 3.`),null)}return null}async expandPrototypeChain(e){if(!e||!this.normalizeWikilink(e))return[];let t=[e],n=new Set([this.normalizeWikilink(e).toLowerCase()]),i=e;for(let s=0;s<wl;s++){let o=this.extractUuidFromRef(i);if(!o)break;let c=null;try{let u=await this.findSubjectByUID(o);if(!u)break;c=await this.getLinkedValue(u,B.Namespace.EXO.term("Asset_prototype"))}catch(u){this.logger.debug(this.capWarning(`[expandPrototypeChain] store lookup failed at hop ${s} for '${i}': ${String(u)}`));break}if(!c)break;let l=this.normalizeWikilink(c).toLowerCase();if(n.has(l))break;n.add(l),t.push(c),i=c}return t}extractUuidFromRef(e){let t=this.normalizeWikilink(e);if(this.looksLikeUUID(t))return t;let n=this.extractPathBasename(t);return n&&this.looksLikeUUID(n)?n:null}async findSubjectByUID(e){if(this.tripleStore.findSubjectsByUUID){let n=await this.tripleStore.findSubjectsByUUID(e);if(n.length>0)return n[0]}let t=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Asset_uid"),void 0);for(let n of t)if(n.object instanceof Xt.Literal&&n.object.value===e)return n.subject;return null}async getLiteralValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal||i instanceof fr.IRI?i.value:null}looksLikeUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}async resolveLabelByUID(e){let t=await this.findSubjectByUID(e);if(!t)return null;let n=await this.getLiteralValue(t,B.Namespace.EXO.term("Asset_label"));return n===null?null:QH.test(n)?(0,TD.iriToObsidianName)(n)??n:n}async getClassAncestors(e){return(await this.getClassAncestorsWithDepth(e)).map(n=>n.ref)}async getClassAncestorsWithDepth(e){let t=this._ancestorDepthCache.get(e);if(t)return t;let n=new Map,i=new Set,s=await this.resolveClassFileIRI(e);if(!s)return[];let o=new Set([e]),c=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_uid"));c&&o.add(c);let l=await this.getLiteralValue(s,B.Namespace.EXO.term("Asset_label"));l&&o.add(l);let u=a((p,h)=>{if(o.has(p))return;let m=n.get(p);(m===void 0||h<m)&&n.set(p,h)},"setMin"),f=[{fileIRI:s,depth:0}];for(;f.length>0;){let p=f.shift();if(!p)break;let{fileIRI:h,depth:m}=p;if(m>=wl||i.has(h.value))continue;i.add(h.value);let y=await this.tripleStore.match(h,B.Namespace.EXO.term("Class_superClass"),void 0);for(let _ of y){let b=_.object;if(!(b instanceof fr.IRI))continue;let T=m+1,I=b.value.startsWith("obsidian://vault/"),E=this.iriToObsidianName(b.value);E&&u(E,T);let S=null;if(I?S=b:E&&(S=await this.resolveClassFileIRI(E)),!S)continue;let R=await this.getLiteralValue(S,B.Namespace.EXO.term("Asset_uid"));R&&u(R,T),i.has(S.value)||f.push({fileIRI:S,depth:T})}}let d=Array.from(n.entries()).map(([p,h])=>({ref:p,depth:h}));return this._ancestorDepthCache.set(e,d),d}async resolveClassFileIRI(e){if(this.looksLikeUUID(e))return this.findSubjectByUID(e);let t=await this.findUidByLabel(e);return t?this.findSubjectByUID(t):null}async findUidByLabel(e){let t=await this.tripleStore.match(void 0,B.Namespace.EXO.term("Asset_label"),void 0);for(let n of t)if(n.object instanceof Xt.Literal&&n.object.value===e&&n.subject instanceof fr.IRI){let i=await this.tripleStore.match(n.subject,B.Namespace.EXO.term("Asset_uid"),void 0);if(i.length>0&&i[0].object instanceof Xt.Literal)return i[0].object.value}return null}async getLinkedUID(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;if(i instanceof fr.IRI){let s=await this.tripleStore.match(i,B.Namespace.EXO.term("Asset_uid"),void 0);return s.length>0&&s[0].object instanceof Xt.Literal?s[0].object.value:i.value.split("/").pop()?.replace(".md","")??null}return i instanceof Xt.Literal?this.normalizeWikilink(i.value):null}async getLinkedUIDs(e,t){let n=await this.tripleStore.match(e,t,void 0),i=[];for(let s of n){let o=s.object;if(o instanceof fr.IRI){let c=await this.tripleStore.match(o,B.Namespace.EXO.term("Asset_uid"),void 0);if(c.length>0&&c[0].object instanceof Xt.Literal)i.push(c[0].object.value);else{let l=o.value.split("/").pop()?.replace(".md","");l&&i.push(l)}}else if(o instanceof Xt.Literal){let c=this.normalizeWikilink(o.value);c&&i.push(c)}}return i}async getLinkedValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal?this.normalizeWikilink(i.value):i instanceof fr.IRI?this.iriToObsidianName(i.value)??i.value:null}async getObsidianName(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;return i instanceof Xt.Literal?this.unwrapWikilink(i.value):i instanceof fr.IRI?this.iriToObsidianName(i.value)??i.value:null}unwrapWikilink(e){if(!e)return e;let t=e.trim().replace(/^"|"$/g,"");if(t.startsWith("http://")||t.startsWith("https://"))return this.iriToObsidianName(t)??t;let n=t.match(/^\[\[([^\]|]+)\|([^\]]+)\]\]$/);if(n)return n[2].trim();let i=t.match(/^\[\[([^\]|]+)\]\]$/);if(i){let s=i[1].trim();return s.startsWith("http://")||s.startsWith("https://")?this.iriToObsidianName(s)??s:s}return t}async getObsidianWikilinkValue(e,t){let n=await this.tripleStore.match(e,t,void 0);if(n.length===0)return null;let i=n[0].object;if(i instanceof Xt.Literal)return this.resolveWikilinkAlias(i.value);if(i instanceof fr.IRI){let s=this.iriToObsidianName(i.value);return s?`"[[${s}]]"`:i.value}return null}async resolveWikilinkAlias(e){let t=e.match(/\[\[([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]\]/);if(!t)return e;let n=t[1],i=await this.findSubjectByUID(n);if(!i)return e;let s=await this.getLiteralValue(i,B.Namespace.EXO.term("Asset_label"));return s?e.replace(`[[${n}]]`,`[[${n}|${s}]]`):e}iriToObsidianName(e){return(0,TD.iriToObsidianName)(e)}normalizeWikilink(e){let t=e.replace(/["'[\]]/g,"").trim(),n=t.indexOf("|");return n>=0?t.substring(0,n):t}};Yo.CommandResolver=cT;Yo.CommandResolver=cT=qH([(0,HH.injectable)(),WH("design:paramtypes",[Object,Object])],cT)});var uT=v(lT=>{"use strict";Object.defineProperty(lT,"__esModule",{value:!0});lT.validateExoQLAllowlist=sz;var S0=Vp();function sz(r){if(!r||typeof r!="object")return;let e=r;if(e.type==="update"){let t=r.updates??[];for(let n of t)if(n?.type==="load")throw new S0.ExoQLForbiddenKeywordError("LOAD");throw new S0.ExoQLForbiddenKeywordError("UPDATE")}if(e.type==="query"){if(e.from){let t=Array.isArray(e.from.default)&&e.from.default.length>0,n=Array.isArray(e.from.named)&&e.from.named.length>0;if(t||n)throw new S0.ExoQLForbiddenKeywordError("FROM")}if(Array.isArray(e.where))for(let t of e.where)w0(t);if(Array.isArray(e.template))for(let t of e.template)w0(t)}}a(sz,"validateExoQLAllowlist");function w0(r){if(!r||typeof r!="object")return;if(r.type==="service")throw new S0.ExoQLForbiddenKeywordError("SERVICE");if(Array.isArray(r.patterns))for(let t of r.patterns)w0(t);let e=r.where;if(Array.isArray(e))for(let t of e)w0(t)}a(w0,"walkPatternForBannedKeywords")});var fT=v(E0=>{"use strict";Object.defineProperty(E0,"__esModule",{value:!0});E0.DEFAULT_EVAL_CONFIG=void 0;E0.DEFAULT_EVAL_CONFIG=Object.freeze({enabled:!0,maxNestedEvalCount:100,maxAggregateEvalMillis:1e4})});var v0=v(dT=>{"use strict";Object.defineProperty(dT,"__esModule",{value:!0});dT.evaluateWithExoEval=dz;var oz=Uu(),az=Hu(),cz=df(),lz=uT(),uz=fT(),fz=Vp();async function dz(r,e={}){if(typeof r!="string")throw new TypeError("evaluateWithExoEval: sparql must be a string");let n=new oz.ExoQLParser().parse(r);if((0,lz.validateExoQLAllowlist)(n),!{...uz.DEFAULT_EVAL_CONFIG,...e.config??{}}.enabled)throw new fz.ExoQLEvalDisabledError;let s="queryType"in n&&typeof n.queryType=="string"?n.queryType:"SELECT";if(!e.store)return s==="ASK"?{kind:"ask",result:!1}:s==="CONSTRUCT"?{kind:"construct",triples:[]}:{kind:"select",rows:[]};let c=new az.ExoQLAlgebraTranslator().translate(n),l=new cz.ExoQLQueryExecutor(e.store);return l.isAskQuery(c)?{kind:"ask",result:await l.executeAsk(c)}:l.isConstructQuery(c)?{kind:"construct",triples:await l.executeConstruct(c)}:{kind:"select",rows:await l.executeAll(c)}}a(dz,"evaluateWithExoEval")});var ps=v(T0=>{"use strict";Object.defineProperty(T0,"__esModule",{value:!0});T0.DateFormatter=void 0;var pT=class r{static{a(this,"DateFormatter")}static toISOTimestamp(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toLocalTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0");return`${t}-${n}-${i}T${s}:${o}:${c}`}static toDateWikilink(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`"[[${t}-${n}-${i}]]"`}static getTodayWikilink(){return r.toDateWikilink(new Date)}static toDateString(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}static parseWikilink(e){let n=e.replace(/^["']|["']$/g,"").match(/\[\[(\d{4}-\d{2}-\d{2})\]\]/);return n?n[1]:null}static addDays(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}static isSameDay(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}static getTodayStartTimestamp(){let e=new Date;return e.setHours(0,0,0,0),r.toLocalTimestamp(e)}static toTimestampAtStartOfDay(e){let t=e.split("-").map(Number);if(t.length!==3||t.some(isNaN))throw new Error(`Invalid date format: ${e}. Expected YYYY-MM-DD`);let[n,i,s]=t,o=new Date(n,i-1,s,0,0,0,0);if(isNaN(o.getTime()))throw new Error(`Invalid date values: ${e}`);return r.toLocalTimestamp(o)}static normalizeTimestamp(e){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e))return e;let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp format: ${e}`);return r.toISOTimestamp(t)}static isISOTimestamp(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(e)}};T0.DateFormatter=pT});var qp=v(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});A0.liveClock=pz;A0.frozenClock=hz;function pz(){return{now:a(()=>new Date,"now")}}a(pz,"liveClock");function hz(r){let e=new Date(r);return{now:a(()=>new Date(e.getTime()),"now")}}a(hz,"frozenClock")});var DD=v(Qo=>{"use strict";var mz=Qo&&Qo.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},gz=Qo&&Qo.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Hp;Object.defineProperty(Qo,"__esModule",{value:!0});Qo.PreconditionEvaluator=void 0;var yz=at(),_z=Uu(),bz=Hu(),FD=df(),Sz=v0(),Wp=ps(),wz=qp(),zp=Hp=class{static{a(this,"PreconditionEvaluator")}constructor(e,t,n){this.hostFunctions=new Map,this.askCache=new Map,this.tripleStore=e,this.queryBodyResolver=t,this.clock=n?.clock??(0,wz.liveClock)()}async evaluate(e,t,n){if(!e)return!0;let i=new Map;return await this.evaluateNode(e,t,n,i)==="yes"}async evaluateNode(e,t,n,i){if(e.broken)return"unknown";if(e.composite){let{op:s,children:o}=e.composite;if(o.length===0)return"unknown";let c=await Promise.all(o.map(l=>this.evaluateNode(l,t,n,i)));return s==="all"?c.includes("no")?"no":c.includes("unknown")?"unknown":"yes":c.includes("yes")?"yes":c.includes("unknown")?"unknown":"no"}if(e.not){let s=await this.evaluateNode(e.not,t,n,i);return s==="unknown"?"unknown":s==="yes"?"no":"yes"}return e.sparqlAsk?await this.evaluateSparqlAskMemoized(e.sparqlAsk,t,i)?"yes":"no":e.query?await this.evaluateQueryRef(e.query,t)?"yes":"no":e.hostFunction?this.evaluateHostFunction(e.hostFunction,t,n)?"yes":"no":"yes"}evaluateSparqlAskMemoized(e,t,n){let i=n.get(e);if(i!==void 0)return i;let s=this.evaluateSparqlAsk(e,t);return n.set(e,s),s}async evaluateQueryRef(e,t){if(!this.queryBodyResolver)return!1;try{let n=await this.queryBodyResolver.resolveSparql(e);if(!n)return!1;let i=this.substituteVariables(n,t),s=await(0,Sz.evaluateWithExoEval)(i,{store:this.tripleStore});return s.kind!=="ask"?!1:s.result}catch{return!1}}registerHostFunction(e,t){this.hostFunctions.set(e,t)}hasHostFunction(e){return this.hostFunctions.has(e)}evaluateHostFunctionSync(e,t,n){return this.hostFunctions.has(e)?this.evaluateHostFunction(e,t,n):null}invalidateCache(){this.askCache.clear()}compileAsk(e){let t=this.substituteVariables(e,Hp.SENTINEL_IRI),i=new _z.ExoQLParser().parse(t),o=new bz.ExoQLAlgebraTranslator().translate(i);return new FD.ExoQLQueryExecutor(this.tripleStore).isAskQuery(o)?o:null}evaluateHostFunction(e,t,n){let i=this.hostFunctions.get(e);if(!i)return!0;let s=n?{...n,targetIRI:t}:{targetIRI:t};try{return i(s)}catch{return!1}}async evaluateSparqlAsk(e,t){try{let n=Hp.TEMPORAL_TOKEN.test(e),i=n?Wp.DateFormatter.toDateString(this.clock.now()):null,s=this.askCache.get(e);if(s===void 0||n&&s.day!==i){let l=this.compileAsk(e);if(!l)return!1;s={day:i,compiled:l},this.askCache.set(e,s)}let o=JSON.parse(JSON.stringify(s.compiled).replaceAll(Hp.SENTINEL_IRI,t));return await new FD.ExoQLQueryExecutor(this.tripleStore).executeAsk(o)}catch{return!1}}substituteVariables(e,t){let n=this.clock.now(),i=n.toISOString(),s=n.getFullYear(),o=n.getMonth(),c=n.getDate(),l=n.getDay(),u=Wp.DateFormatter.toDateString(n),f=Wp.DateFormatter.toDateString(new Date(s,o,c-1)),d=(l+6)%7,p=Wp.DateFormatter.toDateString(new Date(s,o,c-d)),h=Wp.DateFormatter.toDateString(new Date(s,o,c-d-7)),m=`${s}-${String(o+1).padStart(2,"0")}-01`,y=o===0?11:o-1,b=`${o===0?s-1:s}-${String(y+1).padStart(2,"0")}-01`,T=`${s}-01-01`;return e.replace(/\$target\b/g,`<${t}>`).replace(/\$now\b/g,`"${i}"^^xsd:dateTime`).replace(/\$yesterday\b/g,`"${f}"^^xsd:date`).replace(/\$thisWeekStart\b/g,`"${p}"^^xsd:date`).replace(/\$lastWeekStart\b/g,`"${h}"^^xsd:date`).replace(/\$thisMonthStart\b/g,`"${m}"^^xsd:date`).replace(/\$lastMonthStart\b/g,`"${b}"^^xsd:date`).replace(/\$thisYearStart\b/g,`"${T}"^^xsd:date`).replace(/\$today\b/g,`"${u}"^^xsd:date`)}};Qo.PreconditionEvaluator=zp;zp.SENTINEL_IRI="urn:exocortex:cache-sentinel:target";zp.TEMPORAL_TOKEN=/\$(?:now|today|yesterday|thisWeekStart|lastWeekStart|thisMonthStart|lastMonthStart|thisYearStart)\b/;Qo.PreconditionEvaluator=zp=Hp=mz([(0,yz.injectable)(),gz("design:paramtypes",[Object,Object,Object])],zp)});var LD=v(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.hasUidFilename=Xo.hasNonUidFilename=void 0;Xo.registerDefaultHostFunctions=Tz;var Ez=a(r=>{let e=r.assetUid;if(typeof e!="string"||e.trim()==="")return!1;let t=r.fileBasename;return typeof t!="string"?!1:t!==e},"hasNonUidFilename");Xo.hasNonUidFilename=Ez;var vz=a(r=>{let e=r.assetUid;if(typeof e!="string"||e.trim()==="")return!1;let t=r.fileBasename;return typeof t!="string"?!1:t===e},"hasUidFilename");Xo.hasUidFilename=vz;function Tz(r){r.registerHostFunction("hasNonUidFilename",Xo.hasNonUidFilename),r.registerHostFunction("hasUidFilename",Xo.hasUidFilename)}a(Tz,"registerDefaultHostFunctions")});var R0=v(I0=>{"use strict";Object.defineProperty(I0,"__esModule",{value:!0});I0.liveUidGenerator=Az;I0.seededUidGenerator=Rz;var hT=il();function Az(){return{next:a(()=>(0,hT.v4)(),"next")}}a(Az,"liveUidGenerator");var Iz="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Rz(r){let e=0,t=(0,hT.v5)(r,Iz);return{next:a(()=>{let n=`${r}#${e}`;return e+=1,(0,hT.v5)(n,t)},"next")}}a(Rz,"seededUidGenerator")});var O0=v(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.registerResolver=yr;tc.getResolver=xz;tc.isResolverModifierAware=Oz;tc.getRegisteredResolverIds=Pz;tc.clearResolvers=Fz;tc.installDefaultResolvers=Vz;var Cz=ps(),x0=new Map,mT=new Set;function yr(r,e,t=!1){x0.set(r,e),t&&mT.add(r)}a(yr,"registerResolver");function xz(r){return x0.get(r)}a(xz,"getResolver");function Oz(r){return mT.has(r)}a(Oz,"isResolverModifierAware");function Pz(){return Array.from(x0.keys())}a(Pz,"getRegisteredResolverIds");function Fz(){x0.clear(),mT.clear()}a(Fz,"clearResolvers");function _n(r){return r<10?`0${r}`:String(r)}a(_n,"pad2");var Dz=["January","February","March","April","May","June","July","August","September","October","November","December"],Lz=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Nz=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],kz=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Mz(r){let e=["th","st","nd","rd"],t=r%100;return`${r}${e[(t-20)%10]||e[t]||e[0]}`}a(Mz,"ordinalDay");var jz=/YYYY|YY|MMMM|MMM|MM|M|Do|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|A|a/g;function $z(r,e){let t=(r.getHours()+11)%12+1;return e.replace(jz,n=>{switch(n){case"YYYY":return String(r.getFullYear());case"YY":return _n(r.getFullYear()%100);case"MMMM":return Dz[r.getMonth()];case"MMM":return Lz[r.getMonth()];case"MM":return _n(r.getMonth()+1);case"M":return String(r.getMonth()+1);case"Do":return Mz(r.getDate());case"DD":return _n(r.getDate());case"D":return String(r.getDate());case"dddd":return Nz[r.getDay()];case"ddd":return kz[r.getDay()];case"HH":return _n(r.getHours());case"H":return String(r.getHours());case"hh":return _n(t);case"h":return String(t);case"mm":return _n(r.getMinutes());case"m":return String(r.getMinutes());case"ss":return _n(r.getSeconds());case"s":return String(r.getSeconds());case"A":return r.getHours()<12?"AM":"PM";case"a":return r.getHours()<12?"am":"pm";default:return n}})}a($z,"formatDate");function ND(r,e,t){let n=r.getDate(),i=new Date(r.getTime());i.setDate(1),t==="M"?i.setMonth(i.getMonth()+e):i.setFullYear(i.getFullYear()+e);let s=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(n,s)),i}a(ND,"addMonthsClamped");function Uz(r,e){if(!e)return r;let t=e.match(/^([+-])(\d+)([dwMy])?$/);if(!t)return r;let n=(t[1]==="-"?-1:1)*parseInt(t[2],10),i=t[3]??"d",s=new Date(r.getTime());switch(i){case"d":s.setDate(s.getDate()+n);break;case"w":s.setDate(s.getDate()+n*7);break;case"M":s=ND(s,n,"M");break;case"y":s=ND(s,n,"y");break}return isNaN(s.getTime())?r:s}a(Uz,"applyDateOffset");function Bz(r){if(!r)return{offset:null,format:null};let e=r.indexOf(":");if(e<0)return{offset:r,format:null};let t=r.slice(0,e),n=r.slice(e+1);return{offset:t||null,format:n||null}}a(Bz,"parseDateModifier");function C0(r,e){return(t,n)=>{let{offset:i,format:s}=Bz(n),o=new Date;return r!==0&&o.setDate(o.getDate()+r),o=Uz(o,i),$z(o,s??e)}}a(C0,"makeDateResolver");function Vz(){yr("today",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}`}),yr("todayStart",()=>Cz.DateFormatter.getTodayStartTimestamp()),yr("date",C0(0,"YYYY-MM-DD"),!0),yr("now",C0(0,"YYYY-MM-DDTHH:mm:ss"),!0),yr("tomorrow",C0(1,"YYYY-MM-DD"),!0),yr("yesterday",C0(-1,"YYYY-MM-DD"),!0),yr("target",r=>r.targetIRI?`"[[${r.targetIRI}]]"`:""),yr("targetFolder",r=>{if(!r.targetFilePath)return"";let e=r.targetFilePath.replace(/^\/+/,""),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}),yr("randomUUIDv4",()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();throw new Error("randomUUIDv4 resolver requires crypto.randomUUID() \u2014 runtime is missing Node crypto / Web Crypto API.")}),yr("nowTimestamp",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}T${_n(r.getHours())}:${_n(r.getMinutes())}:${_n(r.getSeconds())}`}),yr("nowDate",()=>{let r=new Date;return`${r.getFullYear()}-${_n(r.getMonth()+1)}-${_n(r.getDate())}`}),yr("nowYear",()=>String(new Date().getFullYear())),yr("nowMonth",()=>_n(new Date().getMonth()+1)),yr("userInputLabel",r=>{let e=r.userInput?.label;return typeof e=="string"?e:""}),yr("userInput",(r,e)=>{if(!e)return null;let t=r.userInput?.[e];return typeof t=="string"?t:t==null?null:String(t)}),yr("targetProperty",(r,e)=>{if(!e||!r.targetFm)return null;let t=r.targetFm[e];return t==null?null:Array.isArray(t)?t.map(String):String(t)}),yr("targetRefProperty",(r,e)=>{if(!e)return null;let t=e.indexOf("|");if(t<0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!n||!i)return null;let s=r.targetRefFm?.[n];if(!s)return null;let o=s[i];return o==null?null:Array.isArray(o)?o.length>0?String(o[0]):null:String(o)}),yr("labelAsArray",r=>{let e=r.userInput?.label;return typeof e=="string"&&e.length>0?[e]:[]}),yr("groundingTargetClass",r=>r.groundingTargetClassUid?`"[[${r.groundingTargetClassUid}]]"`:null),yr("targetClassSelf",r=>{if(!r.targetFilePath)return null;let e=r.targetFilePath.replace(/^\/+/,""),n=e.slice(e.lastIndexOf("/")+1).replace(/\.md$/i,"");return n.length>0?`"[[${n}]]"`:null})}a(Vz,"installDefaultResolvers")});var yT=v(P0=>{"use strict";Object.defineProperty(P0,"__esModule",{value:!0});P0.resolveTemplateBody=qz;P0.stripTemplateFrontmatter=Wz;var gT=O0();(0,gT.installDefaultResolvers)();var Gz=/\$([A-Za-z][A-Za-z0-9_]*)((?:[+-]\d+[dwMy])?(?::[A-Za-z0-9:./-]+)?)/g;function qz(r,e={}){return r.replace(Gz,(t,n,i)=>{let s=(0,gT.getResolver)(n);if(s===void 0)return t;let o=s(e,i.length>0?i:void 0);return typeof o!="string"||o.length===0?t:(0,gT.isResolverModifierAware)(n)?o:o+i})}a(qz,"resolveTemplateBody");function Wz(r){let e=r.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return e?r.slice(e[0].length):r}a(Wz,"stripTemplateFrontmatter")});var L0=v(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});hf.registerOrderSpecLoader=Hz;hf.clearOrderSpecLoader=zz;hf.loadDefaultSpec=Kz;hf.orderProperties=Yz;var F0=null,rc,D0=!1;function Hz(r){F0=r,rc=void 0,D0=!1}a(Hz,"registerOrderSpecLoader");function zz(){F0=null,rc=void 0,D0=!1}a(zz,"clearOrderSpecLoader");function Kz(){if(rc!==void 0)return rc;if(!F0)return rc=null,null;try{rc=F0()}catch(r){D0||(console.warn("[OrderSpecResolver] loader threw, falling back to insertion order:",r),D0=!0),rc=null}return rc}a(Kz,"loadDefaultSpec");function Yz(r,e){if(!e||e.head.length===0&&e.tail.length===0)return r;let t=Object.keys(r),n=new Set(e.head),i=new Set(e.tail),s=e.head.filter(u=>Object.prototype.hasOwnProperty.call(r,u)),o=e.tail.filter(u=>Object.prototype.hasOwnProperty.call(r,u)),c=t.filter(u=>!n.has(u)&&!i.has(u));e.middleStrategy==="alphabetical"&&c.sort((u,f)=>u.localeCompare(f));let l={};for(let u of s)l[u]=r[u];for(let u of c)l[u]=r[u];for(let u of o)l[u]=r[u];return l}a(Yz,"orderProperties")});var Qn=v(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});N0.DI_TOKENS=void 0;N0.DI_TOKENS={IFileSystemAdapter:Symbol.for("IFileSystemAdapter"),IVaultAdapter:Symbol.for("IVaultAdapter"),IVaultContext:Symbol.for("IVaultContext"),IMultiVaultManager:Symbol.for("IMultiVaultManager"),ILogger:Symbol.for("ILogger"),IEventBus:Symbol.for("IEventBus"),IConfiguration:Symbol.for("IConfiguration"),INotificationService:Symbol.for("INotificationService"),ClassCreationService:Symbol.for("ClassCreationService"),ConceptCreationService:Symbol.for("ConceptCreationService"),GenericAssetCreationService:Symbol.for("GenericAssetCreationService"),TaskStatusService:Symbol.for("TaskStatusService"),EffortStatusWorkflow:Symbol.for("EffortStatusWorkflow"),StatusTimestampService:Symbol.for("StatusTimestampService"),PropertyCleanupService:Symbol.for("PropertyCleanupService"),FolderRepairService:Symbol.for("FolderRepairService"),RenameToUidService:Symbol.for("RenameToUidService"),NoteToRDFConverter:Symbol.for("NoteToRDFConverter"),IVaultSettings:Symbol.for("IVaultSettings"),AreaHierarchyBuilder:Symbol.for("AreaHierarchyBuilder"),ClassHierarchyResolver:Symbol.for("ClassHierarchyResolver")}});var bT=v(k0=>{"use strict";Object.defineProperty(k0,"__esModule",{value:!0});k0.RDFVocabularyMapper=void 0;var Rr=hi(),kD=Le(),_e=Yt(),_T=class{static{a(this,"RDFVocabularyMapper")}constructor(){this.propertyMappings=new Map([["exo__Instance_class",_e.Namespace.RDF.term("type")],["exo__Asset_isDefinedBy",_e.Namespace.RDFS.term("isDefinedBy")],["exo__Class_superClass",_e.Namespace.RDFS.term("subClassOf")],["exo__Property_range",_e.Namespace.RDFS.term("range")],["exo__Property_domain",_e.Namespace.RDFS.term("domain")],["exo__Property_superProperty",_e.Namespace.RDFS.term("subPropertyOf")]])}generateClassHierarchyTriples(){let e=[];return e.push(new Rr.Triple(_e.Namespace.EXO.term("Asset"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDFS.term("Resource"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Class"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDFS.term("Class"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.RDF.term("Property"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Task"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Project"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Area"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("Workflow"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("WorkflowState"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EMS.term("WorkflowTransition"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Command"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Precondition"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("Grounding"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e.push(new Rr.Triple(_e.Namespace.EXOCMD.term("CommandBinding"),_e.Namespace.RDFS.term("subClassOf"),_e.Namespace.EXO.term("Asset"))),e}generatePropertyHierarchyTriples(){let e=[];return e.push(new Rr.Triple(_e.Namespace.EXO.term("Instance_class"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDF.term("type"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Asset_isDefinedBy"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("isDefinedBy"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Class_superClass"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("subClassOf"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_range"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("range"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_domain"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("domain"))),e.push(new Rr.Triple(_e.Namespace.EXO.term("Property_superProperty"),_e.Namespace.RDFS.term("subPropertyOf"),_e.Namespace.RDFS.term("subPropertyOf"))),e}generateMappedTriple(e,t,n){let i=this.propertyMappings.get(t);if(!i)return null;let s;if(n instanceof kD.IRI)s=n;else{let o=n.match(/^(ems|exo|exocmd)__(.+)$/);if(o){let[,c,l]=o;s=(c==="ems"?_e.Namespace.EMS:c==="exocmd"?_e.Namespace.EXOCMD:_e.Namespace.EXO).term(l)}else s=new kD.IRI(n)}return new Rr.Triple(e,i,s)}hasMappingFor(e){return this.propertyMappings.has(e)}};k0.RDFVocabularyMapper=_T});var M0=v(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.OBSIDIAN_VAULT_SCHEME=void 0;Jo.vaultPathToIRI=Qz;Jo.iriToVaultPath=Xz;Jo.OBSIDIAN_VAULT_SCHEME="obsidian://vault/";function Qz(r){let e=r.startsWith("./")?r.slice(2):r;return`${Jo.OBSIDIAN_VAULT_SCHEME}${encodeURI(e)}`}a(Qz,"vaultPathToIRI");function Xz(r){if(!r.startsWith(Jo.OBSIDIAN_VAULT_SCHEME))return null;let e=r.slice(Jo.OBSIDIAN_VAULT_SCHEME.length);try{return decodeURI(e)}catch{return null}}a(Xz,"iriToVaultPath")});var $0=v(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});Kp.derivePath=MD;Kp.deriveUrl=Jz;Kp.deriveLegacyFlatPath=Zz;var ST="assetspaces",j0=/^[A-Za-z0-9._-]+$/;function MD(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0||/^file:\/\//i.test(e))return null;e=e.replace(/\/+$/,""),e=e.replace(/\.git$/i,"");let t=null;if(!e.includes("://")){let o=/^[^/@\s]+@[^/:\s]+:(.+)$/.exec(e);o&&(t=o[1])}if(t===null){let o=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");o=o.replace(/^[^/@]+@/,"");let c=o.indexOf("/");if(c<0)return null;t=o.slice(c+1)}let n=t.split("/").filter(o=>o.length>0);if(n.length<2)return null;let i=n[0],s=n[1];return i==="."||i===".."||s==="."||s===".."||!j0.test(i)||!j0.test(s)?null:`${ST}/${i}/${s}`}a(MD,"derivePath");function Jz(r){if(typeof r!="string")return null;let e=r.trim();if(e.length===0)return null;e=e.replace(/^\/+/,"").replace(/\/+$/,"");let t=`${ST}/`;if(!e.startsWith(t))return null;let n=e.slice(t.length).split("/").filter(o=>o.length>0);if(n.length<2)return null;let i=n[0],s=n[1];return i==="."||i===".."||s==="."||s===".."||!j0.test(i)||!j0.test(s)?null:`https://github.com/${i}/${s}`}a(Jz,"deriveUrl");function Zz(r){let e=MD(r);if(e===null)return null;let t=e.split("/")[2];if(t===void 0||t.length===0)return null;let n=t.startsWith("exoas-")?t.slice(6):t;return n.length===0?null:`${ST}/${n}`}a(Zz,"deriveLegacyFlatPath")});var U0=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.FILE_SPACE_CLASS_UID=void 0;hs.frontmatterDeclaresFileSpace=tK;hs.discoverFileSpaceExclusions=nK;var eK=$0();hs.FILE_SPACE_CLASS_UID="aad8913e-5e9f-4047-879d-93cc46befd52";var jD=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,wT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function UD(r){let e=Array.isArray(r)?r:[r],t=[];for(let n of e){if(typeof n!="string")continue;jD.lastIndex=0;let i;for(;(i=jD.exec(n))!==null;)t.push(i[1].trim())}return t}a(UD,"wikilinkTargets");function tK(r){return r?UD(r.exo__Instance_class).some(e=>wT.test(e)&&e.toLowerCase()===hs.FILE_SPACE_CLASS_UID):!1}a(tK,"frontmatterDeclaresFileSpace");function $D(r,e){try{return r.getFrontmatter(e)}catch{return null}}a($D,"readFrontmatterSafe");function rK(r){let e=r.exo__AssetSpace_source;if(typeof e=="string"&&e.length>0)return e;let t=r.exo__AssetSpace_git;return typeof t=="string"&&t.length>0?t:null}a(rK,"readSource");function nK(r){let e=[],t=[],n=[],i=new Map,s=a((c,l)=>{if(wT.test(c))return c.toLowerCase()===hs.FILE_SPACE_CLASS_UID;let u=r.getFirstLinkpathDest(c,l);if(u==null)return!1;let f=i.get(u.path);if(f!==void 0)return f;let p=$D(r,u)?.exo__Asset_uid,h=typeof p=="string"&&p.toLowerCase()===hs.FILE_SPACE_CLASS_UID;return i.set(u.path,h),h},"isFileSpaceClassRef"),o=a(c=>c.some(l=>wT.test(l)&&l.toLowerCase()===hs.FILE_SPACE_CLASS_UID),"hasUuidFormRef");for(let c of r.getAllFiles()){let l=$D(r,c);if(!l)continue;let u=UD(l.exo__Instance_class);if(!u.some(h=>s(h,c.path)))continue;t.push(c.path),o(u)||n.push(`FileSpace declaration ${c.path} references the class via a label-form link only \u2014 the sync layer will not pick it up; use the UUID-form wikilink [[${hs.FILE_SPACE_CLASS_UID}]] (UID-canon)`);let f=rK(l);if(f===null){n.push(`FileSpace declaration ${c.path} has no exo__AssetSpace_source/_git \u2014 mount path underivable, content NOT excluded from the index`);continue}let d=(0,eK.derivePath)(f);if(d===null){n.push(`FileSpace declaration ${c.path}: cannot derive mount path from source "${f}" \u2014 content NOT excluded from the index`);continue}let p=`${d}/`;c.path.startsWith(p)&&n.push(`FileSpace declaration ${c.path} lies INSIDE its own mount ${p} \u2014 it will be excluded from the index together with the content; move the declaration outside the mount folder`),e.push(p)}return{prefixes:e,declarationPaths:t,warnings:n}}a(nK,"discoverFileSpaceExclusions")});var vl=v(Br=>{"use strict";var iK=Br&&Br.__decorate||function(r,e,t,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,e,t,n);else for(var c=r.length-1;c>=0;c--)(o=r[c])&&(s=(i<3?o(s):i>3?o(e,t,s):o(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s},sK=Br&&Br.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},BD=Br&&Br.__param||function(r,e){return function(t,n){e(t,n,r)}},TT;Object.defineProperty(Br,"__esModule",{value:!0});Br.NoteToRDFConverter=Br.UNPREFIXED_ASSET_FIELDS=void 0;Br.canonicalYamlKey=uK;Br.normaliseExcludedFolders=qD;Br.isPathExcluded=WD;var ET=at(),Cr=hi(),ms=Le(),Cn=Ye(),VD=rr(),dr=Yt(),GD=Qn(),oK=bT(),aK=Dp(),vT=M0(),Si=tv(),cK=U0();Br.UNPREFIXED_ASSET_FIELDS=new Set(["archived","draft","pinned","aliases"]);var lK=/^exo__Asset_(.+)$/;function uK(r){let e=lK.exec(r);return e&&Br.UNPREFIXED_ASSET_FIELDS.has(e[1])?e[1]:r}a(uK,"canonicalYamlKey");function qD(r){return Array.isArray(r)?r.map(e=>String(e).replace(/\\/g,"/").trim()).filter(e=>e.length>0).map(e=>e.endsWith("/")?e:`${e}/`):[]}a(qD,"normaliseExcludedFolders");function WD(r,e){if(e.length===0)return!1;let t=r.replace(/\\/g,"/");for(let n of e)if(t.startsWith(n))return!0;return!1}a(WD,"isPathExcluded");function fK(r){if(!r)return"";let e=r.replace(/\\/g,"/");for(;e.startsWith("/");)e=e.slice(1);for(;e.endsWith("/");)e=e.slice(0,-1);return e.length>0?`${e}/`:""}a(fK,"normaliseSubjectIriPrefix");var El=TT=class{static{a(this,"NoteToRDFConverter")}constructor(e,t=aK.NullLogger,n={}){this.vault=e,this.logger=t,this.BODY_WIKILINK_PATTERN=/(?<!!)\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,this.pendingExtraTriples=[],this.preResolvedTargetFm=new Map,this.vocabularyMapper=new oK.RDFVocabularyMapper,this.subjectIriPrefix=fK(n.subjectIriPrefix),this.emitInstanceClassAsUid=n.emitInstanceClassAsUid??!1}async convertNote(e){let t=this.vault.getFrontmatterWithFallback?await this.vault.getFrontmatterWithFallback(e):this.vault.getFrontmatter(e);return this.convertNoteFromFrontmatter(e,t)}async convertNoteFromFrontmatter(e,t){if(!t)return[];await this.preResolveWikilinkTargets(t);let n=this.notePathToIRI(e.path),i=dr.Namespace.EXO.term("Asset_filename"),s=new Cr.Triple(n,i,new Cn.Literal(e.basename));if(Si.Exo003Parser.isExo003Format(t)){let o=await this.convertExo003Note(e,t);return[s,...o]}return this.convertLegacyNote(e,t,s)}async convertLegacyNote(e,t,n){this.pendingExtraTriples=[];let i=[n],s=this.notePathToIRI(e.path),o,c,l,u=!1,f=dr.Namespace.EXO.term("Statement").value;for(let[y,_]of Object.entries(t)){let b=Br.UNPREFIXED_ASSET_FIELDS.has(y)?`exo__Asset_${y}`:y;if(!this.isExocortexProperty(b))continue;let T=this.propertyKeyToIRI(b),I=Array.isArray(_)?_:[_];for(let E of I)if(!((y==="exo__Asset_label"||Br.UNPREFIXED_ASSET_FIELDS.has(y))&&(E==null||typeof E=="string"&&E.trim()==="")))if(y==="exo__Instance_class"){let S=this.valueToClassURI(E);i.push(new Cr.Triple(s,T,S))}else{let S=await this.valueToRDFObject(E,e,T);if(b==="exo__Statement_subject"&&o===void 0){let R=S.find(D=>D instanceof ms.IRI);R&&(o=R)}else if(b==="exo__Statement_predicate"&&c===void 0){let R=S.find(D=>D instanceof ms.IRI);R&&(c=R)}else b==="exo__Statement_object"&&l===void 0&&(l=S[0]);for(let R of S)if(i.push(new Cr.Triple(s,T,R)),this.vocabularyMapper.hasMappingFor(y)&&R instanceof ms.IRI){let D=this.vocabularyMapper.generateMappedTriple(s,y,R);D&&i.push(D)}}if(y==="exo__Instance_class")for(let E of I){let S=this.valueToClassURI(E);if(S instanceof ms.IRI){let R=dr.Namespace.RDF.term("type");i.push(new Cr.Triple(s,R,S)),S.value===f&&(u=!0)}}if(y==="exo__Asset_label"){let E=dr.Namespace.RDFS.term("label");for(let S of I)typeof S=="string"&&S.length>0&&i.push(new Cr.Triple(s,E,new Cn.Literal(S)))}}let d="exo__Instance_class"in t||"exo__Asset_uid"in t,p=t.exo__Asset_label,h="exo__Asset_label"in t&&p!==null&&p!==void 0&&!(typeof p=="string"&&p.trim()==="")&&!(Array.isArray(p)&&p.length===0);if(d&&!h){let y=dr.Namespace.RDFS.term("label"),_=dr.Namespace.EXO.term("Asset_label"),b=new Cn.Literal(e.basename);i.push(new Cr.Triple(s,y,b)),i.push(new Cr.Triple(s,_,b))}i.push(...this.pendingExtraTriples),this.pendingExtraTriples=[],u&&o&&c&&l&&i.push(new Cr.Triple(o,c,l));let m=await this.convertBodyWikilinks(e,s);return i.push(...m),i}async convertExo003Note(e,t){let n=Si.Exo003Parser.parse(t);if(!n.success||!n.metadata)return[];let i=n.metadata,s=[];switch(i.metadata){case Si.Exo003MetadataType.Namespace:break;case Si.Exo003MetadataType.Anchor:s.push(...this.convertExo003Anchor(e,i));break;case Si.Exo003MetadataType.BlankNode:s.push(...this.convertExo003BlankNode(e,i));break;case Si.Exo003MetadataType.Statement:s.push(...this.convertExo003Statement(e,i));break;case Si.Exo003MetadataType.Body:s.push(...await this.convertExo003Body(e,i));break}return s}convertExo003Anchor(e,t){let n=this.notePathToIRI(e.path),i=new ms.IRI(t.uri);return[new Cr.Triple(n,dr.Namespace.OWL.term("sameAs"),i),new Cr.Triple(i,dr.Namespace.OWL.term("sameAs"),n)]}convertExo003BlankNode(e,t){let n=this.notePathToIRI(e.path),i=t.uri.replace(/[^a-zA-Z0-9_-]/g,"_");return[new Cr.Triple(n,dr.Namespace.OWL.term("sameAs"),new VD.BlankNode(i))]}convertExo003Statement(e,t){let n=[];try{let i=this.createExo003ReferenceResolver(e),s=Si.Exo003Parser.toTriple(t,i);n.push(s);let o=this.notePathToIRI(e.path);n.push(new Cr.Triple(o,dr.Namespace.RDF.term("value"),s.subject))}catch{}return n}async convertExo003Body(e,t){let n=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),o=this.createExo003ReferenceResolver(e),c=o(t.subject),l=o(t.predicate);if(c.type==="literal")throw new Error("Body subject cannot be a literal");if(l.type!=="iri")throw new Error("Body predicate must be an IRI");let u=c.type==="iri"?new ms.IRI(c.value):new VD.BlankNode(c.value),f=new ms.IRI(l.value),d=Si.Exo003Parser.toLiteral(t,s.trim());n.push(new Cr.Triple(u,f,d));let p=this.notePathToIRI(e.path);n.push(new Cr.Triple(p,dr.Namespace.RDF.term("value"),u))}catch{}return n}createExo003ReferenceResolver(e){return t=>{let n=this.extractWikilink(t),i=n||t,s=this.vault.getFirstLinkpathDest(i,e.path);if(s){let o=this.targetFrontmatter(s);if(o&&Si.Exo003Parser.isExo003Format(o)){let c=Si.Exo003Parser.parse(o);if(c.success&&c.metadata){let l=c.metadata;if(l.metadata===Si.Exo003MetadataType.Anchor||l.metadata===Si.Exo003MetadataType.Namespace)return{type:"iri",value:l.uri};if(l.metadata===Si.Exo003MetadataType.BlankNode)return{type:"blank",value:l.uri.replace(/[^a-zA-Z0-9_-]/g,"_")}}}return{type:"iri",value:this.notePathToIRI(s.path).value}}return!n&&t.includes("://")?{type:"iri",value:t}:{type:"literal",value:t}}}async convertVault(e={}){return(await this.convertVaultWithValidation({strict:!1,excludedFolders:e.excludedFolders})).triples}async convertVaultWithValidation(e={}){let t=this.vault.getAllFiles(),n=[],i=[],s=e.strict??!1,o=0,c=0,l=(0,cK.discoverFileSpaceExclusions)(this.vault);for(let y of l.warnings)this.logger.warn(`FileSpace discovery: ${y}`);let u=[...qD(e.excludedFolders),...l.prefixes],f=u.length===0?t:t.filter(y=>!WD(y.path,u)),d=e.onProgress,p=e.progressIntervalFiles&&e.progressIntervalFiles>0?e.progressIntervalFiles:TT.INDEX_PROGRESS_INTERVAL,h=f.length,m=0;for(let y of f){if(m++,d&&m%p===0&&m<h)try{d(m,h)}catch{}try{let _=this.vault.getFrontmatter(y),b=_?this.validateExocortexAsset(_,y.basename):null;if(b){if(s)throw new Error(`Invariant violation in "${y.path}": ${b.message}`);i.push({path:y.path,reason:`Invariant violation: ${b.message}`}),o++,this.logger.info(`Skipping file with invariant violation: ${y.path}`,{code:b.code,property:b.property,reason:b.message});continue}let T=await this.convertNote(y);n.push(...T)}catch(_){let b=_ instanceof Error?_.message:String(_);if(s)throw new Error(`Invalid IRI for file "${y.path}": ${b}`);i.push({path:y.path,reason:`Invalid IRI: ${b}`}),c++,this.logger.info(`Skipping file with invalid IRI: ${y.path}`,{reason:b})}}return o>0&&this.logger.warn(`Skipped ${o} file${o===1?"":"s"} with invariant violations during indexing (paths in developer console)`,{count:o}),c>0&&this.logger.warn(`Skipped ${c} file${c===1?"":"s"} with invalid IRI during indexing (paths in developer console)`,{count:c}),{triples:n,skippedFiles:i,summary:{total:f.length,indexed:f.length-i.length,skipped:i.length},fileSpaces:l}}static inferLabelFromBasename(e){return dr.Namespace.fromPropertyKey(e)!==null?e:null}validateExocortexAsset(e,t){let n=a(d=>d==null?!0:typeof d=="string"?d.trim()==="":Array.isArray(d)?d.length===0||d.every(n):!1,"isEmpty");if(!("exo__Instance_class"in e||"exo__Asset_uid"in e))return null;let s=["exo__Asset_uid","exo__Instance_class"];for(let d of s){if(!(d in e))return{code:"MISSING_PROPERTY",property:d,message:`Required property "${d}" is missing`};if(n(e[d]))return{code:"EMPTY_PROPERTY",property:d,message:`Required property "${d}" is empty`}}let o=["ems__Effort_status","ems__Effort_parent","ems__Effort_lockedBy","ems__Effort_lockExpires","exo__Asset_updatedAt","ems__Effort_startTimestamp"];for(let d of o)if(d in e&&n(e[d]))return{code:"EMPTY_OPTIONAL_PROPERTY",property:d,message:`Optional property "${d}" is present but empty`};let c=e.exo__Instance_class,l=Array.isArray(c)?c:[c],u=null,f=!1;for(let d of l){if(typeof d!="string")continue;let p=this.removeQuotes(d),m=(this.extractWikilink(p)??p).trim();/^[a-z][a-zA-Z0-9]*__/.test(m)&&/[\s()]/.test(m)?u||(u={candidate:d}):f=!0}return u&&!f?{code:"INVALID_INSTANCE_CLASS_IRI",property:"exo__Instance_class",message:`Invalid Instance_class IRI: "${u.candidate}"`}:null}async validateVault(){let e=this.vault.getAllFiles(),t=[];for(let n of e){let i=(0,vT.vaultPathToIRI)(n.path);ms.IRI.isValidIRI(i)||t.push({path:n.path,reason:`Path "${n.path}" cannot be converted to a valid IRI`})}return t}notePathToIRI(e){return new ms.IRI((0,vT.vaultPathToIRI)(`${this.subjectIriPrefix}${e}`))}synthesizeWikilinkTargetIRI(e){return new ms.IRI((0,vT.vaultPathToIRI)(e))}isExocortexProperty(e){return dr.Namespace.fromPropertyKey(e)!==null}propertyKeyToIRI(e){let t=dr.Namespace.fromPropertyKey(e);if(!t)throw new Error(`Invalid property key: ${e}`);return t.namespace.term(t.localName)}emitTypeTripleForEnumInstance(e,t){let n=this.targetFrontmatter(t);if(!n)return;let i=n.exo__Instance_class,s=Array.isArray(i)?i[0]:i;if(typeof s!="string")return;let o=this.valueToClassURI(s);o instanceof ms.IRI&&(this.pendingExtraTriples.push(new Cr.Triple(e,dr.Namespace.RDF.term("type"),o)),this.pendingExtraTriples.push(new Cr.Triple(e,dr.Namespace.EXO.term("Instance_class"),o)))}async valueToRDFObject(e,t,n){if(typeof e=="string"){let i=this.removeQuotes(e);if(n?.value.endsWith("#TokenInvocation_parameter"))return[new Cn.Literal(i)];let s=this.extractWikilink(i);if(s){let o=this.vault.getFirstLinkpathDest(s,t.path);if(o){let l=this.notePathToIRI(o.path),u=s.includes("|")?s.split("|")[0]:s;if(this.isUUID(u)){let d=new Cn.Literal(u);if(n?.value.endsWith("#Grounding_targetValueRef")||n?.value.endsWith("#Grounding_targetValueSubstitution")||n?.value.endsWith("#Grounding_targetClass")||n?.value.endsWith("#Grounding_type")||n?.value.endsWith("#PropertyDefault_value"))return[l];let h=this.expandClassValue(o.basename);if(h)return this.emitTypeTripleForEnumInstance(h,o),[h];let m=this.targetFrontmatter(o);if(m){let I=m.exo__Asset_label;if(typeof I=="string"){let E=this.expandClassValue(I);if(E)return this.emitTypeTripleForEnumInstance(E,o),[E]}}let y=n?.value.endsWith("#Asset_prototype")||n?.value.endsWith("/Asset_prototype"),b=((typeof process<"u"?process.env:void 0)?.EXOCORTEX_DUAL_STORAGE_PREDICATES??"").split(",").map(I=>I.trim()).filter(Boolean),T=b.length>0&&b.some(I=>n?.value.endsWith(`#${I}`));return y||T?[l,d]:[l]}let f=this.expandClassValue(o.basename);return f?(this.emitTypeTripleForEnumInstance(f,o),[f]):[l]}if(this.isClassReference(s)){let l=this.expandClassValue(s);if(l)return[l]}let c=s.includes("|")?s.split("|")[0]:s;return this.isUUID(c)?[this.synthesizeWikilinkTargetIRI(`${c}.md`)]:[new Cn.Literal(i)]}if(this.isClassReference(i)){let o=this.expandClassValue(i);if(o)return[o]}return this.isISO8601DateTime(i)?[new Cn.Literal(i,dr.Namespace.XSD.term("dateTime"))]:[new Cn.Literal(i)]}return typeof e=="boolean"?[new Cn.Literal(e.toString())]:typeof e=="number"?[new Cn.Literal(e.toString(),dr.Namespace.XSD.term("decimal"))]:e instanceof Date?[new Cn.Literal(e.toISOString(),dr.Namespace.XSD.term("dateTime"))]:[new Cn.Literal(String(e))]}isISO8601DateTime(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})?$/.test(e)}removeQuotes(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.substring(1,t.length-1):e}extractWikilink(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let n=t[1];return n.includes("|")?n.split("|")[0]:n}extractWikilinkAlias(e){let t=e.match(/^\[\[([^\]]+)\]\]$/);if(!t)return null;let n=t[1],i=n.indexOf("|");return i>=0?n.substring(i+1).trim():null}targetFrontmatter(e){return this.vault.getFrontmatter(e)??this.preResolvedTargetFm.get(e.path)??null}async preResolveWikilinkTargets(e){let t=this.vault.getFrontmatterWithFallback;if(t)for(let n of Object.values(e)){let i=Array.isArray(n)?n:n==null?[]:[n];for(let s of i){if(typeof s!="string")continue;let o=this.removeQuotes(s),c=this.extractWikilink(o);if(!c||!this.isUUID(c))continue;let l=this.vault.getFirstLinkpathDest(c,"");!l||this.preResolvedTargetFm.has(l.path)||this.vault.getFrontmatter(l)||this.preResolvedTargetFm.set(l.path,await t.call(this.vault,l))}}}valueToClassURI(e){if(typeof e!="string")return new Cn.Literal(String(e));let t=this.removeQuotes(e),i=this.extractWikilink(t)||t,s=this.expandClassValue(i);if(s)return s;let o=this.extractWikilinkAlias(t);if(o){let c=this.expandClassValue(o);if(c)return c}if(this.isUUID(i)){let c=this.vault.getFirstLinkpathDest(i,"");if(c){let l=this.expandClassValue(c.basename);if(l)return this.emitInstanceClassAsUid?this.notePathToIRI(c.path):l;let u=this.targetFrontmatter(c);if(u){let f=u.exo__Asset_label;if(typeof f=="string"){let d=this.expandClassValue(f);if(d)return this.emitInstanceClassAsUid?this.notePathToIRI(c.path):d}}return this.notePathToIRI(c.path)}}return new Cn.Literal(t)}isClassReference(e){return/\s/.test(e)?!1:dr.Namespace.fromPropertyKey(e)!==null}isUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}expandClassValue(e){let t=this.removeQuotes(e),n=dr.Namespace.fromPropertyKey(t);return!n||/[\s()]/.test(n.localName)?null:n.namespace.term(n.localName)}extractBodyContent(e){let t=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;return e.replace(t,"")}extractBodyWikilinks(e){let t=new Set,n,i=new RegExp(this.BODY_WIKILINK_PATTERN.source,"g");for(;(n=i.exec(e))!==null;)n[1]&&t.add(n[1]);return Array.from(t)}async convertBodyWikilinks(e,t){let n=[];try{let i=await this.vault.read(e),s=this.extractBodyContent(i),o=this.extractBodyWikilinks(s),c=dr.Namespace.EXO.term("Asset_bodyLink");for(let l of o){let u=this.vault.getFirstLinkpathDest(l,e.path);if(u){let f=this.notePathToIRI(u.path);n.push(new Cr.Triple(t,c,f))}else if(this.isClassReference(l)){let f=this.expandClassValue(l);f?n.push(new Cr.Triple(t,c,f)):n.push(new Cr.Triple(t,c,new Cn.Literal(l)))}else n.push(new Cr.Triple(t,c,new Cn.Literal(l)))}}catch{}return n}};Br.NoteToRDFConverter=El;El.INDEX_PROGRESS_INTERVAL=200;El.SkippedFileInfo=class{constructor(r,e){this.path=r,this.reason=e}};El.VaultValidationResult=class{constructor(r,e,t){this.triples=r,this.skippedFiles=e,this.summary=t}};El.VaultValidationOptions=class{constructor(r=!1){this.strict=r}};Br.NoteToRDFConverter=El=TT=iK([(0,ET.injectable)(),BD(0,(0,ET.inject)(GD.DI_TOKENS.IVaultAdapter)),BD(1,(0,ET.inject)(GD.DI_TOKENS.ILogger)),sK("design:paramtypes",[Object,Object,Object])],El)});var Tl=v(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});B0.FrontmatterService=void 0;var HD=L0(),AT=Cu(),IT=vl(),Yp=class r{static{a(this,"FrontmatterService")}parse(e){let t=e.match(r.FRONTMATTER_REGEX);return t?{exists:!0,content:t[1],originalContent:e}:{exists:!1,content:"",originalContent:e}}parseObject(e){let t=this.parse(e);if(!t.exists)return null;let n={},i=t.content.split(/\r?\n/),s=null,o=null,c=a(()=>{s!==null&&o!==null&&(n[s]=o),s=null,o=null},"flushArray");for(let l of i){let u=/^ {2}- (.*)$/.exec(l);if(u){s!==null&&o!==null&&o.push(u[1].trim());continue}c();let f=/^([^:\s][^:]*):\s*(.*)$/.exec(l);if(!f)continue;let d=f[1].trim(),p=f[2].trim();p===""?(s=d,o=[]):n[d]=p}return c(),n}updateProperty(e,t,n){t=(0,IT.canonicalYamlKey)(r.normalizeIRI(t)),typeof n=="string"&&(n=r.normalizeIRIValue(n));let i=this.parse(e),s=this.serializeValue(t,n);if(!i.exists)return`---
|
|
73
73
|
${s}
|
|
74
74
|
---
|
|
75
75
|
${e}`;let o=i.content,c=o.split(`
|
|
@@ -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.7"),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.7")),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