@adhd/backlog 0.1.9 → 1.0.1

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 (65) hide show
  1. package/CHANGELOG.md +128 -47
  2. package/README.md +369 -81
  3. package/api.d.ts +196 -0
  4. package/api.ir.json +1 -0
  5. package/cli.d.ts +45 -18
  6. package/env.d.ts +23 -3
  7. package/envelope.d.ts +163 -0
  8. package/extract-live.d.ts +56 -0
  9. package/index.d.ts +11 -10
  10. package/index.js +255 -197
  11. package/index.mjs +11348 -19043
  12. package/install-skill.d.ts +23 -0
  13. package/ir-artifact.d.ts +86 -0
  14. package/package.json +51 -15
  15. package/query/card.d.ts +31 -0
  16. package/query/get.d.ts +11 -0
  17. package/query/index.d.ts +67 -0
  18. package/query/markdown.d.ts +11 -0
  19. package/query/query.d.ts +131 -0
  20. package/query/resolve.d.ts +123 -0
  21. package/query/types.d.ts +450 -0
  22. package/query/views/registry.d.ts +43 -0
  23. package/query/views/semantic.d.ts +101 -0
  24. package/query/views/stats.d.ts +109 -0
  25. package/search-shortcut.d.ts +79 -0
  26. package/serve.d.ts +18 -0
  27. package/server.d.ts +139 -4
  28. package/skill/SKILL.md +632 -138
  29. package/store/graph-backlog-store.d.ts +80 -17
  30. package/store/immediate-retry.d.ts +24 -13
  31. package/store/type-policy.d.ts +4 -0
  32. package/store/vocabulary-guard.d.ts +52 -0
  33. package/write/audit.d.ts +36 -0
  34. package/write/bootstrap.d.ts +161 -0
  35. package/write/catalog.d.ts +369 -0
  36. package/write/citation-path.d.ts +133 -0
  37. package/write/claim-lease.d.ts +21 -0
  38. package/write/claim.d.ts +80 -0
  39. package/write/create-issue.d.ts +253 -0
  40. package/write/delete.d.ts +39 -0
  41. package/write/embed-drain.d.ts +68 -0
  42. package/write/embedding-config.d.ts +81 -0
  43. package/write/embedding-observer.d.ts +80 -0
  44. package/write/errors.d.ts +365 -0
  45. package/write/issue-status.d.ts +10 -0
  46. package/write/move.d.ts +70 -0
  47. package/write/relate.d.ts +52 -0
  48. package/write/transition.d.ts +64 -0
  49. package/write/tx.d.ts +344 -0
  50. package/write/update.d.ts +81 -0
  51. package/client.d.ts +0 -174
  52. package/markdown.d.ts +0 -75
  53. package/migration-admin.d.ts +0 -26
  54. package/model.d.ts +0 -437
  55. package/store/audit-log.d.ts +0 -16
  56. package/store/claim.d.ts +0 -24
  57. package/store/crud.d.ts +0 -62
  58. package/store/ids.d.ts +0 -24
  59. package/store/lifecycle.d.ts +0 -36
  60. package/store/mapping.d.ts +0 -101
  61. package/store/mutate-metadata.d.ts +0 -8
  62. package/store/query.d.ts +0 -68
  63. package/store/repo-migration.d.ts +0 -51
  64. package/store/serve-lock.d.ts +0 -42
  65. package/store/structure.d.ts +0 -66
package/index.js CHANGED
@@ -1,211 +1,247 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var cm=Object.create;var tc=Object.defineProperty;var um=Object.getOwnPropertyDescriptor;var lm=Object.getOwnPropertyNames;var fm=Object.getPrototypeOf,dm=Object.prototype.hasOwnProperty;var pm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lm(t))!dm.call(e,o)&&o!==n&&tc(e,o,{get:()=>t[o],enumerable:!(r=um(t,o))||r.enumerable});return e};var hm=(e,t,n)=>(n=e!=null?cm(fm(e)):{},pm(t||!e||!e.__esModule?tc(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("node:fs"),Ln=require("node:url"),xl=require("@adhd/sox-telemetry"),kn=require("ts-morph"),T=require("node:path"),bt=require("ts-json-schema-generator"),je=require("pino"),Pr=require("ajv"),Tr=require("ajv-formats"),Ko=require("@adhd/sox-store-adapter"),mm=require("@adhd/sox-graph-store"),Ue=require("node:os"),Un=require("node:crypto"),Pl=require("node:module"),gm=require("node:fs/promises"),ym=require("fastify"),nc=require("node:http"),$m=require("@modelcontextprotocol/sdk/server/index.js"),vm=require("@modelcontextprotocol/sdk/server/stdio.js"),wm=require("@modelcontextprotocol/sdk/server/sse.js"),bm=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),rc=require("@modelcontextprotocol/sdk/types.js"),oc=require("yaml");var re=typeof document<"u"?document.currentScript:null;function Tl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Go=Tl(T),Et=Tl(gm),Jo="$apigen";let sc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Em(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new sc(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new sc("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Ws="x-apigen-logical",Ys="x-apigen-codec",Ho="x-apigen-ctor",zo="x-apigen-tojson",Sm="0.1.0";function ic(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Dt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Dt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Cl(e,s,t);return Dt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return $o(e,t,n);const a=t.items;if(!a)return e.map(u=>St(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?St(u):Dt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Dt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return $o(e,t,n);const a=t.properties;if(!a)return St(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Dt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?$o(e,t,n):St(e)}function Lt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Cl(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Lt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Lt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Lt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Nm(e,n):e}function Cl(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function $o(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Jo]:r,v:s}}catch{}}return St(e)}function Nm(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Jo in e){const n=e,r=n[Jo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function St(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(St);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=St(r));return t}return null}function Om(e){return{encode(t,n,r){const o=ic(e,r);return Dt(t,n,o)},decode(t,n,r){const o=ic(e,r);return Lt(t,n,o)}}}const Qs={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Zs={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Xs={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},ei={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},km=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ti={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!km.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Wo="NaN",Yo="Infinity",Qo="-Infinity",_m=new Set([Wo,Yo,Qo]),ni={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Wo:e===1/0?Yo:e===-1/0?Qo:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Wo)return NaN;if(e===Yo)return 1/0;if(e===Qo)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[..._m].join(", ")}.`);return NaN}},Am=[Qs,Zs,Xs,ei,ti,ni];function jm(e,t={}){for(const n of Am)e.register(n,{override:t.override??!1})}const Im=12;function xm(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function ac(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Pm(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Tm(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function cc(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?_n(a,t,n+1):`<${i}>`}return s}function Cm(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[_n(r,t,n+1)]:[]}function _n(e,t=e??{},n=0){if(!e||n>Im)return null;if(typeof e.$ref=="string"){const o=xm(e.$ref,t);return o!==void 0?_n(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return cc({...e,properties:o,required:s},t,n)}const r=ac(e.oneOf)??ac(e.anyOf);if(r)return _n(r,t,n+1);switch(Pm(e)){case"object":return cc(e,t,n);case"array":return Cm(e,t,n);case"string":return Tm(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Rm(e){if(!e)return;const t=_n(e);return`Example: ${JSON.stringify(t)}`}Qs.id,Zs.id,Xs.id,ei.id,ti.id,ni.id;const Rl=Em();jm(Rl);const Ml=Om(Rl.freeze());function Dl(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Zo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Mm(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function Dm(e,t){return t===void 0||e===void 0?e:Ml.decode(e,t)}function vo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Ml.encode(e,n)}async function Lm(e,t,n,r,o,s){const i=Zo(n).map(c=>Dm(s[c],Mm(n,c)));if(Dl(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return vo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return vo(u,n)}const a=await e[r](...i);return vo(a,n)}let Ll=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function Um(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>Lm(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Bm={"decimal.js":"Decimal"};function Fm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Bm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Fm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function qm(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function Ul(e){return e?e.type==="array"?`${Ul(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Vm(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Ul(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let Km=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};const Cr=new Pr({allErrors:!0});Tr(Cr);for(const e of[Ws,Ys,Ho,zo,"discriminator"])Cr.addKeyword({keyword:e,valid:!0});Cr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Gm(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Jm(e,t){const n=Rm(t),r=[`Validation failed: ${Gm(e)}`];return n&&r.push(n),r.join(" — ")}function Hm(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Cr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Km("invalid_argument",Jm(a,o.input),a)}return n()}}function zm(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let lt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function wo(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Bl(e,t){const n=e[Ys];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Wm(e,t,n){const r=Bl(t,n);return r?r.encode(e,t,n):e}function Ym(e,t,n){const r=Bl(t,n);return r?r.decode(e,t,n):e}function Qm(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ws]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:wo(r)!==void 0},encode(r,o,s){const i=wo(o);if(!i)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return Wm(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new lt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=wo(o);if(!a)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Ym(r,h,{...s,path:`${s.path}[${f}]`})}}}const Zm="x-apigen-instances";let Gn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function uc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xm(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function lc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function eg(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function tg(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ws]==="nominal"?!0:o[Ys]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Gn("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=uc(s),c=typeof s[zo]=="string"?s[zo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=lc($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=lc(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Gn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Xm(s))if(!(l in a))throw new Gn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Zm]===!1)throw new Gn("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=uc(s),u={};for(const[l,f]of Object.entries(a))u[l]=eg(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ho]=="string"?s[Ho]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const ng=[Qs,Zs,Xs,ei,ti,ni],rg={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},fc=tg({id:"ts.NominalSentinel",schema:rg}),og={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},dc=Qm({id:"ts.UnionSentinel",schema:og});function sg(){const e=[...ng.map(t=>[t.id,t]),[fc.id,fc],[dc.id,dc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Sm,codecs:sg()});const pc=new Set(["string","number","boolean","integer"]);function ig(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?pc.has(n):Array.isArray(n)?n.every(r=>pc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function ag(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(ig)}const cg={"decimal.js":"Decimal"};function ug(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(cg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ug(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function hc(e){return e.words.join("-")}function mc(e){return e.words.map(hg).join("")}function gc(e){return e.words.join("_")}function lg(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||ag(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>hc(h)).join("/"),c=o.map(h=>gc(h)).join("_"),u=o.map(h=>gc(h)).slice(0,-1).join("."),l=mc(o[o.length-2]??o[0]),f=mc(o[o.length-1]),p=o.map(h=>hc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function fg(e,t){return`x-${e}-${t}`}function dg(e,t){return`--${e}-${t}`}function pg(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function hg(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ri(e){return e.anyOf??e.oneOf}function mg(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function gg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function yg(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=ri(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function $g(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function vg(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function yc(e){return typeof e.handler=="function"}function wg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=fg(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:dg(i,s),envVar:pg(i,s)})}return o}function bg(e,t){const n=new Map,{props:r}=vg(e);for(const[o,s]of Object.entries(r)){let i="string";gg(s)?i="boolean":(mg(s)||yg(s))&&(i="json"),n.set($g(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Fl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=lg(t,o),i=n?wg(n):[],a=n?bg(n,i):new Map,c=n?Vm(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:yc(t)};if(yc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function Eg(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Sg(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ng(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function bo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(Ng(s))}return r.push(Hm(e)),Um(r)}function Og(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const kg={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function $c(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Ll};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Og(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:kg}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const _g={"decimal.js":"Decimal"};function Ag(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_g).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ag(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function jg(e,t){return`--${e}-${t}`}function Ig(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Xo(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const xg=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],vc={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let br=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};function wc(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&xg.includes(e.code)&&typeof e.toJSON=="function"}function ql(e){return e.anyOf??e.oneOf}function Pg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o.push({field:s,pluginId:i,flag:jg(i,s),envVar:Ig(i,s)})}return o}function es(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=ql(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Tg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=ql(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function bc(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Cg(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Rg(e){const t=oi(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function Eo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;if(!r)return;const o=r.oneOf,s=r.discriminator;if(!o||!s)return;const i=[];for(const[a,c]of Object.entries(s.mapping)){const u=Cg(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const f=l.properties??{},p=l.required??[];i.push({value:a,commandName:Rg(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function oi(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Mg(e,t){if(!Go.isAbsolute(t))return t;const n=Go.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Dg=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
3
- `);function Vl(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Kl(e,t,n,r){var o;for(const s of t){const i=oi(s),a=Tg(n[s]),c=r.includes(s);a?(e.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&e.push(` .option('--no-${i}')`)):c?e.push(` .requiredOption('--${i} <${i}>')`):e.push(` .option('--${i} <${i}>')`)}}function Gl(e,t,n){return`${e}:${t}::${n}`}function Jl(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const f=Object.entries(u??{}).map(([h,d])=>`'${h}': ${d}`),p=a.map(h=>es(c[h])?`'${h}': __apigenParseJsonArg('${oi(h)}', opts['${h}'])`:`'${h}': opts['${h}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...f,...p].join(", ")} }`),s.length>0){const h=s.map(d=>{const m=d.flag.replace(/^--/,"").replace(/-([a-z])/g,(y,$)=>$.toUpperCase());return`'${d.field}': opts['${m}'] ?? process.env['${d.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${h.join(", ")} }`)}else i?e.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):e.push(" const envelope: Record<string, unknown> = {}");e.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function Lg(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=t,c=Xo(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(p=>p!==a.discriminatorProperty),f=u.required.filter(p=>p!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${u.commandName}')`),Vl(e,s,i),Kl(e,l,u.props,f),Jl(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Gl(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function Ug(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(i=>Object.values(i.schemas).some(a=>{const c=Eo(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(f=>f!==c.discriminatorProperty).some(f=>es(l.props[f])));const{props:u}=bc(a);return Zo(a).some(l=>es(u[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const i of e.packages){const a=Xo(i.id),c=Mg(e.outputDir,i.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(Dg),o.push(""));const s=Object.fromEntries(e.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of e.packages)for(const[a,c]of Object.entries(i.schemas)){const u=Eo(c);if(u)for(const l of u.branches){const f=Gl(i.id,a,l.commandName);s[f]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(s,null,2)}`),o.push(""),o.push(`const program = new Command().name('${t}').version('${n}')`),o.push("");for(const i of e.packages){const a=Xo(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=Dl(u,"session"),f=Pg(u),p=Eo(u);if(p){Lg(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,rootUnion:p});continue}const h=Zo(u),{props:d,required:m}=bc(u);o.push("program"),o.push(` .command('${c}')`),Vl(o,f,l),Kl(o,h,d,m),Jl(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,paramNames:h,schemaProps:d})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
- `)}]}}function Bg(e){return{props:e.properties??{},required:e.required??[]}}function Fg(e){const t=e??{},n=Array.isArray(t.oneOf)&&t.discriminator?t.oneOf:[t],r={},o=new Map;for(const i of n){const{props:a,required:c}=Bg(i);for(const[u,l]of Object.entries(a))u in r||(r[u]=l);for(const u of c)o.set(u,(o.get(u)??0)+1)}const s=[...o.entries()].filter(([,i])=>i===n.length).map(([i])=>i);return{input:{type:"object",properties:{data:{type:"object",properties:r,required:s}},required:["data"]},output:{}}}function qg(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function Vg(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?qg(t):process.argv.slice(2)}function Kg(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function Gg(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,s]of Object.entries(r.schemas)){const i=t.get(`${r.id}:${o}`)??Kg(o,s),a=Fl({op:i,schema:s,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:s,cliPath:c,plan:a})}return n}function Jg(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function Hl(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function Ec(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Hl(o.params);t.push(` ${r}${s?` { ${s} }`:""}`)}return t.join(`
5
- `)}function Jn(e){return new br("invalid_argument",e)}function Hg(e,t){var n;const r={},o={};let s=0;for(;s<e.length;){const i=e[s];if(!i.startsWith("--"))throw Jn(`Unexpected positional argument: "${i}"`);let a=i.slice(2),c;const u=a.indexOf("=");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let l=!1,f=a;a.startsWith("no-")&&((n=t.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,f=a.slice(3));const p=t.get(f);if(!p)throw Jn(`Unknown option: --${a}. Available: ${[...t.keys()].sort().map(d=>`--${d}`).join(", ")}`);s++;let h;if(p.valueKind==="boolean")l?h=!1:c===void 0?h=!0:h=c!=="false";else{const d=c!==void 0?c:e[s++];if(d===void 0)throw Jn(`Missing value for --${a}`);if(p.valueKind==="json")try{h=JSON.parse(d)}catch(m){throw Jn(`Invalid JSON for --${a}: ${m.message}`)}else h=d}p.kind==="domain"?r[p.camelKey]=h:o[p.camelKey]=h}for(const i of t.values()){if(i.kind!=="envelope"||!i.envVar||o[i.camelKey]!==void 0)continue;const a=process.env[i.envVar];a!==void 0&&(o[i.camelKey]=a)}return{domainArgs:r,envelope:o}}function zl(e){const t=wc(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=wc(e)?vc[e.code]:vc.internal}class zg{constructor(t){this.signal=t,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=Hg(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){if(zm(n))throw new br("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){zl(n)}}function Wg(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("cli")||i.push(f)}return i}async function Yg(e){var t,n,r;const o=e.logger??qm();if((t=e.signal)!=null&&t.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=Vg(e.options);s[0]==="--"&&(s=s.slice(1));const i=Eg(e.options),a=Sg(e.options),c=new zg(e.signal),u=Gg(e),l=new Map;for(const U of u.values()){const q=l.get(U.pkgId);q?q.push(U):l.set(U.pkgId,[U])}const f={},p={};for(const U of e.packages){const q=l.get(U.id);if(!q||q.length===0)continue;if(!U.fns)throw new Error(`apigen-plugin-cli-output: package "${U.id}" has no functions`);const Q=U.fns,Z={},ye={};for(const pe of q)Z[pe.plan.op.id]=pe.schema,ye[pe.plan.op.id]=Q[pe.fnName],f[pe.plan.op.id]=pe.schema,p[pe.plan.op.id]=Q[pe.fnName];const _e=bo(Z,i),Ve={fns:ye,createClient:U.createClient,schemas:Z};for(const pe of q)c.registerRoute(pe.plan,cn=>$c(pe.plan,_e,cn,Ve))}const h=((n=e.packages[0])==null?void 0:n.id)??"ts",d=bo(f,i),m={invoke:(U,q,Q)=>d(U,{operation:{id:U},ctx:new Ll,domainArgs:q.domainArgs,envelope:q.envelope,signal:q.signal},Q),invokeOptions:{fns:p,schemas:f,createClient:(r=e.packages[0])==null?void 0:r.createClient}},y=Wg(i,a,h,e.operations??[],m);if(y.length>0){const U=bo({},i),q={fns:{},schemas:{}};for(const Q of y){const Z=Fl({op:Q,schema:Fg(Q.input),transport:"cli"});c.registerRoute(Z,ye=>$c(Z,U,ye,q))}}const $=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(Ec($));return}const v=Jg(s,$);if(!v){zl(new br("not_found",`Unknown command: ${s.join(" ")}
6
-
7
- ${Ec($)}`));return}const{entry:E,rest:b}=v,{plan:N,dispatch:j}=E,R=N.cli.path.join(" ");if(b.includes("--help")||b.includes("-h")){const U=Hl(N.params);console.log(`${R}${U?` { ${U} }`:""}`);return}const J={rest:b};try{if(N.streaming)throw new br("invalid_argument",`Command "${R}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const U=await c.readCall(J,N),q=Date.now(),Q=await j(U);await c.writeResult(J,Q,N),o.info({command:R,ms:Date.now()-q},`→ ${R}`)}catch(U){o.error({command:R,err:U},`✗ ${R}`),await c.writeError(J,U,N)}}const Qg={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(e){return Ug(e)},run(e){return Yg(e)}};let tt=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};function Sc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Zg(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Sc(i),path:s.map(Sc),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}function Xg(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of t){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}const ey={"decimal.js":"Decimal"};function ty(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ey).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ty(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ny(e){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:e}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function ry(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:ny(e.output)}}function oy(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function Nc(e){return{type:"string",enum:[e]}}function Oc(e,t){return{type:"object",required:["operation","items"],properties:{operation:t,items:{type:"array",items:e.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}}function sy(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(ry);if(e.length===1){const[o]=e,[s]=t;return{input:Oc(s,Nc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>Oc(t[s],Nc(o.id))),r=Xg(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function iy(e,t={}){const n=oy(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=sy(s),c=Zg(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const ts="$apigen";let kc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function ay(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new kc(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new kc("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const si="x-apigen-logical",ii="x-apigen-codec",ns="x-apigen-ctor",rs="x-apigen-tojson",cy="0.1.0";function _c(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Ut(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ut(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Wl(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return So(e,t,n);const a=t.items;if(!a)return e.map(u=>Nt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Nt(u):Ut(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ut(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return So(e,t,n);const a=t.properties;if(!a)return Nt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?So(e,t,n):Nt(e)}function Bt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Bt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Wl(e,s,t);return Bt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Bt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Bt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Bt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?uy(e,n):e}function Wl(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function So(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[ts]:r,v:s}}catch{}}return Nt(e)}function uy(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&ts in e){const n=e,r=n[ts],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Nt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Nt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Nt(r));return t}return null}function ly(e){return{encode(t,n,r){const o=_c(e,r);return Ut(t,n,o)},decode(t,n,r){const o=_c(e,r);return Bt(t,n,o)}}}const ai={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},ci={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},ui={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},li={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},fy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,fi={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!fy.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},os="NaN",ss="Infinity",is="-Infinity",dy=new Set([os,ss,is]),di={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?os:e===1/0?ss:e===-1/0?is:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===os)return NaN;if(e===ss)return 1/0;if(e===is)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...dy].join(", ")}.`);return NaN}},py=[ai,ci,ui,li,fi,di];function hy(e,t={}){for(const n of py)e.register(n,{override:t.override??!1})}ai.id,ci.id,ui.id,li.id,fi.id,di.id;const Yl=ay();hy(Yl);ly(Yl.freeze());let my=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};const gy={"decimal.js":"Decimal"};function yy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(gy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${yy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const $y=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let Ql=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};function Zl(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&$y.includes(e.code)&&typeof e.toJSON=="function"}function Ac(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const pi=new Pr({allErrors:!0});Tr(pi);for(const e of[si,ii,ns,rs,"discriminator"])pi.addKeyword({keyword:e,valid:!0});pi.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function vy(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Zl(n)?n:new Ql("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Ac("before-first-chunk",r)}:{ok:!1,carrier:Ac("after-first-chunk",r,t.length)}}}function wy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ft=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function No(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Xl(e,t){const n=e[ii];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function by(e,t,n){const r=Xl(t,n);return r?r.encode(e,t,n):e}function Ey(e,t,n){const r=Xl(t,n);return r?r.decode(e,t,n):e}function Sy(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[si]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:No(r)!==void 0},encode(r,o,s){const i=No(o);if(!i)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return by(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ft("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=No(o);if(!a)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ft("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ft("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Ey(r,h,{...s,path:`${s.path}[${f}]`})}}}const Ny="x-apigen-instances";let Hn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function jc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Oy(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ic(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function ky(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function _y(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[si]==="nominal"?!0:o[ii]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Hn("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=jc(s),c=typeof s[rs]=="string"?s[rs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Ic($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Ic(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Hn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Oy(s))if(!(l in a))throw new Hn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Ny]===!1)throw new Hn("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=jc(s),u={};for(const[l,f]of Object.entries(a))u[l]=ky(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[ns]=="string"?s[ns]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Ay=[ai,ci,ui,li,fi,di],jy={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},xc=_y({id:"ts.NominalSentinel",schema:jy}),Iy={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Pc=Sy({id:"ts.UnionSentinel",schema:Iy});function xy(){const e=[...Ay.map(t=>[t.id,t]),[xc.id,xc],[Pc.id,Pc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:cy,codecs:xy()});const Py=4,Ty=32;function as(e){return Zl(e)?e:e instanceof Error?new Ql("internal",e.message):e}function Cy(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Py;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ty)}function Ry(){}function My(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:Ry};const r=new AbortController,o=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",o,{once:!0}));let s;return t!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function Tc(e,t,n,r,o,s){const i=My(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(wy(c)){const u=await vy(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:as(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:as(a)}}finally{i.dispose()}}async function Dy(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=Cy(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:as(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(s==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(s==="serial"||s==="chained"){let d=!1;for(let m=0;m<n.length;m++){if(d){c[m]=u(m);continue}const y=await Tc(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=y,y.status==="rejected"&&(s==="chained"||i==="abort")&&(d=!0)}return c}let l=0,f=!1;const p=Math.max(1,Math.min(a,n.length)),h=Array.from({length:p},async()=>{for(;;){const d=l++;if(d>=n.length)return;if(f){c[d]=u(d);continue}const m=await Tc(e,t,d,n[d],r,o.itemTimeoutMs);c[d]=m,m.status==="rejected"&&i==="abort"&&(f=!0)}});return await Promise.all(h),c}const Ly={"decimal.js":"Decimal"};function Uy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ly).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Uy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function By(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new tt("invalid_argument",`@adhd/apigen-plugin-batch: "operation" ("${n}") is not one of this mount's batchable operations: ${t.join(", ")}`);const r=e.items;if(!Array.isArray(r))throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "concurrency" must be a number');const s=e.mode;if(s!==void 0&&s!=="parallel"&&s!=="serial"&&s!=="chained")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "mode" must be one of "parallel" | "serial" | "chained"');const i=e.onItemError;if(i!==void 0&&i!=="continue"&&i!=="abort")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "onItemError" must be one of "continue" | "abort"');const a=e.itemTimeoutMs;if(a!==void 0&&typeof a!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "itemTimeoutMs" must be a number');return{operation:n,items:r,concurrency:o,mode:s,onItemError:i,itemTimeoutMs:a}}function Fy(e,t){return async n=>{if(!t)throw new tt("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=By(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new my,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return Dy(t.invoke,r.operation,s,t.invokeOptions,o)}}function qy(e,t={},n){return iy(e,t).map(r=>({...r,handler:Fy(r.operationIds,n)}))}const cs={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(e,t,n){return qy(e,t,n)}}}},Cc=new Set(["string","number","boolean","integer"]);function Vy(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Cc.has(n):Array.isArray(n)?n.every(r=>Cc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ky(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Vy)}const Gy={"decimal.js":"Decimal"};function Jy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Gy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Jy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Rc(e){return e.words.join("-")}function Mc(e){return e.words.map(Hy).join("")}function Dc(e){return e.words.join("_")}function ef(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ky(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Rc(h)).join("/"),c=o.map(h=>Dc(h)).join("_"),u=o.map(h=>Dc(h)).slice(0,-1).join("."),l=Mc(o[o.length-2]??o[0]),f=Mc(o[o.length-1]),p=o.map(h=>Rc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Hy(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}async function hi(e,t=5e3){if(e!==":memory:"&&C.mkdirSync(T.dirname(e),{recursive:!0}),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const n=await Ko.createStoreAdapter({dbPath:e},{migrateOnAdapterChange:e!==":memory:"&&C.existsSync(e)});await n.pragmaSet("busy_timeout",t);const r=mm.createGraphBackend(n);return await r.applySchema(),{adapter:n,graph:r}}async function tf(e){await e.adapter.close()}async function nf(e){if(e)try{await tf(e)}catch(t){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${t instanceof Error?t.message:String(t)}`)}}const us=["SIGINT","SIGTERM"];function rf(e,t=n=>process.exit(n)){let n=!1;const r=s=>{n||(n=!0,e().catch(i=>{console.error(`backlog: signal cleanup failed (${s}): ${i instanceof Error?i.message:String(i)}`)}).finally(()=>{o(),t(128+Ue.constants.signals[s])}))},o=()=>{for(const s of us)process.removeListener(s,r)};for(const s of us)process.on(s,r);return{dispose:o}}function zy(){return us.some(e=>process.listenerCount(e)>0)}const Wy=[".git",".adhd","adhd.environment.yaml"];function Oo(e){let t=T.resolve(e);const{root:n}=T.parse(t);for(;;){for(const o of Wy)if(C.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=T.dirname(t);if(r===t)return;t=r}}const Yy=new Set(["system","global","project"]);function Qy(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:Oo(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&Yy.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:Oo(n)??n}:{scope:s}}const o=Oo(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Lc(e){return`.${e}`}function Zy(e){const t=Ue.homedir();if(process.platform==="darwin")return T.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??T.join(t,"AppData","Roaming");return T.join(r,e)}const n=process.env.XDG_DATA_HOME??T.join(t,".local","share");return T.join(n,e)}function Xy(e){const t=e.orgNamespace,n=e.adhdRoot??T.join(Ue.homedir(),Lc(t)),r=e.adhdRoot??Zy(t),o={system:T.join(r,e.project,e.namespace),global:T.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=T.join(e.projectRoot,Lc(t),e.project,e.namespace)),o}function of(e,t){return t==="project"?e.project??e.global:e[t]}function e$(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function t$(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}const oe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},_={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},cr="tag:yaml.org,2002:",rt={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function Uc(e){const t=[0];let n=e.indexOf(`
8
- `);for(;n!==-1;)n+=1,t.push(n),n=e.indexOf(`
9
- `,n);return t}function sf(e){let t,n;return typeof e=="string"?(t=Uc(e),n=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=Uc(e.context.src)),t=e.lineStarts,n=e.context.src)),{lineStarts:t,src:n}}function ls(e,t){if(typeof e!="number"||e<0)return null;const{lineStarts:n,src:r}=sf(t);if(!n||!r||e>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(e<i)return{line:s,col:e-n[s-1]+1};if(e===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:e-n[o-1]+1}}function n$(e,t){const{lineStarts:n,src:r}=sf(t);if(!n||!(e>=1)||e>n.length)return null;const o=n[e-1];let s=n[e];for(;s&&s>o&&r[s-1]===`
10
- `;)--s;return r.slice(o,s)}function r$({start:e,end:t},n,r=80){let o=n$(e.line,n);if(!o)return null;let{col:s}=e;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";t&&(t.line===e.line&&s+(t.col-e.col)<=r+1?i=t.col-e.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
11
- ${c}${u}${a}`}let te=class af{static copy(t){return new af(t.start,t.end)}constructor(t,n){this.start=t,this.end=n||t}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(t,n){const{start:r,end:o}=this;if(t.length===0||o<=t[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<t.length&&!(t[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<t.length&&!(t[s]>=o);)++s;return this.origEnd=o+s,i}},I=class Ke{static addStringTerminator(t,n,r){if(r[r.length-1]===`
12
- `)return r;const o=Ke.endOfWhiteSpace(t,n);return o>=t.length||t[o]===`
13
- `?r+`
14
- `:r}static atDocumentBoundary(t,n,r){const o=t[n];if(!o)return!0;const s=t[n-1];if(s&&s!==`
15
- `)return!1;if(r){if(o!==r)return!1}else if(o!==oe.DIRECTIVES_END&&o!==oe.DOCUMENT_END)return!1;const i=t[n+1],a=t[n+2];if(i!==o||a!==o)return!1;const c=t[n+3];return!c||c===`
16
- `||c===" "||c===" "}static endOfIdentifier(t,n){let r=t[n];const o=r==="<",s=o?[`
17
- `," "," ",">"]:[`
18
- `," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=t[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(t,n){let r=t[n];for(;r===" ";)r=t[n+=1];return n}static endOfLine(t,n){let r=t[n];for(;r&&r!==`
19
- `;)r=t[n+=1];return n}static endOfWhiteSpace(t,n){let r=t[n];for(;r===" "||r===" ";)r=t[n+=1];return n}static startOfLine(t,n){let r=t[n-1];if(r===`
20
- `)return n;for(;r&&r!==`
21
- `;)r=t[n-=1];return n+1}static endOfBlockIndent(t,n,r){const o=Ke.endOfIndent(t,r);if(o>r+n)return o;{const s=Ke.endOfWhiteSpace(t,o),i=t[s];if(!i||i===`
22
- `)return s}return null}static atBlank(t,n,r){const o=t[n];return o===`
23
- `||o===" "||o===" "||r&&!o}static nextNodeIsIndented(t,n,r){return!t||n<0?!1:n>0?!0:r&&t==="-"}static normalizeOffset(t,n){const r=t[n];return r?r!==`
24
- `&&t[n-1]===`
25
- `?n-1:Ke.endOfWhiteSpace(t,n):n}static foldNewline(t,n,r){let o=0,s=!1,i="",a=t[n+1];for(;a===" "||a===" "||a===`
26
- `;){switch(a){case`
27
- `:o=0,n+=1,i+=`
28
- `;break;case" ":o<=r&&(s=!0),n=Ke.endOfWhiteSpace(t,n+2)-1;break;case" ":o+=1,n+=1;break}a=t[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(t,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=t,this.value=null}getPropValue(t,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[t];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,oe.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const t=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,oe.COMMENT,!0);r!=null&&t.push(r)}return t.length>0?t.join(`
29
- `):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||Ke.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===oe.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==oe.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[_.FLOW_MAP,_.FLOW_SEQ,_.QUOTE_DOUBLE,_.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=ls(this.range.start,this.context.root);if(!t)return;const n=ls(this.range.end,this.context.root);return{start:t,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:t,end:n}=this.valueRange;return this.context.src.slice(t,n)}get tag(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,oe.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:t,end:n}=this.valueRange,{src:r}=this.context;for(let o=t;o<n;++o)if(r[o]===`
30
- `)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===oe.COMMENT){const r=Ke.endOfLine(n,t+1),o=new te(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return Ke.addStringTerminator(t,n.end,o)}},jt=class extends Error{constructor(t,n,r){if(!r||!(n instanceof I))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new te(this.offset,this.offset+1);const n=t&&ls(this.offset,t);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=t&&r$(this.linePos,t);o&&(this.message+=`:
31
-
32
- ${o}
33
- `)}delete this.source}},An=class extends jt{constructor(t,n){super("YAMLReferenceError",t,n)}},F=class extends jt{constructor(t,n){super("YAMLSemanticError",t,n)}},de=class extends jt{constructor(t,n){super("YAMLSyntaxError",t,n)}},rn=class extends jt{constructor(t,n){super("YAMLWarning",t,n)}};function me(e,t,n){return(t=s$(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o$(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function s$(e){var t=o$(e,"string");return typeof t=="symbol"?t:t+""}let cf=class fs extends I{static endOfLine(t,n,r){let o=t[n],s=n;for(;o&&o!==`
34
- `&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=t[s+1];if(o===":"&&(!i||i===`
35
- `||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;t<n&&(o===`
36
- `||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=t;a<n;++a){const c=r[a];if(c===`
37
- `){const{fold:u,offset:l}=I.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
38
- `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[t];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new F(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new F(this,a)],str:s}}default:return s}}parseBlockValue(t){const{indent:n,inFlow:r,src:o}=this.context;let s=t,i=t;for(let a=o[s];a===`
39
- `&&!I.atDocumentBoundary(o,s+1);a=o[s]){const c=I.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
40
- `?s=c:(i=fs.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=t),this.valueRange.end=i,i}parse(t,n){this.context=t;const{inFlow:r,src:o}=t;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
41
- `&&(s=fs.endOfLine(o,n,r)),this.valueRange=new te(n,s),s=I.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},jn=class extends I{constructor(){super(_.BLANK_LINE)}get includesTrailingLines(){return!0}parse(t,n){return this.context=t,this.range=new te(n,n+1),n+1}};class mi extends I{constructor(t,n){super(t,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{atLineStart:s,lineStart:i}=t;!s&&this.type===_.SEQ_ITEM&&(this.error=new F(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:t.indent;let c=I.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",f=[];let p=null;for(;u===`
42
- `||u==="#";){if(u==="#"){const d=I.endOfLine(o,c+1);f.push(new te(c,d)),c=d}else{s=!0,i=c+1;const d=I.endOfWhiteSpace(o,i);o[d]===`
43
- `&&f.length===0&&(p=new jn,i=p.parse({src:o},i)),c=I.endOfIndent(o,i)}u=o[c]}if(I.nextNodeIsIndented(u,c-(i+a),this.type!==_.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=I.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new te(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return I.addStringTerminator(t,r.end,s)}}let $n=class extends I{constructor(){super(_.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new te(n,r),r}};function ds(e){let t=e;for(;t instanceof mi;)t=t.node;if(!(t instanceof uf))return null;const n=t.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=t.items[i];if(a.type===_.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===_.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=t.items.splice(r,n-r),s=o[0].range.start;for(;t.range.end=s,t.valueRange&&t.valueRange.end>s&&(t.valueRange.end=s),t!==e;)t=t.context.parent;return o}let uf=class ps extends I{static nextContentHasIndent(t,n,r){const o=I.endOfLine(t,n)+1;n=I.endOfWhiteSpace(t,o);const s=t[n];return s?n>=o+r?!0:s!=="#"&&s!==`
44
- `?!1:ps.nextContentHasIndent(t,n,r):!1}constructor(t){super(t.type===_.SEQ_ITEM?_.SEQ:_.MAP);for(let r=t.props.length-1;r>=0;--r)if(t.props[r].start<t.context.lineStart){this.props=t.props.slice(0,r+1),t.props=t.props.slice(r+1);const o=t.props[0]||t.valueRange;t.range.start=o.start;break}this.items=[t];const n=ds(t);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let s=I.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=te.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=I.normalizeOffset(o,c);let u=o[c],l=I.endOfWhiteSpace(o,s)===c,f=!1;for(;u;){for(;u===`
45
- `||u==="#";){if(l&&u===`
46
- `&&!f){const d=new jn;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!ps.nextContentHasIndent(o,c,a))return c;const d=new $n;if(c=d.parse({indent:a,lineStart:s,src:o},c),this.items.push(d),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=I.endOfIndent(o,s),I.atBlank(o,c)){const d=I.endOfWhiteSpace(o,c),m=o[d];(!m||m===`
47
- `||m==="#")&&(c=d)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const d="All collection items must start at the same column";this.error=new de(this,d)}}if(i.type===_.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const d=o[c+1];if(!d||d===`
48
- `||d===" "||d===" "){const m="A collection cannot be both a mapping and a sequence";this.error=new de(this,m)}}const p=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!p)return c;if(this.items.push(p),this.valueRange.end=p.valueRange.end,c=I.normalizeOffset(o,p.range.end),u=o[c],l=!1,f=p.includesTrailingLines,u){let d=c-1,m=o[d];for(;m===" "||m===" ";)m=o[--d];m===`
49
- `&&(s=d+1,l=!0)}const h=ds(p);h&&Array.prototype.push.apply(this.items,h)}return c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{n=r.setOrigRanges(t,n)}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;let s=t.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return I.addStringTerminator(t,r.end,s)}};class i$ extends I{constructor(){super(_.DIRECTIVE),this.name=null}get parameters(){const t=this.rawValue;return t?t.trim().split(/[ \t]+/):[]}parseName(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
50
- `&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(t,r),r}parseParameters(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
51
- `&&o!=="#";)o=n[r+=1];return this.valueRange=new te(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new te(n,r),r}}let a$=class hs extends I{static startCommentOrEndBlankLine(t,n){const r=I.endOfWhiteSpace(t,n),o=t[r];return o==="#"||o===`
52
- `?r:n}constructor(){super(_.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!I.atDocumentBoundary(n,s,oe.DIRECTIVES_END);)switch(s=hs.startCommentOrEndBlankLine(n,s),n[s]){case`
53
- `:if(r){const i=new jn;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new $n;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new i$;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new te(s,s+3),s+3):(o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(t){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=t;for(;r[o-1]==="-";)o-=1;let s=I.endOfWhiteSpace(r,t),i=o===t;for(this.valueRange=new te(s);!I.atDocumentBoundary(r,s,oe.DOCUMENT_END);){switch(r[s]){case`
54
- `:if(i){const a=new jn;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new $n;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=I.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=ds(c);u&&Array.prototype.push.apply(this.contents,u)}}s=hs.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new te(s,s+3),s+=3,r[s])){if(s=I.endOfWhiteSpace(r,s),r[s]==="#"){const a=new $n;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
55
- `:s+=1;break;case void 0:break;default:this.error=new de(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(t,n){t.root=this,this.context=t;const{src:r}=t;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.directives.forEach(r=>{n=r.setOrigRanges(t,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(t,n)),this.contents.forEach(r=>{n=r.setOrigRanges(t,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(t,n)),n}toString(){const{contents:t,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return t.length>0&&((n.length>0||t[0].type===_.COMMENT)&&(o+=`---
56
- `),o+=t.join("")),o[o.length-1]!==`
57
- `&&(o+=`
58
- `),o}},c$=class extends I{parse(e,t){this.context=e;const{src:n}=e;let r=I.endOfIdentifier(n,t+1);return this.valueRange=new te(t+1,r),r=I.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const Ze={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class u$ extends I{constructor(t,n){super(t,n),this.blockIndent=null,this.chomping=Ze.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===Ze.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
59
- `||i===" "||i===" ";){if(n-=1,n<=t){if(this.chomping===Ze.KEEP)break;return""}i===`
60
- `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===Ze.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===_.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let y=0;y<c&&o[d]===" ";++y)d+=1;const m=o[d];if(m===`
61
- `)p===`
62
- `?f+=`
63
- `:p=`
64
- `;else{const y=I.endOfLine(o,d),$=o.slice(d,y);d=y,u&&(m===" "||m===" ")&&d<a?(p===" "?p=`
65
- `:!h&&!l&&p===`
66
- `&&(p=`
67
-
68
- `),f+=p+$,p=y<n&&o[y]||"",h=!0):(f+=p+$,p=u&&d<a?" ":`
69
- `,h=!1),l&&$!==""&&(l=!1)}}return this.chomping===Ze.STRIP?f:f+`
70
- `}parseBlockHeader(t){const{src:n}=this.context;let r=t+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=Ze.STRIP;break;case"+":this.chomping=Ze.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new te(t,r),r}r+=1}}parseBlockValue(t){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=t,i=t,a=1;for(let c=r[s];c===`
71
- `&&(s+=1,!I.atDocumentBoundary(r,s));c=r[s]){const u=I.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],f=u-(s+n);if(this.blockIndent){if(l&&l!==`
72
- `&&f<this.blockIndent){if(r[u]==="#")break;if(!this.error){const p=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new F(this,p)}}}else if(r[u]!==`
73
- `){if(f<a){const p="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new F(this,p)}this.blockIndent=f}else f>a&&(a=f);r[u]===`
74
- `?s=u:s=i=I.endOfLine(r,u)}return this.chomping!==Ze.KEEP&&(s=r[i]?i+1:i),this.valueRange=new te(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class l$ extends I{constructor(t,n){super(t,n),this.items=null}prevNodeIsJsonLike(t=this.items.length){const n=this.items[t-1];return!!n&&(n.jsonLike||n.type===_.COMMENT&&this.prevNodeIsJsonLike(t-1))}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{indent:s,lineStart:i}=t,a=o[n];this.items=[{char:a,offset:n}];let c=I.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
75
- `:{i=c+1;const u=I.endOfWhiteSpace(o,i);if(o[u]===`
76
- `){const l=new jn;i=l.parse({src:o},i),this.items.push(l)}if(c=I.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new F(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new $n;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
77
- `||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new te(n,c),c;this.items.push(u),c=I.normalizeOffset(o,u.range.end)}}c=I.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new te(n,c+1),a&&(this.items.push({char:a,offset:c}),c=I.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{if(r instanceof I)n=r.setOrigRanges(t,n);else if(t.length===0)r.origOffset=r.offset;else{let o=n;for(;o<t.length&&!(t[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof I);let i="",a=r.start;return s.forEach(c=>{const u=t.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
78
- `&&t[a-1]!==`
79
- `&&t[a]===`
80
- `&&(a+=1)}),i+=t.slice(a,r.end),I.addStringTerminator(t,r.end,i)}}class gi extends I{static endOfQuote(t,n){let r=t[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=t[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&t.push(new de(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
81
- `){I.atDocumentBoundary(s,a+1)&&t.push(new F(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=I.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new F(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
82
- `;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="…";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,t),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,t),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,t),a+=8;break;case`
83
- `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:t.push(new de(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
84
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parseCharCode(t,n,r){const{src:o}=this.context,s=o.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new de(this,`Invalid escape sequence ${o.substr(t-2,n+2)}`)),o.substr(t-2,n+2)):String.fromCodePoint(i)}parse(t,n){this.context=t;const{src:r}=t;let o=gi.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}class yi extends I{static endOfQuote(t,n){let r=t[n];for(;r;)if(r==="'"){if(t[n+1]!=="'")break;r=t[n+=2]}else r=t[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&t.push(new de(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
85
- `){I.atDocumentBoundary(s,a+1)&&t.push(new F(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=I.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new F(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&t.push(new de(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
86
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=yi.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function f$(e,t){switch(e){case _.ALIAS:return new c$(e,t);case _.BLOCK_FOLDED:case _.BLOCK_LITERAL:return new u$(e,t);case _.FLOW_MAP:case _.FLOW_SEQ:return new l$(e,t);case _.MAP_KEY:case _.MAP_VALUE:case _.SEQ_ITEM:return new mi(e,t);case _.COMMENT:case _.PLAIN:return new cf(e,t);case _.QUOTE_DOUBLE:return new gi(e,t);case _.QUOTE_SINGLE:return new yi(e,t);default:return null}}class vn{static parseType(t,n,r){switch(t[n]){case"*":return _.ALIAS;case">":return _.BLOCK_FOLDED;case"|":return _.BLOCK_LITERAL;case"{":return _.FLOW_MAP;case"[":return _.FLOW_SEQ;case"?":return!r&&I.atBlank(t,n+1,!0)?_.MAP_KEY:_.PLAIN;case":":return!r&&I.atBlank(t,n+1,!0)?_.MAP_VALUE:_.PLAIN;case"-":return!r&&I.atBlank(t,n+1,!0)?_.SEQ_ITEM:_.PLAIN;case'"':return _.QUOTE_DOUBLE;case"'":return _.QUOTE_SINGLE;default:return _.PLAIN}}constructor(t={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){me(this,"parseNode",(c,u)=>{if(I.atDocumentBoundary(this.src,u))return null;const l=new vn(this,c),{props:f,type:p,valueStart:h}=l.parseProps(u),d=f$(p,f);let m=u;try{m=d.parse(l,h)}catch(y){const $=y instanceof Error?y.message:String(y);d.error||(d.error=new de(d,$))}if(d.range=new te(u,m),m<=u&&(d.error||(d.error=new Error("Node#parse consumed no characters")),d.error.parseEnd=m,d.error.source=d,d.range.end=u+1),l.nodeStartsCollection(d)){!d.error&&!l.atLineStart&&l.parent.type===_.DOCUMENT&&(d.error=new de(d,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const y=new uf(d);return m=y.parse(new vn(l),m),y.range=new te(u,m),y}return d}),this.atLineStart=n??(t.atLineStart||!1),this.inCollection=r??(t.inCollection||!1),this.inFlow=o??(t.inFlow||!1),this.indent=s??t.indent,this.lineStart=i??t.lineStart,this.parent=a??(t.parent||{}),this.root=t.root,this.src=t.src}nodeStartsCollection(t){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(t instanceof mi)return!0;let s=t.range.end;return o[s]===`
87
- `||o[s-1]===`
88
- `?!1:(s=I.endOfWhiteSpace(o,s),o[s]===":")}parseProps(t){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;t=this.atLineStart?I.endOfIndent(o,t):I.endOfWhiteSpace(o,t);let a=o[t];for(;a===oe.ANCHOR||a===oe.COMMENT||a===oe.TAG||a===`
89
- `;){if(a===`
90
- `){let u=t,l;do l=u+1,u=I.endOfIndent(o,l);while(o[u]===`
91
- `);const f=u-(l+this.indent),p=r.type===_.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!I.nextNodeIsIndented(o[u],f,!p))break;this.atLineStart=!0,this.lineStart=l,i=!1,t=u}else if(a===oe.COMMENT){const u=I.endOfLine(o,t+1);s.push(new te(t,u)),t=u}else{let u=I.endOfIdentifier(o,t+1);a===oe.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(t+1,u+13))&&(u=I.endOfIdentifier(o,u+5)),s.push(new te(t,u)),i=!0,t=I.endOfWhiteSpace(o,u)}a=o[t]}i&&a===":"&&I.atBlank(o,t+1,!0)&&(t-=1);const c=vn.parseType(o,t,n);return{props:s,type:c,valueStart:t}}}function $i(e){const t=[];e.indexOf("\r")!==-1&&(e=e.replace(/\r\n?/g,(o,s)=>(o.length>1&&t.push(s),`
92
- `)));const n=[];let r=0;do{const o=new a$,s=new vn({src:e});r=o.parse(s,r),n.push(o)}while(r<e.length);return n.setOrigRanges=()=>{if(t.length===0)return!1;for(let s=1;s<t.length;++s)t[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(t,o);return t.splice(0,t.length),!0},n.toString=()=>n.join(`...
93
- `),n}function d$(e,t,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${t}#`)}
94
- ${t}${e}`:e}function Jt(e,t,n){return n?n.indexOf(`
95
- `)===-1?`${e} #${n}`:`${e}
96
- `+n.replace(/^/gm,`${t||""}#`):e}let we=class{};function Te(e,t,n){if(Array.isArray(e))return e.map((r,o)=>Te(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let Y=class extends we{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:Te(this.value,t,n)}toString(){return String(this.value)}};function Bc(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){const s=t[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return e.createNode(r,!1)}const hn=e=>e==null||typeof e=="object"&&e[Symbol.iterator]().next().done;let fe=class gt extends we{constructor(t){super(),me(this,"items",[]),this.schema=t}addIn(t,n){if(hn(t))this.add(n);else{const[r,...o]=t,s=this.get(r,!0);if(s instanceof gt)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Bc(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([t,...n]){if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(r instanceof gt)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn([t,...n],r){const o=this.get(t,!0);return n.length===0?!r&&o instanceof Y?o.value:o:o instanceof gt?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(t=>{if(!t||t.type!=="PAIR")return!1;const n=t.value;return n==null||n instanceof Y&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([t,...n]){if(n.length===0)return this.has(t);const r=this.get(t,!0);return r instanceof gt?r.hasIn(n):!1}setIn([t,...n],r){if(n.length===0)this.set(t,r);else{const o=this.get(t,!0);if(o instanceof gt)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(t,Bc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}}toJSON(){return null}toString(t,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=t,f=this.type===_.FLOW_MAP||this.type===_.FLOW_SEQ||t.inFlow;f&&(s+=u);const p=o&&this.hasAllNullValues();t=Object.assign({},t,{allNullValues:p,indent:s,inFlow:f,type:null});let h=!1,d=!1;const m=this.items.reduce(($,v,E)=>{let b;v&&(!h&&v.spaceBefore&&$.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{$.push({type:"comment",str:`#${j}`})}),v.comment&&(b=v.comment),f&&(!h&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(d=!0)),h=!1;let N=l(v,t,()=>b=null,()=>h=!0);return f&&!d&&N.includes(`
97
- `)&&(d=!0),f&&E<this.items.length-1&&(N+=","),N=Jt(N,s,b),h&&(b||f)&&(h=!1),$.push({type:"item",str:N}),$},[]);let y;if(m.length===0)y=r.start+r.end;else if(f){const{start:$,end:v}=r,E=m.map(b=>b.str);if(d||E.reduce((b,N)=>b+N.length+2,2)>gt.maxFlowStringSingleLineLength){y=$;for(const b of E)y+=b?`
98
- ${u}${c}${b}`:`
99
- `;y+=`
100
- ${c}${v}`}else y=`${$} ${E.join(" ")} ${v}`}else{const $=m.map(n);y=$.shift();for(const v of $)y+=v?`
101
- ${c}${v}`:`
102
- `}return this.comment?(y+=`
103
- `+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),y}};me(fe,"maxFlowStringSingleLineLength",60);function zn(e){let t=e instanceof Y?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let Le=class extends fe{add(t){this.items.push(t)}delete(t){const n=zn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=zn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof Y?o.value:o}has(t){const n=zn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=zn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Te(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const p$=(e,t,n)=>t===null?"":typeof t!="object"?String(t):e instanceof we&&n&&n.doc?e.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(t);let H=class lf extends we{constructor(t,n=null){super(),this.key=t,this.value=n,this.type=lf.Type.PAIR}get commentBefore(){return this.key instanceof we?this.key.commentBefore:void 0}set commentBefore(t){if(this.key==null&&(this.key=new Y(null)),this.key instanceof we)this.key.commentBefore=t;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(t,n){const r=Te(this.key,"",t);if(n instanceof Map){const o=Te(this.value,r,t);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=p$(this.key,r,t),s=Te(this.value,o,t);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(t,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(t,n,r){if(!t||!t.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=t.doc.options;let{key:a,value:c}=this,u=a instanceof we&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof fe){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof we?a instanceof fe||a.type===_.BLOCK_FOLDED||a.type===_.BLOCK_LITERAL:typeof a=="object"));const{doc:f,indent:p,indentStep:h,stringify:d}=t;t=Object.assign({},t,{implicitKey:!l,indent:p+h});let m=!1,y=d(a,t,()=>u=null,()=>m=!0);if(y=Jt(y,t.indent,u),!l&&y.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(t.allNullValues&&!i)return this.comment?(y=Jt(y,t.indent,this.comment),n&&n()):m&&!u&&r&&r(),t.inFlow&&!l?y:`? ${y}`;y=l?`? ${y}
104
- ${p}:`:`${y}:`,this.comment&&(y=Jt(y,t.indent,this.comment),n&&n());let $="",v=null;if(c instanceof we){if(c.spaceBefore&&($=`
105
- `),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${t.indent}#`);$+=`
106
- ${N}`}v=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof Y&&(t.indentAtStart=y.length+1),m=!1,!s&&o>=2&&!t.inFlow&&!l&&c instanceof Le&&c.type!==_.FLOW_SEQ&&!c.tag&&!f.anchors.getName(c)&&(t.indent=t.indent.substr(2));const E=d(c,t,()=>v=null,()=>m=!0);let b=" ";return $||this.comment?b=`${$}
107
- ${t.indent}`:!l&&c instanceof fe?(!(E[0]==="["||E[0]==="{")||E.includes(`
108
- `))&&(b=`
109
- ${t.indent}`):E[0]===`
110
- `&&(b=""),m&&!v&&r&&r(),Jt(y+b+E,t.indent,v)}};me(H,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const ur=(e,t)=>{if(e instanceof Ye){const n=t.get(e.source);return n.count*n.aliasCount}else if(e instanceof fe){let n=0;for(const r of e.items){const o=ur(r,t);o>n&&(n=o)}return n}else if(e instanceof H){const n=ur(e.key,t),r=ur(e.value,t);return Math.max(n,r)}return 1};let Ye=class ff extends we{static stringify({range:t,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${t}]`)}constructor(t){super(),this.source=t,this.type=_.ALIAS}set tag(t){throw new Error("Alias nodes cannot have tags")}toJSON(t,n){if(!n)return Te(this.source,t,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new An(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ur(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new An(this.cstNode,i):new ReferenceError(i)}return s.res}toString(t){return ff.stringify(this,t)}};me(Ye,"default",!0);function Ot(e,t){const n=t instanceof Y?t.value:t;for(const r of e)if(r instanceof H&&(r.key===t||r.key===n||r.key&&r.key.value===n))return r}let be=class extends fe{add(t,n){t?t instanceof H||(t=new H(t.key||t,t.value)):t=new H(t);const r=Ot(this.items,t.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=t.value;else throw new Error(`Key ${t.key} already set`);else if(o){const s=this.items.findIndex(i=>o(t,i)<0);s===-1?this.items.push(t):this.items.splice(s,0,t)}else this.items.push(t)}delete(t){const n=Ot(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const r=Ot(this.items,t),o=r&&r.value;return!n&&o instanceof Y?o.value:o}has(t){return!!Ot(this.items,t)}set(t,n){this.add(new H(t,n),!0)}toJSON(t,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(t,n,r){if(!t)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof H))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(t,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:t.indent||""},n,r)}};const df="<<";class pf extends H{constructor(t){if(t instanceof H){let n=t.value;n instanceof Le||(n=new Le,n.items.push(t.value),n.range=t.value.range),super(t.key,n),this.range=t.range}else super(new Y(df),new Le);this.type=H.Type.MERGE_PAIR}addToJSMap(t,n){for(const{source:r}of this.value.items){if(!(r instanceof be))throw new Error("Merge sources must be maps");const o=r.toJSON(null,t,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(t,n){const r=this.value;if(r.items.length>1)return super.toString(t,n);this.value=r.items[0];const o=super.toString(t,n);return this.value=r,o}}const wn={defaultType:_.BLOCK_LITERAL,lineWidth:76},Je={trueStr:"true",falseStr:"false"},at={asBigInt:!1},Zt={nullStr:"null"},Qe={defaultType:_.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function vi(e,t,n){for(const{format:r,test:o,resolve:s}of t)if(o){const i=e.match(o);if(i){let a=s.apply(null,i);return a instanceof Y||(a=new Y(a)),r&&(a.format=r),a}}return n&&(e=n(e)),new Y(e)}const hf="flow",ms="block",lr="quoted",Fc=(e,t)=>{let n=e[t+1];for(;n===" "||n===" ";){do n=e[t+=1];while(n&&n!==`
111
- `);n=e[t+1]}return t};function Rr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,m=-1,y=-1,$=-1;n===ms&&(m=Fc(e,m),m!==-1&&(f=m+c));for(let E;E=e[m+=1];){if(n===lr&&E==="\\"){switch(y=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}$=m}if(E===`
112
- `)n===ms&&(m=Fc(e,m)),f=m+c,p=void 0;else{if(E===" "&&h&&h!==" "&&h!==`
113
- `&&h!==" "){const b=e[m+1];b&&b!==" "&&b!==`
114
- `&&b!==" "&&(p=m)}if(m>=f)if(p)u.push(p),f=p+c,p=void 0;else if(n===lr){for(;h===" "||h===" ";)h=E,E=e[m+=1],d=!0;const b=m>$+1?m-2:y-1;if(l[b])return e;u.push(b),l[b]=!0,f=b+c,p=void 0}else d=!0}h=E}if(d&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let E=0;E<u.length;++E){const b=u[E],N=u[E+1]||e.length;b===0?v=`
115
- ${t}${e.slice(0,N)}`:(n===lr&&l[b]&&(v+=`${e[b]}\\`),v+=`
116
- ${t}${e.slice(b+1,N)}`)}return v}const wi=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},Qe.fold):Qe.fold,Mr=e=>/^(%|---|\.\.\.)/m.test(e);function h$(e,t,n){if(!t||t<0)return!1;const r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
117
- `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function At(e,t){const{implicitKey:n}=t,{jsonEncoding:r,minMultiLineLength:o}=Qe.doubleQuoted,s=JSON.stringify(e);if(r)return s;const i=t.indent||(Mr(e)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const f=s.substr(u+2,4);switch(f){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:f.substr(0,2)==="00"?a+="\\x"+f.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
118
-
119
- `;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
120
- `,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:Rr(a,i,lr,wi(t))}function mf(e,t){if(t.implicitKey){if(/\n/.test(e))return At(e,t)}else if(/[ \t]\n|\n[ \t]/.test(e))return At(e,t);const n=t.indent||(Mr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
121
- ${n}`)+"'";return t.implicitKey?r:Rr(r,n,hf,wi(t))}function fr({comment:e,type:t,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return At(n,r);const i=r.indent||(r.forceBlockIndent||Mr(n)?" ":""),a=i?"2":"1",c=t===_.BLOCK_FOLDED?!1:t===_.BLOCK_LITERAL?!0:!h$(n,Qe.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
122
- `;let l="",f="";if(n=n.replace(/[\n\t ]*$/,h=>{const d=h.indexOf(`
123
- `);return d===-1?u+="-":(n===h||d!==h.length-1)&&(u+="+",s&&s()),f=h.replace(/\n$/,""),""}).replace(/^[\n ]*/,h=>{h.indexOf(" ")!==-1&&(u+=a);const d=h.match(/ +$/);return d?(l=h.slice(0,-d[0].length),d[0]):(l=h,"")}),f&&(f=f.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),e&&(u+=" #"+e.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
124
- ${i}${f}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
125
- ${i}${l}${n}${f}`;n=n.replace(/\n+/g,`
126
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=Rr(`${l}${n}${f}`,i,ms,Qe.fold);return`${u}
127
- ${i}${p}`}function m$(e,t,n,r){const{comment:o,type:s,value:i}=e,{actualString:a,implicitKey:c,indent:u,inFlow:l}=t;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return At(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
128
- `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?mf(i,t):At(i,t):fr(e,t,n,r);if(!c&&!l&&s!==_.PLAIN&&i.indexOf(`
129
- `)!==-1)return fr(e,t,n,r);if(u===""&&Mr(i))return t.forceBlockIndent=!0,fr(e,t,n,r);const f=i.replace(/\n+/g,`$&
130
- ${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof vi(f,h,h.scalarFallback).value!="string")return At(i,t)}const p=c?f:Rr(f,u,hf,wi(t));return o&&!l&&(p.indexOf(`
131
- `)!==-1||o.indexOf(`
132
- `)!==-1)?(n&&n(),d$(p,u,o)):p}function bi(e,t,n,r){const{defaultType:o}=Qe,{implicitKey:s,inFlow:i}=t;let{type:a,value:c}=e;typeof c!="string"&&(c=String(c),e=Object.assign({},e,{value:c}));const u=f=>{switch(f){case _.BLOCK_FOLDED:case _.BLOCK_LITERAL:return fr(e,t,n,r);case _.QUOTE_DOUBLE:return At(c,t);case _.QUOTE_SINGLE:return mf(c,t);case _.PLAIN:return m$(e,t,n,r);default:return null}};(a!==_.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===_.BLOCK_FOLDED||a===_.BLOCK_LITERAL))&&(a=_.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function He({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=t-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function gf(e,t){let n,r;switch(t.type){case _.FLOW_MAP:n="}",r="flow map";break;case _.FLOW_SEQ:n="]",r="flow sequence";break;default:e.push(new F(t,"Not a flow collection!?"));return}let o;for(let s=t.items.length-1;s>=0;--s){const i=t.items[s];if(!i||i.type!==_.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new F(t,s),i.offset=o.offset+1):(i=new F(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),e.push(i)}}function yf(e,t){const n=t.context.src[t.range.start-1];if(n!==`
133
- `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new F(t,r))}}function $f(e,t){const n=String(t),r=n.substr(0,8)+"..."+n.substr(-8);return new F(e,`The "${r}" key is too long`)}function vf(e,t){for(const{afterKey:n,before:r,comment:o}of t){let s=e.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
134
- `+o:s.commentBefore=o):o!==void 0&&(e.comment?e.comment+=`
135
- `+o:e.comment=o)}}function Bn(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function g$(e,t){const{handle:n,suffix:r}=t.tag;let o=e.tagPrefixes.find(s=>s.handle===n);if(!o){const s=e.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new F(t,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new F(t,`The ${n} tag has no suffix.`);if(n==="!"&&(e.version||e.options.version)==="1.0"){if(r[0]==="^")return e.warnings.push(new rn(t,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function y$(e,t){const{tag:n,type:r}=t;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;e.errors.push(new F(t,c))}else if(s==="!"&&!i)o=!0;else try{return g$(e,t)}catch(c){e.errors.push(c)}}switch(r){case _.BLOCK_FOLDED:case _.BLOCK_LITERAL:case _.QUOTE_DOUBLE:case _.QUOTE_SINGLE:return rt.STR;case _.FLOW_MAP:case _.MAP:return rt.MAP;case _.FLOW_SEQ:case _.SEQ:return rt.SEQ;case _.PLAIN:return o?rt.STR:null;default:return null}}function qc(e,t,n){const{tags:r}=e.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(e,t);return a instanceof fe?a:new Y(a)}const s=Bn(e,t);return typeof s=="string"&&o.length>0?vi(s,o,r.scalarFallback):null}function $$({type:e}){switch(e){case _.FLOW_MAP:case _.MAP:return rt.MAP;case _.FLOW_SEQ:case _.SEQ:return rt.SEQ;default:return rt.STR}}function v$(e,t,n){try{const r=qc(e,t,n);if(r)return n&&t.tag&&(r.tag=n),r}catch(r){if(r instanceof jt)r.source||(r.source=t),e.errors.push(r);else{const o=r instanceof Error?r.message:String(r);e.errors.push(new F(t,o))}return null}try{const r=$$(t);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;e.warnings.push(new rn(t,o));const s=qc(e,t,r);return s.tag=n,s}catch(r){const o=new An(t,r.message);return o.stack=r.stack,e.errors.push(o),null}}const w$=e=>{if(!e)return!1;const{type:t}=e;return t===_.MAP_KEY||t===_.MAP_VALUE||t===_.SEQ_ITEM};function b$(e,t){const n={before:[],after:[]};let r=!1,o=!1;const s=w$(t.context.parent)?t.context.parent.props.concat(t.props):t.props;for(const{start:i,end:a}of s)switch(t.context.src[i]){case oe.COMMENT:{if(!t.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";e.push(new F(t,l))}const{header:c,valueRange:u}=t;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(t.context.src.slice(i+1,a));break}case oe.ANCHOR:if(r){const c="A node can have at most one anchor";e.push(new F(t,c))}r=!0;break;case oe.TAG:if(o){const c="A node can have at most one tag";e.push(new F(t,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function E$(e,t){const{anchors:n,errors:r,schema:o}=e;if(t.type===_.ALIAS){const i=t.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new An(t,u)),null}const c=new Ye(a);return n._cstAliases.push(c),c}const s=y$(e,t);if(s)return v$(e,t,s);if(t.type!==_.PLAIN){const i=`Failed to resolve ${t.type} node here`;return r.push(new de(t,i)),null}try{const i=Bn(e,t);return vi(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=t),r.push(i),null}}function st(e,t){if(!t)return null;t.error&&e.errors.push(t.error);const{comments:n,hasAnchor:r,hasTag:o}=b$(e.errors,t);if(r){const{anchors:i}=e,a=t.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=t}if(t.type===_.ALIAS&&(r||o)){const i="An alias node must not specify any properties";e.errors.push(new F(t,i))}const s=E$(e,t);if(s){s.range=[t.range.start,t.range.end],e.options.keepCstNodes&&(s.cstNode=t),e.options.keepNodeTypes&&(s.type=t.type);const i=n.before.join(`
136
- `);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
137
- ${i}`:i);const a=n.after.join(`
138
- `);a&&(s.comment=s.comment?`${s.comment}
139
- ${a}`:a)}return t.resolved=s}function wf(e,t){if(t.type!==_.MAP&&t.type!==_.FLOW_MAP){const i=`A ${t.type} node cannot be resolved as a mapping`;return e.errors.push(new de(t,i)),null}const{comments:n,items:r}=t.type===_.FLOW_MAP?k$(e,t):O$(e,t),o=new be;o.items=r,vf(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof fe&&(s=!0),e.schema.merge&&a&&a.value===df){r[i]=new pf(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof Ye){const{type:f}=l.source;return f===_.MAP||f===_.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&e.errors.push(new F(t,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;e.errors.push(new F(t,l));break}}}if(s&&!e.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new rn(t,i))}return t.resolved=o,o}const S$=({context:{lineStart:e,node:t,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(t&&o>t.valueRange.start||n[o]!==oe.COMMENT)return!1;for(let s=e;s<o;++s)if(n[s]===`
140
- `)return!1;return!0};function N$(e,t){if(!S$(e))return;const n=e.getPropValue(0,oe.COMMENT,!0);let r=!1;const o=t.value.commentBefore;if(o&&o.startsWith(n))t.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=t.value.comment;!e.node&&s&&s.startsWith(n)&&(t.value.comment=s.substr(n.length+1),r=!0)}r&&(t.comment=n)}function O$(e,t){const n=[],r=[];let o,s=null;for(let i=0;i<t.items.length;++i){const a=t.items[i];switch(a.type){case _.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case _.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case _.MAP_KEY:o!==void 0&&r.push(new H(o)),a.error&&e.errors.push(a.error),o=st(e,a.node),s=null;break;case _.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&e.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===_.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";e.errors.push(new F(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new cf(_.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const f=a.range.origStart+1;c.range.origStart=c.range.origEnd=f,c.valueRange.origStart=c.valueRange.origEnd=f}}const u=new H(o,st(e,c));N$(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&e.errors.push($f(t,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new H(o)),o=st(e,a),s=a.range.start,a.error&&e.errors.push(a.error);e:for(let c=i+1;;++c){const u=t.items[c];switch(u&&u.type){case _.BLANK_LINE:case _.COMMENT:continue e;case _.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";e.errors.push(new F(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";e.errors.push(new F(a,c))}}}return o!==void 0&&r.push(new H(o)),{comments:n,items:r}}function k$(e,t){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<t.items.length;++a){const c=t.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new H(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===t.items.length-1)continue}else if(u===i){i=":";continue}const f=`Flow map contains an unexpected ${u}`,p=new de(t,f);p.offset=l,e.errors.push(p)}else c.type===_.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===_.COMMENT?(yf(e.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&e.errors.push(new F(c,"Separator , missing in flow map")),o=st(e,c)):(i!==","&&e.errors.push(new F(c,"Indicator : missing in flow map entry")),r.push(new H(o,st(e,c))),o=void 0,s=!1)}return gf(e.errors,t),o!==void 0&&r.push(new H(o)),{comments:n,items:r}}function bf(e,t){if(t.type!==_.SEQ&&t.type!==_.FLOW_SEQ){const s=`A ${t.type} node cannot be resolved as a sequence`;return e.errors.push(new de(t,s)),null}const{comments:n,items:r}=t.type===_.FLOW_SEQ?A$(e,t):_$(e,t),o=new Le;if(o.items=r,vf(o,n),!e.options.mapAsMap&&r.some(s=>s instanceof H&&s.key instanceof fe)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new rn(t,s))}return t.resolved=o,o}function _$(e,t){const n=[],r=[];for(let o=0;o<t.items.length;++o){const s=t.items[o];switch(s.type){case _.BLANK_LINE:n.push({before:r.length});break;case _.COMMENT:n.push({comment:s.comment,before:r.length});break;case _.SEQ_ITEM:if(s.error&&e.errors.push(s.error),r.push(st(e,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";e.errors.push(new F(s,i))}break;default:s.error&&e.errors.push(s.error),e.errors.push(new de(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function A$(e,t){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<t.items.length;++u){const l=t.items[u];if(typeof l.char=="string"){const{char:f,offset:p}=l;if(f!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new H(s)),o=!1,s=void 0,i=null),f===a)a=null;else if(!a&&f==="?")o=!0;else if(a!=="["&&f===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof H){const h="Chaining flow sequence pairs is invalid",d=new F(t,h);d.offset=p,e.errors.push(d)}if(!o&&typeof i=="number"){const h=l.range?l.range.start:l.offset;h>i+1024&&e.errors.push($f(t,s));const{src:d}=c.context;for(let m=i;m<h;++m)if(d[m]===`
141
- `){const y="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new F(c,y));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new de(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===_.BLANK_LINE)n.push({before:r.length});else if(l.type===_.COMMENT)yf(e.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const p=`Expected a ${a} in flow sequence`;e.errors.push(new F(l,p))}const f=st(e,l);s===void 0?(r.push(f),c=l):(r.push(new H(s,f)),s=void 0),i=l.range.start,a=","}}return gf(e.errors,t),s!==void 0&&r.push(new H(s)),{comments:n,items:r}}const Ef={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(e,t)=>{const n=Bn(e,t);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return e.errors.push(new An(t,r)),null}},options:wn,stringify:({comment:e,type:t,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t||(t=wn.defaultType),t===_.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=wn,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,f=0;l<c;++l,f+=a)u[l]=i.substr(f,a);n=u.join(t===_.BLOCK_LITERAL?`
142
- `:" ")}return bi({comment:e,type:t,value:n},r,o,s)}};function Sf(e,t){const n=bf(e,t);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof H)){if(o instanceof be){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new F(t,i)}const s=o.items[0]||new H;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
143
- ${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
144
- ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof H?o:new H(o)}}return n}function Nf(e,t,n){const r=new Le(e);r.tag="tag:yaml.org,2002:pairs";for(const o of t){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=e.createPair(s,i,n);r.items.push(a)}return r}const Of={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Sf,createNode:Nf};let Dr=class kf extends Le{constructor(){super(),me(this,"add",be.prototype.add.bind(this)),me(this,"delete",be.prototype.delete.bind(this)),me(this,"get",be.prototype.get.bind(this)),me(this,"has",be.prototype.has.bind(this)),me(this,"set",be.prototype.set.bind(this)),this.tag=kf.tag}toJSON(t,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof H?(s=Te(o.key,"",n),i=Te(o.value,s,n)):s=Te(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};me(Dr,"tag","tag:yaml.org,2002:omap");function j$(e,t){const n=Sf(e,t),r=[];for(const{key:o}of n.items)if(o instanceof Y)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new F(t,s)}else r.push(o.value);return Object.assign(new Dr,n)}function I$(e,t,n){const r=Nf(e,t,n),o=new Dr;return o.items=r.items,o}const _f={identify:e=>e instanceof Map,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:omap",resolve:j$,createNode:I$};let Lr=class Af extends be{constructor(){super(),this.tag=Af.tag}add(t){const n=t instanceof H?t:new H(t);Ot(this.items,n.key)||this.items.push(n)}get(t,n){const r=Ot(this.items,t);return!n&&r instanceof H?r.key instanceof Y?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=Ot(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new H(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(t,n,r);throw new Error("Set items must all have null values")}};me(Lr,"tag","tag:yaml.org,2002:set");function x$(e,t){const n=wf(e,t);if(!n.hasAllNullValues())throw new F(t,"Set items must all have null values");return Object.assign(new Lr,n)}function P$(e,t,n){const r=new Lr;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const jf={identify:e=>e instanceof Set,nodeClass:Lr,default:!1,tag:"tag:yaml.org,2002:set",resolve:x$,createNode:P$},Ei=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},If=({value:e})=>{if(isNaN(e)||!isFinite(e))return He(e);let t="";e<0&&(t="-",e=Math.abs(e));const n=[e%60];return e<60?n.unshift(0):(e=Math.round((e-n[0])/60),n.unshift(e%60),e>=60&&(e=Math.round((e-n[0])/60),n.unshift(e))),t+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},xf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(e,t,n)=>Ei(t,n.replace(/_/g,"")),stringify:If},Pf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(e,t,n)=>Ei(t,n.replace(/_/g,"")),stringify:If},Tf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(e,t,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(t,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=Ei(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Cf(e){const t=typeof process<"u"&&process.env||{};return e?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!t.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!t.YAML_SILENCE_WARNINGS}function Rf(e,t){if(Cf(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const Vc={};function T$(e,t){if(!Vc[e]&&Cf(!0)){Vc[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,Rf(n,"DeprecationWarning")}}function C$(e,t,n){const r=new be(e);if(t instanceof Map)for(const[o,s]of t)r.items.push(e.createPair(o,s,n));else if(t&&typeof t=="object")for(const o of Object.keys(t))r.items.push(e.createPair(o,t[o],n));return typeof e.sortMapEntries=="function"&&r.items.sort(e.sortMapEntries),r}const In={createNode:C$,default:!0,nodeClass:be,tag:"tag:yaml.org,2002:map",resolve:wf};function R$(e,t,n){const r=new Le(e);if(t&&t[Symbol.iterator])for(const o of t){const s=e.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Ur={createNode:R$,default:!0,nodeClass:Le,tag:"tag:yaml.org,2002:seq",resolve:bf},M$={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Bn,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),bi(e,t,n,r)},options:Qe},Si=[In,Ur,M$],Br=e=>typeof e=="bigint"||Number.isInteger(e),Ni=(e,t,n)=>at.asBigInt?BigInt(e):parseInt(t,n);function Mf(e,t,n){const{value:r}=e;return Br(r)&&r>=0?n+r.toString(t):He(e)}const Df={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Zt,stringify:()=>Zt.nullStr},Lf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>e[0]==="t"||e[0]==="T",options:Je,stringify:({value:e})=>e?Je.trueStr:Je.falseStr},Uf={identify:e=>Br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>Ni(e,t,8),options:at,stringify:e=>Mf(e,8,"0o")},Bf={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>Ni(e,e,10),options:at,stringify:He},Ff={identify:e=>Br(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>Ni(e,t,16),options:at,stringify:e=>Mf(e,16,"0x")},qf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},Vf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify:({value:e})=>Number(e).toExponential()},Kf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(e,t,n){const r=t||n,o=new Y(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:He},D$=Si.concat([Df,Lf,Uf,Bf,Ff,qf,Vf,Kf]),Kc=e=>typeof e=="bigint"||Number.isInteger(e),Wn=({value:e})=>JSON.stringify(e),Gf=[In,Ur,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Bn,stringify:Wn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Wn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:Wn},{identify:Kc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>at.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>Kc(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Wn}];Gf.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Gc=({value:e})=>e?Je.trueStr:Je.falseStr,mn=e=>typeof e=="bigint"||Number.isInteger(e);function Yn(e,t,n){let r=t.replace(/_/g,"");if(at.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return e==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return e==="-"?-1*o:o}function ko(e,t,n){const{value:r}=e;if(mn(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return He(e)}const L$=Si.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Zt,stringify:()=>Zt.nullStr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Je,stringify:Gc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Je,stringify:Gc},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Yn(t,n,2),stringify:e=>ko(e,2,"0b")},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Yn(t,n,8),stringify:e=>ko(e,8,"0")},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Yn(t,n,10),stringify:He},{identify:mn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Yn(t,n,16),stringify:e=>ko(e,16,"0x")},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:He},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify:({value:e})=>Number(e).toExponential()},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(e,t){const n=new Y(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:He}],Ef,_f,Of,jf,xf,Pf,Tf),U$={core:D$,failsafe:Si,json:Gf,yaml11:L$},B$={binary:Ef,bool:Lf,float:Kf,floatExp:Vf,floatNaN:qf,floatTime:Pf,int:Bf,intHex:Ff,intOct:Uf,intTime:xf,map:In,null:Df,omap:_f,pairs:Of,seq:Ur,set:jf,timestamp:Tf};function F$(e,t,n){if(t){const r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>(r.identify&&r.identify(e)||r.class&&e instanceof r.class)&&!r.format)}function q$(e,t,n){if(e instanceof we)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=F$(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new Y(e):e;c=e instanceof Map?In:e[Symbol.iterator]?Ur:In}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(e&&typeof e=="object"&&s){const l=s.get(e);if(l){const f=new Ye(l);return n.aliasNodes.push(f),f}u.value=e,s.set(e,u)}return u.node=c.createNode?c.createNode(n.schema,e,n):a?new Y(e):e,t&&u.node instanceof we&&(u.node.tag=t),u.node}function V$(e,t,n,r){let o=e[r.replace(/\W/g,"")];if(!o){const s=Object.keys(e).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=t[i];if(!a){const c=Object.keys(t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const K$=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let xn=class Jf{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?K$:o||null,!t&&s&&T$("tags","customTags"),this.tags=V$(U$,B$,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Jf.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return q$(t,r,i)}createPair(t,n,r){r||(r={wrapScalars:!0});const o=this.createNode(t,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new H(o,s)}};me(xn,"defaultPrefix",cr);me(xn,"defaultTags",rt);const Er={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},G$={get binary(){return wn},set binary(e){Object.assign(wn,e)},get bool(){return Je},set bool(e){Object.assign(Je,e)},get int(){return at},set int(e){Object.assign(at,e)},get null(){return Zt},set null(e){Object.assign(Zt,e)},get str(){return Qe},set str(e){Object.assign(Qe,e)}},Hf={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:cr},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:cr}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:cr}]}};function Jc(e,t){if((e.version||e.options.version)==="1.0"){const o=t.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=t.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${t.replace(/^tag:/,"")}`}let n=e.tagPrefixes.find(o=>t.indexOf(o.prefix)===0);if(!n){const o=e.getDefaults().tagPrefixes;n=o&&o.find(s=>t.indexOf(s.prefix)===0)}if(!n)return t[0]==="!"?t:`!<${t}>`;const r=t.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function J$(e,t){if(t instanceof Ye)return Ye;if(t.tag){const o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)||o[0]}let n,r;if(t instanceof Y){r=t.value;const o=e.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===t.format)||o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function H$(e,t,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(e);return s&&(n[s]=e,o.push(`&${s}`)),e.tag?o.push(Jc(r,e.tag)):t.default||o.push(Jc(r,t.tag)),o.join(" ")}function Qn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof we)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};e=s.createNode(e,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let f=o.getName(l.source);f||(f=o.newName(),o.map[f]=l.source)}}if(e instanceof H)return e.toString(t,n,r);i||(i=J$(s.tags,e));const a=H$(e,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(e,t,n,r):e instanceof Y?bi(e,t,n,r):e.toString(t,n,r);return a?e instanceof Y||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
145
- ${t.indent}${c}`:c}class Oi{static validAnchorNode(t){return t instanceof Y||t instanceof Le||t instanceof be}constructor(t){me(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new Ye(t)}createMergePair(...t){const n=new pf;return n.value.items=t.map(r=>{if(r instanceof Ye){if(r.source instanceof be)return r}else if(r instanceof be)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(t){const{map:n}=this;return Object.keys(n).find(r=>n[r]===t)}getNames(){return Object.keys(this.map)}getNode(t){return this.map[t]}newName(t){t||(t=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${t}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:t,_cstAliases:n}=this;Object.keys(t).forEach(r=>{t[r]=t[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(t,n){if(t!=null&&!Oi.validAnchorNode(t))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=t&&Object.keys(r).find(s=>r[s]===t);if(o)if(n)o!==n&&(delete r[o],r[n]=t);else return o;else{if(!n){if(!t)return null;n=this.newName()}r[n]=t}return n}}const dr=(e,t)=>{if(e&&typeof e=="object"){const{tag:n}=e;e instanceof fe?(n&&(t[n]=!0),e.items.forEach(r=>dr(r,t))):e instanceof H?(dr(e.key,t),dr(e.value,t)):e instanceof Y&&n&&(t[n]=!0)}return t},z$=e=>Object.keys(dr(e,{}));function W$(e,t){const n={before:[],after:[]};let r,o=!1;for(const s of t)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";e.errors.push(new de(s,a));break}const i=st(e,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===_.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!e.commentBefore&&(e.commentBefore=n.before.join(`
146
- `),n.before=[]));if(e.contents=r||null,!r)e.comment=n.before.concat(n.after).join(`
147
- `)||null;else{const s=n.before.join(`
148
- `);if(s){const i=r instanceof fe&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
149
- ${i.commentBefore}`:s}e.comment=n.after.join(`
150
- `)||null}}function Y$({tagPrefixes:e},t){const[n,r]=t.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new F(t,o)}if(e.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new F(t,o)}return{handle:n,prefix:r}}function Q$(e,t){let[n]=t.parameters;if(t.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new F(t,r)}if(!Hf[n]){const r=`Document will be parsed as YAML ${e.version||e.options.version} rather than YAML ${n}`;e.warnings.push(new rn(t,r))}return n}function Z$(e,t,n){const r=[];let o=!1;for(const s of t){const{comment:i,name:a}=s;switch(a){case"TAG":try{e.tagPrefixes.push(Y$(e,s))}catch(c){e.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(e.version){const c="The %YAML directive must only be given at most once per document.";e.errors.push(new F(s,c))}try{e.version=Q$(e,s)}catch(c){e.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;e.warnings.push(new rn(s,c))}}i&&r.push(i)}if(n&&!o&&(e.version||n.version||e.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});e.tagPrefixes=n.tagPrefixes.map(s),e.version=n.version}e.commentBefore=r.join(`
151
- `)||null}function Ct(e){if(e instanceof fe)return!0;throw new Error("Expected a YAML collection as document contents")}let ki=class gs{constructor(t){this.anchors=new Oi(t.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=t,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(t){return Ct(this.contents),this.contents.add(t)}addIn(t,n){Ct(this.contents),this.contents.addIn(t,n)}delete(t){return Ct(this.contents),this.contents.delete(t)}deleteIn(t){return hn(t)?this.contents==null?!1:(this.contents=null,!0):(Ct(this.contents),this.contents.deleteIn(t))}getDefaults(){return gs.defaults[this.version]||gs.defaults[this.options.version]||{}}get(t,n){return this.contents instanceof fe?this.contents.get(t,n):void 0}getIn(t,n){return hn(t)?!n&&this.contents instanceof Y?this.contents.value:this.contents:this.contents instanceof fe?this.contents.getIn(t,n):void 0}has(t){return this.contents instanceof fe?this.contents.has(t):!1}hasIn(t){return hn(t)?this.contents!==void 0:this.contents instanceof fe?this.contents.hasIn(t):!1}set(t,n){Ct(this.contents),this.contents.set(t,n)}setIn(t,n){hn(t)?this.contents=n:(Ct(this.contents),this.contents.setIn(t,n))}setSchema(t,n){if(!t&&!n&&this.schema)return;typeof t=="number"&&(t=t.toFixed(1)),t==="1.0"||t==="1.1"||t==="1.2"?(this.version?this.version=t:this.options.version=t,delete this.options.schema):t&&typeof t=="string"&&(this.options.schema=t),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new xn(r)}parse(t,n){this.options.keepCstNodes&&(this.cstNode=t),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=t;if(i&&(i.source||(i.source=this),this.errors.push(i)),Z$(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],W$(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof jt&&c.makePretty();for(const c of this.warnings)c instanceof jt&&c.makePretty()}return this}listNonDefaultTags(){return z$(this.contents).filter(t=>t.indexOf(xn.defaultPrefix)!==0)}setTagPrefix(t,n){if(t[0]!=="!"||t[t.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===t);r?r.prefix=n:this.tagPrefixes.push({handle:t,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==t)}toJSON(t,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof t!="string"||!(this.contents instanceof Y)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Qn},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=Te(this.contents,t,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:f}of a.anchors.values())n(f,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const t=this.options.indent;if(!Number.isInteger(t)||t<=0){const c=JSON.stringify(t);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(t),stringify:Qn};let i=!1,a=null;if(this.contents){this.contents instanceof we&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Qn(this.contents,s,()=>a=null,c);n.push(Jt(u,"",a))}else this.contents!==void 0&&n.push(Qn(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
152
- `)+`
153
- `}};me(ki,"defaults",Hf);function X$(e,t=!0,n){n===void 0&&typeof t=="string"&&(n=t,t=!0);const r=Object.assign({},ki.defaults[Er.version],Er);return new xn(r).createNode(e,t,n)}class Fr extends ki{constructor(t){super(Object.assign({},Er,t))}}function ev(e,t){const n=[];let r;for(const o of $i(e)){const s=new Fr(t);s.parse(o,r),n.push(s),r=s}return n}function zf(e,t){const n=$i(e),r=new Fr(t).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new F(n[1],o))}return r}function tv(e,t){const n=zf(e,t);if(n.warnings.forEach(r=>Rf(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function nv(e,t){const n=new Fr(t);return n.contents=e,String(n)}const rv={createNode:X$,defaultOptions:Er,Document:Fr,parse:tv,parseAllDocuments:ev,parseCST:$i,parseDocument:zf,scalarOptions:G$,stringify:nv},ov=Object.freeze(Object.defineProperty({__proto__:null,YAML:rv},Symbol.toStringTag,{value:"Module"})),sv=t$(ov);var iv=sv.YAML;const av="1.0.0-redesign.1",cv="adhd",uv="default",lv="adhd-environment.json",_o="config.yaml",fv="config.local.yaml",dv={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Hc extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function zc(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function Wf(e,t){const n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){const i=n[s].codePointAt(0)??0,a=r[s].codePointAt(0)??0;if(i!==a)return i<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function Wc(e){return new TextEncoder().encode(e).length}function pv(e){const t=Object.keys(e).sort(Wf);let n="";for(const r of t){const o=e[r];if(zc(r))throw new Hc("key",r);if(zc(o))throw new Hc("value",o);n+=`${Wc(r)}:${r}=${Wc(o)}:${o}
154
- `}return`sha256-${Yf(n)}`}function hv(e){const t=[...e].sort((n,r)=>Wf(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
155
- `);return`sha256-${Yf(t)}`}function mv(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function gv(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function yv(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=t;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=$v(o);return}const u=i.properties[a];if(u===void 0){const l={type:"object",properties:{}};i.properties[a]=l,i=l}else i=u})}return t}function $v(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const vv="adhd-env-ref:";function wv(e){return`${vv}${e}`}const bv=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ev=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Re(e,t){return(e>>>t|e<<32-t)>>>0}function Sv(e){const t=Uint32Array.from(Ev),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const s=Math.floor(n/4294967296),i=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,s,!1),a.setUint32(r-4,i,!1);const c=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(f+b*4,!1);for(let b=16;b<64;b++){const N=c[b-15],j=c[b-2],R=Re(N,7)^Re(N,18)^N>>>3,J=Re(j,17)^Re(j,19)^j>>>10;c[b]=c[b-16]+R+c[b-7]+J>>>0}let p=t[0],h=t[1],d=t[2],m=t[3],y=t[4],$=t[5],v=t[6],E=t[7];for(let b=0;b<64;b++){const N=Re(y,6)^Re(y,11)^Re(y,25),j=y&$^~y&v,R=E+N+j+bv[b]+c[b]>>>0,J=Re(p,2)^Re(p,13)^Re(p,22),U=p&h^p&d^h&d,q=J+U>>>0;E=v,v=$,$=y,y=m+R>>>0,m=d,d=h,h=p,p=R+q>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+y>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+E>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let f=0;f<8;f++)l.setUint32(f*4,t[f],!1);return u}function Nv(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Yf(e){const t=new TextEncoder().encode(e);return Nv(Sv(t))}function Qf(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const s=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,Qf(o,s)):n[s]=o}return n}function Zn(e){if(C.existsSync(e))try{const t=C.readFileSync(e,"utf8"),n=iv.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Qf(n)}catch{return}}function Ov(e){return{system:Zn(T.join(e.system,_o)),global:Zn(T.join(e.global,_o)),project:e.project?Zn(T.join(e.project,_o)):void 0,local:e.project?Zn(T.join(e.project,fv)):void 0}}function kv(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function ys(e,t){if(e===void 0)return e;switch(t){case"integer":{if(typeof e=="number")return e;const n=parseInt(String(e),10);return Number.isNaN(n)?e:n}case"number":{if(typeof e=="number")return e;const n=parseFloat(String(e));return Number.isNaN(n)?e:n}case"boolean":{if(typeof e=="boolean")return e;const n=String(e).toLowerCase();return n==="true"?!0:n==="false"?!1:e}case"array":return Array.isArray(e)?e:typeof e=="string"?e.length===0?[]:e.split(",").map(n=>n.trim()):e;case"string":return typeof e=="string"?e:String(e);default:return e}}function Zf(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((s,i)=>{if(i===r.length-1){o[s]=e[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return t}const _v=[["system","system"],["global","global"],["project","project"],["local","local"]];function Av(e,t,n,r){const o={},s={},i={},a={};for(const c of Object.keys(e)){const u=e[c],l=u.env&&u.env!==""?u.env:gv(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[E,b]of _v){const N=t[E];N&&Object.prototype.hasOwnProperty.call(N,c)&&(h=ys(N[c],u.type),d=b)}const m=n[l];let y,$,v;m!==void 0?(y=ys(m,u.type),$="env",v=l):(y=h,$=d),o[c]=f?wv(l):y,s[c]=y,i[c]=kv(f?{source:"env",scope:p,env:l}:{source:$,scope:p,env:v}),a[c]={...u,env:l,live:f,fallbackValue:h}}return{raw:o,nested:Zf(o),typedRaw:s,provenance:i,fields:a}}function jv(e,t){return e.replace(/\$\{HOME\}/g,Ue.homedir()).replace(/\$HOME\b/g,Ue.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Iv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??dv[o.kind],a=o.path?jv(o.path,t):T.join(of(t.roots,s),r),c=i==="per-instance"?T.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function xv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=t[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:T.join(s.path,o.name),share:o.share??"shared"}}return n}var $s={exports:{}},Xf={},Ce={},Xt={},Fn={},G={},Pn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((E,b)=>`${E}${b}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,b)=>(b instanceof n&&(E[b.str]=(E[b.str]||0)+1),E),{})}}e._Code=r,e.nil=new r("");function o($,...v){const E=[$[0]];let b=0;for(;b<v.length;)a(E,v[b]),E.push($[++b]);return new r(E)}e._=o;const s=new r("+");function i($,...v){const E=[h($[0])];let b=0;for(;b<v.length;)E.push(s),a(E,v[b]),E.push(s,h($[++b]));return c(E),new r(E)}e.str=i;function a($,v){v instanceof r?$.push(...v._items):v instanceof n?$.push(v):$.push(f(v))}e.addCodeArg=a;function c($){let v=1;for(;v<$.length-1;){if($[v]===s){const E=u($[v-1],$[v+1]);if(E!==void 0){$.splice(v-1,3,E);continue}$[v++]="+"}v++}}function u($,v){if(v==='""')return $;if($==='""')return v;if(typeof $=="string")return v instanceof n||$[$.length-1]!=='"'?void 0:typeof v!="string"?`${$.slice(0,-1)}${v}"`:v[0]==='"'?$.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!($ instanceof n))return`"${$}${v.slice(1)}`}function l($,v){return v.emptyStr()?$:$.emptyStr()?v:i`${$}${v}`}e.strConcat=l;function f($){return typeof $=="number"||typeof $=="boolean"||$===null?$:h(Array.isArray($)?$.join(","):$)}function p($){return new r(h($))}e.stringify=p;function h($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function d($){return typeof $=="string"&&e.IDENTIFIER.test($)?new r(`.${$}`):o`[${$}]`}e.getProperty=d;function m($){if(typeof $=="string"&&e.IDENTIFIER.test($))return new r(`${$}`);throw new Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}e.getEsmExportName=m;function y($){return new r($.toString())}e.regexpCode=y})(Pn);var vs={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Pn;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,f;if(!((f=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||f===void 0)&&f.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=o;class s extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:f}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${f}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,d=(f=l.key)!==null&&f!==void 0?f:l.ref;let m=this._values[h];if(m){const v=m.get(d);if(v)return v}else m=this._values[h]=new Map;m.set(d,p);const y=this._scope[h]||(this._scope[h]=[]),$=y.length;return y[$]=l.ref,p.setValue(l,{property:h,itemIndex:$}),p}getValue(u,l){const f=this._values[u];if(f)return f.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${u}${f.scopePath}`})}scopeCode(u=this._values,l,f){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,f)}_reduceValues(u,l,f={},p){let h=t.nil;for(const d in u){const m=u[d];if(!m)continue;const y=f[d]=f[d]||new Map;m.forEach($=>{if(y.has($))return;y.set($,r.Started);let v=l($);if(v){const E=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${E} ${$} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p($))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new n($);y.set($,r.Completed)})}return h}}e.ValueScope=a})(vs);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=Pn,n=vs;var r=Pn;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=vs;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(g,w){return this}}class i extends s{constructor(g,w,k){super(),this.varKind=g,this.name=w,this.rhs=k}render({es5:g,_n:w}){const k=g?n.varKinds.var:this.varKind,D=this.rhs===void 0?"":` = ${this.rhs}`;return`${k} ${this.name}${D};`+w}optimizeNames(g,w){if(g[this.name.str])return this.rhs&&(this.rhs=_e(this.rhs,g,w)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(g,w,k){super(),this.lhs=g,this.rhs=w,this.sideEffects=k}render({_n:g}){return`${this.lhs} = ${this.rhs};`+g}optimizeNames(g,w){if(!(this.lhs instanceof t.Name&&!g[this.lhs.str]&&!this.sideEffects))return this.rhs=_e(this.rhs,g,w),this}get names(){const g=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ye(g,this.rhs)}}class c extends a{constructor(g,w,k,D){super(g,k,D),this.op=w}render({_n:g}){return`${this.lhs} ${this.op}= ${this.rhs};`+g}}class u extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`${this.label}:`+g}}class l extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`break${this.label?` ${this.label}`:""};`+g}}class f extends s{constructor(g){super(),this.error=g}render({_n:g}){return`throw ${this.error};`+g}get names(){return this.error.names}}class p extends s{constructor(g){super(),this.code=g}render({_n:g}){return`${this.code};`+g}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(g,w){return this.code=_e(this.code,g,w),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(g=[]){super(),this.nodes=g}render(g){return this.nodes.reduce((w,k)=>w+k.render(g),"")}optimizeNodes(){const{nodes:g}=this;let w=g.length;for(;w--;){const k=g[w].optimizeNodes();Array.isArray(k)?g.splice(w,1,...k):k?g[w]=k:g.splice(w,1)}return g.length>0?this:void 0}optimizeNames(g,w){const{nodes:k}=this;let D=k.length;for(;D--;){const L=k[D];L.optimizeNames(g,w)||(Ve(g,L.names),k.splice(D,1))}return k.length>0?this:void 0}get names(){return this.nodes.reduce((g,w)=>Z(g,w.names),{})}}class d extends h{render(g){return"{"+g._n+super.render(g)+"}"+g._n}}class m extends h{}class y extends d{}y.kind="else";class $ extends d{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();const g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){const k=w.optimizeNodes();w=this.else=Array.isArray(k)?new y(k):k}if(w)return g===!1?w instanceof $?w:w.nodes:this.nodes.length?this:new $(pe(g),w instanceof $?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var k;if(this.else=(k=this.else)===null||k===void 0?void 0:k.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=_e(this.condition,g,w),this}get names(){const g=super.names;return ye(g,this.condition),this.else&&Z(g,this.else.names),g}}$.kind="if";class v extends d{}v.kind="for";class E extends v{constructor(g){super(),this.iteration=g}render(g){return`for(${this.iteration})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iteration=_e(this.iteration,g,w),this}get names(){return Z(super.names,this.iteration.names)}}class b extends v{constructor(g,w,k,D){super(),this.varKind=g,this.name=w,this.from=k,this.to=D}render(g){const w=g.es5?n.varKinds.var:this.varKind,{name:k,from:D,to:L}=this;return`for(${w} ${k}=${D}; ${k}<${L}; ${k}++)`+super.render(g)}get names(){const g=ye(super.names,this.from);return ye(g,this.to)}}class N extends v{constructor(g,w,k,D){super(),this.loop=g,this.varKind=w,this.name=k,this.iterable=D}render(g){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iterable=_e(this.iterable,g,w),this}get names(){return Z(super.names,this.iterable.names)}}class j extends d{constructor(g,w,k){super(),this.name=g,this.args=w,this.async=k}render(g){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(g)}}j.kind="func";class R extends h{render(g){return"return "+super.render(g)}}R.kind="return";class J extends d{render(g){let w="try"+super.render(g);return this.catch&&(w+=this.catch.render(g)),this.finally&&(w+=this.finally.render(g)),w}optimizeNodes(){var g,w;return super.optimizeNodes(),(g=this.catch)===null||g===void 0||g.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(g,w){var k,D;return super.optimizeNames(g,w),(k=this.catch)===null||k===void 0||k.optimizeNames(g,w),(D=this.finally)===null||D===void 0||D.optimizeNames(g,w),this}get names(){const g=super.names;return this.catch&&Z(g,this.catch.names),this.finally&&Z(g,this.finally.names),g}}class U extends d{constructor(g){super(),this.error=g}render(g){return`catch(${this.error})`+super.render(g)}}U.kind="catch";class q extends d{render(g){return"finally"+super.render(g)}}q.kind="finally";class Q{constructor(g,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
156
- `:""},this._extScope=g,this._scope=new n.Scope({parent:g}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(g){return this._scope.name(g)}scopeName(g){return this._extScope.name(g)}scopeValue(g,w){const k=this._extScope.value(g,w);return(this._values[k.prefix]||(this._values[k.prefix]=new Set)).add(k),k}getScopeValue(g,w){return this._extScope.getValue(g,w)}scopeRefs(g){return this._extScope.scopeRefs(g,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(g,w,k,D){const L=this._scope.toName(w);return k!==void 0&&D&&(this._constants[L.str]=k),this._leafNode(new i(g,L,k)),L}const(g,w,k){return this._def(n.varKinds.const,g,w,k)}let(g,w,k){return this._def(n.varKinds.let,g,w,k)}var(g,w,k){return this._def(n.varKinds.var,g,w,k)}assign(g,w,k){return this._leafNode(new a(g,w,k))}add(g,w){return this._leafNode(new c(g,e.operators.ADD,w))}code(g){return typeof g=="function"?g():g!==t.nil&&this._leafNode(new p(g)),this}object(...g){const w=["{"];for(const[k,D]of g)w.length>1&&w.push(","),w.push(k),(k!==D||this.opts.es5)&&(w.push(":"),(0,t.addCodeArg)(w,D));return w.push("}"),new t._Code(w)}if(g,w,k){if(this._blockNode(new $(g)),w&&k)this.code(w).else().code(k).endIf();else if(w)this.code(w).endIf();else if(k)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(g){return this._elseNode(new $(g))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode($,y)}_for(g,w){return this._blockNode(g),w&&this.code(w).endFor(),this}for(g,w){return this._for(new E(g),w)}forRange(g,w,k,D,L=this.opts.es5?n.varKinds.var:n.varKinds.let){const W=this._scope.toName(g);return this._for(new b(L,W,w,k),()=>D(W))}forOf(g,w,k,D=n.varKinds.const){const L=this._scope.toName(g);if(this.opts.es5){const W=w instanceof t.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,t._)`${W}.length`,z=>{this.var(L,(0,t._)`${W}[${z}]`),k(L)})}return this._for(new N("of",D,L,w),()=>k(L))}forIn(g,w,k,D=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(g,(0,t._)`Object.keys(${w})`,k);const L=this._scope.toName(g);return this._for(new N("in",D,L,w),()=>k(L))}endFor(){return this._endBlockNode(v)}label(g){return this._leafNode(new u(g))}break(g){return this._leafNode(new l(g))}return(g){const w=new R;if(this._blockNode(w),this.code(g),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(R)}try(g,w,k){if(!w&&!k)throw new Error('CodeGen: "try" without "catch" and "finally"');const D=new J;if(this._blockNode(D),this.code(g),w){const L=this.name("e");this._currNode=D.catch=new U(L),w(L)}return k&&(this._currNode=D.finally=new q,this.code(k)),this._endBlockNode(U,q)}throw(g){return this._leafNode(new f(g))}block(g,w){return this._blockStarts.push(this._nodes.length),g&&this.code(g).endBlock(w),this}endBlock(g){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const k=this._nodes.length-w;if(k<0||g!==void 0&&k!==g)throw new Error(`CodeGen: wrong number of nodes: ${k} vs ${g} expected`);return this._nodes.length=w,this}func(g,w=t.nil,k,D){return this._blockNode(new j(g,w,k)),D&&this.code(D).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(g=1){for(;g-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(g){return this._currNode.nodes.push(g),this}_blockNode(g){this._currNode.nodes.push(g),this._nodes.push(g)}_endBlockNode(g,w){const k=this._currNode;if(k instanceof g||w&&k instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${g.kind}/${w.kind}`:g.kind}"`)}_elseNode(g){const w=this._currNode;if(!(w instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=g,this}get _root(){return this._nodes[0]}get _currNode(){const g=this._nodes;return g[g.length-1]}set _currNode(g){const w=this._nodes;w[w.length-1]=g}}e.CodeGen=Q;function Z(O,g){for(const w in g)O[w]=(O[w]||0)+(g[w]||0);return O}function ye(O,g){return g instanceof t._CodeOrName?Z(O,g.names):O}function _e(O,g,w){if(O instanceof t.Name)return k(O);if(!D(O))return O;return new t._Code(O._items.reduce((L,W)=>(W instanceof t.Name&&(W=k(W)),W instanceof t._Code?L.push(...W._items):L.push(W),L),[]));function k(L){const W=w[L.str];return W===void 0||g[L.str]!==1?L:(delete g[L.str],W)}function D(L){return L instanceof t._Code&&L._items.some(W=>W instanceof t.Name&&g[W.str]===1&&w[W.str]!==void 0)}}function Ve(O,g){for(const w in g)O[w]=(O[w]||0)-(g[w]||0)}function pe(O){return typeof O=="boolean"||typeof O=="number"||O===null?!O:(0,t._)`!${A(O)}`}e.not=pe;const cn=S(e.operators.AND);function no(...O){return O.reduce(cn)}e.and=no;const Kn=S(e.operators.OR);function x(...O){return O.reduce(Kn)}e.or=x;function S(O){return(g,w)=>g===t.nil?w:w===t.nil?g:(0,t._)`${A(g)} ${O} ${A(w)}`}function A(O){return O instanceof t.Name?O:(0,t._)`(${O})`}})(G);var P={};Object.defineProperty(P,"__esModule",{value:!0});P.checkStrictMode=P.getErrorPath=P.Type=P.useFunc=P.setEvaluated=P.evaluatedPropsToName=P.mergeEvaluated=P.eachItem=P.unescapeJsonPointer=P.escapeJsonPointer=P.escapeFragment=P.unescapeFragment=P.schemaRefOrVal=P.schemaHasRulesButRef=P.schemaHasRules=P.checkUnknownRules=P.alwaysValidSchema=P.toHash=void 0;const X=G,Pv=Pn;function Tv(e){const t={};for(const n of e)t[n]=!0;return t}P.toHash=Tv;function Cv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(ed(e,t),!td(t,e.self.RULES.all))}P.alwaysValidSchema=Cv;function ed(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||od(e,`unknown keyword: "${s}"`)}P.checkUnknownRules=ed;function td(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}P.schemaHasRules=td;function Rv(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}P.schemaHasRulesButRef=Rv;function Mv({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,X._)`${n}`}return(0,X._)`${e}${t}${(0,X.getProperty)(r)}`}P.schemaRefOrVal=Mv;function Dv(e){return nd(decodeURIComponent(e))}P.unescapeFragment=Dv;function Lv(e){return encodeURIComponent(_i(e))}P.escapeFragment=Lv;function _i(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}P.escapeJsonPointer=_i;function nd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}P.unescapeJsonPointer=nd;function Uv(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}P.eachItem=Uv;function Yc({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof X.Name?(s instanceof X.Name?e(o,s,i):t(o,s,i),i):s instanceof X.Name?(t(o,i,s),s):n(s,i);return a===X.Name&&!(c instanceof X.Name)?r(o,c):c}}P.mergeEvaluated={props:Yc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,X._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,X._)`${n} || {}`).code((0,X._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,X._)`${n} || {}`),Ai(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:rd}),items:Yc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,X._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,X._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function rd(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,X._)`{}`);return t!==void 0&&Ai(e,n,t),n}P.evaluatedPropsToName=rd;function Ai(e,t,n){Object.keys(n).forEach(r=>e.assign((0,X._)`${t}${(0,X.getProperty)(r)}`,!0))}P.setEvaluated=Ai;const Qc={};function Bv(e,t){return e.scopeValue("func",{ref:t,code:Qc[t.code]||(Qc[t.code]=new Pv._Code(t.code))})}P.useFunc=Bv;var ws;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ws||(P.Type=ws={}));function Fv(e,t,n){if(e instanceof X.Name){const r=t===ws.Num;return n?r?(0,X._)`"[" + ${e} + "]"`:(0,X._)`"['" + ${e} + "']"`:r?(0,X._)`"/" + ${e}`:(0,X._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,X.getProperty)(e).toString():"/"+_i(e)}P.getErrorPath=Fv;function od(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}P.checkStrictMode=od;var Fe={};Object.defineProperty(Fe,"__esModule",{value:!0});const he=G,qv={data:new he.Name("data"),valCxt:new he.Name("valCxt"),instancePath:new he.Name("instancePath"),parentData:new he.Name("parentData"),parentDataProperty:new he.Name("parentDataProperty"),rootData:new he.Name("rootData"),dynamicAnchors:new he.Name("dynamicAnchors"),vErrors:new he.Name("vErrors"),errors:new he.Name("errors"),this:new he.Name("this"),self:new he.Name("self"),scope:new he.Name("scope"),json:new he.Name("json"),jsonPos:new he.Name("jsonPos"),jsonLen:new he.Name("jsonLen"),jsonPart:new he.Name("jsonPart")};Fe.default=qv;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=G,n=P,r=Fe;e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:$})=>$?(0,t.str)`"${y}" keyword must be ${$} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,$=e.keywordError,v,E){const{it:b}=y,{gen:N,compositeRule:j,allErrors:R}=b,J=f(y,$,v);E??(j||R)?c(N,J):u(b,(0,t._)`[${J}]`)}e.reportError=o;function s(y,$=e.keywordError,v){const{it:E}=y,{gen:b,compositeRule:N,allErrors:j}=E,R=f(y,$,v);c(b,R),N||j||u(E,r.default.vErrors)}e.reportExtraError=s;function i(y,$){y.assign(r.default.errors,$),y.if((0,t._)`${r.default.vErrors} !== null`,()=>y.if($,()=>y.assign((0,t._)`${r.default.vErrors}.length`,$),()=>y.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:y,keyword:$,schemaValue:v,data:E,errsCount:b,it:N}){if(b===void 0)throw new Error("ajv implementation error");const j=y.name("err");y.forRange("i",b,r.default.errors,R=>{y.const(j,(0,t._)`${r.default.vErrors}[${R}]`),y.if((0,t._)`${j}.instancePath === undefined`,()=>y.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(r.default.instancePath,N.errorPath))),y.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${$}`),N.opts.verbose&&(y.assign((0,t._)`${j}.schema`,v),y.assign((0,t._)`${j}.data`,E))})}e.extendErrors=a;function c(y,$){const v=y.const("err",$);y.if((0,t._)`${r.default.vErrors} === null`,()=>y.assign(r.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${r.default.vErrors}.push(${v})`),y.code((0,t._)`${r.default.errors}++`)}function u(y,$){const{gen:v,validateName:E,schemaEnv:b}=y;b.$async?v.throw((0,t._)`new ${y.ValidationError}(${$})`):(v.assign((0,t._)`${E}.errors`,$),v.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(y,$,v){const{createErrors:E}=y.it;return E===!1?(0,t._)`{}`:p(y,$,v)}function p(y,$,v={}){const{gen:E,it:b}=y,N=[h(b,v),d(y,v)];return m(y,$,N),E.object(...N)}function h({errorPath:y},{instancePath:$}){const v=$?(0,t.str)`${y}${(0,n.getErrorPath)($,n.Type.Str)}`:y;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,v)]}function d({keyword:y,it:{errSchemaPath:$}},{schemaPath:v,parentSchema:E}){let b=E?$:(0,t.str)`${$}/${y}`;return v&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,b]}function m(y,{params:$,message:v},E){const{keyword:b,data:N,schemaValue:j,it:R}=y,{opts:J,propertyName:U,topSchemaRef:q,schemaPath:Q}=R;E.push([l.keyword,b],[l.params,typeof $=="function"?$(y):$||(0,t._)`{}`]),J.messages&&E.push([l.message,typeof v=="function"?v(y):v]),J.verbose&&E.push([l.schema,j],[l.parentSchema,(0,t._)`${q}${Q}`],[r.default.data,N]),U&&E.push([l.propertyName,U])}})(Fn);Object.defineProperty(Xt,"__esModule",{value:!0});Xt.boolOrEmptySchema=Xt.topBoolOrEmptySchema=void 0;const Vv=Fn,Kv=G,Gv=Fe,Jv={message:"boolean schema is false"};function Hv(e){const{gen:t,schema:n,validateName:r}=e;n===!1?sd(e,!1):typeof n=="object"&&n.$async===!0?t.return(Gv.default.data):(t.assign((0,Kv._)`${r}.errors`,null),t.return(!0))}Xt.topBoolOrEmptySchema=Hv;function zv(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),sd(e)):n.var(t,!0)}Xt.boolOrEmptySchema=zv;function sd(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Vv.reportError)(o,Jv,void 0,t)}var ie={},It={};Object.defineProperty(It,"__esModule",{value:!0});It.getRules=It.isJSONType=void 0;const Wv=["string","number","integer","boolean","null","object","array"],Yv=new Set(Wv);function Qv(e){return typeof e=="string"&&Yv.has(e)}It.isJSONType=Qv;function Zv(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}It.getRules=Zv;var ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.shouldUseRule=ze.shouldUseGroup=ze.schemaHasRulesForType=void 0;function Xv({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&id(e,r)}ze.schemaHasRulesForType=Xv;function id(e,t){return t.rules.some(n=>ad(e,n))}ze.shouldUseGroup=id;function ad(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}ze.shouldUseRule=ad;Object.defineProperty(ie,"__esModule",{value:!0});ie.reportTypeError=ie.checkDataTypes=ie.checkDataType=ie.coerceAndCheckDataType=ie.getJSONTypes=ie.getSchemaTypes=ie.DataType=void 0;const e0=It,t0=ze,n0=Fn,V=G,cd=P;var Wt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Wt||(ie.DataType=Wt={}));function r0(e){const t=ud(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ie.getSchemaTypes=r0;function ud(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(e0.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ie.getJSONTypes=ud;function o0(e,t){const{gen:n,data:r,opts:o}=e,s=s0(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,t0.schemaHasRulesForType)(e,t[0]));if(i){const a=ji(t,r,o.strictNumbers,Wt.Wrong);n.if(a,()=>{s.length?i0(e,t,s):Ii(e)})}return i}ie.coerceAndCheckDataType=o0;const ld=new Set(["string","number","integer","boolean","null"]);function s0(e,t){return t?e.filter(n=>ld.has(n)||t==="array"&&n==="array"):[]}function i0(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,V._)`typeof ${o}`),a=r.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&r.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(ji(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,V._)`${a} !== undefined`);for(const u of n)(ld.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Ii(e),r.endIf(),r.if((0,V._)`${a} !== undefined`,()=>{r.assign(o,a),a0(e,a)});function c(u){switch(u){case"string":r.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":r.elseIf((0,V._)`${i} == "boolean" || ${o} === null
157
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,V._)`+${o}`);return;case"integer":r.elseIf((0,V._)`${i} === "boolean" || ${o} === null
158
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,V._)`+${o}`);return;case"boolean":r.elseIf((0,V._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,V._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,V._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,V._)`${i} === "string" || ${i} === "number"
159
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function a0({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${n}]`,r))}function bs(e,t,n,r=Wt.Correct){const o=r===Wt.Correct?V.operators.EQ:V.operators.NEQ;let s;switch(e){case"null":return(0,V._)`${t} ${o} null`;case"array":s=(0,V._)`Array.isArray(${t})`;break;case"object":s=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${t} ${o} ${e}`}return r===Wt.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,a,n?(0,V._)`isFinite(${t})`:V.nil)}}ie.checkDataType=bs;function ji(e,t,n,r){if(e.length===1)return bs(e[0],t,n,r);let o;const s=(0,cd.toHash)(e);if(s.array&&s.object){const i=(0,V._)`typeof ${t} != "object"`;o=s.null?i:(0,V._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(const i in s)o=(0,V.and)(o,bs(i,t,n,r));return o}ie.checkDataTypes=ji;const c0={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`};function Ii(e){const t=u0(e);(0,n0.reportError)(t,c0)}ie.reportTypeError=Ii;function u0(e){const{gen:t,data:n,schema:r}=e,o=(0,cd.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var qr={};Object.defineProperty(qr,"__esModule",{value:!0});qr.assignDefaults=void 0;const Rt=G,l0=P;function f0(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Zc(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Zc(e,s,o.default))}qr.assignDefaults=f0;function Zc(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,Rt._)`${s}${(0,Rt.getProperty)(t)}`;if(o){(0,l0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Rt._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Rt._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Rt._)`${a} = ${(0,Rt.stringify)(n)}`)}var De={},K={};Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;const ee=G,xi=P,Xe=Fe,d0=P;function p0(e,t){const{gen:n,data:r,it:o}=e;n.if(Ti(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=p0;function h0({gen:e,data:t,it:{opts:n}},r,o){return(0,ee.or)(...r.map(s=>(0,ee.and)(Ti(e,t,s,n.ownProperties),(0,ee._)`${o} = ${s}`)))}K.checkMissingProp=h0;function m0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=m0;function fd(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=fd;function Pi(e,t,n){return(0,ee._)`${fd(e)}.call(${t}, ${n})`}K.isOwnProperty=Pi;function g0(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} !== undefined`;return r?(0,ee._)`${o} && ${Pi(e,t,n)}`:o}K.propertyInData=g0;function Ti(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} === undefined`;return r?(0,ee.or)(o,(0,ee.not)(Pi(e,t,n))):o}K.noPropertyInData=Ti;function dd(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=dd;function y0(e,t){return dd(t).filter(n=>!(0,xi.alwaysValidSchema)(e,t[n]))}K.schemaProperties=y0;function $0({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ee._)`${e}, ${t}, ${r}${o}`:t,f=[[Xe.default.instancePath,(0,ee.strConcat)(Xe.default.instancePath,s)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);const p=(0,ee._)`${l}, ${n.object(...f)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${p})`:(0,ee._)`${a}(${p})`}K.callValidateCode=$0;const v0=(0,ee._)`new RegExp`;function w0({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ee._)`${o.code==="new RegExp"?v0:(0,d0.useFunc)(e,o)}(${n}, ${r})`})}K.usePattern=w0;function b0(e){const{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){const c=t.const("len",(0,ee._)`${n}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:r,dataProp:u,dataPropType:xi.Type.Num},s),t.if((0,ee.not)(s),a)})}}K.validateArray=b0;function E0(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,xi.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=t.let("valid",!1),i=t.name("_valid");t.block(()=>n.forEach((a,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);t.assign(s,(0,ee._)`${s} || ${i}`),e.mergeValidEvaluated(u,i)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=E0;Object.defineProperty(De,"__esModule",{value:!0});De.validateKeywordUsage=De.validSchemaType=De.funcKeywordCode=De.macroKeywordCode=void 0;const $e=G,$t=Fe,S0=K,N0=Fn;function O0(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=pd(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");e.subschema({schema:a,schemaPath:$e.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}De.macroKeywordCode=O0;function k0(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;A0(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=pd(r,o,u),f=r.let("valid");e.block$data(f,p),e.ok((n=t.valid)!==null&&n!==void 0?n:f);function p(){if(t.errors===!1)m(),t.modifying&&Xc(e),y(()=>e.error());else{const $=t.async?h():d();t.modifying&&Xc(e),y(()=>_0(e,$))}}function h(){const $=r.let("ruleErrs",null);return r.try(()=>m((0,$e._)`await `),v=>r.assign(f,!1).if((0,$e._)`${v} instanceof ${c.ValidationError}`,()=>r.assign($,(0,$e._)`${v}.errors`),()=>r.throw(v))),$}function d(){const $=(0,$e._)`${l}.errors`;return r.assign($,null),m($e.nil),$}function m($=t.async?(0,$e._)`await `:$e.nil){const v=c.opts.passContext?$t.default.this:$t.default.self,E=!("compile"in t&&!a||t.schema===!1);r.assign(f,(0,$e._)`${$}${(0,S0.callValidateCode)(e,l,v,E)}`,t.modifying)}function y($){var v;r.if((0,$e.not)((v=t.valid)!==null&&v!==void 0?v:f),$)}}De.funcKeywordCode=k0;function Xc(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,$e._)`${r.parentData}[${r.parentDataProperty}]`))}function _0(e,t){const{gen:n}=e;n.if((0,$e._)`Array.isArray(${t})`,()=>{n.assign($t.default.vErrors,(0,$e._)`${$t.default.vErrors} === null ? ${t} : ${$t.default.vErrors}.concat(${t})`).assign($t.default.errors,(0,$e._)`${$t.default.vErrors}.length`),(0,N0.extendErrors)(e)},()=>e.error())}function A0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function pd(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,$e.stringify)(n)})}function j0(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}De.validSchemaType=j0;function I0({schema:e,opts:t,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const i=o.dependencies;if(i!=null&&i.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}De.validateKeywordUsage=I0;var it={};Object.defineProperty(it,"__esModule",{value:!0});it.extendSubschemaMode=it.extendSubschemaData=it.getSubschema=void 0;const Me=G,hd=P;function x0(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}${(0,Me.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,hd.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}it.getSubschema=x0;function P0(e,t,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=t;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:f}=t,p=a.let("data",(0,Me._)`${t.data}${(0,Me.getProperty)(n)}`,!0);c(p),e.errorPath=(0,Me.str)`${u}${(0,hd.getErrorPath)(n,r,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Me._)`${n}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){const u=o instanceof Me.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}it.extendSubschemaData=P0;function T0(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}it.extendSubschemaMode=T0;var le={},md=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},gd={exports:{}},ot=gd.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};pr(t,r,o,e,"",e)};ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ot.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ot.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function pr(e,t,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in ot.arrayKeywords)for(var p=0;p<f.length;p++)pr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in ot.propsKeywords){if(f&&typeof f=="object")for(var h in f)pr(e,t,n,f[h],o+"/"+l+"/"+C0(h),s,o,l,r,h)}else(l in ot.keywords||e.allKeys&&!(l in ot.skipKeywords))&&pr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function C0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var R0=gd.exports;Object.defineProperty(le,"__esModule",{value:!0});le.getSchemaRefs=le.resolveUrl=le.normalizeId=le._getFullPath=le.getFullPath=le.inlineRef=void 0;const M0=P,D0=md,L0=R0,U0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Es(e):t?yd(e)<=t:!1}le.inlineRef=B0;const F0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Es(e){for(const t in e){if(F0.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(Es)||typeof n=="object"&&Es(n))return!0}return!1}function yd(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!U0.has(n)&&(typeof e[n]=="object"&&(0,M0.eachItem)(e[n],r=>t+=yd(r)),t===1/0)))return 1/0;return t}function $d(e,t="",n){n!==!1&&(t=Yt(t));const r=e.parse(t);return vd(e,r)}le.getFullPath=$d;function vd(e,t){return e.serialize(t).split("#")[0]+"#"}le._getFullPath=vd;const q0=/#\/?$/;function Yt(e){return e?e.replace(q0,""):""}le.normalizeId=Yt;function V0(e,t,n){return n=Yt(n),e.resolve(t,n)}le.resolveUrl=V0;const K0=/^[a-z_][-a-z0-9._]*$/i;function G0(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Yt(e[n]||t),s={"":o},i=$d(r,o,!1),a={},c=new Set;return L0(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const m=i+p;let y=s[d];typeof f[n]=="string"&&(y=$.call(this,f[n])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),s[p]=y;function $(E){const b=this.opts.uriResolver.resolve;if(E=Yt(y?b(y,E):E),c.has(E))throw l(E);c.add(E);let N=this.refs[E];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(f,N.schema,E):E!==Yt(m)&&(E[0]==="#"?(u(f,a[E],E),a[E]=f):this.refs[E]=m),E}function v(E){if(typeof E=="string"){if(!K0.test(E))throw new Error(`invalid anchor "${E}"`);$.call(this,`#${E}`)}}}),a;function u(f,p,h){if(p!==void 0&&!D0(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}le.getSchemaRefs=G0;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.getData=Ce.KeywordCxt=Ce.validateFunctionCode=void 0;const wd=Xt,eu=ie,Ci=ze,Sr=ie,J0=qr,bn=De,Ao=it,M=G,B=Fe,H0=le,We=P,ln=Fn;function z0(e){if(Sd(e)&&(Nd(e),Ed(e))){Q0(e);return}bd(e,()=>(0,wd.topBoolOrEmptySchema)(e))}Ce.validateFunctionCode=z0;function bd({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,M._)`${B.default.data}, ${B.default.valCxt}`,r.$async,()=>{e.code((0,M._)`"use strict"; ${tu(n,o)}`),Y0(e,o),e.code(s)}):e.func(t,(0,M._)`${B.default.data}, ${W0(o)}`,r.$async,()=>e.code(tu(n,o)).code(s))}function W0(e){return(0,M._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${e.dynamicRef?(0,M._)`, ${B.default.dynamicAnchors}={}`:M.nil}}={}`}function Y0(e,t){e.if(B.default.valCxt,()=>{e.var(B.default.instancePath,(0,M._)`${B.default.valCxt}.${B.default.instancePath}`),e.var(B.default.parentData,(0,M._)`${B.default.valCxt}.${B.default.parentData}`),e.var(B.default.parentDataProperty,(0,M._)`${B.default.valCxt}.${B.default.parentDataProperty}`),e.var(B.default.rootData,(0,M._)`${B.default.valCxt}.${B.default.rootData}`),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,M._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{e.var(B.default.instancePath,(0,M._)`""`),e.var(B.default.parentData,(0,M._)`undefined`),e.var(B.default.parentDataProperty,(0,M._)`undefined`),e.var(B.default.rootData,B.default.data),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,M._)`{}`)})}function Q0(e){const{schema:t,opts:n,gen:r}=e;bd(e,()=>{n.$comment&&t.$comment&&kd(e),nw(e),r.let(B.default.vErrors,null),r.let(B.default.errors,0),n.unevaluated&&Z0(e),Od(e),sw(e)})}function Z0(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,M._)`${n}.evaluated`),t.if((0,M._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,M._)`${e.evaluated}.props`,(0,M._)`undefined`)),t.if((0,M._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,M._)`${e.evaluated}.items`,(0,M._)`undefined`))}function tu(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,M._)`/*# sourceURL=${n} */`:M.nil}function X0(e,t){if(Sd(e)&&(Nd(e),Ed(e))){ew(e,t);return}(0,wd.boolOrEmptySchema)(e,t)}function Ed({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function Sd(e){return typeof e.schema!="boolean"}function ew(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&kd(e),rw(e),ow(e);const s=r.const("_errs",B.default.errors);Od(e,s),r.var(t,(0,M._)`${s} === ${B.default.errors}`)}function Nd(e){(0,We.checkUnknownRules)(e),tw(e)}function Od(e,t){if(e.opts.jtd)return nu(e,[],!1,t);const n=(0,eu.getSchemaTypes)(e.schema),r=(0,eu.coerceAndCheckDataType)(e,n);nu(e,n,!r,t)}function tw(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,We.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function nw(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,We.checkStrictMode)(e,"default is ignored in the schema root")}function rw(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,H0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ow(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function kd({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,M._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,M.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,M._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function sw(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,M._)`${B.default.errors} === 0`,()=>t.return(B.default.data),()=>t.throw((0,M._)`new ${o}(${B.default.vErrors})`)):(t.assign((0,M._)`${r}.errors`,B.default.vErrors),s.unevaluated&&iw(e),t.return((0,M._)`${B.default.errors} === 0`))}function iw({gen:e,evaluated:t,props:n,items:r}){n instanceof M.Name&&e.assign((0,M._)`${t}.props`,n),r instanceof M.Name&&e.assign((0,M._)`${t}.items`,r)}function nu(e,t,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,We.schemaHasRulesButRef)(s,l))){o.block(()=>jd(e,"$ref",l.all.$ref.definition));return}c.jtd||aw(e,t),o.block(()=>{for(const p of l.rules)f(p);f(l.post)});function f(p){(0,Ci.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Sr.checkDataType)(p.type,i,c.strictNumbers)),ru(e,p),t.length===1&&t[0]===p.type&&n&&(o.else(),(0,Sr.reportTypeError)(e)),o.endIf()):ru(e,p),a||o.if((0,M._)`${B.default.errors} === ${r||0}`))}}function ru(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,J0.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,Ci.shouldUseRule)(r,s)&&jd(e,s.keyword,s.definition,t.type)})}function aw(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(cw(e,t),e.opts.allowUnionTypes||uw(e,t),lw(e,e.dataTypes))}function cw(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{_d(e.dataTypes,n)||Ri(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),dw(e,t)}}function uw(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ri(e,"use allowUnionTypes to allow union type keyword")}function lw(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,Ci.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>fw(t,i))&&Ri(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function fw(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function _d(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function dw(e,t){const n=[];for(const r of e.dataTypes)_d(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Ri(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,We.checkStrictMode)(e,t,e.opts.strictTypes)}class Ad{constructor(t,n,r){if((0,bn.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,We.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",Id(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,bn.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",B.default.errors))}result(t,n,r){this.failResult((0,M.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,M.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:n}=this;this.fail((0,M._)`${n} !== undefined && (${(0,M.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?ln.reportExtraError:ln.reportError)(this,this.def.error,n)}$dataError(){(0,ln.reportError)(this,this.def.$dataError||ln.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ln.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=M.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=M.nil,n=M.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,M.or)((0,M._)`${o} === undefined`,n)),t!==M.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==M.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,M.or)(i(),a());function i(){if(r.length){if(!(n instanceof M.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,M._)`${(0,Sr.checkDataTypes)(c,n,s.opts.strictNumbers,Sr.DataType.Wrong)}`}return M.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,M._)`!${c}(${n})`}return M.nil}}subschema(t,n){const r=(0,Ao.getSubschema)(this.it,t);(0,Ao.extendSubschemaData)(r,this.it,t),(0,Ao.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return X0(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=We.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=We.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,M.Name)),!0}}Ce.KeywordCxt=Ad;function jd(e,t,n,r){const o=new Ad(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,bn.funcKeywordCode)(o,n):"macro"in n?(0,bn.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,bn.funcKeywordCode)(o,n)}const pw=/^\/(?:[^~]|~0|~1)*$/,hw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Id(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return B.default.rootData;if(e[0]==="/"){if(!pw.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=B.default.rootData}else{const u=hw.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return r[t-l]}if(l>t)throw new Error(c("data",l));if(s=n[t-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,M._)`${s}${(0,M.getProperty)((0,We.unescapeJsonPointer)(u))}`,i=(0,M._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Ce.getData=Id;var qn={};Object.defineProperty(qn,"__esModule",{value:!0});let mw=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};qn.default=mw;var on={};Object.defineProperty(on,"__esModule",{value:!0});const jo=le;class gw extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,jo.resolveUrl)(t,n,r),this.missingSchema=(0,jo.normalizeId)((0,jo.getFullPath)(t,this.missingRef))}}on.default=gw;var Ee={};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.resolveSchema=Ee.getCompilingSchema=Ee.resolveRef=Ee.compileSchema=Ee.SchemaEnv=void 0;const Ie=G,yw=qn,dt=Fe,Pe=le,ou=P,$w=Ce;class Vr{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Pe.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}Ee.SchemaEnv=Vr;function Mi(e){const t=xd.call(this,e);if(t)return t;const n=(0,Pe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ie.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:yw.default,code:(0,Ie._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:dt.default.data,parentData:dt.default.parentData,parentDataProperty:dt.default.parentDataProperty,dataNames:[dt.default.data],dataPathArr:[Ie.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ie.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ie.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ie._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,$w.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(dt.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${dt.default.self}`,`${dt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:h,items:d}=u;p.evaluated={props:h instanceof Ie.Name?void 0:h,items:d instanceof Ie.Name?void 0:d,dynamicProps:h instanceof Ie.Name,dynamicItems:d instanceof Ie.Name},p.source&&(p.source.evaluated=(0,Ie.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}Ee.compileSchema=Mi;function vw(e,t,n){var r;n=(0,Pe.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=Ew.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Vr({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=ww.call(this,s)}Ee.resolveRef=vw;function ww(e){return(0,Pe.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Mi.call(this,e)}function xd(e){for(const t of this._compilations)if(bw(t,e))return t}Ee.getCompilingSchema=xd;function bw(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Ew(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Kr.call(this,e,t)}function Kr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Pe._getFullPath)(this.opts.uriResolver,n);let o=(0,Pe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return Io.call(this,n,e);const s=(0,Pe.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Kr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:Io.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||Mi.call(this,i),s===(0,Pe.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pe.resolveUrl)(this.opts.uriResolver,o,u)),new Vr({schema:a,schemaId:c,root:e,baseId:o})}return Io.call(this,n,i)}}Ee.resolveSchema=Kr;const Sw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Io(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,ou.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Sw.has(a)&&u&&(t=(0,Pe.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,ou.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Pe.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Kr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Vr({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const Nw="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Ow="Meta-schema for $data reference (JSON AnySchema extension proposal)",kw="object",_w=["$data"],Aw={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},jw=!1,Iw={$id:Nw,description:Ow,type:kw,required:_w,properties:Aw,additionalProperties:jw};var Di={},Gr={exports:{}};const xw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Pd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Li=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Td=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Pw=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Cd(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const Tw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function su(e){return e.length=0,!0}function Cw(e,t,n){if(e.length){const r=Cd(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function Rw(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Cw;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=su}else{o.push(u);continue}}return o.length&&(a===su?n.zone=o.join(""):i?r.push(o.join("")):r.push(Cd(o))),n.address=r.join(""),n}function Rd(e){if(Mw(e,":")<2)return{host:e,isIPV6:!1};const t=Rw(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Mw(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Dw(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}const Lw={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Uw=/[@/?#:]/g,Bw=/[@/?#]/g;function Md(e,t){const n=t?Bw:Uw;return n.lastIndex=0,e.replace(n,r=>Lw[r])}function Fw(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const o=e.slice(r+1,r+3);if(Li(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Td(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function qw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(Li(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Td(s)?t+=s:t+="%"+o,n+=2;continue}}Pw(e[n])?t+=e[n]:t+=escape(e[n])}return t}function Vw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(Li(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function Kw(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Pd(n)){const r=Rd(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Md(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var Dd={nonSimpleDomain:Tw,recomposeAuthority:Kw,reescapeHostDelimiters:Md,normalizePercentEncoding:Fw,normalizePathEncoding:qw,escapePreservingEscapes:Vw,removeDotSegments:Dw,isIPv4:Pd,isUUID:xw,normalizeIPv6:Rd};const{isUUID:Gw}=Dd,Jw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Ld(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Ud(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Bd(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function Hw(e){return e.secure=Ld(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function zw(e){if((e.port===(Ld(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function Ww(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(Jw);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=Ui(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Yw(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=Ui(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function Qw(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!Gw(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Zw(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Fd={scheme:"http",domainHost:!0,parse:Ud,serialize:Bd},Xw={scheme:"https",domainHost:Fd.domainHost,parse:Ud,serialize:Bd},hr={scheme:"ws",domainHost:!0,parse:Hw,serialize:zw},eb={scheme:"wss",domainHost:hr.domainHost,parse:hr.parse,serialize:hr.serialize},tb={scheme:"urn",parse:Ww,serialize:Yw,skipNormalize:!0},nb={scheme:"urn:uuid",parse:Qw,serialize:Zw,skipNormalize:!0},Nr={http:Fd,https:Xw,ws:hr,wss:eb,urn:tb,"urn:uuid":nb};Object.setPrototypeOf(Nr,null);function Ui(e){return e&&(Nr[e]||Nr[e.toLowerCase()])||void 0}var rb={SCHEMES:Nr,getSchemeHandler:Ui};const{normalizeIPv6:ob,removeDotSegments:gn,recomposeAuthority:sb,normalizePercentEncoding:ib,normalizePathEncoding:ab,escapePreservingEscapes:cb,reescapeHostDelimiters:ub,isIPv4:lb,nonSimpleDomain:fb}=Dd,{SCHEMES:db,getSchemeHandler:qd}=rb;function pb(e,t){return typeof e=="string"?e=vb(e,t):typeof e=="object"&&(e=en(xt(e,t),t)),e}function hb(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Vd(en(e,r),en(t,r),r,!0);return r.skipEscape=!0,xt(o,r)}function Vd(e,t,n,r){const o={};return r||(e=en(xt(e,n),n),t=en(xt(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=gn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=gn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=gn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=gn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function mb(e,t,n){const r=iu(e,n),o=iu(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function xt(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=qd(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=ib(n.path):(n.path=cb(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=sb(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=gn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const gb=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yb=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function $b(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Kd(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);const i=e.match(yb);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=e.match(gb);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=$b(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(lb(r.host)===!1){const l=ob(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const u=qd(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&fb(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=ub(unescape(r.host),s))),r.path&&(r.path=ab(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function en(e,t){return Kd(e,t).parsed}function vb(e,t){return Gd(e,t).normalized}function Gd(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Kd(e,t);return{normalized:r?e:xt(n,t),malformedAuthorityOrPort:r}}function iu(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Gd(e,t);return r?void 0:n}if(typeof e=="object")return xt(e,t)}const Bi={SCHEMES:db,normalize:pb,resolve:hb,resolveComponent:Vd,equal:mb,serialize:xt,parse:en};Gr.exports=Bi;Gr.exports.default=Bi;Gr.exports.fastUri=Bi;var wb=Gr.exports;Object.defineProperty(Di,"__esModule",{value:!0});const Jd=wb;Jd.code='require("ajv/dist/runtime/uri").default';Di.default=Jd;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Ce;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=qn,o=on,s=It,i=Ee,a=G,c=le,u=ie,l=P,f=Iw,p=Di,h=(x,S)=>new RegExp(x,S);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function E(x){var S,A,O,g,w,k,D,L,W,z,ce,Tt,ro,oo,so,io,ao,co,uo,lo,fo,po,ho,mo,go;const un=x.strict,yo=(S=x.code)===null||S===void 0?void 0:S.optimize,Xa=yo===!0||yo===void 0?1:yo||0,ec=(O=(A=x.code)===null||A===void 0?void 0:A.regExp)!==null&&O!==void 0?O:h,am=(g=x.uriResolver)!==null&&g!==void 0?g:p.default;return{strictSchema:(k=(w=x.strictSchema)!==null&&w!==void 0?w:un)!==null&&k!==void 0?k:!0,strictNumbers:(L=(D=x.strictNumbers)!==null&&D!==void 0?D:un)!==null&&L!==void 0?L:!0,strictTypes:(z=(W=x.strictTypes)!==null&&W!==void 0?W:un)!==null&&z!==void 0?z:"log",strictTuples:(Tt=(ce=x.strictTuples)!==null&&ce!==void 0?ce:un)!==null&&Tt!==void 0?Tt:"log",strictRequired:(oo=(ro=x.strictRequired)!==null&&ro!==void 0?ro:un)!==null&&oo!==void 0?oo:!1,code:x.code?{...x.code,optimize:Xa,regExp:ec}:{optimize:Xa,regExp:ec},loopRequired:(so=x.loopRequired)!==null&&so!==void 0?so:v,loopEnum:(io=x.loopEnum)!==null&&io!==void 0?io:v,meta:(ao=x.meta)!==null&&ao!==void 0?ao:!0,messages:(co=x.messages)!==null&&co!==void 0?co:!0,inlineRefs:(uo=x.inlineRefs)!==null&&uo!==void 0?uo:!0,schemaId:(lo=x.schemaId)!==null&&lo!==void 0?lo:"$id",addUsedSchema:(fo=x.addUsedSchema)!==null&&fo!==void 0?fo:!0,validateSchema:(po=x.validateSchema)!==null&&po!==void 0?po:!0,validateFormats:(ho=x.validateFormats)!==null&&ho!==void 0?ho:!0,unicodeRegExp:(mo=x.unicodeRegExp)!==null&&mo!==void 0?mo:!0,int32range:(go=x.int32range)!==null&&go!==void 0?go:!0,uriResolver:am}}class b{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...E(S)};const{es5:A,lines:O}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:m,es5:A,lines:O}),this.logger=Z(S.logger);const g=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,y,S,"NOT SUPPORTED"),N.call(this,$,S,"DEPRECATED","warn"),this._metaOpts=q.call(this),S.formats&&J.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&U.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),R.call(this),S.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:O}=this.opts;let g=f;O==="id"&&(g={...f},g.id=g.$id,delete g.$id),A&&S&&this.addMetaSchema(g,g[O],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let O;if(typeof S=="string"){if(O=this.getSchema(S),!O)throw new Error(`no schema with key or ref "${S}"`)}else O=this.compile(S);const g=O(A);return"$async"in O||(this.errors=O.errors),g}compile(S,A){const O=this._addSchema(S,A);return O.validate||this._compileSchemaEnv(O)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:O}=this.opts;return g.call(this,S,A);async function g(z,ce){await w.call(this,z.$schema);const Tt=this._addSchema(z,ce);return Tt.validate||k.call(this,Tt)}async function w(z){z&&!this.getSchema(z)&&await g.call(this,{$ref:z},!0)}async function k(z){try{return this._compileSchemaEnv(z)}catch(ce){if(!(ce instanceof o.default))throw ce;return D.call(this,ce),await L.call(this,ce.missingSchema),k.call(this,z)}}function D({missingSchema:z,missingRef:ce}){if(this.refs[z])throw new Error(`AnySchema ${z} is loaded but ${ce} cannot be resolved`)}async function L(z){const ce=await W.call(this,z);this.refs[z]||await w.call(this,ce.$schema),this.refs[z]||this.addSchema(ce,z,A)}async function W(z){const ce=this._loading[z];if(ce)return ce;try{return await(this._loading[z]=O(z))}finally{delete this._loading[z]}}}addSchema(S,A,O,g=this.opts.validateSchema){if(Array.isArray(S)){for(const k of S)this.addSchema(k,void 0,O,g);return this}let w;if(typeof S=="object"){const{schemaId:k}=this.opts;if(w=S[k],w!==void 0&&typeof w!="string")throw new Error(`schema ${k} must be string`)}return A=(0,c.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,O,A,g,!0),this}addMetaSchema(S,A,O=this.opts.validateSchema){return this.addSchema(S,A,!0,O),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let O;if(O=S.$schema,O!==void 0&&typeof O!="string")throw new Error("$schema must be a string");if(O=O||this.opts.defaultMeta||this.defaultMeta(),!O)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const g=this.validate(O,S);if(!g&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return g}getSchema(S){let A;for(;typeof(A=j.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:O}=this.opts,g=new i.SchemaEnv({schema:{},schemaId:O});if(A=i.resolveSchema.call(this,g,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const A=j.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let O=S[this.opts.schemaId];return O&&(O=(0,c.normalizeId)(O),delete this.schemas[O],delete this.refs[O]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let O;if(typeof S=="string")O=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=O);else if(typeof S=="object"&&A===void 0){if(A=S,O=A.keyword,Array.isArray(O)&&!O.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(_e.call(this,O,A),!A)return(0,l.eachItem)(O,w=>Ve.call(this,w)),this;cn.call(this,A);const g={...A,type:(0,u.getJSONTypes)(A.type),schemaType:(0,u.getJSONTypes)(A.schemaType)};return(0,l.eachItem)(O,g.type.length===0?w=>Ve.call(this,w,g):w=>g.type.forEach(k=>Ve.call(this,w,g,k))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const O of A.rules){const g=O.rules.findIndex(w=>w.keyword===S);g>=0&&O.rules.splice(g,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:O="data"}={}){return!S||S.length===0?"No errors":S.map(g=>`${O}${g.instancePath} ${g.message}`).reduce((g,w)=>g+A+w)}$dataMetaSchema(S,A){const O=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const g of A){const w=g.split("/").slice(1);let k=S;for(const D of w)k=k[D];for(const D in O){const L=O[D];if(typeof L!="object")continue;const{$data:W}=L.definition,z=k[D];W&&z&&(k[D]=Kn(z))}}return S}_removeAllSchemas(S,A){for(const O in S){const g=S[O];(!A||A.test(O))&&(typeof g=="string"?delete S[O]:g&&!g.meta&&(this._cache.delete(g.schema),delete S[O]))}}_addSchema(S,A,O,g=this.opts.validateSchema,w=this.opts.addUsedSchema){let k;const{schemaId:D}=this.opts;if(typeof S=="object")k=S[D];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let L=this._cache.get(S);if(L!==void 0)return L;O=(0,c.normalizeId)(k||O);const W=c.getSchemaRefs.call(this,S,O);return L=new i.SchemaEnv({schema:S,schemaId:D,meta:A,baseId:O,localRefs:W}),this._cache.set(L.schema,L),w&&!O.startsWith("#")&&(O&&this._checkUnique(O),this.refs[O]=L),g&&this.validateSchema(S,!0),L}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const A=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=A}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function N(x,S,A,O="error"){for(const g in x){const w=g;w in S&&this.logger[O](`${A}: option ${g}. ${x[w]}`)}}function j(x){return x=(0,c.normalizeId)(x),this.schemas[x]||this.refs[x]}function R(){const x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(const S in x)this.addSchema(x[S],S)}function J(){for(const x in this.opts.formats){const S=this.opts.formats[x];S&&this.addFormat(x,S)}}function U(x){if(Array.isArray(x)){this.addVocabulary(x);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in x){const A=x[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function q(){const x={...this.opts};for(const S of d)delete x[S];return x}const Q={log(){},warn(){},error(){}};function Z(x){if(x===!1)return Q;if(x===void 0)return console;if(x.log&&x.warn&&x.error)return x;throw new Error("logger must implement log, warn and error methods")}const ye=/^[a-z_$][a-z0-9_$:-]*$/i;function _e(x,S){const{RULES:A}=this;if((0,l.eachItem)(x,O=>{if(A.keywords[O])throw new Error(`Keyword ${O} is already defined`);if(!ye.test(O))throw new Error(`Keyword ${O} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Ve(x,S,A){var O;const g=S==null?void 0:S.post;if(A&&g)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let k=g?w.post:w.rules.find(({type:L})=>L===A);if(k||(k={type:A,rules:[]},w.rules.push(k)),w.keywords[x]=!0,!S)return;const D={keyword:x,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,k,D,S.before):k.rules.push(D),w.all[x]=D,(O=S.implements)===null||O===void 0||O.forEach(L=>this.addKeyword(L))}function pe(x,S,A){const O=x.rules.findIndex(g=>g.keyword===A);O>=0?x.rules.splice(O,0,S):(x.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function cn(x){let{metaSchema:S}=x;S!==void 0&&(x.$data&&this.opts.$data&&(S=Kn(S)),x.validateSchema=this.compile(S,!0))}const no={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Kn(x){return{anyOf:[x,no]}}})(Xf);var Fi={},qi={},Vi={};Object.defineProperty(Vi,"__esModule",{value:!0});const bb={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vi.default=bb;var Pt={};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.callRef=Pt.getValidate=void 0;const Eb=on,au=K,ve=G,Mt=Fe,cu=Ee,Xn=P,Sb={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return f();const l=cu.resolveRef.call(c,u,o,n);if(l===void 0)throw new Eb.default(r.opts.uriResolver,o,n);if(l instanceof cu.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return mr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return mr(e,(0,ve._)`${d}.validate`,u,u.$async)}function p(d){const m=Hd(e,d);mr(e,m,d,d.$async)}function h(d){const m=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,ve.stringify)(d)}:{ref:d}),y=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:ve.nil,topSchemaRef:m,errSchemaPath:n},y);e.mergeEvaluated($),e.ok(y)}}};function Hd(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,ve._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Pt.getValidate=Hd;function mr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Mt.default.this:ve.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const d=o.let("valid");o.try(()=>{o.code((0,ve._)`await ${(0,au.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},m=>{o.if((0,ve._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,au.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const m=(0,ve._)`${d}.errors`;o.assign(Mt.default.vErrors,(0,ve._)`${Mt.default.vErrors} === null ? ${m} : ${Mt.default.vErrors}.concat(${m})`),o.assign(Mt.default.errors,(0,ve._)`${Mt.default.vErrors}.length`)}function h(d){var m;if(!s.opts.unevaluated)return;const y=(m=n==null?void 0:n.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Xn.mergeEvaluated.props(o,y.props,s.props));else{const $=o.var("props",(0,ve._)`${d}.evaluated.props`);s.props=Xn.mergeEvaluated.props(o,$,s.props,ve.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Xn.mergeEvaluated.items(o,y.items,s.items));else{const $=o.var("items",(0,ve._)`${d}.evaluated.items`);s.items=Xn.mergeEvaluated.items(o,$,s.items,ve.Name)}}}Pt.callRef=mr;Pt.default=Sb;Object.defineProperty(qi,"__esModule",{value:!0});const Nb=Vi,Ob=Pt,kb=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Nb.default,Ob.default];qi.default=kb;var Ki={},Gi={};Object.defineProperty(Gi,"__esModule",{value:!0});const Or=G,et=Or.operators,kr={maximum:{okStr:"<=",ok:et.LTE,fail:et.GT},minimum:{okStr:">=",ok:et.GTE,fail:et.LT},exclusiveMaximum:{okStr:"<",ok:et.LT,fail:et.GTE},exclusiveMinimum:{okStr:">",ok:et.GT,fail:et.LTE}},_b={message:({keyword:e,schemaCode:t})=>(0,Or.str)`must be ${kr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Or._)`{comparison: ${kr[e].okStr}, limit: ${t}}`},Ab={keyword:Object.keys(kr),type:"number",schemaType:"number",$data:!0,error:_b,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,Or._)`${n} ${kr[t].fail} ${r} || isNaN(${n})`)}};Gi.default=Ab;var Ji={};Object.defineProperty(Ji,"__esModule",{value:!0});const En=G,jb={message:({schemaCode:e})=>(0,En.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,En._)`{multipleOf: ${e}}`},Ib={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:jb,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,En._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,En._)`${i} !== parseInt(${i})`;e.fail$data((0,En._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ji.default=Ib;var Hi={},zi={};Object.defineProperty(zi,"__esModule",{value:!0});function zd(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}zi.default=zd;zd.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Hi,"__esModule",{value:!0});const vt=G,xb=P,Pb=zi,Tb={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,vt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,vt._)`{limit: ${e}}`},Cb={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Tb,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?vt.operators.GT:vt.operators.LT,i=o.opts.unicode===!1?(0,vt._)`${n}.length`:(0,vt._)`${(0,xb.useFunc)(e.gen,Pb.default)}(${n})`;e.fail$data((0,vt._)`${i} ${s} ${r}`)}};Hi.default=Cb;var Wi={};Object.defineProperty(Wi,"__esModule",{value:!0});const Rb=K,Mb=P,Ht=G,Db={message:({schemaCode:e})=>(0,Ht.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ht._)`{pattern: ${e}}`},Lb={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Db,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Ht._)`new RegExp`:(0,Mb.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,Ht._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,Ht._)`!${l}`)}else{const c=(0,Rb.usePattern)(e,o);e.fail$data((0,Ht._)`!${c}.test(${n})`)}}};Wi.default=Lb;var Yi={};Object.defineProperty(Yi,"__esModule",{value:!0});const Sn=G,Ub={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,Sn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,Sn._)`{limit: ${e}}`},Bb={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ub,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?Sn.operators.GT:Sn.operators.LT;e.fail$data((0,Sn._)`Object.keys(${n}).length ${o} ${r}`)}};Yi.default=Bb;var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0});const fn=K,Nn=G,Fb=P,qb={message:({params:{missingProperty:e}})=>(0,Nn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Nn._)`{missingProperty: ${e}}`},Vb={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qb,code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:d}=e.it;for(const m of n)if((h==null?void 0:h[m])===void 0&&!d.has(m)){const y=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Fb.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(Nn.nil,f);else for(const h of n)(0,fn.checkReportMissingProp)(e,h)}function l(){const h=t.let("missing");if(c||s){const d=t.let("valid",!0);e.block$data(d,()=>p(h,d)),e.ok(d)}else t.if((0,fn.checkMissingProp)(e,n,h)),(0,fn.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,fn.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,fn.propertyInData)(t,o,h,a.ownProperties)),t.if((0,Nn.not)(d),()=>{e.error(),t.break()})},Nn.nil)}}};Qi.default=Vb;var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});const On=G,Kb={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,On.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,On._)`{limit: ${e}}`},Gb={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Kb,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?On.operators.GT:On.operators.LT;e.fail$data((0,On._)`${n}.length ${o} ${r}`)}};Zi.default=Gb;var Xi={},Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});const Wd=md;Wd.code='require("ajv/dist/runtime/equal").default';Vn.default=Wd;Object.defineProperty(Xi,"__esModule",{value:!0});const xo=ie,ue=G,Jb=P,Hb=Vn,zb={message:({params:{i:e,j:t}})=>(0,ue.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ue._)`{i: ${e}, j: ${t}}`},Wb={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:zb,code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const c=t.let("valid"),u=s.items?(0,xo.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,ue._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,ue._)`${n}.length`),m=t.let("j");e.setParams({i:d,j:m}),t.assign(c,!0),t.if((0,ue._)`${d} > 1`,()=>(f()?p:h)(d,m))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,m){const y=t.name("item"),$=(0,xo.checkDataTypes)(u,y,a.opts.strictNumbers,xo.DataType.Wrong),v=t.const("indices",(0,ue._)`{}`);t.for((0,ue._)`;${d}--;`,()=>{t.let(y,(0,ue._)`${n}[${d}]`),t.if($,(0,ue._)`continue`),u.length>1&&t.if((0,ue._)`typeof ${y} == "string"`,(0,ue._)`${y} += "_"`),t.if((0,ue._)`typeof ${v}[${y}] == "number"`,()=>{t.assign(m,(0,ue._)`${v}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ue._)`${v}[${y}] = ${d}`)})}function h(d,m){const y=(0,Jb.useFunc)(t,Hb.default),$=t.name("outer");t.label($).for((0,ue._)`;${d}--;`,()=>t.for((0,ue._)`${m} = ${d}; ${m}--;`,()=>t.if((0,ue._)`${y}(${n}[${d}], ${n}[${m}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};Xi.default=Wb;var ea={};Object.defineProperty(ea,"__esModule",{value:!0});const Ss=G,Yb=P,Qb=Vn,Zb={message:"must be equal to constant",params:({schemaCode:e})=>(0,Ss._)`{allowedValue: ${e}}`},Xb={keyword:"const",$data:!0,error:Zb,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,Ss._)`!${(0,Yb.useFunc)(t,Qb.default)}(${n}, ${o})`):e.fail((0,Ss._)`${s} !== ${n}`)}};ea.default=Xb;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});const yn=G,eE=P,tE=Vn,nE={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,yn._)`{allowedValues: ${e}}`},rE={keyword:"enum",schemaType:"array",$data:!0,error:nE,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,eE.useFunc)(t,tE.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);l=(0,yn.or)(...o.map((d,m)=>p(h,m)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,yn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const m=o[d];return typeof m=="object"&&m!==null?(0,yn._)`${u()}(${n}, ${h}[${d}])`:(0,yn._)`${n} === ${m}`}}};ta.default=rE;Object.defineProperty(Ki,"__esModule",{value:!0});const oE=Gi,sE=Ji,iE=Hi,aE=Wi,cE=Yi,uE=Qi,lE=Zi,fE=Xi,dE=ea,pE=ta,hE=[oE.default,sE.default,iE.default,aE.default,cE.default,uE.default,lE.default,fE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dE.default,pE.default];Ki.default=hE;var na={},sn={};Object.defineProperty(sn,"__esModule",{value:!0});sn.validateAdditionalItems=void 0;const wt=G,Ns=P,mE={message:({params:{len:e}})=>(0,wt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,wt._)`{limit: ${e}}`},gE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:mE,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Ns.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yd(e,r)}};function Yd(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,wt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,wt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,Ns.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,wt._)`${a} <= ${t.length}`);n.if((0,wt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:Ns.Type.Num},u),i.allErrors||n.if((0,wt.not)(u),()=>n.break())})}}sn.validateAdditionalItems=Yd;sn.default=gE;var ra={},an={};Object.defineProperty(an,"__esModule",{value:!0});an.validateTuple=void 0;const uu=G,gr=P,yE=K,$E={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Qd(e,"additionalItems",t);n.items=!0,!(0,gr.alwaysValidSchema)(n,t)&&e.ok((0,yE.validateArray)(e))}};function Qd(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=gr.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,uu._)`${s}.length`);n.forEach((f,p)=>{(0,gr.alwaysValidSchema)(a,f)||(r.if((0,uu._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(f){const{opts:p,errSchemaPath:h}=a,d=n.length,m=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!m){const y=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,gr.checkStrictMode)(a,y,p.strictTuples)}}}an.validateTuple=Qd;an.default=$E;Object.defineProperty(ra,"__esModule",{value:!0});const vE=an,wE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,vE.validateTuple)(e,"items")};ra.default=wE;var oa={};Object.defineProperty(oa,"__esModule",{value:!0});const lu=G,bE=P,EE=K,SE=sn,NE={message:({params:{len:e}})=>(0,lu.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,lu._)`{limit: ${e}}`},OE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:NE,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,bE.alwaysValidSchema)(r,t)&&(o?(0,SE.validateAdditionalItems)(e,o):e.ok((0,EE.validateArray)(e)))}};oa.default=OE;var sa={};Object.defineProperty(sa,"__esModule",{value:!0});const Ae=G,er=P,kE={message:({params:{min:e,max:t}})=>t===void 0?(0,Ae.str)`must contain at least ${e} valid item(s)`:(0,Ae.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ae._)`{minContains: ${e}}`:(0,Ae._)`{minContains: ${e}, maxContains: ${t}}`},_E={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,Ae._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,er.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,er.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,er.alwaysValidSchema)(s,n)){let m=(0,Ae._)`${l} >= ${i}`;a!==void 0&&(m=(0,Ae._)`${m} && ${l} <= ${a}`),e.pass(m);return}s.items=!0;const f=t.name("valid");a===void 0&&i===1?h(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,Ae._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const m=t.name("_valid"),y=t.let("count",0);h(m,()=>t.if(m,()=>d(y)))}function h(m,y){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:er.Type.Num,compositeRule:!0},m),y()})}function d(m){t.code((0,Ae._)`${m}++`),a===void 0?t.if((0,Ae._)`${m} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,Ae._)`${m} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,Ae._)`${m} >= ${i}`,()=>t.assign(f,!0)))}}};sa.default=_E;var Zd={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=P,r=K;e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:f}})=>(0,t._)`{property: ${c},
160
- missingProperty: ${f},
161
- depsCount: ${u},
162
- deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const p=Array.isArray(c[f])?u:l;p[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:p}=c;if(Object.keys(u).length===0)return;const h=l.let("missing");for(const d in u){const m=u[d];if(m.length===0)continue;const y=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:m.length,deps:m.join(", ")}),p.allErrors?l.if(y,()=>{for(const $ of m)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,m,h)})`),(0,r.reportMissingProp)(c,h),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:p,it:h}=c,d=l.name("valid");for(const m in u)(0,n.alwaysValidSchema)(h,u[m])||(l.if((0,r.propertyInData)(l,f,m,h.opts.ownProperties),()=>{const y=c.subschema({keyword:p,schemaProp:m},d);c.mergeValidEvaluated(y,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Zd);var ia={};Object.defineProperty(ia,"__esModule",{value:!0});const Xd=G,AE=P,jE={message:"property name must be valid",params:({params:e})=>(0,Xd._)`{propertyName: ${e.propertyName}}`},IE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jE,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,AE.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Xd.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};ia.default=IE;var Jr={};Object.defineProperty(Jr,"__esModule",{value:!0});const tr=K,xe=G,xE=Fe,nr=P,PE={message:"must NOT have additional properties",params:({params:e})=>(0,xe._)`{additionalProperty: ${e.additionalProperty}}`},TE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,nr.alwaysValidSchema)(i,n))return;const u=(0,tr.allSchemaProperties)(r.properties),l=(0,tr.allSchemaProperties)(r.patternProperties);f(),e.ok((0,xe._)`${s} === ${xE.default.errors}`);function f(){t.forIn("key",o,y=>{!u.length&&!l.length?d(y):t.if(p(y),()=>d(y))})}function p(y){let $;if(u.length>8){const v=(0,nr.schemaRefOrVal)(i,r.properties,"properties");$=(0,tr.isOwnProperty)(t,v,y)}else u.length?$=(0,xe.or)(...u.map(v=>(0,xe._)`${y} === ${v}`)):$=xe.nil;return l.length&&($=(0,xe.or)($,...l.map(v=>(0,xe._)`${(0,tr.usePattern)(e,v)}.test(${y})`))),(0,xe.not)($)}function h(y){t.code((0,xe._)`delete ${o}[${y}]`)}function d(y){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(y);return}if(n===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,nr.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(m(y,$,!1),t.if((0,xe.not)($),()=>{e.reset(),h(y)})):(m(y,$),a||t.if((0,xe.not)($),()=>t.break()))}}function m(y,$,v){const E={keyword:"additionalProperties",dataProp:y,dataPropType:nr.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(E,$)}}};Jr.default=TE;var aa={};Object.defineProperty(aa,"__esModule",{value:!0});const CE=Ce,fu=K,Po=P,du=Jr,RE={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&du.default.code(new CE.KeywordCxt(s,du.default,"additionalProperties"));const i=(0,fu.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Po.mergeEvaluated.props(t,(0,Po.toHash)(i),s.props));const a=i.filter(f=>!(0,Po.alwaysValidSchema)(s,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,fu.propertyInData)(t,o,f,s.opts.ownProperties)),l(f),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return s.opts.useDefaults&&!s.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};aa.default=RE;var ca={};Object.defineProperty(ca,"__esModule",{value:!0});const pu=K,rr=G,hu=P,mu=P,ME={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,pu.allSchemaProperties)(n),c=a.filter(m=>(0,hu.alwaysValidSchema)(s,n[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof rr.Name)&&(s.props=(0,mu.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const m of a)u&&h(m),s.allErrors?d(m):(t.var(l,!0),d(m),t.if(l))}function h(m){for(const y in u)new RegExp(m).test(y)&&(0,hu.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function d(m){t.forIn("key",r,y=>{t.if((0,rr._)`${(0,pu.usePattern)(e,m)}.test(${y})`,()=>{const $=c.includes(m);$||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:mu.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,rr._)`${f}[${y}]`,!0):!$&&!s.allErrors&&t.if((0,rr.not)(l),()=>t.break())})})}}};ca.default=ME;var ua={};Object.defineProperty(ua,"__esModule",{value:!0});const DE=P,LE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,DE.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ua.default=LE;var la={};Object.defineProperty(la,"__esModule",{value:!0});const UE=K,BE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:UE.validateUnion,error:{message:"must match a schema in anyOf"}};la.default=BE;var fa={};Object.defineProperty(fa,"__esModule",{value:!0});const yr=G,FE=P,qE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,yr._)`{passingSchemas: ${e.passing}}`},VE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qE,code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,f)=>{let p;(0,FE.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,yr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,yr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,yr.Name)})})}}};fa.default=VE;var da={};Object.defineProperty(da,"__esModule",{value:!0});const KE=P,GE={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,i)=>{if((0,KE.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};da.default=GE;var pa={};Object.defineProperty(pa,"__esModule",{value:!0});const _r=G,ep=P,JE={message:({params:e})=>(0,_r.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,_r._)`{failingKeyword: ${e.ifClause}}`},HE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:JE,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,ep.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=gu(r,"then"),s=gu(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,_r.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{const p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),f?t.assign(f,(0,_r._)`${l}`):e.setParams({ifClause:l})}}}};function gu(e,t){const n=e.schema[t];return n!==void 0&&!(0,ep.alwaysValidSchema)(e,n)}pa.default=HE;var ha={};Object.defineProperty(ha,"__esModule",{value:!0});const zE=P,WE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,zE.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};ha.default=WE;Object.defineProperty(na,"__esModule",{value:!0});const YE=sn,QE=ra,ZE=an,XE=oa,eS=sa,tS=Zd,nS=ia,rS=Jr,oS=aa,sS=ca,iS=ua,aS=la,cS=fa,uS=da,lS=pa,fS=ha;function dS(e=!1){const t=[iS.default,aS.default,cS.default,uS.default,lS.default,fS.default,nS.default,rS.default,tS.default,oS.default,sS.default];return e?t.push(QE.default,XE.default):t.push(YE.default,ZE.default),t.push(eS.default),t}na.default=dS;var ma={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});const ne=G,pS={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},hS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:pS,code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?p():h();function p(){const d=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),m=n.const("fDef",(0,ne._)`${d}[${i}]`),y=n.let("fType"),$=n.let("format");n.if((0,ne._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(y,(0,ne._)`${m}.type || "string"`).assign($,(0,ne._)`${m}.validate`),()=>n.assign(y,(0,ne._)`"string"`).assign($,m)),e.fail$data((0,ne.or)(v(),E()));function v(){return c.strictSchema===!1?ne.nil:(0,ne._)`${i} && !${$}`}function E(){const b=l.$async?(0,ne._)`(${m}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ne._)`${$}(${r})`,N=(0,ne._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${r}))`;return(0,ne._)`${$} && ${$} !== true && ${y} === ${t} && !${N}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[m,y,$]=E(d);m===t&&e.pass(b());function v(){if(c.strictSchema===!1){f.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function E(N){const j=N instanceof RegExp?(0,ne.regexpCode)(N):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ne._)`${R}.validate`]:["string",N,R]}function b(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ne._)`await ${$}(${r})`}return typeof y=="function"?(0,ne._)`${$}(${r})`:(0,ne._)`${$}.test(${r})`}}}};ga.default=hS;Object.defineProperty(ma,"__esModule",{value:!0});const mS=ga,gS=[mS.default];ma.default=gS;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});tn.contentVocabulary=tn.metadataVocabulary=void 0;tn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];tn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(Fi,"__esModule",{value:!0});const yS=qi,$S=Ki,vS=na,wS=ma,yu=tn,bS=[yS.default,$S.default,(0,vS.default)(),wS.default,yu.metadataVocabulary,yu.contentVocabulary];Fi.default=bS;var ya={},Hr={};Object.defineProperty(Hr,"__esModule",{value:!0});Hr.DiscrError=void 0;var $u;(function(e){e.Tag="tag",e.Mapping="mapping"})($u||(Hr.DiscrError=$u={}));Object.defineProperty(ya,"__esModule",{value:!0});const Ft=G,Os=Hr,vu=Ee,ES=on,SS=P,NS={message:({params:{discrError:e,tagName:t}})=>e===Os.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Ft._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},OS={keyword:"discriminator",type:"object",schemaType:"object",error:NS,code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=t.let("valid",!1),u=t.const("tag",(0,Ft._)`${n}${(0,Ft.getProperty)(a)}`);t.if((0,Ft._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Os.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const h=p();t.if(!1);for(const d in h)t.elseIf((0,Ft._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:Os.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(m,Ft.Name),d}function p(){var h;const d={},m=$(o);let y=!0;for(let b=0;b<i.length;b++){let N=i[b];if(N!=null&&N.$ref&&!(0,SS.schemaHasRulesButRef)(N,s.self.RULES)){const R=N.$ref;if(N=vu.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),N instanceof vu.SchemaEnv&&(N=N.schema),N===void 0)throw new ES.default(s.opts.uriResolver,s.baseId,R)}const j=(h=N==null?void 0:N.properties)===null||h===void 0?void 0:h[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||$(N)),v(j,b)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,N){if(b.const)E(b.const,N);else if(b.enum)for(const j of b.enum)E(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(b,N){if(typeof b!="string"||b in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[b]=N}}}};ya.default=OS;const kS="http://json-schema.org/draft-07/schema#",_S="http://json-schema.org/draft-07/schema#",AS="Core schema meta-schema",jS={schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},IS=["object","boolean"],xS={$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},PS={$schema:kS,$id:_S,title:AS,definitions:jS,type:IS,properties:xS,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=Xf,r=Fi,o=ya,s=PS,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(d=>this.addVocabulary(d)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const d=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(d,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Ce;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=G;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var f=qn;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=on;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})($s,$s.exports);var TS=$s.exports;const CS=e$(TS);class tp extends Error{constructor(t){super(t.length>0?`Config validation failed: ${t.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=t,this.name="ValidationError"}}function RS(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new CS({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new tp(MS(o.errors??[]))}function MS(e){return e.map(t=>({field:DS(t),message:t.message??"is invalid",keyword:t.keyword}))}function DS(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function LS(e,t){return T.join(of(e,t),lv)}const US=384,BS=448;function FS(e,t,n={}){const r=n.mode??US,o=n.dirMode??BS,s=T.dirname(e);C.mkdirSync(s,{recursive:!0,mode:o}),C.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{C.writeFileSync(i,a,{encoding:"utf8",mode:r}),C.chmodSync(i,r),C.renameSync(i,e),C.chmodSync(e,r)}catch(c){try{C.existsSync(i)&&C.unlinkSync(i)}catch{}throw c}}const qS="0.1.0";function wu(e,t){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(e)}`)}function VS(){return`${process.pid}-${Un.randomBytes(3).toString("hex")}`}function np(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");wu(e,"project");const r=t.orgNamespace??cv,o=t.envPrefixOverride??mv(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[uv],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);wu(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=Qy({scope:n.scope,cwd:n.cwd},a),l=Xy({project:e,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:e,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function KS(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=np(e,t,n),u=n.processEnv??process.env,l=Ov(c),f=n.instanceId??VS(),{raw:p,nested:h,typedRaw:d,provenance:m,fields:y}=Av(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const N of Object.keys(y)){const j=y[N];j.live&&($[N]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=yv(t.config);RS(Zf(d),v);const E=Iv(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),b=xv(t.files,E);return{version:av,libraryVersion:qS,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:pv(Object.fromEntries(Object.entries(d).map(([N,j])=>[N,String(j)]))),structureHash:hv(Object.values(E).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(E),files:Object.values(b),provenance:m}}let Tn=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class GS extends Tn{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class JS extends Tn{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function HS(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function ks(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>ks(n));const t={};for(const[n,r]of Object.entries(e))t[n]=ks(r);return t}function zS(e,t){const n=ks(e);for(const r of Object.keys(t)){const o=t[r],s=r.split(".");let i=n;for(let c=0;c<s.length-1;c++){const u=s[c],l=i[u];(typeof l!="object"||l===null||Array.isArray(l))&&(i[u]={}),i=i[u]}const a=s[s.length-1];Object.defineProperty(i,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?ys(c,o.type):o.fallback}})}return n}function WS(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Tn(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class zr{constructor(t,n,r={}){let o,s;try{o=KS(t,n,r);const i=np(t,n,r);s=LS(i.roots,o.scope)}catch(i){throw i instanceof tp||i instanceof Tn?i:new Tn(i instanceof Error?i.message:String(i))}return bu(this,o,s)}static fromSnapshot(t){if(!C.existsSync(t))throw new GS(t);const n=JSON.parse(C.readFileSync(t,"utf8")),r=Object.create(zr.prototype);return bu(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return HS(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){WS(t);const n=this.paths.run??this._runDirFallback();C.mkdirSync(n,{recursive:!0});const r=T.join(n,`${t}.lock`);let o;try{o=C.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new JS(t,r):i}C.writeSync(o,`${process.pid}
2
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("node:fs"),W=require("node:os"),k=require("node:path"),et=require("node:url"),Mn=require("@adhd/sox-telemetry"),st=require("pino"),Zr=require("ajv"),ka=require("ajv-formats"),pe=require("@adhd/sox-store-adapter"),Aa=require("@adhd/sox-graph-store"),Ct=require("node:fs/promises"),ue=require("node:crypto"),ja=require("fastify"),To=require("node:http"),_a=require("@modelcontextprotocol/sdk/server/index.js"),Na=require("@modelcontextprotocol/sdk/server/stdio.js"),Oa=require("@modelcontextprotocol/sdk/server/sse.js"),Ra=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),$o=require("@modelcontextprotocol/sdk/types.js"),Ia=require("@adhd/sox-hybrid-search"),Fn=require("node:module"),Ta=require("yaml");var $=typeof document<"u"?document.currentScript:null;function ei(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const cn=ei(k),ge=ei(Ct),dn="$apigen";class Co extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function $a(e){const t=new Map;return{register(r,o){if(t.has(r.id)&&!(o!=null&&o.override))throw new Co(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const o of t.values())if(o.matches(r))return o},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),o={register(){throw new Co("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(i){for(const s of r.values())if(s.matches(i))return s},get(i){return r.get(i)},ids(){return[...r.keys()]},freeze(){return o}};return o}}}const Ae="x-apigen-logical",Bn="x-apigen-codec",ln="x-apigen-ctor",un="x-apigen-tojson",Ca="0.1.0";function Po(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Re(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Re(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=ti(e,i,t,n);return Re(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return Ve(e,t,n);const a=t.items;if(!a)return e.map(d=>Ee(d));const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?Ee(d):Re(d,u,{...n,path:`${c}/${l}`})}):e.map((d,l)=>Re(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Ve(e,t,n);const a=t.properties;if(!a)return Ee(e);const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=e[l];f!==void 0&&(d[l]=Re(f,u,{...n,path:`${c}/${l}`}))}return d}return s==null?Ve(e,t,n):Ee(e)}function Ie(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ie(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=ti(e,i,t,n);return Ie(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?d:Ie(d,u,{...n,path:`${c}/${l}`})}):e.map((d,l)=>Ie(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=e[l];f!==void 0&&(d[l]=Ie(f,u,{...n,path:`${c}/${l}`}))}for(const[l,u]of Object.entries(e))!(l in a)&&u!==void 0&&(d[l]=u);return d}return s==null?fn(e,n):e}function ti(e,t,n,r){var c;const o=n.discriminator;if(o!=null&&o.propertyName){const d=o.propertyName,l=e!==null&&typeof e=="object"?e[d]:void 0;if(typeof l=="string"){if(o.mapping){const u=o.mapping[l];if(u){const f=t.find(g=>g.$ref===u);if(f)return f}}for(const u of t){const g=(c=kt(u,r).properties)==null?void 0:c[d];if(!g)continue;const p=g.enum;if(g.const===l||Array.isArray(p)&&p.includes(l))return u}}}const i=Pa(e,t,r);if(i)return i;let s,a=-1;for(const d of t){const l=kt(d,r),u=qn(e,l,r);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:t[0]??{}}function kt(e,t){const n=e.$ref;return typeof n=="string"?t.resolve(n):e}function xo(e){if("const"in e)return e.const;const t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function Pa(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return;const r=e,o=t.map(s=>kt(s,n)),i=new Set;for(const s of o){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))xo(d)!==void 0&&i.add(c)}for(const s of i){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[s];return p?xo(p):void 0}),c=a.filter(f=>f!==void 0),d=new Set(c);if(c.length<2||d.size!==c.length)continue;const l=r[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&qn(e,o[u],n)!==null)return t[u]}}function xa(e){if(e===null)return"null";if(Array.isArray(e))return"array";const t=typeof e;return t==="number"?Number.isInteger(e)?"integer":"number":t}function qn(e,t,n){const r=t.oneOf;if(Array.isArray(r)){let l=null;for(const u of r){const f=qn(e,kt(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=t.type,i=xa(e);if(typeof o=="string"){if(!(o===i||o==="number"&&i==="integer"))return null}else if(Array.isArray(o)&&!o.some(u=>u===i||u==="number"&&i==="integer"))return null;if(e===null||typeof e!="object"||Array.isArray(e))return typeof o=="string"?1:0;const s=e,a=t.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(s[l]===void 0)return null;c+=2}}const d=t.properties;if(d){for(const l of Object.keys(d))s[l]!==void 0&&(c+=1);for(const l of Object.keys(s))d[l]===void 0&&(c-=1)}return c}function Ve(e,t,n){var r;for(const o of n.registry.ids()){const i=n.registry.get(o);if((r=i==null?void 0:i.ownsValue)!=null&&r.call(i,e))return{[dn]:o,v:i.encode(e,i.schema,n)}}if(Array.isArray(e))return e.map(o=>Ve(o,{},n));if(ni(e)){const o={};for(const[i,s]of Object.entries(e))s!==void 0&&(o[i]=Ve(s,{},n));return o}return Ee(e)}function ni(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function fn(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&dn in e){const n=e,r=n[dn],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}if(Array.isArray(e))return e.map(n=>fn(n,t));if(ni(e)){const n={};for(const[r,o]of Object.entries(e))n[r]=fn(o,t);return n}return e}function Ee(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Ee);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Ee(r));return t}return null}function Lo(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const u=t[i];if(!u){const f=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${f}`)}r.push(u)}continue}const s=o.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&r.push(u);const a=o.properties;if(a)for(const u of Object.values(a))r.push(u);const c=o.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&r.push(u);else typeof c=="object"&&c!==null&&r.push(c);const d=o.additionalProperties;typeof d=="object"&&d!==null&&r.push(d);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}function La(e){return{encode(t,n,r){const o=Po(e,r);return Re(t,n,o)},decode(t,n,r){const o=Po(e,r);return Ie(t,n,o)}}}const Kn={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},ownsValue(e){return e instanceof Date},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Hn={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},ownsValue(e){return typeof e=="bigint"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}};const Vn={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},Gn={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},ownsValue(e){return e instanceof Uint8Array},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Jn={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!Ua.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},pn="NaN",mn="Infinity",gn="-Infinity",Da=new Set([pn,mn,gn]),Wn={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},ownsValue(e){return typeof e=="number"&&!Number.isFinite(e)},encode(e,t,n){return Number.isNaN(e)?pn:e===1/0?mn:e===-1/0?gn:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===pn)return NaN;if(e===mn)return 1/0;if(e===gn)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Da].join(", ")}.`);return NaN}},Ma=[Kn,Hn,Vn,Gn,Jn,Wn];function Fa(e,t={}){for(const n of Ma)e.register(n,{override:t.override??!1})}const Ba=12;function qa(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,i=r==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(o)]}function Uo(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Ka(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Ha(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Do(e,t,n){const r=e.properties??{},o=e.required??[],i={};for(const s of o){const a=r[s];i[s]=a!==void 0?Je(a,t,n+1):`<${s}>`}return i}function Va(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Je(r,t,n+1)]:[]}function Je(e,t=e??{},n=0){if(!e||n>Ba)return null;if(typeof e.$ref=="string"){const i=qa(e.$ref,t);return i!==void 0?Je(i,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const i={},s=[];for(const a of e.allOf){Object.assign(i,a.properties??{});for(const c of a.required??[])s.includes(c)||s.push(c)}return Do({...e,properties:i,required:s},t,n)}const r=Uo(e.oneOf)??Uo(e.anyOf);if(r)return Je(r,t,n+1);switch(Ka(e)){case"object":return Do(e,t,n);case"array":return Va(e,t,n);case"string":return Ha(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function oi(e){if(!e)return;const t=Je(e);return`Example: ${JSON.stringify(t)}`}Kn.id,Hn.id,Vn.id,Gn.id,Jn.id,Wn.id;const ri=$a();Fa(ri);const ii=La(ri.freeze());function si(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function hn(e){var n,r;const t=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data;return Object.keys((t==null?void 0:t.properties)??{})}function Ga(e,t){var o,i,s;const n=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,r=n==null?void 0:n[t];return r!==void 0?r:void 0}function Ja(e,t){return t===void 0||e===void 0?e:ii.decode(e,t)}function Xt(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:ii.encode(e,n)}async function Wa(e,t,n,r,o,i){const a=hn(n).map(d=>Ja(i[d],Ga(n,d)));if(si(n,"session")&&t){const d=await t({session:o.session}),l=await e[r](d,...a);return Xt(l,n)}if(n.hasCtx){const d=t?await t(o):void 0,l=await e[r](d,...a);return Xt(l,n)}const c=await e[r](...a);return Xt(c,n)}class tt{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function za(e=[]){return async function(n,r,o){const i=o.schemas[n];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>Wa(o.fns,o.createClient,i,n,r.envelope,r.domainArgs);return e.reduceRight((c,d)=>()=>d(r,c),s)()}}function Mo(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function ai(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(d=>d.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...i]=r,s=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Mo(s),path:i.map(Mo),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}const ce=Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);let at;function ci(){return at||(at=ce("ts-morph").Project,at)}const di=Symbol.for("adhd.apigen.extraction-session");function zn(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}zn(r,t)}}}function li(e){try{const t=O.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const bt=new Map,Fo=new Map;function Ya(e,t,n){const r=t??"",o=bt.get(r);let i=n;if(o&&o.fileVersions.size>0){const c=[n],d=[...o.fileVersions.entries()].sort(([l],[u])=>l.localeCompare(u));for(const[l,u]of d)l!==e&&c.push(`${l}:${u}`);i=c.join("|")}const s=`${e}\0${t??""}`;let a=Fo.get(s);return(a==null?void 0:a.version)!==i&&(a={version:i,schemas:new Map},Fo.set(s,a)),a.schemas}let Qt;function Xa(){if(!Qt){const e=ci();Qt=new e({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return Qt}function ui(e){const t=Xa(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return zn(r,o),[...o].sort()}function Qa(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[di]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(o){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const i=o??"",s=o?this.statVersion(o):"";let a=bt.get(i);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=ci();a={project:o?new c({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},bt.set(i,a),e.projectsBuilt++}return a.project},sourceFileFor(o,i){const s=this.projectFor(i),a=bt.get(i??""),c=this.statVersion(o);let d=s.getSourceFile(o);if(d===void 0?d=s.addSourceFileAtPath(o):a&&a.fileVersions.get(o)!==c&&d.refreshFromFileSystemSync(),a==null||a.fileVersions.set(o,c),a){const l=new Set([o]);zn(d,l);for(const u of l)u!==o&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(o){let i=t.get(o);return i===void 0&&(i=li(o),t.set(o,i)),i},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function Za(e){const t=e;if(t[di]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Bo=new Set(["string","number","boolean","integer"]);function ec(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Bo.has(n):Array.isArray(n)?n.every(r=>Bo.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function fi(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(ec)}function tc(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const i=r[o];if(i)for(const[s,a]of Object.entries(i)){const c=s.startsWith("#/")?s:`#/${o}/${s}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{Lo(o.input,t),Lo(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`)}}function nc(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function oc(e,t,n){tc(e);const r={};for(const[o,i]of Object.entries(e.schemas)){const s={},a=i.input.properties??{},c=i.input.required??[],d={},l=[],u={};for(const v of t)if(v.envelope&&s[v.id]!==!1)for(const[h,y]of Object.entries(v.envelope))d[h]=y,u[h]=v.id,l.includes(h)||l.push(h);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},g=i.safe===!0||fi(i.input),p=i.input.definitions,m=i.input.$defs;r[o]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:nc(Object.keys(d),Object.keys(a).length>0),...p?{definitions:p}:{},...m?{$defs:m}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":g,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return r}const rc=8;function ic(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let sc=0;async function ac(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${sc++}`;let i;try{i=t.addTypeAlias({name:o,type:n});const s=i.getType();return await r(s)}catch{return}finally{try{i==null||i.remove()}catch{}}}async function pi(e,t,n){if(n>rc)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean",const:e.getText()==="true"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.getUnionTypes(),o=r.filter(p=>p.isBooleanLiteral()),i=o.some(p=>p.getText()==="true"),s=o.some(p=>p.getText()==="false");let a=!1;const c=r.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(r.every(p=>p.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(p=>p.getLiteralValue())};if(r.every(p=>p.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?i&&s?{type:"boolean"}:{type:"boolean",const:i}:pi(p,t,n+1))),f=Pt(u);return{oneOf:uc(lc(u)),...f?{discriminator:f}:{},[Ae]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(i=>t(i.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),i=r??o,s=e.getProperties();if(i&&s.length===0)return{type:"object",additionalProperties:await t(i.getText())};const a={},c=[];for(const d of s){const l=d.getName(),f=d.getDeclarations()[0];let g;if(f)try{g=d.getTypeAtLocation(f)}catch{g=void 0}if(g!==void 0&&g.getCallSignatures().length>0)continue;const p=g!==void 0?ic(g,f):void 0;a[l]=p!==void 0?await t(p):{},d.isOptional()||c.push(l)}if(Object.keys(a).length>0){const d=i?await t(i.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:d}}return{}}return{}}function cc(e){return Object.keys(e).length===0?!0:e.type==="object"&&e.additionalProperties!==void 0&&e.additionalProperties!==!1&&(e.properties===void 0||Object.keys(e.properties).length===0)}const dc=new Set(["required","enum","type"]);function yn(e,t){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e)){const o=e.map(i=>yn(i));return t!==void 0&&dc.has(t)&&o.sort(),`[${o.join(",")}]`}const n=e;return`{${Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>`${JSON.stringify(o)}:${yn(n[o],o)}`).join(",")}}`}function lc(e){const t=new Set,n=[];for(const r of e){const o=yn(r);t.has(o)||(t.add(o),n.push(r))}return n}function uc(e){if(e.length<2)return e.slice();const t=e.map(cc),n=e.map((o,i)=>t[i]?i:-1).filter(o=>o>=0);if(n.length===0||n.length===e.length)return e.slice();const r=e.map((o,i)=>t[i]?-1:i).filter(o=>o>=0);return e.map((o,i)=>{if(!t[i])return o;const s=e.filter((a,c)=>c!==i&&(r.includes(c)||t[c]&&c<i));return{allOf:[o,{not:{anyOf:s}}]}})}function Pt(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let i=!0;for(const a of t){const c=a[r],d=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!d||!Array.isArray(l)||l.length!==1){i=!1;break}o.push(String(l[0]))}if(!i||new Set(o).size!==o.length)continue;const s={};return o.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:s}}}function St(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=wn[r];if(o!==void 0)return o;if(n!=null&&n.size){const i=n.get(r);if(i!==void 0){const s=wn[i];if(s!==void 0)return s}}if(r.endsWith("[]"))return{type:"array",items:St(r.slice(0,-2),t+1,n)};if(r.includes("|")){const i=r.split("|").map(c=>c.trim());if(i.every(c=>c.startsWith("'")))return{type:"string",enum:i.map(c=>c.replace(/'/g,""))};const s=i.map(c=>St(c,t+1,n)),a=Pt(s);return{oneOf:s,...a?{discriminator:a}:{},[Ae]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const i=r.slice(1,-1).trim(),s={};for(const a of i.split(";").filter(Boolean)){const[c,d]=a.split(":").map(l=>l.trim());c&&d&&(s[c.replace("?","")]=St(d,t+1,n))}return{type:"object",properties:s}}return{}}function mi(e){const t=[];let n=0,r=0;for(let i=0;i<e.length;i++){const s=e[i];s==="<"||s==="["||s==="{"||s==="("?n++:s===">"||s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function fc(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function pc(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function mc(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const n=t.slice(1,-1).trim();if(n.length!==0)return mi(n)}async function gc(e,t){const n=e.trim(),r=fc(n);if(r!==void 0){const s=mi(r);if(s.length===2){const[a,c]=await Promise.all([t(s[0]),t(s[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=pc(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const i=mc(n);if(i!==void 0){const s=await Promise.all(i.map(a=>t(a)));return{type:"array",items:s,minItems:s.length,maxItems:s.length}}}const gi={"decimal.js":"Decimal"},wn={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},qo={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Ko(e){var n;const t=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),i=gi[o];if(!i)continue;const s=r.getDefaultImport();if(s){const a=s.getText();a!==i&&t.set(a,i)}for(const a of r.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==i&&t.set(c,i)}}return t}function hc(e,t){return n=>{n.addNodeParser({supportsNode(r){var i,s,a;if(r.kind!==t)return!1;const o=((i=r.typeName)==null?void 0:i.escapedText)??((a=(s=r.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return o!==void 0&&Object.prototype.hasOwnProperty.call(qo,o)},createType(r){var a,c,d;const o=((a=r.typeName)==null?void 0:a.escapedText)??((d=(c=r.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:i,StringType:s}=vn();return new i(new s,{format:qo[o]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){const{AnnotatedType:r,StringType:o}=vn();return new r(new o,{format:"int64"},!1)}})}}let ct;function vn(){return ct||(ct=ce("ts-json-schema-generator"),ct)}let Be;function yc(){if(Be)return Be;try{const e=k.dirname(ce.resolve("ts-json-schema-generator/package.json"));Be=ce(ce.resolve("typescript",{paths:[e]}))}catch{Be=ce("typescript")}return Be}const me=new Map;function wc(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function vc(e){const t=me.get(e);return t&&(me.delete(e),me.set(e,t)),t}function bc(e,t){const n=wc();if(n!==0)for(me.delete(e),me.set(e,t);me.size>n;){const r=me.keys().next().value;me.delete(r)}}function Sc(e,t){return`${e}\0${t??""}`}const Ec=new Set(["zod",/^zod\/./]);function kc(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of Ec)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function Ac(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(i=>/zod/i.test(i)));for(const[i,s]of Object.entries(n)){if(o.has(i)||typeof s!="object"||s===null)continue;const a=s,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const d of o)if(c.includes(d)){o.add(i);break}}}for(const i of o)delete n[i]}bn(e)}function bn(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&bn(o,n);else bn(r,n)}}function jc(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const i of Object.keys(o))t.add(i)}const n=Sn(e,t);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function Sn(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const i=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);i&&!t.has(i[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const i of o)typeof i=="object"&&i!==null&&n.push(...Sn(i,t));else n.push(...Sn(o,t));return n}function _c(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=Pt(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Ae]:o[Ae]??"union"}}function Nc(e,t,n){const{DEFAULT_CONFIG:r}=ce("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},i=o.path,s=Sc(i,o.tsconfig);let a;a=n?n.statVersion(i):li(i);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??vc(s);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=ce("ts-json-schema-generator/dist/factory/program.js"),{createParser:u,createFormatter:f,SchemaGenerator:g}=vn(),p=yc(),m=hc(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),v=l(o),h=u(v,o,m),y=f(o);if(c=new g(v,h,y,o),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const w={version:a,gen:c};bc(s,w),n==null||n.generatorCache.set(s,w)}}const d=c.createSchema(o.type);return Ac(d),jc(d),d}function Oc(e,t){let n=e.trim();if(n=yi(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rc=Object.entries(gi).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${hi(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function yi(e){let t=e;for(const{pattern:n,key:r}of Rc)t=t.replace(n,r);return t}function Ic(e,t){let n=yi(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${hi(r)}\\b`,"g"),o);return n}async function We(e,t,n,r,o,i){const s=t.getFilePath(),a=`${s}\0${r??""}\0${n}`,c=i??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),Ho(e,t,n,r,void 0,p)}const d=o.schemaCache.get(a);if(d!==void 0)return o.stats.schemaCacheHits++,d;const l=Ya(s,r,o.statVersion(s)),u=l.get(n);if(u!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(u)),u;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const g=Ho(e,t,n,r,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,g),g}async function Ho(e,t,n,r,o,i){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(o){const f=o.aliasCache.get(t);s=f??Ko(t),f||o.aliasCache.set(t,s)}else s=Ko(t);const a=Oc(n,s),c=wn[a];if(c!==void 0)return c;const d=await gc(a,f=>We(e,t,f,r,o,i));if(d!==void 0)return d;const l=(o==null?void 0:o.zodImportCache.get(t))??kc(t);if(o&&o.zodImportCache.set(t,l),!l)try{const f={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},g=Nc(f,!0,o);return _c(g)}catch{}try{const f=await ac(e,t,a,g=>pi(g,p=>We(e,t,p,r,o,i),0));if(f!==void 0)return f}catch{}const u=Ic(a,s);return St(u,0,s)}function Yn(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return Tc(n,t)}function Tc(e,t){var s;const n=e,r=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${o}\\s*=\\s*([^\\]]+)\\]`);for(const a of r)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(i);if(d)return d[1].trim()}}function $c(e){const t=e.trim(),n=t.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(t!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(t))return Number(t);try{return JSON.parse(t)}catch{return t}}}function Cc(e,t){const n=$c(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}let dt;function Pc(){return dt||(dt=ce("ts-morph").SyntaxKind,dt)}function xt(e){try{if(!e)return;const t=Pc();if(e.getKind()!==t.TypeReference)return;const n=e;if(n.getTypeArguments().length>0)return;const r=n.getTypeName();if(r.getKind()!==t.Identifier)return;const i=r.getSymbol();if(!i)return;const s=i.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const a=s,c=a.getType();if(!(c.isString()||c.isNumber()||c.isBoolean()))return;const l=a.getJsDocs();for(const u of l)for(const f of u.getTags())if(f.getTagName()==="format"){const g=f.getCommentText();if(g!==void 0)return g.trim()}return}catch{return}}const xc=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function Lc(e){const t=[];let n=0,r="";for(const o of e)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(t.push(r.trim()),r=""):r+=o;return r.trim().length>0&&t.push(r.trim()),t}function Uc(e){const t=e.trim(),n=t.indexOf("<");if(n===-1||!t.endsWith(">"))return null;const r=t.slice(0,n),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!xc.has(o))return null;let i=0;for(let c=n;c<t.length;c++){const d=t[c];if(d==="<")i++;else if(d===">"&&(i--,i===0&&c!==t.length-1))return null}if(i!==0)return null;const s=t.slice(n+1,-1),a=Lc(s);return a.length>0?a[0]:null}async function wi(e){const t=e.session===void 0,n=Za(e.session??Qa());try{return await Dc(e,n)}finally{t&&n.dispose()}}async function Dc(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:i}=e,s=t.projectFor(i),a=t.sourceFileFor(n,i),c=k.basename(n),d=ae(Fc(c)),l=o?null:d,u=ae(r),f=[];for(const[m,v]of a.getExportedDeclarations()){if(m==="default"||ut(m))continue;const h=qc(v);if(h){const S=h.getSignature(),E=Jo(S,h),A=S.getReturnType().getText(),j=ve(S);f.push(await lt(s,a,u,l,m,E,A,h.isAsync(),i,t,j));continue}const y=v.find(S=>S.getKindName()==="VariableDeclaration");if(!y)continue;const w=y.getInitializer(),b=w==null?void 0:w.getKindName();if(w&&["ArrowFunction","FunctionExpression"].includes(b??"")){const E=y.getType().getCallSignatures();if(E.length===0)continue;const A=E[0],j=Wo(A,y,y.getVariableStatement()),N=A.getReturnType().getText(),_=ve(A),R=w.isAsync();f.push(await lt(s,a,u,l,m,j,N,R,i,t,_))}else if(b==="ObjectLiteralExpression"){const S=y.getType();for(const E of S.getProperties()){const A=E.getName();if(ut(A))continue;const N=E.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const _=N[0],R=Wo(_,y,y.getVariableStatement()),T=_.getReturnType().getText(),C=ve(_),q=[...l?[l]:[],ae(m),ae(A)];f.push(await Et(s,a,u,q,A,R,T,!1,i,t,C))}}else{const S=y.getType(),E=S.getText();if(Se(S,y)){const A=await We(s,a,E,i,t);f.push(Mc(u,l,m,A))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const g=a.getDefaultExportSymbol();if(g){const m=a.getExportAssignment(v=>!v.isExportEquals());if(m){const v=m.getExpression(),h=v.getKindName();if(["ArrowFunction","FunctionExpression"].includes(h)){const w=v.getType().getCallSignatures();if(w.length>0){const b=w[0],S=Zt(b,m),E=b.getReturnType().getText(),A=ve(b),j=v.isAsync();f.push(await lt(s,a,u,l,"default",S,E,j,i,t,A))}}else{const y=v.getType();for(const w of y.getProperties()){const b=w.getName();if(ut(b))continue;const E=w.getTypeAtLocation(m).getCallSignatures();if(E.length===0)continue;const A=E[0],j=Zt(A,m),N=A.getReturnType().getText(),_=ve(A),R=[...l?[l]:[],ae("default"),ae(b)];f.push(await Et(s,a,u,R,b,j,N,!1,i,t,_))}}}else{const v=g.getDeclarations();for(const h of v){if(h.getKindName()!=="FunctionDeclaration")continue;const y=h,w=y.getName(),b=w&&w.length>0?w:"default",S=y.getSignature(),E=Jo(S,y),A=S.getReturnType().getText(),j=ve(S);f.push(await lt(s,a,u,l,b,E,A,y.isAsync(),i,t,j))}}}const p=Bc(a);if(p.length>0)for(const{name:m,sig:v}of p){if(ut(m))continue;const h=Zt(v),y=v.getReturnType().getText(),w=ve(v),b=[...l?[l]:[],ae(m)];f.push(await Et(s,a,u,b,m,h,y,!1,i,t,w))}return f}function Vo(e,t,n,r){const o=new Set,i=s=>{if(Array.isArray(s))return s.map(i);if(!s||typeof s!="object"||o.has(s))return s;o.add(s);try{const a=s,c={};for(const[d,l]of Object.entries(a)){if(d==="definitions"||d==="$defs"){const u=d,f=t[u];for(const[g,p]of Object.entries(l)){const m=i(p),v=f[g];if(v!==void 0&&JSON.stringify(v)!==JSON.stringify(m))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${u}.${g}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);f[g]=m}continue}c[d]=i(l)}return c}finally{o.delete(s)}};return i(e)}function Go(e,t){if(!t||e.format!==void 0||"$ref"in e||"properties"in e||"items"in e)return;const n=e.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(e.format=t)}function ve(e){var t;try{return xt((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function lt(e,t,n,r,o,i,s,a,c,d,l){const u=ae(o);return Et(e,t,n,r?[r,u]:[u],o,i,s,a,c,d,l)}async function Et(e,t,n,r,o,i,s,a,c,d,l){const u=i.length>0&&i[0].name==="ctx",f=i.filter(_=>_.name!=="ctx"),g=f.filter(_=>!_.optional).map(_=>_.name),p={},m={definitions:{},$defs:{}};for(const _ of f){const R=await We(e,t,_.type,c,d),T=Vo(R,m,o,_.name);_.defaultValue!==void 0&&Cc(T,_.defaultValue),Go(T,_.format),p[_.name]=T}const v=s.replace(/^Promise<(.+)>$/,"$1").trim(),h=Uc(v),y=h!==null,w=y?h:v,b=await We(e,t,w,c,d),S={definitions:{},$defs:{}},E=Vo(b,S,o,"<return>"),A=l?{...E}:E;Go(A,l),Object.keys(S.definitions).length>0&&(A.definitions={...A.definitions,...S.definitions}),Object.keys(S.$defs).length>0&&(A.$defs={...A.$defs,...S.$defs});const j={type:"object",properties:p,required:g,...Object.keys(m.definitions).length>0?{definitions:m.definitions}:{},...Object.keys(m.$defs).length>0?{$defs:m.$defs}:{}};return{id:vi(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:y,safe:!1,input:j,output:A,envelope:{},typeText:{lang:"ts",input:Kc(i),output:w},...u?{hasCtx:!0}:{}}}function Mc(e,t,n,r){const o=ae(n),i=t?[t,o]:[o];return{id:vi(e,i),host:"ts",namespace:e,path:i,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function vi(e,t){return(e.raw?[e,...t]:t).map(r=>r.words.join("-")).join("/")}function ze(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function ae(e){return{raw:e,words:ze(e)}}function Fc(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Bc(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),a=s.getType();for(const c of a.getProperties()){const l=c.getTypeAtLocation(s).getCallSignatures();l.length!==0&&t.push({name:c.getName(),sig:l[0]})}}return t}function qc(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function Jo(e,t){return e.getParameters().map(n=>{var s;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:Yn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function Wo(e,t,n){return e.getParameters().map(r=>{var a;const o=r.getDeclarations(),i=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,s=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((a=i==null?void 0:i.hasQuestionToken)==null?void 0:a.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:s,defaultValue:Yn(i,r.getName(),n??t),format:xt(i==null?void 0:i.getTypeNode())}})}function Zt(e,t){return e.getParameters().map(n=>{var s,a,c;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:o?o.getType().getText():((c=(a=n.getValueDeclaration())==null?void 0:a.getType())==null?void 0:c.getText())??"unknown",optional:i,defaultValue:Yn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function Kc(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function ut(e){return!!(e==="__samples__"||e.startsWith("__"))}function Se(e,t,n=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const r=e.getArrayElementType();return r?Se(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>Se(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>Se(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>Se(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),i=e.getNumberIndexType();if(o||i)return[o,i].every(a=>!a||Se(a,t,n));const s=e.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(t);return Se(c,t,n)})}return!1}function Hc(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const i=e[o],s=r;r=()=>i(n,s)}return r()}}function Vc(e,t){return Hc(e,t)}function Gc(e,t,n={}){const r=e.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return Vc(r,t)}function Jc(e){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:e}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function Wc(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:Jc(e.output)}}function zc(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const i=r.get(o.kind);i?i.push(o):r.set(o.kind,[o])}return r}function zo(e){return{type:"string",enum:[e]}}function Yo(e,t){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:t,items:{type:"array",items:e.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}},additionalProperties:!1}}function Xo(e,t){const n={},r={},o=[["definitions",n],["$defs",r]];for(const i of e){const s=t(i);for(const[a,c]of o){const d=s[a];if(d)for(const[l,u]of Object.entries(d)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(u))throw new Error(`[apigen-core-client] _batch mount: operation "${i.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=u}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(r).length>0?{$defs:r}:{}}}function Yc(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(Wc),n=Xo(e,s=>s.input),r=Xo(e,s=>s.output);if(e.length===1){const[s]=e,[a]=t;return{input:{...Yo(a,zo(s.id)),...n},output:{type:"array",items:a.resultSchema,...r}}}const o=e.map((s,a)=>Yo(t[a],zo(s.id))),i=Pt(o);return{input:{oneOf:o,...i?{discriminator:i}:{},...n},output:{oneOf:t.map(s=>({type:"array",items:s.resultSchema})),...r},...i?{discriminator:i}:{}}}function Xc(e,t={}){const n=zc(e.operations,t),r=[];for(const[o,i]of n){const{input:s,output:a}=Yc(i),c=ai(`_batch/${o}`,e,{kind:o,safe:o==="query",input:s,output:a});r.push({...c,operationIds:i.map(d=>d.id)})}return r}function Xn(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},st(i);const s=n?st.destination({dest:e.destination,mkdir:!0,sync:!0}):st.destination(2);return st(i,s)}function Qc(e){if((e==null?void 0:e.type)!=="object"||!e.properties)return;const t=Object.entries(e.properties);if(t.length===0)return;const n=new Set(e.required??[]);return`{ ${t.map(([o,i])=>`${o}${n.has(o)?"":"?"}: ${Lt(i)}`).join(", ")} }`}function Zc(e){return typeof e=="string"?`'${e}'`:JSON.stringify(e)}function ed(e){const t=e.enum??[];return t.length===0?"unknown":t.map(Zc).join("|")}function td(e,t){return e.map(n=>Lt(n,t)).join(" | ")}function Lt(e,t=0){if(!e)return"unknown";if(e.type==="array")return`${Lt(e.items,0)}[]`;if(e.enum)return ed(e);if(e.$ref)return String(e.$ref).split("/").pop()||"object";const n=e.anyOf??e.oneOf;return n?n.length===0?"unknown":t>=2?td(n,t-1):"union":t>=1&&e.type==="object"?Qc(e)??"object":e.type??"object"}function bi(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),i=Object.entries(r).map(([c,d])=>({name:c,type:Lt(d,2),required:o.has(c)})),s=i.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:i,text:s}}function nd(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function od(e,t){var i,s;const r=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,c]of Object.entries(r)){const d=o[a];if(typeof d!="string")continue;const l=nd(c==null?void 0:c.type);if(l==="number"||l==="integer"){const u=Number(d);!Number.isNaN(u)&&d.trim()!==""&&(o[a]=u)}else l==="boolean"&&(d==="true"?o[a]=!0:d==="false"&&(o[a]=!1))}return o}const rd=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],id={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},Qo={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class L extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function re(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&rd.includes(e.code)&&typeof e.toJSON=="function"}function Zo(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Ut=new Zr({allErrors:!0});ka(Ut);for(const e of[Ae,Bn,ln,un,"discriminator"])Ut.addKeyword({keyword:e,valid:!0});Ut.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function sd(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function ad(e,t){const n=oi(t),r=[`Validation failed: ${sd(e)}`];return n&&r.push(n),r.join(" — ")}function cd(e){return async function(n,r){const o=n.operation.id,i=e[o];if(i===void 0)return r();const s={data:n.domainArgs,...n.envelope},a=Ut.compile(i.input);if(!a(s)){const d=a.errors??[];throw new L("invalid_argument",ad(d,i.input),d)}return r()}}async function Si(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=re(n)?n:new L("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Zo("before-first-chunk",r)}:{ok:!1,carrier:Zo("after-first-chunk",r,t.length)}}}function Dt(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class be extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function en(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Ei(e,t){const n=e[Bn];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function dd(e,t,n){const r=Ei(t,n);return r?r.encode(e,t,n):e}function ld(e,t,n){const r=Ei(t,n);return r?r.decode(e,t,n):e}function ud(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ae]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:en(r)!==void 0},encode(r,o,i){const s=en(o);if(!s)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=s,d=r[a];if(d==null)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const l=String(d),u=c[l];if(!u)throw new be("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=i.resolve(u);return dd(r,f,{...i,path:`${i.path}[${l}]`})},decode(r,o,i){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new be("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=r,a=en(o);if(!a)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:d}=a,l=s[c];if(l==null)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${c}".`);const u=String(l),f=d[u];if(!f)throw new be("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${u}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(d).join(", ")}).`);const g=i.resolve(f);return ld(r,g,{...i,path:`${i.path}[${u}]`})}}}const fd="x-apigen-instances";class ft extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function er(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function pd(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function tr(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function md(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function gd(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ae]==="nominal"?!0:o[Bn]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new ft("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=er(i),c=typeof i[un]=="string"?i[un]:"toJSON",d=o[c];if(typeof d=="function"){const p=d.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const m={};for(const[v,h]of Object.entries(p))m[v]=tr(h,a[v],{...s,path:`${s.path}/${v}`});return m}return p}const l={},u=Object.keys(a),f=o,g=u.length>0?u:Object.keys(f);for(const p of g){const m=f[p];m!==void 0&&(l[p]=tr(m,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ft("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=o;for(const l of pd(i))if(!(l in a))throw new ft("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${s.path}".`);if(i[fd]===!1)throw new ft("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=er(i),d={};for(const[l,u]of Object.entries(a))d[l]=md(u,c[l],{...s,path:`${s.path}/${l}`});if(r){const l=typeof i[ln]=="string"?i[ln]:"fromJSON",u=r[l];if(typeof u=="function")return u.call(r,d);const f=r;return new f(d)}return d}}}const hd=[Kn,Hn,Vn,Gn,Jn,Wn],yd={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},nr=gd({id:"ts.NominalSentinel",schema:yd}),wd={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},or=ud({id:"ts.UnionSentinel",schema:wd});function vd(){const e=[...hd.map(t=>[t.id,t]),[nr.id,nr],[or.id,or]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Ca,codecs:vd()});function En(e,t,n){var s;const r=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,o=oi(t==null?void 0:t.input),i=[n,r,o].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function ki(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!0}:{outputSchema:void 0,wrapped:!1}}function bd(e,t){if(e)return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Sd=4,Ed=32;function kn(e){return re(e)?e:e instanceof Error?new L("internal",e.message):e}function kd(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Sd;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ed)}function Ad(){}function jd(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Ad};const n=new AbortController,r=()=>{n.abort(e==null?void 0:e.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener("abort",r,{once:!0}));let o;return t!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:n.signal,dispose(){e&&e.removeEventListener("abort",r),o&&clearTimeout(o)}}}async function rr(e,t,n,r,o,i){const s=jd(r.signal,i);try{const a=s.signal?{...r,signal:s.signal}:r,c=await e(t,a,o);if(Dt(c)){const d=await Si(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:kn(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",chunks:d.chunks}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:kn(a)}}finally{s.dispose()}}async function _d(e,t,n,r,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=kd(i,o.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:kn(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(i==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(i==="serial"||i==="chained"){let p=!1;for(let m=0;m<n.length;m++){if(p){c[m]=d(m);continue}const v=await rr(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=v,v.status==="rejected"&&(i==="chained"||s==="abort")&&(p=!0)}return c}let l=0,u=!1;const f=Math.max(1,Math.min(a,n.length)),g=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(u){c[p]=d(p);continue}const m=await rr(e,t,p,n[p],r,o.itemTimeoutMs);c[p]=m,m.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(g),c}function ir(e){return e.words.join("-")}function sr(e){return e.words.map(Rd).join("")}function ar(e){return e.words.join("_")}function Nd(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Me(e,t={}){var f,g;const n=[e.namespace,...e.path],r=e.safe||fi(e.input)?"GET":"POST",o=((g=(f=t.http)==null?void 0:f.verb)==null?void 0:g[e.id])??r,i="/"+n.map(p=>ir(p)).join("/"),s=n.map(p=>ar(p)).join("_"),c=n.map(p=>ar(p)).slice(0,-1).join("."),d=sr(n[n.length-2]??n[0]),l=sr(n[n.length-1]),u=n.map(p=>ir(p));return{http:{verb:o,route:i},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function Ai(e,t){return`x-${e}-${t}`}function ji(e,t){return`--${e}-${t}`}function _i(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function At(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}function Od(e){const t=new Set,n=[];for(const r of e){const o=At(r);let i=o,s=2;for(;t.has(i);)i=`${o}_${s}`,s+=1;t.add(i),n.push(i)}return n}function Rd(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ni(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function se(e){return Ni(JSON.stringify(e))}function Id(e,t=3e3){if(e==null)return t;if(typeof e!="string"&&typeof e!="number")throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);if(typeof e=="string"&&e.trim()==="")throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);const n=Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);return n}function Qn(e){return e.anyOf??e.oneOf}function Td(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function $d(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Cd(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function Pd(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function xd(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function cr(e){return typeof e.handler=="function"}function Ld(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd",a=Ai(s,i);r.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:ji(s,i),envVar:_i(s,i)})}return r}function Ud(e,t,n,r){t===n||e.has(t)||e.set(t,{...r,aliasOf:n})}function Dd(e,t){const n=new Map,{props:r}=xd(e);for(const[o,i]of Object.entries(r)){let s="string";$d(i)?s="boolean":(Td(i)||Cd(i))&&(s="json");const a=Pd(o),c={camelKey:o,kind:"domain",valueKind:s};n.set(a,c),Ud(n,o,a,c)}for(const o of t){const i=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(i,s)}return n}function ye(e){const{op:t,schema:n,transport:r,projection:o}=e,i=Me(t,o),s=n?Ld(n):[],a=n?Dd(n,s):new Map,c=n?bi(n).params:void 0,d={op:t,transport:r,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:c,envelope:s,cliFlags:a,streaming:t.streaming,isMount:cr(t)};if(cr(t)){const l=t.handler;d.mountHandler=async u=>l(u)}return d}function Zn(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Md(e){const t=e.exitCode;return typeof t=="function"?t:void 0}function eo(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Fd(e){return async function(n,r){const o=Object.assign(n,{data:n.domainArgs});return await e.layer(o,r)}}function de(e,t){var r;const n=[];for(const o of t){const i=(r=o.capabilities)==null?void 0:r.layer;i&&n.push(Fd(i))}return n.push(cd(e)),za(n)}function Bd(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const qd={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function xe(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new tt};if(e.isMount){const i=e.mountHandler;if(!i)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const s={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Bd(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:qd}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}function Oi(e){return e.anyOf??e.oneOf}function Kd(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r.push({field:i,pluginId:s,flag:ji(s,i),envVar:_i(s,i)})}return r}function An(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Oi(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Hd(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Oi(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function dr(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function Vd(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Gd(e){const n=to(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function tn(e){var i,s;const t=(s=(i=e.input)==null?void 0:i.properties)==null?void 0:s.data;if(!t)return;const n=t.oneOf,r=t.discriminator;if(!n||!r)return;const o=[];for(const[a,c]of Object.entries(r.mapping)){const d=Vd(c);if(d===void 0)continue;const l=n[d];if(!l)continue;const u=l.properties??{},f=l.required??[];o.push({value:a,commandName:Gd(a),props:u,required:f})}if(o.length!==0)return{discriminatorProperty:r.propertyName,branches:o}}function to(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Jd(e,t){if(!cn.isAbsolute(t))return t;const n=cn.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Wd=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
3
+ `);function Ri(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Ii(e,t,n,r){var o;for(const i of t){const s=to(i),a=Hd(n[i]),c=r.includes(i);a?(e.push(` .option('--${s}')`),((o=n[i])==null?void 0:o.default)===!0&&e.push(` .option('--no-${s}')`)):c?e.push(` .requiredOption('--${s} <${s}>')`):e.push(` .option('--${s} <${s}>')`)}}function Ti(e,t,n){return`${e}:${t}::${n}`}function $i(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([g,p])=>`'${g}': ${p}`),f=a.map(g=>An(c[g])?`'${g}': __apigenParseJsonArg('${to(g)}', opts['${g}'])`:`'${g}': opts['${g}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...u,...f].join(", ")} }`),i.length>0){const g=i.map(p=>{const v=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(h,y)=>y.toUpperCase());return`'${p.field}': opts['${v}'] ?? process.env['${p.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${g.join(", ")} }`)}else s?e.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):e.push(" const envelope: Record<string, unknown> = {}");e.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function zd(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,rootUnion:a}=t,c=At(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const d of a.branches){const l=Object.keys(d.props).filter(f=>f!==a.discriminatorProperty),u=d.required.filter(f=>f!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${d.commandName}')`),Ri(e,i,s),Ii(e,l,d.props,u),$i(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Ti(r,o,d.commandName),bindings:i,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function Yd(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(s=>Object.values(s.schemas).some(a=>{const c=tn(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>An(l.props[u])));const{props:d}=dr(a);return hn(a).some(l=>An(d[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const s of e.packages){const a=At(s.id),c=Jd(e.outputDir,s.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(Wd),o.push(""));const i=Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,c])));for(const s of e.packages)for(const[a,c]of Object.entries(s.schemas)){const d=tn(c);if(d)for(const l of d.branches){const u=Ti(s.id,a,l.commandName);i[u]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(i,null,2)}`),o.push(""),o.push(`const program = new Command().name('${t}').version('${n}')`),o.push("");for(const s of e.packages){const a=At(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=si(d,"session"),u=Kd(d),f=tn(d);if(f){zd(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const g=hn(d),{props:p,required:m}=dr(d);o.push("program"),o.push(` .command('${c}')`),Ri(o,u,l),Ii(o,g,p,m),$i(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,paramNames:g,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
+ `)}]}}function Xd(e){return{props:e.properties??{},required:e.required??[]}}function Qd(e){const t=e??{},r=Array.isArray(t.oneOf)&&t.oneOf.length>0?t.oneOf:[t],o={},i=new Map;for(const a of r){const{props:c,required:d}=Xd(a);for(const[l,u]of Object.entries(c))l in o||(o[l]=u);for(const l of d)i.set(l,(i.get(l)??0)+1)}const s=[...i.entries()].filter(([,a])=>a===r.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:o,required:s}},required:["data"]},output:{}}}function Zd(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function el(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?Zd(t):process.argv.slice(2)}function tl(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function nl(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,i]of Object.entries(r.schemas)){const s=t.get(`${r.id}:${o}`)??tl(o,i),a=ye({op:s,schema:i,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:i,cliPath:c,plan:a})}return n}function ol(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function Ci(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function lr(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const i=Ci(o.params);t.push(` ${r}${i?` { ${i} }`:""}`)}return t.join(`
5
+ `)}function pt(e){return new L("invalid_argument",e)}function rl(e,t){var i;const n={},r={};let o=0;for(;o<e.length;){const s=e[o];if(!s.startsWith("--"))throw pt(`Unexpected positional argument: "${s}"`);let a=s.slice(2),c;const d=a.indexOf("=");d!==-1&&(c=a.slice(d+1),a=a.slice(0,d));let l=!1,u=a;a.startsWith("no-")&&((i=t.get(a.slice(3)))==null?void 0:i.valueKind)==="boolean"&&(l=!0,u=a.slice(3));const f=t.get(u);if(!f)throw pt(`Unknown option: --${a}. Available: ${[...t.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);o++;let g;if(f.valueKind==="boolean")l?g=!1:c===void 0?g=!0:g=c!=="false";else{const p=c!==void 0?c:e[o++];if(p===void 0)throw pt(`Missing value for --${a}`);if(f.valueKind==="json")try{g=JSON.parse(p)}catch(m){throw pt(`Invalid JSON for --${a}: ${m.message}`)}else g=p}f.kind==="domain"?n[f.camelKey]=g:r[f.camelKey]=g}for(const s of t.values()){if(s.kind!=="envelope"||!s.envVar||r[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(r[s.camelKey]=a)}return{domainArgs:n,envelope:r}}function Pi(e){const t=re(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=re(e)?Qo[e.code]:Qo.internal}function il(e,t,n){if(re(n)&&n.code!=="internal"){e.error({command:t,code:n.code,message:n.message},`✗ ${t}`);return}e.error({command:t,err:n},`✗ ${t}`)}class sl{constructor(t,n){this.signal=t,this.exitCodeHook=n,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=rl(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){var i;if(Dt(n))throw new L("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const o=(i=this.exitCodeHook)==null?void 0:i.call(this,n);typeof o=="number"&&o!==0&&(process.exitCode=o)}writeError(t,n,r){Pi(n)}}function al(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("cli")||i.push(u)}return i}async function cl(e){var E,A,j;const t=e.logger??Xn();if((E=e.signal)!=null&&E.aborted){t.info("cli run: signal already aborted before dispatch — skipping");return}let n=el(e.options);n[0]==="--"&&(n=n.slice(1));const r=Zn(e.options),o=eo(e.options),i=new sl(e.signal,Md(e.options)),s=nl(e),a=new Map;for(const N of s.values()){const _=a.get(N.pkgId);_?_.push(N):a.set(N.pkgId,[N])}const c={},d={};for(const N of e.packages){const _=a.get(N.id);if(!_||_.length===0)continue;if(!N.fns)throw new Error(`apigen-plugin-cli-output: package "${N.id}" has no functions`);const R=N.fns,T={},C={};for(const P of _)T[P.plan.op.id]=P.schema,C[P.plan.op.id]=R[P.fnName],c[P.plan.op.id]=P.schema,d[P.plan.op.id]=R[P.fnName];const q=de(T,r),x={fns:C,createClient:N.createClient,schemas:T};for(const P of _)i.registerRoute(P.plan,Y=>xe(P.plan,q,Y,x))}const l=((A=e.packages[0])==null?void 0:A.id)??"ts",u=de(c,r),f={invoke:(N,_,R)=>u(N,{operation:{id:N},ctx:new tt,domainArgs:_.domainArgs,envelope:_.envelope,signal:_.signal},R),invokeOptions:{fns:d,schemas:c,createClient:(j=e.packages[0])==null?void 0:j.createClient}},g=al(r,o,l,e.operations??[],f);if(g.length>0){const N=de({},r),_={fns:{},schemas:{}};for(const R of g){const T=ye({op:R,schema:Qd(R.input),transport:"cli"});i.registerRoute(T,C=>xe(T,N,C,_))}}const p=i.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(lr(p));return}const m=ol(n,p);if(!m){Pi(new L("not_found",`Unknown command: ${n.join(" ")}
6
+
7
+ ${lr(p)}`));return}const{entry:v,rest:h}=m,{plan:y,dispatch:w}=v,b=y.cli.path.join(" ");if(h.includes("--help")||h.includes("-h")){const N=Ci(y.params);console.log(`${b}${N?` { ${N} }`:""}`);return}const S={rest:h};try{if(y.streaming)throw new L("invalid_argument",`Command "${b}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const N=await i.readCall(S,y),_=Date.now(),R=await w(N);await i.writeResult(S,R,y),t.info({command:b,ms:Date.now()-_},`→ ${b}`)}catch(N){il(t,b,N),await i.writeError(S,N,y)}}const dl={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(e){return Yd(e)},run(e){return cl(e)}};function ll(e,t){const n=e.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const r=n,o=r.operation;if(typeof o!="string"||o.length===0)throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!t.includes(o))throw new L("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${t.join(", ")}`);const i=r.items;if(!Array.isArray(i))throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=r.concurrency;if(s!==void 0&&typeof s!="number")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=r.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=r.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=r.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:i,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function ul(e,t){return async n=>{if(!t)throw new L("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=ll(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},i=r.items.map(s=>({operation:{id:r.operation},ctx:new tt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return _d(t.invoke,r.operation,i,t.invokeOptions,o)}}function fl(e,t={},n){return Xc(e,t).map(o=>({...o,handler:ul(o.operationIds,n)}))}const jt={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(e,t,n){return fl(e,t,n)}}}},ur={validateKind(){},validateRel(){},validateEdge(){}},pl=5,ml=20,gl=500;function hl(e){return pe.isBusyError(e)||pe.isConcurrentConflict(e)}function yl(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function wl(e,t={}){const n=t.maxAttempts??pl;for(let r=0;;r++)try{return await e()}catch(o){if(!hl(o)||r>=n-1)throw o;const i=Math.min(gl,ml*2**r);await yl(i*(.5+Math.random()*.5))}}const no=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class xi extends Error{constructor(t,n){const r=t.length>0?t.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
8
+ expected node kind(s): ${n.join(", ")}
9
+ found in store: ${r}
10
+ The store holds live node(s) but none of a kind this build recognizes, so every item read would match zero rows and report a misleading "0 items".
11
+ Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=t,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function Li(e){const{rows:t}=await e.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=t.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,i)=>o+i.count,0),observed:n}}async function vl(e){const t=[...no],n=t.map(()=>"?").join(", "),{rows:r}=await e.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,t);return r.length>0}async function oo(e){if(await vl(e))return;const{total:t,observed:n}=await Li(e);if(t!==0)throw new xi(n,[...no])}const bl=3e4,fr=new WeakMap;function Sl(e){let t=fr.get(e);return t||(t=new Set,fr.set(e,t)),t}function Ui(e){const t=Sl(e);return{register(n){t.add(n);let r=!1;return()=>{r||(r=!0,t.delete(n))}},get size(){return t.size},snapshot(){return[...t]},async drain(n){const r=(n==null?void 0:n.timeoutMs)??bl,o=Date.now()+r;let i=0;for(;;){const a=[...t].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const d=await El(Promise.allSettled(a.map(l=>l.settled)),c);if(i+=a.filter(l=>l.outcome!=="pending").length,d==="timeout")break}const s=[...t];return{drained:i,stillPending:s.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:s.filter(a=>a.outcome==="unrecorded")}}}}async function El(e,t){let n;const r=new Promise(o=>{n=setTimeout(()=>o("timeout"),t),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([e,r])}finally{n!==void 0&&clearTimeout(n)}}function jn(){return[]}function kl(e){const t=W.homedir();if(e===t)return"~";const n=t.endsWith(k.sep)?t:t+k.sep;return e.startsWith(n)?"~"+e.slice(t.length):e}function Al(e,t){if(e===t)return!0;const n=k.relative(e,t);return n!==".."&&!n.startsWith(`..${k.sep}`)&&!k.isAbsolute(n)}function ro(e){const t=e==null?void 0:e.code;return t==="ENOENT"||t==="ENOTDIR"}async function _n(e){const t=k.resolve(e);try{return await Ct.realpath(t)}catch(n){if(!ro(n))throw n;const r=k.dirname(t);if(r===t)throw n;return k.join(await _n(r),k.basename(t))}}async function Di(e,t,n){const r=k.isAbsolute(t)?k.resolve(t):k.resolve(e,t),o=await _n(r);return{accepted:(await Promise.all([e,...n].map(a=>_n(a)))).some(a=>Al(a,o)),candidate:o}}class B extends Error{constructor(t,n=void 0,r){super(t),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class Mi extends B{constructor(t,n){super(`Write contention: exhausted the retry budget (last backoff ${t}ms)`,n,t),this.code="E_CONTENTION",this.retryable=!0}}class Fi extends B{constructor(t){const n=Bi(t);super(`Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction: ${n.message}`,t),this.code="E_IO",this.retryable=!0,this.causeMessage=n.message,n.code!==void 0&&(this.causeCode=n.code)}}function Bi(e){if(e instanceof Error){const t=e.code;return{message:e.message,...typeof t=="string"?{code:t}:{},...e.stack!==void 0?{stack:e.stack}:{}}}if(typeof e=="object"&&e!==null){const t=e;return{message:typeof t.message=="string"?t.message:JSON.stringify(e),...typeof t.code=="string"?{code:t.code}:{}}}return{message:String(e)}}const jl="backlog.write.io_failure";function Nn(e,t,n){const r=Bi(e);Mn.log.error(jl,{origin:t,retryable:n,error:r.message,...r.code!==void 0?{error_code:r.code}:{},...r.stack!==void 0?{stack:r.stack}:{}})}class Mt extends B{constructor(t,n){super(n===void 0?`Issue "${t}" was already superseded by a concurrent write; re-get and retry`:`Issue "${t}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=t,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class G extends B{constructor(t,n){super(`${t} "${n}" was not found`),this.catalogKind=t,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class I extends B{constructor(t,n){super(n?`Invalid argument "${t}": ${n}`:`Invalid argument "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}class Ft extends B{constructor(t){super(`No live issue found for uid "${t}"`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class _t extends B{constructor(t,n){super(`Claim already held by "${t}" since ${n}`),this.heldBy=t,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class qi extends B{constructor(t,n){super(`Issue "${t}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=t,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class On extends B{constructor(t){const n=t.side==="source"?`"${t.rel}" already has a single target (${t.conflictingUid}) for source "${t.cappedUid}"`:`"${t.rel}" already has a single source (${t.conflictingUid}) for target "${t.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=t.side,this.cappedUid=t.cappedUid,this.rel=t.rel,this.conflictingUid=t.conflictingUid}}class io extends B{constructor(t,n){const r=n.length===0?"the project root":n.map(kl).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots";super(`Citation target "${t}" could not be verified and this project requires a real sha — accepted only under: ${r} (${o})`),this.target=t,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class _l extends B{constructor(t){super(`Citation target "${t}" is a directory, not a file — a citation must name a file inside it (use the citation's \`lines\` field for a range) so its content can be hashed`),this.target=t,this.code="E_VALIDATION",this.retryable=!1}}function Ki(e,t){return(e==null?void 0:e.code)==="EISDIR"?new _l(t):(Nn(e,"citation_sha",!0),new Fi(e))}class Hi extends B{constructor(t){super(`A note is required to transition issue "${t}" (project_policy.transition_requires_note)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Vi extends B{constructor(t){super(`At least one citation is required to close issue "${t}" (project_policy.citation_required)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class je extends B{constructor(t,n){super(n?`Invalid "${t}": ${n}`:`Invalid "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}function Nl(e){const t=e instanceof Error?e.message:String(e);return pe.isBusyError(e)||pe.isConcurrentConflict(e)?{code:"E_CONTENTION",retryable:!0,message:t,cause:e}:pe.isUniqueConstraintError(e)||pe.isForeignKeyError(e)?{code:"E_CONSTRAINT",retryable:!1,message:t,cause:e}:pe.isDatabaseError(e)?(Nn(e,"transaction",!0),{code:"E_IO",retryable:!0,message:t,cause:e}):(Nn(e,"transaction",!1),{code:"E_IO",retryable:!1,message:t,cause:e})}const Ol=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function Q(e,t){if(Ol.has(t.trim().toLowerCase()))throw new I(e,`"${t}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}function Gi(e){if(e!=null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}function Ji(e){return{rowid:e.rowid,uid:e.uid,kind:e.kind,name:e.name,content:e.content??"",metadata:Gi(e.meta),tInvalid:e.t_invalid,isSuperseded:e.is_superseded===1}}function V(){return new Date().toISOString()}function so(e){return ue.createHash("sha256").update(e).digest("hex")}function Wi(e){return JSON.stringify(Rn(e))}function Rn(e){if(Array.isArray(e))return e.map(Rn);if(e!==null&&typeof e=="object"){const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=Rn(t[r]));return n}return e}async function Bt(e,t){const n=await e.executeGet("SELECT * FROM node WHERE uid = ?",[t]);return n?Ji(n):null}async function we(e,t){const n=await Bt(e,t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid!==null)throw new Ft(t);if(n.isSuperseded)throw new Mt(t);return n}async function fe(e,t){const n=await e.executeGet("SELECT * FROM node WHERE rowid = ?",[t]);return n?Ji(n):null}const Rl=["off","on"];function Il(){const e=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(e===void 0)return"off";if(Rl.includes(e))return e;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${e}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function J(e,t){const n=t.at??V(),r=t.content??t.name??"",o=so(r.trim().toLowerCase());if(Il()==="on"){const c=await e.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const i=ue.randomUUID(),s=t.metadata!==void 0?JSON.stringify(t.metadata):null,a=await e.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
12
+ confidence, content_hash, namespace, meta, agent_id, session_id, source,
13
+ project_path, t_occurred, t_expires, t_created, t_valid)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
15
+ RETURNING rowid`,[i,t.kind,r,t.name??null,null,null,null,1,null,o,"global",s,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${t.kind}" name="${t.name??""}"`);return{rowid:a.rowid,uid:i}}async function Tl(e,t){const{multiplicity:n}=t.rule;if(n==="n:m")return;if(n==="n:1"){const o=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
16
+ WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[t.srcRowid,t.rel,t.dstRowid]);if(o)throw new On({side:"source",cappedUid:t.srcUid,rel:t.rel,conflictingUid:o.uid});return}const r=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
17
+ WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[t.dstRowid,t.rel,t.srcRowid]);if(r)throw new On({side:"target",cappedUid:t.dstUid,rel:t.rel,conflictingUid:r.uid})}async function M(e,t){const{rule:n}=t;if(n.sourceKind!=="*"&&n.sourceKind!==t.srcKind)throw new pr(t.rel,"source",n.sourceKind,t.srcKind);if(n.targetKind!==t.dstKind)throw new pr(t.rel,"target",n.targetKind,t.dstKind);await Tl(e,t),t.typePolicy.validateEdge?t.typePolicy.validateEdge(t.srcKind,t.rel,t.dstKind):t.typePolicy.validateRel(t.rel);const r=t.at??V(),o=t.metadata!==void 0?JSON.stringify(t.metadata):null;await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
18
+ VALUES (?, ?, ?, ?, 'user_asserted', ?, ?, ?)
19
+ ON CONFLICT(src, dst, rel) DO UPDATE SET
20
+ meta = excluded.meta, weight = excluded.weight,
21
+ t_invalid = NULL, t_valid = excluded.t_valid`,[t.srcRowid,t.dstRowid,t.rel,t.weight??1,o,r,r])}class pr extends B{constructor(t,n,r,o){super(`"${t}" requires a ${n} of kind "${r}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function _e(e,t){const n=await e.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t.srcRowid,t.dstRowid,t.rel]);if(!n)return;const r=t.at??V(),o={...Gi(n.meta)??{},invalidatedAt:r,...t.reason!==void 0?{invalidatedReason:t.reason}:{}};await e.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(o),n.rowid])}const mt=[250,500];function $l(e){return new Promise(t=>setTimeout(t,e))}const Cl=["immediate","deferred"];function Pl(){const e=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(e===void 0)return"immediate";if(Cl.includes(e))return e;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${e}" is not a recognized transaction mode (expected "immediate" or "deferred"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "immediate" so a mistyped negative control can never pass for the wrong reason.`)}async function z(e,t){let n=0;for(;;)try{return await e.adapter.transaction(t,{mode:Pl()})}catch(r){if(r instanceof B)throw r;const o=Nl(r);if(o.code==="E_CONTENTION"){if(n<mt.length){const i=mt[n];n+=1,await $l(i);continue}throw new Mi(mt[mt.length-1],r)}throw o.code==="E_IO"&&o.retryable?new Fi(r):r}}function ao(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}const xl=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Ne(e){return xl.test(e)}async function nt(e,t,n){const r=await Bt(e,n);if((r==null?void 0:r.tInvalid)!==null||r.kind!==t)throw new G(t,n);const{name:o}=r;if(o===null)throw new G(t,n);return{...r,name:o}}async function Ye(e,t){if(Ne(t)){const o=await nt(e,"project",t);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[t]);if(!n)throw new G("project",t);let r;if(n.meta!==null)try{r=JSON.parse(n.meta)}catch{r=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??t,metadata:r}}async function co(e,t){var r;if(Ne(t.ref)){const o=await nt(e,"component",t.ref);if(((r=o.metadata)==null?void 0:r.projectUid)!==t.projectUid)throw new G("component",t.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await e.executeGet(`SELECT rowid, uid, name FROM node
22
+ WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
23
+ AND json_extract(meta, '$.projectUid') = ?
24
+ LIMIT 1`,[t.ref,t.projectUid]);if(!n)throw new G("component",t.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??t.ref}}async function zi(e,t){const n=await e.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
25
+ FROM edge e JOIN node c ON c.rowid = e.dst
26
+ WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
27
+ AND c.name = '(root)' AND c.t_invalid IS NULL
28
+ LIMIT 1`,[t.projectRowid]);if(!n)throw new G("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}async function he(e,t){if(Ne(t.ref)){const i=await nt(e,t.catalogKind,t.ref);return{rowid:i.rowid,uid:i.uid,name:i.name}}const n=await e.executeGet("SELECT rowid, uid, name FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[t.catalogKind,t.ref]);if(n)return{rowid:n.rowid,uid:n.uid,name:n.name??t.ref};const r=t.mintMetadata?await t.mintMetadata(e):{},o=await J(e,{kind:t.catalogKind,name:t.ref,metadata:r,at:t.at});return{rowid:o.rowid,uid:o.uid,name:t.ref}}async function Yi(e){const t=await e.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(t==null?void 0:t.maxRank)??null;return n===null?0:n+1}const Ll=[{rel:"owns_project",sourceKind:"project",targetKind:"component",multiplicity:"1:n"},{rel:"owns_component",sourceKind:"component",targetKind:"issue",multiplicity:"1:n"},{rel:"has_kind",sourceKind:"issue",targetKind:"kind",multiplicity:"n:1"},{rel:"has_status",sourceKind:"issue",targetKind:"status",multiplicity:"n:1"},{rel:"has_priority",sourceKind:"issue",targetKind:"priority",multiplicity:"n:1"},{rel:"authored_by",sourceKind:"issue",targetKind:"agent",multiplicity:"n:1"},{rel:"has_note",sourceKind:"issue",targetKind:"note",multiplicity:"1:n"},{rel:"has_citation",sourceKind:"issue",targetKind:"citation",multiplicity:"1:n"},{rel:"has_transition",sourceKind:"issue",targetKind:"transition",multiplicity:"1:n"},{rel:"audits",sourceKind:"*",targetKind:"audit",multiplicity:"1:n"},{rel:"depends_on",sourceKind:"component",targetKind:"component",multiplicity:"n:m"},{rel:"has_location",sourceKind:"component",targetKind:"location",multiplicity:"1:n"},{rel:"relates_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"supersedes",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"blocks",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"duplicate_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"part_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"}],mr=new Map(Ll.map(e=>[e.rel,e]));async function F(e,t){const n=await e.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[t]);if(n){const o=ao(n.meta)??{},i=typeof o.source_kind=="string"?o.source_kind:void 0,s=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(i&&s&&a)return{rel:t,sourceKind:i,targetKind:s,multiplicity:a};const c=mr.get(t);if(!c)throw new G("edge_kind",t);return await e.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[V(),n.rowid]),await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const r=mr.get(t);if(!r)throw new G("edge_kind",t);return await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:r.sourceKind,target_kind:r.targetKind,multiplicity:r.multiplicity}}),r}const ee=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,citationAllowedExternalRoots:Object.freeze([]),dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[]});function oe(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}function Le(e){var r;const t=(r=e.metadata)==null?void 0:r.policy;if(t===null||typeof t!="object")return{...ee,citationAllowedExternalRoots:jn()};const n=t;return{transitionRequiresNote:n.transitionRequiresNote??ee.transitionRequiresNote,citationRequired:n.citationRequired??ee.citationRequired,citationRequiresSha:n.citationRequiresSha??ee.citationRequiresSha,citationAllowedExternalRoots:Ul(n),defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??ee.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??ee.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??ee.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??ee.allowedStatuses,allowedKinds:n.allowedKinds??ee.allowedKinds,requiredFields:n.requiredFields??ee.requiredFields}}function Ul(e){const t=e.citationAllowedExternalRoots;return t===void 0||!Array.isArray(t)||!t.every(n=>typeof n=="string")?jn():t}function qt(e){var n;const t=(n=e.metadata)==null?void 0:n.path;return typeof t=="string"&&t.length>0}function Nt(e,t){const n={...e};for(const[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}async function Dl(e,t){return oe("name",t.name),oe("by",t.by),Q("by",t.by),z(e,n=>Ml(n,e,t))}async function Ml(e,t,n){const r=V(),o=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),i={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=Nt(ao(o.meta)??{},i);return await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:r}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const s=Nt({},i),a=await J(e,{kind:"project",name:n.name,metadata:s,at:r}),c=await J(e,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:r}),d=await F(e,"owns_project");return await M(e,{at:r,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:d,typePolicy:t.typePolicy}),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:r}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function Fl(e,t){return oe("project",t.project),oe("name",t.name),oe("by",t.by),Q("by",t.by),z(e,n=>Bl(n,e,t))}async function Bl(e,t,n){const r=V(),o=await Ye(e,n.project),i=await e.executeGet(`SELECT rowid, uid, name, meta FROM node
29
+ WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
30
+ AND json_extract(meta, '$.projectUid') = ?
31
+ LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(i)u=Nt({...ao(i.meta)??{},projectUid:o.uid},s),await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(u),i.rowid]),a=i.rowid,c=i.uid,d=i.name??n.name,l=!1;else{u=Nt({projectUid:o.uid},s);const g=await J(e,{kind:"component",name:n.name,metadata:u,at:r});a=g.rowid,c=g.uid,d=n.name,l=!0}const f=await F(e,"owns_project");return await M(e,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:t.typePolicy}),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:r}),{uid:c,created:l,component:{uid:c,name:d,projectUid:o.uid,path:u.path,description:u.description}}}const gr=["path","url","tool"];async function ql(e,t){if(oe("component",t.component),oe("value",t.value),oe("by",t.by),Q("by",t.by),!gr.includes(t.locType))throw new I("locType",`must be one of ${gr.join(", ")}`);return z(e,async n=>{const r=V();let o;if(Ne(t.component)){const d=await nt(n,"component",t.component);o={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(t.project===void 0||t.project.trim().length===0)throw new I("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await Ye(n,t.project);o=await co(n,{projectUid:d.uid,ref:t.component})}const i=await n.executeGet(`SELECT rowid, uid FROM node
32
+ WHERE kind = 'location' AND t_invalid IS NULL
33
+ AND json_extract(meta, '$.componentUid') = ?
34
+ AND json_extract(meta, '$.locType') = ?
35
+ AND json_extract(meta, '$.value') = ?
36
+ LIMIT 1`,[o.uid,t.locType,t.value]);if(i)return{uid:i.uid,created:!1,location:{uid:i.uid,locType:t.locType,value:t.value,componentUid:o.uid}};const s={componentUid:o.uid,locType:t.locType,value:t.value},a=await J(n,{kind:"location",name:t.value,metadata:s,at:r}),c=await F(n,"has_location");return await M(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:t.by,action:"created",at:r}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:t.locType,value:t.value,componentUid:o.uid}}})}async function Kl(e,t){return oe("uid",t.uid),oe("by",t.by),Q("by",t.by),z(e,async n=>{var c;const r=V(),o=await nt(n,"location",t.uid),i={...o.metadata??{},...t.reason!==void 0?{invalidatedReason:t.reason}:{},invalidatedAt:r},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[r,JSON.stringify(i),o.rowid]);if(s.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${s.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const d=await Bt(n,a);(d==null?void 0:d.tInvalid)===null&&await _e(n,{srcRowid:d.rowid,dstRowid:o.rowid,rel:"has_location",reason:t.reason,at:r})}return await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:t.by,action:"deleted",note:t.reason,at:r}),{uid:o.uid,invalidated:!0}})}async function U(e){const t=e.at??V(),n={actor:e.actor,action:e.action,target_uid:e.subjectUid,from:e.from??null,to:e.to??null,note:e.note??null,at:t},r=so(Wi(n)),o={...n,sha:r},i=await J(e.tx,{at:t,kind:"audit",name:e.action,content:e.note??e.action,metadata:o}),s=await F(e.tx,"audits");return await M(e.tx,{at:t,srcRowid:e.subjectRowid,srcUid:e.subjectUid,srcKind:e.subjectKind,dstRowid:i.rowid,dstUid:i.uid,dstKind:"audit",rel:"audits",rule:s,typePolicy:e.typePolicy}),{rowid:i.rowid,uid:i.uid,sha:r}}const Hl="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function lo(e,t){return`${e}
37
+ ${t}`.trim()}function Ot(e,t){const n=e.embedding;if(!n)return Promise.resolve();const r=Vl(e,n,t),o={subjectRowid:t.subjectRowid,subjectUid:t.subjectUid,actor:t.actor,action:t.action,settled:r,outcome:"pending"},i=Ui(e.adapter).register(o);return r.then(s=>{o.outcome=s,s!=="unrecorded"&&i()},()=>{o.outcome="unrecorded"}),r.then(()=>{})}async function Vl(e,t,n){let r,o;try{if(n.action==="upsert"){const i=await t.embedDocument(n.content);await t.upsertVector(n.subjectRowid,i),r="embedding_upserted"}else await t.deleteVector(n.subjectRowid),r="embedding_deleted"}catch(i){r="embedding_failed",o=i instanceof Error?i.message:String(i),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,i)}try{await z(e,async i=>{await U({tx:i,typePolicy:e.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:r,note:o})})}catch(i){return console.error(`scheduleIssueEmbedding: failed to persist "${r}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,i),"unrecorded"}switch(r){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function Gl(e,t){const n=[],r=[];for(const o of t)try{await z(e,async i=>{await U({tx:i,typePolicy:e.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:Hl})}),o.outcome="failed",n.push(o)}catch(i){o.outcome="unrecorded",r.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,i)}return{recorded:n,unrecorded:r}}async function Rt(e,t=5e3){if(e!==":memory:"&&O.mkdirSync(k.dirname(e),{recursive:!0}),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const n=await pe.createStoreAdapter({dbPath:e});await n.pragmaSet("busy_timeout",t);const r=Aa.createGraphBackend(n,{typePolicy:ur});await wl(()=>r.applySchema());try{await oo(n)}catch(i){throw await n.close().catch(()=>{}),i}return{adapter:n,graph:r,typePolicy:ur,flushEmbeds:i=>Ui(n).drain(i)}}async function Xi(e,t){const n=await e.flushEmbeds(t);let r=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const i=await Gl(e,n.stillPending);r=i.recorded.length,o=[...o,...i.unrecorded]}}finally{await e.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:r,unrecorded:o}}async function In(e){if(!e)return;let t;try{t=await Xi(e)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}t.unrecorded.length>0?(console.error(`backlog: ${t.unrecorded.length} scheduled embed(s) died UNRECORDED — the store closed before they settled and the embedding_failed audit row could not be written. The subject write(s) are durable; the vector(s) are missing. Re-run the embedding backfill.`),process.exitCode||(process.exitCode=1)):t.stillPending.length>0&&console.error(`backlog: ${t.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Tn=["SIGINT","SIGTERM"];function Qi(e,t=n=>process.exit(n)){let n=!1;const r=i=>{n||(n=!0,e().catch(s=>{console.error(`backlog: signal cleanup failed (${i}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{o(),t(128+W.constants.signals[i])}))},o=()=>{for(const i of Tn)process.removeListener(i,r)};for(const i of Tn)process.on(i,r);return{dispose:o}}function Jl(){return Tn.some(e=>process.listenerCount(e)>0)}const Wl=[".git",".adhd","adhd.environment.yaml"];function nn(e){let t=k.resolve(e);const{root:n}=k.parse(t);for(;;){for(const o of Wl)if(O.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=k.dirname(t);if(r===t)return;t=r}}const zl=new Set(["system","global","project"]);function Yl(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:nn(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&zl.has(r)){const i=r;return i==="project"?{scope:"project",projectRoot:nn(n)??n}:{scope:i}}const o=nn(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function hr(e){return`.${e}`}function Xl(e){const t=W.homedir();if(process.platform==="darwin")return k.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??k.join(t,"AppData","Roaming");return k.join(r,e)}const n=process.env.XDG_DATA_HOME??k.join(t,".local","share");return k.join(n,e)}function Ql(e){const t=e.orgNamespace,n=e.adhdRoot??k.join(W.homedir(),hr(t)),r=e.adhdRoot??Xl(t),o={system:k.join(r,e.project,e.namespace),global:k.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=k.join(e.projectRoot,hr(t),e.project,e.namespace)),o}function Zi(e,t){return t==="project"?e.project??e.global:e[t]}const Zl="1.0.0-redesign.1",eu="adhd",tu="default",nu="adhd-environment.json",Te="config.yaml",es="config.local.yaml",ou={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class yr extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function wr(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function ts(e,t){const n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i++){const s=n[i].codePointAt(0)??0,a=r[i].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function vr(e){return new TextEncoder().encode(e).length}function ru(e){const t=Object.keys(e).sort(ts);let n="";for(const o of t){const i=e[o];if(wr(o))throw new yr("key",o);if(wr(i))throw new yr("value",i);n+=`${vr(o)}:${o}=${vr(i)}:${i}
38
+ `}return`sha256-${ns(n)}`}function iu(e){const n=[...e].sort((r,o)=>ts(r.name,o.name)).map(r=>`${r.name}:${r.kind}:${r.scope}`).join(`
39
+ `);return`sha256-${ns(n)}`}function su(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function au(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function cu(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],i=r.split(".");let s=t;i.forEach((a,c)=>{if(c===i.length-1){s.properties[a]=du(o);return}const l=s.properties[a];if(l===void 0){const u={type:"object",properties:{}};s.properties[a]=u,s=u}else s=l})}return t}function du(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const lu="adhd-env-ref:";function uu(e){return`${lu}${e}`}const fu=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],pu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function te(e,t){return(e>>>t|e<<32-t)>>>0}function mu(e){const t=Uint32Array.from(pu),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const i=Math.floor(n/4294967296),s=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,i,!1),a.setUint32(r-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(u+b*4,!1);for(let b=16;b<64;b++){const S=c[b-15],E=c[b-2],A=te(S,7)^te(S,18)^S>>>3,j=te(E,17)^te(E,19)^E>>>10;c[b]=c[b-16]+A+c[b-7]+j>>>0}let f=t[0],g=t[1],p=t[2],m=t[3],v=t[4],h=t[5],y=t[6],w=t[7];for(let b=0;b<64;b++){const S=te(v,6)^te(v,11)^te(v,25),E=v&h^~v&y,A=w+S+E+fu[b]+c[b]>>>0,j=te(f,2)^te(f,13)^te(f,22),N=f&g^f&p^g&p,_=j+N>>>0;w=y,y=h,h=v,v=m+A>>>0,m=p,p=g,g=f,f=A+_>>>0}t[0]=t[0]+f>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+p>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+v>>>0,t[5]=t[5]+h>>>0,t[6]=t[6]+y>>>0,t[7]=t[7]+w>>>0}const d=new Uint8Array(32),l=new DataView(d.buffer);for(let u=0;u<8;u++)l.setUint32(u*4,t[u],!1);return d}function gu(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function ns(e){const t=new TextEncoder().encode(e);return gu(mu(t))}const{parse:hu}=Ta;function os(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const i=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,os(o,i)):n[i]=o}return n}function gt(e){if(O.existsSync(e))try{const t=O.readFileSync(e,"utf8"),n=hu(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:os(n)}catch{return}}function yu(e){return{system:gt(k.join(e.system,Te)),global:gt(k.join(e.global,Te)),project:e.project?gt(k.join(e.project,Te)):void 0,local:e.project?gt(k.join(e.project,es)):void 0}}function br(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function $n(e,t){if(e===void 0)return e;switch(t){case"integer":{if(typeof e=="number")return e;const n=parseInt(String(e),10);return Number.isNaN(n)?e:n}case"number":{if(typeof e=="number")return e;const n=parseFloat(String(e));return Number.isNaN(n)?e:n}case"boolean":{if(typeof e=="boolean")return e;const n=String(e).toLowerCase();return n==="true"?!0:n==="false"?!1:e}case"array":return Array.isArray(e)?e:typeof e=="string"?e.length===0?[]:e.split(",").map(n=>n.trim()):e;case"string":return typeof e=="string"?e:String(e);default:return e}}function rs(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((i,s)=>{if(s===r.length-1){o[i]=e[n];return}const a=o[i];(typeof a!="object"||a===null||Array.isArray(a))&&(o[i]={}),o=o[i]})}return t}const wu=[["system","system"],["global","global"],["project","project"],["local","local"]];function vu(e,t,n,r){const o={},i={},s={},a={};for(const c of Object.keys(e)){const d=e[c],l=d.env&&d.env!==""?d.env:au(r.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??r.activeScope;let g=d.default,p="default";for(const[w,b]of wu){const S=t[w];S&&Object.prototype.hasOwnProperty.call(S,c)&&(g=$n(S[c],d.type),p=b)}const m=n[l];let v,h,y;m!==void 0?(v=$n(m,d.type),h="env",y=l):(v=g,h=p),o[c]=u?uu(l):v,i[c]=v,s[c]=br(u?{source:"env",scope:f,env:l}:{source:h,scope:f,env:y}),a[c]={...d,env:l,live:u,fallbackValue:g}}return{raw:o,nested:rs(o),typedRaw:i,provenance:s,fields:a}}function bu(e,t){return e.replace(/\$\{HOME\}/g,W.homedir()).replace(/\$HOME\b/g,W.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Su(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=o.scope??t.activeScope,s=o.share??ou[o.kind],a=o.path?bu(o.path,t):k.join(Zi(t.roots,i),r),c=s==="per-instance"?k.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:i,share:s}}return n}function Eu(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=t[o.in];if(!i)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:k.join(i.path,o.name),share:o.share??"shared"}}return n}class is extends Error{constructor(t){super(t.length>0?`Config validation failed: ${t.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=t,this.name="ValidationError"}}function ku(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const i=new Zr({allErrors:!0,strict:!1}).compile(n);if(!i(e))throw new is(Au(i.errors??[]))}function Au(e){return e.map(t=>({field:ju(t),message:t.message??"is invalid",keyword:t.keyword}))}function ju(e){var r;const t=(e.instancePath??"").replace(/^\//,"").replace(/\//g,".");return t||(((r=e.params)==null?void 0:r.missingProperty)??"(root)")}function _u(e,t){return k.join(Zi(e,t),nu)}const Nu=384,Ou=448;function Ru(e,t,n={}){const r=n.mode??Nu,o=n.dirMode??Ou,i=k.dirname(e);O.mkdirSync(i,{recursive:!0,mode:o}),O.chmodSync(i,o);const s=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{O.writeFileSync(s,a,{encoding:"utf8",mode:r}),O.chmodSync(s,r),O.renameSync(s,e),O.chmodSync(e,r)}catch(c){try{O.existsSync(s)&&O.unlinkSync(s)}catch{}throw c}}const Iu="0.1.0";function Sr(e,t){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(e)}`)}function Tu(){return`${process.pid}-${ue.randomBytes(3).toString("hex")}`}function uo(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Sr(e,"project");const r=t.orgNamespace??eu,o=t.envPrefixOverride??su(e),i=t.namespaces&&t.namespaces.length>0?t.namespaces:[tu],s=n.namespace??i[0];if(!i.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${e}" (declared: ${i.join(", ")})`);Sr(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=Yl({scope:n.scope,cwd:n.cwd},a),l=Ql({project:e,namespace:s,orgNamespace:r,projectRoot:d,adhdRoot:n.adhdRoot});return{project:e,namespace:s,orgNamespace:r,envPrefix:o,scope:c,projectRoot:d,roots:l}}function $u(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:i,scope:s,projectRoot:a,roots:c}=uo(e,t,n),d=n.processEnv??process.env,l=yu(c),u=n.instanceId??Tu(),{raw:f,nested:g,typedRaw:p,provenance:m,fields:v}=vu(t.config,l,d,{prefix:i,activeScope:s}),h={};for(const E of Object.keys(v)){const A=v[E];A.live&&(h[E]={env:A.env,type:A.type,fallback:A.secret===!0?void 0:A.fallbackValue})}const y=cu(t.config);ku(rs(p),y);const w=Su(t.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:r}),b=Eu(t.files,w);return{version:Zl,libraryVersion:Iu,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:i,scope:s,instanceId:u,config:g,raw:f,liveFields:h,fieldSchema:y,configHash:ru(Object.fromEntries(Object.entries(p).map(([E,A])=>[E,String(A)]))),structureHash:iu(Object.values(w).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(w),files:Object.values(b),provenance:m}}class Xe extends Error{constructor(t){super(t),this.name="EnvironmentError"}}class Cu extends Xe{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class Pu extends Xe{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function xu(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function Cn(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Cn(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Cn(r);return t}function Lu(e,t){const n=Cn(e);for(const r of Object.keys(t)){const o=t[r],i=r.split(".");let s=n;for(let c=0;c<i.length-1;c++){const d=i[c],l=s[d];(typeof l!="object"||l===null||Array.isArray(l))&&(s[d]={}),s=s[d]}const a=i[i.length-1];Object.defineProperty(s,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?$n(c,o.type):o.fallback}})}return n}function Uu(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Xe(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class Kt{constructor(t,n,r={}){let o,i;try{o=$u(t,n,r);const s=uo(t,n,r);i=_u(s.roots,o.scope)}catch(s){throw s instanceof is||s instanceof Xe?s:new Xe(s instanceof Error?s.message:String(s))}return Er(this,o,i)}static fromSnapshot(t){if(!O.existsSync(t))throw new Cu(t);const n=JSON.parse(O.readFileSync(t,"utf8")),r=Object.create(Kt.prototype);return Er(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return xu(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){Uu(t);const n=this.paths.run??this._runDirFallback();O.mkdirSync(n,{recursive:!0});const r=k.join(n,`${t}.lock`);let o;try{o=O.openSync(r,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new Pu(t,r):s}O.writeSync(o,`${process.pid}
163
40
  ${this.instanceId}
164
- `),C.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{C.unlinkSync(r)}catch{}}}}_runDirFallback(){return T.join(T.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))C.mkdirSync(t,{recursive:!0})}write(){return FS(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function bu(e,t,n){const r={};for(const i of t.dirs)r[i.name]=i.path;const o={};for(const i of t.files)o[i.name]=i.path;const s=zS(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const $a={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"SQLite backlog-graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"SQLite `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"migration.phase":{type:"string",env:"ADHD_BACKLOG_MIGRATION_PHASE",default:"not-started",enum:["not-started","phase-1","phase-2","phase-3","phase-4","phase-5","complete"],description:"MIGRATION.md §4.4 — a queried signal (never hardcoded prose) for whether BACKLOG.md or the tool is authoritative right now. Read via `migrationStatus(ctx)`/`backlog migration-status`. NOT yet per-repo-keyed (MIGRATION.md §9 open decision 6) — one global value."}}};function rp(e){if(e)return e;const t=process.env.ADHD_BACKLOG_SCOPE;if(t)return t;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function va(e={}){const t={namespace:"production",scope:rp(e.scope)};return e.adhdRoot!==void 0&&(t.adhdRoot=e.adhdRoot),e.cwd!==void 0&&(t.cwd=e.cwd),e.instanceId!==void 0&&(t.instanceId=e.instanceId),new zr("backlog",$a,t)}function wa(e){return e.config.db.path??e.files.db}function YS(e,t){return`${e}:${t}`}function QS(e={}){const t=process.env.APIGEN_IR_CACHE_FILE;if(t)return t;const n={namespace:"production",scope:"global"};e.adhdRoot!==void 0&&(n.adhdRoot=e.adhdRoot),e.instanceId!==void 0&&(n.instanceId=e.instanceId);const r=new zr("backlog",$a,n);return T.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}const op=Symbol.for("adhd.apigen.extraction-session");function sp(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}sp(r,t)}}}function ip(e){try{const t=C.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const $r=new Map,Eu=new Map;function ZS(e,t,n){const r=t??"",o=$r.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[f])=>l.localeCompare(f));for(const[l,f]of u)l!==e&&c.push(`${l}:${f}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=Eu.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Eu.set(i,a)),a.schemas}function XS(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[op]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(r){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=r??"",s=r?this.statVersion(r):"";let i=$r.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new kn.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new kn.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},$r.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=$r.get(o??""),a=this.statVersion(r);let c=s.getSourceFile(r);if(c===void 0?c=s.addSourceFileAtPath(r):i&&i.fileVersions.get(r)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(r,a),i){const u=new Set([r]);sp(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=t.get(r);return o===void 0&&(o=ip(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function eN(e){const t=e;if(t[op]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Ar="x-apigen-logical";function Su(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const s=o.$ref;if(typeof s=="string"){if(t){const f=t[s];if(!f){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}r.push(f)}continue}const i=o.oneOf;if(Array.isArray(i))for(const f of i)typeof f=="object"&&f!==null&&r.push(f);const a=o.properties;if(a)for(const f of Object.values(a))r.push(f);const c=o.items;if(Array.isArray(c))for(const f of c)typeof f=="object"&&f!==null&&r.push(f);else typeof c=="object"&&c!==null&&r.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}const Nu=new Set(["string","number","boolean","integer"]);function tN(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Nu.has(n):Array.isArray(n)?n.every(r=>Nu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function nN(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(tN)}function rN(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const s=r[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{Su(o.input,t),Su(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function oN(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function sN(e,t,n){rN(e);const r={};for(const[o,s]of Object.entries(e.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],f={};for(const y of t)if(y.envelope&&i[y.id]!==!1)for(const[$,v]of Object.entries(y.envelope))u[$]=v,f[$]=y.id,l.includes($)||l.push($);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||nN(s.input),d=s.input.definitions,m=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:oN(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...m?{$defs:m}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const iN=8;function aN(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let cN=0;async function uN(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${cN++}`;let s;try{s=t.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function ap(e,t,n){if(n>iN)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.getUnionTypes();if(r.every(i=>i.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(i=>i.getLiteralValue())};if(r.every(i=>i.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(i=>i.getLiteralValue())};const o=await Promise.all(r.map(i=>ap(i,t,n+1))),s=ba(o);return{oneOf:o,...s?{discriminator:s}:{},[Ar]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),s=r??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),f=u.getDeclarations()[0];let p;if(f)try{p=u.getTypeAtLocation(f)}catch{p=void 0}if(p!==void 0&&p.getCallSignatures().length>0)continue;const h=p!==void 0?aN(p,f):void 0;a[l]=h!==void 0?await t(h):{},u.isOptional()||c.push(l)}return Object.keys(a).length>0?{type:"object",properties:a,...c.length>0?{required:c}:{}}:{}}return{}}function ba(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of t){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}function vr(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=_s[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=_s[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:vr(r.slice(0,-2),t+1,n)};if(r.includes("|")){const s=r.split("|").map(c=>c.trim());if(s.every(c=>c.startsWith("'")))return{type:"string",enum:s.map(c=>c.replace(/'/g,""))};const i=s.map(c=>vr(c,t+1,n)),a=ba(i);return{oneOf:i,...a?{discriminator:a}:{},[Ar]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(l=>l.trim());c&&u&&(i[c.replace("?","")]=vr(u,t+1,n))}return{type:"object",properties:i}}return{}}function cp(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function lN(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function fN(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function dN(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const n=t.slice(1,-1).trim();if(n.length!==0)return cp(n)}async function pN(e,t){const n=e.trim(),r=lN(n);if(r!==void 0){const i=cp(r);if(i.length===2){const[a,c]=await Promise.all([t(i[0]),t(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=fN(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=dN(n);if(s!==void 0){const i=await Promise.all(s.map(a=>t(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const up={"decimal.js":"Decimal"},_s={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},Ou={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function ku(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=up[o];if(!s)continue;const i=r.getDefaultImport();if(i){const a=i.getText();a!==s&&n.set(a,s)}for(const a of r.getNamedImports()){const c=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function hN(e,t){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==t)return!1;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(Ou,a)},createType(r){var o,s,i;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return new bt.AnnotatedType(new bt.StringType,{format:Ou[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new bt.AnnotatedType(new bt.StringType,{format:"int64"},!1)}})}}let dn;function mN(){if(dn)return dn;try{const e=T.dirname(require.resolve("ts-json-schema-generator/package.json"));dn=require(require.resolve("typescript",{paths:[e]}))}catch{dn=require("typescript")}return dn}const nt=new Map;function gN(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function yN(e){const t=nt.get(e);return t&&(nt.delete(e),nt.set(e,t)),t}function $N(e,t){const n=gN();if(n!==0)for(nt.delete(e),nt.set(e,t);nt.size>n;){const r=nt.keys().next().value;nt.delete(r)}}function vN(e,t){return`${e}\0${t??""}`}const wN=new Set(["zod",/^zod\/./]);function bN(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of wN)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function EN(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(n)){if(o.has(s)||typeof i!="object"||i===null)continue;const a=i,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const u of o)if(c.includes(u)){o.add(s);break}}}for(const s of o)delete n[s]}As(e)}function As(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&As(o,n);else As(r,n)}}function SN(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const n=js(e,t);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function js(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.has(s[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&n.push(...js(s,t));else n.push(...js(o,t));return n}function NN(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=ba(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Ar]:o[Ar]??"union"}}function ON(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=vN(s,o.tsconfig);let a;a=n?n.statVersion(s):ip(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??yN(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=mN(),p=hN(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=bt.createParser(h,o,p),m=bt.createFormatter(o);if(c=new bt.SchemaGenerator(h,d,m,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const y={version:a,gen:c};$N(i,y),n==null||n.generatorCache.set(i,y)}}const u=c.createSchema(o.type);return EN(u),SN(u),u}function kN(e,t){let n=e.trim();if(n=fp(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function lp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const _N=Object.entries(up).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${lp(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function fp(e){let t=e;for(const{pattern:n,key:r}of _N)t=t.replace(n,r);return t}function AN(e,t){let n=fp(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${lp(r)}\\b`,"g"),o);return n}async function Cn(e,t,n,r,o,s){const i=t.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const d=new Set(c);return d.add(a),_u(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=ZS(i,r,o.statVersion(i)),f=l.get(n);if(f!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(f)),f;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=_u(e,t,n,r,o,p).then(d=>(l.set(n,d),d)).catch(d=>{throw o.schemaCache.delete(a),d});return o.schemaCache.set(a,h),h}async function _u(e,t,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??ku(t),p||o.aliasCache.set(t,i)}else i=ku(t);const a=kN(n,i),c=_s[a];if(c!==void 0)return c;const u=await pN(a,p=>Cn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??bN(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=ON(p,!0,o);return NN(h)}catch{}try{const p=await uN(e,t,a,h=>ap(h,d=>Cn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=AN(a,i);return vr(f,0,i)}function Ea(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return jN(n,t)}function jN(e,t){var n;const r=e,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${s}\\s*=\\s*([^\\]]+)\\]`);for(const a of o)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const u=c.getText().match(i);if(u)return u[1].trim()}}function IN(e){const t=e.trim(),n=t.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(t!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(t))return Number(t);try{return JSON.parse(t)}catch{return t}}}function xN(e,t){const n=IN(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}function Wr(e){try{if(!e||e.getKind()!==kn.SyntaxKind.TypeReference)return;const t=e;if(t.getTypeArguments().length>0)return;const n=t.getTypeName();if(n.getKind()!==kn.SyntaxKind.Identifier)return;const r=n.getSymbol();if(!r)return;const o=r.getDeclarations().find(c=>c.getKindName()==="TypeAliasDeclaration");if(!o)return;const s=o,i=s.getType();if(!(i.isString()||i.isNumber()||i.isBoolean()))return;const a=s.getJsDocs();for(const c of a)for(const u of c.getTags())if(u.getTagName()==="format"){const l=u.getCommentText();if(l!==void 0)return l.trim()}return}catch{return}}async function PN(e){const t=e.session===void 0,n=eN(e.session??XS());try{return await TN(e,n)}finally{t&&n.dispose()}}async function TN(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=e,i=t.projectFor(s),a=t.sourceFileFor(n,s),c=T.basename(n),u=Ge(DN(c)),l=o?null:u,f=Ge(r),p=[];for(const[m,y]of a.getExportedDeclarations()){if(m==="default"||sr(m))continue;const $=UN(y);if($){const N=$.getSignature(),j=ju(N,$),R=N.getReturnType().getText(),J=pt(N);p.push(await or(i,a,f,l,m,j,R,$.isAsync(),s,t,J));continue}const v=y.find(N=>N.getKindName()==="VariableDeclaration");if(!v)continue;const E=v.getInitializer(),b=E==null?void 0:E.getKindName();if(E&&["ArrowFunction","FunctionExpression"].includes(b??"")){const N=v.getType().getCallSignatures();if(N.length===0)continue;const j=N[0],R=Iu(j,v,v.getVariableStatement()),J=j.getReturnType().getText(),U=pt(j),q=E.isAsync();p.push(await or(i,a,f,l,m,R,J,q,s,t,U))}else if(b==="ObjectLiteralExpression"){const N=v.getType();for(const j of N.getProperties()){const R=j.getName();if(sr(R))continue;const J=j.getTypeAtLocation(v).getCallSignatures();if(J.length===0)continue;const U=J[0],q=Iu(U,v,v.getVariableStatement()),Q=U.getReturnType().getText(),Z=pt(U),ye=[...l?[l]:[],Ge(m),Ge(R)];p.push(await wr(i,a,f,ye,R,q,Q,!1,s,t,Z))}}else{const N=v.getType(),j=N.getText();if(yt(N,v)){const R=await Cn(i,a,j,s,t);p.push(RN(f,l,m,R))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const h=a.getDefaultExportSymbol();if(h){const m=a.getExportAssignment(y=>!y.isExportEquals());if(m){const y=m.getExpression(),$=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=y.getType().getCallSignatures();if(v.length>0){const E=v[0],b=To(E,m),N=E.getReturnType().getText(),j=pt(E),R=y.isAsync();p.push(await or(i,a,f,l,"default",b,N,R,s,t,j))}}else{const v=y.getType();for(const E of v.getProperties()){const b=E.getName();if(sr(b))continue;const N=E.getTypeAtLocation(m).getCallSignatures();if(N.length===0)continue;const j=N[0],R=To(j,m),J=j.getReturnType().getText(),U=pt(j),q=[...l?[l]:[],Ge("default"),Ge(b)];p.push(await wr(i,a,f,q,b,R,J,!1,s,t,U))}}}else{const y=h.getDeclarations();for(const $ of y){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,E=v.getName(),b=E&&E.length>0?E:"default",N=v.getSignature(),j=ju(N,v),R=N.getReturnType().getText(),J=pt(N);p.push(await or(i,a,f,l,b,j,R,v.isAsync(),s,t,J))}}}const d=LN(a);if(d.length>0)for(const{name:m,sig:y}of d){if(sr(m))continue;const $=To(y),v=y.getReturnType().getText(),E=pt(y),b=[...l?[l]:[],Ge(m)];p.push(await wr(i,a,f,b,m,$,v,!1,s,t,E))}return p}function CN(e,t,n,r){const o=new Set,s=i=>{if(Array.isArray(i))return i.map(s);if(!i||typeof i!="object"||o.has(i))return i;o.add(i);try{const a=i,c={};for(const[u,l]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const f=u,p=t[f];for(const[h,d]of Object.entries(l)){const m=s(d),y=p[h];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(m))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${f}.${h}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);p[h]=m}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}function Au(e,t){if(!t||e.format!==void 0||"$ref"in e||"properties"in e||"items"in e)return;const n=e.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(e.format=t)}function pt(e){var t;try{return Wr((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function or(e,t,n,r,o,s,i,a,c,u,l){const f=Ge(o);return wr(e,t,n,r?[r,f]:[f],o,s,i,a,c,u,l)}async function wr(e,t,n,r,o,s,i,a,c,u,l){const f=s.length>0&&s[0].name==="ctx",p=s.filter(b=>b.name!=="ctx"),h=p.filter(b=>!b.optional).map(b=>b.name),d={},m={definitions:{},$defs:{}};for(const b of p){const N=await Cn(e,t,b.type,c,u),j=CN(N,m,o,b.name);b.defaultValue!==void 0&&xN(j,b.defaultValue),Au(j,b.format),d[b.name]=j}const y=i.replace(/^Promise<(.+)>$/,"$1").trim(),$=await Cn(e,t,y,c,u),v=l?{...$}:$;Au(v,l);const E={type:"object",properties:d,required:h,...Object.keys(m.definitions).length>0?{definitions:m.definitions}:{},...Object.keys(m.$defs).length>0?{$defs:m.$defs}:{}};return{id:dp(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:E,output:v,envelope:{},typeText:{lang:"ts",input:BN(s),output:y},...f?{hasCtx:!0}:{}}}function RN(e,t,n,r){const o=Ge(n),s=t?[t,o]:[o];return{id:dp(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function dp(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function MN(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function Ge(e){return{raw:e,words:MN(e)}}function DN(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function LN(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&t.push({name:a.getName(),sig:c[0]})}}return t}function UN(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function ju(e,t){return e.getParameters().map(n=>{var r;const o=n.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((r=s==null?void 0:s.hasQuestionToken)==null?void 0:r.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:Ea(s,n.getName(),t),format:Wr(s==null?void 0:s.getTypeNode())}})}function Iu(e,t,n){return e.getParameters().map(r=>{var o;const s=r.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:a,defaultValue:Ea(i,r.getName(),n??t),format:Wr(i==null?void 0:i.getTypeNode())}})}function To(e,t){return e.getParameters().map(n=>{var r,o,s;const i=n.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=n.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((r=a==null?void 0:a.hasQuestionToken)==null?void 0:r.call(a))??!1);return{name:n.getName(),type:a?a.getType().getText():((s=(o=n.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:Ea(a,n.getName(),t),format:Wr(a==null?void 0:a.getTypeNode())}})}function BN(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function sr(e){return!!(e==="__samples__"||e.startsWith("__"))}function yt(e,t,n=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const r=e.getArrayElementType();return r?yt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>yt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>yt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>yt(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||yt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return yt(c,t,n)})}return!1}function FN(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const s=e[o],i=r;r=()=>s(n,i)}return r()}}function qN(e,t){return FN(e,t)}function VN(e,t,n={}){const r=e.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return qN(r,t)}function pp(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}pp(r,t)}}}let Co;function KN(){return Co||(Co=new kn.Project({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})),Co}function hp(e){const t=KN(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return pp(r,o),[...o].sort()}const GN={"decimal.js":"Decimal"};function JN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(GN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${JN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));async function HN(e,t){await Et.mkdir(T.dirname(e),{recursive:!0});const n=`${e}.${process.pid}.${Un.randomUUID()}.tmp`;try{await Et.writeFile(n,JSON.stringify(t),"utf8"),await Et.rename(n,e)}catch(r){throw await Et.unlink(n).catch(()=>{}),r}}function zN(e){return{async get(){try{const t=await Et.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await HN(e,n)}}}const Is=1;function WN(e){return Un.createHash("sha256").update(e).digest("hex")}async function xu(e){return WN(await Et.readFile(e,"utf8"))}async function jr(e){try{return(await Et.stat(e)).mtimeMs}catch{return}}async function Pu(e,t){const n=await xu(e.source),r=Un.createHash("sha256");r.update(`formatVersion:${Is}
165
- `),r.update(`extractorVersion:${t}
166
- `),r.update(`host:${e.host}
167
- `),r.update(`namespace:${e.namespace??""}
168
- `),r.update(`source:${n}
169
- `);for(const o of hp(e.source))o!==e.source&&r.update(`dep:${o}:${await xu(o)}
170
- `);return r.digest("hex")}async function Tu(e,t){const n=await jr(e.source)??0,r=[];for(const o of hp(e.source)){if(o===e.source)continue;const s=await jr(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function YN(e,t){if(t.source.path!==e.source)return!1;const n=await jr(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await jr(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function QN(e){if(e.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const t=zN(e.cache),n=e.extractorVersion;async function r(o,s,i){const a=i??await Pu(o,n),c=await Tu(o,a);await t.put(e.cache,{formatVersion:Is,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await t.get(e.cache);if(!i||i.formatVersion!==Is||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await YN(o,i.staleness))return i.operations;const a=await Pu(o,n);if(a===i.staleness.contentKey)return Tu(o,a).then(u=>t.put(e.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}Pl.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href);const ZN={"decimal.js":"Decimal"};function XN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ZN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${XN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const eO=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],tO={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let nO=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};function Sa(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&eO.includes(e.code)&&typeof e.toJSON=="function"}const xs="$apigen";let Cu=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function rO(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Cu(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Cu("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Na="x-apigen-logical",Oa="x-apigen-codec",Ps="x-apigen-ctor",Ts="x-apigen-tojson",oO="0.1.0";function Ru(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function qt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return qt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=mp(e,s,t);return qt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Ro(e,t,n);const a=t.items;if(!a)return e.map(u=>kt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?kt(u):qt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>qt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Ro(e,t,n);const a=t.properties;if(!a)return kt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=qt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Ro(e,t,n):kt(e)}function Vt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Vt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=mp(e,s,t);return Vt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Vt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Vt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Vt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?sO(e,n):e}function mp(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Ro(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[xs]:r,v:s}}catch{}}return kt(e)}function sO(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&xs in e){const n=e,r=n[xs],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function kt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(kt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=kt(r));return t}return null}function iO(e){return{encode(t,n,r){const o=Ru(e,r);return qt(t,n,o)},decode(t,n,r){const o=Ru(e,r);return Vt(t,n,o)}}}const ka={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},_a={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Aa={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},ja={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},aO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ia={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!aO.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Cs="NaN",Rs="Infinity",Ms="-Infinity",cO=new Set([Cs,Rs,Ms]),xa={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Cs:e===1/0?Rs:e===-1/0?Ms:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Cs)return NaN;if(e===Rs)return 1/0;if(e===Ms)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...cO].join(", ")}.`);return NaN}},uO=[ka,_a,Aa,ja,Ia,xa];function lO(e,t={}){for(const n of uO)e.register(n,{override:t.override??!1})}const fO=12;function dO(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Mu(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function pO(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function hO(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Du(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Rn(a,t,n+1):`<${i}>`}return s}function mO(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Rn(r,t,n+1)]:[]}function Rn(e,t=e??{},n=0){if(!e||n>fO)return null;if(typeof e.$ref=="string"){const o=dO(e.$ref,t);return o!==void 0?Rn(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Du({...e,properties:o,required:s},t,n)}const r=Mu(e.oneOf)??Mu(e.anyOf);if(r)return Rn(r,t,n+1);switch(pO(e)){case"object":return Du(e,t,n);case"array":return mO(e,t,n);case"string":return hO(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function gO(e){if(!e)return;const t=Rn(e);return`Example: ${JSON.stringify(t)}`}ka.id,_a.id,Aa.id,ja.id,Ia.id,xa.id;const gp=rO();lO(gp);const yp=iO(gp.freeze());function yO(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function $O(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function vO(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function wO(e,t){return t===void 0||e===void 0?e:yp.decode(e,t)}function Mo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:yp.encode(e,n)}async function bO(e,t,n,r,o,s){const i=$O(n).map(c=>wO(s[c],vO(n,c)));if(yO(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Mo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Mo(u,n)}const a=await e[r](...i);return Mo(a,n)}let $p=class{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}};function EO(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>bO(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const SO={"decimal.js":"Decimal"};function NO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(SO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${NO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function OO(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function vp(e){return e?e.type==="array"?`${vp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function wp(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:vp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function kO(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function _O(e,t){var n,r;const o=((r=(n=((t==null?void 0:t.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=kO(a==null?void 0:a.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(s[i]=l)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let AO=class extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}};const Yr=new Pr({allErrors:!0});Tr(Yr);for(const e of[Na,Oa,Ps,Ts,"discriminator"])Yr.addKeyword({keyword:e,valid:!0});Yr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function jO(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function IO(e,t){const n=gO(t),r=[`Validation failed: ${jO(e)}`];return n&&r.push(n),r.join(" — ")}function xO(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Yr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new AO("invalid_argument",IO(a,o.input),a)}return n()}}function PO(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ht extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Do(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function bp(e,t){const n=e[Oa];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function TO(e,t,n){const r=bp(t,n);return r?r.encode(e,t,n):e}function CO(e,t,n){const r=bp(t,n);return r?r.decode(e,t,n):e}function RO(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Na]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Do(r)!==void 0},encode(r,o,s){const i=Do(o);if(!i)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return TO(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ht("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Do(o);if(!a)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return CO(r,h,{...s,path:`${s.path}[${f}]`})}}}const MO="x-apigen-instances";let ir=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Lu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function DO(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Uu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function LO(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function UO(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Na]==="nominal"?!0:o[Oa]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new ir("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Lu(s),c=typeof s[Ts]=="string"?s[Ts]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Uu($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Uu(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ir("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of DO(s))if(!(l in a))throw new ir("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[MO]===!1)throw new ir("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Lu(s),u={};for(const[l,f]of Object.entries(a))u[l]=LO(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ps]=="string"?s[Ps]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const BO=[ka,_a,Aa,ja,Ia,xa],FO={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Bu=UO({id:"ts.NominalSentinel",schema:FO}),qO={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Fu=RO({id:"ts.UnionSentinel",schema:qO});function VO(){const e=[...BO.map(t=>[t.id,t]),[Bu.id,Bu],[Fu.id,Fu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:oO,codecs:VO()});const qu=new Set(["string","number","boolean","integer"]);function KO(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?qu.has(n):Array.isArray(n)?n.every(r=>qu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function GO(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(KO)}const JO={"decimal.js":"Decimal"};function HO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(JO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${HO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Vu(e){return e.words.join("-")}function Ku(e){return e.words.map(ZO).join("")}function Gu(e){return e.words.join("_")}function zO(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||GO(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Vu(h)).join("/"),c=o.map(h=>Gu(h)).join("_"),u=o.map(h=>Gu(h)).slice(0,-1).join("."),l=Ku(o[o.length-2]??o[0]),f=Ku(o[o.length-1]),p=o.map(h=>Vu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function WO(e,t){return`x-${e}-${t}`}function YO(e,t){return`--${e}-${t}`}function QO(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function ZO(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Pa(e){return e.anyOf??e.oneOf}function XO(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function ek(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function tk(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Pa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function nk(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function rk(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Ju(e){return typeof e.handler=="function"}function ok(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=WO(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:YO(i,s),envVar:QO(i,s)})}return o}function sk(e,t){const n=new Map,{props:r}=rk(e);for(const[o,s]of Object.entries(r)){let i="string";ek(s)?i="boolean":(XO(s)||tk(s))&&(i="json"),n.set(nk(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Hu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=zO(t,o),i=n?ok(n):[],a=n?sk(n,i):new Map,c=n?wp(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Ju(t)};if(Ju(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function ik(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function ak(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function ck(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Lo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(ck(s))}return r.push(xO(e)),EO(r)}function uk(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const lk={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function zu(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new $p};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:uk(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:lk}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const fk={"decimal.js":"Decimal"};function dk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(fk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${dk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ds(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function Wu(e){return{raw:e,words:Ds(e)}}function pk(e,t,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===e&&(s==null?void 0:s.raw)===t)return o}return{id:`${Ds(e).join("-")}/${Ds(t).join("-")}`,host:"ts",namespace:Wu(e),path:[Wu(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function hk(e){return`data: ${e}
41
+ `),O.closeSync(o);let i=!1;return()=>{if(!i){i=!0;try{O.unlinkSync(r)}catch{}}}}_runDirFallback(){return k.join(k.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))O.mkdirSync(t,{recursive:!0})}write(){return Ru(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Er(e,t,n){const r={};for(const s of t.dirs)r[s.name]=s.path;const o={};for(const s of t.files)o[s.name]=s.path;const i=Lu(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:i,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(s,a,c){return typeof a=="string"&&!(a in s)?s.get(a):Reflect.get(s,a,c)}})}const Ue={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production","test","sandbox"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"Backlog graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"The store adapter's `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"embedding.enabled":{type:"boolean",env:"ADHD_BACKLOG_EMBEDDING_ENABLED",default:!1,description:'RAG-SPEC.md §1.6 — opt IN to the semantic/RAG stack. Default FALSE: semantic inputs (filter.semantic, filter.anchor, view:"similar", sort:"relevance", fields:["_vector"]) answer RagNotConfiguredError (§5a) until this is set. Requires the optionalDependencies @adhd/sox-embedding-provider + @adhd/sox-vector-store to be installed, and a store whose adapter reports capabilities.nativeVectors (turso). Enabling it with any of those missing logs a typed reason and leaves RAG unconfigured — it never crashes startup.'},"embedding.provider":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_PROVIDER",default:"fastembed",description:"Embedding provider type, forwarded verbatim to @adhd/sox-embedding-provider's createEmbeddingProvider ('fastembed' | 'remote')."},"embedding.model":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_MODEL",default:"bge-base-en-v1.5",description:"Embedding model id (768-dim bge-base-en-v1.5 by default). RAG-SPEC.md §2.5: the dimensional contract is STRUCTURAL — changing this after items are embedded orphans existing vectors under the old model id rather than silently truncating; re-embed via admin(embedding_backfill)."}}};function fo(e){if(e)return e;const t=process.env.ADHD_BACKLOG_SCOPE;if(t)return t;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function $e(e={}){const t={namespace:e.namespace??"production",scope:fo(e.scope)};return e.adhdRoot!==void 0&&(t.adhdRoot=e.adhdRoot),e.cwd!==void 0&&(t.cwd=e.cwd),e.instanceId!==void 0&&(t.instanceId=e.instanceId),new Kt("backlog",Ue,t)}function Ge(e){return e.config.db.path??e.files.db}function Du(e,t){return`${e}:${t}`}function Mu(e={}){const t=process.env.APIGEN_IR_CACHE_FILE;if(t)return t;const n={namespace:"production",scope:"global"};e.adhdRoot!==void 0&&(n.adhdRoot=e.adhdRoot),e.instanceId!==void 0&&(n.instanceId=e.instanceId);const r=new Kt("backlog",Ue,n);return k.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function kr(e){return{raw:e,words:ze(e)}}function ss(e,t,n,r){for(const o of r??[]){const i=o.path[o.path.length-1];if(o.namespace.raw===e&&(i==null?void 0:i.raw)===t)return o}return{id:`${ze(e).join("-")}/${ze(t).join("-")}`,host:"ts",namespace:kr(e),path:[kr(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function Fu(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r={};for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r[i]=Ai(s,i)}return r}function Bu(e){const t=Id(e.options.port),n=e.options.routePrefix??"",r=e.options.projection??{},o=Od(e.packages.map(s=>s.id)),i=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const[s,a]of e.packages.entries()){const c=o[s];i.push(`import * as ${c}_ns from ${se(a.importPath)}`),i.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}i.push(""),i.push(`const schemas: Record<string, unknown> = ${Ni(JSON.stringify(Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,{schema:c,pkgId:s.id}]))),null,2))}`),i.push(""),i.push("const app = Fastify()"),i.push("");for(const[s,a]of e.packages.entries()){const c=o[s];for(const[d,l]of Object.entries(a.schemas)){const u=ss(a.id,d,l,e.operations),f=ye({op:u,schema:l,transport:"http",projection:r}),g=n+f.http.route,p=f.http.verb,m=Fu(l),v=Object.entries(m),h=se(`${a.id}:${d}`),y=se(d);if(p==="GET"){if(i.push(`app.get(${se(g)}, async (req) => {`),i.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas[${h}]['schema'] as any)`),v.length>0){const w=v.map(([b,S])=>`${se(b)}: (req.headers as Record<string, unknown>)[${se(S)}]`).join(", ");i.push(` const envelope: Record<string, unknown> = { ${w} }`)}else i.push(" const envelope: Record<string, unknown> = {}");i.push(` return dispatch(${c}_fns as any, undefined, schemas[${h}]['schema'] as any, ${y}, envelope, query as any)`),i.push("})")}else{if(i.push(`app.post(${se(g)}, async (req) => {`),i.push(" const { data = {} } = req.body as Record<string, unknown>"),v.length>0){const w=v.map(([b,S])=>`${se(b)}: (req.headers as Record<string, unknown>)[${se(S)}]`).join(", ");i.push(` const envelope: Record<string, unknown> = { ${w} }`)}else i.push(" const envelope: Record<string, unknown> = {}");i.push(` return dispatch(${c}_fns as any, undefined, schemas[${h}]['schema'] as any, ${y}, envelope, data as any)`),i.push("})")}}}return i.push(""),i.push("app.setErrorHandler((err, _req, reply) => {"),i.push(" reply.status(500).send({"),i.push(" code: 'internal',"),i.push(" message: err instanceof Error ? err.message : 'Internal error',"),i.push(" })"),i.push("})"),i.push(""),i.push("async function main(): Promise<void> {"),i.push(" try {"),i.push(` await app.listen({ port: ${t} })`),i.push(" } catch (err) {"),i.push(" app.log.error(err)"),i.push(" process.exit(1)"),i.push(" }"),i.push("}"),i.push(""),i.push("main()"),{files:[{path:"routes.ts",content:i.join(`
42
+ `)}]}}function qu(e){return`data: ${e}
171
43
 
172
- `}function mk(e){return`event: error
44
+ `}function Ku(e){return`event: error
173
45
  data: ${e}
174
46
 
175
- `}async function gk(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of e){if(r.signal.aborted)break;s||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),s=!0),o.write(hk(JSON.stringify(i)))}s||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(i){const a=Sa(i)?i:new nO("internal",i instanceof Error?i.message:String(i));if(s)o.write(mk(JSON.stringify(a.toJSON()))),o.end();else{const c=$k(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const yk={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function $k(e){return yk[e]??500}function Ep(e){return Sa(e)?tO[e.code]??500:500}function Sp(e){return Sa(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function vk(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}let wk=class{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,t),u=await n(c);await this.writeResult(a,u,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,s={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(s[a.field]=c)}let i={};if(n.isMount)i=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};i=a?_O(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:s}=t;if(PO(n)){await gk(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(Ep(n)).send(Sp(n))}};function bk(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("http")||i.push(f)}return i}async function Ek(e){var t,n;const r=e.options.port??3e3,o=e.options.host??"127.0.0.1",s=e.options.routePrefix??"",i=e.options.projection??{},a=ik(e.options),c=ak(e.options),u=e.logger??OO(),l=ym({logger:u});l.setErrorHandler((E,b,N)=>{N.status(Ep(E)).send(Sp(E))});const f=new wk(l,s,e.signal),p=[],h={},d={};for(const E of e.packages){if(!E.fns)throw new Error(`Package "${E.id}" is missing fns`);const b=E.fns,N=Object.entries(E.schemas).map(([q,Q])=>({fnName:q,fnSchema:Q,op:pk(E.id,q,Q,e.operations)})),j={},R={};for(const{fnName:q,fnSchema:Q,op:Z}of N)j[Z.id]=Q,R[Z.id]=b[q],h[Z.id]=Q,d[Z.id]=b[q];const J=Lo(j,a),U={fns:R,createClient:E.createClient,schemas:j};for(const{fnSchema:q,op:Q}of N){const Z=Hu({op:Q,schema:q,transport:"http",projection:i});f.bindSchema(Q.id,q),f.registerRoute(Z,Ve=>zu(Z,J,Ve,U));const{params:ye,text:_e}=wp(q);p.push({method:Z.http.verb,route:s+Z.http.route,text:_e,params:ye})}}const m=((t=e.packages[0])==null?void 0:t.id)??"ts",y=Lo(h,a),$={invoke:(E,b,N)=>y(E,{operation:{id:E},ctx:new $p,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},N),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=bk(a,c,m,e.operations??[],$);if(v.length>0){const E=Lo({},a),b={fns:{},schemas:{}};for(const N of v){const j=Hu({op:N,transport:"http",projection:i});f.registerRoute(j,R=>zu(j,E,R,b)),p.push({method:j.http.verb,route:`${s}/${N.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),vk(u,p),new Promise(E=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),E()})})}const Sk={id:"api-fastify",run(e){return Ek(e)}};function Yu(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Nk(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Yu(i),path:s.map(Yu),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}const Ok={"decimal.js":"Decimal"};function kk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ok).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${kk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Qu=new Set(["string","number","boolean","integer"]);function _k(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Qu.has(n):Array.isArray(n)?n.every(r=>Qu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ak(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(_k)}const jk={"decimal.js":"Decimal"};function Ik(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ik(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Zu(e){return e.words.join("-")}function Xu(e){return e.words.map(Pk).join("")}function el(e){return e.words.join("_")}function xk(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ak(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Zu(h)).join("/"),c=o.map(h=>el(h)).join("_"),u=o.map(h=>el(h)).slice(0,-1).join("."),l=Xu(o[o.length-2]??o[0]),f=Xu(o[o.length-1]),p=o.map(h=>Zu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Pk(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Tk(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=xk(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:Ck(s.output)}};if(a==="GET")l.parameters=Rk(s.input);else{const f=s.input;typeof f=="object"&&f!==null&&Object.keys(f).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:f}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Ck(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Rk(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function Mk(e,t={}){return[{...Nk("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>Tk(e.operations,{title:t.title,version:t.version})}]}const Dk={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return Mk(e,t)}}}},Ls="$apigen";class tl extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Lk(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new tl(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new tl("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Ta="x-apigen-logical",Ca="x-apigen-codec",Us="x-apigen-ctor",Bs="x-apigen-tojson",Uk="0.1.0";function nl(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Kt(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Kt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Np(e,s,t);return Kt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Uo(e,t,n);const a=t.items;if(!a)return e.map(u=>_t(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?_t(u):Kt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Kt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Uo(e,t,n);const a=t.properties;if(!a)return _t(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Kt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Uo(e,t,n):_t(e)}function Gt(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Gt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Np(e,s,t);return Gt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?u:Gt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Gt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Gt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Bk(e,n):e}function Np(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Uo(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Ls]:r,v:s}}catch{}}return _t(e)}function Bk(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ls in e){const n=e,r=n[Ls],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function _t(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(_t);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=_t(r));return t}return null}function Fk(e){return{encode(t,n,r){const o=nl(e,r);return Kt(t,n,o)},decode(t,n,r){const o=nl(e,r);return Gt(t,n,o)}}}const Ra={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Ma={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},Da={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},La={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},qk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ua={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!qk.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Fs="NaN",qs="Infinity",Vs="-Infinity",Vk=new Set([Fs,qs,Vs]),Ba={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Fs:e===1/0?qs:e===-1/0?Vs:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Fs)return NaN;if(e===qs)return 1/0;if(e===Vs)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Vk].join(", ")}.`);return NaN}},Kk=[Ra,Ma,Da,La,Ua,Ba];function Gk(e,t={}){for(const n of Kk)e.register(n,{override:t.override??!1})}const Jk=12;function Hk(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function rl(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function zk(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Wk(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function ol(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Mn(a,t,n+1):`<${i}>`}return s}function Yk(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Mn(r,t,n+1)]:[]}function Mn(e,t=e??{},n=0){if(!e||n>Jk)return null;if(typeof e.$ref=="string"){const o=Hk(e.$ref,t);return o!==void 0?Mn(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return ol({...e,properties:o,required:s},t,n)}const r=rl(e.oneOf)??rl(e.anyOf);if(r)return Mn(r,t,n+1);switch(zk(e)){case"object":return ol(e,t,n);case"array":return Yk(e,t,n);case"string":return Wk(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Op(e){if(!e)return;const t=Mn(e);return`Example: ${JSON.stringify(t)}`}Ra.id,Ma.id,Da.id,La.id,Ua.id,Ba.id;const kp=Lk();Gk(kp);const _p=Fk(kp.freeze());function Qk(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Zk(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Xk(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function e_(e,t){return t===void 0||e===void 0?e:_p.decode(e,t)}function Bo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:_p.encode(e,n)}async function t_(e,t,n,r,o,s){const i=Zk(n).map(c=>e_(s[c],Xk(n,c)));if(Qk(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Bo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Bo(u,n)}const a=await e[r](...i);return Bo(a,n)}let Ap=class{constructor(){this._map=new Map}set(e,t){this._map.set(e,t)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function n_(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>t_(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const r_={"decimal.js":"Decimal"};function o_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(r_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${o_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function s_(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},je(s);const i=n?je.destination({dest:e.destination,mkdir:!0,sync:!0}):je.destination(2);return je(s,i)}function jp(e){return e?e.type==="array"?`${jp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function i_(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:jp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const a_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class Ip extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function c_(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&a_.includes(e.code)&&typeof e.toJSON=="function"}function sl(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Qr=new Pr({allErrors:!0});Tr(Qr);for(const e of[Ta,Ca,Us,Bs,"discriminator"])Qr.addKeyword({keyword:e,valid:!0});Qr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function u_(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function l_(e,t){const n=Op(t),r=[`Validation failed: ${u_(e)}`];return n&&r.push(n),r.join(" — ")}function f_(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Qr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Ip("invalid_argument",l_(a,o.input),a)}return n()}}async function d_(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=c_(n)?n:new Ip("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:sl("before-first-chunk",r)}:{ok:!1,carrier:sl("after-first-chunk",r,t.length)}}}function p_(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class mt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Fo(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function xp(e,t){const n=e[Ca];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function h_(e,t,n){const r=xp(t,n);return r?r.encode(e,t,n):e}function m_(e,t,n){const r=xp(t,n);return r?r.decode(e,t,n):e}function g_(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ta]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Fo(r)!==void 0},encode(r,o,s){const i=Fo(o);if(!i)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return h_(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new mt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Fo(o);if(!a)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new mt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new mt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return m_(r,h,{...s,path:`${s.path}[${f}]`})}}}const y_="x-apigen-instances";class ar extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function il(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function $_(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function al(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function v_(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function w_(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ta]==="nominal"?!0:o[Ca]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new ar("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=il(s),c=typeof s[Bs]=="string"?s[Bs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=al($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=al(m,a[d],{...i,path:`${i.path}/${d}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ar("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of $_(s))if(!(l in a))throw new ar("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[y_]===!1)throw new ar("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=il(s),u={};for(const[l,f]of Object.entries(a))u[l]=v_(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Us]=="string"?s[Us]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const b_=[Ra,Ma,Da,La,Ua,Ba],E_={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},cl=w_({id:"ts.NominalSentinel",schema:E_}),S_={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ul=g_({id:"ts.UnionSentinel",schema:S_});function N_(){const e=[...b_.map(t=>[t.id,t]),[cl.id,cl],[ul.id,ul]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Uk,codecs:N_()});function ll(e,t,n){var r;const o=typeof((r=t==null?void 0:t.input)==null?void 0:r.description)=="string"?t.input.description:void 0,s=Op(t==null?void 0:t.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function Pp(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function O_(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const fl=new Set(["string","number","boolean","integer"]);function k_(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?fl.has(n):Array.isArray(n)?n.every(r=>fl.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function __(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(k_)}const A_={"decimal.js":"Decimal"};function j_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(A_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${j_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function dl(e){return e.words.join("-")}function pl(e){return e.words.map(C_).join("")}function hl(e){return e.words.join("_")}function I_(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||__(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>dl(h)).join("/"),c=o.map(h=>hl(h)).join("_"),u=o.map(h=>hl(h)).slice(0,-1).join("."),l=pl(o[o.length-2]??o[0]),f=pl(o[o.length-1]),p=o.map(h=>dl(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function x_(e,t){return`x-${e}-${t}`}function P_(e,t){return`--${e}-${t}`}function T_(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function C_(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Fa(e){return e.anyOf??e.oneOf}function R_(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function M_(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function D_(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Fa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function L_(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function U_(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function ml(e){return typeof e.handler=="function"}function B_(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=x_(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:P_(i,s),envVar:T_(i,s)})}return o}function F_(e,t){const n=new Map,{props:r}=U_(e);for(const[o,s]of Object.entries(r)){let i="string";M_(s)?i="boolean":(R_(s)||D_(s))&&(i="json"),n.set(L_(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function gl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=I_(t,o),i=n?B_(n):[],a=n?F_(n,i):new Map,c=n?i_(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:ml(t)};if(ml(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function q_(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function V_(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function K_(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function qo(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(K_(s))}return r.push(f_(e)),n_(r)}function G_(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const J_={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function yl(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Ap};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:G_(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:J_}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const H_={"decimal.js":"Decimal"};function z_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(H_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${z_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function W_(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}const Y_={"decimal.js":"Decimal"};function Q_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Y_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Q_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Z_(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Ks(e){return{raw:e,words:W_(e)}}function X_(e){return Ks(Z_(Go.basename(e)))}function eA(e,t,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===e.id&&((i=s.path[s.path.length-1])==null?void 0:i.raw)===t});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=Ks(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Ks(e.id),path:e.dropFileSegment?[r]:[X_(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const tA=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function nA(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&tA.includes(e.code)&&typeof e.toJSON=="function"}async function rA(e){const t=await d_(e);if(t.ok){const o=t.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}class oA{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.toolMeta.set(t,n)}registerRoute(t,n){this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){return[...this.plans.keys()].map(t=>{const n=this.toolMeta.get(t);return{name:t,description:(n==null?void 0:n.description)??t,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(t,n){const r={};for(const s of n.envelope){const i=t.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(p_(n)){t.output=await rA(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=Pp(o==null?void 0:o.output),i=O_(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw nA(n)&&n.code,n}}function sA(e){if(e&&typeof e=="object"&&e.type==="object")return e;const t=e==null?void 0:e.oneOf;if(Array.isArray(t)&&t.length>0){const n={};let r=null;for(const o of t){if(!o||typeof o!="object")continue;const s=o,i=s.properties;if(i&&typeof i=="object")for(const[c,u]of Object.entries(i))c in n||(n[c]=u);const a=Array.isArray(s.required)?s.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function iA(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("mcp")||i.push(f)}return i}function aA(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=q_(e.options),a=V_(e.options),c={},u={};for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const m=d.fns,y=Object.entries(d.schemas).map(([N,j])=>({fnName:N,fnSchema:j,op:eA({id:d.id,importPath:d.importPath},N,e.operations)})),$={},v={};for(const{fnName:N,fnSchema:j,op:R}of y)$[R.id]=j,v[R.id]=m[N],c[R.id]=j,u[R.id]=m[N];const E=qo($,i),b={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:N,fnSchema:j,op:R}of y){const J=gl({op:R,schema:j,transport:"mcp",projection:o});t.bindSchema(R.id,j);const{outputSchema:U}=Pp(j.output),q=ll(J.mcp.name,j,s[J.mcp.name]??s[N]);t.bindToolMeta(J.mcp.name,{description:q,inputSchema:j.input,outputSchema:U}),t.registerRoute(J,Q=>yl(J,E,Q,b))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=qo(c,i),p={invoke:(d,m,y)=>f(d,{operation:{id:d},ctx:new Ap,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},y),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=iA(i,a,l,e.operations??[],p);if(h.length>0){const d=qo({},i),m={fns:{},schemas:{}};for(const y of h){const $=gl({op:y,transport:"mcp",projection:o}),v=sA(y.input),E=ll($.mcp.name,{input:v},s[$.mcp.name]);t.bindToolMeta($.mcp.name,{description:E,inputSchema:v}),t.registerRoute($,b=>yl($,d,b,m))}}}function Vo(e,t){const n=new $m.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(rc.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(rc.CallToolRequestSchema,async r=>{const{name:o,arguments:s={}}=r.params,i=e.getPlan(o),a=e.getDispatch(o);if(!i||!a)throw new Error(`Unknown tool: ${o}`);const c=s,u=c._meta??{},l={args:c,meta:u},f=Date.now();try{const p=await e.readCall(l,i),h=await a(p);return await e.writeResult(l,h,i),t.info({tool:o,ms:Date.now()-f},`→ ${o}`),l.output}catch(p){throw t.error({tool:o,ms:Date.now()-f,err:p},`✗ ${o}`),e.writeError(l,p,i),p}}),n}function $l(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}async function cA(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??s_();o.info(`mcp server starting (${t})`);const s=new oA;aA(e,s);const i=s.listTools().map(c=>c.name);o.info({tools:i},`${i.length} tools available`);for(const c of i){const u=s.getPlan(c),l=(u==null?void 0:u.params)??[],f=l.map(p=>`${p.name}${p.required?"":"?"}: ${p.type}`).join(", ");o.info({tool:c,args:{data:l}},`tool: ${c} args { data: {${f?` ${f} `:""}} }`)}if(t==="stdio"){const c=Vo(s,o),u=new vm.StdioServerTransport;return await c.connect(u),o.info("stdio transport ready"),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l()})})}if(t==="sse"){const c=new Map,u=nc.createServer($l(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=Vo(s,o),d=new wm.SSEServerTransport("/messages",f);c.set(d.sessionId,d),d.onclose=()=>c.delete(d.sessionId),await h.connect(d)}else if(l.method==="POST"&&p.startsWith("/messages")){const h=new URLSearchParams(p.split("?")[1]??"").get("sessionId"),d=h?c.get(h):void 0;if(!d){f.writeHead(404),f.end("Session not found");return}await d.handlePostMessage(l,f)}else f.writeHead(404),f.end("Not found")}));return u.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),u.close(()=>l())})})}const a=nc.createServer($l(o,async(c,u)=>{const l=Vo(s,o),f=new bm.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(f),await f.handleRequest(c,u)}));return a.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(c=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),a.close(()=>c())})})}const uA={id:"mcp",run(e){return cA(e)}},Tp=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),Cp=new Set(["MITIGATED"]),Rp=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),qa=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Be(e){return qa.has(e)}function Ir(e){return Tp.has(e)||Cp.has(e)}function xr(e){return Rp.has(e)}class Mp extends Error{constructor(t,n,r=[]){const o=r.length>0?` - did you mean repo ${r.map(s=>`'${s}'`).join(" or ")}?`:"";super(`backlog item not found: ${t}::${n}${o}`),this.foundInRepos=r,this.name="BacklogItemNotFoundError"}}class Dp extends Error{constructor(t){super(`transition to terminal status "${t}" requires at least one citation (either already attached via addCitation or passed inline to transitionStatus/resolveItem) — per the global CLAUDE.md rule "No citation, no claim."`),this.name="CitationRequiredError"}}class Lp extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class Up extends Error{constructor(t,n){super(`item is claimed by "${t}" since ${n} (not stale) — cannot start work`),this.heldBy=t,this.heldSince=n,this.name="ClaimHeldError"}}class lA extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}class ae extends Error{constructor(t,n){super(n),this.argument=t,this.name="InvalidArgumentError"}}class Va extends Error{constructor(t,n,r){super(`backlog: ambiguous lookup — ${r.length} live items share the same (repo, humanId) key "${t}"::"${n}" (nodeIds: ${r.join(", ")}). Refusing to silently pick one — this is a data-integrity defect (see BUG-BACKLOG-HUMANID-COLLISION-001); repair the collision (e.g. rename one of these nodeIds to a distinct humanId) before retrying this operation.`),this.nodeIds=r,this.name="AmbiguousHumanIdError"}}function fA(e,t){const n=t??T.join(Ue.homedir(),`.${e.orgNamespace}`);return T.join(n,e.project,e.namespace,"config.yaml")}function dA(e,t,n){const r=fA(e,n);let o={};if(C.existsSync(r))try{const a=oc.parse(C.readFileSync(r,"utf8"));a!==null&&typeof a=="object"&&!Array.isArray(a)&&(o=a)}catch{o={}}const s=o.migration&&typeof o.migration=="object"&&!Array.isArray(o.migration)?o.migration:{},i={...o,migration:{...s,phase:t}};return C.mkdirSync(T.dirname(r),{recursive:!0}),C.writeFileSync(r,oc.stringify(i),"utf8"),r}const ge="backlog-item",vl="backlog-plan",wl="backlog-assignee",pA="adhd-backlog:";function Bp(e){return Un.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Ka(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function nn(e){return e.split("-")[0]??e}function ct(e){return e.replace(/-\d+$/,"")}function Zr(e,t,n,r){return`${n}
47
+ `}async function Hu(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let i=!1;try{for await(const s of e){if(r.signal.aborted)break;i||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),i=!0),o.write(qu(JSON.stringify(s)))}i||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(s){const a=re(s)?s:new L("internal",s instanceof Error?s.message:String(s));if(i)o.write(Ku(JSON.stringify(a.toJSON()))),o.end();else{const c=Gu(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const Vu={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function Gu(e){return Vu[e]??500}function as(e){return re(e)?id[e.code]??500:500}function cs(e){return re(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function Ju(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}class Wu{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(i,s)=>{const a={req:i,reply:s};try{const c=await this.readCall(a,t),d=await n(c);await this.writeResult(a,d,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,i={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(i[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};s=a?od(c,a):c}else{const{data:c={}}=r.body??{};s=c}}return{envelope:i,domainArgs:s,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:i}=t;if(Dt(n)){await Hu(n,o,i);return}i.type("application/json"),i.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(as(n)).send(cs(n))}}function zu(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("http")||i.push(u)}return i}async function Yu(e){var h,y;const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",r=e.options.routePrefix??"",o=e.options.projection??{},i=Zn(e.options),s=eo(e.options),a=e.logger??Xn(),c=ja({logger:a});c.setErrorHandler((w,b,S)=>{S.status(as(w)).send(cs(w))});const d=new Wu(c,r,e.signal),l=[],u={},f={};for(const w of e.packages){if(!w.fns)throw new Error(`Package "${w.id}" is missing fns`);const b=w.fns,S=Object.entries(w.schemas).map(([_,R])=>({fnName:_,fnSchema:R,op:ss(w.id,_,R,e.operations)})),E={},A={};for(const{fnName:_,fnSchema:R,op:T}of S)E[T.id]=R,A[T.id]=b[_],u[T.id]=R,f[T.id]=b[_];const j=de(E,i),N={fns:A,createClient:w.createClient,schemas:E};for(const{fnSchema:_,op:R}of S){const T=ye({op:R,schema:_,transport:"http",projection:o});d.bindSchema(R.id,_),d.registerRoute(T,x=>xe(T,j,x,N));const{params:C,text:q}=bi(_);l.push({method:T.http.verb,route:r+T.http.route,text:q,params:C})}}const g=((h=e.packages[0])==null?void 0:h.id)??"ts",p=de(u,i),m={invoke:(w,b,S)=>p(w,{operation:{id:w},ctx:new tt,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},S),invokeOptions:{fns:f,schemas:u,createClient:(y=e.packages[0])==null?void 0:y.createClient}},v=zu(i,s,g,e.operations??[],m);if(v.length>0){const w=de({},i),b={fns:{},schemas:{}};for(const S of v){const E=ye({op:S,transport:"http",projection:o});d.registerRoute(E,A=>xe(E,w,A,b)),l.push({method:E.http.verb,route:`${r}/${S.id}`,text:"",params:[]})}}return await c.listen({port:t,host:n}),a.info({host:n,port:t},`listening on http://${n}:${t}`),Ju(a,l),new Promise(w=>{e.signal&&e.signal.addEventListener("abort",async()=>{await c.close(),w()})})}const Xu={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return Bu(e)},run(e){return Yu(e)}};function Qu(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const i of e){const s=Me(i),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:i.id,summary:i.id,responses:{200:Zu(i.output)}};if(a==="GET")l.parameters=ef(i.input);else{const u=i.input;typeof u=="object"&&u!==null&&Object.keys(u).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:u}}})}o[c]===void 0&&(o[c]={}),o[c][d]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Zu(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function ef(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function tf(e,t={}){return[{...ai("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>Qu(e.operations,{title:t.title,version:t.version})}]}const nf={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return tf(e,t)}}}};function of(){return`// Auto-generated by @adhd/apigen-cli — do not edit
48
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
49
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
50
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
51
+ import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
52
+ import { toolMetas, groupFns, groupCreateClient } from './index.js'
53
+
54
+ // §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
55
+ // x-apigen-envelope (field→pluginId map) is carried on each schema entry.
56
+ function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, unknown>): Record<string, unknown> {
57
+ const inputProps = ((schema['input'] as any)?.['properties'] as Record<string, unknown>) ?? {}
58
+ const envMeta = schema['x-apigen-envelope'] as Record<string, string> | undefined
59
+ const envelope: Record<string, unknown> = {}
60
+ for (const field of Object.keys(inputProps)) {
61
+ if (field === 'data') continue
62
+ const pluginId = envMeta?.[field] ?? 'adhd'
63
+ const key = \`x-\${pluginId}-\${field}\`
64
+ if (meta[key] !== undefined) envelope[field] = meta[key]
65
+ }
66
+ return envelope
67
+ }
68
+
69
+ const server = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
70
+
71
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
72
+ tools: Object.entries(toolMetas).map(([name, meta]) => {
73
+ // ADR-0004: publish the function's return-type schema as MCP's outputSchema
74
+ // ONLY when it is already a top-level type:"object". A union/array/scalar
75
+ // return carries no outputSchema (it is optional in MCP) and is passed
76
+ // through flat — never wrapped under \`result\`.
77
+ const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
78
+ return {
79
+ name,
80
+ // BUG-APIGEN-020: description baked at generate time by generate.ts —
81
+ // documents the "data" envelope calling convention (+ any envelope
82
+ // fields) so consumers don't have to discover it by trial and error.
83
+ description: (meta as any).description ?? name,
84
+ inputSchema: (meta.schema as any).input,
85
+ ...(outputSchema ? { outputSchema } : {}),
86
+ }
87
+ }),
88
+ }))
89
+
90
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
91
+ const { name, arguments: args = {} } = req.params
92
+ const meta = toolMetas[name]
93
+ if (!meta) throw new Error(\`Unknown tool: \${name}\`)
94
+ // §9.1: envelope from _meta, domain args from data
95
+ const mcpMeta = (args as any)['_meta'] as Record<string, unknown> | undefined ?? {}
96
+ const envelope = extractEnvelope(meta.schema as Record<string, unknown>, mcpMeta)
97
+ // Dispatch by the REAL exported fn name (\`meta.fnName\`, not the incoming
98
+ // call's canonical tool name \`name\`) — see ../tool-naming.ts module doc
99
+ // (BUG-APIGEN-OPENAPI-ROUTE-PATH-MISMATCH-001 / BEHAVIOR CHANGE).
100
+ const result = await dispatch(
101
+ groupFns[meta.group],
102
+ groupCreateClient[meta.group],
103
+ meta.schema as any,
104
+ meta.fnName,
105
+ envelope,
106
+ ((args as any)['data'] ?? {}) as Record<string, unknown>,
107
+ )
108
+ // ADR-0004: \`content\` is the canonical flat payload. \`structuredContent\` is
109
+ // emitted only for an already-object return (\`wrapped === true\` == emit),
110
+ // and then it is the value itself — never \`{ result: value }\`.
111
+ const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
112
+ const structuredContent = wrapMcpStructuredContent(wrapped, result)
113
+ return {
114
+ content: [{ type: 'text', text: JSON.stringify(result) }],
115
+ ...(structuredContent ? { structuredContent } : {}),
116
+ }
117
+ })
118
+
119
+ const transport = new StdioServerTransport()
120
+ server.connect(transport)
121
+ `}function rf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
122
+ import { createServer } from 'node:http'
123
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
124
+ ${e==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
125
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
126
+ import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
127
+ import { toolMetas, groupFns, groupCreateClient } from './index.js'
128
+
129
+ // §9.1 — extract envelope from MCP _meta["x-<pluginId>-<field>"].
130
+ // x-apigen-envelope (field→pluginId map) is carried on each schema entry.
131
+ function extractEnvelope(schema: Record<string, unknown>, meta: Record<string, unknown>): Record<string, unknown> {
132
+ const inputProps = ((schema['input'] as any)?.['properties'] as Record<string, unknown>) ?? {}
133
+ const envMeta = schema['x-apigen-envelope'] as Record<string, string> | undefined
134
+ const envelope: Record<string, unknown> = {}
135
+ for (const field of Object.keys(inputProps)) {
136
+ if (field === 'data') continue
137
+ const pluginId = envMeta?.[field] ?? 'adhd'
138
+ const key = \`x-\${pluginId}-\${field}\`
139
+ if (meta[key] !== undefined) envelope[field] = meta[key]
140
+ }
141
+ return envelope
142
+ }
143
+
144
+ const mcpServer = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabilities: { tools: {} } })
145
+
146
+ mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
147
+ tools: Object.entries(toolMetas).map(([name, meta]) => {
148
+ // ADR-0004: publish the function's return-type schema as MCP's outputSchema
149
+ // ONLY when it is already a top-level type:"object". A union/array/scalar
150
+ // return carries no outputSchema (it is optional in MCP) and is passed
151
+ // through flat — never wrapped under \`result\`.
152
+ const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
153
+ return {
154
+ name,
155
+ // BUG-APIGEN-020: description baked at generate time by generate.ts —
156
+ // documents the "data" envelope calling convention (+ any envelope
157
+ // fields) so consumers don't have to discover it by trial and error.
158
+ description: (meta as any).description ?? name,
159
+ inputSchema: (meta.schema as any).input,
160
+ ...(outputSchema ? { outputSchema } : {}),
161
+ }
162
+ }),
163
+ }))
176
164
 
177
- ${r}
165
+ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
166
+ const { name, arguments: args = {} } = req.params
167
+ const meta = toolMetas[name]
168
+ if (!meta) throw new Error(\`Unknown tool: \${name}\`)
169
+ // §9.1: envelope from _meta, domain args from data
170
+ const mcpMeta = (args as any)['_meta'] as Record<string, unknown> | undefined ?? {}
171
+ const envelope = extractEnvelope(meta.schema as Record<string, unknown>, mcpMeta)
172
+ // Dispatch by the REAL exported fn name (\`meta.fnName\`, not the incoming
173
+ // call's canonical tool name \`name\`) — see ../tool-naming.ts module doc
174
+ // (BUG-APIGEN-OPENAPI-ROUTE-PATH-MISMATCH-001 / BEHAVIOR CHANGE).
175
+ const result = await dispatch(
176
+ groupFns[meta.group],
177
+ groupCreateClient[meta.group],
178
+ meta.schema as any,
179
+ meta.fnName,
180
+ envelope,
181
+ ((args as any)['data'] ?? {}) as Record<string, unknown>,
182
+ )
183
+ // ADR-0004: \`content\` is the canonical flat payload. \`structuredContent\` is
184
+ // emitted only for an already-object return (\`wrapped === true\` == emit),
185
+ // and then it is the value itself — never \`{ result: value }\`.
186
+ const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
187
+ const structuredContent = wrapMcpStructuredContent(wrapped, result)
188
+ return {
189
+ content: [{ type: 'text', text: JSON.stringify(result) }],
190
+ ...(structuredContent ? { structuredContent } : {}),
191
+ }
192
+ })
178
193
 
179
- <!-- ${pA}${e}::${t} -->`}function Xr(e,t){return`${e}::${t}`}function Ga(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function Ja(e,t,n=[]){return[...new Set([ge,e,t,...n])]}function Se(e){return e.tags.includes(ge)&&!e.isSuperseded}function se(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??nn(n),o=t.family??ct(n),s=new Set([ge,r,o]);return{nodeId:e.id,humanId:n,kind:r,family:o,title:t.title??e.summary??"",body:t.body??"",status:t.status??"UNKNOWN",priority:t.priority,repo:t.repo??e.namespace,projectPath:t.projectPath,plan:t.plan,importedFrom:t.importedFrom,assignee:t.assignee,claimedBy:t.claimedBy,claimedAt:t.claimedAt,citations:t.citations??[],notes:t.notes??[],tags:e.tags.filter(i=>!s.has(i)),createdAt:t.createdAt??e.tCreated,updatedAt:t.updatedAt??t.createdAt??e.tCreated}}const hA=5,mA=20,gA=500;function yA(e){return Ko.isBusyError(e)||Ko.isConcurrentConflict(e)}function $A(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function Ha(e,t={}){const n=t.maxAttempts??hA;for(let r=0;;r++)try{return await e()}catch(o){if(!yA(o)||r>=n-1)throw o;const s=Math.min(gA,mA*2**r);await $A(s*(.5+Math.random()*.5))}}async function vA(e,t,n){if(typeof n!="string"||n.trim().length===0)throw new ae("family",`backlog: cannot allocate a humanId for repo=${JSON.stringify(t)} — "family" is required and must be a non-empty string, received ${JSON.stringify(n)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);const r=await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{family:n}});let o=0;for(const s of r){const i=s.metadata,a=/-(\d+)$/.exec((i==null?void 0:i.humanId)??"");a&&(o=Math.max(o,Number(a[1])))}return`${n}-${String(o+1).padStart(3,"0")}`}async function wA(e,t,n){const o=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{humanId:n}})).filter(s=>{var i;return Se(s)&&((i=s.metadata)==null?void 0:i.humanId)===n});if(o.length>1)throw new Va(t,n,o.map(s=>s.id));return o[0]??null}async function Fp(e,t,n,r,o){return Ha(()=>e.adapter.transaction(async()=>{if(r){const i=await wA(e,t,r);return o(r,i)}const s=await vA(e,t,n);return o(s,null)},{mode:"immediate"}))}const qp="backlog-audit-event";async function Vp(e,t,n,r,o,s){const i=new Date().toISOString(),a={itemNodeId:t,kind:o,at:i,detail:s},c=`audit-event::${n}::${r}::${o}::${i}::${Math.random().toString(36).slice(2)}`,u=await e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[qp],namespace:n,metadata:a});await e.graph.writeEdge(u,t,"DERIVED_FROM")}async function bA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[qp],metadata:{itemNodeId:t}})).map(r=>r.metadata).filter(r=>r!==void 0&&r.itemNodeId===t).map(r=>({at:r.at,kind:r.kind,detail:r.detail})).sort((r,o)=>r.at.localeCompare(o.at))}const bl={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function El(e){const t=[ge];e.kind&&t.push(e.kind),e.tags&&t.push(...e.tags);const n={};e.family&&(n.family=e.family),e.priority&&(n.priority=e.priority),e.plan&&(n.plan=e.plan),e.importedFrom&&(n.importedFrom=e.importedFrom),e.assignee&&(n.assignee=e.assignee),e.claimedBy&&(n.claimedBy=e.claimedBy),e.status&&e.status!=="open"&&e.status!=="closed"&&(n.status=e.status);const r={kind:"generic",tags:t,tagsMatchAll:!0};return e.repo!==void 0&&(r.namespace=e.repo),e.projectPath!==void 0&&(r.projectPath=e.projectPath),Object.keys(n).length>0&&(r.metadata=n),r}function EA(e,t){return t.status==="open"?e.filter(n=>!Be(n.status)):t.status==="closed"?e.filter(n=>Be(n.status)):e}function Sl(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function Nl(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}async function Kp(e,t={}){if(t.grep){const o=El({...t}),s=Ka(t.grep);if(!s)return[];const i=await e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=Nl(Sl(i.filter(Se),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=El(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=await e.graph.queryNodes(n);return Nl(Sl(r.filter(Se),t),t)}async function ut(e,t={}){const r=(await Kp(e,t)).map(se);return EA(r,t)}async function qe(e,t,n){const r=Xr(t,n),s=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{humanId:n}})).filter(Se);if(s.length>1)throw new Va(t,n,s.map(i=>i.id));return s.find(i=>i.name===r)??s[0]??null}function Gs(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}async function SA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[ge],metadata:{humanId:t}})).filter(Se)}async function Gp(e){const t=await e.graph.queryNodes({kind:"generic",tags:[ge]}),n=new Set;for(const r of t){if(!Se(r))continue;const o=Gs(r);o&&n.add(o)}return n}async function Oe(e,t,n){const r=(await SA(e,n)).filter(s=>Gs(s)!==t),o=[...new Set(r.map(Gs).filter(s=>s.length>0))];return new Mp(t,n,o)}function pn(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}async function NA(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Be(s.status)),o=n.filter(s=>Be(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:pn(n,s=>s.status),byKind:pn(n,s=>s.kind),byFamily:pn(n,s=>s.family),byPriority:pn(n,s=>s.priority),byRepo:t.repo===void 0?pn(n,s=>s.repo):{}}}async function OA(e,t={},n=20){const o=(await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"})).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=bl[s.priority??""]??4,c=bl[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}async function Jp(e,t){const n=await e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=await e.graph.getNode(o.dst);s&&r.push(s)}return r}async function kA(e,t,n){const r=await qe(e,t,n);return r?(await Jp(e,r.id)).filter(o=>!o.tInvalid).map(se).filter(o=>!Be(o.status)):[]}async function _A(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}),r=[];for(const o of n){if(o.claimedBy)continue;const s=await qe(e,o.repo,o.humanId);if(!s)continue;(await Jp(e,s.id)).filter(a=>!a.tInvalid).every(a=>Be(se(a).status))&&r.push(o)}return r}async function Hp(e,t={}){const n=await ut(e,{repo:t.repo,projectPath:t.projectPath}),r=n.map(s=>({humanId:s.humanId,title:s.title,status:s.status})),o=[];for(const s of n){const i=await qe(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of await e.graph.getEdges({src:i.id,rel:a})){const u=await e.graph.getNode(c.dst);if(!u||u.tInvalid)continue;const l=u.metadata;l!=null&&l.humanId&&o.push({from:s.humanId,to:l.humanId,rel:a})}}return{nodes:r,edges:o}}async function AA(e,t={}){var c;const n=await Hp(e,t),r=n.edges.filter(u=>u.rel==="DEPENDS_ON"),o=new Map;for(const u of n.nodes)o.set(u.humanId,new Set);for(const u of r)(c=o.get(u.from))==null||c.add(u.to);const s=new Set(n.nodes.map(u=>u.humanId)),i=[];let a=!0;for(;s.size>0&&a;){a=!1;for(const u of[...s].sort())[...o.get(u)??new Set].every(p=>!s.has(p))&&(i.push(u),s.delete(u),a=!0)}return s.size>0?{ok:!1,cycle:jA([...s],o)}:{ok:!0,order:i}}function jA(e,t){const n=new Set(e),r=new Set,o=[];function s(i){if(r.has(i)){const a=o.indexOf(i);return[...o.slice(a),i]}if(!n.has(i))return null;r.add(i),o.push(i);for(const a of t.get(i)??[]){const c=s(a);if(c)return c}return o.pop(),r.delete(i),null}for(const i of e){const a=s(i);if(a)return a}return e}async function IA(e,t,n={}){const r=await ut(e,{repo:n.repo,projectPath:n.projectPath}),o=t*6e4,s=Date.now();return r.filter(i=>!i.claimedBy||!i.claimedAt?!1:s-Date.parse(i.claimedAt)>=o)}async function xA(e,t,n){var u,l,f,p;const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);const o=se(r),s=[{at:o.createdAt,kind:"created",detail:{title:o.title,repo:o.repo}}];for(const h of o.citations)s.push({at:o.updatedAt,kind:"citation",detail:{...h}});for(const h of o.notes)s.push({at:h.at,kind:"note",detail:{by:h.by,text:h.text}});s.push(...await bA(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=await e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(y=>y.id===r.id),d=h>0?((l=(u=i[h-1])==null?void 0:u.metadata)==null?void 0:l.humanId)??void 0:void 0,m=h>=0&&h<i.length-1?((p=(f=i[h+1])==null?void 0:f.metadata)==null?void 0:p.humanId)??void 0:void 0;a={},d&&(a.supersedes=d),m&&(a.supersededBy=m)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class PA extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}async function ke(e,t,n){return Ha(()=>e.adapter.transaction(async()=>{const r=await e.graph.getNode(t);if(!r||r.tInvalid)throw new PA(t);const o=r.metadata??{},s=n(o);return await e.graph.touch(t,{metadata:s}),s},{mode:"immediate"}))}async function za(e,t,n){const r=await e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&await Vp(e,t,o.repo,o.humanId,"claim",n)}const TA=30;class CA extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}async function zp(e,t,n,r={}){const o=(r.staleAfterMin??TA)*6e4;let s;return await ke(e,t,i=>{const a=Date.now(),c=new Date(a).toISOString();return!i.claimedBy||i.claimedBy===n?(s={status:i.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:c},{...i,claimedBy:n,claimedAt:c,updatedAt:c}):(i.claimedAt?a-Date.parse(i.claimedAt):Number.POSITIVE_INFINITY)<=o&&!r.force?(s={status:"held",claimedBy:n,claimedAt:c,heldBy:i.claimedBy,...i.claimedAt!==void 0?{heldSince:i.claimedAt}:{}},i):(s={status:"reclaimed-stale",claimedBy:n,claimedAt:c,previousClaimant:i.claimedBy},{...i,claimedBy:n,claimedAt:c,updatedAt:c})}),s.status!=="held"&&await za(e,t,{status:s.status,by:n}),s}async function RA(e,t,n){let r;return await ke(e,t,o=>{const s=new Date().toISOString();return r={status:o.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:s},{...o,claimedBy:n,claimedAt:s,updatedAt:s}}),await za(e,t,{status:r.status,by:n}),r}async function MA(e,t,n,r={}){let o;return await ke(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new CA(s.claimedBy,n);o={status:"released",wasClaimedBy:s.claimedBy};const a=new Date().toISOString(),c={...s,updatedAt:a};return delete c.claimedBy,delete c.claimedAt,c}),o.status!=="release-noop"&&await za(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}async function eo(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}function to(e){if(typeof e.file!="string"||e.file.trim().length===0)throw new ae("citation.file",`backlog: a citation requires a non-empty "file" — received file=${JSON.stringify(e.file)}.`)}async function Dn(e,t,n,r,o){if(o.citations)for(const c of o.citations)to(c);const s=await eo(e,t,n);let i;await ke(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(Ir(r)&&u.length===0)throw new Dp(r);if(xr(r)&&(!o.reason||o.reason.trim().length===0))throw new Lp(r);const l=new Date().toISOString(),f=[...c.notes];o.note&&f.push({by:o.by,at:l,text:o.note}),o.reason&&f.push({by:o.by,at:l,text:`[transition to ${r}] ${o.reason}`});const p={...c,status:r,citations:u,notes:f,updatedAt:l};return qa.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),await Vp(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}async function DA(e,t,n,r,o){return Dn(e,t,n,r,o)}async function LA(e,t,n,r){const o=await eo(e,t,n),s=await zp(e,o.id,r);if(s.status==="held")throw new Up(s.heldBy??"unknown",s.heldSince??"unknown");return Dn(e,t,n,"IN_PROGRESS",{by:r})}async function UA(e,t,n,r){to(r);const o=await eo(e,t,n);await ke(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=await e.graph.getNode(o.id);if(!s)throw await Oe(e,t,n);return se(s)}async function BA(e,t,n,r,o){const s=await eo(e,t,n);await ke(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=await e.graph.getNode(s.id);if(!i)throw await Oe(e,t,n);return se(i)}async function FA(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=await ut(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Be(i.status))continue;const a=new Date().toISOString();await ke(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=await e.graph.getNode(i.nodeId);c&&s.push(se(c))}return s}const qA=new Set(["a","an","and","are","as","at","be","been","but","by","can","do","does","for","from","had","has","have","if","in","into","is","it","its","no","not","of","on","or","our","so","such","than","that","the","their","then","there","these","this","to","was","were","will","with","would","you","your"]);function Wp(e){return Ka(e).toLowerCase().split(" ").filter(t=>t.length>0&&!qA.has(t))}function VA(e,t){if(e.length===0)return!0;const n=new Set(Wp(t));return e.every(r=>n.has(r))}async function KA(e,t,n){var i;const r=new Map,o=Ka(n.title);if(o){const a=Wp(n.title);for(const c of await e.graph.searchNodes(o,{limit:10,filter:{tags:[ge],namespace:t}})){if(!Se(c))continue;const u=((i=c.metadata)==null?void 0:i.title)??c.summary??"";VA(a,u)&&r.set(c.id,c)}}const s=n.dedupeScan;if(s!=null&&s.symbol)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupeSymbol:s.symbol}}))Se(a)&&r.set(a.id,a);if(s!=null&&s.path)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupePath:s.path}}))Se(a)&&r.set(a.id,a);if(s!=null&&s.errorText)for(const a of await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t,metadata:{dedupeErrorText:s.errorText}}))Se(a)&&r.set(a.id,a);return[...r.values()].map(se)}async function Wa(e,t){if(!t.idOverride&&(typeof t.family!="string"||t.family.trim().length===0))throw new ae("family",`backlog: createItem requires a non-empty "family" (e.g. "BUG-APIGEN") unless "idOverride" is given — received family=${JSON.stringify(t.family)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);if(typeof t.title!="string"||t.title.trim().length===0)throw new ae("title",`backlog: createItem requires a non-empty "title" — received title=${JSON.stringify(t.title)}.`);if(typeof t.body!="string"||t.body.trim().length===0)throw new ae("body",`backlog: createItem requires a non-empty "body" — received body=${JSON.stringify(t.body)}.`);if(typeof t.repo!="string"||t.repo.trim().length===0)throw new ae("repo",`backlog: createItem requires a non-empty "repo" — received repo=${JSON.stringify(t.repo)}.`);if(t.citations)for(const s of t.citations)to(s);if(t.idOverride){const s=await qe(e,t.repo,t.idOverride);if(s){const i=se(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:await KA(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=await Gp(e),o=r.size>0&&!r.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...r].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0;return Fp(e,t.repo,t.family,t.idOverride,async(s,i)=>{var h,d,m;if(i){const y=se(i);return{item:y,created:!1,duplicateCandidates:[y]}}const a=nn(s),c=ct(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,citations:t.citations??[],notes:[],createdAt:u,updatedAt:u};t.priority!==void 0&&(l.priority=t.priority),t.projectPath!==void 0&&(l.projectPath=t.projectPath),t.plan!==void 0&&(l.plan=t.plan),t.importedFrom!==void 0&&(l.importedFrom=t.importedFrom),((h=t.dedupeScan)==null?void 0:h.symbol)!==void 0&&(l.dedupeSymbol=t.dedupeScan.symbol),((d=t.dedupeScan)==null?void 0:d.path)!==void 0&&(l.dedupePath=t.dedupeScan.path),((m=t.dedupeScan)==null?void 0:m.errorText)!==void 0&&(l.dedupeErrorText=t.dedupeScan.errorText);const f=await e.graph.writeNode(Zr(t.repo,s,t.title,t.body),{kind:"generic",name:Xr(t.repo,s),summary:t.title,tags:Ja(a,c,t.tags),namespace:t.repo,importance:Ga(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: writeNode returned an id that does not resolve: ${f}`);return{item:se(p),created:!0,duplicateCandidates:[],...o!==void 0?{repoWarning:o}:{}}})}async function Yp(e,t,n){const r=await qe(e,t,n);return r?se(r):null}async function Qp(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}async function Zp(e,t,n,r){const o=await Qp(e,t,n);let s="",i="";if(await ke(e,o.id,c=>{const u={...c,updatedAt:new Date().toISOString()};return r.title!==void 0&&(u.title=r.title),r.body!==void 0&&(u.body=r.body),r.projectPath!==void 0&&(u.projectPath=r.projectPath),r.importedFrom!==void 0&&(u.importedFrom=r.importedFrom),s=u.title,i=u.body,u}),r.title!==void 0||r.tags!==void 0||r.projectPath!==void 0){const c={};if(r.title!==void 0&&(c.summary=r.title),r.tags!==void 0){const u=nn(n),l=ct(n);c.tags=Ja(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),await e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=Zr(t,n,s,i);await e.adapter.executeRun("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL",[c,Bp(c),o.id])}const a=await e.graph.getNode(o.id);if(!a)throw await Oe(e,t,n);return se(a)}async function GA(e,t,n,r){if(typeof r!="string"||r.trim().length===0)throw new ae("reason",`backlog: softDeleteItem requires a non-empty "reason" — received reason=${JSON.stringify(r)}.`);const o=await Qp(e,t,n);await e.graph.invalidate(o.id,r)}async function Ne(e,t,n){const r=await qe(e,t,n);if(!r)throw await Oe(e,t,n);return r}async function JA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}async function HA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.adapter.executeRun("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'",[o.id,s.id])}async function zA(e,t,n,r){const o=await Ne(e,t,n),s=await Ne(e,t,r);await e.graph.writeEdge(o.id,s.id,"RELATES_TO")}async function WA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new ae("reason",`backlog: supersedeItem requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);if(r.citations)for(const c of r.citations)to(c);const s=await Ne(e,t,n),i=new Date().toISOString(),a=await Fp(e,t,r.family,r.idOverride,c=>c);{const c=nn(a),u=ct(a),l={humanId:a,kind:c,family:u,title:r.title,body:r.body,status:"OPEN",repo:t,citations:r.citations??[],notes:[],createdAt:i,updatedAt:i};r.priority!==void 0&&(l.priority=r.priority),r.projectPath!==void 0&&(l.projectPath=r.projectPath),r.plan!==void 0&&(l.plan=r.plan);const f=await e.graph.supersede(s.id,Zr(t,a,r.title,r.body),{kind:"generic",name:Xr(t,a),summary:r.title,tags:["backlog-item",c,u,...r.tags??[]],namespace:t,importance:Ga(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:l});await ke(e,s.id,h=>{const d=[...h.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],m={...h,status:"SUPERSEDED",notes:d,updatedAt:i};return delete m.claimedBy,delete m.claimedAt,m}),await e.graph.invalidate(s.id,o);const p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: supersede() returned an id that does not resolve: ${f}`);return se(p)}}async function YA(e,t,n,r){const o=await Ne(e,t,n),s=[];for(const i of r){const a=await Wa(e,{...i,repo:t});await e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}async function QA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new ae("reason",`backlog: mergeItems requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=await Ne(e,t,n),i=await Ne(e,t,r);await ke(e,i.id,c=>{const u=new Date().toISOString(),l={...c,status:"DUPLICATE",notes:[...c.notes,{by:"system",at:u,text:`[merged into ${n}] ${o}`}],updatedAt:u};return delete l.claimedBy,delete l.claimedAt,l}),await e.graph.writeEdge(i.id,s.id,"SAME_AS"),await e.graph.invalidate(i.id,o);const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}async function Xp(e,t,n,r){const o=await Ne(e,t,n);await ke(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),await e.graph.touch(o.id,{importance:Ga(r)});const s=await e.graph.getNode(o.id);if(!s)throw await Oe(e,t,n);return se(s)}async function ZA(e,t,n){const r=`${t}::plan:${n}`,s=(await e.graph.queryNodes({kind:"generic",tags:[vl],namespace:t,metadata:{planSlug:n}})).find(i=>i.name===r&&!i.isSuperseded);return s?s.id:e.graph.writeNode(`plan:${n}`,{kind:"generic",name:r,summary:n,tags:[vl],namespace:t,metadata:{planSlug:n}})}async function Js(e,t,n,r){const o=await Ne(e,t,n),s=await ZA(e,t,r);await ke(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),await e.graph.writeEdge(o.id,s,"MEMBER_OF")}async function XA(e,t){const r=(await e.graph.queryNodes({kind:"entity",tags:[wl],metadata:{identity:t}})).find(o=>o.name===t&&!o.isSuperseded);return r?r.id:e.graph.writeNode(`assignee:${t}`,{kind:"entity",name:t,summary:t,tags:[wl],metadata:{identity:t}})}async function ej(e,t,n,r,o){const s=await Ne(e,t,n),i=await XA(e,r);await ke(e,s.id,c=>{const u=new Date().toISOString();return{...c,assignee:r,notes:[...c.notes,{by:o,at:u,text:`assigned to ${r}`}],updatedAt:u}}),await e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=await e.graph.getNode(s.id);if(!a)throw await Oe(e,t,n);return se(a)}function zt(e){return e.metadata??{}}function tj(e){const t=/-(\d+)$/.exec(e);return(t==null?void 0:t[1])===void 0?void 0:Number(t[1])}async function nj(e,t,n){if(typeof t!="string"||t.trim().length===0)throw new ae("fromRepo",`backlog: planRepoMigration requires a non-empty fromRepo, received ${JSON.stringify(t)}`);if(typeof n!="string"||n.trim().length===0)throw new ae("toRepo",`backlog: planRepoMigration requires a non-empty toRepo, received ${JSON.stringify(n)}`);if(t===n)throw new ae("toRepo",`backlog: planRepoMigration requires fromRepo and toRepo to differ (both were ${JSON.stringify(t)})`);const r=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:t})).filter(Se),o=(await e.graph.queryNodes({kind:"generic",tags:[ge],namespace:n})).filter(Se),s=new Set,i=new Map;for(const u of o){const l=zt(u),f=l.humanId;if(!f)continue;s.add(f);const p=l.family??ct(f),h=tj(f);h!==void 0&&i.set(p,Math.max(i.get(p)??0,h))}const a=[...r].sort((u,l)=>(zt(u).humanId??"").localeCompare(zt(l).humanId??"")),c=[];for(const u of a){const l=zt(u),f=l.humanId??"",p=l.family??ct(f);let h=f,d=!1;if(s.has(f)){const m=(i.get(p)??0)+1;i.set(p,m),h=`${p}-${String(m).padStart(3,"0")}`,d=!0}s.add(h),c.push({nodeId:u.id,humanId:f,targetHumanId:h,renamed:d,title:l.title??"",status:l.status??"UNKNOWN"})}return{fromRepo:t,toRepo:n,items:c,collisionCount:c.filter(u=>u.renamed).length}}async function rj(e,t,n,r,o){const s=await e.graph.getNode(t.nodeId);if(!s||s.tInvalid||!Se(s))throw new ae("nodeId",`backlog: migration plan item nodeId=${t.nodeId} (humanId=${JSON.stringify(t.humanId)}) is no longer a live backlog item — re-run planRepoMigration and retry.`);const i=zt(s);if(i.humanId!==t.humanId||s.namespace!==n)throw new ae("nodeId",`backlog: migration plan for nodeId=${t.nodeId} is stale — expected (namespace=${JSON.stringify(n)}, humanId=${JSON.stringify(t.humanId)}), found (namespace=${JSON.stringify(s.namespace)}, humanId=${JSON.stringify(i.humanId)}). Re-run planRepoMigration and retry.`);const a=await qe(e,r,t.targetHumanId);if(a)throw new ae("targetHumanId",`backlog: migration target humanId=${JSON.stringify(t.targetHumanId)} in repo=${JSON.stringify(r)} is now claimed by nodeId=${a.id} (it was free when planRepoMigration ran) — re-run planRepoMigration and retry.`);const c=new Date().toISOString(),u=nn(t.targetHumanId),l=ct(t.targetHumanId),f=new Set([ge,i.kind??nn(t.humanId),i.family??ct(t.humanId)]),p=s.tags.filter(d=>!f.has(d));await Ha(()=>e.adapter.transaction(async()=>{const d=await e.graph.getNode(t.nodeId);if(!d||d.tInvalid)throw new ae("nodeId",`backlog: migration plan item nodeId=${t.nodeId} (humanId=${JSON.stringify(t.humanId)}) was invalidated between planning and commit — re-run planRepoMigration and retry.`);const m=zt(d),y=m.title??"",$=m.body??"",v=t.renamed?` and renamed humanId from ${JSON.stringify(t.humanId)} to ${JSON.stringify(t.targetHumanId)} (id collision with an existing item already in ${JSON.stringify(r)})`:"",E=[...m.notes??[],{by:o,at:c,text:`[repo migration] moved from repo=${JSON.stringify(n)}${v} to repo=${JSON.stringify(r)} — BUG-BACKLOG-REPO-SPLIT-001 / DEBT-BACKLOG-REPO-MOVE-001 reconciliation`}],b={...m,repo:r,humanId:t.targetHumanId,kind:u,family:l,notes:E,updatedAt:c};await e.graph.touch(t.nodeId,{metadata:b,name:Xr(r,t.targetHumanId),tags:Ja(u,l,p)});const N=Zr(r,t.targetHumanId,y,$),j=await e.adapter.executeRun("UPDATE node SET namespace = ?, content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL",[r,N,Bp(N),t.nodeId]);if(j.rowsAffected!==1)throw new ae("nodeId",`backlog: namespace UPDATE for nodeId=${t.nodeId} affected ${j.rowsAffected} row(s), expected exactly 1 — rolling back the whole move rather than leaving metadata.repo and node.namespace divergent.`)},{mode:"immediate"}));const h=await e.graph.getNode(t.nodeId);if(!h)throw new ae("nodeId",`backlog: migrateRepoItemNode nodeId=${t.nodeId} vanished mid-move — this should be unreachable.`);return se(h)}async function oj(e,t,n){const r=[];for(const o of t.items)try{await rj(e,o,t.fromRepo,t.toRepo,n),r.push({nodeId:o.nodeId,fromHumanId:o.humanId,toHumanId:o.targetHumanId,renamed:o.renamed,ok:!0})}catch(s){r.push({nodeId:o.nodeId,fromHumanId:o.humanId,toHumanId:o.targetHumanId,renamed:o.renamed,ok:!1,error:s instanceof Error?s.message:String(s)})}return r}async function sj(e,t,n,r,o=!0){const s=await nj(e,t,n);if(o)return{fromRepo:t,toRepo:n,dryRun:!0,plan:s};const i=await oj(e,s,r),a=i.filter(c=>c.ok).length;return{fromRepo:t,toRepo:n,dryRun:!1,plan:s,results:i,succeeded:a,failed:i.length-a}}const Ol=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,ij=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],aj=["MITIGATED"],cj=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],uj=new Set([...ij,...aj,...cj]),lj=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function eh(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":lj.has(t)?t:"UNKNOWN"}function th(e){var s;const t=(e??"").toLowerCase();if(!t.trim())return null;const n=i=>t.includes(i);if(n("outstanding"))return{label:"OUTSTANDING",open:!0};if(n("partially"))return{label:"PARTIAL",open:!0};if(n("in progress"))return{label:"IN-PROGRESS",open:!0};const r=n("shipped")&&"SHIPPED"||n("superseded")&&"SUPERSEDED"||n("invalid")&&"INVALID"||n("mitigated")&&"MITIGATED"||n("removed")&&!n("open")&&"REMOVED"||n("fixed")&&"FIXED"||n("resolved")&&"RESOLVED"||n("done")&&"DONE"||null,o=n("open")&&"OPEN"||(n("deferred")||n("defer"))&&"DEFERRED"||null;return r&&o?{label:"MIXED",open:!0}:r?{label:r,open:!1}:o?{label:o,open:!0}:n("downgraded")?{label:"OPEN",open:!0}:{label:((s=t.trim().split(/\s+/)[0])==null?void 0:s.toUpperCase().replace(/[^A-Z]/g,""))||"UNKNOWN",open:!0}}function nh(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?th(n[1]):null;if(r)return r;const o=e.toUpperCase();for(const s of["RESOLVED","FIXED","MITIGATED","DONE","CLOSED"])if(o.includes(s))return{label:s,open:!1};return{label:"UNKNOWN",open:!0}}function rh(e,t){const r=`${e}
180
- ${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const fj=/^[A-Z][A-Z0-9_-]*$/;function dj(e){const t=e.trim().split(/\s+/)[0]??"";return fj.test(t)&&/[0-9_]/.test(t)}function oh(e){const t=e.split(`
181
- `),n=[],r=[];let o=null;const s=()=>{if(!o)return;const i=o.bodyLines.join(`
182
- `),a=nh(o.headerLine,i),c=rh(o.headerLine,i),{bodyLines:u,...l}=o,f=!uj.has(a.label);n.push({...l,status:a.label,open:f,terminal:!f,priority:c,body:i.trim()}),o=null};return t.forEach((i,a)=>{const c=i.match(Ol),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace(Ol,"").replace(/^\s*[—–-]\s*/,"").trim(),p=l.split("-");o={id:l,kind:p[0]??l,family:l.replace(/-\d+[a-z]?$/i,""),title:f,level:c[1].length,line:a+1,headerLine:i,bodyLines:[]}}else if(u){const l=i.replace(/^#{2,3}\s+/,"");dj(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function pj(e){return oh(e).items}function sh(e){return oh(e)}function hj(e){return`**Citations:** [${e.map(n=>{const r=n.lines?`${n.file}:${n.lines}`:n.file;return n.context?`${r} (${n.context})`:r}).join(", ")}]`}function mj(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function ih(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${mj(e.status)}`),e.priority&&t.push(`**Priority:** ${e.priority}`),e.assignee&&t.push(`**Assignee:** ${e.assignee}`),e.plan&&t.push(`**Plan:** ${e.plan}`),t.push(""),e.body&&t.push(e.body,""),e.citations.length>0&&t.push(hj(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
183
- `).trimEnd()}function ah(e){return e.length===0?"":`${e.map(ih).join(`
194
+ const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
195
+ const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
196
+ httpServer.listen(${t}, () => console.error('MCP ${e} server on port ${t}'))
197
+ `}function Pn(e){return{raw:e,words:ze(e)}}function sf(e){return Pn(Nd(cn.basename(e)))}function ds(e,t,n){if(n){const o=n.find(i=>{var s;return i.kind==="action"&&i.namespace.raw===e.id&&((s=i.path[i.path.length-1])==null?void 0:s.raw)===t});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=Pn(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Pn(e.id),path:e.dropFileSegment?[r]:[sf(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function af(e,t,n){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of e)r.push(`import * as ${o.id}_ns from '${o.importPath}'`),r.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of e)for(const[i,s]of Object.entries(o.schemas)){const a=ds({id:o.id,importPath:o.importPath},i,n),d=ye({op:a,schema:s,transport:"mcp"}).mcp.name,l=En(d,s,t[d]??t[i]);r.push(` ${JSON.stringify(d)}: { group: '${o.id}', fnName: ${JSON.stringify(i)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of e)r.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);r.push("}"),r.push(""),r.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of e)r.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
198
+ `)}function cf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.toolDescriptions??{},o=e.operations,i=af(e.packages,r,o),s=t==="stdio"?of():rf(t,n);return{files:[{path:"index.ts",content:i},{path:"server.ts",content:s}]}}async function df(e){const t=await Si(e);if(t.ok){const o=t.chunks.map(i=>({type:"text",text:JSON.stringify(i)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}const lf=Object.freeze({type:"object",properties:{}});class uf{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.cachedList=void 0,this.toolMeta.set(t,n)}registerRoute(t,n){this.cachedList=void 0,this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){if(this.cachedList)return this.cachedList;const t=[...this.plans.keys()].map(n=>{const r=this.toolMeta.get(n);return Object.freeze({name:n,description:(r==null?void 0:r.description)??n,inputSchema:(r==null?void 0:r.inputSchema)??lf,...r!=null&&r.outputSchema?{outputSchema:r.outputSchema}:{}})});return this.cachedList=Object.freeze(t),this.cachedList}readCall(t,n){const r={};for(const i of n.envelope){const s=t.meta[i.mcpMetaKey];s!==void 0&&(r[i.field]=s)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(Dt(n)){t.output=await df(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:i}=ki(o==null?void 0:o.output),s=bd(i,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(t,n,r){throw re(n)&&n.code,n}}function ff(e){if(e&&typeof e=="object"&&e.type==="object")return e;const t=e==null?void 0:e.oneOf;if(Array.isArray(t)&&t.length>0){const n={};let r=null;for(const o of t){if(!o||typeof o!="object")continue;const i=o,s=i.properties;if(s&&typeof s=="object")for(const[c,d]of Object.entries(s))c in n||(n[c]=d);const a=Array.isArray(i.required)?i.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function pf(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("mcp")||i.push(u)}return i}function mf(e,t){var f,g;const n=e.options.projection??{},r=e.options.toolDescriptions??{},o=Zn(e.options),i=eo(e.options),s={},a={};for(const p of e.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const m=p.fns,v=Object.entries(p.schemas).map(([S,E])=>({fnName:S,fnSchema:E,op:ds({id:p.id,importPath:p.importPath},S,e.operations)})),h={},y={};for(const{fnName:S,fnSchema:E,op:A}of v)h[A.id]=E,y[A.id]=m[S],s[A.id]=E,a[A.id]=m[S];const w=de(h,o),b={fns:y,createClient:p.createClient,schemas:h};for(const{fnName:S,fnSchema:E,op:A}of v){const j=ye({op:A,schema:E,transport:"mcp",projection:n});t.bindSchema(A.id,E);const{outputSchema:N}=ki(E.output),_=En(j.mcp.name,E,r[j.mcp.name]??r[S]);t.bindToolMeta(j.mcp.name,{description:_,inputSchema:E.input,outputSchema:N}),t.registerRoute(j,R=>xe(j,w,R,b))}}const c=((f=e.packages[0])==null?void 0:f.id)??"ts",d=de(s,o),l={invoke:(p,m,v)=>d(p,{operation:{id:p},ctx:new tt,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},v),invokeOptions:{fns:a,schemas:s,createClient:(g=e.packages[0])==null?void 0:g.createClient}},u=pf(o,i,c,e.operations??[],l);if(u.length>0){const p=de({},o),m={fns:{},schemas:{}};for(const v of u){const h=ye({op:v,transport:"mcp",projection:n}),y=ff(v.input),w=En(h.mcp.name,{input:y},r[h.mcp.name]);t.bindToolMeta(h.mcp.name,{description:w,inputSchema:y}),t.registerRoute(h,b=>xe(h,p,b,m))}}}function gf(e){const t=e.packages[0];return{name:(t==null?void 0:t.id)??"apigen-mcp",version:(t==null?void 0:t.version)??"1.0.0"}}function on(e,t,n){const r=new _a.Server(n,{capabilities:{tools:{}}});return r.setRequestHandler($o.ListToolsRequestSchema,async()=>({tools:e.listTools()})),r.setRequestHandler($o.CallToolRequestSchema,async o=>{const{name:i,arguments:s={}}=o.params,a=e.getPlan(i),c=e.getDispatch(i);if(!a||!c)throw new Error(`Unknown tool: ${i}`);const d=s,l=d._meta??{},u={args:d,meta:l},f=Date.now();try{const g=await e.readCall(u,a),p=await c(g);return await e.writeResult(u,p,a),t.info({tool:i,ms:Date.now()-f},`→ ${i}`),u.output}catch(g){throw re(g)&&g.code!=="internal"?t.error({tool:i,ms:Date.now()-f,code:g.code,message:g.message},`✗ ${i}`):t.error({tool:i,ms:Date.now()-f,err:g},`✗ ${i}`),e.writeError(u,g,a),g}}),r}function Ar(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}function jr(e,t){const n=e.signal;if(!n)throw new L("invalid_argument",`apigen mcp transport "${t}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function _r(e,t,n,r,o,i){return new Promise((s,a)=>{const c=d=>{a(new L("internal",`failed to bind mcp ${r} server on ${n}:${t}: ${d.message}`,{cause:d}))};e.once("error",c),e.listen(t,n,()=>{e.removeListener("error",c),e.on("error",l=>o.error({err:l},"mcp http server error")),o.info({host:n,port:t},`listening on http://${n}:${t}`);const d=()=>{o.info("mcp server shutting down"),e.close(()=>s()),e.closeAllConnections()};if(i.aborted){d();return}i.addEventListener("abort",d,{once:!0})})})}function hf(e,t,n,r=process.stdin){return new Promise(o=>{let i=!1;function s(l){i||(i=!0,r.off("end",a),r.off("close",a),n==null||n.removeEventListener("abort",c),t.info(l),o())}function a(){s("stdio transport closed (stdin EOF)")}function c(){s("mcp server shutting down")}const d=e.onclose;if(e.onclose=()=>{d==null||d(),s("stdio transport closed")},r.once("end",a),r.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function yf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??Xn();o.info(`mcp server starting (${t})`);const i=new uf;mf(e,i);const a=i.listTools().map(u=>u.name);o.info({tools:a},`${a.length} tools available`);for(const u of a){const f=i.getPlan(u),g=(f==null?void 0:f.params)??[],p=g.map(m=>`${m.name}${m.required?"":"?"}: ${m.type}`).join(", ");o.info({tool:u,args:{data:g}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}const c=gf(e);if(o.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),t==="stdio"){const u=on(i,o,c),f=new Na.StdioServerTransport;return await u.connect(f),o.info("stdio transport ready"),hf(f,o,e.signal)}if(t==="sse"){const u=jr(e,t),f=new Map,g=To.createServer(Ar(o,async(p,m)=>{const v=p.url??"";if(p.method==="GET"&&v==="/sse"){const h=on(i,o,c),y=new Oa.SSEServerTransport("/messages",m);f.set(y.sessionId,y),y.onclose=()=>f.delete(y.sessionId),await h.connect(y)}else if(p.method==="POST"&&v.startsWith("/messages")){const h=new URLSearchParams(v.split("?")[1]??"").get("sessionId"),y=h?f.get(h):void 0;if(!y){m.writeHead(404),m.end("Session not found");return}await y.handlePostMessage(p,m)}else m.writeHead(404),m.end("Not found")}));return _r(g,n,r,t,o,u)}const d=jr(e,t),l=To.createServer(Ar(o,async(u,f)=>{const g=on(i,o,c),p=new Ra.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await g.connect(p),await p.handleRequest(u,f)}));return _r(l,n,r,t,o,d)}const wf={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(e){return cf(e)},run(e){return yf(e)}},ls=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],us=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],vf=new Set([...ls,...us]);function bf(e){return vf.has(e)}const ot=["uid","kind","title","status","priority"],ne=1e3,fs=50;async function po(e,t){const n=await e.getNodeByUid(t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid)throw new Ft(t);if(n.isSuperseded)throw new Mt(t,await Sf(e,n));return n}async function Sf(e,t){const n=new Set([t.id]);let r,o=t;for(;;){const s=(await e.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return r==null?void 0:r.uid;n.add(s.src);const a=(await e.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return r==null?void 0:r.uid;if(r=a,!a.isSuperseded)return a.uid;o=a}}async function D(e,t,n){if(Ne(n)){const i=await e.getNodeByUid(n);return(i==null?void 0:i.kind)!==t||i.tInvalid?null:{id:i.id,uid:i.uid,name:i.name??n,record:i}}const o=(await e.queryNodes({kind:t,name:n,liveOnly:!0,limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}async function Fe(e,t,n){var i;if(Ne(n)){const s=await D(e,"component",n);return!s||((i=s.record.metadata)==null?void 0:i.projectUid)!==t?null:s}const o=(await e.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:t}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function De(e,t){return e.getEdges({src:t})}async function ps(e,t){var c,d;const r=(c=(await e.getEdges({dst:t,rel:"owns_component"}))[0])==null?void 0:c.src;if(r===void 0)return{};const[o]=await e.getNodesByIds([r]);if(!o)return{};const s=(d=(await e.getEdges({dst:r,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:o};const[a]=await e.getNodesByIds([s]);return{component:o,project:a}}async function Ef(e,t){const n=t.expectedKind==="component"&&t.projectUid!==void 0?await Fe(e,t.projectUid,t.ref):await D(e,t.expectedKind,t.ref);if(!n)return;if(await kf(e,t.rel,t.expectedKind)){const o=await e.getEdges({src:n.id,rel:t.rel});return new Set(o.map(i=>i.dst))}const r=await e.getEdges({dst:n.id,rel:t.rel});return new Set(r.map(o=>o.src))}async function kf(e,t,n){var i;const o=(i=(await e.queryNodes({kind:"edge_kind",name:t,liveOnly:!0,limit:1}))[0])==null?void 0:i.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function Af(e,t){return(await e.queryNodes({kind:t,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function jf(e,t){const n=e.length+1,r=t.length+1,o=Array.from({length:n},()=>new Array(r).fill(0));for(let i=0;i<n;i+=1)o[i][0]=i;for(let i=0;i<r;i+=1)o[0][i]=i;for(let i=1;i<n;i+=1)for(let s=1;s<r;s+=1)o[i][s]=e[i-1]===t[s-1]?o[i-1][s-1]:1+Math.min(o[i-1][s],o[i][s-1],o[i-1][s-1]);return o[e.length][t.length]}function ms(e,t,n=3){const r=Math.max(2,Math.ceil(e.length/2));return t.map(o=>({candidate:o,distance:jf(e.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=r).sort((o,i)=>o.distance-i.distance).slice(0,n).map(o=>o.candidate)}async function Ce(e,t){const n=await Af(e,t.catalogKind),r=new Set,o=[];for(const i of t.refs){const s=await D(e,t.catalogKind,i);if(!s){o.push(i);continue}const a=await e.getEdges({dst:s.id,rel:t.rel});for(const c of a)r.add(c.src)}if(o.length>0){const i=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=o.map(a=>{const c=ms(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new je(t.field,`unknown ${t.catalogKind} value(s): ${s} — no live "${t.catalogKind}" catalog row matches (existing ${t.catalogKind} values: ${i})`)}return r}function _f(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}function mo(e){if(e){for(const t of e)if(!bf(t))throw new je("fields",`unknown field "${t}" — known fields: ${[...ls,...us].join(", ")}`)}}function Oe(e){var t;return((t=e==null?void 0:e.metadata)==null?void 0:t.terminal)===!0}async function Nf(e,t,n){const r=n.find(l=>l.rel==="has_kind"&&l.src===t),o=n.find(l=>l.rel==="has_status"&&l.src===t),i=n.find(l=>l.rel==="has_priority"&&l.src===t),s=n.find(l=>l.rel==="authored_by"&&l.src===t),a=[r==null?void 0:r.dst,o==null?void 0:o.dst,i==null?void 0:i.dst,s==null?void 0:s.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await e.getNodesByIds(a),d=new Map(c.map(l=>[l.id,l]));return{kind:r?d.get(r.dst):void 0,status:o?d.get(o.dst):void 0,priority:i?d.get(i.dst):void 0,author:s?d.get(s.dst):void 0}}async function Of(e,t,n){const r=n.filter(i=>i.rel==="has_citation"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c,d,l;return{uid:i.uid,file:typeof((s=i.metadata)==null?void 0:s.target)=="string"?i.metadata.target:i.name??"",lines:typeof((a=i.metadata)==null?void 0:a.line)=="string"?i.metadata.line:void 0,context:i.content||void 0,symbol:typeof((c=i.metadata)==null?void 0:c.symbol)=="string"?i.metadata.symbol:void 0,sha:typeof((d=i.metadata)==null?void 0:d.sha)=="string"?i.metadata.sha:"unverified",at:typeof((l=i.metadata)==null?void 0:l.at)=="string"?i.metadata.at:i.tCreated}})}async function Rf(e,t,n){const r=n.filter(i=>i.rel==="has_note"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c;return{uid:i.uid,author:typeof((s=i.metadata)==null?void 0:s.author)=="string"?i.metadata.author:"",text:typeof((a=i.metadata)==null?void 0:a.text)=="string"?i.metadata.text:i.content,at:typeof((c=i.metadata)==null?void 0:c.at)=="string"?i.metadata.at:i.tCreated}})}async function If(e,t,n){const r=(n??await De(e,t)).filter(s=>s.rel==="audits"&&s.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,g;return{uid:s.uid,actor:typeof((a=s.metadata)==null?void 0:a.actor)=="string"?s.metadata.actor:"",action:typeof((c=s.metadata)==null?void 0:c.action)=="string"?s.metadata.action:s.name??"",from:typeof((d=s.metadata)==null?void 0:d.from)=="string"?s.metadata.from:void 0,to:typeof((l=s.metadata)==null?void 0:l.to)=="string"?s.metadata.to:void 0,note:typeof((u=s.metadata)==null?void 0:u.note)=="string"?s.metadata.note:void 0,sha:typeof((f=s.metadata)==null?void 0:f.sha)=="string"?s.metadata.sha:"",at:typeof((g=s.metadata)==null?void 0:g.at)=="string"?s.metadata.at:s.tCreated}}).sort((s,a)=>s.at.localeCompare(a.at))}async function Tf(e,t){const n=await e.getEdges({dst:t,rel:"blocks"});if(n.length===0)return[];const r=n.map(s=>s.src),o=await e.getNodesByIds(r),i=await gs(e,o);return o.filter(s=>!Oe(i.get(s.id))).map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=i.get(s.id))==null?void 0:a.name)??""}})}async function $f(e,t,n){const r=(n??await De(e,t)).filter(c=>c.rel==="relates_to"&&c.src===t),o=await e.getEdges({dst:t,rel:"relates_to"}),i=new Set([...r.map(c=>c.dst),...o.map(c=>c.src)]);if(i.size===0)return[];const s=await e.getNodesByIds([...i]),a=await gs(e,s);return s.map(c=>{var d;return{uid:c.uid,title:c.name??"",status:((d=a.get(c.id))==null?void 0:d.name)??""}})}async function gs(e,t){if(t.length===0)return new Map;const n=new Set(t.map(d=>d.id)),r=await e.getEdges({rel:"has_status"}),o=new Map;for(const d of r)n.has(d.src)&&!o.has(d.src)&&o.set(d.src,d.dst);const i=[...new Set(o.values())];if(i.length===0)return new Map;const s=await e.getNodesByIds(i),a=new Map(s.map(d=>[d.id,d])),c=new Map;for(const[d,l]of o){const u=a.get(l);u&&c.set(d,u)}return c}async function hs(e,t,n,r={}){var p,m,v;const o={uid:t.uid},i=h=>n.includes(h),s=i("kind")||i("status")||i("priority")||i("author"),a=i("project")||i("component"),c=i("citations"),d=i("notes"),l=i("auditTrail"),u=i("blockers"),f=i("related"),g=r.outgoingEdges??(s||c||d||l||f?await De(e,t.id):void 0);if(i("title")&&(o.title=t.name??""),i("createdAt")&&(o.createdAt=t.tCreated),i("updatedAt")&&(o.updatedAt=t.tValid),i("assignee")){const h=(p=t.metadata)==null?void 0:p.assignee;typeof h=="string"&&(o.assignee=h)}if(i("gitContext")){const h=(m=t.metadata)==null?void 0:m.gitContext;typeof h=="string"&&h.length>0&&(o.gitContext=h)}if(i("closedAt")){const h=(v=t.metadata)==null?void 0:v.closedAt;typeof h=="string"&&(o.closedAt=h)}if(i("body")&&(o.body=t.content),s&&g){const h=await Nf(e,t.id,g);i("kind")&&h.kind&&(o.kind=h.kind.name??""),i("status")&&h.status&&(o.status=h.status.name??""),i("priority")&&h.priority&&(o.priority=h.priority.name??""),i("author")&&h.author&&(o.author=h.author.name??"")}if(a){const{project:h,component:y}=await ps(e,t.id);i("project")&&h&&(o.project=h.uid),i("component")&&y&&(o.component=y.uid)}return c&&g&&(o.citations=await Of(e,t.id,g)),d&&g&&(o.notes=await Rf(e,t.id,g)),l&&g&&(o.auditTrail=await If(e,t.id,g)),u&&(o.blockers=await Tf(e,t.id)),f&&g&&(o.related=await $f(e,t.id,g)),i("_score")&&r.score!==void 0&&(o._score=r.score),o}async function Qe(e,t,n,r){return Promise.all(t.map(o=>hs(e,o,n,{score:r==null?void 0:r.get(o.uid)})))}const Cf=.0050125;function Pf(e){if(e===void 0)return fs;if(!Number.isInteger(e)||e<=0||e>ne)throw new je("limit",`must be a positive integer ≤ ${ne}, got ${e}`);return e}async function xf(e,t){const n=new Set;for(const r of t.refs){const o=await Ef(e,{rel:t.rel,expectedKind:t.expectedKind,ref:r});if(o)for(const i of o)n.add(i)}return n}async function Lf(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function Uf(e,t){if(t.project===void 0&&t.component===void 0)return;let n,r;if(t.project!==void 0){const c=await D(e,"project",t.project);if(!c)return new Set;n=c.uid;const d=await e.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const u of d){const f=await e.getEdges({src:u.dst,rel:"owns_component"});for(const g of f)l.add(g.dst)}r=l}if(t.component===void 0)return r;const o=n!==void 0?await Fe(e,n,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"}),s=new Set(i.map(c=>c.dst));if(!r)return s;const a=new Set;for(const c of s)r.has(c)&&a.add(c);return a}function Df(e){var r,o,i,s;const t={};e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until}));const n={};return Object.keys(t).length>0&&(n.metadata=t),(r=e.createdAt)!=null&&r.since&&(n.tCreatedAfter=e.createdAt.since),(o=e.createdAt)!=null&&o.until&&(n.tCreatedBefore=e.createdAt.until),(i=e.updatedAt)!=null&&i.since&&(n.tUpdatedAfter=e.updatedAt.since),(s=e.updatedAt)!=null&&s.until&&(n.tUpdatedBefore=e.updatedAt.until),Object.keys(n).length>0?n:void 0}async function ys(e,t){if(!t)return;const n=[],r=await Uf(e,t);if(r!==void 0&&n.push(r),t.kind!==void 0){const c=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ce(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await Lf(e,t.status));else{const c=Array.isArray(t.status)?t.status:[t.status];n.push(await Ce(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(t.priority!==void 0){const c=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Ce(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}t.author!==void 0&&n.push(await xf(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]}));const o=Df(t);if(n.length===0&&!o)return;let i;if(n.length>0){let[c]=n;for(const d of n.slice(1)){const l=new Set;for(const u of c)d.has(u)&&l.add(u);c=l}if(i=c,i.size===0)return new Set}const s={kind:"issue",liveOnly:!0,isSuperseded:!1,...i?{ids:[...i]}:{},...o},a=await e.queryNodes(s);return new Set(a.map(c=>c.id))}const Mf=4;async function Ff(e,t){if(t.length===0)return[];const n=t.map(s=>s.id),r={ids:n,isSuperseded:!1,limit:n.length},o=await e.queryNodes(r),i=new Set(o.map(s=>s.id));return t.filter(s=>i.has(s.id))}async function Bf(e,t){var s;if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(((s=t.candidateIds)==null?void 0:s.size)===0)return[];const n=t.candidateIds?{ids:[...t.candidateIds]}:{kind:"issue"},r={text:t.text,vec:t.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:t.decayPerHour??Cf}],filters:n},o=[];let i=t.limit;for(let a=0;a<Mf;a++){const c=await e.search.backend.searchRanked(r,i);if(o.length=0,o.push(...await Ff(e.graph,c)),o.length>=t.limit||c.length<i)break;i*=2}return o.slice(0,t.limit)}async function qf(e,t){var v,h;const{graph:n}=e;if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");mo(t.fields);const r=t.fields??ot,o=Pf(t.limit);let i,s;if(((v=t.filter)==null?void 0:v.anchor)!==void 0)s=await po(n,t.filter.anchor),i=`${s.name??""}
199
+ ${s.content}`.trim();else if(((h=t.filter)==null?void 0:h.semantic)!==void 0)i=t.filter.semantic;else throw new I("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await ys(n,t.filter);if(a&&s&&a.delete(s.id),(a==null?void 0:a.size)===0)return[];const c=await e.search.embedQuery(i),d=s?o+1:o,l=await Bf(e,{text:i,vec:c,candidateIds:a,limit:d}),u=(s?l.filter(y=>y.id!==s.id):l).slice(0,o);if(u.length===0)return[];const f=await n.getNodesByIds(u.map(y=>y.id)),g=new Map(f.map(y=>[y.id,y])),p=u.map(y=>g.get(y.id)).filter(y=>y!==void 0),m=new Map(u.map(y=>{var w;return[(w=g.get(y.id))==null?void 0:w.uid,y.score]}).filter(y=>y[0]!==void 0));return Qe(n,p,r,m)}function Kf(e){return e.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function Hf(e){const t=typeof e.gitContext=="string"&&e.gitContext.length>0?e.gitContext:void 0,n=e.citations??[];if(t===void 0&&n.length===0)return[];const r=["",t!==void 0?`Citations: [${Kf(t)}]`:"Citations:"];for(const o of n){const i=o.lines?`${o.file}:${o.lines}`:o.file;r.push(`- [${i} sha:${o.sha}]`)}return r}function Vf(e){const t=[];return e.kind!==void 0&&t.push(`kind: ${e.kind}`),e.status!==void 0&&t.push(`status: ${e.status}`),e.priority!==void 0&&t.push(`priority: ${e.priority}`),e.assignee!==void 0&&t.push(`assignee: ${e.assignee}`),e.project!==void 0&&t.push(`project: ${e.project}`),e.component!==void 0&&t.push(`component: ${e.component}`),t.length>0?t.join(" · "):void 0}function Gf(e){const t=[`## ${e.title??"(untitled)"}`],n=Vf(e);return n!==void 0&&t.push(n),e.body!==void 0&&e.body.length>0&&t.push("",e.body),t.push(...Hf(e)),t.join(`
200
+ `)}function Jf(e){return e.length===0?`_No matching issues._
201
+ `:`${e.map(Gf).join(`
184
202
 
185
203
  `)}
186
- `}function gj(e){return e.split(`
187
- `).map(yj).join(`
188
- `)}function yj(e){return/^###\s/.test(e)?`##${e}`:/^##\s/.test(e)?`##${e}`:e}function ch(e,t){let n=`### Archived — resolved/terminal backlog items relocated in batch (${t})
189
-
190
- `;return n+="> Moved via `@adhd/backlog`'s `archiveResolved` (canonical terminal statuses: FIXED/RESOLVED/DONE/\n",n+=`> SHIPPED/VERIFIED/REMOVED/MITIGATED/SUPERSEDED/INVALID/DUPLICATE/WONTFIX). The graph node itself is
191
- `,n+=`> NEVER deleted — this is a rendered snapshot; full history remains queryable via auditTrail.
192
-
193
- `,n+=e.map(r=>gj(ih(r))).join(`
194
-
195
- `),n+=`
196
- `,n}function uh(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:eh(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}function $j(){const e=T.dirname(Ln.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"package.json");return C.existsSync(t)?t:T.join(e,"..","package.json")}function lh(){const e=$j(),t=JSON.parse(C.readFileSync(e,"utf8"));return{name:t.name,version:t.version}}async function Ya(e,t,n){const r=await Yp(e.store,t,n);if(!r)throw await Oe(e.store,t,n);return r}async function fh(e,t){return Wa(e.store,t)}async function dh(e,t,n){const r=await Yp(e.store,t,n);if(r)return r;const o=await Oe(e.store,t,n);if(o.foundInRepos.length>0)throw o;return null}async function ph(e,t,n,r){return Zp(e.store,t,n,r)}async function hh(e,t){return ut(e.store,t??{})}async function mh(e,t,n,r){await GA(e.store,t,n,r)}async function gh(e,t){return NA(e.store,t??{})}async function yh(e,t,n){return OA(e.store,t??{},n??20)}async function $h(e,t){return _A(e.store,t??{})}async function vh(e,t,n){return kA(e.store,t,n)}async function wh(e,t){return Hp(e.store,t??{})}async function bh(e,t){return AA(e.store,t??{})}async function Eh(e,t,n){return IA(e.store,t,n??{})}async function Sh(e,t,n,r,o){const s=await Ya(e,t,n);return zp(e.store,s.nodeId,r,o??{})}async function Nh(e,t,n,r){const o=await Ya(e,t,n);return RA(e.store,o.nodeId,r)}async function Oh(e,t,n,r,o){const s=await Ya(e,t,n);return MA(e.store,s.nodeId,r,o??{})}async function kh(e,t,n,r,o){return ej(e.store,t,n,r,o)}async function _h(e,t,n,r){return LA(e.store,t,n,r)}async function Ah(e,t,n,r,o){return Dn(e.store,t,n,r,o)}async function jh(e,t,n,r){return UA(e.store,t,n,r)}async function Ih(e,t,n,r,o){return BA(e.store,t,n,r,o)}async function xh(e,t,n,r,o){return DA(e.store,t,n,r,o)}async function Ph(e,t,n){const r=await FA(e.store,t,n??{}),o=r.length>0?ch(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function Th(e,t,n,r){await JA(e.store,t,n,r)}async function Ch(e,t,n,r){await HA(e.store,t,n,r)}async function Rh(e,t,n,r){await zA(e.store,t,n,r)}async function Mh(e,t,n,r,o){return WA(e.store,t,n,r,o)}async function Dh(e,t,n,r){return YA(e.store,t,n,r)}async function Lh(e,t,n,r,o){return QA(e.store,t,n,r,o)}async function Uh(e,t,n,r){return Xp(e.store,t,n,r)}async function Bh(e,t,n,r){await Js(e.store,t,n,r)}async function vj(e,t,n,r,o){return sj(e.store,t,n,r,o??!0)}async function Fh(e,t){const n=C.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=sh(n),s=uh(r),i=t.sourcePath??t.path,a=await Gp(e.store),c=a.size>0&&!a.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...a].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0,u={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o,...c!==void 0?{repoWarning:c}:{}};if(t.dryRun)return u;for(const l of s)try{const f=await Wa(e.store,{family:l.humanId.replace(/-\d+$/,""),idOverride:l.humanId,title:l.title,body:l.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...l.priority!==void 0?{priority:l.priority}:{},force:!0});if(f.created&&t.plan!==void 0&&await Js(e.store,t.repo,l.humanId,t.plan),f.created&&l.status!=="OPEN"&&await Dn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...Ir(l.status)?{citations:[{file:t.path}]}:{},...xr(l.status)?{reason:`imported from markdown at status ${l.status}`}:{}}),f.created){u.created+=1;continue}u.skippedDuplicates+=1;const p=f.duplicateCandidates[0]??f.item;let h=!1;if(p.importedFrom===void 0||p.importedFrom===i){const m={};p.title!==l.title&&(m.title=l.title),p.body!==l.body&&(m.body=l.body),p.importedFrom===void 0&&(m.importedFrom=i),t.projectPath!==void 0&&p.projectPath!==t.projectPath&&(m.projectPath=t.projectPath),Object.keys(m).length>0&&(await Zp(e.store,t.repo,l.humanId,m),h=!0),l.priority!==void 0&&p.priority!==l.priority&&(await Xp(e.store,t.repo,l.humanId,l.priority),h=!0),p.status!==l.status&&(await Dn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...Ir(l.status)?{citations:[{file:t.path}]}:{},...xr(l.status)?{reason:`re-imported from markdown at status ${l.status}`}:{}}),h=!0)}t.plan!==void 0&&p.plan!==t.plan&&(await Js(e.store,t.repo,l.humanId,t.plan),h=!0),h&&(u.updated+=1)}catch(f){u.errors.push({humanId:l.humanId,message:f instanceof Error?f.message:String(f)})}return u}async function qh(e,t){let r=(await Kp(e.store,{...t,excludeArchived:!0})).map(se);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Be(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Be(o.status))),ah(r)}async function Vh(e,t){return ut(e.store,t??{})}async function Kh(e,t,n){return xA(e.store,t,n)}const wj={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function Gh(e){const t=e.env.config.migration.phase;return Jh(t)}function Jh(e){const t=wj[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function Hh(e,t){const n=dA(e.env,t,e.adhdRoot);return{...Jh(t),configPath:n}}async function zh(e){return lh()}const bj=Object.freeze(Object.defineProperty({__proto__:null,addCitation:jh,addDependency:Th,appendNote:Ih,archiveResolved:Ph,assignItem:kh,attachToPlan:Bh,auditTrail:Kh,blockers:vh,claimItem:Sh,createItem:fh,dependencyGraph:wh,exportJson:Vh,getItem:dh,importFromMarkdown:Fh,linkRelated:Rh,listItems:hh,mergeItems:Lh,migrateRepo:vj,migrationStatus:Gh,readyItems:$h,releaseClaim:Oh,removeDependency:Ch,renderToMarkdown:qh,renewClaim:Nh,resolveItem:xh,setMigrationPhase:Hh,setPriority:Uh,softDeleteItem:mh,splitItem:Dh,spotlight:yh,staleClaims:Eh,startWork:_h,stats:gh,supersedeItem:Mh,topoOrder:bh,transitionStatus:Ah,updateItem:ph,version:zh},Symbol.toStringTag,{value:"Module"}));class kl extends Error{constructor(t,n){super(`backlog serve: refusing to start — another "backlog serve" instance (pid ${t}) already holds the writer lock for this store (${n}). Two concurrent servers against the same store is the exact condition that corrupted this database before (upstream turso race tursodatabase/turso#7833/#8348). Stop the other instance first, or if you are certain pid ${t} is gone, remove the stale lock: ${n}`),this.name="ServeLockHeldError",this.holderPid=t,this.lockPath=n}}function Ej(e){return e!==":memory:"}function Sj(e){const t=T.resolve(e);if(C.existsSync(t))try{return C.realpathSync(t)}catch{return t}const n=T.dirname(t);if(C.existsSync(n))try{return T.resolve(C.realpathSync(n),t.slice(n.length+1))}catch{return t}return t}function Nj(e){return`${Sj(e)}.serve.lock`}function Hs(e){try{const t=C.readFileSync(e,"utf8").split(`
197
- `,1)[0]??"",n=Number.parseInt(t,10);return Number.isInteger(n)&&n>0?n:null}catch{return null}}function Oj(e){try{return process.kill(e,0),!0}catch{return!1}}function kj(e){const t=C.openSync(e,C.constants.O_WRONLY|C.constants.O_CREAT|C.constants.O_EXCL,384);try{C.writeSync(t,`${process.pid}
198
- ${new Date().toISOString()}
199
- `)}finally{C.closeSync(t)}}function _j(e){const t=Nj(e),n=()=>{try{return kj(t),"created"}catch(s){if(s.code==="EEXIST")return"exists";throw s}};if(n()==="created")return _l(t);const r=Hs(t);if(r!==null&&Oj(r))throw new kl(r,t);try{C.unlinkSync(t)}catch{}if(n()==="created")return _l(t);const o=Hs(t);throw new kl(o??-1,t)}function _l(e){let t=!1;return{release:()=>{if(!t){t=!0;try{Hs(e)===process.pid&&C.unlinkSync(e)}catch{}}}}}function zs(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function Wh(){if(!process.env.VITEST)return;const e=()=>{},t={info:e,error:e,debug:e,fatal:e,warn:e,trace:e};return t.child=()=>t,t}function Yh(){const e=T.dirname(Ln.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href));return C.existsSync(T.join(e,"client.d.ts"))?e:T.join(e,"..","dist")}function Al(e){if(!e||typeof e!="object")return e;const t={},n=o=>{if(Array.isArray(o)){for(const i of o)n(i);return}if(!o||typeof o!="object")return;const s=o;for(const i of["definitions","$defs"]){const a=s[i];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,u]of Object.entries(a))c in t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;const r=(o,s)=>{if(Array.isArray(o))return o.map(u=>r(u,s));if(!o||typeof o!="object")return o;const i=o,a=i.$ref;if(typeof a=="string"){const u=a.replace(/^#\/(?:definitions|\$defs)\//,"");return s.has(u)||!(u in t)?{}:r(t[u],new Set([...s,u]))}const c={};for(const[u,l]of Object.entries(i))u==="definitions"||u==="$defs"||(c[u]=r(l,s));return c};return r(e,new Set)}const Aj=Pl.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href),jj=Aj("@adhd/apigen-core-client/package.json").version;function Ij(){return QS()}function xj(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function Pj(){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:QN({cache:Ij(),extractorVersion:jj})}}}}let jl;function Tj(){return jl??(jl=VN(xj()?[Pj()]:[],e=>{var t;return PN({sourceFile:e.source,namespace:e.namespace,tsconfig:typeof((t=e.extractorOptions)==null?void 0:t.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0,dropFileSegment:!0})})),jl}async function Cj(){const e=T.join(Yh(),"client.d.ts");if(!C.existsSync(e))throw new Error(`@adhd/backlog: cannot mount — ${e} does not exist. Run "nx build backlog" first (extract() needs the built .d.ts for type information).`);return Tj()({source:e,host:"ts",namespace:"backlog",extractorOptions:{}})}async function Qa(e){const t=typeof e=="function"?e:()=>e,n=await Cj(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:Al(s.input),output:Al(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:sN(r,[]),importPath:T.join(Yh(),"client.js"),fns:bj,createClient:async()=>t()},operations:n}}async function Qh(e){const t=va({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();let n,r;const o=wa(t),s=Ej(o)?_j(o):void 0,i=()=>(n||(n=nf(r).finally(()=>s==null?void 0:s.release())),n),a=zy()?void 0:rf(i);try{r=await hi(o,t.config.db.busyTimeoutMs)}catch(h){throw s==null||s.release(),a==null||a.dispose(),h}const c={store:r,env:t},{pkg:u,operations:l}=await Qa(c),f=Wh(),p=[];(e.transport==="http"||e.transport==="both")&&p.push(zs(Sk)({packages:[u],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[Dk,cs]},signal:e.signal,operations:l,logger:f})),(e.transport==="mcp"||e.transport==="both")&&p.push(zs(uA)({packages:[u],outputDir:"",options:{transport:"stdio",usePlugins:[cs]},signal:e.signal,operations:l,logger:f}));try{await Promise.all(p)}finally{a==null||a.dispose(),await i()}}const Qt=["claude","codex","opencode"],Rj={claude:".claude",codex:".codex",opencode:".opencode"};function Zh(e,t){return t?T.join(e,".codex"):process.env.CODEX_HOME??T.join(e,".codex")}function Mj(e,t,n,r){if(t==="project")return T.join(n,Rj[e],"skills");const o=r??Ue.homedir();return e==="claude"?T.join(o,".claude","skills"):e==="codex"?T.join(Zh(o,r),"skills"):T.join(o,".config","opencode","skills")}function Dj(){const e=T.dirname(Ln.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"skill","SKILL.md");return C.existsSync(t)?t:T.join(e,"..","skill","SKILL.md")}function Lj(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...Qt]:[t];for(const o of r)if(!Qt.includes(o))throw new Error(`backlog install-skill: --host must be one of ${Qt.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function Xh(e,t=process.cwd(),n){const{hosts:r,scope:o}=Lj(e);return em(r,o,t,n)}function em(e,t,n,r){const o=Dj();if(!C.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=C.readFileSync(o,"utf8"),i=T.dirname(Ln.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),a=T.join(i,"package.json"),c=C.existsSync(a)?a:T.join(i,"..","package.json"),u=JSON.parse(C.readFileSync(c,"utf8")),l=[];for(const f of e){const p=T.join(Mj(f,t,n,r),"backlog");C.mkdirSync(p,{recursive:!0});const h=T.join(p,"SKILL.md");C.writeFileSync(h,s,"utf8"),C.writeFileSync(T.join(p,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
200
- `,"utf8"),l.push({host:f,scope:t,path:h})}return l}async function tm(e){const t=Xh(e);console.log(JSON.stringify({installed:t}))}const Za=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Uj(e){if(!C.existsSync(e))return{};const t=C.readFileSync(e,"utf8").trim();if(t==="")return{};const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${e} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function nm(e,t,n,r){const o=Uj(e),s=o[t],i=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};i[n]=r,o[t]=i,C.mkdirSync(T.dirname(e),{recursive:!0}),C.writeFileSync(e,JSON.stringify(o,null,2)+`
201
- `,"utf8")}function Bj(e,t,n){if(e==="project")return T.join(t,".mcp.json");const r=Ue.homedir();return T.join(r,".claude.json")}function Fj(e,t,n){if(e==="project")return T.join(t,"opencode.json");const r=Ue.homedir();return T.join(r,".config","opencode","opencode.json")}function qj(e,t,n){if(e==="project")return T.join(t,".codex","config.toml");const r=Ue.homedir();return T.join(Zh(r,n),"config.toml")}function Vj(e,t,n){var u,l;const r=`[${t}]`,o=e.length>0?e.split(`
202
- `):[],s=o.findIndex(f=>f.trim()===r),i=[r,...n];if(s===-1){if(o.length===0||o.every(f=>f.trim()===""))return i.join(`
204
+ `}function xn(e){var t,n,r,o;return{uid:e.uid,name:e.name??"",path:typeof((t=e.metadata)==null?void 0:t.path)=="string"?e.metadata.path:void 0,repoUrl:typeof((n=e.metadata)==null?void 0:n.repoUrl)=="string"?e.metadata.repoUrl:void 0,monorepo:typeof((r=e.metadata)==null?void 0:r.monorepo)=="boolean"?e.metadata.monorepo:void 0,description:typeof((o=e.metadata)==null?void 0:o.description)=="string"?e.metadata.description:void 0}}function Ln(e){var t,n,r;return{uid:e.uid,name:e.name??"",projectUid:typeof((t=e.metadata)==null?void 0:t.projectUid)=="string"?e.metadata.projectUid:"",path:typeof((n=e.metadata)==null?void 0:n.path)=="string"?e.metadata.path:void 0,description:typeof((r=e.metadata)==null?void 0:r.description)=="string"?e.metadata.description:void 0}}function Un(e){var t,n,r;return{uid:e.uid,locType:typeof((t=e.metadata)==null?void 0:t.locType)=="string"?e.metadata.locType:"path",value:typeof((n=e.metadata)==null?void 0:n.value)=="string"?e.metadata.value:e.name??"",componentUid:typeof((r=e.metadata)==null?void 0:r.componentUid)=="string"?e.metadata.componentUid:""}}async function Wf(e,t){if((t==null?void 0:t.project)!==void 0){const r=await D(e,"project",t.project);return r?[xn(r.record)]:[]}return(await e.queryNodes({kind:"project",liveOnly:!0})).map(xn)}async function zf(e,t){if((t==null?void 0:t.project)!==void 0){const r=await D(e,"project",t.project);return r?(await e.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:r.uid}}})).map(Ln):[]}return(await e.queryNodes({kind:"component",liveOnly:!0})).map(Ln)}async function Yf(e,t){if((t==null?void 0:t.component)!==void 0){const r=t.project!==void 0?await(async()=>{const i=await D(e,"project",t.project);return i?Fe(e,i.uid,t.component):null})():await D(e,"component",t.component);return r?(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:r.uid}}})).map(Un):[]}return(await e.queryNodes({kind:"location",liveOnly:!0})).map(Un)}async function rn(e,t){var d,l,u,f,g,p,m,v,h;if(t.registry==="project"){const y=await D(e,"project",t.name);if(!y)throw new G("project",t.name);const w=await e.getEdges({src:y.id,rel:"owns_project"}),b=w.length>0?await e.getNodesByIds(w.map(j=>j.dst),{liveOnly:!0}):[],E=(await Promise.all(b.map(j=>e.getEdges({src:j.id,rel:"has_location"})))).flatMap(j=>j.map(N=>N.dst)),A=E.length>0?await e.getNodesByIds(E,{liveOnly:!0}):[];return{...xn(y.record),components:b.map(j=>{var N;return{name:j.name??"",path:typeof((N=j.metadata)==null?void 0:N.path)=="string"?j.metadata.path:void 0}}),locations:A.map(j=>{var N,_;return{locType:typeof((N=j.metadata)==null?void 0:N.locType)=="string"?j.metadata.locType:"path",value:typeof((_=j.metadata)==null?void 0:_.value)=="string"?j.metadata.value:j.name??""}})}}if(t.registry==="component"){const y=(d=t.filter)==null?void 0:d.project,w=y!==void 0?await(async()=>{const N=await D(e,"project",y);if(!N)throw new G("project",y);return Fe(e,N.uid,t.name)})():await D(e,"component",t.name);if(!w)throw new G("component",t.name);const b=typeof((l=w.record.metadata)==null?void 0:l.projectUid)=="string"?w.record.metadata.projectUid:void 0,S=b?await e.getNodeByUid(b):null,E=S&&!S.tInvalid?S:null,A=await e.getEdges({src:w.id,rel:"has_location"}),j=A.length>0?await e.getNodesByIds(A.map(N=>N.dst),{liveOnly:!0}):[];return{...Ln(w.record),project:{name:(E==null?void 0:E.name)??"",path:typeof((u=E==null?void 0:E.metadata)==null?void 0:u.path)=="string"?E.metadata.path:void 0,repoUrl:typeof((f=E==null?void 0:E.metadata)==null?void 0:f.repoUrl)=="string"?E.metadata.repoUrl:void 0},locations:j.map(N=>{var _,R;return{locType:typeof((_=N.metadata)==null?void 0:_.locType)=="string"?N.metadata.locType:"path",value:typeof((R=N.metadata)==null?void 0:R.value)=="string"?N.metadata.value:N.name??""}})}}if(!Ne(t.name))throw new I("name","a location has no name — pass its uid");const n=await e.getNodeByUid(t.name);if((n==null?void 0:n.kind)!=="location"||n.tInvalid)throw new G("location",t.name);const r=typeof((g=n.metadata)==null?void 0:g.componentUid)=="string"?n.metadata.componentUid:void 0,o=r?await e.getNodeByUid(r):null,i=o&&!o.tInvalid?o:null,s=typeof((p=i==null?void 0:i.metadata)==null?void 0:p.projectUid)=="string"?i.metadata.projectUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;return{...Un(n),component:{name:(i==null?void 0:i.name)??"",path:typeof((m=i==null?void 0:i.metadata)==null?void 0:m.path)=="string"?i.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((v=c==null?void 0:c.metadata)==null?void 0:v.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((h=c==null?void 0:c.metadata)==null?void 0:h.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function Xf(e){try{return new URL(e),!0}catch{return!1}}function Qf(e){return Xf(e)?"url":e.includes("/")||e.includes(".")||e.startsWith("~")?"path":"tool"}async function Zf(e,t){var f,g,p,m,v,h;const n=Qf(t);let r=(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:t}},limit:1}))[0],o,i=!1;if(!r&&n==="path"){const y=await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:ne+1});i=y.length>ne;const b=(i?y.slice(0,ne):y).find(S=>{var A;const E=typeof((A=S.metadata)==null?void 0:A.value)=="string"?S.metadata.value:"";return E.endsWith(t)||t.endsWith(E)});b&&(r=b,o="matched by path suffix/prefix fallback, not an exact value match")}if(!r)throw new G("location",i?`${t} (path suffix/prefix fallback scanned only the first ${ne} live path locations; a match may exist beyond this cap)`:t);const s=typeof((f=r.metadata)==null?void 0:f.componentUid)=="string"?r.metadata.componentUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new G("component",s??"(unresolved)");const d=typeof((g=c.metadata)==null?void 0:g.projectUid)=="string"?c.metadata.projectUid:void 0,l=d?await e.getNodeByUid(d):null,u=l&&!l.tInvalid?l:null;return u?{project:{uid:u.uid,name:u.name??"",path:typeof((p=u.metadata)==null?void 0:p.path)=="string"?u.metadata.path:void 0,repoUrl:typeof((m=u.metadata)==null?void 0:m.repoUrl)=="string"?u.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((v=c.metadata)==null?void 0:v.path)=="string"?c.metadata.path:void 0},location:{uid:r.uid,locType:n,value:typeof((h=r.metadata)==null?void 0:h.value)=="string"?r.metadata.value:t},hint:o}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:r.uid,locType:n,value:t},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function rt(e){if(e===void 0)return fs;if(!Number.isInteger(e)||e<=0||e>ne)throw new je("limit",`must be a positive integer ≤ ${ne}, got ${e}`);return e}function ep(e){var t,n;if(e.after!==void 0){if(e.sort!==void 0)throw new I("sort","sort is incompatible with keyset pagination (after) — request the first page unsorted, or page by offset if a non-insertion order is required");if(((t=e.filter)==null?void 0:t.grep)!==void 0||((n=e.filter)==null?void 0:n.semantic)!==void 0)throw new I("after","after (keyset) is incompatible with grep/semantic search — these route through the ranked search primitives, which have no rowid-ordered keyset contract; page a searched result set by sort + offset (rule 6) instead")}}async function tp(e,t){const n=new Set;for(const r of t.refs){const o=await D(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function ws(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function it(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await D(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await Fe(e,r,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ce(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await ws(e,t.status));else{const o=Array.isArray(t.status)?t.status:[t.status];n.push(await Ce(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(t.priority!==void 0){const o=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Ce(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(t.author!==void 0&&n.push(await tp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]})),t.plan!==void 0){const o=await D(e,"issue",t.plan);if(!o)return new Set;const i=await e.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(i.map(s=>s.src)))}if(t.projectPath!==void 0){const o=await e.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:t.projectPath}}});if(o.length===0)return new Set;const i=new Set;for(const s of o){const a=await e.getEdges({src:s.id,rel:"owns_component"});for(const c of a)i.add(c.dst)}n.push(i)}return _f(n)}function np(e){if(!e)return;const t={};return e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until})),Object.keys(t).length>0?t:void 0}function op(e){if(e==="created")return"tCreated";if(e==="updated")return"tValid"}async function rp(e,t,n){const r=await Promise.all(t.map(d=>e.getEdges({src:d.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(d=>d.map(l=>l.dst)))],i=o.length>0?await e.getNodesByIds(o):[],s=new Map(i.map(d=>{var l;return[d.id,typeof((l=d.metadata)==null?void 0:l.rank)=="number"?d.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;t.forEach((d,l)=>{var f;const u=(f=r[l][0])==null?void 0:f.dst;a.set(d.id,u!==void 0?s.get(u)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...t].sort((d,l)=>a.get(d.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function ip(e,t){var w,b,S,E,A,j,N,_,R,T,C,q;const{graph:n}=e;ep(t),mo(t.fields);const r=rt(t.limit),o=t.fields??ot;if((t.sort==="relevance"||t.sort==="textMatch")&&((w=t.filter)==null?void 0:w.grep)===void 0&&((b=t.filter)==null?void 0:b.semantic)===void 0)throw new je("sort",`"${t.sort}" requires filter.grep or filter.semantic`);const i=await it(n,t.filter);if((i==null?void 0:i.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:r}};const s=np(t.filter),a=(S=t.filter)==null?void 0:S.grep,c=(E=t.filter)==null?void 0:E.semantic,d={kind:"issue",isSuperseded:!1,...i?{ids:[...i]}:{},...s?{metadata:s}:{},...(j=(A=t.filter)==null?void 0:A.createdAt)!=null&&j.since?{tCreatedAfter:t.filter.createdAt.since}:{},...(_=(N=t.filter)==null?void 0:N.createdAt)!=null&&_.until?{tCreatedBefore:t.filter.createdAt.until}:{},...(T=(R=t.filter)==null?void 0:R.updatedAt)!=null&&T.since?{tUpdatedAfter:t.filter.updatedAt.since}:{},...(q=(C=t.filter)==null?void 0:C.updatedAt)!=null&&q.until?{tUpdatedBefore:t.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let x,P;const Y=t.offset??0,Jt=Y+r;if(a!==void 0){const K=await n.searchNodes(a,{limit:Jt,filter:d});P=new Set(K.map(ie=>ie.id))}if(c!==void 0){if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const ie={vec:await e.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Io=await e.search.backend.searchRanked(ie,Jt);x=P?Io.filter(Ea=>P.has(Ea.id)):Io}else P&&(x=(await n.searchNodes(a,{limit:Jt,filter:d})).map(ie=>({id:ie.id,score:ie.score,fields:{}})));const Wt=(x??[]).map(K=>K.id).slice(Y,Y+r),ya=Wt.length>0?await n.getNodesByIds(Wt):[],Oo=new Map(ya.map(K=>[K.id,K])),wa=Wt.map(K=>Oo.get(K)).filter(K=>K!==void 0),va=new Map((x??[]).map(K=>{var ie;return[(ie=Oo.get(K.id))==null?void 0:ie.uid,K.score]}).filter(K=>K[0]!==void 0)),Ro=await Qe(n,wa,o,va),zt=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Yt=Ro.length,ba=Yt<Math.min(zt-Y,r),Sa=Y+Yt<zt;return{page:{items:Ro,hasMore:Sa},meta:{total:zt,returned:Yt,limit:r,...t.offset!==void 0?{offset:t.offset}:{},...ba?{truncated:!0}:{}}}}const l=op(t.sort),u={...d,limit:r+1,...t.after!==void 0?{after:Number(t.after)}:{},...l&&t.after===void 0?{orderBy:l,orderDir:t.direction??"desc"}:{},...t.after===void 0&&t.offset!==void 0?{offset:t.offset}:{}};let f=await n.queryNodes(u);t.sort==="priority"&&t.after===void 0&&(f=await rp(n,f,t.direction??"asc"));const g=f.length>r,p=g?f.slice(0,r):f,m=g?String(p[p.length-1].id):void 0,v=await Qe(n,p,o),h=await n.countNodes(d),y=t.after===void 0?t.offset:void 0;return{page:{items:v,nextCursor:m,hasMore:g},meta:{total:h,returned:v.length,limit:r,...y!==void 0?{offset:y}:{}}}}async function sp(e,t){var y;const{graph:n}=e,r=rt(t.limit),o=t.fields??ot,i=await ws(n,"open"),s=await it(n,t.filter),a=s?[...i].filter(w=>s.has(w)):[...i];if(a.length===0)return[];const c=await n.getNodesByIds(a),d=await n.getEdges({rel:"blocks"}),l=new Map;for(const w of d){const b=l.get(w.dst);b?b.push(w.src):l.set(w.dst,[w.src])}const u=[...new Set(d.map(w=>w.src))],f=new Set((u.length>0?await n.getNodesByIds(u):[]).map(w=>w.id)),g=await n.getEdges({rel:"has_status"}),p=new Map;for(const w of g)p.has(w.src)||p.set(w.src,w.dst);const m=[...new Set(p.values())],v=new Map((m.length>0?await n.getNodesByIds(m):[]).map(w=>[w.id,w])),h=[];for(const w of c){if(h.length>=r)break;if(typeof((y=w.metadata)==null?void 0:y.claimedBy)=="string")continue;const b=(l.get(w.id)??[]).filter(E=>f.has(E));if(b.length===0){h.push(w);continue}b.every(E=>{const A=p.get(E);return A!==void 0&&Oe(v.get(A))})&&h.push(w)}return Qe(n,h,o)}async function ap(e,t){const{graph:n}=e,r=rt(t.limit),o=t.fields??ot,i=t.staleAfterMin??30,s=new Date(Date.now()-i*6e4).toISOString(),a=await it(n,t.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:r},d=await n.queryNodes(c);return Qe(n,d,o)}const cp=["blocks","relates_to","part_of"];function dp(e){return cp.includes(e)}async function lp(e,t){var u;const{graph:n}=e,r=rt(t.limit??ne),o=await it(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(f=>f.id)),c=await up(n,s),d=s.map(f=>{var g;return{uid:f.uid,title:f.name??"",status:((g=c.get(f.id))==null?void 0:g.name)??""}}),l=[];for(const f of s){const g=await De(n,f.id);for(const p of g)if(dp(p.rel)&&a.has(p.dst)){const m=(u=(await n.getNodesByIds([p.dst]))[0])==null?void 0:u.uid;m&&l.push({from:f.uid,to:m,rel:p.rel})}}return{nodes:d,edges:l}}async function up(e,t){const n=await Promise.all(t.map(a=>e.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await e.getNodesByIds(r):[],i=new Map(o.map(a=>[a.id,a])),s=new Map;return t.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=i.get(d);u&&s.set(a.id,u)}}),s}async function fp(e,t){const{graph:n}=e,r=rt(t.limit??ne),o=await it(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(p=>p.id)),c=new Map(s.map(p=>[p.id,p.uid])),d=new Map,l=new Map;for(const p of s)d.set(p.id,0),l.set(p.id,[]);for(const p of s){const m=await n.getEdges({src:p.id,rel:"blocks"});for(const v of m)a.has(v.dst)&&(l.get(p.id).push(v.dst),d.set(v.dst,(d.get(v.dst)??0)+1))}const u=s.filter(p=>(d.get(p.id)??0)===0).map(p=>p.id),f=[],g=new Map(d);for(;u.length>0;){const p=u.shift();f.push(p);for(const m of l.get(p)??[]){const v=(g.get(m)??0)-1;g.set(m,v),v===0&&u.push(m)}}return f.length!==s.length?{ok:!1,cycle:s.filter(m=>!f.includes(m.id)).map(m=>c.get(m.id))}:{ok:!0,order:f.map(p=>c.get(p))}}async function pp(e,t){var s;const{graph:n}=e,r=t.overlapAxis,o=t.overlapUids;if(!r)throw new I("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new I("overlapUids","requires at least 2 uids to detect an overlap");const i=new Map;for(const a of o){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(r==="file"){const g=(await De(n,c.id)).filter(m=>m.rel==="has_citation"),p=g.length>0?await n.getNodesByIds(g.map(m=>m.dst)):[];for(const m of p){const v=typeof((s=m.metadata)==null?void 0:s.target)=="string"?m.metadata.target:void 0;v&&(i.has(v)||i.set(v,new Set),i.get(v).add(a))}continue}if(r==="author"){const g=(await De(n,c.id)).find(m=>m.rel==="authored_by");if(!g)continue;const[p]=await n.getNodesByIds([g.dst]);if(!p)continue;i.has(p.uid)||i.set(p.uid,new Set),i.get(p.uid).add(a);continue}const{project:d,component:l}=await ps(n,c.id),u=r==="project"?d:l;u&&(i.has(u.uid)||i.set(u.uid,new Set),i.get(u.uid).add(a))}return[...i.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function mp(e,t){return Wf(e.graph,t.filter)}async function gp(e,t){return zf(e.graph,t.filter)}async function hp(e,t){return Yf(e.graph,t.filter)}function yp(e){var t,n;return e.text!==void 0||((t=e.filter)==null?void 0:t.semantic)!==void 0||((n=e.filter)==null?void 0:n.anchor)!==void 0||e.view==="similar"||e.sort==="relevance"||(e.fields??[]).includes("_vector")}function wp(e,t){var i,s;if(t.text===void 0)return t;if(((i=t.filter)==null?void 0:i.semantic)!==void 0||((s=t.filter)==null?void 0:s.grep)!==void 0)throw new I("text","text is mutually exclusive with filter.semantic/filter.grep — pick one: the free-text positional (text), or an explicit filter.semantic/filter.grep");if(t.text.trim().length===0)throw new I("text","must not be blank");const n=e.search!==void 0&&e.spacePopulated===!0,{text:r,...o}=t;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:r}:{grep:r}}}}async function vp(e,t){const n=t.view??"list";switch(n){case"list":{const{page:r,meta:o}=await ip(e,t);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await sp(e,t)}};case"graph":return{result:{view:"graph",graph:await lp(e,t)}};case"order":return{result:{view:"order",order:await fp(e,t)}};case"stale":return{result:{view:"stale",items:await ap(e,t)}};case"similar":return{result:{view:"similar",items:await qf(e,t)}};case"overlap":return{result:{view:"overlap",groups:await pp(e,t)}};case"projects":return{result:{view:"projects",items:await mp(e,t)}};case"components":return{result:{view:"components",items:await gp(e,t)}};case"locations":return{result:{view:"locations",items:await hp(e,t)}};default:{const r=n;throw new je("view",`unknown view "${r}"`)}}}const bp=["list","ready","stale","similar"];async function Sp(e,t={}){var a;await((a=e.assertVocabulary)==null?void 0:a.call(e));const n=wp(e,t),r=await vp(e,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:i}=o;if(i!=="list"&&i!=="ready"&&i!=="stale"&&i!=="similar")throw new I("format",`"markdown" is only supported for view:${bp.map(c=>`"${c}"`).join("/")} — view:"${i}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=o.items;return{result:{view:i,format:"markdown",markdown:Jf(s)},meta:r.meta}}const vs=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],Ep=new Set(vs);function bs(e){return typeof e=="string"&&Ep.has(e)}const go={not_found:4,item_not_found:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function kp(e){return e.ok===!0}function Ap(e){return e.ok===!1&&typeof e.error=="object"&&e.error!==null&&bs(e.error.code)}function ho(e,t){const n={ok:!0,data:e};return t!=null&&t.warnings&&t.warnings.length>0&&(n.warnings=t.warnings),t!=null&&t.meta&&(n.meta=t.meta),n}function le(e,t,n){const r={code:e,message:t},o={...n??{}};return e==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(r.details=o),{ok:!1,error:r}}function ke(e){return e.ok?0:go[e.error.code]}function Ss(e){if(e===null||typeof e!="object")return!1;const t=e;if(typeof t.ok!="boolean")return!1;if(t.ok)return!0;const n=t.error;if(n===null||typeof n!="object")return!1;const r=n.code;return typeof r=="string"&&r in go}class Es extends Error{constructor(t,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${t}" needs an embedded vector space and this store has none — a backend is configured, but zero items have been embedded, so nearest-neighbour ranking has nothing to rank. Run an embedding backfill to populate it. `:`backlog: "${t}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}class jp extends Error{constructor(t,n,r,o){super(`backlog embedding: ${t} produced a ${o}-dimensional vector but space "${n}" is ${r}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=t,this.modelId=n,this.expected=r,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let Nr=!1,Or=!1,Rr=!1;const It=new WeakMap;async function _p(e,t){const n=e;return typeof n.hasVectors!="function"?(Nr||(Nr=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${t}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(t)}async function Ir(e){try{return{mod:await import(e)}}catch(t){return{err:t}}}const ht=e=>e instanceof Error?e.message:String(e),He=new WeakMap;async function Np(e,t,n,r=i=>console.error(i),o){const i=He.get(e);if(i)return i;const s=Ip(e,t,n,r,o);He.set(e,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?He.delete(e):It.set(e,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw He.delete(e),It.delete(e),a}}function Op(e){const t=It.get(e);if(t)return{present:!0,embedding:t.embedding,search:t.search}}function Rp(e){He.delete(e),It.delete(e)}function Tr(e){return e&&e.length>0?e.join(", "):"(no config layer files found on disk)"}async function Ip(e,t,n,r,o){var p;if(!(n!=null&&n.enabled))return(o==null?void 0:o.configuredEnabled)===!0?Rr||(Rr=!0,r(`backlog: embedding.enabled is TRUE in the on-disk config but this process is still running with it DISABLED (startup configHash ${o.startupHash??"unknown"}, on-disk configHash ${o.configuredHash??"unknown"}). The next semantic verb adopts it without a restart; if it does not, restart the process. Resolved config layers: ${Tr(o.configPaths)}.`)):Or||(Or=!0,r(`backlog: embedding is DISABLED (the default) — semantic/RAG features are OFF for this process. Set embedding.enabled: true in a resolved config layer to opt in (adopted without a restart). Resolved config layers: ${Tr(o==null?void 0:o.configPaths)}.`)),{};const i=(p=e.capabilities)==null?void 0:p.nativeVectors;if(i!==!0)return r(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(i)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,a]=await Promise.all([Ir("@adhd/sox-vector-store"),Ir("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const m=[..."err"in s?[`@adhd/sox-vector-store (${ht(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${ht(a.err)})`]:[]];return r(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${m.join("; ")}. Continuing WITHOUT semantic search.`),{}}let c;try{c=await a.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(m){return r(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${ht(m)}. Continuing WITHOUT semantic search.`),{}}const d={modelId:c.metadata.modelId,dim:c.metadata.dimensions};let l;try{l=await s.mod.openTursoVectorStore(e,{dim:d.dim,modelId:d.modelId}),await l.ensureSpace(d)}catch(m){return r(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${ht(m)}. Continuing WITHOUT semantic search.`),{}}const u=(m,v)=>{if(m.length!==d.dim)throw new jp(v,d.modelId,d.dim,m.length);return m},f={modelId:d.modelId,async embedDocument(m){return u(await c.embedSingle(m,"document"),"embedDocument")},async upsertVector(m,v){await l.upsert(m,u(v,"upsertVector"),d)},async deleteVector(m){await l.delete(m,d.modelId)}};return{search:{backend:new Ia.StoreSearchBackend(l,t),async embedQuery(m){return u(await c.embedSingle(m,"query"),"embedQuery")},async spacePopulated(){return _p(l,d.modelId)}},embedding:f}}async function Tp(e,t){mo(t.fields);const n=t.fields??ot,r=await po(e,t.uid);return hs(e,r,n)}const $p=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function ks(e,t,n){if(e){for(const r of $p)if(e[r]!==void 0&&!t.has(r))throw new I(`filter.${r}`,`not supported by ${n} — this view scopes by ${[...t].join("/")} only`)}}async function As(e,t){const n=new Set;for(const r of t.refs){const o=await D(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function Cp(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}function js(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}async function _s(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await D(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await Fe(e,r,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await As(e,{rel:"has_kind",expectedKind:"kind",refs:o}))}return js(n)}const Pp=new Set(["project","component","kind","status"]);async function xp(e,t){const n=t??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await Cp(e,n),scope:n};const r=Array.isArray(n)?n:[n];return{candidates:await As(e,{rel:"has_status",expectedKind:"status",refs:r}),scope:n}}async function Lp(e,t={}){var f,g,p;const{graph:n}=e;ks(t.filter,Pp,"priorityMatrix");const r=await _s(n,t.filter);if((r==null?void 0:r.size)===0)return{rows:[],unassigned:0,statusScope:((f=t.filter)==null?void 0:f.status)??"open"};const{candidates:o,scope:i}=await xp(n,(g=t.filter)==null?void 0:g.status),s=js([r,o].filter(m=>m!==void 0));if((s==null?void 0:s.size)===0)return{rows:[],unassigned:0,statusScope:i};const a=new Set((await n.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...s?{ids:[...s]}:{}})).map(m=>m.id)),c=await n.queryNodes({kind:"priority",liveOnly:!0}),d=new Set,l=[];for(const m of c){const v=await n.getEdges({dst:m.id,rel:"has_priority"});let h=0;for(const w of v)a.has(w.src)&&(h+=1,d.add(w.src));const y=typeof((p=m.metadata)==null?void 0:p.rank)=="number"?m.metadata.rank:void 0;l.push({priority:m.name??"",priorityUid:m.uid,rank:y,count:h})}l.sort((m,v)=>(m.rank??Number.MAX_SAFE_INTEGER)-(v.rank??Number.MAX_SAFE_INTEGER));let u=0;for(const m of a)d.has(m)||(u+=1);return{rows:l,unassigned:u,statusScope:i}}async function Up(e,t){if(t.length===0)return new Map;const n=await Promise.all(t.map(c=>e.getEdges({src:c.id,rel:"has_status"}))),r=new Map;n.forEach((c,d)=>{const l=c[0];l&&r.set(t[d].id,l.dst)});const o=[...new Set(r.values())];if(o.length===0)return new Map;const i=await e.getNodesByIds(o),s=new Map(i.map(c=>[c.id,c])),a=new Map;for(const[c,d]of r){const l=s.get(d);l&&a.set(c,l)}return a}async function Dp(e,t){const{graph:n}=e,r=await po(n,t.uid),i=(await n.getSubgraph(r.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==r.id&&l.kind==="issue"&&!l.tInvalid),s=await Up(n,i);let a=0,c=0;const d=[];for(const l of i)Oe(s.get(l.id))?c+=1:(a+=1,d.push(l.uid));return{uid:r.uid,childrenTotal:i.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:d}}const Mp=new Set(["project","component","kind"]);function Fp(e,t,n){var i;const r=e.filter(s=>s.to!==void 0);if(r.length===0)return n;let o;for(const s of r)if(s.at<=t)o=s;else break;return o?o.to:(i=r[0])==null?void 0:i.from}async function Bp(e){var u;const t=await e.getEdges({rel:"has_status"}),n=new Map;for(const f of t)n.has(f.src)||n.set(f.src,f.dst);const r=[...new Set(n.values())],o=new Map((r.length>0?await e.getNodesByIds(r):[]).map(f=>[f.id,f])),i=new Map;for(const[f,g]of n)i.set(f,(u=o.get(g))==null?void 0:u.name);const s=await e.getEdges({rel:"audits"}),a=new Map;for(const f of s){const g=a.get(f.src);g?g.push(f.dst):a.set(f.src,[f.dst])}const c=[...new Set(s.map(f=>f.dst))],d=new Map((c.length>0?await e.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,g]of a){const p=g.map(m=>d.get(m)).filter(m=>m!==void 0).map(m=>{var v,h,y,w,b,S,E;return{uid:m.uid,actor:typeof((v=m.metadata)==null?void 0:v.actor)=="string"?m.metadata.actor:"",action:typeof((h=m.metadata)==null?void 0:h.action)=="string"?m.metadata.action:m.name??"",from:typeof((y=m.metadata)==null?void 0:y.from)=="string"?m.metadata.from:void 0,to:typeof((w=m.metadata)==null?void 0:w.to)=="string"?m.metadata.to:void 0,note:typeof((b=m.metadata)==null?void 0:b.note)=="string"?m.metadata.note:void 0,sha:typeof((S=m.metadata)==null?void 0:S.sha)=="string"?m.metadata.sha:"",at:typeof((E=m.metadata)==null?void 0:E.at)=="string"?m.metadata.at:m.tCreated}}).sort((m,v)=>m.at.localeCompare(v.at));l.set(f,p)}return{currentStatusNameByIssue:i,auditTrailByIssue:l}}async function qp(e,t){const{graph:n}=e;if(ks(t.filter,Mp,"openCurve"),t.at.length===0)throw new I("at","requires at least one ISO-8601 instant to sample");const r=t.at.map(u=>{const f=new Date(u);if(Number.isNaN(f.getTime()))throw new I("at",`"${u}" is not a parsable ISO-8601 instant`);return f.toISOString()}),o=await _s(n,t.filter);if((o==null?void 0:o.size)===0)return{points:r.map(u=>({at:u,existed:0,open:0,closed:0}))};const i=await n.queryNodes({kind:"status",liveOnly:!0}),s=new Map(i.map(u=>[u.name??"",Oe(u)])),{currentStatusNameByIssue:a,auditTrailByIssue:c}=await Bp(n),d=new Map;for(const u of await n.getEdges({rel:"SUPERSEDES"})){const f=d.get(u.dst);(f===void 0||u.tCreated<f)&&d.set(u.dst,u.tCreated)}const l=[];for(const u of r){const f={kind:"issue",validAt:u,liveOnly:!1,...o?{ids:[...o]}:{}},g=await n.queryNodes(f);let p=0,m=0;for(const v of g){const h=d.get(v.id);if(h!==void 0&&h<=u)continue;m+=1;const y=a.get(v.id),w=c.get(v.id)??[],b=Fp(w,u,y);(b!==void 0?s.get(b)??!1:!1)||(p+=1)}l.push({at:u,existed:m,open:p,closed:m-p})}return{points:l}}const $r=["abort","force","comment"];function qe(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}const Cr=512;function Ns(e){if(typeof e=="string"&&e.length>Cr)throw new I("gitContext",`must be at most ${Cr} characters, got ${e.length}`)}async function Kp(e,t,n){if(!qt(e))return"unverified";try{const{accepted:r,candidate:o}=await Di(e.metadata.path,t,n);if(!r)return"unverified";const i=await Ct.readFile(o);return ue.createHash("sha256").update(i).digest("hex")}catch(r){if(ro(r))return"unverified";throw Ki(r,t)}}function Pr(e,t,n){if(e.length>0&&!e.includes(n))throw new I(t,`"${n}" is not in this project's allowed ${t} set`)}function Hp(e,t){for(const n of e){const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function Vp(e,t,n,r,o){if(!n.dedupeScanEnabled)return[];const{search:i,graph:s}=e;if(!i||!s)return[];const a={project:t.uid},c=await ys(s,a);if(!c||c.size===0)return[];const d=lo(r,o),l=typeof i.embedQuery=="function"?await i.embedQuery(d):void 0,f={text:d,vec:l,signals:l?[{kind:"text"},{kind:"vec"}]:[{kind:"text"}],filters:{ids:[...c]}},g=5,p=g*4,m=await i.backend.search(f,p);if(m.length===0)return[];const v=await s.getNodesByIds(m.map(w=>w.id)),h=new Map(v.map(w=>[w.id,w])),y=[];for(const w of m){const b=h.get(w.id);if(!b||b.tInvalid!==void 0||b.isSuperseded)continue;const S=w.vecScore;S!==void 0&&c.has(w.id)&&S>=n.dedupeThreshold&&y.push({uid:b.uid,title:b.name??"",score:S})}return y.sort((w,b)=>b.score-w.score),y.slice(0,g)}async function Gp(e,t){qe("title",t.title),qe("body",t.body),qe("project",t.project),qe("by",t.by),Q("by",t.by),Ns(t.gitContext);const n=t.citations??[];n.forEach((u,f)=>qe(`citations[${f}].file`,u.file));const r=typeof t.gitContext=="string"&&t.gitContext.trim().length>0?t.gitContext:void 0,o=t.duplicateAction??"abort";if(t.duplicateAction!==void 0&&!$r.includes(t.duplicateAction))throw new I("duplicateAction",`must be one of ${$r.map(u=>`'${u}'`).join("|")}, got "${t.duplicateAction}"`);const i=await Ye(e.adapter,t.project),s=Le(i),a=[];for(const u of n){const f=await Kp(i,u.file,s.citationAllowedExternalRoots);if(f==="unverified"&&s.citationRequiresSha){if(qt(i))throw new io(u.file,s.citationAllowedExternalRoots);console.error(`createIssue: citation_requires_sha waived for path-less project uid="${i.uid}" — cannot verify citation "${u.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}a.push(f)}const c=await Vp(e,i,s,t.title,t.body);if(c.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let d;const l=await z(e,async u=>{const f=V();if(c.length>0&&o==="comment"){const[C]=c,q=await we(u,C.uid),x=`${t.title}
205
+
206
+ ${t.body}`,P=await J(u,{kind:"note",content:x,metadata:{author:t.by,text:x,at:f},at:f}),Y=await F(u,"has_note");return await M(u,{at:f,srcRowid:q.rowid,srcUid:q.uid,srcKind:"issue",dstRowid:P.rowid,dstUid:P.uid,dstKind:"note",rel:"has_note",rule:Y,typePolicy:e.typePolicy}),{created:!1,commentedOn:{uid:q.uid,noteId:P.uid},duplicateCandidates:c}}const g=await Ye(u,t.project),p=Le(g),m=t.component!==void 0?await co(u,{projectUid:g.uid,ref:t.component}):await zi(u,{projectRowid:g.rowid}),v=t.kind??p.defaultKind??"issue",h=await he(u,{catalogKind:"kind",ref:v,at:f});Pr(p.allowedKinds,"kind",h.name);const y=t.status??p.defaultStatus??"open",w=await he(u,{catalogKind:"status",ref:y,at:f,mintMetadata:async()=>({terminal:!1})});Pr(p.allowedStatuses,"status",w.name);let b;t.priority!==void 0&&(b=await he(u,{catalogKind:"priority",ref:t.priority,at:f,mintMetadata:async C=>({rank:await Yi(C)})}));const S=t.author??t.by,E=await he(u,{catalogKind:"agent",ref:S,at:f});Hp(p.requiredFields,{...t,component:m.name,kind:h.name,status:w.name,priority:b==null?void 0:b.name});const A={};t.assignee!==void 0&&(A.assignee=t.assignee),r!==void 0&&(A.gitContext=r);const j=await J(u,{kind:"issue",name:t.title,content:t.body,metadata:A,at:f});d={rowid:j.rowid,uid:j.uid};const N=await F(u,"owns_component");await M(u,{at:f,srcRowid:m.rowid,srcUid:m.uid,srcKind:"component",dstRowid:j.rowid,dstUid:j.uid,dstKind:"issue",rel:"owns_component",rule:N,typePolicy:e.typePolicy});const _=await F(u,"has_kind");await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"kind",rel:"has_kind",rule:_,typePolicy:e.typePolicy});const R=await F(u,"has_status");if(await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"status",rel:"has_status",rule:R,typePolicy:e.typePolicy}),b){const C=await F(u,"has_priority");await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"priority",rel:"has_priority",rule:C,typePolicy:e.typePolicy})}const T=await F(u,"authored_by");if(await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:E.rowid,dstUid:E.uid,dstKind:"agent",rel:"authored_by",rule:T,typePolicy:e.typePolicy}),n.length>0){const C=await F(u,"has_citation");for(let q=0;q<n.length;q+=1){const x=n[q],P=a[q],Y=await J(u,{at:f,kind:"citation",name:x.file,content:x.context??x.file,metadata:{target:x.file,target_type:"path",sha:P,line:x.lines??null,at:f,symbol:x.symbol??null,blastRadius:x.blastRadius??null}});await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:Y.rowid,dstUid:Y.uid,dstKind:"citation",rel:"has_citation",rule:C,typePolicy:e.typePolicy})}}return await U({tx:u,typePolicy:e.typePolicy,subjectRowid:j.rowid,subjectUid:j.uid,subjectKind:"issue",actor:t.by,action:"created",at:f}),{created:!0,uid:j.uid,item:{uid:j.uid,title:t.title,kind:h.name,status:w.name,priority:b==null?void 0:b.name,project:g.uid,component:m.uid,createdAt:f,assignee:t.assignee,author:E.name,...r!==void 0?{gitContext:r}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(d){const u=Ot(e,{action:"upsert",subjectRowid:d.rowid,subjectUid:d.uid,actor:t.by,content:lo(t.title,t.body)});t.awaitEmbed?await u:u.catch(()=>{})}return l}function yt(e,t){if(typeof t!="string"||t.trim().length===0)throw new I(e,"is required")}async function Jp(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Wp(e,t){if(e.length>0&&!e.includes(t))throw new I("kind",`"${t}" is not in this project's allowed kind set`)}function zp(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function xr(e,t,n,r){const o=[],i=[];n.name!==void 0&&(o.push("name = ?"),i.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),i.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),i.push(r);const s=await e.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...i,t]);if(s.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${s.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function wt(e,t,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let i=n.override;if(!i&&o){const a=await fe(e,o.dst);(a==null?void 0:a.tInvalid)===null&&(i={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!i){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await _e(e,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await F(e,n.rel);await M(e,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:i.kind,rel:n.rel,rule:s,typePolicy:t.typePolicy})}async function Yp(e,t,n){if(n.oldIssueRowid===n.newIssueRowid)return;const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!r)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${r.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await _e(e,{srcRowid:r.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const i=await F(e,"owns_component");await M(e,{at:n.at,srcRowid:r.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:i,typePolicy:t.typePolicy})}const Lr=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Xp(e,t){if(t.oldIssueRowid===t.newIssueRowid)return;const n=Lr.map(()=>"?").join(", ");for(const r of["outgoing","incoming"]){const o=r==="outgoing"?"src":"dst",i=r==="outgoing"?"dst":"src",{rows:s}=await e.executeAll(`SELECT ${i} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[t.oldIssueRowid,...Lr]);for(const a of s){const c=r==="outgoing"?t.oldIssueRowid:a.other,d=r==="outgoing"?a.other:t.oldIssueRowid,l=r==="outgoing"?t.newIssueRowid:a.other,u=r==="outgoing"?a.other:t.newIssueRowid;await _e(e,{srcRowid:c,dstRowid:d,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:t.at}),await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
207
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
208
+ ON CONFLICT(src, dst, rel) DO UPDATE SET
209
+ weight = excluded.weight, confidence = excluded.confidence,
210
+ origin = excluded.origin, meta = excluded.meta,
211
+ t_invalid = NULL, t_valid = excluded.t_valid`,[l,u,a.rel,a.weight,a.confidence,a.origin,a.meta,t.at,t.at])}}}function Qp(e){const t=[];return e.title!==void 0&&t.push("title"),e.body!==void 0&&t.push("body"),e.kind!==void 0&&t.push("kind"),e.priority!==void 0&&t.push("priority"),e.assignee!==void 0&&t.push("assignee"),e.author!==void 0&&t.push("author"),t}function Zp(e,t){const n=["title","body","kind","priority","assignee","author"];for(const r of n)if(e[r]!==void 0&&!t.includes(r))throw new Error(`update: patch key "${r}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function em(e,t){if(yt("uid",t.uid),yt("by",t.by),Q("by",t.by),t.status!==void 0)throw new je("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");t.title!==void 0&&yt("title",t.title),t.body!==void 0&&yt("body",t.body);const r=Qp(t);if(r.length===0)throw new I("patch","update requires at least one of title/body/kind/priority/assignee/author");Zp(t,r);let o;const i=await z(e,async s=>{const a=V(),c=await we(s,t.uid),d=await Jp(s,c.rowid),l=Le(d);let u;if(t.kind!==void 0){const y=await he(s,{catalogKind:"kind",ref:t.kind,at:a});Wp(l.allowedKinds,y.name),u={rowid:y.rowid,uid:y.uid,kind:"kind",name:y.name}}let f;if(t.priority!==void 0){const y=await he(s,{catalogKind:"priority",ref:t.priority,at:a,mintMetadata:async w=>({rank:await Yi(w)})});f={rowid:y.rowid,uid:y.uid,kind:"priority",name:y.name}}let g;if(t.author!==void 0){const y=await he(s,{catalogKind:"agent",ref:t.author,at:a});g={rowid:y.rowid,uid:y.uid,kind:"agent",name:y.name}}const p={...t};u&&(p.kind=u.name),f&&(p.priority=f.name),g&&(p.author=g.name),zp(l.requiredFields,p);let m=c.rowid,v=c.uid,h=!1;if(t.body!==void 0){if((await s.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[c.rowid])).rowsAffected!==1)throw new Mt(t.uid);const w=t.title??c.name??void 0,b={...c.metadata??{}};t.assignee!==void 0&&(b.assignee=t.assignee);const S=await J(s,{kind:"issue",name:w,content:t.body,metadata:b,at:a});await s.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
212
+ VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
213
+ ON CONFLICT(src, dst, rel) DO UPDATE SET
214
+ meta = excluded.meta, weight = excluded.weight,
215
+ t_invalid = NULL, t_valid = excluded.t_valid`,[S.rowid,c.rowid,a,a]),await xr(s,S.rowid,{},a),o={oldRowid:c.rowid,oldUid:c.uid,newRowid:S.rowid,newUid:S.uid,newTitle:w??"",newBody:t.body},m=S.rowid,v=S.uid,h=!0}else{const y=t.assignee!==void 0?{...c.metadata??{},assignee:t.assignee}:void 0;await xr(s,c.rowid,{name:t.title,metadata:y},a)}return await Yp(s,e,{oldIssueRowid:c.rowid,newIssueRowid:m,newIssueUid:v,at:a}),await wt(s,e,{rel:"has_status",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,reason:"superseded — status carried forward to the new node (update never changes status)",at:a,required:!0}),await wt(s,e,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:u,reason:"kind changed via update",at:a}),await wt(s,e,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:f,reason:"priority changed via update",at:a}),await wt(s,e,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:g,reason:"author changed via update",at:a}),await Xp(s,{oldIssueRowid:c.rowid,newIssueRowid:m,at:a}),await U({tx:s,typePolicy:e.typePolicy,subjectRowid:m,subjectUid:v,subjectKind:"issue",actor:t.by,action:"updated",from:h?c.uid:void 0,to:h?v:void 0,note:`fields changed: ${r.join(", ")}`,at:a}),{uid:v,changed:r}});if(o){const{oldRowid:s,oldUid:a,newRowid:c,newUid:d,newTitle:l,newBody:u}=o,f=Promise.all([Ot(e,{action:"delete",subjectRowid:s,subjectUid:a,actor:t.by}),Ot(e,{action:"upsert",subjectRowid:c,subjectUid:d,actor:t.by,content:lo(l,u)})]);t.awaitEmbed?await f:f.catch(()=>{})}return i}function Os(e){const t=e??{};return{claimedBy:typeof t.claimedBy=="string"?t.claimedBy:void 0,claimedAt:typeof t.claimedAt=="string"?t.claimedAt:void 0}}function Rs(e,t){return e!==void 0?(Date.parse(t)-Date.parse(e))/6e4:Number.POSITIVE_INFINITY}function Is(e,t,n){return Rs(e,t)>=n}async function Ts(e,t,n){const r=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[t,"has_status"]);if(!r)throw new Error(`${n}: issue rowid=${t} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await fe(e,r.dst);if((o==null?void 0:o.kind)!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${r.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function vt(e,t){if(typeof t!="string"||t.trim().length===0)throw new I(e,"is required")}async function Ur(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}async function tm(e,t,n){if(!qt(e))return"unverified";try{const{accepted:r,candidate:o}=await Di(e.metadata.path,t,n);if(!r)return"unverified";const i=await Ct.readFile(o);return ue.createHash("sha256").update(i).digest("hex")}catch(r){if(ro(r))return"unverified";throw Ki(r,t)}}function nm(e,t){if(e.length>0&&!e.includes(t))throw new I("toStatus",`"${t}" is not in this project's allowed status set`)}function om(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function rm(e,t){vt("uid",t.uid),vt("by",t.by),Q("by",t.by),vt("toStatus",t.toStatus),Ns(t.gitContext);const n=t.citations??[];n.forEach((o,i)=>vt(`citations[${i}].file`,o.file));const r=[];if(n.length>0){const o=await Bt(e.adapter,t.uid);if((o==null?void 0:o.kind)!=="issue"||o.tInvalid!==null)throw new Ft(t.uid);const i=await Ur(e.adapter,o.rowid),s=Le(i);for(const a of n){const c=await tm(i,a.file,s.citationAllowedExternalRoots);if(c==="unverified"&&s.citationRequiresSha){if(qt(i))throw new io(a.file,s.citationAllowedExternalRoots);console.error(`transition: citation_requires_sha waived for path-less project uid="${i.uid}" — cannot verify citation "${a.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}r.push(c)}}return z(e,async o=>{var j;const i=V(),s=await we(o,t.uid),a=await Ur(o,s.rowid),c=Le(a),{claimedBy:d,claimedAt:l}=Os(s.metadata);if(d!==void 0&&d!==t.by&&!Is(l,i,c.claimStaleAfterMin))throw new _t(d,l??i);const u=await Ts(o,s.rowid,"transition"),f=u.name??"",g=await he(o,{catalogKind:"status",ref:t.toStatus,at:i,mintMetadata:async()=>({terminal:!1})});nm(c.allowedStatuses,g.name),om(c.requiredFields,{status:g.name,note:t.note});const p=await fe(o,g.rowid),m=((j=p==null?void 0:p.metadata)==null?void 0:j.terminal)===!0;if(!(typeof t.note=="string"&&t.note.trim().length>0)&&c.transitionRequiresNote)throw new Hi(s.uid);if(m&&c.citationRequired&&n.length===0)throw new Vi(s.uid);const h={target_uid:s.uid,from:f,to:g.name,agent:t.by,note:t.note??null,at:i},y=so(Wi(h)),w=await J(o,{kind:"transition",content:t.note??"",metadata:{from_status:f,to_status:g.name,agent:t.by,note:t.note??null,sha:y,at:i},at:i}),b=await F(o,"has_transition");await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"transition",rel:"has_transition",rule:b,typePolicy:e.typePolicy}),await _e(o,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${g.name}"`,at:i});const S=await F(o,"has_status");if(await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:g.rowid,dstUid:g.uid,dstKind:"status",rel:"has_status",rule:S,typePolicy:e.typePolicy}),n.length>0){const N=await F(o,"has_citation");for(let _=0;_<n.length;_+=1){const R=n[_],T=r[_],C=await J(o,{at:i,kind:"citation",name:R.file,content:R.context??R.file,metadata:{target:R.file,target_type:"path",sha:T,line:R.lines??null,at:i,symbol:R.symbol??null,blastRadius:R.blastRadius??null}});await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:C.rowid,dstUid:C.uid,dstKind:"citation",rel:"has_citation",rule:N,typePolicy:e.typePolicy})}}const E={...s.metadata??{}};m?E.closedAt=i:delete E.closedAt,typeof t.gitContext=="string"&&t.gitContext.trim().length>0&&(E.gitContext=t.gitContext);const A=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(E),i,s.rowid]);if(A.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${A.rowsAffected} rows for rowid=${s.rowid}, expected exactly 1.`);return await U({tx:o,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"transitioned",from:f,to:g.name,note:t.note,at:i}),{uid:s.uid,fromStatus:f,toStatus:g.name,closedAt:m?i:void 0,transitionUid:w.uid}})}function Dr(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function im(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const i={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Le(i)}async function Ke(e,t,n,r){const o=await e.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),r,t]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function sm(e,t){if(Dr("uid",t.uid),Dr("by",t.by),Q("by",t.by),t.action!=="claim"&&t.action!=="release"&&t.action!=="renew")throw new I("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(t.action)})`);const n=t.force===!0;return z(e,async r=>{var d;const o=V(),i=await we(r,t.uid),s={...i.metadata??{}},{claimedBy:a,claimedAt:c}=Os(s);if(t.action==="claim"){const l=await Ts(r,i.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new qi(i.uid,l.name??"");if(a===void 0){const m={...s,claimedBy:t.by,claimedAt:o};return await Ke(r,i.rowid,m,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",to:t.by,at:o}),{uid:i.uid,status:"claimed",claimedBy:t.by,claimedAt:o}}if(a===t.by){const m={...s,claimedAt:o};return await Ke(r,i.rowid,m,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",from:t.by,to:t.by,note:"re-affirmed (held)",at:o}),{uid:i.uid,status:"held",heldBy:t.by,claimedBy:t.by,claimedAt:o}}const u=await im(r,i.rowid),f=Rs(c,o),g=Is(c,o,u.claimStaleAfterMin);if(!g&&!n)throw new _t(a,c??o);const p={...s,claimedBy:t.by,claimedAt:o,previousClaimant:a};return await Ke(r,i.rowid,p,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"reclaimed-stale",from:a,to:t.by,note:g?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${u.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:o}),{uid:i.uid,status:"reclaimed-stale",claimedBy:t.by,claimedAt:o,previousClaimant:a}}if(t.action==="release"){if(a===t.by){const l={...s};return delete l.claimedBy,delete l.claimedAt,await Ke(r,i.rowid,l,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"released",from:t.by,at:o}),{uid:i.uid,status:"released"}}return{uid:i.uid,status:"release-noop",wasClaimedBy:a}}if(a===t.by){const l={...s,claimedAt:o};return await Ke(r,i.rowid,l,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"renewed",from:t.by,to:t.by,at:o}),{uid:i.uid,status:"renewed",claimedBy:t.by,claimedAt:o}}throw new _t(a??"",c??"")})}const Mr=["relates_to","supersedes","blocks","duplicate_of","part_of"];function sn(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function am(e,t,n,r){const o=await e.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t,n,r]);return o?o.rowid:null}async function cm(e,t){if(sn("sourceUid",t.sourceUid),sn("targetUid",t.targetUid),sn("by",t.by),Q("by",t.by),!Mr.includes(t.rel))throw new I("rel",`must be one of ${Mr.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.rel)})`);if(t.action!=="add"&&t.action!=="remove")throw new I("action",`must be "add" or "remove" (got ${JSON.stringify(t.action)})`);if(t.sourceUid===t.targetUid)throw new I("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return z(e,async n=>{const r=V(),o=await we(n,t.sourceUid),i=await we(n,t.targetUid),s=await am(n,o.rowid,i.rowid,t.rel);if(t.action==="add"){if(s!==null)return{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!0};const a=await F(n,t.rel);return await M(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"issue",rel:t.rel,rule:a,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"related",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!1}}return s===null?{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!0}:(await _e(n,{srcRowid:o.rowid,dstRowid:i.rowid,rel:t.rel,reason:`relate: removed by "${t.by}"`,at:r}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"unrelated",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!1})})}function Fr(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function dm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await fe(e,n.src);if((r==null?void 0:r.kind)!=="component"||r.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function lm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_project"]);if(!n)throw new Error(`move: component rowid=${t} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const r=await fe(e,n.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function um(e,t){return Fr("uid",t.uid),Fr("by",t.by),Q("by",t.by),z(e,async n=>{const r=V(),o=await we(n,t.uid),i=await dm(n,o.rowid),s=await lm(n,i.rowid);let a;if(t.toProject!==void 0){const l=await Ye(n,t.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=s;let c;if(t.toComponent!==void 0?c=await co(n,{projectUid:a.uid,ref:t.toComponent}):c=await zi(n,{projectRowid:a.rowid}),c.rowid===i.rowid)return{uid:o.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid};await _e(n,{srcRowid:i.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:r});const d=await F(n,"owns_component");return await M(n,{at:r,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"moved",from:i.uid,to:c.uid,at:r}),{uid:o.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid}})}function an(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function fm(e,t){an("uid",t.uid),an("by",t.by),Q("by",t.by),an("reason",t.reason);let n;const r=await z(e,async o=>{const i=V(),s=await we(o,t.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:t.reason,invalidatedAt:i},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[i,JSON.stringify(a),s.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);return await U({tx:o,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"deleted",note:t.reason,at:i}),{uid:s.uid,invalidated:!0}});if(n){const o=Ot(e,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:t.by});t.awaitEmbed?await o:o.catch(()=>{})}return r}function Tt(e){var t;return(t=e.env.version)==null?void 0:t.configHash}async function $s(e){const t=e.embeddingConfig;t!=null&&t.refresh().changed&&Rp(e.store.adapter);const n=t?t.current():e.env.config.embedding;return Np(e.store.adapter,e.store.graph,n,void 0,{configuredEnabled:t?t.configured().enabled:n==null?void 0:n.enabled,startupHash:Tt(e),configuredHash:t?t.fingerprint().configHash:Tt(e),configPaths:t?t.fingerprint().files.map(r=>r.path):void 0})}async function Z(e,t){await oo(e.store.adapter);const{search:n,embedding:r}=t.needsSemantic?await $s(e):{};return{adapter:e.store.adapter,typePolicy:e.store.typePolicy,graph:e.store.graph,...n!==void 0?{search:n}:{},...r!==void 0?{embedding:r}:{}}}async function Ht(e,t){const{search:n}=t.needsSemantic?await $s(e):{},r=n!==void 0&&t.probeSpace?await n.spacePopulated():void 0;return{graph:e.store.graph,assertVocabulary:()=>oo(e.store.adapter),...n!==void 0?{search:n}:{},...r!==void 0?{spacePopulated:r}:{}}}const pm=[[Ft,"item_not_found"],[G,"not_found"],[I,"invalid_argument"],[_t,"conflict"],[On,"conflict"],[Mt,"conflict"],[qi,"precondition_failed"],[Vi,"precondition_failed"],[Hi,"precondition_failed"],[io,"precondition_failed"],[Mi,"store_busy"],[Es,"rag_not_configured"]],mm={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function Cs(e){for(const[t,n]of pm)if(e instanceof t){const r=e instanceof B?{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}:void 0;return le(n,e.message,r)}return e instanceof B?le(mm[e.code]??"internal",e.message,{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}):le("internal",e instanceof Error?e.message:String(e))}async function H(e){try{return ho(await e())}catch(t){return Cs(t)}}async function Ps(e,t){return H(()=>"registry"in t?t.registry==="project"?rn(e.store.graph,{registry:"project",name:t.name}):t.registry==="component"?rn(e.store.graph,{registry:"component",name:t.name,filter:t.filter}):rn(e.store.graph,{registry:"location",name:t.name}):Tp(e.store.graph,t))}async function xs(e,t){try{const{result:n,meta:r}=await Sp(await Ht(e,{needsSemantic:yp(t),probeSpace:t.text!==void 0}),t);return ho(n,r?{meta:r}:void 0)}catch(n){return Cs(n)}}async function Ls(e,t){return H(async()=>Lp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Us(e,t){return H(async()=>Dp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ds(e,t){return H(async()=>qp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ms(e){return H(async()=>{const t=e.embeddingConfig,n=t?t.configured():e.env.config.embedding,r=t?t.current():e.env.config.embedding,o=Op(e.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(r==null?void 0:r.enabled)===!0,provider:(r==null?void 0:r.provider)??"",model:(r==null?void 0:r.model)??"",membersPresent:{embedding:(o==null?void 0:o.embedding)??!1,search:(o==null?void 0:o.search)??!1},divergent:(n==null?void 0:n.enabled)===!0!=((r==null?void 0:r.enabled)===!0),startupHash:Tt(e)??"",currentHash:t?t.fingerprint().configHash:Tt(e)??""}})}async function Fs(e,t){return H(()=>Zf(e.store.graph,t.q))}async function Bs(e,t){return H(async()=>Gp(await Z(e,{needsSemantic:!0}),t))}async function qs(e,t){return H(async()=>em(await Z(e,{needsSemantic:!0}),t))}async function Ks(e,t){return H(async()=>rm(await Z(e,{needsSemantic:!1}),t))}async function Hs(e,t){return H(async()=>sm(await Z(e,{needsSemantic:!1}),t))}async function Vs(e,t){return H(async()=>cm(await Z(e,{needsSemantic:!1}),t))}async function Gs(e,t){return H(async()=>um(await Z(e,{needsSemantic:!1}),t))}async function Js(e,t){return H(async()=>fm(await Z(e,{needsSemantic:!1}),t))}async function Ws(e,t){return H(async()=>Dl(await Z(e,{needsSemantic:!1}),t))}async function zs(e,t){return H(async()=>Fl(await Z(e,{needsSemantic:!1}),t))}async function Ys(e,t){return H(async()=>ql(await Z(e,{needsSemantic:!1}),t))}async function Xs(e,t){return H(async()=>Kl(await Z(e,{needsSemantic:!1}),t))}const gm=Object.freeze(Object.defineProperty({__proto__:null,claim:Hs,create:Bs,delete:Js,embeddingStatus:Ms,get:Ps,lookup:Fs,move:Gs,openCurve:Ds,partOfRollup:Us,priorityMatrix:Ls,query:xs,relate:Vs,rmLocation:Xs,transition:Ks,update:qs,upsertComponent:zs,upsertLocation:Ys,upsertProject:Ws},Symbol.toStringTag,{value:"Module"}));async function hm(e){let t;try{t=await ge.open(e,"r"),await t.sync()}catch{}finally{t&&await t.close().catch(()=>{})}}async function Qs(e,t){const n=k.dirname(e);await ge.mkdir(n,{recursive:!0});const r=`${e}.${process.pid}.${ue.randomUUID()}.tmp`;let o;try{o=await ge.open(r,"w"),await o.writeFile(JSON.stringify(t),"utf8"),await o.sync(),await o.close(),o=void 0,await ge.rename(r,e),await hm(n)}catch(i){throw o&&await o.close().catch(()=>{}),await ge.unlink(r).catch(()=>{}),i}}function ym(e){return{async get(){try{const t=await ge.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await Qs(e,n)}}}const Ze=1;function wm(e){return ue.createHash("sha256").update(e).digest("hex")}async function Br(e){return wm(await ge.readFile(e,"utf8"))}async function $t(e){try{return(await ge.stat(e)).mtimeMs}catch{return}}async function qr(e,t){const n=await Br(e.source),r=ue.createHash("sha256");r.update(`formatVersion:${Ze}
216
+ `),r.update(`extractorVersion:${t}
217
+ `),r.update(`host:${e.host}
218
+ `),r.update(`namespace:${e.namespace??""}
219
+ `),r.update(`source:${n}
220
+ `);for(const o of ui(e.source))o!==e.source&&r.update(`dep:${o}:${await Br(o)}
221
+ `);return r.digest("hex")}async function Kr(e,t){const n=await $t(e.source)??0,r=[];for(const o of ui(e.source)){if(o===e.source)continue;const i=await $t(o);i!==void 0&&r.push({path:o,mtimeMs:i})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function vm(e,t){if(t.source.path!==e.source)return!1;const n=await $t(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await $t(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function bm(e){if(e.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const t=ym(e.cache),n=e.extractorVersion;async function r(o,i,s){const a=s??await qr(o,n),c=await Kr(o,a);await t.put(e.cache,{formatVersion:Ze,operations:i,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,i)=>{const s=await t.get(e.cache);if((s==null?void 0:s.formatVersion)!==Ze||s.extractorVersion!==n||!s.staleness){const d=await i();try{await r(o,d)}catch{}return d}if(await vm(o,s.staleness))return s.operations;const a=await qr(o,n);if(a===s.staleness.contentKey)return Kr(o,a).then(d=>t.put(e.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await i();try{await r(o,c,a)}catch{}return c}}Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);const Sm="api.ir.json",Em=Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href),yo=Em("@adhd/apigen-core-client/package.json").version;function Vt(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href));return O.existsSync(k.join(e,"api.d.ts"))?e:k.join(e,"..","dist")}function km(e){return k.join(e,Sm)}function wo(e){return ue.createHash("sha256").update(e).digest("hex")}function Zs(e){const t=[],n=o=>{let i;try{i=O.readdirSync(o,{withFileTypes:!0})}catch{return}for(const s of i){const a=k.join(o,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&t.push(a)}};n(e),t.sort();const r={};for(const o of t)r[k.relative(e,o).split(k.sep).join("/")]=wo(O.readFileSync(o));return r}function Am(e,t){const n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++){const i=n[o];if(i!==r[o]||e[i]!==t[i])return!1}return!0}function jm(e){try{const t=km(e);if(!O.existsSync(t))return;const n=JSON.parse(O.readFileSync(t,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==Ze||n.extractorVersion!==yo)return;const r=n.artifactSource;if(!r||typeof r.sha256!="string"||typeof r.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const o=k.join(e,"api.d.ts");if(!O.existsSync(o))return;const i=O.readFileSync(o);if(i.byteLength!==r.bytes||wo(i)!==r.sha256)return;const s=r.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return Am(s,Zs(e))?n.operations:void 0}catch{return}}async function _m(e){const t=O.readFileSync(e.apiDts),n={formatVersion:Ze,operations:e.operations,extractorVersion:e.extractorVersion,createdAt:new Date().toISOString(),artifactSource:{path:e.apiDts,sha256:wo(t),bytes:t.byteLength,deps:Zs(k.dirname(e.apiDts))}};await Qs(e.outFile,n)}function Nm(e={}){const t=uo("backlog",Ue,{namespace:e.namespace??"production",scope:fo(e.scope),...e.adhdRoot!==void 0?{adhdRoot:e.adhdRoot}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),n=[k.join(t.roots.system,Te),k.join(t.roots.global,Te)];return t.roots.project&&(n.push(k.join(t.roots.project,Te)),n.push(k.join(t.roots.project,es))),[...new Set(n)]}const Om=e=>e instanceof Error?e.message:String(e),Hr=e=>({enabled:e.enabled===!0,provider:e.provider,model:e.model}),Rm=(e,t)=>e.enabled===t.enabled&&e.provider===t.provider&&e.model===t.model;function Im(e){const t=()=>e.layerFiles().map(a=>{try{const c=O.statSync(a);return{path:a,stamp:`${c.mtimeMs}:${c.size}`}}catch{return{path:a,stamp:"absent"}}}),n=(a,c)=>a.length===c.length&&a.every((d,l)=>d.path===c[l].path&&d.stamp===c[l].stamp);let r=Hr(e.baseline.config.embedding),o=r,i={configHash:e.baseline.version.configHash,files:t()};const s=()=>{const a=t();if(n(a,i.files))return!1;let c;try{c=e.rebuild()}catch(d){return e.log("warn",`backlog: could not re-read the embedding config layers (${Om(d)}) — continuing with the last known effective embedding settings`),!1}return i={configHash:c.version.configHash,files:a},o=Hr(c.config.embedding),!0};return{current:()=>r,configured:()=>(s(),o),divergent:()=>(s(),o.enabled&&!r.enabled),refresh:()=>{const a=r;return s(),Rm(o,r)?{changed:!1,from:a,to:r}:(r=o,e.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${r.enabled}, provider ${r.provider}, model ${r.model}); adopting without restart`),{changed:!0,from:a,to:r})},fingerprint:()=>i}}function Tm(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),t=k.join(e,"package.json");return O.existsSync(t)?t:k.join(e,"..","package.json")}function vo(){const e=Tm(),t=JSON.parse(O.readFileSync(e,"utf8"));return{name:t.name,version:t.version}}function Dn(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function ea(){if(!process.env.VITEST)return;const e=()=>{},t={info:e,error:e,debug:e,fatal:e,warn:e,trace:e};return t.child=()=>t,t}const Vr=["install","install-skill","serve"];function ta(e){return e.filter(t=>t.kind==="action").map(t=>{const n=Me(t);return{id:t.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((t,n)=>t.id.localeCompare(n.id))}function $m(e){const t=e.filter(n=>{const r=n.cliPath[n.cliPath.length-1]??"";return Vr.includes(r)||Vr.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(t.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${t.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function Cm(e,t=[jt]){const n=ta(e),r=new Set(n.map(i=>i.mcpTool)),o={host:"backlog",operations:e};for(const i of t){const s=i.capabilities.mount;if(s)for(const a of s.operations(o,void 0,void 0))r.add(Me(a).mcp.name)}return[...r].sort()}function Gr(e){if(!e||typeof e!="object")return e;const t={},n=o=>{if(Array.isArray(o)){for(const s of o)n(s);return}if(!o||typeof o!="object")return;const i=o;for(const s of["definitions","$defs"]){const a=i[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,d]of Object.entries(a))c in t||(t[c]=d)}for(const[s,a]of Object.entries(i))s==="definitions"||s==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;const r=(o,i)=>{if(Array.isArray(o))return o.map(d=>r(d,i));if(!o||typeof o!="object")return o;const s=o,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return i.has(d)||!(d in t)?{}:r(t[d],new Set([...i,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=r(l,i));return c};return r(e,new Set)}async function Pm(e={}){const t=Vt(),n=k.join(t,"api.d.ts");if(!O.existsSync(n))throw new Error(`@adhd/backlog: cannot mount — ${n} does not exist. Run "nx build backlog" first (the mounted surface is derived from the built .d.ts).`);const r=jm(t);return r||(await Promise.resolve().then(()=>ha)).extractApiOperationsLive(e)}async function bo(e,t={}){const n=typeof e=="function"?e:()=>e,r=await Pm(t),o={schemas:Object.fromEntries(r.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:Gr(c.input),output:Gr(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},i=oc(o,[]),s=ta(r);$m(s);const{version:a}=vo();return{pkg:{id:"backlog",version:a,schemas:i,importPath:k.join(Vt(),"api.js"),fns:gm,createClient:async()=>n()},operations:r,surface:s}}async function na(e){const t=$e({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace});t.ensureDirs();let n,r;const o=Ge(t),i=()=>(n||(n=In(r)),n),s=Jl()?void 0:Qi(i);try{r=await Rt(o,t.config.db.busyTimeoutMs)}catch(c){throw s==null||s.dispose(),c}const a={store:r,env:t,embeddingConfig:Im({baseline:t,rebuild:()=>$e({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),layerFiles:()=>Nm({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),log:(c,d)=>console.error(d)})};try{const{pkg:c,operations:d}=await bo(a,{adhdRoot:e.adhdRoot}),l=ea(),u=[];(e.transport==="http"||e.transport==="both")&&u.push(Dn(Xu)({packages:[c],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[nf,jt]},signal:e.signal,operations:d,logger:l})),(e.transport==="mcp"||e.transport==="both")&&u.push(Dn(wf)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[jt]},signal:e.signal,operations:d,logger:l})),await Promise.all(u)}finally{s==null||s.dispose(),await i()}}const Pe=["claude","codex","opencode"],xm={claude:".claude",codex:".codex",opencode:".opencode"};function oa(e,t){return t?k.join(e,".codex"):process.env.CODEX_HOME??k.join(e,".codex")}function Lm(e,t,n,r){if(t==="project")return k.join(n,xm[e],"skills");const o=r??W.homedir();return e==="claude"?k.join(o,".claude","skills"):e==="codex"?k.join(oa(o,r),"skills"):k.join(o,".config","opencode","skills")}function Um(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),t=k.join(e,"skill","SKILL.md");return O.existsSync(t)?t:k.join(e,"..","skill","SKILL.md")}class X extends Error{constructor(t){super(t),this.name="BacklogUsageError"}}function So(e,t){console.error(JSON.stringify({code:"invalid_argument",message:e.message})),console.error(""),console.error(t),process.exitCode=2}const Jr=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
222
+
223
+ Copies the packaged backlog SKILL.md into an agent host's skills directory.
224
+ (\`backlog install\` is the richer successor — it also registers the MCP server.)
225
+
226
+ --host <name> claude | codex | opencode | all (default: all)
227
+ --scope <name> user | project (default: user)
228
+ "user" is the machine-wide install (~/.claude/skills/...);
229
+ there is no "global" — that is spelled "user" here.
230
+
231
+ Examples:
232
+ backlog install-skill
233
+ backlog install-skill --host opencode --scope user
234
+ backlog install-skill --host claude --scope project
235
+ `;function Dm(e){let t="all",n="user";for(let o=0;o<e.length;o++){const i=e[o];if(i==="--host")t=e[++o]??"all";else if(i==="--scope")n=e[++o]??"user";else throw new X(`backlog install-skill: unknown argument "${i}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new X(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const r=t==="all"?[...Pe]:[t];for(const o of r)if(!Pe.includes(o))throw new X(`backlog install-skill: --host must be one of ${Pe.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function ra(e,t=process.cwd(),n){const{hosts:r,scope:o}=Dm(e);return ia(r,o,t,n)}function ia(e,t,n,r){const o=Um();if(!O.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const i=O.readFileSync(o,"utf8"),s=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),a=k.join(s,"package.json"),c=O.existsSync(a)?a:k.join(s,"..","package.json"),d=JSON.parse(O.readFileSync(c,"utf8")),l=[];for(const u of e){const f=k.join(Lm(u,t,n,r),"backlog");O.mkdirSync(f,{recursive:!0});const g=k.join(f,"SKILL.md");O.writeFileSync(g,i,"utf8"),O.writeFileSync(k.join(f,"extension.json"),JSON.stringify({name:d.name,version:d.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
236
+ `,"utf8"),l.push({host:u,scope:t,path:g})}return l}async function sa(e){if(e.includes("--help")||e.includes("-h")){console.log(Jr);return}let t;try{t=ra(e)}catch(n){if(n instanceof X)return So(n,Jr);throw n}console.log(JSON.stringify({installed:t}))}const Eo=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Mm(e){if(!O.existsSync(e))return{};const t=O.readFileSync(e,"utf8").trim();if(t==="")return{};const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${e} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function aa(e,t,n,r){const o=Mm(e),i=o[t],s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};s[n]=r,o[t]=s,O.mkdirSync(k.dirname(e),{recursive:!0}),O.writeFileSync(e,JSON.stringify(o,null,2)+`
237
+ `,"utf8")}function Fm(e,t,n){if(e==="project")return k.join(t,".mcp.json");const r=W.homedir();return k.join(r,".claude.json")}function Bm(e,t,n){if(e==="project")return k.join(t,"opencode.json");const r=W.homedir();return k.join(r,".config","opencode","opencode.json")}function qm(e,t,n){if(e==="project")return k.join(t,".codex","config.toml");const r=W.homedir();return k.join(oa(r,n),"config.toml")}function Km(e,t,n){var d,l;const r=`[${t}]`,o=e.length>0?e.split(`
238
+ `):[],i=o.findIndex(u=>u.trim()===r),s=[r,...n];if(i===-1){if(o.length===0||o.every(u=>u.trim()===""))return s.join(`
203
239
  `)+`
204
- `;for(;o.length>0&&((u=o[o.length-1])==null?void 0:u.trim())==="";)o.pop();return[...o,"",...i].join(`
240
+ `;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
205
241
  `)+`
206
- `}let a=s+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,s),...i,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
242
+ `}let a=i+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,i),...s,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
207
243
  `)+`
208
- `}function Kj(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Gj(e,t,n){const r=Bj(e,t);return nm(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...Za]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Jj(e,t,n){const r=Fj(e,t);return nm(r,"mcp","backlog",{type:"local",command:["npx",...Za]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function Hj(e,t,n){const r=qj(e,t,n),o=C.existsSync(r)?C.readFileSync(r,"utf8"):"",s=Vj(o,"mcp_servers.backlog",['command = "npx"',`args = ${Kj(Za)}`]);return C.mkdirSync(T.dirname(r),{recursive:!0}),C.writeFileSync(r,s,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function zj(e,t,n,r){return e==="claude"?Gj(t,n):e==="opencode"?Jj(t,n):Hj(t,n,r)}function Wj(e,t){let n="all",r="user",o=!1,s=!1;for(let a=0;a<e.length;a++){const c=e[a];if(c==="--host")n=e[++a]??"all";else if(c==="--scope")r=e[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")s=!0;else throw new Error(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&s)throw new Error(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project")throw new Error(`backlog ${t}: --scope must be "user" or "project", got "${r}"`);const i=n==="all"?[...Qt]:[n];for(const a of i)if(!Qt.includes(a))throw new Error(`backlog ${t}: --host must be one of ${Qt.join("|")}|all, got "${n}"`);return{hosts:i,scope:r,skillOnly:o,mcpOnly:s}}const Yj=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
244
+ `}function Hm(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Vm(e,t,n){const r=Fm(e,t);return aa(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...Eo]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Gm(e,t,n){const r=Bm(e,t);return aa(r,"mcp","backlog",{type:"local",command:["npx",...Eo]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function Jm(e,t,n){const r=qm(e,t,n),o=O.existsSync(r)?O.readFileSync(r,"utf8"):"",i=Km(o,"mcp_servers.backlog",['command = "npx"',`args = ${Hm(Eo)}`]);return O.mkdirSync(k.dirname(r),{recursive:!0}),O.writeFileSync(r,i,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function Wm(e,t,n,r){return e==="claude"?Vm(t,n):e==="opencode"?Gm(t,n):Jm(t,n,r)}function zm(e,t){let n="all",r="user",o=!1,i=!1;for(let a=0;a<e.length;a++){const c=e[a];if(c==="--host")n=e[++a]??"all";else if(c==="--scope")r=e[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")i=!0;else throw new X(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&i)throw new X(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project"){const a=r==="global"?' — the machine-wide scope is spelled "user"':"";throw new X(`backlog ${t}: --scope must be "user" or "project", got "${r}"${a}`)}const s=n==="all"?[...Pe]:[n];for(const a of s)if(!Pe.includes(a))throw new X(`backlog ${t}: --host must be one of ${Pe.join("|")}|all, got "${n}"`);return{hosts:s,scope:r,skillOnly:o,mcpOnly:i}}const Wr=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
209
245
 
210
246
  Installs the backlog skill AND registers the backlog MCP server into an agent
211
247
  host's config, in one step.
@@ -222,4 +258,26 @@ Examples:
222
258
 
223
259
  Back-compat: \`backlog install-skill\` remains available and behaves exactly
224
260
  like \`backlog install --skill-only\` (original --host/--scope grammar only).
225
- `;function Qj(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:s,mcpOnly:i}=Wj(e,"install"),a=i?[]:em(r,o,t,n),c=s?[]:r.map(u=>zj(u,o,t,n));return{skill:a,mcp:c}}async function Zj(e){if(e[0]==="--help"||e[0]==="-h"){console.log(Yj);return}const t=Qj(e);for(const n of t.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of t.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(t))}function Xj(e){let t="mcp",n,r;for(let s=0;s<e.length;s++){const i=e[s];if(i==="--transport")t=e[++s];else if(i==="--port")n=Number(e[++s]);else if(i==="--host")r=e[++s];else throw new Error(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Error(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function rm(e,t={}){const n=Xj(e),r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=Qh({...n,...t,signal:r.signal});try{xl.initTelemetry({service:"backlog",role:"live-service",logSink:"file"})}catch(s){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${s instanceof Error?s.message:String(s)}); telemetry records will be silently dropped this process`)}await o}function om(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return ef(t).cli.path.slice(0,-1)}const Il=[cs];function eI(e,t,n){const r={host:n,operations:t},o=new Set;for(const s of e){const i=s.capabilities.mount;if(!i)continue;const a=i.operations(r,void 0,void 0);for(const c of a){const[u]=ef(c).cli.path;u!==void 0&&o.add(u)}}return o}function sm(e,t,n){var o;return e.length===0?[...e]:(o=e[0])!=null&&o.startsWith("-")?[...e]:e[0]!==void 0&&n.has(e[0])?[...e]:t.length>0&&t.every((s,i)=>e[i]===s)?[...e]:[...t,...e]}async function im(e,t={}){const n=e??process.argv.slice(2);if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log("")),n[0]==="install-skill"){await tm(n.slice(1));return}if(n[0]==="install"){await Zj(n.slice(1));return}if(n[0]==="serve"){await rm(n.slice(1),t);return}if(n[0]==="version"){console.log(JSON.stringify(lh()));return}let o;const s=async()=>{if(!o){const u=va({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd});u.ensureDirs();const l=await hi(wa(u),u.config.db.busyTimeoutMs);o={store:l,ctx:{store:l,env:u}}}return o.ctx};let i;const a=()=>(i||(i=nf(o==null?void 0:o.store)),i),c=rf(a);try{const{pkg:u,operations:l}=await Qa(s),f=n,p=om(l),h=eI(Il,l,u.id);await zs(Qg)({packages:[u],operations:l,outputDir:"",options:{argv:sm(f,p,h),usePlugins:[...Il]},signal:t.signal??new AbortController().signal,logger:Wh()})}finally{c.dispose(),await a()}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)===Ln.pathToFileURL(C.realpathSync(process.argv[1])).href){try{xl.initTelemetry({service:"backlog",role:"cli",logSink:"file"})}catch(e){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${e instanceof Error?e.message:String(e)}); telemetry records will be silently dropped this process`)}im().catch(e=>{console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1})}exports.AmbiguousHumanIdError=Va;exports.BacklogItemNotFoundError=Mp;exports.CitationRequiredError=Dp;exports.ClaimHeldError=Up;exports.DependencyCycleError=lA;exports.InvalidArgumentError=ae;exports.ReasonRequiredError=Lp;exports.TERMINAL_DISMISSED_STATUSES=Rp;exports.TERMINAL_DONE_STATUSES=Tp;exports.TERMINAL_STATUSES=qa;exports.TERMINAL_WORKAROUND_STATUSES=Cp;exports.addCitation=jh;exports.addDependency=Th;exports.appendNote=Ih;exports.archiveResolved=Ph;exports.assignItem=kh;exports.attachToPlan=Bh;exports.auditTrail=Kh;exports.backlogEnvironmentSpec=$a;exports.blockers=vh;exports.buildBacklogApigenPackage=Qa;exports.buildBacklogEnv=va;exports.buildChangelogSection=ch;exports.claimItem=Sh;exports.classifyStatus=th;exports.closeGraphBacklogStore=tf;exports.createItem=fh;exports.dependencyGraph=wh;exports.detectPriority=rh;exports.detectStatus=nh;exports.exportJson=Vh;exports.getItem=dh;exports.importFromMarkdown=Fh;exports.installSkill=Xh;exports.isTerminalStatus=Be;exports.linkRelated=Rh;exports.listItems=hh;exports.mergeItems=Lh;exports.migrationStatus=Gh;exports.normalizeLegacyStatus=eh;exports.openGraphBacklogStore=hi;exports.parseBacklogMarkdown=pj;exports.parseBacklogMarkdownWithDiagnostics=sh;exports.prefixCommand=sm;exports.readyItems=$h;exports.releaseClaim=Oh;exports.removeDependency=Ch;exports.renderItemsToMarkdown=ah;exports.renderToMarkdown=qh;exports.renewClaim=Nh;exports.requiresCitation=Ir;exports.requiresReason=xr;exports.resolveBacklogDbPath=wa;exports.resolveBacklogScope=rp;exports.resolveCommandPrefix=om;exports.resolveItem=xh;exports.runBacklogCli=im;exports.runInstallSkillCommand=tm;exports.runServeCommand=rm;exports.setMigrationPhase=Hh;exports.setPriority=Uh;exports.softDeleteItem=mh;exports.splitItem=Dh;exports.spotlight=yh;exports.staleClaims=Eh;exports.startBacklogServer=Qh;exports.startWork=_h;exports.stats=gh;exports.suggestClaimantIdentity=YS;exports.supersedeItem=Mh;exports.toImportItems=uh;exports.topoOrder=bh;exports.transitionStatus=Ah;exports.updateItem=ph;exports.version=zh;
261
+ `;function Ym(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:i,mcpOnly:s}=zm(e,"install"),a=s?[]:ia(r,o,t,n),c=i?[]:r.map(d=>Wm(d,o,t,n));return{skill:a,mcp:c}}async function Xm(e){if(e.includes("--help")||e.includes("-h")){console.log(Wr);return}let t;try{t=Ym(e)}catch(n){if(n instanceof X)return So(n,Wr);throw n}for(const n of t.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of t.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(t))}const zr=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
262
+
263
+ Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
264
+ process's own configured transports to the way an agent host or a script
265
+ expects to reach it.
266
+
267
+ --transport <name> mcp | http | both (default: mcp)
268
+ --port <N> HTTP listen port (default: 3300; ignored for mcp-only)
269
+ --host <name> HTTP listen host (default: 127.0.0.1; ignored for mcp-only)
270
+
271
+ Examples:
272
+ backlog serve
273
+ backlog serve --transport http --port 3300
274
+ backlog serve --transport both --host 0.0.0.0
275
+ `;function Qm(e){let t="mcp",n,r;for(let i=0;i<e.length;i++){const s=e[i];if(s==="--transport")t=e[++i];else if(s==="--port")n=Number(e[++i]);else if(s==="--host")r=e[++i];else throw new X(`backlog serve: unknown argument "${s}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new X(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function ca(e,t={}){if(e.includes("--help")||e.includes("-h")){console.log(zr);return}let n;try{n=Qm(e)}catch(s){if(s instanceof X)return So(s,zr);throw s}const r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=na({...n,...t,signal:r.signal}),i=t.namespace==="sandbox"?O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Mn.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...i!==void 0?{logDir:i}:{}})}catch(s){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${s instanceof Error?s.message:String(s)}); telemetry records will be silently dropped this process`)}await o}const ko=["limit","offset","sort","direction"],da=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],Ao=["status","priority"],Gt=["fields"],Zm={"claimed-by":"claimedBy","project-path":"projectPath"},la=[...ko,...Gt,...da,...Ao].map(e=>`--${e}`).sort(),eg=new Set([...ko,...Gt]),tg=new Set([...Ao,...Gt]),ng=new Set([...ko,...Gt,...da,...Ao]),og=new Set(["limit","offset"]),ua=['backlog search "<natural-language query>" [flags]',"",'Shorthand for `backlog query --input \'{"text": "<query>", ...}\'` — the same',"command, the same JSON envelope, the same exit codes. The query text is","matched semantically when the embedding space is populated, and by keyword","(FTS) when it is not.","","Paging / ranking:"," --limit <n> max items to return"," --offset <n> skip the first n"," --sort <s> override the derived default (relevance / textMatch)"," --direction <d> asc | desc"," --fields <a,b,c> projection; add _score to see ranking scores","","Filters (all compose with the query text):"," --status <s> open | closed | OPEN,IN_PROGRESS | …"," --priority <p> CRITICAL | HIGH | MEDIUM | LOW (comma-separated for several)"," --kind <k> BUG | DEBT | FEAT | …"," --project-path <p> component's repo-relative path (component.meta.path)"," --plan <uid|title> the parent plan issue this item is filed under (part_of)"," --assignee <a> durable owner"," --claimed-by <c> ephemeral claim holder"," --grep <q> extra keyword predicate. Composes with the query text ONLY"," once the embedding space is populated — without it the query"," text IS the keyword query and the two collide (§2.1b step 1).","","More-like-this:",' --anchor <ID> nearest neighbours of an EXISTING item (view:"similar").'," Replaces the positional query rather than refining it."].join(`
276
+ `);function Yr(e,t,n,r){if(!r){e[t]=n;return}const o=e[t]??[];e[t]=[...o,...n.split(",").map(i=>i.trim()).filter(i=>i.length>0)]}function fa(e){if(e.includes("--help")||e.includes("-h"))return{kind:"help",text:ua};const t={},n={};let r,o=0;for(;o<e.length;){const a=e[o];if(!a.startsWith("--")){if(r!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};r=a,o+=1;continue}let c=a.slice(2),d;const l=c.indexOf("=");if(l!==-1&&(d=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!ng.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${la.join(", ")}`};o+=1;let u;if(d!==void 0)u=d;else{if(o>=e.length)return{kind:"error",message:`Missing value for --${c}`};u=e[o],o+=1}const f=tg.has(c);eg.has(c)?Yr(t,c,u,f):Yr(n,Zm[c]??c,u,f)}for(const a of["status","priority"]){const c=n[a];(c==null?void 0:c.length)===1&&(n[a]=c[0])}for(const a of og){const c=t[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(t[a]=Number(c))}const i=n.anchor;if(i!==void 0&&r!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(i===void 0&&r===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const s={...t};return i!==void 0?s.view="similar":s.text=r,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function pa(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return Me(t).cli.path.slice(0,-1)}const Xr=[jt];function rg(e,t,n){const r={host:n,operations:t},o=new Set;for(const i of e){const s=i.capabilities.mount;if(!s)continue;const a=s.operations(r,void 0,void 0);for(const c of a){const[d]=Me(c).cli.path;d!==void 0&&o.add(d)}}return o}function ma(e,t,n){var o;return e.length===0?[...e]:(o=e[0])!=null&&o.startsWith("-")?[...e]:e[0]!==void 0&&n.has(e[0])?[...e]:t.length>0&&t.every((i,s)=>e[s]===i)?[...e]:[...t,...e]}function jo(e){const t=[],n=[];let r=!1;for(let i=0;i<e.length;i++){const s=e[i];if(s!==void 0){if(s.startsWith("--namespace=")){const a=s.slice(12);a===""?r=!0:t.push(a);continue}if(s==="--namespace"){const a=e[i+1];a===void 0||a.startsWith("-")?r=!0:(t.push(a),i++);continue}n.push(s)}}const o=new Set(t);return{argv:n,namespace:t[t.length-1],missingValue:r,conflicting:o.size>1}}async function ig(e){let t;for(let s=0;s<e.length;s++){const a=e[s];if(a!==void 0){if(a==="--out"||a==="-o"){const c=e[s+1];c!==void 0&&!c.startsWith("-")&&(t=c,s++)}else if(a.startsWith("--out=")){const c=a.slice(6);c!==""&&(t=c)}}}if(!t){const s=le("invalid_argument","ir-artifact: --out <path> is required");console.error(JSON.stringify(s)),process.exitCode=ke(s);return}const n=k.join(Vt(),"api.d.ts");if(!O.existsSync(n)){const s=le("internal",`ir-artifact: ${n} does not exist — run "nx build backlog" first`);console.error(JSON.stringify(s)),process.exitCode=ke(s);return}const r=k.resolve(t),{buildBakedOperations:o}=await Promise.resolve().then(()=>ha),i=await o(n);await _m({apiDts:n,outFile:r,extractorVersion:yo,operations:i}),console.log(JSON.stringify({ok:!0,out:r,operations:i.length}))}async function ga(e,t={}){var v;const{argv:n,namespace:r,missingValue:o,conflicting:i}=jo(e??process.argv.slice(2)),s={...t};if(o){const h=le("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=ke(h);return}if(i){const h=e??process.argv.slice(2),y=new Set;for(let b=0;b<h.length;b++){const S=h[b];S!==void 0&&(S.startsWith("--namespace=")?y.add(S.slice(12)):S==="--namespace"&&h[b+1]!==void 0&&y.add(h[b+1]))}const w=le("invalid_argument",`Invalid argument "namespace": conflicting values ${[...y].map(b=>`"${b}"`).join(", ")}`);console.log(JSON.stringify(w)),process.exitCode=ke(w);return}if(r!==void 0&&!((v=Ue.namespaces)!=null&&v.includes(r))){const h=Ue.namespaces??[],y=ms(r,h),w=`must be one of ${h.map(S=>`"${S}"`).join(", ")}`+(y.length>0?` (did you mean ${y.map(S=>`"${S}"`).join(" or ")}?)`:""),b=le("invalid_argument",`Invalid argument "namespace": ${w}`);console.log(JSON.stringify(b)),process.exitCode=ke(b);return}r!==void 0&&(s.namespace=r);const a=s.namespace??"production";s.adhdRoot===void 0&&process.env.ADHD_ROOT&&(s.adhdRoot=process.env.ADHD_ROOT);const c=h=>h.includes(`${k.sep}backlog-sandbox-`);if(a==="sandbox"){s.adhdRoot!==void 0&&!c(s.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${s.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),s.adhdRoot=void 0),s.adhdRoot===void 0&&(s.adhdRoot=O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-")),console.error(`[backlog] --namespace sandbox: isolated store at ${s.adhdRoot} (not auto-deleted — pass ADHD_ROOT=${s.adhdRoot} to reuse it, or remove it yourself when done)`)),s.namespace="sandbox";const h=k.join(s.adhdRoot,"backlog","sandbox");O.mkdirSync(h,{recursive:!0}),O.writeFileSync(k.join(h,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
277
+ # an absence-of-file default. embedding.enabled is off so a sandboxed
278
+ # run never pays a real model-load cost or opens a real vector store.
279
+ embedding:
280
+ enabled: false
281
+ `)}if(s.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=k.join(s.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:Ge(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await ig(n.slice(1));return}if(n[0]==="store-check"){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=Ge(h);let w;try{w=await Rt(y,h.config.db.busyTimeoutMs);const{total:b,observed:S}=await Li(w.adapter);console.log(JSON.stringify({ok:!0,dbPath:y,total:b,kinds:S,expectedKinds:[...no]}));return}catch(b){if(b instanceof xi){console.error(JSON.stringify({ok:!1,dbPath:y,error:{code:"store_vocabulary_mismatch",message:b.message},observed:b.observed,expectedKinds:b.recognized})),process.exitCode=1;return}throw b}finally{w&&await In(w)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present; non-zero on a mismatch"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await sa(n.slice(1));return}if(n[0]==="install"){await Xm(n.slice(1));return}if(n[0]==="serve"){await ca(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(vo()));return}let l;if(n[0]==="search"){const h=fa(n.slice(1));if(h.kind==="help"){console.log(h.text);return}if(h.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:h.message})),process.exitCode=2;return}l=h.argv}let u;const f=async()=>{if(!u){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=await Rt(Ge(h),h.config.db.busyTimeoutMs);u={store:y,ctx:{store:y,env:h}}}return u.ctx};let g;const p=()=>(g||(g=In(u==null?void 0:u.store)),g),m=Qi(p);try{const{pkg:h,operations:y}=await bo(f,{adhdRoot:s.adhdRoot}),w=l??n,b=pa(y),S=rg(Xr,y,h.id);await Dn(dl)({packages:[h],operations:y,outputDir:"",options:{argv:ma(w,b,S),usePlugins:[...Xr],exitCode:A=>Ss(A)?ke(A):void 0},signal:s.signal??new AbortController().signal,logger:ea()});const E=w.length>1&&w[0]!=="batch"&&(w.includes("--help")||w.includes("-h"));E&&console.log("See also: `adhd-backlog batch action` — run this SAME operation over many items in one call instead of N one-at-a-time invocations (skill/SKILL.md §5)."),E&&w[0]==="query"&&console.log(`Notes:
282
+ - view:"similar" additionally requires filter.anchor (uid of the reference issue) OR filter.semantic (free text) — neither given throws invalid_argument.
283
+ - view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{m.dispose(),await p()}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)===et.pathToFileURL(O.realpathSync(process.argv[1])).href){const{namespace:e,argv:t}=jo(process.argv.slice(2)),n=t[0]==="ir-artifact",r=e==="sandbox"?O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{Mn.initTelemetry({service:"backlog",role:"cli",logSink:"file",...r!==void 0?{logDir:r}:{}})}catch(o){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${o instanceof Error?o.message:String(o)}); telemetry records will be silently dropped this process`)}ga().catch(o=>{console.error(o instanceof Error?o.stack??o.message:String(o)),process.exitCode=1})}const sg=yo,_o="backlog";function No(e,t){return{sourceFile:e,namespace:_o,tsconfig:t,dropFileSegment:!0}}function ag(e={}){return Mu(e)}function cg(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function dg(e={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:bm({cache:ag(e),extractorVersion:sg})}}}}let Qr;function lg(e={}){return Qr??(Qr=Gc(cg()?[dg(e)]:[],t=>{var n;return wi(No(t.source,typeof((n=t.extractorOptions)==null?void 0:n.tsconfig)=="string"?t.extractorOptions.tsconfig:void 0))})),Qr}async function ug(e){return wi(No(e))}async function fg(e={}){const t=k.join(Vt(),"api.d.ts");return lg(e)({source:t,host:"ts",namespace:_o,extractorOptions:{}})}const ha=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:_o,buildBacklogExtractOptions:No,buildBakedOperations:ug,extractApiOperationsLive:fg},Symbol.toStringTag,{value:"Module"}));exports.BACKLOG_ERROR_CODES=vs;exports.BACKLOG_EXIT_CODE=go;exports.RagNotConfiguredError=Es;exports.SEARCH_FLAGS=la;exports.SEARCH_HELP=ua;exports.backlogEnvironmentSpec=Ue;exports.buildBacklogApigenPackage=bo;exports.buildBacklogEnv=$e;exports.buildSearchArgv=fa;exports.claim=Hs;exports.closeGraphBacklogStore=Xi;exports.create=Bs;exports.delete=Js;exports.embeddingStatus=Ms;exports.errorEnvelope=le;exports.exitCodeForEnvelope=ke;exports.get=Ps;exports.installSkill=ra;exports.isBacklogErrorCode=bs;exports.isOutcomeEnvelope=Ss;exports.isOutcomeError=Ap;exports.isOutcomeOk=kp;exports.lookup=Fs;exports.move=Gs;exports.okEnvelope=ho;exports.openCurve=Ds;exports.openGraphBacklogStore=Rt;exports.partOfRollup=Us;exports.prefixCommand=ma;exports.priorityMatrix=Ls;exports.query=xs;exports.readBacklogVersionInfo=vo;exports.relate=Vs;exports.resolveBacklogDbPath=Ge;exports.resolveBacklogScope=fo;exports.resolveCommandPrefix=pa;exports.resolveExpectedMcpToolNames=Cm;exports.rmLocation=Xs;exports.runBacklogCli=ga;exports.runInstallSkillCommand=sa;exports.runServeCommand=ca;exports.startBacklogServer=na;exports.stripNamespaceFlag=jo;exports.suggestClaimantIdentity=Du;exports.transition=Ks;exports.update=qs;exports.upsertComponent=zs;exports.upsertLocation=Ys;exports.upsertProject=Ws;