@kitelev/exocortex-cli 17.5.10 → 17.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +3 -3
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // @kitelev/exocortex-cli v17.5.10
2
+ // @kitelev/exocortex-cli v17.5.12
3
3
  // CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more
4
4
  // License: MIT
5
5
 
@@ -143,7 +143,7 @@ ${c}`}let o=n?(0,Zb.serializeYamlScalar)(t,s,i):String(t);return`${e}: ${o}`}esc
143
143
  Stack trace:
144
144
  ${t.stack}`:"";console.error(`[Exocortex ERROR]${s} ${e}${o}`,t??"")}else{let o=t?.message?`
145
145
  Details: ${t.message}`:"";console.error(`[Exocortex ERROR]${s} ${e}${o}`)}}};t_.LoggingService=Vh;Vh.isVerbose=!1;Vh.isDevelopment=void 0});var DI=T(r_=>{"use strict";Object.defineProperty(r_,"__esModule",{value:!0});r_.CLASS_UID_TO_LABEL=void 0;var FI=vl();r_.CLASS_UID_TO_LABEL=Object.freeze({"1b20a8f0-d745-4e93-91db-4531b3df120e":FI.AssetClass.TASK,"7db5eeff-718a-49b0-8d2b-39b084a356e3":FI.AssetClass.PROJECT,"1b0a5e34-dd7f-4ead-b43a-6c7c5a5ecaca":FI.AssetClass.MEETING})});var jM=T(vr=>{"use strict";var Uee=vr&&vr.__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},Bee=vr&&vr.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},Vt;Object.defineProperty(vr,"__esModule",{value:!0});vr.GroundingExecutor=vr.ServiceRegistry=vr.CLASS_UID_TO_LABEL=vr.STATUS_UID_BY_ENUM=void 0;vr.missingInputHint=kI;vr.missingInputError=kM;vr.findMissingInput=Jee;vr.missingRequiredInputError=MM;vr.findInputSchemaViolation=ete;var Vee=lt(),Gee=Mh(),qee=$b(),Un=uc(),Wee=vI(),zee=Ul(),NM=tf(),Hee=De(),LI=eu(),$n=gc(),Jf=Zl(),Kee=tu(),Yee=yc(),OM=Yb(),Gh=Ts(),PM=Fh(),Rs=ru();vr.STATUS_UID_BY_ENUM=NM.EFFORT_STATUS_UID;var Xee=DI();Object.defineProperty(vr,"CLASS_UID_TO_LABEL",{enumerable:!0,get:a(function(){return Xee.CLASS_UID_TO_LABEL},"get")});var NI=Vb();(0,NI.installDefaultResolvers)();function Qee(r){if(r){if(r==="1b20a8f0-d745-4e93-91db-4531b3df120e")return"ems__Task";if(r==="7db5eeff-718a-49b0-8d2b-39b084a356e3")return"ems__Project";if(r==="ems__Task"||r==="ems__Project")return r}}a(Qee,"resolveClassFlipTarget");function kI(r,e){let t=e??{},n=a(c=>c!=null,"isProvided"),i=[...r.matchAll(/\$input\.([A-Za-z_]\w*)/g)].map(c=>c[1]),s=/\$input\b(?!\.)/.test(r)||/\$value\b/.test(r),o=i.find(c=>!n(t[c]));return o!==void 0?`--input '{"${o}":...}'`:s&&!n(t.value)?`--input '{"value":...}'`:null}a(kI,"missingInputHint");function kM(r){return`property_set: value template references an input that was not provided (${r} required)`}a(kM,"missingInputError");function Jee(r,e){let t=a(i=>{if(i.type===Un.GroundingType.PROPERTY_SET){if(i.targetValueRef!==void 0)return`"[[${i.targetValueRef}]]"`;if(i.targetValueLiteral!==void 0)return i.targetValueLiteral;if(i.targetValueSubstitution!==void 0)return i.targetValueSubstitution}},"staticTemplate"),n=a(i=>{let s=t(i);if(s!==void 0){let o=kI(s,e);if(o!==null)return o}for(let o of i.steps??[]){let c=n(o);if(c!==null)return c}return null},"visit");return n(r)}a(Jee,"findMissingInput");var Zee="label";function MM(r){return`input_schema: required input "${r}" was not provided and no declared source supplies it (--input '{"${r}":...}' required)`}a(MM,"missingRequiredInputError");function ete(r,e){let t=[],n=new Set,i=a(l=>{for(let u of l.inputSchema??[])n.has(u.name)||(n.add(u.name),t.push(u));for(let u of l.steps??[])i(u)},"collect");if(i(r),t.length===0)return null;let s=e??{},o=a(l=>l!=null&&!(typeof l=="string"&&l.trim().length===0),"isSupplied"),c=a(l=>{let u=(0,Jf.canonicalYamlKey)(l),f=l===Zee,d=a(h=>{if(h.serviceCallPayload===void 0)return!1;try{let g=JSON.parse(h.serviceCallPayload);return typeof g=="object"&&g!==null&&!Array.isArray(g)&&Object.prototype.hasOwnProperty.call(g,l)}catch{return!1}},"payloadSupplies"),p=a(h=>f&&(h.labelTemplate!==void 0||h.omitLabel)||!f&&(h.propertyDefault??[]).some(g=>(0,Jf.canonicalYamlKey)(g.propertyName)===u)||!f&&(h.inheritanceRule??[]).some(g=>(0,Jf.canonicalYamlKey)(g.targetPropertyName)===u)||l==="isDefinedBy"&&h.isDefinedBy!==void 0||d(h)?!0:(h.steps??[]).some(p),"visit");return p(r)},"hasDeclaredSource");for(let l of t)if(l.required===!0&&!o(s[l.name])&&!o(l.defaultValue)&&!c(l.name))return MM(l.name);return null}a(ete,"findInputSchemaViolation");var tte=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,FM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,rte=/^__SUBSTITUTE__([a-zA-Z][a-zA-Z0-9_]*)__[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/,DM=/^__SUBSTITUTE_P__([a-zA-Z][a-zA-Z0-9_]*)__[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__([A-Za-z0-9_-]*)__$/,n_=class{static{a(this,"ServiceRegistry")}constructor(){this.services=new Map}register(e,t){this.services.set(e,t)}get(e){return this.services.get(e)}has(e){return this.services.has(e)}getRegisteredIds(){return Array.from(this.services.keys())}};vr.ServiceRegistry=n_;var LM=20;function nte(r){return/^\[\[[\s\S]*\]\]$/.test(r.trim())}a(nte,"isUnquotedWikilink");var Zf=Vt=class{static{a(this,"GroundingExecutor")}constructor(e,t,n,i,s){this.frontmatterService=new LI.FrontmatterService,this.fileReader=e,this.fileWriter=t,this.serviceRegistry=n,this.classLabelToUid=i,this.refToFolder=s?.refToFolder,this.refToFrontmatter=s?.refToFrontmatter,this.workflowResolver=s?.workflowResolver,this.groundingLoader=s?.groundingLoader,this.templateLoader=s?.templateLoader,this.namedQueryRunner=s?.namedQueryRunner,this.declaredRanges=s?.declaredRanges,this.clock=s?.clock??(0,Gee.liveClock)(),this.uidGen=s?.uidGenerator??(0,qee.liveUidGenerator)()}async execute(e,t,n,i,s){try{switch(e.type){case Un.GroundingType.PROPERTY_SET:return await this.executePropertySet(e,t,n,i);case Un.GroundingType.PROPERTY_DELETE:return await this.executePropertyDelete(e,n);case Un.GroundingType.PROPERTY_REPLACE:return await this.executePropertyReplace(e,t,n,i);case Un.GroundingType.COMPOSITE:return await this.executeComposite(e,t,n,i,0,s);case Un.GroundingType.SERVICE_CALL:return await this.executeServiceCall(e,t,n,i);case Un.GroundingType.CREATE_INSTANCE:return await this.executeCreateInstance(e,t,n,i,s);case Un.GroundingType.PROPERTY_APPEND:return await this.executePropertyAppend(e,t,n,i);case Un.GroundingType.PROPERTY_INCREMENT:return await this.executePropertyIncrement(e,n);case Un.GroundingType.PROPERTY_SHIFT:return await this.executePropertyShift(e,n);case Un.GroundingType.SPARQL_UPDATE:return{success:!1,error:"sparql_update grounding not yet implemented. Use property_set/property_delete instead."};case Un.GroundingType.WORKFLOW_TRANSITION:return await this.executeWorkflowTransition(e,t,n,i,s);case Un.GroundingType.BODY_TEMPLATE:return await this.executeBodyTemplate(e,t,n,i);default:return{success:!1,error:`Unknown grounding type: ${e.type}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}stampUpdatedAt(e,t,n){return t===e||n!==void 0&&(0,Jf.canonicalYamlKey)(LI.FrontmatterService.normalizeIRI(n))==="exo__Asset_updatedAt"||!this.frontmatterService.parse(t).exists?t:this.frontmatterService.updateProperty(t,"exo__Asset_updatedAt",Gh.DateFormatter.toLocalTimestamp(this.clock.now()))}async executePropertySet(e,t,n,i){if(!e.targetProperty)return{success:!1,error:"property_set requires targetProperty"};if(e.targetQuery!==void 0&&e.targetsCreatedInstance===!0)return{success:!1,error:"property_set: targetQuery and targetsCreatedInstance are mutually exclusive (both address the step's TARGET \u2014 pick one)."};let s;if([e.targetValueRef!==void 0,e.targetValueLiteral!==void 0,e.targetValueSubstitution!==void 0,e.targetValueQuery!==void 0].filter(Boolean).length>1)return{success:!1,error:"property_set: more than one of targetValueRef/targetValueLiteral/targetValueSubstitution/targetValueQuery set (cardinality 0..1 each, mutually exclusive)"};if(e.targetValueRef!==void 0)s=`"[[${e.targetValueRef}]]"`;else if(e.targetValueLiteral!==void 0)s=e.targetValueLiteral;else if(e.targetValueSubstitution!==void 0)s=e.targetValueSubstitution;else if(e.targetValueQuery!==void 0){let A=await this.resolveTargetValueQuery(e.targetValueQuery,t);if(!A.success)return A;s=A.value}else return{success:!1,error:"property_set requires one of targetValueRef/targetValueLiteral/targetValueSubstitution/targetValueQuery"};let c=kI(s,i);if(c!==null)return{success:!1,error:kM(c)};let l=e.targetValueRef!==void 0&&/\$/.test(e.targetValueRef),u;if(l){let A=this.substituteVariables(e.targetValueRef,t,i),E=A.trim().replace(/^["']|["']$/g,"").replace(/^\[\[|\]\]$/g,""),w=/\[\[|\]\]/.test(E)?null:(0,Kee.extractAssetReference)(A)?.trim()||null;if(w===null)return{success:!1,error:`property_set: asset-reference value ${JSON.stringify(A)} for ${e.targetProperty} is not a single reference \u2014 pass a BARE uid (or one [[uid]] / [[uid|alias]] wikilink, which is unwrapped); nested brackets, a link inside prose or an empty value would be written as a broken link.`};u=`"[[${w}]]"`}else u=this.substituteVariables(s,t,i);let f=LI.FrontmatterService.normalizeIRI(e.targetProperty),d=(0,Jf.canonicalYamlKey)(f),p=(0,Yee.iriToObsidianName)(e.targetProperty)??f,h=this.declaredRanges?(await this.declaredRanges([p])).get(p):void 0,g=$n.STRING_SCALAR_PROPERTIES.has(d),m=(0,$n.scalarTypingForRange)(h)!==void 0?(0,$n.serializeYamlScalar)(u,g,h):g?(0,$n.serializeYamlScalar)(u,!0):u;if(nte(m))return{success:!1,error:`property_set: value ${m} is an UNQUOTED wikilink \u2014 YAML reads it as a flow sequence, so the graph would receive a literal instead of a link (silent data loss). Pass the QUOTED form for a substituted reference (the quotes are part of the string, e.g. --input '{"<key>":"\\"[[<uid>]]\\""}'), or use targetValueRef, which takes a BARE uid and wraps it itself.`};let b=n;if(e.targetQuery!==void 0){let A=await this.resolveTargetQuery(e.targetQuery,t);if(!A.success)return A;b=A.path}let _=await this.fileReader.readFile(b),S=this.stampUpdatedAt(_,this.frontmatterService.updateProperty(_,e.targetProperty,m),e.targetProperty);return await this.fileWriter.updateFile(b,S),{success:!0}}async resolveTargetQuery(e,t){if(!this.namedQueryRunner)return{success:!1,error:"property_set targetQuery requires NamedQueryRunner injection (options.namedQueryRunner). Wire the plugin/CLI before using this target-source."};let n;try{n=await this.namedQueryRunner.runScalar(e,{currentAsset:t})}catch(s){return{success:!1,error:`property_set targetQuery: NamedQuery '${e}' failed \u2014 ${s instanceof Error?s.message:String(s)}`}}if(n===null)return{success:!1,error:`property_set targetQuery: NamedQuery '${e}' matched no asset (empty result set) \u2014 refusing to fall back to the click-target.`};if(n.kind!=="iri")return{success:!1,error:`property_set targetQuery: NamedQuery '${e}' returned a literal ('${n.value}'), not an asset reference \u2014 a target must be an asset.`};if(n.iri===void 0)return{success:!1,error:`property_set targetQuery: NamedQuery '${e}' returned an asset reference without its source IRI, so its file path cannot be resolved.`};let i=(0,OM.iriToVaultPath)(n.iri);return i===null?{success:!1,error:`property_set targetQuery: NamedQuery '${e}' matched '${n.iri}', which is not a vault asset IRI (no resolvable file path).`}:{success:!0,path:i}}async resolveTargetValueQuery(e,t){if(!this.namedQueryRunner)return{success:!1,error:"property_set targetValueQuery requires NamedQueryRunner injection (options.namedQueryRunner). Wire the plugin/CLI before using this value-source."};let n;try{n=await this.namedQueryRunner.runScalar(e,{currentAsset:t})}catch(s){return{success:!1,error:`property_set targetValueQuery: NamedQuery '${e}' failed \u2014 ${s instanceof Error?s.message:String(s)}`}}return n===null?{success:!1,error:`property_set targetValueQuery: NamedQuery '${e}' returned no scalar value (empty result set or non-scalar shape).`}:{success:!0,value:n.kind==="iri"?`"[[${n.value}]]"`:n.value}}async executePropertyDelete(e,t){if(!e.targetProperty)return{success:!1,error:"property_delete requires targetProperty"};let n=await this.fileReader.readFile(t),i=this.stampUpdatedAt(n,this.frontmatterService.removeProperty(n,e.targetProperty),e.targetProperty);return await this.fileWriter.updateFile(t,i),{success:!0}}async executeComposite(e,t,n,i,s,o){if(s>=LM)return{success:!1,error:`Composite grounding exceeded maximum depth of ${LM}`};let c=e.steps??[];if(c.length===0)return{success:!0};let l;try{l=await this.fileReader.readFile(n)}catch{}let u=[],f,d=[];try{for(let p=0;p<c.length;p++){let h=c[p],m=(h.type===Un.GroundingType.BODY_TEMPLATE||h.targetsCreatedInstance===!0)&&f?f:n,b=await this.executeStep(h,t,m,i,s+1,f??o);if(!b.success)return await this.rollback(l,n,u,d),{success:!1,error:`Composite step ${p} failed: ${b.error}`};b.openPath&&(f=b.openPath),b.openPath&&d.push(b.openPath),b.createdPaths&&b.createdPaths.length>0&&d.push(...b.createdPaths),u.push(p)}return{success:!0,...d.length>0?{createdPaths:await this.resolveCreatedPaths(d)}:{}}}catch(p){return await this.rollback(l,n,u,d),{success:!1,error:`Composite execution failed: ${p instanceof Error?p.message:String(p)}`}}}async executeServiceCall(e,t,n,i){let s=e.targetProperty;if(!s)return{success:!1,error:"service_call requires targetProperty as serviceId"};if(e.targetQuery!==void 0&&e.targetsCreatedInstance===!0)return{success:!1,error:"service_call: targetQuery and targetsCreatedInstance are mutually exclusive (both address the step's TARGET \u2014 pick one)."};if(s==="convertToTask")return await this.executeConvertToTask(n);if(s==="updateProperty"){let f=Qee(e.targetValueRef);if(f==="ems__Task")return await this.executeConvertToTask(n);if(f==="ems__Project")return await this.executeConvertToProject(n)}let o=this.serviceRegistry.get(s);if(!o)return{success:!1,error:`Service not found: "${s}". Registered services: ${this.serviceRegistry.getRegisteredIds().join(", ")||"none"}`};let c=i;if(e.isDefinedBy&&(c={isDefinedBy:e.isDefinedBy,...c??{}}),e.serviceCallPayload)try{let f=this.substituteVariables(e.serviceCallPayload,t,i),d=JSON.parse(f);typeof d=="object"&&d!==null&&(c={...d,...c??{}})}catch{}let l=e.targetsCreatedInstance===!0&&n?(0,OM.vaultPathToIRI)(n):t,u=await this.readServiceCallSnapshot(n);return await o.execute(l,c),await this.stampServiceCallTarget(n,u,c),{success:!0}}async readServiceCallSnapshot(e){if(!e||!await this.fileReader.fileExists(e))return;let t=await this.fileReader.readFile(e),n=this.frontmatterService.parseObject(t)?.exo__Asset_uid,i=typeof n=="string"?n.trim().replace(/^"|"$/g,""):"";if(!tte.test(i))return{bytes:t};let s=e.lastIndexOf("/"),c=`${s>=0?e.slice(0,s+1):""}${i}.md`;return c===e?{bytes:t}:await this.fileReader.fileExists(c)?{bytes:t}:{bytes:t,canon:c}}async stampServiceCallTarget(e,t,n){if(t===void 0)return;let i=await this.locateServiceCallTarget(e,t);if(i===void 0)return;let s=t.bytes,o=await this.fileReader.readFile(i);if(o===s)return;let c=typeof n?.property=="string"?n.property:void 0,l=this.stampUpdatedAt(s,o,c);l!==o&&await this.fileWriter.updateFile(i,l)}async locateServiceCallTarget(e,t){if(await this.fileReader.fileExists(e))return e;if(t.canon!==void 0&&await this.fileReader.fileExists(t.canon))return t.canon}async executeConvertToTask(e){let t=await this.fileReader.readFile(e),n=await this.resolveClassRefToUid("ems__Task"),i=this.stampUpdatedAt(t,this.frontmatterService.updateProperty(t,"exo__Instance_class",`["[[${n}]]"]`),"exo__Instance_class");return await this.fileWriter.updateFile(e,i),{success:!0}}async executeConvertToProject(e){let t=await this.fileReader.readFile(e),n=await this.resolveClassRefToUid("ems__Project"),i=this.stampUpdatedAt(t,this.frontmatterService.updateProperty(t,"exo__Instance_class",`["[[${n}]]"]`),"exo__Instance_class");return await this.fileWriter.updateFile(e,i),{success:!0}}async executeBodyTemplate(e,t,n,i){let s=null;if(e.templateRef)if(this.templateLoader){if(s=await this.templateLoader(e.templateRef),s===null)return{success:!1,error:`body_template: templateRef "${e.templateRef}" did not resolve to a template body (asset missing or empty).`}}else{if(e.bodyTemplate===void 0)return{success:!1,error:`body_template: templateRef "${e.templateRef}" set but no TemplateLoaderPort is wired (and no inline bodyTemplate fallback).`};s=e.bodyTemplate}else if(e.bodyTemplate!==void 0)s=e.bodyTemplate;else return{success:!1,error:"body_template requires bodyTemplate or templateRef"};let o=(0,Wee.resolveTemplateBody)(s,{userInput:i,targetIRI:t,targetFilePath:n}),c;try{c=await this.fileReader.readFile(n)}catch(u){return{success:!1,error:`body_template: failed to read target file "${n}": ${u instanceof Error?u.message:String(u)}`}}let l=this.stampUpdatedAt(c,Vt.replaceBody(c,o));return await this.fileWriter.updateFile(n,l),{success:!0}}static replaceBody(e,t){let n=e.match(/^---\r?\n[\s\S]*?\r?\n---/);return n?`${n[0]}
146
- ${t}`:t}static extractBody(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---/);return t?e.slice(t[0].length).replace(/^\r?\n/,""):e}async executeCreateInstance(e,t,n,i,s){if(!e.targetFolder)return{success:!1,error:"create_instance requires targetFolder"};let o={},c=null,l=null;if((e.inheritanceRule&&e.inheritanceRule.length>0||e.propertyDefault&&e.propertyDefault.some(w=>typeof w.value=="string"&&w.value.includes("__SUBSTITUTE"))||e.labelTemplate!==void 0&&/\$target\./.test(e.labelTemplate)||e.cloneTargetBody===!0)&&t&&n){let w;try{w=await this.fileReader.readFile(n)}catch(R){return{success:!1,error:`create_instance: failed to read $target file "${n}": ${R instanceof Error?R.message:String(R)}`}}c=this.frontmatterService.parseObject(w)??null,e.cloneTargetBody&&(l=Vt.extractBody(w))}let f;e.targetClass&&(f=await this.resolveClassRefToUid(e.targetClass));let d=await this.preResolveTargetRefs(e.propertyDefault,c),p={userInput:i,targetIRI:t,targetFilePath:n,targetFm:c??void 0,targetRefFm:d,groundingTargetClassUid:f,createdInstancePath:s};if(e.propertyDefault&&e.propertyDefault.length>0&&this.applyPropertyDefaultStep(o,e.propertyDefault,p),this.applyMissingScalarPrimitives(o,i,f,e,t,c,n),i)for(let[w,R]of Object.entries(i))w!=="label"&&w!=="body"&&w!=="plannedDate"&&R!=null&&(o[w]=R);if(e.inheritanceRule&&e.inheritanceRule.length>0&&c&&await this.applyInheritanceRuleStep(o,e.inheritanceRule,c),await this.applyMissingBacklinkTopUp(o,e,t,n,c),t&&e.linkBackProperty&&o[e.linkBackProperty]===void 0){let w=Vt.extractBacklinkTarget(t,n);o[e.linkBackProperty]=`"[[${w}]]"`}this.applyPrototypeTimePropagation(o,c,i);let h=o.exo__Asset_uid,g=this.declaredRanges?await this.declaredRanges(Object.keys(o)):void 0,m=this.frontmatterService.createFrontmatter("",o,g===void 0?void 0:w=>g.get(w)),b=e.targetFolder.includes("$isDefinedByFolder")?await this.resolveIsDefinedByFolder(o,n):this.substituteVariables(e.targetFolder,t,i,void 0,n),_=b?`${b}/${h}.md`:`${h}.md`,S=i?.body,A=typeof S=="string"&&S.length>0?S:e.cloneTargetBody&&typeof l=="string"&&l.length>0?l:null,E=A!==null?Vt.replaceBody(m,A):m;return await this.fileWriter.createFile(_,E),{success:!0,openPath:_}}resolveInstanceDate(e,t){let n=Vt.firstScalar(e?.plannedDate);return n&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:Gh.DateFormatter.toDateString(t??this.clock.now())}applyPrototypeTimePropagation(e,t,n){if(!t)return;let i=Vt.firstScalar(t.ems__EffortPrototype_startTime),s=Vt.firstScalar(t.ems__EffortPrototype_endTime);if(!i&&!s)return;let o=this.resolveInstanceDate(n);if(i&&e.ems__Effort_plannedStartTimestamp===void 0){let c=Vt.combineDateAndTime(o,i);c!==null?e.ems__Effort_plannedStartTimestamp=c:Rs.LoggingService.warn(`[GroundingExecutor] prototype ems__EffortPrototype_startTime "${i}" is not a valid HH:MM[:SS] time-of-day \u2014 skipping plannedStartTimestamp stamp.`)}if(s&&e.ems__Effort_plannedEndTimestamp===void 0){let c=Vt.combineDateAndTime(o,s);c!==null?e.ems__Effort_plannedEndTimestamp=c:Rs.LoggingService.warn(`[GroundingExecutor] prototype ems__EffortPrototype_endTime "${s}" is not a valid HH:MM[:SS] time-of-day \u2014 skipping plannedEndTimestamp stamp.`)}}static firstScalar(e){if(e==null)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let n=t.trim().replace(/^["'](.*)["']$/,"$1").trim();return n.length>0?n:null}static combineDateAndTime(e,t){if(!/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(t))return null;let n=/^\d{2}:\d{2}$/.test(t)?`${t}:00`:t;return`${e}T${n}`}async resolveIsDefinedByFolder(e,t){let n=Vt.parentFolderOf(t),i=e.exo__Asset_isDefinedBy,s=Vt.extractBareRef(i);if(s&&this.refToFolder)try{let o=await this.refToFolder(s);if(o!=null)return o}catch(o){Rs.LoggingService.error(`[GroundingExecutor] $isDefinedByFolder resolution failed for ref "${s}" \u2014 falling back to host folder.`,o instanceof Error?o:new Error(String(o)))}return n}static parentFolderOf(e){let t=e.replace(/^\/+/,""),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}static extractBareRef(e){if(typeof e!="string")return null;let t=e.trim();t=t.replace(/^["']|["']$/g,"").trim(),t=t.replace(/^\[\[/,"").replace(/\]\]$/,"");let n=t.indexOf("|");return n>=0&&(t=t.slice(0,n)),t=t.trim(),t.length>0?t:null}async preResolveTargetRefs(e,t){if(!e||!this.refToFrontmatter||!t)return;let n=new Set;for(let{value:s}of e){if(typeof s!="string")continue;let o=Vt.extractTargetRefPropertyRefKey(s);o&&n.add(o)}if(n.size===0)return;let i={};for(let s of n){let o=t[s],c=Array.isArray(o)?o[0]:o,l=Vt.extractBareRef(c);if(!l){i[s]=null;continue}try{i[s]=await this.refToFrontmatter(l)}catch(u){Rs.LoggingService.error(`[GroundingExecutor] targetRefProperty second-hop resolution failed for ref "${l}" (refKey "${s}") \u2014 routing skipped, instance co-locates with the click-target.`,u instanceof Error?u:new Error(String(u))),i[s]=null}}return i}static extractTargetRefPropertyRefKey(e){let t=e.match(DM);if(!t||t[1]!=="targetRefProperty")return null;let n=Vt.decodeBase64UrlSafe(t[2]),i=n.indexOf("|");if(i<0)return null;let s=n.slice(0,i);return s.length>0?s:null}async resolveClassRefToUid(e){if(FM.test(e)||!this.classLabelToUid)return e;try{let t=await this.classLabelToUid(e);return t&&t.length>0?t:e}catch{return e}}applyPropertyDefaultStep(e,t,n){for(let{propertyName:i,value:s}of t){if(e[i]!==void 0)continue;let o=this.resolveSubstitutionMarker(s,n);if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;e[i]=o;continue}if(i==="exo__Instance_class"&&typeof o=="string"){e[i]=[o];continue}e[i]=o}}}applyMissingScalarPrimitives(e,t,n,i,s,o,c){let l=[];e.exo__Asset_uid===void 0&&(e.exo__Asset_uid=this.uidGen.next(),l.push("exo__Asset_uid")),e.exo__Asset_createdAt===void 0&&(e.exo__Asset_createdAt=Gh.DateFormatter.toLocalTimestamp(this.clock.now()),l.push("exo__Asset_createdAt")),e.exo__Asset_updatedAt===void 0&&(e.exo__Asset_updatedAt=e.exo__Asset_createdAt);let u=typeof e.exo__Asset_label=="string"&&e.exo__Asset_label.trim().length===0;if(e.exo__Asset_label===void 0||u){let f=t?.label;if(f===void 0&&i?.labelTemplate)try{let p=this.substituteVariables(i.labelTemplate,s??"",t,o??void 0,c);p.trim().length>0&&(f=p)}catch(p){Rs.LoggingService.error(`[GroundingExecutor] labelTemplate substitution failed: ${p instanceof Error?p.message:String(p)}. Falling back to "Untitled".`)}if(i?.omitLabel===!0&&(f===void 0||f.trim().length===0))delete e.exo__Asset_label;else{let p=f!==void 0&&f.trim().length>0?f:"Untitled";e.exo__Asset_label=p;let h=Object.keys(e).some(g=>(0,Jf.canonicalYamlKey)(g)==="aliases");p!=="Untitled"&&!h&&(e.aliases=[p]),p==="Untitled"&&l.push("exo__Asset_label")}}e.exo__Instance_class===void 0&&n&&(e.exo__Instance_class=[`"[[${n}]]"`],l.push("exo__Instance_class")),l.length>0&&Rs.LoggingService.error(`[GroundingExecutor] Universal Default Template did not cover essential scalar primitives: ${l.join(", ")}. Filled from legacy TS fallback. Vault may be in an unhealthy state \u2014 verify UniversalDefaultTemplate singleton is present and complete.`)}async applyMissingBacklinkTopUp(e,t,n,i,s){if(!n||t.linkBackProperty||e.exo__Asset_prototype!==void 0||e.ems__Effort_parent!==void 0)return;let o=Vt.extractBacklinkTarget(n,i);if(Vt.propertiesReferenceTarget(e,o))return;let c=s??await this.readTargetFrontmatter(n,i);if(!await this.targetIsPrototype(c))return;let l=c?.exo__Asset_uid,u=typeof l=="string"?l.trim().replace(/^['"]+|['"]+$/g,"").trim():"",f=u.length>0?u:o;e.exo__Asset_prototype=`"[[${f}]]"`,Rs.LoggingService.error("[GroundingExecutor] No backlink rule fired (Universal IRs absent or no class match). Falling back to legacy exo__Asset_prototype default \u2014 the target is a prototype, so the link is valid.")}async readTargetFrontmatter(e,t){let n=t;if(!n){let i=Vt.resolveTargetPath(e,"");if(!i)return null;n=/\.md$/i.test(i)?i:`${i}.md`}try{let i=await this.fileReader.readFile(n);return this.frontmatterService.parseObject(i)??null}catch{return null}}async targetIsPrototype(e){if(!e)return!1;let t=this.resolveClassRefsFromFrontmatter(e),n=new Set;for(let i of t)if(await this.classRefReachesPrototype(i,0,n))return!0;return!1}async classRefReachesPrototype(e,t,n){if(t>Vt.MAX_PROTOTYPE_CLASS_WALK_DEPTH)return!1;let i=e.trim();if(!i||n.has(i))return!1;n.add(i);let s=i.split("|"),o=s[0].trim();if((s[1]??s[0]).trim()===Vt.PROTOTYPE_CLASS_LABEL)return!0;if(!this.refToFrontmatter||!o)return!1;let l;try{l=await this.refToFrontmatter(o)}catch{return!1}if(!l)return!1;if(String(l.exo__Asset_label??"").trim()===Vt.PROTOTYPE_CLASS_LABEL)return!0;let u=l.exo__Class_superClass,f=Array.isArray(u)?u:u==null?[]:[u];for(let d of f){let p=this.extractWikilinkInner(String(d));if(p&&await this.classRefReachesPrototype(p,t+1,n))return!0}return!1}static propertiesReferenceTarget(e,t){if(!t)return!1;let n=`[[${t}]]`,i=a(s=>typeof s=="string"&&s.includes(n),"refs");for(let s of Object.values(e))if(i(s)||Array.isArray(s)&&s.some(i))return!0;return!1}resolveSubstitutionMarker(e,t){let n=e.match(DM);if(n){let c=n[1],l=n[2],u=Vt.decodeBase64UrlSafe(l),f=(0,NI.getResolver)(c);return f?f(t,u):(Rs.LoggingService.warn(`[GroundingExecutor] Parameterised marker references unknown resolver '${c}' \u2014 value left as marker.`),e)}let i=e.match(rte);if(!i)return e;let s=i[1];if(s==="target"){let c=t.targetIRI??"",l=t.targetFilePath??"";return`"[[${Vt.extractBacklinkTarget(c,l)}]]"`}if(s==="createdInstance"){let c=t.createdInstancePath??"";return c?`"[[${Vt.extractBacklinkTarget("",c)}]]"`:null}if(s==="targetFolder"){let c=t.targetFilePath??"";if(!c)return"";let l=c.replace(/^\/+/,""),u=l.lastIndexOf("/");return u>=0?l.slice(0,u):""}let o=(0,NI.getResolver)(s);return o?o(t):(Rs.LoggingService.warn(`[GroundingExecutor] Marker references unknown resolver '${s}' \u2014 value left as marker.`),e)}static decodeBase64UrlSafe(e){return(0,zee.base64ToUtf8)(e.replace(/-/g,"+").replace(/_/g,"/"))}async applyInheritanceRuleStep(e,t,n){let i=this.extractTargetClassNames(n),s=[];for(let o of t)!await this.inheritanceConditionMatches(o.targetClassCondition,o.targetClassConditionUid,i)||await this.inheritanceExclusionMatches(o.targetClassExclusion,o.targetClassExclusionUids,i)||s.push(o);s.sort((o,c)=>c.priority-o.priority);for(let o of s){if(e[o.targetPropertyName]!==void 0)continue;let c=n[o.sourcePropertyName];c!=null&&(e[o.targetPropertyName]=this.formatInheritedValue(c))}}async inheritanceConditionMatches(e,t,n){return!e&&!t?!0:this.classRefMatchesAny(e,t,n)}async inheritanceExclusionMatches(e,t,n){for(let i of t??[])if(i&&n.includes(i))return!0;for(let i of e)if(await this.classRefMatchesAny(i,void 0,n))return!0;return!1}async classRefMatchesAny(e,t,n){if(t&&n.includes(t)||e&&n.includes(e))return!0;if(e&&this.classLabelToUid)try{let i=await this.classLabelToUid(e);if(i&&i.length>0&&n.includes(i))return!0}catch{}return!1}extractTargetClassNames(e){let t=e.exo__Instance_class;if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let s of n){let o=this.extractWikilinkInner(String(s));o&&i.push(o)}return i}extractWikilinkInner(e){let t=e.match(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);return t?t[1].trim():e.replace(/^["']|["']$/g,"").trim()}formatInheritedValue(e){return Array.isArray(e)?e.map(t=>this.formatInheritedScalar(String(t),!0)):this.formatInheritedScalar(String(e),!1)}formatInheritedScalar(e,t){return/^"?\[\[.+\]\]"?$/.test(e)?this.reformatWikilink(e):FM.test(e)?`"[[${e}]]"`:(0,$n.decodeYamlBlockScalar)(e,t)}reformatWikilink(e){return e.startsWith('"[[')&&e.endsWith(']]"')?e:e.startsWith("[[")&&e.endsWith("]]")?`"${e}"`:e}async executeStep(e,t,n,i,s,o){return e.type===Un.GroundingType.COMPOSITE?this.executeComposite(e,t,n,i,s,o):this.execute(e,t,n,i,o)}async resolveCreatedPaths(e){let t=[],n;for(let i of e){if(await this.fileReader.fileExists(i)){t.push(i);continue}let s=i.slice(i.lastIndexOf("/")+1);if(s.length===0){t.push(i);continue}try{n??(n=await this.fileReader.getMarkdownFiles())}catch{t.push(i);continue}let o=n.filter(c=>c.slice(c.lastIndexOf("/")+1)===s);t.push(o.length===1?o[0]:i)}return t}async rollback(e,t,n,i=[]){if(e!==void 0)try{await this.fileWriter.updateFile(t,e)}catch(s){Rs.LoggingService.error(`[GroundingExecutor] Rollback failed for ${t}`,s instanceof Error?s:new Error(String(s)))}for(let s of i)try{await this.fileWriter.deleteFile(s)}catch(o){Rs.LoggingService.error(`[GroundingExecutor] Rollback: failed to delete orphaned created asset ${s}`,o instanceof Error?o:new Error(String(o)))}}substituteVariables(e,t,n,i,s){let o=this.clock.now(),c=o.toISOString(),l=Gh.DateFormatter.toLocalTimestamp(o),u=this.resolveInstanceDate(n,o),f=`${u}T00:00:00`,d=`${l.slice(0,10)}-${l.slice(11,13)}-${l.slice(14,16)}`;if(/\$createdInstance\b/.test(e))throw new Error(`$createdInstance is not supported here (asset IRI: ${t}). The token resolves only in a create_instance step's PropertyDefault (exocmd__PropertyDefault \u2192 exocmd__SubstitutionToken with resolver 'createdInstance'), where the composite executor supplies the created path.`);let p=e.replace(/\$target\.([A-Za-z_][\w]*)/g,(h,g)=>{if(!i)throw new Error(`$target.${g} substitution requires target frontmatter context; none was supplied (asset IRI: ${t})`);let m=i[g];if(m==null)throw new Error(`$target.${g} is undefined on asset ${t}`);if(Array.isArray(m))throw new Error(`$target.${g} resolved to an array on asset ${t}; only scalar properties are supported for substitution`);return(0,$n.decodeYamlQuotedScalar)(String(m))});if(/\$targetFolder\b/.test(p)){if(!s)throw new Error("$targetFolder substitution requires targetFilePath context; none was supplied (asset IRI: "+t+")");let h=s.replace(/^\/+/,""),g=h.lastIndexOf("/"),m=g>=0?h.slice(0,g):"";p=p.replace(/\$targetFolder\b/g,m)}if(p=p.replace(/\$target/g,t).replace(/\$nowCompact\b/g,d).replace(/\$nowLocal/g,l).replace(/\$now/g,c).replace(/\$todayStart\b/g,f).replace(/\$today/g,u),n){let h=n;p=p.replace(/\$input\.([A-Za-z_]\w*)|\$(?:input|value)\b/g,(g,m)=>{let b=m!==void 0?h[m]:h.value;return b==null?g:String(b)})}return p}async executePropertyAppend(e,t,n,i){if(!e.targetProperty)return{success:!1,error:"property_append requires targetProperty"};if(e.appendExpression===void 0)return{success:!1,error:"property_append requires appendExpression"};let s=await this.fileReader.readFile(n),o=this.frontmatterService.parseObject(s)??{},c=this.substituteVariables(e.appendExpression,t,i,o),l=o[e.targetProperty],u=Array.isArray(l)?l:l!==void 0?[(0,$n.blockScalarAsSequenceItem)(String(l))]:[],f=(0,$n.isCompleteDoubleQuotedScalar)(c)?(0,$n.decodeYamlQuotedScalar)(c):c,d=new Set(u.map($n.decodeYamlSequenceItem)),p;d.has(f)?p=u:p=[...u,(0,$n.quoteYamlString)(f)];let h=this.stampUpdatedAt(s,this.frontmatterService.updateProperty(s,e.targetProperty,p),e.targetProperty);return await this.fileWriter.updateFile(n,h),{success:!0}}async executePropertyReplace(e,t,n,i){if(!e.targetProperty)return{success:!1,error:"property_replace requires targetProperty"};if(e.replaceFromExpression===void 0)return{success:!1,error:"property_replace requires replaceFromExpression"};if(e.replaceToExpression===void 0)return{success:!1,error:"property_replace requires replaceToExpression"};let s=await this.fileReader.readFile(n),o=this.frontmatterService.parseObject(s)??{},c=o[e.targetProperty];if(!Array.isArray(c))return{success:!1,error:`property_replace: <${e.targetProperty}> is not a list on this asset (replacing one element of a scalar is identical to property_set \u2014 use that instead)`};let l=c,u=a(b=>{let _=this.substituteVariables(b,t,i,o);return(0,$n.isCompleteDoubleQuotedScalar)(_)?(0,$n.decodeYamlQuotedScalar)(_):_},"plainOf"),f=u(e.replaceFromExpression),d=u(e.replaceToExpression);if(f===""||d==="")return{success:!1,error:`property_replace: ${f===""?"replaceFromExpression":"replaceToExpression"} resolved to an empty value \u2014 refusing rather than matching an empty list element`};let p=l.findIndex(b=>(0,$n.decodeYamlSequenceItem)(b)===f);if(p===-1)return{success:!1,error:`property_replace: "${f}" is not a value of <${e.targetProperty}> on this asset \u2014 refusing rather than appending`};let g=l.findIndex((b,_)=>_!==p&&(0,$n.decodeYamlSequenceItem)(b)===d)===-1?l.map((b,_)=>_===p?(0,$n.quoteYamlString)(d):b):l.filter((b,_)=>_!==p),m=this.stampUpdatedAt(s,this.frontmatterService.updateProperty(s,e.targetProperty,g),e.targetProperty);return await this.fileWriter.updateFile(n,m),{success:!0}}async executePropertyIncrement(e,t){if(!e.targetProperty)return{success:!1,error:"property_increment requires targetProperty"};let n=e.incrementBy??1;if(!Number.isFinite(n)||!Number.isInteger(n))return{success:!1,error:`property_increment: incrementBy must be an integer (got ${String(e.incrementBy)})`};let i=await this.fileReader.readFile(t),o=(this.frontmatterService.parseObject(i)??{})[e.targetProperty],c;if(o==null||o==="")c=0;else{if(Array.isArray(o))return{success:!1,error:`property_increment: targetProperty "${e.targetProperty}" is an array, expected integer`};{let f=String(o).replace(/^["'](.*)["']$/,"$1").trim();if(!/^-?\d+$/.test(f))return{success:!1,error:`property_increment: targetProperty "${e.targetProperty}" current value "${String(o)}" is not a valid integer`};c=Number.parseInt(f,10)}}let l=c+n,u=this.stampUpdatedAt(i,this.frontmatterService.updateProperty(i,e.targetProperty,l),e.targetProperty);return await this.fileWriter.updateFile(t,u),{success:!0}}async executePropertyShift(e,t){if(!e.targetProperty)return{success:!1,error:"property_shift requires targetProperty"};if(!e.shiftDelta)return{success:!1,error:"property_shift requires shiftDelta (ISO-8601 duration literal)"};let n=await this.fileReader.readFile(t),s=(this.frontmatterService.parseObject(n)??{})[e.targetProperty];if(s==null||s==="")return{success:!1,error:`property_shift: targetProperty "${e.targetProperty}" is not set on target asset`};if(Array.isArray(s))return{success:!1,error:`property_shift: targetProperty "${e.targetProperty}" is an array, expected single datetime`};let o=String(s).replace(/^["'](.*)["']$/,"$1").trim(),c=new Date(o);if(Number.isNaN(c.getTime()))return{success:!1,error:`property_shift: current value "${o}" is not a valid datetime`};let l;try{l=Vt.applyIsoDuration(c,e.shiftDelta)}catch(d){return{success:!1,error:`property_shift: invalid shiftDelta "${e.shiftDelta}": ${d instanceof Error?d.message:String(d)}`}}let u=Gh.DateFormatter.toLocalTimestamp(l),f=this.stampUpdatedAt(n,this.frontmatterService.updateProperty(n,e.targetProperty,u),e.targetProperty);return await this.fileWriter.updateFile(t,f),{success:!0}}async executeWorkflowTransition(e,t,n,i,s){if(!this.workflowResolver)return{success:!1,error:"workflow_transition requires WorkflowResolver injection (options.workflowResolver). Wire the plugin/CLI before using this grounding type."};let o=await this.fileReader.readFile(n),c=this.frontmatterService.parseObject(o)??{},l=this.resolveClassRefsFromFrontmatter(c);if(l.length===0)return{success:!1,notApplicable:!0,error:"workflow_transition: target asset has no exo__Instance_class \u2014 status transitions are not available for it."};let u;try{u=new Hee.IRI(t)}catch(E){return{success:!1,error:`workflow_transition: invalid targetIRI "${t}" \u2014 ${E instanceof Error?E.message:String(E)}`}}let f=await this.workflowResolver.resolveForAssetOrNull(u,l);if(!f)return{success:!1,notApplicable:!0,error:"workflow_transition: this asset's class has no status workflow \u2014 status transitions are not available for it."};let d=this.resolveStatusFromFrontmatter(c);if(!d)return{success:!1,error:"workflow_transition: target asset has no parseable ems__Effort_status value (need wikilink to an ems__EffortStatus* asset)."};let p=e.direction??"forward",h=p==="rollback",g=f.transitions.find(E=>E.from===d&&E.isRollback===h);if(!g)return{success:!1,error:`workflow_transition: no ${p} transition from "${d}" defined in workflow "${f.name}" (target class: ${f.targetClass}).`};let m=vr.STATUS_UID_BY_ENUM[g.to];if(!m)return{success:!1,error:`workflow_transition: no UID mapping for destination status "${g.to}" (transition target unreachable).`};let b={id:`${e.id}.statusMutation`,label:`workflow_transition: ${g.from} \u2192 ${g.to}`,type:Un.GroundingType.PROPERTY_SET,targetProperty:"ems__Effort_status",targetValueRef:m},_=await this.executePropertySet(b,t,n,i);if(!_.success)return{success:!1,error:`workflow_transition: status mutation failed \u2014 ${_.error}`};let S=g.postActions??[],A=this.groundingLoader;if(S.length>0&&A===void 0)return{success:!1,error:"workflow_transition: transition has postActions but no GroundingLoader injected (options.groundingLoader). Wire commandResolver.loadGroundingByUid in plugin/CLI."};for(let E of S){if(A===void 0)break;let w=await A(E);if(!w)return{success:!1,error:`workflow_transition: postAction grounding UID "${E}" could not be loaded (asset missing or invalid Grounding shape).`};let R=await this.execute(w,t,n,i,s);if(!R.success)return{success:!1,error:`workflow_transition: postAction "${w.label}" (UID ${E}) failed \u2014 ${R.error}`}}return{success:!0}}resolveClassRefsFromFrontmatter(e){let t=e.exo__Instance_class;if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let s of n){if(typeof s!="string")continue;let o=s.replace(/^\s*"?\[\[/,"").replace(/\]\]"?\s*$/,"").trim();o.length>0&&i.push(o)}return i}resolveStatusFromFrontmatter(e){return(0,NM.normalizeEffortStatus)(e.ems__Effort_status)}static applyIsoDuration(e,t){let n=t.trim();if(/^-?P(\d+Y)(\d+M)?$|^-?P\d+M$/.test(n)){let o=PM.DateTimeParsing.parseYearMonthDuration(n),c=new Date(e.getTime());return c.setMonth(c.getMonth()+o),c}let s=PM.DateTimeParsing.parseDayTimeDuration(n);return new Date(e.getTime()+s)}static extractBacklinkTarget(e,t){let n=Vt.resolveTargetPath(e,t),i=n.split("/").pop()??n;return Vt.UUID_BASENAME_RE.test(i)?i:n}static resolveTargetPath(e,t){if(t)return t.replace(/\.md$/i,"").replace(/^\/+/,"");if(e){let n=e.match(/^obsidian:\/\/vault\/(.+?)(?:\.md)?(?:\?|#|$)/i);if(n&&n[1])try{return decodeURIComponent(n[1])}catch{return n[1]}}return e}};vr.GroundingExecutor=Zf;Zf.UUID_BASENAME_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Zf.PROTOTYPE_CLASS_LABEL="exo__Prototype";Zf.MAX_PROTOTYPE_CLASS_WALK_DEPTH=6;vr.GroundingExecutor=Zf=Vt=Uee([(0,Vee.injectable)(),Bee("design:paramtypes",[Object,Object,n_,Function,Object])],Zf)});var $M=T(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.createVaultFrontmatterClassLabelResolver=ite;function ite(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_label:e});if(t.length>0){let s=(await r.getFileMetadata(t[0])).exo__Asset_uid;if(typeof s=="string"&&s.length>0)return s}let n=await r.findFilesByMetadata({aliases:e});if(n.length>0){let s=(await r.getFileMetadata(n[0])).exo__Asset_uid;if(typeof s=="string"&&s.length>0)return s}return null}}a(ite,"createVaultFrontmatterClassLabelResolver")});var UM=T(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.createVaultFrontmatterRefToFolderResolver=ste;function ste(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_uid:e});return t.length===0?null:ote(t[0])}}a(ste,"createVaultFrontmatterRefToFolderResolver");function ote(r){let e=r.replace(/^\/+/,""),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}a(ote,"parentFolderOf")});var BM=T($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.createVaultFrontmatterRefToFrontmatterResolver=ate;function ate(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_uid:e});return t.length===0?null:r.getFileMetadata(t[0])}}a(ate,"createVaultFrontmatterRefToFrontmatterResolver")});var GM=T(_a=>{"use strict";var cte=_a&&_a.__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},lte=_a&&_a.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ed;Object.defineProperty(_a,"__esModule",{value:!0});_a.NamedQueryRunner=void 0;var ute=lt(),fte=De(),dte=He(),VM=Nb(),pte=yc(),UI=ed=class{static{a(this,"NamedQueryRunner")}constructor(e,t){this.queryBodyResolver=e,this.tripleStore=t}async run(e,t={}){if(!e)return null;let n=await this.queryBodyResolver.resolveSparql(e);if(!n)return null;let i=this.substitute(n,t);return(0,VM.evaluateWithExoEval)(i,{store:this.tripleStore})}async runScalar(e,t={},n){if(!e)throw new Error("NamedQueryRunner.runScalar: empty queryUid");let i=await this.queryBodyResolver.resolveSparql(e);if(!i)throw new Error(`NamedQueryRunner: query__NamedQuery '${e}' has no resolvable SPARQL body (asset missing or no \`\`\`sparql block).`);let s=this.substitute(i,t),o=await(0,VM.evaluateWithExoEval)(s,{store:this.tripleStore});if(o.kind==="ask")return{value:o.result?"true":"false",kind:"literal"};if(o.kind==="construct")return null;let c=o.rows[0];if(!c)return null;let l=c.variables(),u=n??l[0];if(!u)return null;let f=c.get(u);return f===void 0?null:f instanceof fte.IRI?{value:(0,pte.iriToObsidianName)(f.value)??f.value,kind:"iri",iri:f.value}:f instanceof dte.Literal?{value:f.value,kind:"literal"}:null}substitute(e,t){let n=e;t.currentAsset&&(n=n.replace(/\$currentAsset\b/g,ed.formatIri(t.currentAsset))),t.currentClass&&(n=n.replace(/\$currentClass\b/g,ed.formatIri(t.currentClass)));let i=t.params;if(i){let s=Object.keys(i).sort((o,c)=>c.length-o.length);for(let o of s){let c=i[o],l=c.kind==="iri"?ed.formatIri(c.value):`"${ed.escapeLiteral(c.value)}"`,u=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`\\$${u}\\b`,"g"),l)}}return n}static formatIri(e){if(/[\s<>"{}|\\^`]/.test(e))throw new Error(`NamedQueryRunner: refusing to inject malformed IRI "${e}" \u2014 contains a character illegal in a SPARQL IRIREF (would break out of <...>). Pass a percent-encoded IRI.`);return`<${e}>`}static escapeLiteral(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}};_a.NamedQueryRunner=UI;_a.NamedQueryRunner=UI=ed=cte([(0,ute.injectable)(),lte("design:paramtypes",[Object,Object])],UI)});var qM=T(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});i_.extractSparqlBlock=hte;i_.stripFrontmatter=mte;function hte(r){let e=r.match(/```sparql\s*\n([\s\S]*?)\n```/);if(!e)return null;let t=e[1].trim();return t.length>0?t:null}a(hte,"extractSparqlBlock");function mte(r){if(!r.startsWith("---"))return r;let e=r.indexOf(`
146
+ ${t}`:t}static extractBody(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---/);return t?e.slice(t[0].length).replace(/^\r?\n/,""):e}async executeCreateInstance(e,t,n,i,s){if(!e.targetFolder)return{success:!1,error:"create_instance requires targetFolder"};let o={},c=null,l=null;if((e.inheritanceRule&&e.inheritanceRule.length>0||e.propertyDefault&&e.propertyDefault.some(w=>typeof w.value=="string"&&w.value.includes("__SUBSTITUTE"))||e.labelTemplate!==void 0&&/\$target\./.test(e.labelTemplate)||e.cloneTargetBody===!0)&&t&&n){let w;try{w=await this.fileReader.readFile(n)}catch(R){return{success:!1,error:`create_instance: failed to read $target file "${n}": ${R instanceof Error?R.message:String(R)}`}}c=this.frontmatterService.parseObject(w)??null,e.cloneTargetBody&&(l=Vt.extractBody(w))}let f;e.targetClass&&(f=await this.resolveClassRefToUid(e.targetClass));let d=await this.preResolveTargetRefs(e.propertyDefault,c),p={userInput:i,targetIRI:t,targetFilePath:n,targetFm:c??void 0,targetRefFm:d,groundingTargetClassUid:f,createdInstancePath:s};if(e.propertyDefault&&e.propertyDefault.length>0&&this.applyPropertyDefaultStep(o,e.propertyDefault,p),this.applyMissingScalarPrimitives(o,i,f,e,t,c,n),i)for(let[w,R]of Object.entries(i))w!=="label"&&w!=="body"&&w!=="plannedDate"&&R!=null&&(o[w]=R);if(e.inheritanceRule&&e.inheritanceRule.length>0&&c&&await this.applyInheritanceRuleStep(o,e.inheritanceRule,c),await this.applyMissingBacklinkTopUp(o,e,t,n,c),t&&e.linkBackProperty&&o[e.linkBackProperty]===void 0){let w=Vt.extractBacklinkTarget(t,n);o[e.linkBackProperty]=`"[[${w}]]"`}this.applyPrototypeTimePropagation(o,c,i);let h=o.exo__Asset_uid,g=this.declaredRanges?await this.declaredRanges(Object.keys(o)):void 0,m=this.frontmatterService.createFrontmatter("",o,g===void 0?void 0:w=>g.get(w)),b=e.targetFolder.includes("$isDefinedByFolder")?await this.resolveIsDefinedByFolder(o,n):this.substituteVariables(e.targetFolder,t,i,void 0,n),_=b?`${b}/${h}.md`:`${h}.md`,S=i?.body,A=typeof S=="string"&&S.length>0?S:e.cloneTargetBody&&typeof l=="string"&&l.length>0?l:null,E=A!==null?Vt.replaceBody(m,A):m;return await this.fileWriter.createFile(_,E),{success:!0,openPath:_}}resolveInstanceDate(e,t){let n=Vt.firstScalar(e?.plannedDate);return n&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:Gh.DateFormatter.toDateString(t??this.clock.now())}applyPrototypeTimePropagation(e,t,n){if(!t)return;let i=Vt.firstScalar(t.ems__EffortPrototype_startTime),s=Vt.firstScalar(t.ems__EffortPrototype_endTime);if(!i&&!s)return;let o=this.resolveInstanceDate(n);if(i&&e.ems__Effort_plannedStartTimestamp===void 0){let c=Vt.combineDateAndTime(o,i);c!==null?e.ems__Effort_plannedStartTimestamp=c:Rs.LoggingService.warn(`[GroundingExecutor] prototype ems__EffortPrototype_startTime "${i}" is not a valid HH:MM[:SS] time-of-day \u2014 skipping plannedStartTimestamp stamp.`)}if(s&&e.ems__Effort_plannedEndTimestamp===void 0){let c=Vt.combineDateAndTime(o,s);c!==null?e.ems__Effort_plannedEndTimestamp=c:Rs.LoggingService.warn(`[GroundingExecutor] prototype ems__EffortPrototype_endTime "${s}" is not a valid HH:MM[:SS] time-of-day \u2014 skipping plannedEndTimestamp stamp.`)}}static firstScalar(e){if(e==null)return null;let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return null;let n=t.trim().replace(/^["'](.*)["']$/,"$1").trim();return n.length>0?n:null}static combineDateAndTime(e,t){if(!/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(t))return null;let n=/^\d{2}:\d{2}$/.test(t)?`${t}:00`:t;return`${e}T${n}`}async resolveIsDefinedByFolder(e,t){let n=Vt.parentFolderOf(t),i=e.exo__Asset_isDefinedBy,s=Vt.extractBareRef(i);if(s&&this.refToFolder)try{let o=await this.refToFolder(s);if(o!=null)return o}catch(o){Rs.LoggingService.error(`[GroundingExecutor] $isDefinedByFolder resolution failed for ref "${s}" \u2014 falling back to host folder.`,o instanceof Error?o:new Error(String(o)))}return n}static parentFolderOf(e){let t=e.replace(/^\/+/,""),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}static extractBareRef(e){if(typeof e!="string")return null;let t=e.trim();t=t.replace(/^["']|["']$/g,"").trim(),t=t.replace(/^\[\[/,"").replace(/\]\]$/,"");let n=t.indexOf("|");return n>=0&&(t=t.slice(0,n)),t=t.trim(),t.length>0?t:null}async preResolveTargetRefs(e,t){if(!e||!this.refToFrontmatter||!t)return;let n=new Set;for(let{value:s}of e){if(typeof s!="string")continue;let o=Vt.extractTargetRefPropertyRefKey(s);o&&n.add(o)}if(n.size===0)return;let i={};for(let s of n){let o=t[s],c=Array.isArray(o)?o[0]:o,l=Vt.extractBareRef(c);if(!l){i[s]=null;continue}try{i[s]=await this.refToFrontmatter(l)}catch(u){Rs.LoggingService.error(`[GroundingExecutor] targetRefProperty second-hop resolution failed for ref "${l}" (refKey "${s}") \u2014 routing skipped, instance co-locates with the click-target.`,u instanceof Error?u:new Error(String(u))),i[s]=null}}return i}static extractTargetRefPropertyRefKey(e){let t=e.match(DM);if(!t||t[1]!=="targetRefProperty")return null;let n=Vt.decodeBase64UrlSafe(t[2]),i=n.indexOf("|");if(i<0)return null;let s=n.slice(0,i);return s.length>0?s:null}async resolveClassRefToUid(e){if(FM.test(e)||!this.classLabelToUid)return e;try{let t=await this.classLabelToUid(e);return t&&t.length>0?t:e}catch{return e}}applyPropertyDefaultStep(e,t,n){for(let{propertyName:i,value:s}of t){if(e[i]!==void 0)continue;let o=this.resolveSubstitutionMarker(s,n);if(o!=null){if(Array.isArray(o)){if(o.length===0)continue;e[i]=o;continue}if(i==="exo__Instance_class"&&typeof o=="string"){e[i]=[o];continue}e[i]=o}}}applyMissingScalarPrimitives(e,t,n,i,s,o,c){let l=[];e.exo__Asset_uid===void 0&&(e.exo__Asset_uid=this.uidGen.next(),l.push("exo__Asset_uid")),e.exo__Asset_createdAt===void 0&&(e.exo__Asset_createdAt=Gh.DateFormatter.toLocalTimestamp(this.clock.now()),l.push("exo__Asset_createdAt")),e.exo__Asset_updatedAt===void 0&&(e.exo__Asset_updatedAt=e.exo__Asset_createdAt);let u=typeof e.exo__Asset_label=="string"&&e.exo__Asset_label.trim().length===0;if(e.exo__Asset_label===void 0||u){let f=t?.label;if(f===void 0&&i?.labelTemplate)try{let p=this.substituteVariables(i.labelTemplate,s??"",t,o??void 0,c);p.trim().length>0&&(f=p)}catch(p){Rs.LoggingService.error(`[GroundingExecutor] labelTemplate substitution failed: ${p instanceof Error?p.message:String(p)}. Falling back to "Untitled".`)}if(i?.omitLabel===!0&&(f===void 0||f.trim().length===0))delete e.exo__Asset_label;else{let p=f!==void 0&&f.trim().length>0?f:"Untitled";e.exo__Asset_label=p;let h=Object.keys(e).some(g=>(0,Jf.canonicalYamlKey)(g)==="aliases");p!=="Untitled"&&!h&&(e.aliases=[p]),p==="Untitled"&&l.push("exo__Asset_label")}}e.exo__Instance_class===void 0&&n&&(e.exo__Instance_class=[`"[[${n}]]"`],l.push("exo__Instance_class")),l.length>0&&Rs.LoggingService.error(`[GroundingExecutor] Universal Default Template did not cover essential scalar primitives: ${l.join(", ")}. Filled from legacy TS fallback. Vault may be in an unhealthy state \u2014 verify UniversalDefaultTemplate singleton is present and complete.`)}async applyMissingBacklinkTopUp(e,t,n,i,s){if(!n||t.linkBackProperty||e.exo__Asset_prototype!==void 0||e.ems__Effort_parent!==void 0)return;let o=Vt.extractBacklinkTarget(n,i);if(Vt.propertiesReferenceTarget(e,o))return;let c=s??await this.readTargetFrontmatter(n,i);if(!await this.targetIsPrototype(c))return;let l=c?.exo__Asset_uid,u=typeof l=="string"?l.trim().replace(/^['"]+|['"]+$/g,"").trim():"",f=u.length>0?u:o;e.exo__Asset_prototype=`"[[${f}]]"`,Rs.LoggingService.error("[GroundingExecutor] No backlink rule fired (Universal IRs absent or no class match). Falling back to legacy exo__Asset_prototype default \u2014 the target is a prototype, so the link is valid.")}async readTargetFrontmatter(e,t){let n=t;if(!n){let i=Vt.resolveTargetPath(e,"");if(!i)return null;n=/\.md$/i.test(i)?i:`${i}.md`}try{let i=await this.fileReader.readFile(n);return this.frontmatterService.parseObject(i)??null}catch{return null}}async targetIsPrototype(e){if(!e)return!1;let t=this.resolveClassRefsFromFrontmatter(e),n=new Set;for(let i of t)if(await this.classRefReachesPrototype(i,0,n))return!0;return!1}async classRefReachesPrototype(e,t,n){if(t>Vt.MAX_PROTOTYPE_CLASS_WALK_DEPTH)return!1;let i=e.trim();if(!i||n.has(i))return!1;n.add(i);let s=i.split("|"),o=s[0].trim();if((s[1]??s[0]).trim()===Vt.PROTOTYPE_CLASS_LABEL)return!0;if(!this.refToFrontmatter||!o)return!1;let l;try{l=await this.refToFrontmatter(o)}catch{return!1}if(!l)return!1;if(String(l.exo__Asset_label??"").trim()===Vt.PROTOTYPE_CLASS_LABEL)return!0;let u=l.exo__Class_superClass,f=Array.isArray(u)?u:u==null?[]:[u];for(let d of f){let p=this.extractWikilinkInner(String(d));if(p&&await this.classRefReachesPrototype(p,t+1,n))return!0}return!1}static propertiesReferenceTarget(e,t){if(!t)return!1;let n=`[[${t}]]`,i=a(s=>typeof s=="string"&&s.includes(n),"refs");for(let s of Object.values(e))if(i(s)||Array.isArray(s)&&s.some(i))return!0;return!1}resolveSubstitutionMarker(e,t){let n=e.match(DM);if(n){let c=n[1],l=n[2],u=Vt.decodeBase64UrlSafe(l),f=(0,NI.getResolver)(c);return f?f(t,u):(Rs.LoggingService.warn(`[GroundingExecutor] Parameterised marker references unknown resolver '${c}' \u2014 value left as marker.`),e)}let i=e.match(rte);if(!i)return e;let s=i[1];if(s==="target"){let c=t.targetIRI??"",l=t.targetFilePath??"";return`"[[${Vt.extractBacklinkTarget(c,l)}]]"`}if(s==="createdInstance"){let c=t.createdInstancePath??"";return c?`"[[${Vt.extractBacklinkTarget("",c)}]]"`:null}if(s==="targetFolder"){let c=t.targetFilePath??"";if(!c)return"";let l=c.replace(/^\/+/,""),u=l.lastIndexOf("/");return u>=0?l.slice(0,u):""}let o=(0,NI.getResolver)(s);return o?o(t):(Rs.LoggingService.warn(`[GroundingExecutor] Marker references unknown resolver '${s}' \u2014 value left as marker.`),e)}static decodeBase64UrlSafe(e){return(0,zee.base64ToUtf8)(e.replace(/-/g,"+").replace(/_/g,"/"))}async applyInheritanceRuleStep(e,t,n){let i=this.extractTargetClassNames(n),s=[];for(let o of t)!await this.inheritanceConditionMatches(o.targetClassCondition,o.targetClassConditionUid,i)||await this.inheritanceExclusionMatches(o.targetClassExclusion,o.targetClassExclusionUids,i)||s.push(o);s.sort((o,c)=>c.priority-o.priority);for(let o of s){if(e[o.targetPropertyName]!==void 0)continue;let c=n[o.sourcePropertyName];c!=null&&(e[o.targetPropertyName]=this.formatInheritedValue(c))}}async inheritanceConditionMatches(e,t,n){return!e&&!t?!0:this.classRefMatchesAny(e,t,n)}async inheritanceExclusionMatches(e,t,n){for(let i of t??[])if(i&&n.includes(i))return!0;for(let i of e)if(await this.classRefMatchesAny(i,void 0,n))return!0;return!1}async classRefMatchesAny(e,t,n){if(t&&n.includes(t)||e&&n.includes(e))return!0;if(e&&this.classLabelToUid)try{let i=await this.classLabelToUid(e);if(i&&i.length>0&&n.includes(i))return!0}catch{}return!1}extractTargetClassNames(e){let t=e.exo__Instance_class;if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let s of n){let o=this.extractWikilinkInner(String(s));o&&i.push(o)}return i}extractWikilinkInner(e){let t=e.match(/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/);return t?t[1].trim():e.replace(/^["']|["']$/g,"").trim()}formatInheritedValue(e){return Array.isArray(e)?e.map(t=>this.formatInheritedScalar(String(t),!0)):this.formatInheritedScalar(String(e),!1)}formatInheritedScalar(e,t){return/^"?\[\[.+\]\]"?$/.test(e)?this.reformatWikilink(e):FM.test(e)?`"[[${e}]]"`:(0,$n.decodeYamlBlockScalar)(e,t)}reformatWikilink(e){return e.startsWith('"[[')&&e.endsWith(']]"')?e:e.startsWith("[[")&&e.endsWith("]]")?`"${e}"`:e}async executeStep(e,t,n,i,s,o){return e.type===Un.GroundingType.COMPOSITE?this.executeComposite(e,t,n,i,s,o):this.execute(e,t,n,i,o)}async resolveCreatedPaths(e){let t=[],n;for(let i of e){if(await this.fileReader.fileExists(i)){t.push(i);continue}let s=i.slice(i.lastIndexOf("/")+1);if(s.length===0){t.push(i);continue}try{n??(n=await this.fileReader.getMarkdownFiles())}catch{t.push(i);continue}let o=n.filter(c=>c.slice(c.lastIndexOf("/")+1)===s);t.push(o.length===1?o[0]:i)}return t}async rollback(e,t,n,i=[]){if(e!==void 0)try{await this.fileWriter.updateFile(t,e)}catch(s){Rs.LoggingService.error(`[GroundingExecutor] Rollback failed for ${t}`,s instanceof Error?s:new Error(String(s)))}for(let s of i)try{await this.fileWriter.deleteFile(s)}catch(o){Rs.LoggingService.error(`[GroundingExecutor] Rollback: failed to delete orphaned created asset ${s}`,o instanceof Error?o:new Error(String(o)))}}substituteVariables(e,t,n,i,s){let o=this.clock.now(),c=o.toISOString(),l=Gh.DateFormatter.toLocalTimestamp(o),u=this.resolveInstanceDate(n,o),f=`${u}T00:00:00`,d=`${l.slice(0,10)}-${l.slice(11,13)}-${l.slice(14,16)}`;if(/\$createdInstance\b/.test(e))throw new Error(`$createdInstance is not supported here (asset IRI: ${t}). The token resolves only in a create_instance step's PropertyDefault (exocmd__PropertyDefault \u2192 exocmd__SubstitutionToken with resolver 'createdInstance'), where the composite executor supplies the created path.`);let p=e.replace(/\$target\.([A-Za-z_][\w]*)/g,(h,g)=>{if(!i)throw new Error(`$target.${g} substitution requires target frontmatter context; none was supplied (asset IRI: ${t})`);let m=i[g];if(m==null)throw new Error(`$target.${g} is undefined on asset ${t}`);if(Array.isArray(m))throw new Error(`$target.${g} resolved to an array on asset ${t}; only scalar properties are supported for substitution`);return(0,$n.decodeYamlQuotedScalar)(String(m))});if(/\$targetFolder\b/.test(p)){if(!s)throw new Error("$targetFolder substitution requires targetFilePath context; none was supplied (asset IRI: "+t+")");let h=s.replace(/^\/+/,""),g=h.lastIndexOf("/"),m=g>=0?h.slice(0,g):"";p=p.replace(/\$targetFolder\b/g,m)}if(p=p.replace(/\$target/g,t).replace(/\$nowCompact\b/g,d).replace(/\$nowLocal/g,l).replace(/\$now/g,c).replace(/\$todayStart\b/g,f).replace(/\$today/g,u),n){let h=n;p=p.replace(/\$input\.([A-Za-z_]\w*)|\$(?:input|value)\b/g,(g,m)=>{let b=m!==void 0?h[m]:h.value;return b==null?g:String(b)})}return p}async executePropertyAppend(e,t,n,i){if(!e.targetProperty)return{success:!1,error:"property_append requires targetProperty"};if(e.appendExpression===void 0)return{success:!1,error:"property_append requires appendExpression"};let s=await this.fileReader.readFile(n),o=this.frontmatterService.parseObject(s)??{},c=this.substituteVariables(e.appendExpression,t,i,o),l=o[e.targetProperty],u=Array.isArray(l)?l:l!==void 0?[(0,$n.blockScalarAsSequenceItem)(String(l))]:[],f=(0,$n.isCompleteDoubleQuotedScalar)(c)?(0,$n.decodeYamlQuotedScalar)(c):c,d=new Set(u.map($n.decodeYamlSequenceItem)),p;d.has(f)?p=u:p=[...u,(0,$n.quoteYamlString)(f)];let h=this.stampUpdatedAt(s,this.frontmatterService.updateProperty(s,e.targetProperty,p),e.targetProperty);return await this.fileWriter.updateFile(n,h),{success:!0}}async executePropertyReplace(e,t,n,i){if(!e.targetProperty)return{success:!1,error:"property_replace requires targetProperty"};if(e.replaceFromExpression===void 0)return{success:!1,error:"property_replace requires replaceFromExpression"};if(e.replaceToExpression===void 0)return{success:!1,error:"property_replace requires replaceToExpression"};let s=await this.fileReader.readFile(n),o=this.frontmatterService.parseObject(s)??{},c=o[e.targetProperty];if(!Array.isArray(c))return{success:!1,error:`property_replace: <${e.targetProperty}> is not a list on this asset (replacing one element of a scalar is identical to property_set \u2014 use that instead)`};let l=c,u=a(b=>{let _=this.substituteVariables(b,t,i,o);return(0,$n.isCompleteDoubleQuotedScalar)(_)?(0,$n.decodeYamlQuotedScalar)(_):_},"plainOf"),f=u(e.replaceFromExpression),d=u(e.replaceToExpression);if(f===""||d==="")return{success:!1,error:`property_replace: ${f===""?"replaceFromExpression":"replaceToExpression"} resolved to an empty value \u2014 refusing rather than matching an empty list element`};let p=l.findIndex(b=>(0,$n.decodeYamlSequenceItem)(b)===f);if(p===-1)return{success:!1,error:`property_replace: "${f}" is not a value of <${e.targetProperty}> on this asset \u2014 refusing rather than appending`};if(f===d)return{success:!1,error:`property_replace: replaceFromExpression and replaceToExpression both resolved to "${f}" \u2014 this can only leave <${e.targetProperty}> unchanged, and reporting a no-op as a replacement would hide that`};let g=l.findIndex((b,_)=>_!==p&&(0,$n.decodeYamlSequenceItem)(b)===d)===-1?l.map((b,_)=>_===p?(0,$n.quoteYamlString)(d):b):l.filter((b,_)=>_!==p),m=this.stampUpdatedAt(s,this.frontmatterService.updateProperty(s,e.targetProperty,g),e.targetProperty);return await this.fileWriter.updateFile(n,m),{success:!0}}async executePropertyIncrement(e,t){if(!e.targetProperty)return{success:!1,error:"property_increment requires targetProperty"};let n=e.incrementBy??1;if(!Number.isFinite(n)||!Number.isInteger(n))return{success:!1,error:`property_increment: incrementBy must be an integer (got ${String(e.incrementBy)})`};let i=await this.fileReader.readFile(t),o=(this.frontmatterService.parseObject(i)??{})[e.targetProperty],c;if(o==null||o==="")c=0;else{if(Array.isArray(o))return{success:!1,error:`property_increment: targetProperty "${e.targetProperty}" is an array, expected integer`};{let f=String(o).replace(/^["'](.*)["']$/,"$1").trim();if(!/^-?\d+$/.test(f))return{success:!1,error:`property_increment: targetProperty "${e.targetProperty}" current value "${String(o)}" is not a valid integer`};c=Number.parseInt(f,10)}}let l=c+n,u=this.stampUpdatedAt(i,this.frontmatterService.updateProperty(i,e.targetProperty,l),e.targetProperty);return await this.fileWriter.updateFile(t,u),{success:!0}}async executePropertyShift(e,t){if(!e.targetProperty)return{success:!1,error:"property_shift requires targetProperty"};if(!e.shiftDelta)return{success:!1,error:"property_shift requires shiftDelta (ISO-8601 duration literal)"};let n=await this.fileReader.readFile(t),s=(this.frontmatterService.parseObject(n)??{})[e.targetProperty];if(s==null||s==="")return{success:!1,error:`property_shift: targetProperty "${e.targetProperty}" is not set on target asset`};if(Array.isArray(s))return{success:!1,error:`property_shift: targetProperty "${e.targetProperty}" is an array, expected single datetime`};let o=String(s).replace(/^["'](.*)["']$/,"$1").trim(),c=new Date(o);if(Number.isNaN(c.getTime()))return{success:!1,error:`property_shift: current value "${o}" is not a valid datetime`};let l;try{l=Vt.applyIsoDuration(c,e.shiftDelta)}catch(d){return{success:!1,error:`property_shift: invalid shiftDelta "${e.shiftDelta}": ${d instanceof Error?d.message:String(d)}`}}let u=Gh.DateFormatter.toLocalTimestamp(l),f=this.stampUpdatedAt(n,this.frontmatterService.updateProperty(n,e.targetProperty,u),e.targetProperty);return await this.fileWriter.updateFile(t,f),{success:!0}}async executeWorkflowTransition(e,t,n,i,s){if(!this.workflowResolver)return{success:!1,error:"workflow_transition requires WorkflowResolver injection (options.workflowResolver). Wire the plugin/CLI before using this grounding type."};let o=await this.fileReader.readFile(n),c=this.frontmatterService.parseObject(o)??{},l=this.resolveClassRefsFromFrontmatter(c);if(l.length===0)return{success:!1,notApplicable:!0,error:"workflow_transition: target asset has no exo__Instance_class \u2014 status transitions are not available for it."};let u;try{u=new Hee.IRI(t)}catch(E){return{success:!1,error:`workflow_transition: invalid targetIRI "${t}" \u2014 ${E instanceof Error?E.message:String(E)}`}}let f=await this.workflowResolver.resolveForAssetOrNull(u,l);if(!f)return{success:!1,notApplicable:!0,error:"workflow_transition: this asset's class has no status workflow \u2014 status transitions are not available for it."};let d=this.resolveStatusFromFrontmatter(c);if(!d)return{success:!1,error:"workflow_transition: target asset has no parseable ems__Effort_status value (need wikilink to an ems__EffortStatus* asset)."};let p=e.direction??"forward",h=p==="rollback",g=f.transitions.find(E=>E.from===d&&E.isRollback===h);if(!g)return{success:!1,error:`workflow_transition: no ${p} transition from "${d}" defined in workflow "${f.name}" (target class: ${f.targetClass}).`};let m=vr.STATUS_UID_BY_ENUM[g.to];if(!m)return{success:!1,error:`workflow_transition: no UID mapping for destination status "${g.to}" (transition target unreachable).`};let b={id:`${e.id}.statusMutation`,label:`workflow_transition: ${g.from} \u2192 ${g.to}`,type:Un.GroundingType.PROPERTY_SET,targetProperty:"ems__Effort_status",targetValueRef:m},_=await this.executePropertySet(b,t,n,i);if(!_.success)return{success:!1,error:`workflow_transition: status mutation failed \u2014 ${_.error}`};let S=g.postActions??[],A=this.groundingLoader;if(S.length>0&&A===void 0)return{success:!1,error:"workflow_transition: transition has postActions but no GroundingLoader injected (options.groundingLoader). Wire commandResolver.loadGroundingByUid in plugin/CLI."};for(let E of S){if(A===void 0)break;let w=await A(E);if(!w)return{success:!1,error:`workflow_transition: postAction grounding UID "${E}" could not be loaded (asset missing or invalid Grounding shape).`};let R=await this.execute(w,t,n,i,s);if(!R.success)return{success:!1,error:`workflow_transition: postAction "${w.label}" (UID ${E}) failed \u2014 ${R.error}`}}return{success:!0}}resolveClassRefsFromFrontmatter(e){let t=e.exo__Instance_class;if(t==null)return[];let n=Array.isArray(t)?t:[t],i=[];for(let s of n){if(typeof s!="string")continue;let o=s.replace(/^\s*"?\[\[/,"").replace(/\]\]"?\s*$/,"").trim();o.length>0&&i.push(o)}return i}resolveStatusFromFrontmatter(e){return(0,NM.normalizeEffortStatus)(e.ems__Effort_status)}static applyIsoDuration(e,t){let n=t.trim();if(/^-?P(\d+Y)(\d+M)?$|^-?P\d+M$/.test(n)){let o=PM.DateTimeParsing.parseYearMonthDuration(n),c=new Date(e.getTime());return c.setMonth(c.getMonth()+o),c}let s=PM.DateTimeParsing.parseDayTimeDuration(n);return new Date(e.getTime()+s)}static extractBacklinkTarget(e,t){let n=Vt.resolveTargetPath(e,t),i=n.split("/").pop()??n;return Vt.UUID_BASENAME_RE.test(i)?i:n}static resolveTargetPath(e,t){if(t)return t.replace(/\.md$/i,"").replace(/^\/+/,"");if(e){let n=e.match(/^obsidian:\/\/vault\/(.+?)(?:\.md)?(?:\?|#|$)/i);if(n&&n[1])try{return decodeURIComponent(n[1])}catch{return n[1]}}return e}};vr.GroundingExecutor=Zf;Zf.UUID_BASENAME_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Zf.PROTOTYPE_CLASS_LABEL="exo__Prototype";Zf.MAX_PROTOTYPE_CLASS_WALK_DEPTH=6;vr.GroundingExecutor=Zf=Vt=Uee([(0,Vee.injectable)(),Bee("design:paramtypes",[Object,Object,n_,Function,Object])],Zf)});var $M=T(MI=>{"use strict";Object.defineProperty(MI,"__esModule",{value:!0});MI.createVaultFrontmatterClassLabelResolver=ite;function ite(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_label:e});if(t.length>0){let s=(await r.getFileMetadata(t[0])).exo__Asset_uid;if(typeof s=="string"&&s.length>0)return s}let n=await r.findFilesByMetadata({aliases:e});if(n.length>0){let s=(await r.getFileMetadata(n[0])).exo__Asset_uid;if(typeof s=="string"&&s.length>0)return s}return null}}a(ite,"createVaultFrontmatterClassLabelResolver")});var UM=T(jI=>{"use strict";Object.defineProperty(jI,"__esModule",{value:!0});jI.createVaultFrontmatterRefToFolderResolver=ste;function ste(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_uid:e});return t.length===0?null:ote(t[0])}}a(ste,"createVaultFrontmatterRefToFolderResolver");function ote(r){let e=r.replace(/^\/+/,""),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}a(ote,"parentFolderOf")});var BM=T($I=>{"use strict";Object.defineProperty($I,"__esModule",{value:!0});$I.createVaultFrontmatterRefToFrontmatterResolver=ate;function ate(r){return async e=>{if(!e)return null;let t=await r.findFilesByMetadata({exo__Asset_uid:e});return t.length===0?null:r.getFileMetadata(t[0])}}a(ate,"createVaultFrontmatterRefToFrontmatterResolver")});var GM=T(_a=>{"use strict";var cte=_a&&_a.__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},lte=_a&&_a.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},ed;Object.defineProperty(_a,"__esModule",{value:!0});_a.NamedQueryRunner=void 0;var ute=lt(),fte=De(),dte=He(),VM=Nb(),pte=yc(),UI=ed=class{static{a(this,"NamedQueryRunner")}constructor(e,t){this.queryBodyResolver=e,this.tripleStore=t}async run(e,t={}){if(!e)return null;let n=await this.queryBodyResolver.resolveSparql(e);if(!n)return null;let i=this.substitute(n,t);return(0,VM.evaluateWithExoEval)(i,{store:this.tripleStore})}async runScalar(e,t={},n){if(!e)throw new Error("NamedQueryRunner.runScalar: empty queryUid");let i=await this.queryBodyResolver.resolveSparql(e);if(!i)throw new Error(`NamedQueryRunner: query__NamedQuery '${e}' has no resolvable SPARQL body (asset missing or no \`\`\`sparql block).`);let s=this.substitute(i,t),o=await(0,VM.evaluateWithExoEval)(s,{store:this.tripleStore});if(o.kind==="ask")return{value:o.result?"true":"false",kind:"literal"};if(o.kind==="construct")return null;let c=o.rows[0];if(!c)return null;let l=c.variables(),u=n??l[0];if(!u)return null;let f=c.get(u);return f===void 0?null:f instanceof fte.IRI?{value:(0,pte.iriToObsidianName)(f.value)??f.value,kind:"iri",iri:f.value}:f instanceof dte.Literal?{value:f.value,kind:"literal"}:null}substitute(e,t){let n=e;t.currentAsset&&(n=n.replace(/\$currentAsset\b/g,ed.formatIri(t.currentAsset))),t.currentClass&&(n=n.replace(/\$currentClass\b/g,ed.formatIri(t.currentClass)));let i=t.params;if(i){let s=Object.keys(i).sort((o,c)=>c.length-o.length);for(let o of s){let c=i[o],l=c.kind==="iri"?ed.formatIri(c.value):`"${ed.escapeLiteral(c.value)}"`,u=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`\\$${u}\\b`,"g"),l)}}return n}static formatIri(e){if(/[\s<>"{}|\\^`]/.test(e))throw new Error(`NamedQueryRunner: refusing to inject malformed IRI "${e}" \u2014 contains a character illegal in a SPARQL IRIREF (would break out of <...>). Pass a percent-encoded IRI.`);return`<${e}>`}static escapeLiteral(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}};_a.NamedQueryRunner=UI;_a.NamedQueryRunner=UI=ed=cte([(0,ute.injectable)(),lte("design:paramtypes",[Object,Object])],UI)});var qM=T(i_=>{"use strict";Object.defineProperty(i_,"__esModule",{value:!0});i_.extractSparqlBlock=hte;i_.stripFrontmatter=mte;function hte(r){let e=r.match(/```sparql\s*\n([\s\S]*?)\n```/);if(!e)return null;let t=e[1].trim();return t.length>0?t:null}a(hte,"extractSparqlBlock");function mte(r){if(!r.startsWith("---"))return r;let e=r.indexOf(`
147
147
  ---`,3);return e<0?r:r.slice(e+4)}a(mte,"stripFrontmatter")});var zM=T(Sa=>{"use strict";var gte=Sa&&Sa.__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},yte=Sa&&Sa.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)},qh;Object.defineProperty(Sa,"__esModule",{value:!0});Sa.CommandExecutionFlow=void 0;var bte=lt(),WM=uc(),_te=De(),Ste=He(),wte=At(),Ete=Ts(),s_=qh=class{static{a(this,"CommandExecutionFlow")}constructor(e,t,n,i,s,o,c){this.groundingExecutor=e,this.notificationService=t,this.logger=n,this.prompts=i,this.tripleStore=s,this.fileOpener=o,this.requiredPropertyResolver=c}async run(e,t){let{command:n}=e;if(n.confirmMessage&&!await this.prompts.confirm(n.confirmMessage))return;let i=t.injectedUserInput,s=qh.extractInputSchema(e);if(s!==null&&s.length>0){let l=await this.applyLabelDatePrefill(s,n.grounding,t.targetIRI);l=await this.applyRequiredPropertyFields(l,n.grounding,t);let u=await this.prompts.promptInputSchema(l);if(u===null)return;i={...t.injectedUserInput??{},...u}}let o=await this.groundingExecutor.execute(n.grounding,t.targetIRI??"",t.filePath??"",i),c=t.filePath??"<no-file>";if(o.success){if(n.successMessage&&this.notificationService.success(n.successMessage),await new Promise(l=>setTimeout(l,100)),t.onComplete&&await t.onComplete(),o.openPath&&this.fileOpener)try{await this.fileOpener.open(o.openPath,{sameTab:n.openInSameTab})}catch(l){this.logger.info(`[CommandExecutionFlow] Failed to open created file "${o.openPath}": ${l instanceof Error?l.message:String(l)}`)}this.logger.info(`[CommandExecutionFlow] Executed "${n.name}" on ${c}`)}else o.notApplicable?(this.notificationService.info(o.error??"This command is not available for this asset."),this.logger.info(`[CommandExecutionFlow] Not applicable "${n.name}": ${o.error}`)):(this.notificationService.error(`Command failed: ${o.error??"unknown error"}`),this.logger.info(`[CommandExecutionFlow] Failed "${n.name}": ${o.error}`))}static extractInputSchema(e){let n=e.command.grounding.inputSchema;return!n||!Array.isArray(n)?null:n}async applyLabelDatePrefill(e,t,n){if(t.type!==WM.GroundingType.CREATE_INSTANCE||!t.prefillLabelWithDate||!n||!this.tripleStore)return e;let i=await this.resolveAssetLabel(n);if(!i)return e;let s=Ete.DateFormatter.toDateString(new Date),o=`${i} ${s}`;return e.map(c=>{if(typeof c!="object"||c===null)return c;let l=c;if(l.name!=="label")return c;let u=l.defaultValue;return typeof u=="string"&&u.length>0?c:{...l,defaultValue:o}})}async applyRequiredPropertyFields(e,t,n){if(t.type!==WM.GroundingType.CREATE_INSTANCE||t.targetClass||!this.requiredPropertyResolver||!n.filePath)return e;let i=qh.basenameUid(n.filePath);if(!i)return e;let s;try{s=await this.requiredPropertyResolver(i)}catch(l){return this.logger.info(`[CommandExecutionFlow] required-property resolution failed for "${i}": ${l instanceof Error?l.message:String(l)}`),e}if(s.length===0)return e;let o=new Set(qh.ALWAYS_COVERED);for(let l of e)l&&typeof l=="object"&&typeof l.name=="string"&&o.add(l.name);let c=s.filter(l=>!o.has(l.propertyKey)).map(l=>{let u={name:l.propertyKey,type:l.fieldType,label:l.label,required:!0};return l.targetClassUid&&(u.targetClassUid=l.targetClassUid),l.fieldType==="boolean"&&(u.defaultValue="false"),u});return c.length===0?e:[...e,...c]}static basenameUid(e){let t=e.replace(/^\/+/,"").split("/").pop()?.replace(/\.md$/i,"");return t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)?t.toLowerCase():null}async resolveAssetLabel(e){if(!this.tripleStore)return;let t=new _te.IRI(e),n=await this.tripleStore.match(t,wte.Namespace.EXO.term("Asset_label"),void 0);if(n.length===0)return;let i=n[0].object;if(i instanceof Ste.Literal)return i.value.length>0?i.value:void 0}};Sa.CommandExecutionFlow=s_;s_.ALWAYS_COVERED=["exo__Asset_uid","exo__Asset_createdAt","exo__Asset_updatedAt","exo__Asset_label","exo__Asset_createdBy","exo__Instance_class","exo__Asset_isDefinedBy"];Sa.CommandExecutionFlow=s_=qh=gte([(0,bte.injectable)(),yte("design:paramtypes",[Function,Object,Object,Object,Object,Object,Function])],s_)});var VI=T(BI=>{"use strict";Object.defineProperty(BI,"__esModule",{value:!0});BI.parseMinCount=HM;var vte=He();function HM(r){if(Array.isArray(r)){let e;for(let t of r){let n=HM(t);n!==void 0&&(e===void 0||n>e)&&(e=n)}return e}if(r instanceof vte.Literal){let e=parseInt(r.value,10);return Number.isNaN(e)?void 0:e}if(typeof r=="string"){let e=parseInt(r.trim().replace(/^["']|["']$/g,""),10);return Number.isNaN(e)?void 0:e}}a(HM,"parseMinCount")});var JM=T(a_=>{"use strict";Object.defineProperty(a_,"__esModule",{value:!0});a_.createTripleStoreRequiredPropertyResolver=Cte;a_.createTripleStoreClassPropertyResolver=xte;var ai=De(),td=He(),rd=At(),GI=yc(),YM=VI(),Tte=v0(),Ate=/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.md$/i,Ite=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function o_(r){let e=Ate.exec(r);return e?e[1].toLowerCase():Ite.test(r.trim())?r.trim().toLowerCase():null}a(o_,"uidFrom");function Rte(r){let e=(0,Tte.xsdDatatypeLocalName)(r);return e===null?null:e.toLowerCase()}a(Rte,"xsdLocalName");function XM(r){for(let e of r){let t=e.value,n=Rte(t);if(n!==null)return n==="date"||n==="datetime"?{fieldType:"date"}:n==="boolean"?{fieldType:"boolean"}:["integer","int","long","short","decimal","float","double","nonnegativeinteger","positiveinteger"].includes(n)?{fieldType:"number"}:{fieldType:"text"};if(e.iri){let i=o_(t)??(0,GI.iriToObsidianName)(t);return i?{fieldType:"assetRef",targetClassUid:i}:{fieldType:"assetRef"}}}return{fieldType:"text"}}a(XM,"fieldTypeFromRange");function Wh(r){let e=o_(r);if(e)return e;let t=(0,GI.iriToObsidianName)(r);return t?t.trim().toLowerCase():null}a(Wh,"classKeyOf");function KM(r){let t=(r instanceof td.Literal?r.value:r instanceof ai.IRI?(0,GI.iriToObsidianName)(r.value)??"":"").trim().toLowerCase();return t.length>0?t:null}a(KM,"labelKeyOf");async function QM(r,e){let t=rd.Namespace.EXO,n=rd.Namespace.RDFS,i=Wh(e)??e.trim().toLowerCase();if(!i)return new Set;let s=new Map,o=a((h,g)=>{let m=s.get(h);m||(m=new Set,s.set(h,m)),m.add(g)},"rememberIRI"),c=new Map,l=a(async h=>{let g=c.get(h);if(g)return g;let m=new Set;for(let _ of s.get(h)??[])if(o_(_))for(let S of[t.term("Asset_label"),n.term("label")])for(let A of await r.match(new ai.IRI(_),S,void 0)){let E=KM(A.object);E&&E!==h&&m.add(E)}else for(let S of await r.match(void 0,t.term("Asset_label"),new ai.IRI(_))){let A=S.subject instanceof ai.IRI?o_(S.subject.value):null;A&&A!==h&&m.add(A)}if(h===i){for(let _ of await r.match(void 0,t.term("Asset_uid"),new td.Literal(i)))if(_.subject instanceof ai.IRI)for(let S of[t.term("Asset_label"),n.term("label")])for(let A of await r.match(_.subject,S,void 0)){let E=KM(A.object);E&&E!==h&&m.add(E)}}let b=[...m];return c.set(h,b),b},"twinsOf"),u=await r.match(void 0,t.term("Class_superClass"),void 0),f=new Map;for(let h of u){let g=h.subject instanceof ai.IRI?Wh(h.subject.value):null,m=h.object instanceof ai.IRI?Wh(h.object.value):null;if(!g||!m)continue;h.subject instanceof ai.IRI&&o(g,h.subject.value),h.object instanceof ai.IRI&&o(m,h.object.value);let b=f.get(g);b||(b=new Set,f.set(g,b)),b.add(m)}let d=new Set([i]),p=[i];for(;p.length>0;){let h=p.shift();if(h===void 0)break;let g=[...f.get(h)??[],...await l(h)];for(let m of g)d.has(m)||(d.add(m),p.push(m))}return d}a(QM,"resolveClassKeyClosure");function Cte(r){let e=rd.Namespace.EXO,t=rd.Namespace.RDFS;return async n=>{let i=await QM(r,n);if(i.size===0)return[];let s=await r.match(void 0,e.term("Property_minCount"),void 0),o=[],c=new Set;for(let l of s){let u=(0,YM.parseMinCount)(l.object);if(u===void 0||u<=0)continue;let f=l.subject;if(!(f instanceof ai.IRI)||!(await r.match(f,e.term("Property_domain"),void 0)).map(S=>S.object instanceof ai.IRI?Wh(S.object.value):null).filter(S=>S!==null).some(S=>i.has(S)))continue;let h=null;for(let S of[e.term("Asset_label"),t.term("label")]){let A=await r.match(f,S,void 0);for(let E of A)if(E.object instanceof td.Literal&&E.object.value.trim().length>0){h=E.object.value.trim();break}if(h)break}if(!h||c.has(h))continue;c.add(h);let m=(await r.match(f,e.term("Property_range"),void 0)).map(S=>S.object instanceof ai.IRI?{iri:!0,value:S.object.value}:S.object instanceof td.Literal?{iri:!1,value:S.object.value}:null).filter(S=>S!==null),{fieldType:b,targetClassUid:_}=XM(m);o.push({propertyKey:h,label:h,fieldType:b,targetClassUid:_})}return o.sort((l,u)=>l.propertyKey.localeCompare(u.propertyKey)),o}}a(Cte,"createTripleStoreRequiredPropertyResolver");function xte(r){let e=rd.Namespace.EXO,t=rd.Namespace.RDFS;return async n=>{let i=await QM(r,n);if(i.size===0)return[];let s=await r.match(void 0,e.term("Property_domain"),void 0),o=[],c=new Set;for(let l of s){let u=l.object instanceof ai.IRI?Wh(l.object.value):null;if(!u||!i.has(u))continue;let f=l.subject;if(!(f instanceof ai.IRI))continue;let d=null;for(let S of[e.term("Asset_label"),t.term("label")]){let A=await r.match(f,S,void 0);for(let E of A)if(E.object instanceof td.Literal&&E.object.value.trim().length>0){d=E.object.value.trim();break}if(d)break}if(!d||c.has(d))continue;c.add(d);let p=(0,YM.parseMinCount)((await r.match(f,e.term("Property_minCount"),void 0)).map(S=>S.object)),h=p!==void 0&&p>0,m=(await r.match(f,e.term("Property_range"),void 0)).map(S=>S.object instanceof ai.IRI?{iri:!0,value:S.object.value}:S.object instanceof td.Literal?{iri:!1,value:S.object.value}:null).filter(S=>S!==null),{fieldType:b,targetClassUid:_}=XM(m);o.push({propertyKey:d,label:d,fieldType:b,targetClassUid:_,required:h})}return o.sort((l,u)=>l.propertyKey.localeCompare(u.propertyKey)),o}}a(xte,"createTripleStoreClassPropertyResolver")});var tj=T(qI=>{"use strict";Object.defineProperty(qI,"__esModule",{value:!0});qI.createTripleStoreDeclaredRanges=Pte;var c_=De(),ZM=He(),ej=At(),Ote=yc();function Pte(r){let e=ej.Namespace.EXO,t=ej.Namespace.RDFS;return async()=>{let n=await r.match(void 0,e.term("Property_range"),void 0),i=await r.match(void 0,e.term("Asset_label"),void 0),s=await r.match(void 0,t.term("label"),void 0),o=new Map,c=new Map;for(let f of[...i,...s]){if(!(f.subject instanceof c_.IRI))continue;let d=f.subject.value;if(f.object instanceof ZM.Literal){let p=f.object.value.trim();p.length>0&&!o.has(d)&&o.set(d,p)}else f.object instanceof c_.IRI&&!c.has(d)&&c.set(d,f.object.value)}let l=new Map,u=new Map;for(let f of n){if(!(f.subject instanceof c_.IRI))continue;let d=f.object instanceof c_.IRI||f.object instanceof ZM.Literal?f.object.value:null;if(d===null)continue;let p=f.subject.value,h=u.get(p);h?h.push(d):u.set(p,[d])}for(let[f,d]of u){let p=o.get(f),h=c.get(f),g=p??(h===void 0?null:(0,Ote.iriToObsidianName)(h));g==null||g.length===0||l.has(g)||l.set(g,d)}return l}}a(Pte,"createTripleStoreDeclaredRanges")});var zh=T(wa=>{"use strict";var Fte=wa&&wa.__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},Dte=wa&&wa.__metadata||function(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)};Object.defineProperty(wa,"__esModule",{value:!0});wa.WorkflowEngine=void 0;var Lte=lt(),WI=class{static{a(this,"WorkflowEngine")}constructor(e){this.definition=e}getAvailableTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&!t.isRollback)}getRollbackTransitions(e){return this.definition.transitions.filter(t=>t.from===e&&t.isRollback)}getAllTransitions(e){return this.definition.transitions.filter(t=>t.from===e)}canTransition(e,t){return this.definition.transitions.some(n=>n.from===e&&n.to===t)}getPreviousStatus(e){return this.definition.transitions.find(n=>n.from===e&&n.isRollback)?.to??null}getNextStates(e){return this.getAvailableTransitions(e).map(t=>t.to)}isTerminalState(e){return this.definition.terminalStates.includes(e)}isInitialState(e){return this.definition.initialState===e}getTimestampsForStatus(e){return this.definition.states.find(n=>n.status===e)?.timestampOnEnter??[]}getTransition(e,t){return this.definition.transitions.find(n=>n.from===e&&n.to===t)}getOrderedStates(){return this.definition.states.map(e=>e.status)}getDefinition(){return this.definition}validate(){let e=[],t=new Set(this.definition.states.map(i=>i.status));this.definition.states.length===0&&e.push("Workflow must have at least one state"),t.has(this.definition.initialState)||e.push(`Initial state "${this.definition.initialState}" is not in the states list`);for(let i of this.definition.terminalStates)t.has(i)||e.push(`Terminal state "${i}" is not in the states list`);for(let i of this.definition.transitions)t.has(i.from)||e.push(`Transition "${i.label}" references unknown source state "${i.from}"`),t.has(i.to)||e.push(`Transition "${i.label}" references unknown target state "${i.to}"`);for(let i of this.definition.states){if(this.definition.terminalStates.includes(i.status))continue;this.definition.transitions.filter(o=>o.from===i.status&&!o.isRollback).length===0&&e.push(`State "${i.status}" has no outgoing forward transitions (dead end)`)}let n=new Set;for(let i of this.definition.transitions){let s=`${i.from}\u2192${i.to}`;n.has(s)&&e.push(`Duplicate transition: ${s}`),n.add(s)}return{valid:e.length===0,errors:e}}};wa.WorkflowEngine=WI;wa.WorkflowEngine=WI=Fte([(0,Lte.injectable)(),Dte("design:paramtypes",[Object])],WI)});var rj=T(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.EFFORT_WORKFLOW_PROPERTY=vo.WorkflowTransitionProperty=vo.WorkflowStateProperty=vo.WorkflowProperty=void 0;vo.WorkflowProperty={TARGET_CLASS:"ems__Workflow_targetClass",INITIAL_STATE:"ems__Workflow_initialState",TERMINAL_STATES:"ems__Workflow_terminalStates",IS_DEFAULT:"ems__Workflow_isDefault"};vo.WorkflowStateProperty={WORKFLOW:"ems__WorkflowState_workflow",STATUS:"ems__WorkflowState_status",ORDER:"ems__WorkflowState_order",OPTIONAL:"ems__WorkflowState_optional",TIMESTAMP_ON_ENTER:"ems__WorkflowState_timestampOnEnter",BADGE_COLOR:"ems__WorkflowState_badgeColor"};vo.WorkflowTransitionProperty={WORKFLOW:"ems__WorkflowTransition_workflow",FROM:"ems__WorkflowTransition_from",TO:"ems__WorkflowTransition_to",LABEL:"ems__WorkflowTransition_label",ICON:"ems__WorkflowTransition_icon",IS_ROLLBACK:"ems__WorkflowTransition_isRollback"};vo.EFFORT_WORKFLOW_PROPERTY="ems__Effort_workflow"});var Ea=T(u_=>{"use strict";Object.defineProperty(u_,"__esModule",{value:!0});u_.MetadataHelpers=void 0;var nj=zb(),Nte=Zl(),zI=gc(),l_=class r{static{a(this,"MetadataHelpers")}static findAllReferencingProperties(e,t){let n=[];for(let[i,s]of Object.entries(e))this.containsReference(s,t)&&n.push(i);return n}static findReferencingProperty(e,t){for(let[n,i]of Object.entries(e))if(this.containsReference(i,t))return n}static containsReference(e,t){if(!e)return!1;let n=t.replace(/\.md$/,"");if(typeof e=="string"){let i=/\[\[([^[\]]+)\]\]/g,s;for(;(s=i.exec(e))!==null;){let c=s[1].split("|")[0].trim();if(c===n||c.endsWith(`/${n}`))return!0}return!1}return Array.isArray(e)?e.some(i=>this.containsReference(i,t)):!1}static isAssetArchived(e){for(let t of r.ARCHIVED_FLAG_KEYS){let n=e?.[t];if(n!=null)return r.isTruthyFlag(n)}return!1}static isTruthyFlag(e){let t=Array.isArray(e)?e.length===1?e[0]:void 0:e;if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let n=t.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"}return!1}static getPropertyValue(e,t){return t==="Name"||t==="title"?e.title:t==="created"?e.created:t==="modified"?e.modified:t==="path"?e.path:e.metadata?.[t]}static ensureQuoted(e){return!e||e==='""'?'""':e.startsWith('"')&&e.endsWith('"')?e:`"${e}"`}static buildFileContent(e,t,n){let i={},s={};for(let[f,d]of Object.entries(e)){let p=(0,Nte.canonicalYamlKey)(f);i[p]=d,s[p]=f}let o=(0,nj.orderProperties)(i,(0,nj.loadDefaultSpec)()),c=Object.entries(o).map(([f,d])=>{let p=zI.STRING_SCALAR_PROPERTIES.has(f),h=n?.(s[f]??f);if(Array.isArray(d)){let g=d.map(m=>` - ${(0,zI.serializeYamlScalar)(m,p,h)}`).join(`
148
148
  `);return`${f}:
149
149
  ${g}`}return`${f}: ${(0,zI.serializeYamlScalar)(d,p,h)}`}).join(`
@@ -708,7 +708,7 @@ Next steps:
708
708
  `).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(jEe,"parseLastJsonLine");function uq(r,e){return e.filter(t=>{let n=r[t];return typeof n!="string"||n.trim().length===0})}a(uq,"missingStringFields");var dv=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:lq,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:lq,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:kEe,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:cq}};case"tools/call":return{jsonrpc:"2.0",id:i,result:await this.callTool(e.params??{})};default:return{jsonrpc:"2.0",id:i,error:{code:MEe,message:`Method not found: ${e.method}`}}}}async callTool(e){let t=e.name,n=e.arguments??{},i;if(t==="create_asset"){let c=uq(n,["vault","class","label"]);if(c.length>0)return Dp(`create_asset: missing required argument(s): ${c.join(", ")}`,!0);let l=sq(n);if(l!==null)return Dp(`create_asset: ${l}`,!0);i=oq(n)}else if(t==="create_effort"){let c=uq(n,["vault","command","target"]);if(c.length>0)return Dp(`create_effort: missing required argument(s): ${c.join(", ")}`,!0);i=aq(n)}else return Dp(`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 Dp(`exocortex-cli exited ${s.exitCode}
709
709
  ${c}`,!0)}let o=jEe(s.stdout);return Dp(o===void 0?s.stdout.trim():JSON.stringify(o))}};var pq=require("child_process");var $Ee=32*1024*1024;function hq(r){return e=>new Promise(t=>{(0,pq.execFile)(process.execPath,[r,...e],{maxBuffer:$Ee},(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(hq,"createSelfCliRunner");async function UEe(r,e,t){let n=(0,mq.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:fq,message:"Parse error: invalid JSON"}})+`
710
710
  `);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:dq,message:`Internal error: ${l instanceof Error?l.message:String(l)}`}}}c!==null&&t(JSON.stringify(c)+`
711
- `)}}a(UEe,"runStdioServer");function gq(r){return new pe("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 dv({runCli:hq(t),version:r??"unknown"});await UEe(n,process.stdin,i=>process.stdout.write(i))})}a(gq,"mcpCommand");function pv(r){let e=new pe;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more").version(r??"17.5.10"),e.addCommand($V()),e.addCommand(YV()),e.addCommand(S7()),e.addCommand(T7()),e.addCommand(W7()),e.addCommand(A7()),e.addCommand(O7()),e.addCommand(P7()),e.addCommand(Z7()),e.addCommand(iV()),e.addCommand(vV()),e.addCommand(CV()),e.addCommand(FV()),e.addCommand(DV()),e.addCommand(NV()),e.addCommand(kV()),e.addCommand(bG()),e.addCommand(wG()),e.addCommand(HG()),e.addCommand(YG()),e.addCommand(JG()),e.addCommand(ZG()),e.addCommand(rq()),e.addCommand(kG()),e.addCommand(qG()),e.addCommand(nq()),e.addCommand(gq(r??"17.5.10")),e}a(pv,"createProgram");pv().parse();0&&(module.exports={createProgram});
711
+ `)}}a(UEe,"runStdioServer");function gq(r){return new pe("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 dv({runCli:hq(t),version:r??"unknown"});await UEe(n,process.stdin,i=>process.stdout.write(i))})}a(gq,"mcpCommand");function pv(r){let e=new pe;return e.name("exocortex").description("CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more").version(r??"17.5.12"),e.addCommand($V()),e.addCommand(YV()),e.addCommand(S7()),e.addCommand(T7()),e.addCommand(W7()),e.addCommand(A7()),e.addCommand(O7()),e.addCommand(P7()),e.addCommand(Z7()),e.addCommand(iV()),e.addCommand(vV()),e.addCommand(CV()),e.addCommand(FV()),e.addCommand(DV()),e.addCommand(NV()),e.addCommand(kV()),e.addCommand(bG()),e.addCommand(wG()),e.addCommand(HG()),e.addCommand(YG()),e.addCommand(JG()),e.addCommand(ZG()),e.addCommand(rq()),e.addCommand(kG()),e.addCommand(qG()),e.addCommand(nq()),e.addCommand(gq(r??"17.5.12")),e}a(pv,"createProgram");pv().parse();0&&(module.exports={createProgram});
712
712
  /*! Bundled license information:
713
713
 
714
714
  reflect-metadata/Reflect.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitelev/exocortex-cli",
3
- "version": "17.5.10",
3
+ "version": "17.5.12",
4
4
  "description": "CLI tool for Exocortex knowledge management system - SPARQL queries, task management, and more",
5
5
  "main": "dist/index.js",
6
6
  "bin": {