@adhd/backlog 1.0.5 → 1.0.6

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 (58) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +194 -39
  3. package/api.d.ts +87 -0
  4. package/api.ir.json +1 -1
  5. package/citation.d.ts +176 -0
  6. package/envelope.d.ts +35 -1
  7. package/index.d.ts +23 -3
  8. package/index.js +106 -58
  9. package/index.mjs +11627 -7068
  10. package/ir-artifact.d.ts +7 -3
  11. package/lifecycle.d.ts +49 -0
  12. package/package.json +5 -5
  13. package/query/canonical.d.ts +16 -0
  14. package/query/card.d.ts +116 -4
  15. package/query/get.d.ts +8 -1
  16. package/query/index.d.ts +1 -0
  17. package/query/query.d.ts +20 -13
  18. package/query/redirect.d.ts +30 -0
  19. package/query/resolve.d.ts +48 -0
  20. package/query/similar-clusters.d.ts +8 -0
  21. package/query/similarity-signals.d.ts +47 -0
  22. package/query/spec-staleness.d.ts +21 -0
  23. package/query/types.d.ts +249 -34
  24. package/query/verdict-core.d.ts +21 -0
  25. package/query/verdict.d.ts +22 -0
  26. package/query/views/catalog.d.ts +47 -0
  27. package/query/views/registry.d.ts +27 -7
  28. package/query/views/report.d.ts +49 -0
  29. package/query/views/semantic.d.ts +28 -5
  30. package/query/views/stats.d.ts +38 -2
  31. package/readiness.d.ts +29 -0
  32. package/retry-policy.d.ts +44 -0
  33. package/serve.d.ts +1 -1
  34. package/server.d.ts +71 -3
  35. package/service-config.d.ts +109 -0
  36. package/service-errors.d.ts +51 -0
  37. package/skill/SKILL.md +688 -81
  38. package/store/catalog-invariant-guard.d.ts +4 -4
  39. package/vocabulary.d.ts +48 -0
  40. package/write/anchor-check.d.ts +139 -0
  41. package/write/attestation.d.ts +64 -0
  42. package/write/catalog-merge.d.ts +15 -8
  43. package/write/catalog.d.ts +63 -0
  44. package/write/citation-path.d.ts +31 -0
  45. package/write/citation.d.ts +157 -0
  46. package/write/create-issue.d.ts +143 -29
  47. package/write/errors.d.ts +159 -0
  48. package/write/gate.d.ts +67 -0
  49. package/write/merge-project.d.ts +54 -0
  50. package/write/obligation.d.ts +133 -0
  51. package/write/relate.d.ts +1 -1
  52. package/write/revision.d.ts +27 -0
  53. package/write/similarity-scan.d.ts +84 -0
  54. package/write/spec-revision.d.ts +131 -0
  55. package/write/spec-revision.reconcile.d.ts +48 -0
  56. package/write/transition.d.ts +13 -2
  57. package/write/tx.d.ts +21 -1
  58. package/write/update.d.ts +23 -1
package/index.js CHANGED
@@ -1,50 +1,51 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("node:fs"),z=require("node:os"),k=require("node:path"),ot=require("node:url"),Hn=require("@adhd/sox-telemetry"),dt=require("pino"),ui=require("ajv"),Ya=require("ajv-formats"),he=require("@adhd/sox-store-adapter"),Xa=require("@adhd/sox-graph-store"),Lt=require("node:fs/promises"),me=require("node:crypto"),Qa=require("fastify"),Mo=require("node:http"),Za=require("@modelcontextprotocol/sdk/server/index.js"),ec=require("@modelcontextprotocol/sdk/server/stdio.js"),tc=require("@modelcontextprotocol/sdk/server/sse.js"),nc=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Fo=require("@modelcontextprotocol/sdk/types.js"),oc=require("@adhd/sox-hybrid-search"),Vn=require("node:module"),rc=require("yaml");var $=typeof document<"u"?document.currentScript:null;function fi(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const fn=fi(k),ve=fi(Lt),pn="$apigen";class Bo extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function ic(e){const t=new Map;return{register(o,r){if(t.has(o.id)&&!(r!=null&&r.override))throw new Bo(`E_DUP_CODEC: a codec is already registered for id "${o.id}"`);t.set(o.id,o)},resolve(o){for(const r of t.values())if(r.matches(o))return r},get(o){return t.get(o)},ids(){return[...t.keys()]},freeze(){const o=new Map(t),r={register(){throw new Bo("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(i){for(const s of o.values())if(s.matches(i))return s},get(i){return o.get(i)},ids(){return[...o.keys()]},freeze(){return r}};return r}}}const Ne="x-apigen-logical",Gn="x-apigen-codec",mn="x-apigen-ctor",gn="x-apigen-tojson",sc="0.1.0";function Ko(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 Ie(e,t,n){const o=n.registry.resolve(t);if(o)return o.encode(e,t,n);const r=t.$ref;if(typeof r=="string"){const a=n.resolve(r);return Ie(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=pi(e,i,t,n);return Ie(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return Je(e,t,n);const a=t.items;if(!a)return e.map(d=>_e(d));const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?_e(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 Je(e,t,n);const a=t.properties;if(!a)return _e(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}`}))}return d}return s==null?Je(e,t,n):_e(e)}function $e(e,t,n){const o=n.registry.resolve(t);if(o)return o.decode(e,t,n);const r=t.$ref;if(typeof r=="string"){const a=n.resolve(r);return $e(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=pi(e,i,t,n);return $e(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:$e(d,u,{...n,path:`${c}/${l}`})}):e.map((d,l)=>$e(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]=$e(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?hn(e,n):e}function pi(e,t,n,o){var c;const r=n.discriminator;if(r!=null&&r.propertyName){const d=r.propertyName,l=e!==null&&typeof e=="object"?e[d]:void 0;if(typeof l=="string"){if(r.mapping){const u=r.mapping[l];if(u){const f=t.find(m=>m.$ref===u);if(f)return f}}for(const u of t){const m=(c=jt(u,o).properties)==null?void 0:c[d];if(!m)continue;const p=m.enum;if(m.const===l||Array.isArray(p)&&p.includes(l))return u}}}const i=ac(e,t,o);if(i)return i;let s,a=-1;for(const d of t){const l=jt(d,o),u=Wn(e,l,o);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:t[0]??{}}function jt(e,t){const n=e.$ref;return typeof n=="string"?t.resolve(n):e}function qo(e){if("const"in e)return e.const;const t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function ac(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return;const o=e,r=t.map(s=>jt(s,n)),i=new Set;for(const s of r){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))qo(d)!==void 0&&i.add(c)}for(const s of i){const a=r.map(f=>{const m=f.properties,p=m==null?void 0:m[s];return p?qo(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=o[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&Wn(e,r[u],n)!==null)return t[u]}}function cc(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 Wn(e,t,n){const o=t.oneOf;if(Array.isArray(o)){let l=null;for(const u of o){const f=Wn(e,jt(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const r=t.type,i=cc(e);if(typeof r=="string"){if(!(r===i||r==="number"&&i==="integer"))return null}else if(Array.isArray(r)&&!r.some(u=>u===i||u==="number"&&i==="integer"))return null;if(e===null||typeof e!="object"||Array.isArray(e))return typeof r=="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 Je(e,t,n){var o;for(const r of n.registry.ids()){const i=n.registry.get(r);if((o=i==null?void 0:i.ownsValue)!=null&&o.call(i,e))return{[pn]:r,v:i.encode(e,i.schema,n)}}if(Array.isArray(e))return e.map(r=>Je(r,{},n));if(mi(e)){const r={};for(const[i,s]of Object.entries(e))s!==void 0&&(r[i]=Je(s,{},n));return r}return _e(e)}function mi(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function hn(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&pn in e){const n=e,o=n[pn],r=t.registry.get(o);if(r)return r.decode(n.v,r.schema,t)}if(Array.isArray(e))return e.map(n=>hn(n,t));if(mi(e)){const n={};for(const[o,r]of Object.entries(e))n[o]=hn(r,t);return n}return e}function _e(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(_e);if(typeof e=="object"){const t={};for(const[n,o]of Object.entries(e))o!==void 0&&(t[n]=_e(o));return t}return null}function Ho(e,t){const n=new Set,o=[e];for(;o.length>0;){const r=o.pop();if(!r||n.has(r))continue;n.add(r);const i=r.$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}`)}o.push(u)}continue}const s=r.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&o.push(u);const a=r.properties;if(a)for(const u of Object.values(a))o.push(u);const c=r.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&o.push(u);else typeof c=="object"&&c!==null&&o.push(c);const d=r.additionalProperties;typeof d=="object"&&d!==null&&o.push(d);const l=r.propertyNames;typeof l=="object"&&l!==null&&o.push(l)}}function dc(e){return{encode(t,n,o){const r=Ko(e,o);return Ie(t,n,r)},decode(t,n,o){const r=Ko(e,o);return $e(t,n,r)}}}const Jn={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)}},zn={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 Yn={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}},Xn={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"))}},lc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Qn={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"&&!lc.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},yn="NaN",wn="Infinity",vn="-Infinity",uc=new Set([yn,wn,vn]),Zn={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)?yn:e===1/0?wn:e===-1/0?vn:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===yn)return NaN;if(e===wn)return 1/0;if(e===vn)return-1/0;const o=Number(e);if(!Number.isNaN(o))return o}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...uc].join(", ")}.`);return NaN}},fc=[Jn,zn,Yn,Xn,Qn,Zn];function pc(e,t={}){for(const n of fc)e.register(n,{override:t.override??!1})}const mc=12;function gc(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,o,r]=n,i=o==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(r)]}function Vo(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function hc(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 yc(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 Go(e,t,n){const o=e.properties??{},r=e.required??[],i={};for(const s of r){const a=o[s];i[s]=a!==void 0?De(a,t,n+1):`<${s}>`}return i}function wc(e,t,n){const o=Array.isArray(e.items)?e.items[0]:e.items;return o?[De(o,t,n+1)]:[]}function De(e,t=e??{},n=0){if(!e||n>mc)return null;if(typeof e.$ref=="string"){const i=gc(e.$ref,t);return i!==void 0?De(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 Go({...e,properties:i,required:s},t,n)}const o=Vo(e.oneOf)??Vo(e.anyOf);if(o)return De(o,t,n+1);switch(hc(e)){case"object":return Go(e,t,n);case"array":return wc(e,t,n);case"string":return yc(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function gi(e){if(!e)return;const t=De(e);return`Example: ${JSON.stringify(t)}`}Jn.id,zn.id,Yn.id,Xn.id,Qn.id,Zn.id;const hi=ic();pc(hi);const yi=dc(hi.freeze());function wi(e,t){var o;const n=((o=e.input)==null?void 0:o.properties)??{};return t in n}function bn(e){var n,o;const t=(o=(n=e.input)==null?void 0:n.properties)==null?void 0:o.data;return Object.keys((t==null?void 0:t.properties)??{})}function vc(e,t){var r,i,s;const n=(s=(i=(r=e.input)==null?void 0:r.properties)==null?void 0:i.data)==null?void 0:s.properties,o=n==null?void 0:n[t];return o!==void 0?o:void 0}function bc(e,t){return t===void 0||e===void 0?e:yi.decode(e,t)}function en(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:yi.encode(e,n)}async function Sc(e,t,n,o,r,i){const a=bn(n).map(d=>bc(i[d],vc(n,d)));if(wi(n,"session")&&t){const d=await t({session:r.session}),l=await e[o](d,...a);return en(l,n)}if(n.hasCtx){const d=t?await t(r):void 0,l=await e[o](d,...a);return en(l,n)}const c=await e[o](...a);return en(c,n)}class rt{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 Ec(e=[]){return async function(n,o,r){const i=r.schemas[n];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>Sc(r.fns,r.createClient,i,n,o.envelope,o.domainArgs);return e.reduceRight((c,d)=>()=>d(o,c),s)()}}function Wo(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function vi(e,t,n={}){const o=e.split("/");if(o.length<2||o.some(d=>d.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[r,...i]=o,s=r.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Wo(s),path:i.map(Wo),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 ue=Vn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);let lt;function bi(){return lt||(lt=ue("ts-morph").Project,lt)}const Si=Symbol.for("adhd.apigen.extraction-session");function eo(e,t){const n=[...e.getImportDeclarations().map(o=>o.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(o=>o.getModuleSpecifierSourceFile())];for(const o of n){if(!o)continue;const r=o.getFilePath();if(!r.includes("/node_modules/")&&!t.has(r)){t.add(r);try{o.refreshFromFileSystemSync()}catch{}eo(o,t)}}}function Ei(e){try{const t=R.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const kt=new Map,Jo=new Map;function kc(e,t,n){const o=t??"",r=kt.get(o);let i=n;if(r&&r.fileVersions.size>0){const c=[n],d=[...r.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=Jo.get(s);return(a==null?void 0:a.version)!==i&&(a={version:i,schemas:new Map},Jo.set(s,a)),a.schemas}let tn;function Ac(){if(!tn){const e=bi();tn=new e({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return tn}function ki(e){const t=Ac(),n=t.getSourceFile(e),o=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const r=new Set([e]);return eo(o,r),[...r].sort()}function _c(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[Si]:!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 i=r??"",s=r?this.statVersion(r):"";let a=kt.get(i);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=bi();a={project:r?new c({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},kt.set(i,a),e.projectsBuilt++}return a.project},sourceFileFor(r,i){const s=this.projectFor(i),a=kt.get(i??""),c=this.statVersion(r);let d=s.getSourceFile(r);if(d===void 0?d=s.addSourceFileAtPath(r):a&&a.fileVersions.get(r)!==c&&d.refreshFromFileSystemSync(),a==null||a.fileVersions.set(r,c),a){const l=new Set([r]);eo(d,l);for(const u of l)u!==r&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(r){let i=t.get(r);return i===void 0&&(i=Ei(r),t.set(r,i)),i},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function jc(e){const t=e;if(t[Si]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const zo=new Set(["string","number","boolean","integer"]);function Nc(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"?zo.has(n):Array.isArray(n)?n.every(o=>zo.has(o)||o==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(o=>["string","number","boolean"].includes(typeof o)):!1}function Ai(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(Nc)}function Rc(e){const t={},n=o=>{for(const r of["definitions","$defs"]){const i=o[r];if(i)for(const[s,a]of Object.entries(i)){const c=s.startsWith("#/")?s:`#/${r}/${s}`;t[c]=a}}};for(const o of Object.values(e.schemas))n(o.input),n(o.output);if(Object.keys(t).length!==0)for(const[o,r]of Object.entries(e.schemas))try{Ho(r.input,t),Ho(r.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${o}": ${i.message}`)}}function Oc(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(o=>`"${o}"`).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 Tc(e,t,n){Rc(e);const o={};for(const[r,i]of Object.entries(e.schemas)){const s={},a=i.input.properties??{},c=i.input.required??[],d={},l=[],u={};for(const b of t)if(b.envelope&&s[b.id]!==!1)for(const[h,y]of Object.entries(b.envelope))d[h]=y,u[h]=b.id,l.includes(h)||l.push(h);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},m=i.safe===!0||Ai(i.input),p=i.input.definitions,g=i.input.$defs;o[r]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:Oc(Object.keys(d),Object.keys(a).length>0),...p?{definitions:p}:{},...g?{$defs:g}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return o}const Ic=8;function $c(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let Cc=0;async function Pc(e,t,n,o){const r=`__ApigenProbe_${process.pid}_${Cc++}`;let i;try{i=t.addTypeAlias({name:r,type:n});const s=i.getType();return await o(s)}catch{return}finally{try{i==null||i.remove()}catch{}}}async function _i(e,t,n){if(n>Ic)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 o=e.getUnionTypes(),r=o.filter(p=>p.isBooleanLiteral()),i=r.some(p=>p.getText()==="true"),s=r.some(p=>p.getText()==="false");let a=!1;const c=o.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(o.every(p=>p.isStringLiteral())&&o.length>0)return{type:"string",enum:o.map(p=>p.getLiteralValue())};if(o.every(p=>p.isNumberLiteral())&&o.length>0)return{type:"number",enum:o.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?i&&s?{type:"boolean"}:{type:"boolean",const:i}:_i(p,t,n+1))),f=Ut(u);return{oneOf:Dc(Uc(u)),...f?{discriminator:f}:{},[Ne]:"union"}}if(e.isArray()){const o=e.getArrayElementType();return{type:"array",items:o?await t(o.getText()):{}}}if(e.isTuple()){const o=e.getTupleElements(),r=await Promise.all(o.map(i=>t(i.getText())));return{type:"array",items:r,minItems:r.length,maxItems:r.length}}if(e.isObject()){const o=e.getStringIndexType(),r=e.getNumberIndexType(),i=o??r,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 m;if(f)try{m=d.getTypeAtLocation(f)}catch{m=void 0}if(m!==void 0&&m.getCallSignatures().length>0)continue;const p=m!==void 0?$c(m,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 xc(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 Lc=new Set(["required","enum","type"]);function Sn(e,t){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e)){const r=e.map(i=>Sn(i));return t!==void 0&&Lc.has(t)&&r.sort(),`[${r.join(",")}]`}const n=e;return`{${Object.keys(n).filter(r=>n[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${Sn(n[r],r)}`).join(",")}}`}function Uc(e){const t=new Set,n=[];for(const o of e){const r=Sn(o);t.has(r)||(t.add(r),n.push(o))}return n}function Dc(e){if(e.length<2)return e.slice();const t=e.map(xc),n=e.map((r,i)=>t[i]?i:-1).filter(r=>r>=0);if(n.length===0||n.length===e.length)return e.slice();const o=e.map((r,i)=>t[i]?-1:i).filter(r=>r>=0);return e.map((r,i)=>{if(!t[i])return r;const s=e.filter((a,c)=>c!==i&&(o.includes(c)||t[c]&&c<i));return{allOf:[r,{not:{anyOf:s}}]}})}function Ut(e){if(e.length<2)return;const t=[];for(const o of e){if(o.type!=="object")return;const r=o.properties;if(!r||typeof r!="object")return;t.push(r)}const n=Object.keys(t[0]).filter(o=>t.every(r=>Object.prototype.hasOwnProperty.call(r,o)));for(const o of n){const r=[];let i=!0;for(const a of t){const c=a[o],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}r.push(String(l[0]))}if(!i||new Set(r).size!==r.length)continue;const s={};return r.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:o,mapping:s}}}function At(e,t,n){if(t>6)return{};const o=e.trim();if(o==="string")return{type:"string"};if(o==="number")return{type:"number"};if(o==="boolean")return{type:"boolean"};if(o==="null")return{type:"null"};if(o==="undefined")return{type:"null"};const r=En[o];if(r!==void 0)return r;if(n!=null&&n.size){const i=n.get(o);if(i!==void 0){const s=En[i];if(s!==void 0)return s}}if(o.endsWith("[]"))return{type:"array",items:At(o.slice(0,-2),t+1,n)};if(o.includes("|")){const i=o.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=>At(c,t+1,n)),a=Ut(s);return{oneOf:s,...a?{discriminator:a}:{},[Ne]:"union"}}if(o.startsWith("{")&&o.endsWith("}")){const i=o.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("?","")]=At(d,t+1,n))}return{type:"object",properties:s}}return{}}function ji(e){const t=[];let n=0,o=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(o,i).trim()),o=i+1)}const r=e.slice(o).trim();return r.length>0&&t.push(r),t}function Mc(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function Fc(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function Bc(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 ji(n)}async function Kc(e,t){const n=e.trim(),o=Mc(n);if(o!==void 0){const s=ji(o);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 r=Fc(n);if(r!==void 0)return{type:"array",items:await t(r),uniqueItems:!0};const i=Bc(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 Ni={"decimal.js":"Decimal"},En={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"}},Yo={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Xo(e){var n;const t=new Map;for(const o of e.getImportDeclarations()){const r=o.getModuleSpecifierValue(),i=Ni[r];if(!i)continue;const s=o.getDefaultImport();if(s){const a=s.getText();a!==i&&t.set(a,i)}for(const a of o.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==i&&t.set(c,i)}}return t}function qc(e,t){return n=>{n.addNodeParser({supportsNode(o){var i,s,a;if(o.kind!==t)return!1;const r=((i=o.typeName)==null?void 0:i.escapedText)??((a=(s=o.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return r!==void 0&&Object.prototype.hasOwnProperty.call(Yo,r)},createType(o){var a,c,d;const r=((a=o.typeName)==null?void 0:a.escapedText)??((d=(c=o.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:i,StringType:s}=kn();return new i(new s,{format:Yo[r]},!1)}}),n.addNodeParser({supportsNode(o){return o.kind===e},createType(){const{AnnotatedType:o,StringType:r}=kn();return new o(new r,{format:"int64"},!1)}})}}let ut;function kn(){return ut||(ut=ue("ts-json-schema-generator"),ut)}let He;function Hc(){if(He)return He;try{const e=k.dirname(ue.resolve("ts-json-schema-generator/package.json"));He=ue(ue.resolve("typescript",{paths:[e]}))}catch{He=ue("typescript")}return He}const ye=new Map;function Vc(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function Gc(e){const t=ye.get(e);return t&&(ye.delete(e),ye.set(e,t)),t}function Wc(e,t){const n=Vc();if(n!==0)for(ye.delete(e),ye.set(e,t);ye.size>n;){const o=ye.keys().next().value;ye.delete(o)}}function Jc(e,t){return`${e}\0${t??""}`}const zc=new Set(["zod",/^zod\/./]);function Yc(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const o of zc)if(typeof o=="string"){if(n===o)return!0}else if(o.test(n))return!0}return!1}function Xc(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const o=Object.keys(n);if(o.length===0)continue;const r=new Set(o.filter(i=>/zod/i.test(i)));for(const[i,s]of Object.entries(n)){if(r.has(i)||typeof s!="object"||s===null)continue;const a=s,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const d of r)if(c.includes(d)){r.add(i);break}}}for(const i of r)delete n[i]}An(e)}function An(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const o of Object.keys(e))if(o==="$ref"&&typeof e[o]=="string"){const r=e[o];/zod/i.test(r)&&delete e[o]}for(const[,o]of Object.entries(e))if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const r of o)typeof r=="object"&&r!==null&&An(r,n);else An(o,n)}}function Qc(e){const t=new Set;for(const o of["$defs","definitions"]){const r=e[o];if(r&&typeof r=="object")for(const i of Object.keys(r))t.add(i)}const n=_n(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 _n(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[o,r]of Object.entries(e))if(o==="$ref"&&typeof r=="string"){const i=r.match(/#\/(?:\$defs|definitions)\/(.+)$/);i&&!t.has(i[1])&&n.push(r)}else if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const i of r)typeof i=="object"&&i!==null&&n.push(..._n(i,t));else n.push(..._n(r,t));return n}function Zc(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,o=Ut(n),r={...e};return delete r.anyOf,{...r,oneOf:n,...o?{discriminator:o}:{},[Ne]:r[Ne]??"union"}}function ed(e,t,n){const{DEFAULT_CONFIG:o}=ue("ts-json-schema-generator/dist/src/Config.js"),r={...o,...e},i=r.path,s=Jc(i,r.tsconfig);let a;a=n?n.statVersion(i):Ei(i);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??Gc(s);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=ue("ts-json-schema-generator/dist/factory/program.js"),{createParser:u,createFormatter:f,SchemaGenerator:m}=kn(),p=Hc(),g=qc(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),b=l(r),h=u(b,r,g),y=f(r);if(c=new m(b,h,y,r),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const w={version:a,gen:c};Wc(s,w),n==null||n.generatorCache.set(s,w)}}const d=c.createSchema(r.type);return Xc(d),Qc(d),d}function td(e,t){let n=e.trim();if(n=Oi(n),t!=null&&t.size){const r=t.get(n);if(r!==void 0)return r}const o=n.match(/^ReadonlyArray<(.+)>$/);for(o&&(n=`${o[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function Ri(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const nd=Object.entries(Ni).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ri(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Oi(e){let t=e;for(const{pattern:n,key:o}of nd)t=t.replace(n,o);return t}function od(e,t){let n=Oi(e);for(const[o,r]of t)n=n.replace(new RegExp(`\\b${Ri(o)}\\b`,"g"),r);return n}async function Ye(e,t,n,o,r,i){const s=t.getFilePath(),a=`${s}\0${o??""}\0${n}`,c=i??new Set;if(c.has(a))return{};if(!r){const p=new Set(c);return p.add(a),Qo(e,t,n,o,void 0,p)}const d=r.schemaCache.get(a);if(d!==void 0)return r.stats.schemaCacheHits++,d;const l=kc(s,o,r.statVersion(s)),u=l.get(n);if(u!==void 0)return r.stats.schemaCacheHits++,r.schemaCache.set(a,Promise.resolve(u)),u;r.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const m=Qo(e,t,n,o,r,f).then(p=>(l.set(n,p),p)).catch(p=>{throw r.schemaCache.delete(a),p});return r.schemaCache.set(a,m),m}async function Qo(e,t,n,o,r,i){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(r){const f=r.aliasCache.get(t);s=f??Xo(t),f||r.aliasCache.set(t,s)}else s=Xo(t);const a=td(n,s),c=En[a];if(c!==void 0)return c;const d=await Kc(a,f=>Ye(e,t,f,o,r,i));if(d!==void 0)return d;const l=(r==null?void 0:r.zodImportCache.get(t))??Yc(t);if(r&&r.zodImportCache.set(t,l),!l)try{const f={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:o,topRef:!1},m=ed(f,!0,r);return Zc(m)}catch{}try{const f=await Pc(e,t,a,m=>_i(m,p=>Ye(e,t,p,o,r,i),0));if(f!==void 0)return f}catch{}const u=od(a,s);return At(u,0,s)}function to(e,t,n){if(e!=null&&e.hasInitializer()){const o=e.getInitializer();if(o)return o.getText()}return rd(n,t)}function rd(e,t){var s;const n=e,o=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${r}\\s*=\\s*([^\\]]+)\\]`);for(const a of o)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(i);if(d)return d[1].trim()}}function id(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 sd(e,t){const n=id(t);if(n===void 0)return;e.default=n;const o=typeof n=="string"?n:JSON.stringify(n),r=typeof e.description=="string"?e.description:void 0;e.description=r?`${r} (default: ${o})`:`(default: ${o})`}let ft;function ad(){return ft||(ft=ue("ts-morph").SyntaxKind,ft)}function Dt(e){try{if(!e)return;const t=ad();if(e.getKind()!==t.TypeReference)return;const n=e;if(n.getTypeArguments().length>0)return;const o=n.getTypeName();if(o.getKind()!==t.Identifier)return;const i=o.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 m=f.getCommentText();if(m!==void 0)return m.trim()}return}catch{return}}const cd=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function dd(e){const t=[];let n=0,o="";for(const r of e)r==="<"||r==="("||r==="["||r==="{"?n++:(r===">"||r===")"||r==="]"||r==="}")&&n--,r===","&&n===0?(t.push(o.trim()),o=""):o+=r;return o.trim().length>0&&t.push(o.trim()),t}function ld(e){const t=e.trim(),n=t.indexOf("<");if(n===-1||!t.endsWith(">"))return null;const o=t.slice(0,n),r=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;if(!cd.has(r))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=dd(s);return a.length>0?a[0]:null}async function Ti(e){const t=e.session===void 0,n=jc(e.session??_c());try{return await ud(e,n)}finally{t&&n.dispose()}}async function ud(e,t){const{sourceFile:n,namespace:o="",dropFileSegment:r=!1,tsconfig:i}=e,s=t.projectFor(i),a=t.sourceFileFor(n,i),c=k.basename(n),d=le(pd(c)),l=r?null:d,u=le(o),f=[];for(const[g,b]of a.getExportedDeclarations()){if(g==="default"||mt(g))continue;const h=gd(b);if(h){const S=h.getSignature(),E=tr(S,h),A=S.getReturnType().getText(),_=Ee(S);f.push(await pt(s,a,u,l,g,E,A,h.isAsync(),i,t,_));continue}const y=b.find(S=>S.getKindName()==="VariableDeclaration");if(!y)continue;const w=y.getInitializer(),v=w==null?void 0:w.getKindName();if(w&&["ArrowFunction","FunctionExpression"].includes(v??"")){const E=y.getType().getCallSignatures();if(E.length===0)continue;const A=E[0],_=nr(A,y,y.getVariableStatement()),N=A.getReturnType().getText(),j=Ee(A),O=w.isAsync();f.push(await pt(s,a,u,l,g,_,N,O,i,t,j))}else if(v==="ObjectLiteralExpression"){const S=y.getType();for(const E of S.getProperties()){const A=E.getName();if(mt(A))continue;const N=E.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const j=N[0],O=nr(j,y,y.getVariableStatement()),I=j.getReturnType().getText(),C=Ee(j),q=[...l?[l]:[],le(g),le(A)];f.push(await _t(s,a,u,q,A,O,I,!1,i,t,C))}}else{const S=y.getType(),E=S.getText();if(Ae(S,y)){const A=await Ye(s,a,E,i,t);f.push(fd(u,l,g,A))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${g}`)}}const m=a.getDefaultExportSymbol();if(m){const g=a.getExportAssignment(b=>!b.isExportEquals());if(g){const b=g.getExpression(),h=b.getKindName();if(["ArrowFunction","FunctionExpression"].includes(h)){const w=b.getType().getCallSignatures();if(w.length>0){const v=w[0],S=nn(v,g),E=v.getReturnType().getText(),A=Ee(v),_=b.isAsync();f.push(await pt(s,a,u,l,"default",S,E,_,i,t,A))}}else{const y=b.getType();for(const w of y.getProperties()){const v=w.getName();if(mt(v))continue;const E=w.getTypeAtLocation(g).getCallSignatures();if(E.length===0)continue;const A=E[0],_=nn(A,g),N=A.getReturnType().getText(),j=Ee(A),O=[...l?[l]:[],le("default"),le(v)];f.push(await _t(s,a,u,O,v,_,N,!1,i,t,j))}}}else{const b=m.getDeclarations();for(const h of b){if(h.getKindName()!=="FunctionDeclaration")continue;const y=h,w=y.getName(),v=w&&w.length>0?w:"default",S=y.getSignature(),E=tr(S,y),A=S.getReturnType().getText(),_=Ee(S);f.push(await pt(s,a,u,l,v,E,A,y.isAsync(),i,t,_))}}}const p=md(a);if(p.length>0)for(const{name:g,sig:b}of p){if(mt(g))continue;const h=nn(b),y=b.getReturnType().getText(),w=Ee(b),v=[...l?[l]:[],le(g)];f.push(await _t(s,a,u,v,g,h,y,!1,i,t,w))}return f}function Zo(e,t,n,o){const r=new Set,i=s=>{if(Array.isArray(s))return s.map(i);if(!s||typeof s!="object"||r.has(s))return s;r.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[m,p]of Object.entries(l)){const g=i(p),b=f[m];if(b!==void 0&&JSON.stringify(b)!==JSON.stringify(g))throw new Error(`[apigen-core-client] Function "${n}": param "${o}" contributes a "${u}.${m}" 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[m]=g}continue}c[d]=i(l)}return c}finally{r.delete(s)}};return i(e)}function er(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 Ee(e){var t;try{return Dt((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function pt(e,t,n,o,r,i,s,a,c,d,l){const u=le(r);return _t(e,t,n,o?[o,u]:[u],r,i,s,a,c,d,l)}async function _t(e,t,n,o,r,i,s,a,c,d,l){const u=i.length>0&&i[0].name==="ctx",f=i.filter(j=>j.name!=="ctx"),m=f.filter(j=>!j.optional).map(j=>j.name),p={},g={definitions:{},$defs:{}};for(const j of f){const O=await Ye(e,t,j.type,c,d),I=Zo(O,g,r,j.name);j.defaultValue!==void 0&&sd(I,j.defaultValue),er(I,j.format),p[j.name]=I}const b=s.replace(/^Promise<(.+)>$/,"$1").trim(),h=ld(b),y=h!==null,w=y?h:b,v=await Ye(e,t,w,c,d),S={definitions:{},$defs:{}},E=Zo(v,S,r,"<return>"),A=l?{...E}:E;er(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 _={type:"object",properties:p,required:m,...Object.keys(g.definitions).length>0?{definitions:g.definitions}:{},...Object.keys(g.$defs).length>0?{$defs:g.$defs}:{}};return{id:Ii(n,o),host:"ts",namespace:n,path:o,kind:"action",async:a,streaming:y,safe:!1,input:_,output:A,envelope:{},typeText:{lang:"ts",input:hd(i),output:w},...u?{hasCtx:!0}:{}}}function fd(e,t,n,o){const r=le(n),i=t?[t,r]:[r];return{id:Ii(e,i),host:"ts",namespace:e,path:i,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:o,envelope:{},typeText:null}}function Ii(e,t){return(e.raw?[e,...t]:t).map(o=>o.words.join("-")).join("/")}function Xe(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 le(e){return{raw:e,words:Xe(e)}}function pd(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function md(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const o=n.getExpression();if(o.getKindName()!=="BinaryExpression")continue;const r=o;if(r.getLeft().getText().trim()!=="module.exports"||r.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=r.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 gd(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const o=n;if(t||(t=o),o.getBody())return o}return t}function tr(e,t){return e.getParameters().map(n=>{var s;const o=n.getDeclarations(),r=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((s=r==null?void 0:r.hasQuestionToken)==null?void 0:s.call(r))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:to(r,n.getName(),t),format:Dt(r==null?void 0:r.getTypeNode())}})}function nr(e,t,n){return e.getParameters().map(o=>{var a;const r=o.getDeclarations(),i=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,s=o.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((a=i==null?void 0:i.hasQuestionToken)==null?void 0:a.call(i))??!1);return{name:o.getName(),type:o.getTypeAtLocation(t).getText(),optional:s,defaultValue:to(i,o.getName(),n??t),format:Dt(i==null?void 0:i.getTypeNode())}})}function nn(e,t){return e.getParameters().map(n=>{var s,a,c;const o=n.getDeclarations(),r=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((s=r==null?void 0:r.hasQuestionToken)==null?void 0:s.call(r))??!1);return{name:n.getName(),type:r?r.getType().getText():((c=(a=n.getValueDeclaration())==null?void 0:a.getType())==null?void 0:c.getText())??"unknown",optional:i,defaultValue:to(r,n.getName(),t),format:Dt(r==null?void 0:r.getTypeNode())}})}function hd(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function mt(e){return!!(e==="__samples__"||e.startsWith("__"))}function Ae(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 o=e.getArrayElementType();return o?Ae(o,t,n):!1}if(e.isTuple())return e.getTupleElements().every(o=>Ae(o,t,n));if(e.isUnion())return e.getUnionTypes().every(o=>Ae(o,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(o=>Ae(o,t,n));if(e.isObject()){const o=e.getText(t);if(n.has(o))return!0;n.add(o);const r=e.getStringIndexType(),i=e.getNumberIndexType();if(r||i)return[r,i].every(a=>!a||Ae(a,t,n));const s=e.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(t);return Ae(c,t,n)})}return!1}function yd(e,t){return async n=>{let o=()=>t(n);for(let r=e.length-1;r>=0;r--){const i=e[r],s=o;o=()=>i(n,s)}return o()}}function wd(e,t){return yd(e,t)}function vd(e,t,n={}){const o=e.map(r=>r.capabilities.extractLayer).filter(r=>!!r).map(r=>r.createLayer?r.createLayer(n):r.layer).filter(r=>!!r);return wd(o,t)}function bd(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 Sd(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:bd(e.output)}}function Ed(e,t={}){const n=new Set(t.exclude??[]),o=new Map;for(const r of e){if(n.has(r.id))continue;const i=o.get(r.kind);i?i.push(r):o.set(r.kind,[r])}return o}function or(e){return{type:"string",enum:[e]}}function rr(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 ir(e,t){const n={},o={},r=[["definitions",n],["$defs",o]];for(const i of e){const s=t(i);for(const[a,c]of r){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(o).length>0?{$defs:o}:{}}}function kd(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(Sd),n=ir(e,s=>s.input),o=ir(e,s=>s.output);if(e.length===1){const[s]=e,[a]=t;return{input:{...rr(a,or(s.id)),...n},output:{type:"array",items:a.resultSchema,...o}}}const r=e.map((s,a)=>rr(t[a],or(s.id))),i=Ut(r);return{input:{oneOf:r,...i?{discriminator:i}:{},...n},output:{oneOf:t.map(s=>({type:"array",items:s.resultSchema})),...o},...i?{discriminator:i}:{}}}function Ad(e,t={}){const n=Ed(e.operations,t),o=[];for(const[r,i]of n){const{input:s,output:a}=kd(i),c=vi(`_batch/${r}`,e,{kind:r,safe:r==="query",input:s,output:a});o.push({...c,operationIds:i.map(d=>d.id)})}return o}function no(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,o=!n&&!!process.stderr.isTTY,r=e.format??(o?"pretty":"json"),i={level:t};if(r==="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}}},dt(i);const s=n?dt.destination({dest:e.destination,mkdir:!0,sync:!0}):dt.destination(2);return dt(i,s)}function _d(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(([r,i])=>`${r}${n.has(r)?"":"?"}: ${Mt(i)}`).join(", ")} }`}function jd(e){return typeof e=="string"?`'${e}'`:JSON.stringify(e)}function Nd(e){const t=e.enum??[];return t.length===0?"unknown":t.map(jd).join("|")}function Rd(e,t){return e.map(n=>Mt(n,t)).join(" | ")}function Mt(e,t=0){if(!e)return"unknown";if(e.type==="array")return`${Mt(e.items,0)}[]`;if(e.enum)return Nd(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?Rd(n,t-1):"union":t>=1&&e.type==="object"?_d(e)??"object":e.type??"object"}function $i(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,o=(n==null?void 0:n.properties)??{},r=new Set((n==null?void 0:n.required)??[]),i=Object.entries(o).map(([c,d])=>({name:c,type:Mt(d,2),required:r.has(c)})),s=i.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:i,text:s}}function Od(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function Td(e,t){var i,s;const o=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},r={...e};for(const[a,c]of Object.entries(o)){const d=r[a];if(typeof d!="string")continue;const l=Od(c==null?void 0:c.type);if(l==="number"||l==="integer"){const u=Number(d);!Number.isNaN(u)&&d.trim()!==""&&(r[a]=u)}else l==="boolean"&&(d==="true"?r[a]=!0:d==="false"&&(r[a]=!1))}return r}const Id=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],$d={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},sr={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class F extends Error{constructor(t,n,o){super(n),this.name="ApiError",this.code=t,this.details=o,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 ae(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Id.includes(e.code)&&typeof e.toJSON=="function"}function ar(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Ft=new ui({allErrors:!0});Ya(Ft);for(const e of[Ne,Gn,mn,gn,"discriminator"])Ft.addKeyword({keyword:e,valid:!0});Ft.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Cd(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Pd(e,t){const n=gi(t),o=[`Validation failed: ${Cd(e)}`];return n&&o.push(n),o.join(" — ")}function xd(e){return async function(n,o){const r=n.operation.id,i=e[r];if(i===void 0)return o();const s={data:n.domainArgs,...n.envelope},a=Ft.compile(i.input);if(!a(s)){const d=a.errors??[];throw new F("invalid_argument",Pd(d,i.input),d)}return o()}}async function Ci(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const o=ae(n)?n:new F("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:ar("before-first-chunk",o)}:{ok:!1,carrier:ar("after-first-chunk",o,t.length)}}}function Bt(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ke extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function on(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 o=n.mapping;if(!(o===null||typeof o!="object"||Array.isArray(o)))return{propertyName:n.propertyName,mapping:o}}function Pi(e,t){const n=e[Gn];if(typeof n=="string"){const o=t.registry.get(n);if(o)return o}return t.registry.resolve(e)}function Ld(e,t,n){const o=Pi(t,n);return o?o.encode(e,t,n):e}function Ud(e,t,n){const o=Pi(t,n);return o?o.decode(e,t,n):e}function Dd(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(o){if(o[Ne]==="union")return!0;const r=o.oneOf;return!Array.isArray(r)||r.length===0?!1:on(o)!==void 0},encode(o,r,i){const s=on(r);if(!s)throw new ke("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=o[a];if(d==null)throw new ke("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 ke("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 Ld(o,f,{...i,path:`${i.path}[${l}]`})},decode(o,r,i){if(o===null||typeof o!="object"||Array.isArray(o)){let p;throw o===null?p="null":Array.isArray(o)?p="array":p=typeof o,new ke("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=o,a=on(r);if(!a)throw new ke("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 ke("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 ke("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 m=i.resolve(f);return Ud(o,m,{...i,path:`${i.path}[${u}]`})}}}const Md="x-apigen-instances";class gt extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function cr(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Fd(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function dr(e,t,n){if(t){const o=n.registry.resolve(t);if(o)return o.encode(e,t,n)}return e}function Bd(e,t,n){if(t){const o=n.registry.resolve(t);if(o)return o.decode(e,t,n)}return e}function Kd(e){const{id:t,schema:n,ctor:o}=e;return{id:t,kind:"nominal",schema:n,matches(r){return r[Ne]==="nominal"?!0:r[Gn]===t},encode(r,i,s){if(r===null||typeof r!="object")return r;if(s.seen.has(r)){if(s.mode==="strict")throw new gt("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(r);try{const a=cr(i),c=typeof i[gn]=="string"?i[gn]:"toJSON",d=r[c];if(typeof d=="function"){const p=d.call(r);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const g={};for(const[b,h]of Object.entries(p))g[b]=dr(h,a[b],{...s,path:`${s.path}/${b}`});return g}return p}const l={},u=Object.keys(a),f=r,m=u.length>0?u:Object.keys(f);for(const p of m){const g=f[p];g!==void 0&&(l[p]=dr(g,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(r)}},decode(r,i,s){if(r===null||typeof r!="object"||Array.isArray(r)){let l;throw r===null?l="null":Array.isArray(r)?l="array":l=typeof r,new gt("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=r;for(const l of Fd(i))if(!(l in a))throw new gt("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${s.path}".`);if(i[Md]===!1)throw new gt("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=cr(i),d={};for(const[l,u]of Object.entries(a))d[l]=Bd(u,c[l],{...s,path:`${s.path}/${l}`});if(o){const l=typeof i[mn]=="string"?i[mn]:"fromJSON",u=o[l];if(typeof u=="function")return u.call(o,d);const f=o;return new f(d)}return d}}}const qd=[Jn,zn,Yn,Xn,Qn,Zn],Hd={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},lr=Kd({id:"ts.NominalSentinel",schema:Hd}),Vd={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ur=Dd({id:"ts.UnionSentinel",schema:Vd});function Gd(){const e=[...qd.map(t=>[t.id,t]),[lr.id,lr],[ur.id,ur]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:sc,codecs:Gd()});function jn(e,t,n){var s;const o=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,r=gi(t==null?void 0:t.input),i=[n,o,r].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function xi(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 Wd(e,t){if(e)return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Jd=4,zd=32;function Nn(e){return ae(e)?e:e instanceof Error?new F("internal",e.message):e}function Yd(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Jd;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),zd)}function Xd(){}function Qd(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Xd};const n=new AbortController,o=()=>{n.abort(e==null?void 0:e.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener("abort",o,{once:!0}));let r;return t!==void 0&&!n.signal.aborted&&(r=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=r.unref)==null||i.call(r)),{signal:n.signal,dispose(){e&&e.removeEventListener("abort",o),r&&clearTimeout(r)}}}async function fr(e,t,n,o,r,i){const s=Qd(o.signal,i);try{const a=s.signal?{...o,signal:s.signal}:o,c=await e(t,a,r);if(Bt(c)){const d=await Ci(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:Nn(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:Nn(a)}}finally{s.dispose()}}async function Zd(e,t,n,o,r={}){const i=r.mode??"parallel",s=r.onItemError??"continue",a=Yd(i,r.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:Nn(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 g=0;g<n.length;g++){if(p){c[g]=d(g);continue}const b=await fr(e,t,g,n[g],o,r.itemTimeoutMs);c[g]=b,b.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)),m=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(u){c[p]=d(p);continue}const g=await fr(e,t,p,n[p],o,r.itemTimeoutMs);c[p]=g,g.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(m),c}function pr(e){return e.words.join("-")}function mr(e){return e.words.map(nl).join("")}function gr(e){return e.words.join("_")}function el(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Re(e,t={}){var f,m;const n=[e.namespace,...e.path],o=e.safe||Ai(e.input)?"GET":"POST",r=((m=(f=t.http)==null?void 0:f.verb)==null?void 0:m[e.id])??o,i="/"+n.map(p=>pr(p)).join("/"),s=n.map(p=>gr(p)).join("_"),c=n.map(p=>gr(p)).slice(0,-1).join("."),d=mr(n[n.length-2]??n[0]),l=mr(n[n.length-1]),u=n.map(p=>pr(p));return{http:{verb:r,route:i},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function Li(e,t){return`x-${e}-${t}`}function Ui(e,t){return`--${e}-${t}`}function Di(e,t){const n=o=>o.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Nt(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}function tl(e){const t=new Set,n=[];for(const o of e){const r=Nt(o);let i=r,s=2;for(;t.has(i);)i=`${r}_${s}`,s+=1;t.add(i),n.push(i)}return n}function nl(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Mi(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function de(e){return Mi(JSON.stringify(e))}function ol(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 oo(e){return e.anyOf??e.oneOf}function rl(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=oo(e);if(t){const n=t.filter(o=>o.type!=="null");return n.length>0&&n.every(o=>o.type==="array"||o.type==="object")}return!1}function il(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=oo(e);if(t){const n=t.filter(o=>o.type!=="null");return n.length>0&&n.every(o=>o.type==="boolean")}return!1}function sl(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=oo(e);if(t){const n=t.filter(o=>o.type!=="null");return n.length>0&&n.every(o=>o.type==="number"||o.type==="integer")}return!1}function al(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function cl(e){var r,i;const t=(i=(r=e.input)==null?void 0:r.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},o=(t==null?void 0:t.required)??[];return{props:n,required:o}}function hr(e){return typeof e.handler=="function"}function dl(e){var r;const t=((r=e.input)==null?void 0:r.properties)??{},n=e["x-apigen-envelope"],o=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd",a=Li(s,i);o.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:Ui(s,i),envVar:Di(s,i)})}return o}function ll(e,t,n,o){t===n||e.has(t)||e.set(t,{...o,aliasOf:n})}function ul(e,t){const n=new Map,{props:o}=cl(e);for(const[r,i]of Object.entries(o)){let s="string";il(i)?s="boolean":(rl(i)||sl(i))&&(s="json");const a=al(r),c={camelKey:r,kind:"domain",valueKind:s};n.set(a,c),ll(n,r,a,c)}for(const r of t){const i=r.cliFlag.replace(/^--/,""),s={camelKey:r.field,kind:"envelope",valueKind:"string",envVar:r.envVar};n.set(i,s)}return n}function be(e){const{op:t,schema:n,transport:o,projection:r}=e,i=Re(t,r),s=n?dl(n):[],a=n?ul(n,s):new Map,c=n?$i(n).params:void 0,d={op:t,transport:o,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:c,envelope:s,cliFlags:a,streaming:t.streaming,isMount:hr(t)};if(hr(t)){const l=t.handler;d.mountHandler=async u=>l(u)}return d}function ro(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function fl(e){const t=e.exitCode;return typeof t=="function"?t:void 0}function io(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function pl(e){return async function(n,o){const r=Object.assign(n,{data:n.domainArgs});return await e.layer(r,o)}}function fe(e,t){var o;const n=[];for(const r of t){const i=(o=r.capabilities)==null?void 0:o.layer;i&&n.push(pl(i))}return n.push(xd(e)),Ec(n)}function ml(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const gl={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Me(e,t,n,o){const r={...n,operation:{id:e.op.id},ctx:new rt};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:ml(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...o,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:gl}};return t(e.op.id,r,a)}return t(e.op.id,r,o)}function Fi(e){return e.anyOf??e.oneOf}function hl(e){var r;const t=((r=e.input)==null?void 0:r.properties)??{},n=e["x-apigen-envelope"],o=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";o.push({field:i,pluginId:s,flag:Ui(s,i),envVar:Di(s,i)})}return o}function Rn(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Fi(e);if(t){const n=t.filter(o=>o.type!=="null");return n.length>0&&n.every(o=>o.type==="array"||o.type==="object")}return!1}function yl(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Fi(e);if(t){const n=t.filter(o=>o.type!=="null");return n.length>0&&n.every(o=>o.type==="boolean")}return!1}function yr(e){var r,i;const t=(i=(r=e.input)==null?void 0:r.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},o=(t==null?void 0:t.required)??[];return{props:n,required:o}}function wl(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function vl(e){const n=so(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function rn(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,o=t.discriminator;if(!n||!o)return;const r=[];for(const[a,c]of Object.entries(o.mapping)){const d=wl(c);if(d===void 0)continue;const l=n[d];if(!l)continue;const u=l.properties??{},f=l.required??[];r.push({value:a,commandName:vl(a),props:u,required:f})}if(r.length!==0)return{discriminatorProperty:o.propertyName,branches:r}}function so(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function bl(e,t){if(!fn.isAbsolute(t))return t;const n=fn.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Sl=["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 Bi(e,t,n){for(const o of t){const r=o.flag.replace(/^--/,"");e.push(` .option('${o.flag} <${r}>', '${o.field} (env: ${o.envVar})')`)}n&&!t.some(o=>o.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Ki(e,t,n,o){var r;for(const i of t){const s=so(i),a=yl(n[i]),c=o.includes(i);a?(e.push(` .option('--${s}')`),((r=n[i])==null?void 0:r.default)===!0&&e.push(` .option('--no-${s}')`)):c?e.push(` .requiredOption('--${s} <${s}>')`):e.push(` .option('--${s} <${s}>')`)}}function qi(e,t,n){return`${e}:${t}::${n}`}function Hi(e,t){const{varName:n,pkgId:o,fnName:r,bindings:i,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=t,l=t.dispatchSchemaKey??`${o}:${r}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([m,p])=>`'${m}': ${p}`),f=a.map(m=>Rn(c[m])?`'${m}': __apigenParseJsonArg('${so(m)}', opts['${m}'])`:`'${m}': opts['${m}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...u,...f].join(", ")} }`),i.length>0){const m=i.map(p=>{const b=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(h,y)=>y.toUpperCase());return`'${p.field}': opts['${b}'] ?? process.env['${p.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${m.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, '${r}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function El(e,t){const{varName:n,pkgId:o,fnName:r,bindings:i,needsSession:s,rootUnion:a}=t,c=Nt(`${o}_${r}_cmd`);e.push(`const ${c} = program.command('${r}')`);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}')`),Bi(e,i,s),Ki(e,l,d.props,u),Hi(e,{varName:n,pkgId:o,fnName:r,dispatchSchemaKey:qi(o,r,d.commandName),bindings:i,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function kl(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",o=e.packages.some(s=>Object.values(s.schemas).some(a=>{const c=rn(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>Rn(l.props[u])));const{props:d}=yr(a);return bn(a).some(l=>Rn(d[l]))})),r=["#!/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=Nt(s.id),c=bl(e.outputDir,s.importPath);r.push(`import * as ${a}_ns from '${c}'`),r.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}r.push(""),o&&(r.push(Sl),r.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=rn(c);if(d)for(const l of d.branches){const u=qi(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}:{}}}}r.push(`const schemas: Record<string, unknown> = ${JSON.stringify(i,null,2)}`),r.push(""),r.push(`const program = new Command().name('${t}').version('${n}')`),r.push("");for(const s of e.packages){const a=Nt(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=wi(d,"session"),u=hl(d),f=rn(d);if(f){El(r,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const m=bn(d),{props:p,required:g}=yr(d);r.push("program"),r.push(` .command('${c}')`),Bi(r,u,l),Ki(r,m,p,g),Hi(r,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,paramNames:m,schemaProps:p})}}return r.push(""),r.push("program.parseAsync()"),{files:[{path:"cli.ts",content:r.join(`
4
- `)}]}}function Al(e){return{props:e.properties??{},required:e.required??[]}}function _l(e){const t=e??{},o=Array.isArray(t.oneOf)&&t.oneOf.length>0?t.oneOf:[t],r={},i=new Map;for(const a of o){const{props:c,required:d}=Al(a);for(const[l,u]of Object.entries(c))l in r||(r[l]=u);for(const l of d)i.set(l,(i.get(l)??0)+1)}const s=[...i.entries()].filter(([,a])=>a===o.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:r,required:s}},required:["data"]},output:{}}}function jl(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let o;for(;o=n.exec(e);)t.push(o[1]??o[2]??o[3]);return t}function Nl(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?jl(t):process.argv.slice(2)}function Rl(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 Ol(e){const t=new Map;for(const o of e.operations??[]){const r=o.path[o.path.length-1];r&&t.set(`${o.namespace.raw}:${r.raw}`,o)}const n=new Map;for(const o of e.packages)for(const[r,i]of Object.entries(o.schemas)){const s=t.get(`${o.id}:${r}`)??Rl(r,i),a=be({op:s,schema:i,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:o.id,fnName:r,schema:i,cliPath:c,plan:a})}return n}function Tl(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let o=n;o>=1;o--){const r=t.get(e.slice(0,o).join(" "));if(r)return{entry:r,rest:e.slice(o)}}return null}function Vi(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function wr(e){const t=["Available commands:",""],n=[...e.entries()].sort(([o],[r])=>o.localeCompare(r));for(const[o,{plan:r}]of n){const i=Vi(r.params);t.push(` ${o}${i?` { ${i} }`:""}`)}return t.join(`
5
- `)}function ht(e){return new F("invalid_argument",e)}function Il(e,t){var i;const n={},o={};let r=0;for(;r<e.length;){const s=e[r];if(!s.startsWith("--"))throw ht(`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 ht(`Unknown option: --${a}. Available: ${[...t.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);r++;let m;if(f.valueKind==="boolean")l?m=!1:c===void 0?m=!0:m=c!=="false";else{const p=c!==void 0?c:e[r++];if(p===void 0)throw ht(`Missing value for --${a}`);if(f.valueKind==="json")try{m=JSON.parse(p)}catch(g){throw ht(`Invalid JSON for --${a}: ${g.message}`)}else m=p}f.kind==="domain"?n[f.camelKey]=m:o[f.camelKey]=m}for(const s of t.values()){if(s.kind!=="envelope"||!s.envVar||o[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(o[s.camelKey]=a)}return{domainArgs:n,envelope:o}}function Gi(e){const t=ae(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=ae(e)?sr[e.code]:sr.internal}function $l(e,t,n){if(ae(n)&&n.code!=="internal"){e.error({command:t,code:n.code,message:n.message},`✗ ${t}`);return}e.error({command:t,err:n},`✗ ${t}`)}class Cl{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:o,envelope:r}=Il(t.rest,n.cliFlags);return{domainArgs:o,envelope:r,signal:this.signal}}writeResult(t,n,o){var i;if(Bt(n))throw new F("invalid_argument",`Command "${o.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 r=(i=this.exitCodeHook)==null?void 0:i.call(this,n);typeof r=="number"&&r!==0&&(process.exitCode=r)}writeError(t,n,o){Gi(n)}}function Pl(e,t,n,o,r){var a;const i=[],s={host:n,operations:o};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],r);for(const u of l)u.transports&&!u.transports.includes("cli")||i.push(u)}return i}async function xl(e){var E,A,_;const t=e.logger??no();if((E=e.signal)!=null&&E.aborted){t.info("cli run: signal already aborted before dispatch — skipping");return}let n=Nl(e.options);n[0]==="--"&&(n=n.slice(1));const o=ro(e.options),r=io(e.options),i=new Cl(e.signal,fl(e.options)),s=Ol(e),a=new Map;for(const N of s.values()){const j=a.get(N.pkgId);j?j.push(N):a.set(N.pkgId,[N])}const c={},d={};for(const N of e.packages){const j=a.get(N.id);if(!j||j.length===0)continue;if(!N.fns)throw new Error(`apigen-plugin-cli-output: package "${N.id}" has no functions`);const O=N.fns,I={},C={};for(const P of j)I[P.plan.op.id]=P.schema,C[P.plan.op.id]=O[P.fnName],c[P.plan.op.id]=P.schema,d[P.plan.op.id]=O[P.fnName];const q=fe(I,o),M={fns:C,createClient:N.createClient,schemas:I};for(const P of j)i.registerRoute(P.plan,X=>Me(P.plan,q,X,M))}const l=((A=e.packages[0])==null?void 0:A.id)??"ts",u=fe(c,o),f={invoke:(N,j,O)=>u(N,{operation:{id:N},ctx:new rt,domainArgs:j.domainArgs,envelope:j.envelope,signal:j.signal},O),invokeOptions:{fns:d,schemas:c,createClient:(_=e.packages[0])==null?void 0:_.createClient}},m=Pl(o,r,l,e.operations??[],f);if(m.length>0){const N=fe({},o),j={fns:{},schemas:{}};for(const O of m){const I=be({op:O,schema:_l(O.input),transport:"cli"});i.registerRoute(I,C=>Me(I,N,C,j))}}const p=i.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(wr(p));return}const g=Tl(n,p);if(!g){Gi(new F("not_found",`Unknown command: ${n.join(" ")}
2
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("node:fs"),te=require("node:os"),_=require("node:path"),Ct=require("node:url"),Jo=require("@adhd/sox-telemetry"),Gt=require("pino"),qs=require("ajv"),Sl=require("ajv-formats"),Ne=require("@adhd/sox-store-adapter"),kl=require("@adhd/sox-graph-store"),zo=require("node:fs/promises"),ke=require("node:crypto"),_l=require("fastify"),zi=require("node:http"),Al=require("@modelcontextprotocol/sdk/server/index.js"),Nl=require("@modelcontextprotocol/sdk/server/stdio.js"),Rl=require("@modelcontextprotocol/sdk/server/sse.js"),jl=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Yi=require("@modelcontextprotocol/sdk/types.js"),Hs=require("node:child_process"),Tl=require("@adhd/sox-hybrid-search"),Yo=require("node:module"),Ol=require("yaml");var B=typeof document<"u"?document.currentScript:null;function Vs(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const ao=Vs(_),Te=Vs(zo),co="$apigen";class Xi extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Il(t){const e=new Map;return{register(i,o){if(e.has(i.id)&&!(o!=null&&o.override))throw new Xi(`E_DUP_CODEC: a codec is already registered for id "${i.id}"`);e.set(i.id,i)},resolve(i){for(const o of e.values())if(o.matches(i))return o},get(i){return e.get(i)},ids(){return[...e.keys()]},freeze(){const i=new Map(e),o={register(){throw new Xi("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(r){for(const s of i.values())if(s.matches(r))return s},get(r){return i.get(r)},ids(){return[...i.keys()]},freeze(){return o}};return o}}}const Fe="x-apigen-logical",Xo="x-apigen-codec",lo="x-apigen-ctor",uo="x-apigen-tojson",$l="0.1.0";function Qi(t,e){return{registry:t,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",...e}}function We(t,e,n){const i=n.registry.resolve(e);if(i)return i.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return We(t,a,n)}const r=e.oneOf;if(Array.isArray(r)){const a=Gs(t,r,e,n);return We(t,a,n)}const s=e.type;if(s==="array"){if(!Array.isArray(t))return St(t,e,n);const a=e.items;if(!a)return t.map(d=>De(d));const c=n.path;return Array.isArray(a)?t.map((d,l)=>{const u=a[l];return u===void 0?De(d):We(d,u,{...n,path:`${c}/${l}`})}):t.map((d,l)=>We(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return St(t,e,n);const a=e.properties;if(!a)return De(t);const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=t[l];f!==void 0&&(d[l]=We(f,u,{...n,path:`${c}/${l}`}))}return d}return s==null?St(t,e,n):De(t)}function Je(t,e,n){const i=n.registry.resolve(e);if(i)return i.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Je(t,a,n)}const r=e.oneOf;if(Array.isArray(r)){const a=Gs(t,r,e,n);return Je(t,a,n)}const s=e.type;if(s==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((d,l)=>{const u=a[l];return u===void 0?d:Je(d,u,{...n,path:`${c}/${l}`})}):t.map((d,l)=>Je(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=t[l];f!==void 0&&(d[l]=Je(f,u,{...n,path:`${c}/${l}`}))}for(const[l,u]of Object.entries(t))!(l in a)&&u!==void 0&&(d[l]=u);return d}return s==null?fo(t,n):t}function Gs(t,e,n,i){var c;const o=n.discriminator;if(o!=null&&o.propertyName){const d=o.propertyName,l=t!==null&&typeof t=="object"?t[d]:void 0;if(typeof l=="string"){if(o.mapping){const u=o.mapping[l];if(u){const f=e.find(m=>m.$ref===u);if(f)return f}}for(const u of e){const m=(c=un(u,i).properties)==null?void 0:c[d];if(!m)continue;const p=m.enum;if(m.const===l||Array.isArray(p)&&p.includes(l))return u}}}const r=Cl(t,e,i);if(r)return r;let s,a=-1;for(const d of e){const l=un(d,i),u=Qo(t,l,i);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:e[0]??{}}function un(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Zi(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function Cl(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const i=t,o=e.map(s=>un(s,n)),r=new Set;for(const s of o){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))Zi(d)!==void 0&&r.add(c)}for(const s of r){const a=o.map(f=>{const m=f.properties,p=m==null?void 0:m[s];return p?Zi(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=i[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&Qo(t,o[u],n)!==null)return e[u]}}function Pl(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function Qo(t,e,n){const i=e.oneOf;if(Array.isArray(i)){let l=null;for(const u of i){const f=Qo(t,un(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,r=Pl(t);if(typeof o=="string"){if(!(o===r||o==="number"&&r==="integer"))return null}else if(Array.isArray(o)&&!o.some(u=>u===r||u==="number"&&r==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const s=t,a=e.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=e.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 St(t,e,n){var i;for(const o of n.registry.ids()){const r=n.registry.get(o);if((i=r==null?void 0:r.ownsValue)!=null&&i.call(r,t))return{[co]:o,v:r.encode(t,r.schema,n)}}if(Array.isArray(t))return t.map(o=>St(o,{},n));if(Ws(t)){const o={};for(const[r,s]of Object.entries(t))s!==void 0&&(o[r]=St(s,{},n));return o}return De(t)}function Ws(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function fo(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&co in t){const n=t,i=n[co],o=e.registry.get(i);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>fo(n,e));if(Ws(t)){const n={};for(const[i,o]of Object.entries(t))n[i]=fo(o,e);return n}return t}function De(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(De);if(typeof t=="object"){const e={};for(const[n,i]of Object.entries(t))i!==void 0&&(e[n]=De(i));return e}return null}function er(t,e){const n=new Set,i=[t];for(;i.length>0;){const o=i.pop();if(!o||n.has(o))continue;n.add(o);const r=o.$ref;if(typeof r=="string"){if(e){const u=e[r];if(!u){const f=Object.keys(e).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved. Available $defs: ${f}`)}i.push(u)}continue}const s=o.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&i.push(u);const a=o.properties;if(a)for(const u of Object.values(a))i.push(u);const c=o.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&i.push(u);else typeof c=="object"&&c!==null&&i.push(c);const d=o.additionalProperties;typeof d=="object"&&d!==null&&i.push(d);const l=o.propertyNames;typeof l=="object"&&l!==null&&i.push(l)}}function Ll(t){return{encode(e,n,i){const o=Qi(t,i);return We(e,n,o)},decode(e,n,i){const o=Qi(t,i);return Je(e,n,o)}}}const Zo={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},ei={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}};const ti={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},ni={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},Ul=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,oi={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!Ul.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},po="NaN",mo="Infinity",go="-Infinity",Dl=new Set([po,mo,go]),ii={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?po:t===1/0?mo:t===-1/0?go:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===po)return NaN;if(t===mo)return 1/0;if(t===go)return-1/0;const i=Number(t);if(!Number.isNaN(i))return i}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...Dl].join(", ")}.`);return NaN}},Ml=[Zo,ei,ti,ni,oi,ii];function xl(t,e={}){for(const n of Ml)t.register(n,{override:e.override??!1})}const Fl=12;function Bl(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,i,o]=n,r=i==="$defs"?e.$defs:e.definitions;return r==null?void 0:r[decodeURIComponent(o)]}function tr(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function Kl(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function ql(t){switch(t.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 nr(t,e,n){const i=t.properties??{},o=t.required??[],r={};for(const s of o){const a=i[s];r[s]=a!==void 0?rt(a,e,n+1):`<${s}>`}return r}function Hl(t,e,n){const i=Array.isArray(t.items)?t.items[0]:t.items;return i?[rt(i,e,n+1)]:[]}function rt(t,e=t??{},n=0){if(!t||n>Fl)return null;if(typeof t.$ref=="string"){const r=Bl(t.$ref,e);return r!==void 0?rt(r,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const r={},s=[];for(const a of t.allOf){Object.assign(r,a.properties??{});for(const c of a.required??[])s.includes(c)||s.push(c)}return nr({...t,properties:r,required:s},e,n)}const i=tr(t.oneOf)??tr(t.anyOf);if(i)return rt(i,e,n+1);switch(Kl(t)){case"object":return nr(t,e,n);case"array":return Hl(t,e,n);case"string":return ql(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Js(t){if(!t)return;const e=rt(t);return`Example: ${JSON.stringify(e)}`}Zo.id,ei.id,ti.id,ni.id,oi.id,ii.id;const zs=Il();xl(zs);const Ys=Ll(zs.freeze());function Xs(t,e){var i;const n=((i=t.input)==null?void 0:i.properties)??{};return e in n}function ho(t){var n,i;const e=(i=(n=t.input)==null?void 0:n.properties)==null?void 0:i.data;return Object.keys((e==null?void 0:e.properties)??{})}function Vl(t,e){var o,r,s;const n=(s=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data)==null?void 0:s.properties,i=n==null?void 0:n[e];return i!==void 0?i:void 0}function Gl(t,e){return e===void 0||t===void 0?t:Ys.decode(t,e)}function Jn(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:Ys.encode(t,n)}async function Wl(t,e,n,i,o,r){const a=ho(n).map(d=>Gl(r[d],Vl(n,d)));if(Xs(n,"session")&&e){const d=await e({session:o.session}),l=await t[i](d,...a);return Jn(l,n)}if(n.hasCtx){const d=e?await e(o):void 0,l=await t[i](d,...a);return Jn(l,n)}const c=await t[i](...a);return Jn(c,n)}class Pt{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}}function Jl(t=[]){return async function(n,i,o){const r=o.schemas[n];if(!r)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>Wl(o.fns,o.createClient,r,n,i.envelope,i.domainArgs);return t.reduceRight((c,d)=>()=>d(i,c),s)()}}function or(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function Qs(t,e,n={}){const i=t.split("/");if(i.length<2||i.some(d=>d.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...r]=i,s=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:or(s),path:r.map(or),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 be=Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href);let Wt;function Zs(){return Wt||(Wt=be("ts-morph").Project,Wt)}const ea=Symbol.for("adhd.apigen.extraction-session");function ri(t,e){const n=[...t.getImportDeclarations().map(i=>i.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(i=>i.getModuleSpecifierSourceFile())];for(const i of n){if(!i)continue;const o=i.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{i.refreshFromFileSystemSync()}catch{}ri(i,e)}}}function ta(t){try{const e=j.statSync(t);return`${e.mtimeMs}:${e.size}`}catch{return"nostat"}}const an=new Map,ir=new Map;function zl(t,e,n){const i=e??"",o=an.get(i);let r=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!==t&&c.push(`${l}:${u}`);r=c.join("|")}const s=`${t}\0${e??""}`;let a=ir.get(s);return(a==null?void 0:a.version)!==r&&(a={version:r,schemas:new Map},ir.set(s,a)),a.schemas}let zn;function Yl(){if(!zn){const t=Zs();zn=new t({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return zn}function na(t){const e=Yl(),n=e.getSourceFile(t),i=n??e.addSourceFileAtPath(t);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([t]);return ri(i,o),[...o].sort()}function Xl(){const t={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},e=new Map;let n=!1;return{[ea]:!0,stats:t,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 r=o??"",s=o?this.statVersion(o):"";let a=an.get(r);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=Zs();a={project:o?new c({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},an.set(r,a),t.projectsBuilt++}return a.project},sourceFileFor(o,r){const s=this.projectFor(r),a=an.get(r??""),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]);ri(d,l);for(const u of l)u!==o&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(o){let r=e.get(o);return r===void 0&&(r=ta(o),e.set(o,r)),r},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),e.clear()}}}function Ql(t){const e=t;if(e[ea]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return e}const rr=new Set(["string","number","boolean","integer"]);function Zl(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?rr.has(n):Array.isArray(n)?n.every(i=>rr.has(i)||i==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(i=>["string","number","boolean"].includes(typeof i)):!1}function oa(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(Zl)}function eu(t){const e={},n=i=>{for(const o of["definitions","$defs"]){const r=i[o];if(r)for(const[s,a]of Object.entries(r)){const c=s.startsWith("#/")?s:`#/${o}/${s}`;e[c]=a}}};for(const i of Object.values(t.schemas))n(i.input),n(i.output);if(Object.keys(e).length!==0)for(const[i,o]of Object.entries(t.schemas))try{er(o.input,e),er(o.output,e)}catch(r){throw new Error(`[apigen-core-client] Schema validation failed for function "${i}": ${r.message}`)}}function tu(t,e){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(e?".":" (an empty object for this zero-parameter tool).")];return t.length>0&&n.push(`Field(s) ${t.map(i=>`"${i}"`).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 nu(t,e,n){eu(t);const i={};for(const[o,r]of Object.entries(t.schemas)){const s={},a=r.input.properties??{},c=r.input.required??[],d={},l=[],u={};for(const y of e)if(y.envelope&&s[y.id]!==!1)for(const[w,v]of Object.entries(y.envelope))d[w]=v,u[w]=y.id,l.includes(w)||l.push(w);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},m=r.safe===!0||oa(r.input),p=r.input.definitions,g=r.input.$defs;i[o]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:tu(Object.keys(d),Object.keys(a).length>0),...p?{definitions:p}:{},...g?{$defs:g}:{}},output:r.output,...r.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return i}const ou=8;function iu(t,e){try{return e?t.getText(e):t.getText()}catch{try{return t.getText()}catch{return}}}let ru=0;async function su(t,e,n,i){const o=`__ApigenProbe_${process.pid}_${ru++}`;let r;try{r=e.addTypeAlias({name:o,type:n});const s=r.getType();return await i(s)}catch{return}finally{try{r==null||r.remove()}catch{}}}async function ia(t,e,n){if(n>ou)return{};if(t.isString()||t.isStringLiteral())return t.isStringLiteral()?{type:"string",enum:[t.getLiteralValue()]}:{type:"string"};if(t.isNumber()||t.isNumberLiteral())return t.isNumberLiteral()?{type:"number",enum:[t.getLiteralValue()]}:{type:"number"};if(t.isBoolean())return{type:"boolean"};if(t.isBooleanLiteral())return{type:"boolean",const:t.getText()==="true"};if(t.isNull()||t.isUndefined()||t.isVoid())return{type:"null"};if(t.isUnion()){const i=t.getUnionTypes(),o=i.filter(p=>p.isBooleanLiteral()),r=o.some(p=>p.getText()==="true"),s=o.some(p=>p.getText()==="false");let a=!1;const c=i.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(i.every(p=>p.isStringLiteral())&&i.length>0)return{type:"string",enum:i.map(p=>p.getLiteralValue())};if(i.every(p=>p.isNumberLiteral())&&i.length>0)return{type:"number",enum:i.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?r&&s?{type:"boolean"}:{type:"boolean",const:r}:ia(p,e,n+1))),f=jn(u);return{oneOf:lu(du(u)),...f?{discriminator:f}:{},[Fe]:"union"}}if(t.isArray()){const i=t.getArrayElementType();return{type:"array",items:i?await e(i.getText()):{}}}if(t.isTuple()){const i=t.getTupleElements(),o=await Promise.all(i.map(r=>e(r.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(t.isObject()){const i=t.getStringIndexType(),o=t.getNumberIndexType(),r=i??o,s=t.getProperties();if(r&&s.length===0)return{type:"object",additionalProperties:await e(r.getText())};const a={},c=[];for(const d of s){const l=d.getName(),f=d.getDeclarations()[0];let m;if(f)try{m=d.getTypeAtLocation(f)}catch{m=void 0}if(m!==void 0&&m.getCallSignatures().length>0)continue;const p=m!==void 0?iu(m,f):void 0;a[l]=p!==void 0?await e(p):{},d.isOptional()||c.push(l)}if(Object.keys(a).length>0){const d=r?await e(r.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:d}}return{}}return{}}function au(t){return Object.keys(t).length===0?!0:t.type==="object"&&t.additionalProperties!==void 0&&t.additionalProperties!==!1&&(t.properties===void 0||Object.keys(t.properties).length===0)}const cu=new Set(["required","enum","type"]);function yo(t,e){if(t===null||typeof t!="object")return JSON.stringify(t)??"undefined";if(Array.isArray(t)){const o=t.map(r=>yo(r));return e!==void 0&&cu.has(e)&&o.sort(),`[${o.join(",")}]`}const n=t;return`{${Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>`${JSON.stringify(o)}:${yo(n[o],o)}`).join(",")}}`}function du(t){const e=new Set,n=[];for(const i of t){const o=yo(i);e.has(o)||(e.add(o),n.push(i))}return n}function lu(t){if(t.length<2)return t.slice();const e=t.map(au),n=t.map((o,r)=>e[r]?r:-1).filter(o=>o>=0);if(n.length===0||n.length===t.length)return t.slice();const i=t.map((o,r)=>e[r]?-1:r).filter(o=>o>=0);return t.map((o,r)=>{if(!e[r])return o;const s=t.filter((a,c)=>c!==r&&(i.includes(c)||e[c]&&c<r));return{allOf:[o,{not:{anyOf:s}}]}})}function jn(t){if(t.length<2)return;const e=[];for(const i of t){if(i.type!=="object")return;const o=i.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(i=>e.every(o=>Object.prototype.hasOwnProperty.call(o,i)));for(const i of n){const o=[];let r=!0;for(const a of e){const c=a[i],d=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!d||!Array.isArray(l)||l.length!==1){r=!1;break}o.push(String(l[0]))}if(!r||new Set(o).size!==o.length)continue;const s={};return o.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:i,mapping:s}}}function cn(t,e,n){if(e>6)return{};const i=t.trim();if(i==="string")return{type:"string"};if(i==="number")return{type:"number"};if(i==="boolean")return{type:"boolean"};if(i==="null")return{type:"null"};if(i==="undefined")return{type:"null"};const o=wo[i];if(o!==void 0)return o;if(n!=null&&n.size){const r=n.get(i);if(r!==void 0){const s=wo[r];if(s!==void 0)return s}}if(i.endsWith("[]"))return{type:"array",items:cn(i.slice(0,-2),e+1,n)};if(i.includes("|")){const r=i.split("|").map(c=>c.trim());if(r.every(c=>c.startsWith("'")))return{type:"string",enum:r.map(c=>c.replace(/'/g,""))};const s=r.map(c=>cn(c,e+1,n)),a=jn(s);return{oneOf:s,...a?{discriminator:a}:{},[Fe]:"union"}}if(i.startsWith("{")&&i.endsWith("}")){const r=i.slice(1,-1).trim(),s={};for(const a of r.split(";").filter(Boolean)){const[c,d]=a.split(":").map(l=>l.trim());c&&d&&(s[c.replace("?","")]=cn(d,e+1,n))}return{type:"object",properties:s}}return{}}function ra(t){const e=[];let n=0,i=0;for(let r=0;r<t.length;r++){const s=t[r];s==="<"||s==="["||s==="{"||s==="("?n++:s===">"||s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(e.push(t.slice(i,r).trim()),i=r+1)}const o=t.slice(i).trim();return o.length>0&&e.push(o),e}function uu(t){const e=/^(?:Readonly)?Map<(.+)>$/.exec(t);return e?e[1]:void 0}function fu(t){const e=/^(?:Readonly)?Set<(.+)>$/.exec(t);return e?e[1]:void 0}function pu(t){let e=t.trim();if(e.startsWith("readonly ")&&(e=e.slice(9).trim()),!e.startsWith("[")||!e.endsWith("]"))return;const n=e.slice(1,-1).trim();if(n.length!==0)return ra(n)}async function mu(t,e){const n=t.trim(),i=uu(n);if(i!==void 0){const s=ra(i);if(s.length===2){const[a,c]=await Promise.all([e(s[0]),e(s[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=fu(n);if(o!==void 0)return{type:"array",items:await e(o),uniqueItems:!0};const r=pu(n);if(r!==void 0){const s=await Promise.all(r.map(a=>e(a)));return{type:"array",items:s,minItems:s.length,maxItems:s.length}}}const sa={"decimal.js":"Decimal"},wo={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"}},sr={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function ar(t){var n;const e=new Map;for(const i of t.getImportDeclarations()){const o=i.getModuleSpecifierValue(),r=sa[o];if(!r)continue;const s=i.getDefaultImport();if(s){const a=s.getText();a!==r&&e.set(a,r)}for(const a of i.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==r&&e.set(c,r)}}return e}function gu(t,e){return n=>{n.addNodeParser({supportsNode(i){var r,s,a;if(i.kind!==e)return!1;const o=((r=i.typeName)==null?void 0:r.escapedText)??((a=(s=i.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return o!==void 0&&Object.prototype.hasOwnProperty.call(sr,o)},createType(i){var a,c,d;const o=((a=i.typeName)==null?void 0:a.escapedText)??((d=(c=i.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:r,StringType:s}=vo();return new r(new s,{format:sr[o]},!1)}}),n.addNodeParser({supportsNode(i){return i.kind===t},createType(){const{AnnotatedType:i,StringType:o}=vo();return new i(new o,{format:"int64"},!1)}})}}let Jt;function vo(){return Jt||(Jt=be("ts-json-schema-generator"),Jt)}let mt;function hu(){if(mt)return mt;try{const t=_.dirname(be.resolve("ts-json-schema-generator/package.json"));mt=be(be.resolve("typescript",{paths:[t]}))}catch{mt=be("typescript")}return mt}const Re=new Map;function yu(){const t=process.env.APIGEN_PROGRAM_CACHE,e=t===void 0?NaN:Number(t);return Number.isFinite(e)&&e>=0?e:8}function wu(t){const e=Re.get(t);return e&&(Re.delete(t),Re.set(t,e)),e}function vu(t,e){const n=yu();if(n!==0)for(Re.delete(t),Re.set(t,e);Re.size>n;){const i=Re.keys().next().value;Re.delete(i)}}function bu(t,e){return`${t}\0${e??""}`}const Eu=new Set(["zod",/^zod\/./]);function Su(t){for(const e of t.getImportDeclarations()){const n=e.getModuleSpecifierValue();for(const i of Eu)if(typeof i=="string"){if(n===i)return!0}else if(i.test(n))return!0}return!1}function ku(t){for(const e of["$defs","definitions"]){const n=t[e];if(!n||typeof n!="object")continue;const i=Object.keys(n);if(i.length===0)continue;const o=new Set(i.filter(r=>/zod/i.test(r)));for(const[r,s]of Object.entries(n)){if(o.has(r)||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(r);break}}}for(const r of o)delete n[r]}bo(t)}function bo(t,e){if(!t||typeof t!="object")return;const n=e??new WeakSet;if(!n.has(t)){n.add(t);for(const i of Object.keys(t))if(i==="$ref"&&typeof t[i]=="string"){const o=t[i];/zod/i.test(o)&&delete t[i]}for(const[,i]of Object.entries(t))if(typeof i=="object"&&i!==null)if(Array.isArray(i))for(const o of i)typeof o=="object"&&o!==null&&bo(o,n);else bo(i,n)}}function _u(t){const e=new Set;for(const i of["$defs","definitions"]){const o=t[i];if(o&&typeof o=="object")for(const r of Object.keys(o))e.add(r)}const n=Eo(t,e);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 Eo(t,e){if(!t||typeof t!="object")return[];const n=[];for(const[i,o]of Object.entries(t))if(i==="$ref"&&typeof o=="string"){const r=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);r&&!e.has(r[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const r of o)typeof r=="object"&&r!==null&&n.push(...Eo(r,e));else n.push(...Eo(o,e));return n}function Au(t){const e=t.anyOf;if(!Array.isArray(e)||e.length<2)return t;const n=e,i=jn(n),o={...t};return delete o.anyOf,{...o,oneOf:n,...i?{discriminator:i}:{},[Fe]:o[Fe]??"union"}}function Nu(t,e,n){const{DEFAULT_CONFIG:i}=be("ts-json-schema-generator/dist/src/Config.js"),o={...i,...t},r=o.path,s=bu(r,o.tsconfig);let a;a=n?n.statVersion(r):ta(r);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??wu(s);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=be("ts-json-schema-generator/dist/factory/program.js"),{createParser:u,createFormatter:f,SchemaGenerator:m}=vo(),p=hu(),g=gu(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),y=l(o),w=u(y,o,g),v=f(o);if(c=new m(y,w,v,o),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const b={version:a,gen:c};vu(s,b),n==null||n.generatorCache.set(s,b)}}const d=c.createSchema(o.type);return ku(d),_u(d),d}function Ru(t,e){let n=t.trim();if(n=ca(n),e!=null&&e.size){const o=e.get(n);if(o!==void 0)return o}const i=n.match(/^ReadonlyArray<(.+)>$/);for(i&&(n=`${i[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function aa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const ju=Object.entries(sa).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${aa(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ca(t){let e=t;for(const{pattern:n,key:i}of ju)e=e.replace(n,i);return e}function Tu(t,e){let n=ca(t);for(const[i,o]of e)n=n.replace(new RegExp(`\\b${aa(i)}\\b`,"g"),o);return n}async function At(t,e,n,i,o,r){const s=e.getFilePath(),a=`${s}\0${i??""}\0${n}`,c=r??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),cr(t,e,n,i,void 0,p)}const d=o.schemaCache.get(a);if(d!==void 0)return o.stats.schemaCacheHits++,d;const l=zl(s,i,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 m=cr(t,e,n,i,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,m),m}async function cr(t,e,n,i,o,r){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(o){const f=o.aliasCache.get(e);s=f??ar(e),f||o.aliasCache.set(e,s)}else s=ar(e);const a=Ru(n,s),c=wo[a];if(c!==void 0)return c;const d=await mu(a,f=>At(t,e,f,i,o,r));if(d!==void 0)return d;const l=(o==null?void 0:o.zodImportCache.get(e))??Su(e);if(o&&o.zodImportCache.set(e,l),!l)try{const f={path:e.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:i,topRef:!1},m=Nu(f,!0,o);return Au(m)}catch{}try{const f=await su(t,e,a,m=>ia(m,p=>At(t,e,p,i,o,r),0));if(f!==void 0)return f}catch{}const u=Tu(a,s);return cn(u,0,s)}function si(t,e,n){if(t!=null&&t.hasInitializer()){const i=t.getInitializer();if(i)return i.getText()}return Ou(n,e)}function Ou(t,e){var s;const n=t,i=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],o=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\[\\s*${o}\\s*=\\s*([^\\]]+)\\]`);for(const a of i)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(r);if(d)return d[1].trim()}}function Iu(t){const e=t.trim(),n=e.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(e))return Number(e);try{return JSON.parse(e)}catch{return e}}}function $u(t,e){const n=Iu(e);if(n===void 0)return;t.default=n;const i=typeof n=="string"?n:JSON.stringify(n),o=typeof t.description=="string"?t.description:void 0;t.description=o?`${o} (default: ${i})`:`(default: ${i})`}let zt;function Cu(){return zt||(zt=be("ts-morph").SyntaxKind,zt)}function Tn(t){try{if(!t)return;const e=Cu();if(t.getKind()!==e.TypeReference)return;const n=t;if(n.getTypeArguments().length>0)return;const i=n.getTypeName();if(i.getKind()!==e.Identifier)return;const r=i.getSymbol();if(!r)return;const s=r.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 m=f.getCommentText();if(m!==void 0)return m.trim()}return}catch{return}}const Pu=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function Lu(t){const e=[];let n=0,i="";for(const o of t)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(e.push(i.trim()),i=""):i+=o;return i.trim().length>0&&e.push(i.trim()),e}function Uu(t){const e=t.trim(),n=e.indexOf("<");if(n===-1||!e.endsWith(">"))return null;const i=e.slice(0,n),o=i.includes(".")?i.slice(i.lastIndexOf(".")+1):i;if(!Pu.has(o))return null;let r=0;for(let c=n;c<e.length;c++){const d=e[c];if(d==="<")r++;else if(d===">"&&(r--,r===0&&c!==e.length-1))return null}if(r!==0)return null;const s=e.slice(n+1,-1),a=Lu(s);return a.length>0?a[0]:null}async function da(t){const e=t.session===void 0,n=Ql(t.session??Xl());try{return await Du(t,n)}finally{e&&n.dispose()}}async function Du(t,e){const{sourceFile:n,namespace:i="",dropFileSegment:o=!1,tsconfig:r}=t,s=e.projectFor(r),a=e.sourceFileFor(n,r),c=_.basename(n),d=we(xu(c)),l=o?null:d,u=we(i),f=[];for(const[g,y]of a.getExportedDeclarations()){if(g==="default"||Xt(g))continue;const w=Bu(y);if(w){const S=w.getSignature(),E=ur(S,w),N=S.getReturnType().getText(),k=Ce(S);f.push(await Yt(s,a,u,l,g,E,N,w.isAsync(),r,e,k));continue}const v=y.find(S=>S.getKindName()==="VariableDeclaration");if(!v)continue;const b=v.getInitializer(),h=b==null?void 0:b.getKindName();if(b&&["ArrowFunction","FunctionExpression"].includes(h??"")){const E=v.getType().getCallSignatures();if(E.length===0)continue;const N=E[0],k=fr(N,v,v.getVariableStatement()),R=N.getReturnType().getText(),A=Ce(N),O=b.isAsync();f.push(await Yt(s,a,u,l,g,k,R,O,r,e,A))}else if(h==="ObjectLiteralExpression"){const S=v.getType();for(const E of S.getProperties()){const N=E.getName();if(Xt(N))continue;const R=E.getTypeAtLocation(v).getCallSignatures();if(R.length===0)continue;const A=R[0],O=fr(A,v,v.getVariableStatement()),I=A.getReturnType().getText(),L=Ce(A),$=[...l?[l]:[],we(g),we(N)];f.push(await dn(s,a,u,$,N,O,I,!1,r,e,L))}}else{const S=v.getType(),E=S.getText();if(Le(S,v)){const N=await At(s,a,E,r,e);f.push(Mu(u,l,g,N))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${g}`)}}const m=a.getDefaultExportSymbol();if(m){const g=a.getExportAssignment(y=>!y.isExportEquals());if(g){const y=g.getExpression(),w=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes(w)){const b=y.getType().getCallSignatures();if(b.length>0){const h=b[0],S=Yn(h,g),E=h.getReturnType().getText(),N=Ce(h),k=y.isAsync();f.push(await Yt(s,a,u,l,"default",S,E,k,r,e,N))}}else{const v=y.getType();for(const b of v.getProperties()){const h=b.getName();if(Xt(h))continue;const E=b.getTypeAtLocation(g).getCallSignatures();if(E.length===0)continue;const N=E[0],k=Yn(N,g),R=N.getReturnType().getText(),A=Ce(N),O=[...l?[l]:[],we("default"),we(h)];f.push(await dn(s,a,u,O,h,k,R,!1,r,e,A))}}}else{const y=m.getDeclarations();for(const w of y){if(w.getKindName()!=="FunctionDeclaration")continue;const v=w,b=v.getName(),h=b&&b.length>0?b:"default",S=v.getSignature(),E=ur(S,v),N=S.getReturnType().getText(),k=Ce(S);f.push(await Yt(s,a,u,l,h,E,N,v.isAsync(),r,e,k))}}}const p=Fu(a);if(p.length>0)for(const{name:g,sig:y}of p){if(Xt(g))continue;const w=Yn(y),v=y.getReturnType().getText(),b=Ce(y),h=[...l?[l]:[],we(g)];f.push(await dn(s,a,u,h,g,w,v,!1,r,e,b))}return f}function dr(t,e,n,i){const o=new Set,r=s=>{if(Array.isArray(s))return s.map(r);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=e[u];for(const[m,p]of Object.entries(l)){const g=r(p),y=f[m];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(g))throw new Error(`[apigen-core-client] Function "${n}": param "${i}" contributes a "${u}.${m}" 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[m]=g}continue}c[d]=r(l)}return c}finally{o.delete(s)}};return r(t)}function lr(t,e){if(!e||t.format!==void 0||"$ref"in t||"properties"in t||"items"in t)return;const n=t.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(t.format=e)}function Ce(t){var e;try{return Tn((e=t.getDeclaration())==null?void 0:e.getReturnTypeNode())}catch{return}}async function Yt(t,e,n,i,o,r,s,a,c,d,l){const u=we(o);return dn(t,e,n,i?[i,u]:[u],o,r,s,a,c,d,l)}async function dn(t,e,n,i,o,r,s,a,c,d,l){const u=r.length>0&&r[0].name==="ctx",f=r.filter(A=>A.name!=="ctx"),m=f.filter(A=>!A.optional).map(A=>A.name),p={},g={definitions:{},$defs:{}};for(const A of f){const O=await At(t,e,A.type,c,d),I=dr(O,g,o,A.name);A.defaultValue!==void 0&&$u(I,A.defaultValue),lr(I,A.format),p[A.name]=I}const y=s.replace(/^Promise<(.+)>$/,"$1").trim(),w=Uu(y),v=w!==null,b=v?w:y,h=await At(t,e,b,c,d),S={definitions:{},$defs:{}},E=dr(h,S,o,"<return>"),N=l?{...E}:E;lr(N,l),Object.keys(S.definitions).length>0&&(N.definitions={...N.definitions,...S.definitions}),Object.keys(S.$defs).length>0&&(N.$defs={...N.$defs,...S.$defs});const k={type:"object",properties:p,required:m,...Object.keys(g.definitions).length>0?{definitions:g.definitions}:{},...Object.keys(g.$defs).length>0?{$defs:g.$defs}:{}};return{id:la(n,i),host:"ts",namespace:n,path:i,kind:"action",async:a,streaming:v,safe:!1,input:k,output:N,envelope:{},typeText:{lang:"ts",input:Ku(r),output:b},...u?{hasCtx:!0}:{}}}function Mu(t,e,n,i){const o=we(n),r=e?[e,o]:[o];return{id:la(t,r),host:"ts",namespace:t,path:r,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:i,envelope:{},typeText:null}}function la(t,e){return(t.raw?[t,...e]:e).map(i=>i.words.join("-")).join("/")}function Nt(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function we(t){return{raw:t,words:Nt(t)}}function xu(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Fu(t){const e=[];for(const n of t.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const i=n.getExpression();if(i.getKindName()!=="BinaryExpression")continue;const o=i;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&&e.push({name:c.getName(),sig:l[0]})}}return e}function Bu(t){let e;for(const n of t){if(n.getKindName()!=="FunctionDeclaration")continue;const i=n;if(e||(e=i),i.getBody())return i}return e}function ur(t,e){return t.getParameters().map(n=>{var s;const i=n.getDeclarations(),o=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,r=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(t.getDeclaration()).getText(),optional:r,defaultValue:si(o,n.getName(),e),format:Tn(o==null?void 0:o.getTypeNode())}})}function fr(t,e,n){return t.getParameters().map(i=>{var a;const o=i.getDeclarations(),r=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,s=i.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((a=r==null?void 0:r.hasQuestionToken)==null?void 0:a.call(r))??!1);return{name:i.getName(),type:i.getTypeAtLocation(e).getText(),optional:s,defaultValue:si(r,i.getName(),n??e),format:Tn(r==null?void 0:r.getTypeNode())}})}function Yn(t,e){return t.getParameters().map(n=>{var s,a,c;const i=n.getDeclarations(),o=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,r=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:r,defaultValue:si(o,n.getName(),e),format:Tn(o==null?void 0:o.getTypeNode())}})}function Ku(t){const e=t.filter(n=>n.name!=="ctx");return e.length===0?"()":"("+e.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Xt(t){return!!(t==="__samples__"||t.startsWith("__"))}function Le(t,e,n=new Set){if(t.getCallSignatures().length>0||t.getConstructSignatures().length>0)return!1;if(t.isString()||t.isNumber()||t.isBoolean()||t.isNull()||t.isUndefined()||t.isStringLiteral()||t.isNumberLiteral()||t.isBooleanLiteral()||t.isEnumLiteral())return!0;if(t.isArray()||t.isReadonlyArray()){const i=t.getArrayElementType();return i?Le(i,e,n):!1}if(t.isTuple())return t.getTupleElements().every(i=>Le(i,e,n));if(t.isUnion())return t.getUnionTypes().every(i=>Le(i,e,n));if(t.isIntersection())return t.getIntersectionTypes().every(i=>Le(i,e,n));if(t.isObject()){const i=t.getText(e);if(n.has(i))return!0;n.add(i);const o=t.getStringIndexType(),r=t.getNumberIndexType();if(o||r)return[o,r].every(a=>!a||Le(a,e,n));const s=t.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(e);return Le(c,e,n)})}return!1}function qu(t,e){return async n=>{let i=()=>e(n);for(let o=t.length-1;o>=0;o--){const r=t[o],s=i;i=()=>r(n,s)}return i()}}function Hu(t,e){return qu(t,e)}function Vu(t,e,n={}){const i=t.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return Hu(i,e)}function Gu(t){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:t}},{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 Wu(t){return{operationConst:t.id,itemsSchema:t.input,resultSchema:Gu(t.output)}}function Ju(t,e={}){const n=new Set(e.exclude??[]),i=new Map;for(const o of t){if(n.has(o.id))continue;const r=i.get(o.kind);r?r.push(o):i.set(o.kind,[o])}return i}function pr(t){return{type:"string",enum:[t]}}function mr(t,e){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:e,items:{type:"array",items:t.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 gr(t,e){const n={},i={},o=[["definitions",n],["$defs",i]];for(const r of t){const s=e(r);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 "${r.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(i).length>0?{$defs:i}:{}}}function zu(t){if(t.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const e=t.map(Wu),n=gr(t,s=>s.input),i=gr(t,s=>s.output);if(t.length===1){const[s]=t,[a]=e;return{input:{...mr(a,pr(s.id)),...n},output:{type:"array",items:a.resultSchema,...i}}}const o=t.map((s,a)=>mr(e[a],pr(s.id))),r=jn(o);return{input:{oneOf:o,...r?{discriminator:r}:{},...n},output:{oneOf:e.map(s=>({type:"array",items:s.resultSchema})),...i},...r?{discriminator:r}:{}}}function Yu(t,e={}){const n=Ju(t.operations,e),i=[];for(const[o,r]of n){const{input:s,output:a}=zu(r),c=Qs(`_batch/${o}`,t,{kind:o,safe:o==="query",input:s,output:a});i.push({...c,operationIds:r.map(d=>d.id)})}return i}function ai(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,i=!n&&!!process.stderr.isTTY,o=t.format??(i?"pretty":"json"),r={level:e};if(o==="pretty")return r.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},Gt(r);const s=n?Gt.destination({dest:t.destination,mkdir:!0,sync:!0}):Gt.destination(2);return Gt(r,s)}function Xu(t){if((t==null?void 0:t.type)!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([o,r])=>`${o}${n.has(o)?"":"?"}: ${On(r)}`).join(", ")} }`}function Qu(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function Zu(t){const e=t.enum??[];return e.length===0?"unknown":e.map(Qu).join("|")}function ef(t,e){return t.map(n=>On(n,e)).join(" | ")}function On(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${On(t.items,0)}[]`;if(t.enum)return Zu(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?ef(n,e-1):"union":e>=1&&t.type==="object"?Xu(t)??"object":t.type??"object"}function ua(t){var a;const n=(a=((t==null?void 0:t.input)??{}).properties)==null?void 0:a.data,i=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),r=Object.entries(i).map(([c,d])=>({name:c,type:On(d,2),required:o.has(c)})),s=r.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:r,text:s}}function tf(t){let e;return Array.isArray(t)?e=t:t?e=[t]:e=[],e.find(n=>n==="number"||n==="integer"||n==="boolean")}function nf(t,e){var r,s;const i=((s=(r=((e==null?void 0:e.input)??{}).properties)==null?void 0:r.data)==null?void 0:s.properties)??{},o={...t};for(const[a,c]of Object.entries(i)){const d=o[a];if(typeof d!="string")continue;const l=tf(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 of=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],rf={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},hr={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class z extends Error{constructor(e,n,i){super(n),this.name="ApiError",this.code=e,this.details=i,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}}function fe(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&of.includes(t.code)&&typeof t.toJSON=="function"}function yr(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const In=new qs({allErrors:!0});Sl(In);for(const t of[Fe,Xo,lo,uo,"discriminator"])In.addKeyword({keyword:t,valid:!0});In.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function sf(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function af(t,e){const n=Js(e),i=[`Validation failed: ${sf(t)}`];return n&&i.push(n),i.join(" — ")}function cf(t){return async function(n,i){const o=n.operation.id,r=t[o];if(r===void 0)return i();const s={data:n.domainArgs,...n.envelope},a=In.compile(r.input);if(!a(s)){const d=a.errors??[];throw new z("invalid_argument",af(d,r.input),d)}return i()}}async function fa(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const i=fe(n)?n:new z("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:yr("before-first-chunk",i)}:{ok:!1,carrier:yr("after-first-chunk",i,e.length)}}}function $n(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Pe extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function Xn(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const i=n.mapping;if(!(i===null||typeof i!="object"||Array.isArray(i)))return{propertyName:n.propertyName,mapping:i}}function pa(t,e){const n=t[Xo];if(typeof n=="string"){const i=e.registry.get(n);if(i)return i}return e.registry.resolve(t)}function df(t,e,n){const i=pa(e,n);return i?i.encode(t,e,n):t}function lf(t,e,n){const i=pa(e,n);return i?i.decode(t,e,n):t}function uf(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(i){if(i[Fe]==="union")return!0;const o=i.oneOf;return!Array.isArray(o)||o.length===0?!1:Xn(i)!==void 0},encode(i,o,r){const s=Xn(o);if(!s)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=s,d=i[a];if(d==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${r.path}" is missing the discriminator property "${a}".`);const l=String(d),u=c[l];if(!u)throw new Pe("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${r.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=r.resolve(u);return df(i,f,{...r,path:`${r.path}[${l}]`})},decode(i,o,r){if(i===null||typeof i!="object"||Array.isArray(i)){let p;throw i===null?p="null":Array.isArray(i)?p="array":p=typeof i,new Pe("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${r.path}", got ${p}.`)}const s=i,a=Xn(o);if(!a)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:d}=a,l=s[c];if(l==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${r.path}" is missing the discriminator property "${c}".`);const u=String(l),f=d[u];if(!f)throw new Pe("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${u}" on the wire at "${r.path}" is not in the mapping (known: ${Object.keys(d).join(", ")}).`);const m=r.resolve(f);return lf(i,m,{...r,path:`${r.path}[${u}]`})}}}const ff="x-apigen-instances";class Qt extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}}function wr(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function pf(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function vr(t,e,n){if(e){const i=n.registry.resolve(e);if(i)return i.encode(t,e,n)}return t}function mf(t,e,n){if(e){const i=n.registry.resolve(e);if(i)return i.decode(t,e,n)}return t}function gf(t){const{id:e,schema:n,ctor:i}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Fe]==="nominal"?!0:o[Xo]===e},encode(o,r,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new Qt("E_NOMINAL_CYCLE",`[${e}] 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=wr(r),c=typeof r[uo]=="string"?r[uo]:"toJSON",d=o[c];if(typeof d=="function"){const p=d.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const g={};for(const[y,w]of Object.entries(p))g[y]=vr(w,a[y],{...s,path:`${s.path}/${y}`});return g}return p}const l={},u=Object.keys(a),f=o,m=u.length>0?u:Object.keys(f);for(const p of m){const g=f[p];g!==void 0&&(l[p]=vr(g,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(o)}},decode(o,r,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 Qt("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=o;for(const l of pf(r))if(!(l in a))throw new Qt("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${s.path}".`);if(r[ff]===!1)throw new Qt("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=wr(r),d={};for(const[l,u]of Object.entries(a))d[l]=mf(u,c[l],{...s,path:`${s.path}/${l}`});if(i){const l=typeof r[lo]=="string"?r[lo]:"fromJSON",u=i[l];if(typeof u=="function")return u.call(i,d);const f=i;return new f(d)}return d}}}const hf=[Zo,ei,ti,ni,oi,ii],yf={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},br=gf({id:"ts.NominalSentinel",schema:yf}),wf={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Er=uf({id:"ts.UnionSentinel",schema:wf});function vf(){const t=[...hf.map(e=>[e.id,e]),[br.id,br],[Er.id,Er]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:$l,codecs:vf()});function So(t,e,n){var s;const i=typeof((s=e==null?void 0:e.input)==null?void 0:s.description)=="string"?e.input.description:void 0,o=Js(e==null?void 0:e.input),r=[n,i,o].filter(a=>typeof a=="string"&&a.length>0);return r.length>0?r.join(" — "):t}function ma(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length===0)return{outputSchema:void 0,wrapped:!1};const e=t;return e.type==="object"?{outputSchema:e,wrapped:!0}:{outputSchema:void 0,wrapped:!1}}function bf(t,e){if(t)return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}const Ef=4,Sf=32;function ko(t){return fe(t)?t:t instanceof Error?new z("internal",t.message):t}function kf(t,e){if(t==="serial"||t==="chained")return 1;const n=e??Ef;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Sf)}function _f(){}function Af(t,e){var r;if(!t&&!e)return{signal:void 0,dispose:_f};const n=new AbortController,i=()=>{n.abort(t==null?void 0:t.reason)};t&&(t.aborted?n.abort(t.reason):t.addEventListener("abort",i,{once:!0}));let o;return e!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${e}ms`,"TimeoutError"))},e),(r=o.unref)==null||r.call(o)),{signal:n.signal,dispose(){t&&t.removeEventListener("abort",i),o&&clearTimeout(o)}}}async function Sr(t,e,n,i,o,r){const s=Af(i.signal,r);try{const a=s.signal?{...i,signal:s.signal}:i,c=await t(e,a,o);if($n(c)){const d=await fa(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:ko(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:ko(a)}}finally{s.dispose()}}async function Nf(t,e,n,i,o={}){const r=o.mode??"parallel",s=o.onItemError??"continue",a=kf(r,o.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:ko(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(r==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(r==="serial"||r==="chained"){let p=!1;for(let g=0;g<n.length;g++){if(p){c[g]=d(g);continue}const y=await Sr(t,e,g,n[g],i,o.itemTimeoutMs);c[g]=y,y.status==="rejected"&&(r==="chained"||s==="abort")&&(p=!0)}return c}let l=0,u=!1;const f=Math.max(1,Math.min(a,n.length)),m=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(u){c[p]=d(p);continue}const g=await Sr(t,e,p,n[p],i,o.itemTimeoutMs);c[p]=g,g.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(m),c}function kr(t){return t.words.join("-")}function _r(t){return t.words.map(Tf).join("")}function Ar(t){return t.words.join("_")}function Rf(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function qe(t,e={}){var f,m;const n=[t.namespace,...t.path],i=t.safe||oa(t.input)?"GET":"POST",o=((m=(f=e.http)==null?void 0:f.verb)==null?void 0:m[t.id])??i,r="/"+n.map(p=>kr(p)).join("/"),s=n.map(p=>Ar(p)).join("_"),c=n.map(p=>Ar(p)).slice(0,-1).join("."),d=_r(n[n.length-2]??n[0]),l=_r(n[n.length-1]),u=n.map(p=>kr(p));return{http:{verb:o,route:r},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function ga(t,e){return`x-${t}-${e}`}function ha(t,e){return`--${t}-${e}`}function ya(t,e){const n=i=>i.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function fn(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}function jf(t){const e=new Set,n=[];for(const i of t){const o=fn(i);let r=o,s=2;for(;e.has(r);)r=`${o}_${s}`,s+=1;e.add(r),n.push(r)}return n}function Tf(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function wa(t){return t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ye(t){return wa(JSON.stringify(t))}function Of(t,e=3e3){if(t==null)return e;if(typeof t!="string"&&typeof t!="number")throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);if(typeof t=="string"&&t.trim()==="")throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);const n=Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);return n}function ci(t){return t.anyOf??t.oneOf}function If(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="array"||i.type==="object")}return!1}function $f(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="boolean")}return!1}function Cf(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="number"||i.type==="integer")}return!1}function Pf(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function Lf(t){var o,r;const e=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data,n=(e==null?void 0:e.properties)??{},i=(e==null?void 0:e.required)??[];return{props:n,required:i}}function Nr(t){return typeof t.handler=="function"}function Uf(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i=[];for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd",a=ga(s,r);i.push({field:r,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:ha(s,r),envVar:ya(s,r)})}return i}function Df(t,e,n,i){e===n||t.has(e)||t.set(e,{...i,aliasOf:n})}function Mf(t,e){const n=new Map,{props:i}=Lf(t);for(const[o,r]of Object.entries(i)){let s="string";$f(r)?s="boolean":(If(r)||Cf(r))&&(s="json");const a=Pf(o),c={camelKey:o,kind:"domain",valueKind:s};n.set(a,c),Df(n,o,a,c)}for(const o of e){const r=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(r,s)}return n}function Oe(t){const{op:e,schema:n,transport:i,projection:o}=t,r=qe(e,o),s=n?Uf(n):[],a=n?Mf(n,s):new Map,c=n?ua(n).params:void 0,d={op:e,transport:i,http:r.http,mcp:r.mcp,cli:r.cli,grpc:r.grpc,params:c,envelope:s,cliFlags:a,streaming:e.streaming,isMount:Nr(e)};if(Nr(e)){const l=e.handler;d.mountHandler=async u=>l(u)}return d}function di(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function xf(t){const e=t.exitCode;return typeof e=="function"?e:void 0}function li(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function Ff(t){return async function(n,i){const o=Object.assign(n,{data:n.domainArgs});return await t.layer(o,i)}}function Ee(t,e){var i;const n=[];for(const o of e){const r=(i=o.capabilities)==null?void 0:i.layer;r&&n.push(Ff(r))}return n.push(cf(t)),Jl(n)}function Bf(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const Kf={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function st(t,e,n,i){const o={...n,operation:{id:t.op.id},ctx:new Pt};if(t.isMount){const r=t.mountHandler;if(!r)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const s={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:Bf(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...i,fns:{[t.op.id]:()=>r(s)},schemas:{[t.op.id]:Kf}};return e(t.op.id,o,a)}return e(t.op.id,o,i)}function va(t){return t.anyOf??t.oneOf}function qf(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i=[];for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd";i.push({field:r,pluginId:s,flag:ha(s,r),envVar:ya(s,r)})}return i}function _o(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=va(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="array"||i.type==="object")}return!1}function Hf(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=va(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="boolean")}return!1}function Rr(t){var o,r;const e=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data,n=(e==null?void 0:e.properties)??{},i=(e==null?void 0:e.required)??[];return{props:n,required:i}}function Vf(t){const e=/^#\/oneOf\/(\d+)$/.exec(t);if(e)return Number(e[1])}function Gf(t){const n=ui(t).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function Qn(t){var r,s;const e=(s=(r=t.input)==null?void 0:r.properties)==null?void 0:s.data;if(!e)return;const n=e.oneOf,i=e.discriminator;if(!n||!i)return;const o=[];for(const[a,c]of Object.entries(i.mapping)){const d=Vf(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:Gf(a),props:u,required:f})}if(o.length!==0)return{discriminatorProperty:i.propertyName,branches:o}}function ui(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function Wf(t,e){if(!ao.isAbsolute(e))return e;const n=ao.relative(t,e);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Jf=["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 ba(t,e,n){for(const i of e){const o=i.flag.replace(/^--/,"");t.push(` .option('${i.flag} <${o}>', '${i.field} (env: ${i.envVar})')`)}n&&!e.some(i=>i.field==="session")&&t.push(" .option('--session <key>', 'Session key')")}function Ea(t,e,n,i){var o;for(const r of e){const s=ui(r),a=Hf(n[r]),c=i.includes(r);a?(t.push(` .option('--${s}')`),((o=n[r])==null?void 0:o.default)===!0&&t.push(` .option('--no-${s}')`)):c?t.push(` .requiredOption('--${s} <${s}>')`):t.push(` .option('--${s} <${s}>')`)}}function Sa(t,e,n){return`${t}:${e}::${n}`}function ka(t,e){const{varName:n,pkgId:i,fnName:o,bindings:r,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=e,l=e.dispatchSchemaKey??`${i}:${o}`;t.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([m,p])=>`'${m}': ${p}`),f=a.map(m=>_o(c[m])?`'${m}': __apigenParseJsonArg('${ui(m)}', opts['${m}'])`:`'${m}': opts['${m}']`);if(t.push(` const domainArgs: Record<string, unknown> = { ${[...u,...f].join(", ")} }`),r.length>0){const m=r.map(p=>{const y=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(w,v)=>v.toUpperCase());return`'${p.field}': opts['${y}'] ?? process.env['${p.envVar}']`});t.push(` const envelope: Record<string, unknown> = { ${m.join(", ")} }`)}else s?t.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):t.push(" const envelope: Record<string, unknown> = {}");t.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),t.push(" console.log(JSON.stringify(result))"),t.push(" })")}function zf(t,e){const{varName:n,pkgId:i,fnName:o,bindings:r,needsSession:s,rootUnion:a}=e,c=fn(`${i}_${o}_cmd`);t.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);t.push(`${c}`),t.push(` .command('${d.commandName}')`),ba(t,r,s),Ea(t,l,d.props,u),ka(t,{varName:n,pkgId:i,fnName:o,dispatchSchemaKey:Sa(i,o,d.commandName),bindings:r,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function Yf(t){const e=t.options.name??"cli",n=t.options.version??"0.1.0",i=t.packages.some(s=>Object.values(s.schemas).some(a=>{const c=Qn(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>_o(l.props[u])));const{props:d}=Rr(a);return ho(a).some(l=>_o(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 t.packages){const a=fn(s.id),c=Wf(t.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(""),i&&(o.push(Jf),o.push(""));const r=Object.fromEntries(t.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,c])));for(const s of t.packages)for(const[a,c]of Object.entries(s.schemas)){const d=Qn(c);if(d)for(const l of d.branches){const u=Sa(s.id,a,l.commandName);r[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(r,null,2)}`),o.push(""),o.push(`const program = new Command().name('${e}').version('${n}')`),o.push("");for(const s of t.packages){const a=fn(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=Xs(d,"session"),u=qf(d),f=Qn(d);if(f){zf(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const m=ho(d),{props:p,required:g}=Rr(d);o.push("program"),o.push(` .command('${c}')`),ba(o,u,l),Ea(o,m,p,g),ka(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,paramNames:m,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
+ `)}]}}function Xf(t){return{props:t.properties??{},required:t.required??[]}}function Qf(t){const e=t??{},i=Array.isArray(e.oneOf)&&e.oneOf.length>0?e.oneOf:[e],o={},r=new Map;for(const a of i){const{props:c,required:d}=Xf(a);for(const[l,u]of Object.entries(c))l in o||(o[l]=u);for(const l of d)r.set(l,(r.get(l)??0)+1)}const s=[...r.entries()].filter(([,a])=>a===i.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:o,required:s}},required:["data"]},output:{}}}function Zf(t){const e=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let i;for(;i=n.exec(t);)e.push(i[1]??i[2]??i[3]);return e}function ep(t){const e=t.argv;return Array.isArray(e)?e.map(String):typeof e=="string"?Zf(e):process.argv.slice(2)}function tp(t,e){return{id:t,host:"ts",namespace:{raw:t,words:[t]},path:[],kind:"action",async:!1,streaming:!1,safe:e["x-apigen-safe"]??!1,input:e.input??{},output:e.output??{},envelope:{},typeText:null}}function np(t){const e=new Map;for(const i of t.operations??[]){const o=i.path[i.path.length-1];o&&e.set(`${i.namespace.raw}:${o.raw}`,i)}const n=new Map;for(const i of t.packages)for(const[o,r]of Object.entries(i.schemas)){const s=e.get(`${i.id}:${o}`)??tp(o,r),a=Oe({op:s,schema:r,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:i.id,fnName:o,schema:r,cliPath:c,plan:a})}return n}function op(t,e){let n=0;for(;n<t.length&&!t[n].startsWith("-");)n++;for(let i=n;i>=1;i--){const o=e.get(t.slice(0,i).join(" "));if(o)return{entry:o,rest:t.slice(i)}}return null}function _a(t){return!t||t.length===0?"":t.map(e=>`${e.name}${e.required?"":"?"}: ${e.type}`).join(", ")}function ip(t){return[...t.cliFlags.entries()].filter(([,e])=>e.aliasOf===void 0).map(([e])=>e).sort()}function jr(t){const e=[...t.entries()].sort(([s],[a])=>s.localeCompare(a)),n=[],i=[];for(const s of e)(s[1].plan.isMount?n:i).push(s);const o=([s,{plan:a}])=>{const c=_a(a.params),d=ip(a),l=d.length?` [${d.map(u=>`--${u}`).join(", ")}]`:" (no flags)";return` ${s}${c?` { ${c} }`:""}${l}`},r=["Available commands:","","Namespaced verbs (namespace + verb):"];if(n.length===0)r.push(" (none)");else for(const s of n)r.push(o(s));if(r.push(""),r.push("Verbs (one-token):"),i.length===0)r.push(" (none)");else for(const s of i)r.push(o(s));return r.push(""),r.push("Each command lists the flags it accepts in [brackets]."),r.join(`
5
+ `)}function Zt(t){return new z("invalid_argument",t)}function rp(t,e){var r;const n={},i={};let o=0;for(;o<t.length;){const s=t[o];if(!s.startsWith("--"))throw Zt(`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-")&&((r=e.get(a.slice(3)))==null?void 0:r.valueKind)==="boolean"&&(l=!0,u=a.slice(3));const f=e.get(u);if(!f)throw Zt(`Unknown option: --${a}. Available: ${[...e.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);o++;let m;if(f.valueKind==="boolean")l?m=!1:c===void 0?m=!0:m=c!=="false";else{const p=c!==void 0?c:t[o++];if(p===void 0)throw Zt(`Missing value for --${a}`);if(f.valueKind==="json")try{m=JSON.parse(p)}catch(g){throw Zt(`Invalid JSON for --${a}: ${g.message}`)}else m=p}f.kind==="domain"?n[f.camelKey]=m:i[f.camelKey]=m}for(const s of e.values()){if(s.kind!=="envelope"||!s.envVar||i[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(i[s.camelKey]=a)}return{domainArgs:n,envelope:i}}function Aa(t){const e=fe(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:String(t)};console.error(JSON.stringify(e)),process.exitCode=fe(t)?hr[t.code]:hr.internal}function sp(t,e,n){if(fe(n)&&n.code!=="internal"){t.error({command:e,code:n.code,message:n.message},`✗ ${e}`);return}t.error({command:e,err:n},`✗ ${e}`)}class ap{constructor(e,n){this.signal=e,this.exitCodeHook=n,this.routes=new Map}registerRoute(e,n){this.routes.set(e.cli.path.join(" "),{plan:e,dispatch:n})}routeTable(){return this.routes}readCall(e,n){const{domainArgs:i,envelope:o}=rp(e.rest,n.cliFlags);return{domainArgs:i,envelope:o,signal:this.signal}}writeResult(e,n,i){var r;if($n(n))throw new z("invalid_argument",`Command "${i.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=(r=this.exitCodeHook)==null?void 0:r.call(this,n);typeof o=="number"&&o!==0&&(process.exitCode=o)}writeError(e,n,i){Aa(n)}}function cp(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("cli")||r.push(u)}return r}async function dp(t){var E,N,k;const e=t.logger??ai();if((E=t.signal)!=null&&E.aborted){e.info("cli run: signal already aborted before dispatch — skipping");return}let n=ep(t.options);n[0]==="--"&&(n=n.slice(1));const i=di(t.options),o=li(t.options),r=new ap(t.signal,xf(t.options)),s=np(t),a=new Map;for(const R of s.values()){const A=a.get(R.pkgId);A?A.push(R):a.set(R.pkgId,[R])}const c={},d={};for(const R of t.packages){const A=a.get(R.id);if(!A||A.length===0)continue;if(!R.fns)throw new Error(`apigen-plugin-cli-output: package "${R.id}" has no functions`);const O=R.fns,I={},L={};for(const H of A)I[H.plan.op.id]=H.schema,L[H.plan.op.id]=O[H.fnName],c[H.plan.op.id]=H.schema,d[H.plan.op.id]=O[H.fnName];const $=Ee(I,i),Y={fns:L,createClient:R.createClient,schemas:I};for(const H of A)r.registerRoute(H.plan,ge=>st(H.plan,$,ge,Y))}const l=((N=t.packages[0])==null?void 0:N.id)??"ts",u=Ee(c,i),f={invoke:(R,A,O)=>u(R,{operation:{id:R},ctx:new Pt,domainArgs:A.domainArgs,envelope:A.envelope,signal:A.signal},O),invokeOptions:{fns:d,schemas:c,createClient:(k=t.packages[0])==null?void 0:k.createClient}},m=cp(i,o,l,t.operations??[],f);if(m.length>0){const R=Ee({},i),A={fns:{},schemas:{}};for(const O of m){const I=Oe({op:O,schema:Qf(O.input),transport:"cli"});r.registerRoute(I,L=>st(I,R,L,A))}}const p=r.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(jr(p));return}const g=op(n,p);if(!g){Aa(new z("not_found",`Unknown command: ${n.join(" ")}
6
6
 
7
- ${wr(p)}`));return}const{entry:b,rest:h}=g,{plan:y,dispatch:w}=b,v=y.cli.path.join(" ");if(h.includes("--help")||h.includes("-h")){const N=Vi(y.params);console.log(`${v}${N?` { ${N} }`:""}`);return}const S={rest:h};try{if(y.streaming)throw new F("invalid_argument",`Command "${v}" 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),j=Date.now(),O=await w(N);await i.writeResult(S,O,y),t.info({command:v,ms:Date.now()-j},`→ ${v}`)}catch(N){$l(t,v,N),await i.writeError(S,N,y)}}const Ll={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 kl(e)},run(e){return xl(e)}};function Ul(e,t){const n=e.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const o=n,r=o.operation;if(typeof r!="string"||r.length===0)throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!t.includes(r))throw new F("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${r}") is not one of this mount's batchable operations: ${t.join(", ")}`);const i=o.items;if(!Array.isArray(i))throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=o.concurrency;if(s!==void 0&&typeof s!="number")throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=o.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=o.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=o.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new F("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:r,items:i,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function Dl(e,t){return async n=>{if(!t)throw new F("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 o=Ul(n.data,e),r={concurrency:o.concurrency,mode:o.mode,onItemError:o.onItemError,itemTimeoutMs:o.itemTimeoutMs},i=o.items.map(s=>({operation:{id:o.operation},ctx:new rt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return Zd(t.invoke,o.operation,i,t.invokeOptions,r)}}function Ml(e,t={},n){return Ad(e,t).map(r=>({...r,handler:Dl(r.operationIds,n)}))}const Rt={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 Ml(e,t,n)}}}},vr={validateKind(){},validateRel(){},validateEdge(){}},Fl=5,Bl=20,Kl=500;function ql(e){return he.isBusyError(e)||he.isConcurrentConflict(e)}function Hl(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function Vl(e,t={}){const n=t.maxAttempts??Fl;for(let o=0;;o++)try{return await e()}catch(r){if(!ql(r)||o>=n-1)throw r;const i=Math.min(Kl,Bl*2**o);await Hl(i*(.5+Math.random()*.5))}}const ao=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class Wi extends Error{constructor(t,n){const o=t.length>0?t.map(r=>`${r.kind}=${r.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
7
+ ${jr(p)}`));return}const{entry:y,rest:w}=g,{plan:v,dispatch:b}=y,h=v.cli.path.join(" ");if(w.includes("--help")||w.includes("-h")){const R=_a(v.params);console.log(`${h}${R?` { ${R} }`:""}`);return}const S={rest:w};try{if(v.streaming)throw new z("invalid_argument",`Command "${h}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const R=await r.readCall(S,v),A=Date.now(),O=await b(R);await r.writeResult(S,O,v),e.info({command:h,ms:Date.now()-A},`→ ${h}`)}catch(R){sp(e,h,R),await r.writeError(S,R,v)}}const lp={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(t){return Yf(t)},run(t){return dp(t)}};function up(t,e){const n=t.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const i=n,o=i.operation;if(typeof o!="string"||o.length===0)throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!e.includes(o))throw new z("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${e.join(", ")}`);const r=i.items;if(!Array.isArray(r))throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=i.concurrency;if(s!==void 0&&typeof s!="number")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=i.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=i.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=i.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:r,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function fp(t,e){return async n=>{if(!e)throw new z("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 i=up(n.data,t),o={concurrency:i.concurrency,mode:i.mode,onItemError:i.onItemError,itemTimeoutMs:i.itemTimeoutMs},r=i.items.map(s=>({operation:{id:i.operation},ctx:new Pt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return Nf(e.invoke,i.operation,r,e.invokeOptions,o)}}function pp(t,e={},n){return Yu(t,e).map(o=>({...o,handler:fp(o.operationIds,n)}))}const pn={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(t,e,n){return pp(t,e,n)}}}},Tr={validateKind(){},validateRel(){},validateEdge(){}},mp=5,gp=20,hp=500;function yp(t){return Ne.isBusyError(t)||Ne.isConcurrentConflict(t)}function wp(t){return new Promise(e=>setTimeout(e,Math.max(0,Math.round(t))))}async function vp(t,e={}){const n=e.maxAttempts??mp;for(let i=0;;i++)try{return await t()}catch(o){if(!yp(o)||i>=n-1)throw o;const r=Math.min(hp,gp*2**i);await wp(r*(.5+Math.random()*.5))}}const fi=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit","attestation","obligation","SPEC"]);class Na extends Error{constructor(e,n){const i=e.length>0?e.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
8
  expected node kind(s): ${n.join(", ")}
9
- found in store: ${o}
9
+ found in store: ${i}
10
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 Ji(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(r=>({kind:String(r.kind),count:Number(r.n)}));return{total:n.reduce((r,i)=>r+i.count,0),observed:n}}async function Gl(e){const t=[...ao],n=t.map(()=>"?").join(", "),{rows:o}=await e.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,t);return o.length>0}async function co(e){if(await Gl(e))return;const{total:t,observed:n}=await Ji(e);if(t!==0)throw new Wi(n,[...ao])}const Wl=3e4,br=new WeakMap;function Jl(e){let t=br.get(e);return t||(t=new Set,br.set(e,t)),t}function zi(e){const t=Jl(e);return{register(n){t.add(n);let o=!1;return()=>{o||(o=!0,t.delete(n))}},get size(){return t.size},snapshot(){return[...t]},async drain(n){const o=(n==null?void 0:n.timeoutMs)??Wl,r=Date.now()+o;let i=0;for(;;){const a=[...t].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=r-Date.now();if(c<=0)break;const d=await zl(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 zl(e,t){let n;const o=new Promise(r=>{n=setTimeout(()=>r("timeout"),t),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([e,o])}finally{n!==void 0&&clearTimeout(n)}}function On(){return[]}function Yl(e){const t=z.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 Xl(e,t){if(e===t)return!0;const n=k.relative(e,t);return n!==".."&&!n.startsWith(`..${k.sep}`)&&!k.isAbsolute(n)}function lo(e){const t=e==null?void 0:e.code;return t==="ENOENT"||t==="ENOTDIR"}async function Tn(e){const t=k.resolve(e);try{return await Lt.realpath(t)}catch(n){if(!lo(n))throw n;const o=k.dirname(t);if(o===t)throw n;return k.join(await Tn(o),k.basename(t))}}async function Yi(e,t,n){const o=k.isAbsolute(t)?k.resolve(t):k.resolve(e,t),r=await Tn(o);return{accepted:(await Promise.all([e,...n].map(a=>Tn(a)))).some(a=>Xl(a,r)),candidate:r}}class U extends Error{constructor(t,n=void 0,o){super(t),this.name=new.target.name,this.cause=n,this.retry_after_ms=o}}class Xi extends U{constructor(t,n){super(`Write contention: exhausted the retry budget (last backoff ${t}ms)`,n,t),this.code="E_CONTENTION",this.retryable=!0}}class Qi extends U{constructor(t){const n=Zi(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 Zi(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 Ql="backlog.write.io_failure";function In(e,t,n){const o=Zi(e);Hn.log.error(Ql,{origin:t,retryable:n,error:o.message,...o.code!==void 0?{error_code:o.code}:{},...o.stack!==void 0?{stack:o.stack}:{}})}class Kt extends U{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 W extends U{constructor(t,n){super(`${t} "${n}" was not found`),this.catalogKind=t,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class es extends U{constructor(t,n){super(`uid prefix "${t}" is ambiguous — ${n.length} items match: `+n.map(o=>`${o.uid} (${o.kind} "${o.name}")`).join(", ")+". Re-run with a longer prefix or the full uid."),this.ref=t,this.candidates=n,this.code="E_VALIDATION",this.retryable=!1}}class Zl extends U{constructor(t,n,o){super(`${t} "${o}" differs only by letter case from the existing live ${t} "${n}"; catalog identity is exact-case, so accepting it would mint a duplicate row. Use the existing spelling "${n}".`),this.catalogKind=t,this.canonicalName=n,this.offendingName=o,this.code="E_VALIDATION",this.retryable=!1}}class T extends U{constructor(t,n){super(n?`Invalid argument "${t}": ${n}`:`Invalid argument "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}class ts extends U{constructor(t,n=!1){super(n?`No live issue found — no item matches the uid prefix "${t}"`:`No live issue found for uid "${t}"`),this.uid=t,this.asPrefix=n,this.code="E_VALIDATION",this.retryable=!1}}class Ot extends U{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 ns extends U{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 $n extends U{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 uo extends U{constructor(t,n){const o=n.length===0?"the project root":n.map(Yl).join(", "),r=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: ${o} (${r})`),this.target=t,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class eu extends U{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 os(e,t){return(e==null?void 0:e.code)==="EISDIR"?new eu(t):(In(e,"citation_sha",!0),new Qi(e))}class rs extends U{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 is extends U{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 Oe extends U{constructor(t,n){super(n?`Invalid "${t}": ${n}`:`Invalid "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}function tu(e){const t=e instanceof Error?e.message:String(e);return he.isBusyError(e)||he.isConcurrentConflict(e)?{code:"E_CONTENTION",retryable:!0,message:t,cause:e}:he.isUniqueConstraintError(e)||he.isForeignKeyError(e)?{code:"E_CONSTRAINT",retryable:!1,message:t,cause:e}:he.isDatabaseError(e)?(In(e,"transaction",!0),{code:"E_IO",retryable:!0,message:t,cause:e}):(In(e,"transaction",!1),{code:"E_IO",retryable:!1,message:t,cause:e})}const nu=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function Z(e,t){if(nu.has(t.trim().toLowerCase()))throw new T(e,`"${t}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}const ou=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function pe(e){return ou.test(e)}const fo=8,ss=/^[0-9a-f-]+$/i,ru=new Set([8,13,18,23]);function qt(e){if(e.length<fo||e.length>=36||!ss.test(e))return!1;for(let t=0;t<e.length;t+=1){const n=e[t];if(ru.has(t)){if(n!=="-")return!1}else if(n==="-")return!1}return!0}function Qe(e){return pe(e)?"exact":qt(e)?"prefix":e.length>0&&e.length<fo&&ss.test(e)?"too-short":"not-uid"}async function as(e,t){const n=t.toLowerCase(),{rows:o}=await e.executeAll("SELECT uid, kind, name, is_superseded FROM node WHERE uid >= ? AND uid < ? AND t_invalid IS NULL",[n,`${n}￿`]);return o.map(r=>({uid:r.uid,kind:r.kind,name:r.name,isSuperseded:r.is_superseded===1}))}function cs(e,t){if(t.length===0)return null;if(t.length===1)return t[0];throw new es(e,t.map(n=>({uid:n.uid,kind:n.kind,name:n.name??""})))}function Ce(e,t,n){return e==="issue"?new ts(t,n):new W(e??"uid",t)}function ds(e){return new T("uid",`uid prefix "${e}" is too short — a uid prefix must be at least ${fo} characters (or pass the full uid)`)}function ls(e){if(e!=null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}function us(e){return{rowid:e.rowid,uid:e.uid,kind:e.kind,name:e.name,content:e.content??"",metadata:ls(e.meta),tInvalid:e.t_invalid,isSuperseded:e.is_superseded===1}}function D(){return new Date().toISOString()}function po(e){return me.createHash("sha256").update(e).digest("hex")}function fs(e){return JSON.stringify(Cn(e))}function Cn(e){if(Array.isArray(e))return e.map(Cn);if(e!==null&&typeof e=="object"){const t=e,n={};for(const o of Object.keys(t).sort())t[o]!==void 0&&(n[o]=Cn(t[o]));return n}return e}async function Pn(e,t){const n=await e.executeGet("SELECT * FROM node WHERE uid = ?",[t]);return n?us(n):null}async function mo(e,t,n){const o=n==null?void 0:n.expectedKind,r=await Pn(e,t);if(r){if(r.tInvalid!==null||o!==void 0&&r.kind!==o)throw Ce(o,t,!1);return r}const i=Qe(t);if(i==="too-short")throw ds(t);if(i!=="prefix")throw Ce(o,t,!1);const s=await as(e,t),a=o!==void 0?s.filter(l=>l.kind===o):s,c=cs(t,a);if(!c)throw Ce(o,t,!0);const d=await Pn(e,c.uid);if(!d||d.tInvalid!==null)throw Ce(o,t,!0);return d}async function Se(e,t){const n=await mo(e,t,{expectedKind:"issue"});if(n.isSuperseded)throw new Kt(t);return n}async function ee(e,t){const n=await e.executeGet("SELECT * FROM node WHERE rowid = ?",[t]);return n?us(n):null}const iu=["off","on"];function su(){const e=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(e===void 0)return"off";if(iu.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??D(),o=t.content??t.name??"",r=po(o.trim().toLowerCase());if(su()==="on"){const c=await e.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[r]);if(c)return{rowid:c.rowid,uid:c.uid}}const i=me.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,
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=e,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function Ra(t){const{rows:e}=await t.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=e.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,r)=>o+r.count,0),observed:n}}async function bp(t){const e=[...fi],n=e.map(()=>"?").join(", "),{rows:i}=await t.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,e);return i.length>0}async function pi(t){if(await bp(t))return;const{total:e,observed:n}=await Ra(t);if(e!==0)throw new Na(n,[...fi])}const Ep=3e4,Or=new WeakMap;function Sp(t){let e=Or.get(t);return e||(e=new Set,Or.set(t,e)),e}function ja(t){const e=Sp(t);return{register(n){e.add(n);let i=!1;return()=>{i||(i=!0,e.delete(n))}},get size(){return e.size},snapshot(){return[...e]},async drain(n){const i=(n==null?void 0:n.timeoutMs)??Ep,o=Date.now()+i;let r=0;for(;;){const a=[...e].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const d=await kp(Promise.allSettled(a.map(l=>l.settled)),c);if(r+=a.filter(l=>l.outcome!=="pending").length,d==="timeout")break}const s=[...e];return{drained:r,stillPending:s.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:s.filter(a=>a.outcome==="unrecorded")}}}}async function kp(t,e){let n;const i=new Promise(o=>{n=setTimeout(()=>o("timeout"),e),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([t,i])}finally{n!==void 0&&clearTimeout(n)}}function Ao(){return[]}function Ir(t){const e=te.homedir();if(t===e)return"~";const n=e.endsWith(_.sep)?e:e+_.sep;return t.startsWith(n)?"~"+t.slice(e.length):t}function Ta(t,e){if(t===e)return!0;const n=_.relative(t,e);return n!==".."&&!n.startsWith(`..${_.sep}`)&&!_.isAbsolute(n)}function Oa(t){const e=t==null?void 0:t.code;return e==="ENOENT"||e==="ENOTDIR"}async function No(t){const e=_.resolve(t);try{return await zo.realpath(e)}catch(n){if(!Oa(n))throw n;const i=_.dirname(e);if(i===e)throw n;return _.join(await No(i),_.basename(e))}}async function _p(t,e,n){const i=_.isAbsolute(e)?_.resolve(e):_.resolve(t,e),o=await No(i);return{accepted:(await Promise.all([t,...n].map(a=>No(a)))).some(a=>Ta(a,o)),candidate:o}}function Ia(t){const e=te.homedir();return[_.join(e,".claude","skills","backlog"),_.join(process.env.CODEX_HOME??_.join(e,".codex"),"skills","backlog"),_.join(e,".config","opencode","skills","backlog")]}async function Lt(t,e){const{rows:n}=await t.executeAll("SELECT uid, meta FROM node WHERE kind = 'project' AND t_invalid IS NULL"),i=[];for(const o of n){if(o.uid===e||o.meta===null)continue;let r;try{r=JSON.parse(o.meta)}catch{continue}if(r===null||typeof r!="object")continue;const s=r.path;typeof s=="string"&&s.length>0&&i.push(s)}return i}class C extends Error{constructor(e,n=void 0,i){super(e),this.name=new.target.name,this.cause=n,this.retry_after_ms=i}}class $a extends C{constructor(e,n){super(`Write contention: exhausted the retry budget (last backoff ${e}ms)`,n,e),this.code="E_CONTENTION",this.retryable=!0}}class Ca extends C{constructor(e){const n=Pa(e);super(`Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction: ${n.message}`,e),this.code="E_IO",this.retryable=!0,this.causeMessage=n.message,n.code!==void 0&&(this.causeCode=n.code)}}function Pa(t){if(t instanceof Error){const e=t.code;return{message:t.message,...typeof e=="string"?{code:e}:{},...t.stack!==void 0?{stack:t.stack}:{}}}if(typeof t=="object"&&t!==null){const e=t;return{message:typeof e.message=="string"?e.message:JSON.stringify(t),...typeof e.code=="string"?{code:e.code}:{}}}return{message:String(t)}}const Ap="backlog.write.io_failure";function Ro(t,e,n){const i=Pa(t);Jo.log.error(Ap,{origin:e,retryable:n,error:i.message,...i.code!==void 0?{error_code:i.code}:{},...i.stack!==void 0?{stack:i.stack}:{}})}class Ut extends C{constructor(e,n){super(n===void 0?`Issue "${e}" was already superseded by a concurrent write; re-get and retry`:`Issue "${e}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=e,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class V extends C{constructor(e,n){super(`${e} "${n}" was not found`),this.catalogKind=e,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class mi extends C{constructor(e,n){super(`uid prefix "${e}" is ambiguous — ${n.length} items match: `+n.map(i=>`${i.uid} (${i.kind} "${i.name}")`).join(", ")+". Re-run with a longer prefix or the full uid."),this.ref=e,this.candidates=n,this.code="E_VALIDATION",this.retryable=!1}}class Np extends C{constructor(e,n,i){super(`${e} "${i}" differs only by letter case from the existing live ${e} "${n}"; catalog identity is exact-case, so accepting it would mint a duplicate row. Use the existing spelling "${n}".`),this.catalogKind=e,this.canonicalName=n,this.offendingName=i,this.code="E_VALIDATION",this.retryable=!1}}class T extends C{constructor(e,n){super(n?`Invalid argument "${e}": ${n}`:`Invalid argument "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class mn extends C{constructor(e,n=!1){super(n?`No live issue found — no item matches the uid prefix "${e}"`:`No live issue found for uid "${e}"`),this.uid=e,this.asPrefix=n,this.code="E_VALIDATION",this.retryable=!1}}class gn extends C{constructor(e,n){super(`Claim already held by "${e}" since ${n}`),this.heldBy=e,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class La extends C{constructor(e,n){super(`Issue "${e}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=e,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class jo extends C{constructor(e){const n=e.side==="source"?`"${e.rel}" already has a single target (${e.conflictingUid}) for source "${e.cappedUid}"`:`"${e.rel}" already has a single source (${e.conflictingUid}) for target "${e.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=e.side,this.cappedUid=e.cappedUid,this.rel=e.rel,this.conflictingUid=e.conflictingUid}}class Ua extends C{constructor(e,n){const i=n.length===0?"the project root":n.map(Ir).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots",r=Ia().map(Ir).join(", ");super(`Citation target "${e}" could not be verified and this project requires a real sha — accepted only under: ${i} (${o}). Tool-owned roots are always accepted: ${r}`),this.target=e,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class Rp extends C{constructor(e){super(`Citation target "${e}" 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=e,this.code="E_VALIDATION",this.retryable=!1}}function jp(t,e){return(t==null?void 0:t.code)==="EISDIR"?new Rp(e):(Ro(t,"citation_sha",!0),new Ca(t))}class Da extends C{constructor(e){super(`A note is required to transition issue "${e}" (project_policy.transition_requires_note)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Ma extends C{constructor(e){super(`At least one citation is required to close issue "${e}" (project_policy.citation_required)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class _e extends C{constructor(e,n){super(n?`Invalid "${e}": ${n}`:`Invalid "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class Ue extends C{constructor(e,n){super(n?`Invalid anchor locator "${e}": ${n}`:`Invalid anchor locator "${e}"`),this.locator=e,this.code="E_VALIDATION",this.retryable=!1}}class xa extends C{constructor(e){super(`No live attestation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class ve extends C{constructor(e){super(`Invalid predicate: ${e}`),this.detail=e,this.code="E_VALIDATION",this.retryable=!1}}class Fa extends C{constructor(e){super(`No live obligation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class To extends C{constructor(e,n){super(`spec revision conflict: base_revision "${e}" does not match the current revision "${n}" — re-read the ticket's spec_revision and retry`),this.expected=e,this.actual=n,this.code="E_VALIDATION",this.retryable=!1}}function Tp(t){const e=t instanceof Error?t.message:String(t);return Ne.isBusyError(t)||Ne.isConcurrentConflict(t)?{code:"E_CONTENTION",retryable:!0,message:e,cause:t}:Ne.isUniqueConstraintError(t)||Ne.isForeignKeyError(t)?{code:"E_CONSTRAINT",retryable:!1,message:e,cause:t}:Ne.isDatabaseError(t)?(Ro(t,"transaction",!0),{code:"E_IO",retryable:!0,message:e,cause:t}):(Ro(t,"transaction",!1),{code:"E_IO",retryable:!1,message:e,cause:t})}const Op=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function G(t,e){if(Op.has(e.trim().toLowerCase()))throw new T(t,`"${e}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}class gi extends C{constructor(e){const n=e.required_kind!==void 0?` (requires "${e.required_kind}")`:"";super(`Transition refused: ${e.code}${n} — ${e.message}`),this.refusal=e,this.code="E_VALIDATION",this.retryable=!1}}class Oo extends C{constructor(e,n){super(`Override not permitted: actor "${n}" may not override obligation "${e}" (the actor is not listed in override.actors, or no override reason was recorded — an override always requires a reason)`),this.obligationUid=e,this.actor=n,this.code="E_VALIDATION",this.retryable=!1}}class hi extends C{constructor(e){const n=e.subject!==void 0?` ${e.subject}`:"";super(`Claim refused: ${e.code}${n} — ${e.message??"a block-severity condition is live"}`),this.refusal=e,this.code="E_VALIDATION",this.retryable=!1}}class Ba extends C{constructor(e){super(`No live citation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}const Ip=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function pe(t){return Ip.test(t)}const yi=8,Ka=/^[0-9a-f-]+$/i,$p=new Set([8,13,18,23]);function Dt(t){if(t.length<yi||t.length>=36||!Ka.test(t))return!1;for(let e=0;e<t.length;e+=1){const n=t[e];if($p.has(e)){if(n!=="-")return!1}else if(n==="-")return!1}return!0}function Rt(t){return pe(t)?"exact":Dt(t)?"prefix":t.length>0&&t.length<yi&&Ka.test(t)?"too-short":"not-uid"}async function qa(t,e){const n=e.toLowerCase(),{rows:i}=await t.executeAll("SELECT uid, kind, name, is_superseded FROM node WHERE uid >= ? AND uid < ? AND t_invalid IS NULL",[n,`${n}￿`]);return i.map(o=>({uid:o.uid,kind:o.kind,name:o.name,isSuperseded:o.is_superseded===1}))}function Ha(t,e){if(e.length===0)return null;if(e.length===1)return e[0];throw new mi(t,e.map(n=>({uid:n.uid,kind:n.kind,name:n.name??""})))}function ze(t,e,n){return t==="issue"?new mn(e,n):new V(t??"uid",e)}function Va(t){return new T("uid",`uid prefix "${t}" is too short — a uid prefix must be at least ${yi} characters (or pass the full uid)`)}function wi(t){if(t!=null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function Ga(t){return{rowid:t.rowid,uid:t.uid,kind:t.kind,name:t.name,content:t.content??"",metadata:wi(t.meta),tInvalid:t.t_invalid,isSuperseded:t.is_superseded===1}}function P(){return new Date().toISOString()}function He(t){return ke.createHash("sha256").update(t).digest("hex")}function vi(t){return JSON.stringify(Io(t))}function Io(t){if(Array.isArray(t))return t.map(Io);if(t!==null&&typeof t=="object"){const e=t,n={};for(const i of Object.keys(e).sort())e[i]!==void 0&&(n[i]=Io(e[i]));return n}return t}async function Be(t,e){const n=await t.executeGet("SELECT * FROM node WHERE uid = ?",[e]);return n?Ga(n):null}async function se(t,e,n){const i=n==null?void 0:n.expectedKind,o=await Be(t,e);if(o){if(o.tInvalid!==null||i!==void 0&&o.kind!==i)throw ze(i,e,!1);return o}const r=Rt(e);if(r==="too-short")throw Va(e);if(r!=="prefix")throw ze(i,e,!1);const s=await qa(t,e),a=i!==void 0?s.filter(l=>l.kind===i):s,c=Ha(e,a);if(!c)throw ze(i,e,!0);const d=await Be(t,c.uid);if(!d||d.tInvalid!==null)throw ze(i,e,!0);return d}async function ae(t,e){const n=await se(t,e,{expectedKind:"issue"});if(n.isSuperseded)throw new Ut(e);return n}async function Q(t,e){const n=await t.executeGet("SELECT * FROM node WHERE rowid = ?",[e]);return n?Ga(n):null}const Cp=["off","on"];function Pp(){const t=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(t===void 0)return"off";if(Cp.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${t}" 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 X(t,e){const n=e.at??P(),i=e.content??e.name??"",o=He(i.trim().toLowerCase());if(Pp()==="on"){const c=await t.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const r=ke.randomUUID(),s=e.metadata!==void 0?JSON.stringify(e.metadata):null,a=await t.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
12
12
  confidence, content_hash, namespace, meta, agent_id, session_id, source,
13
13
  project_path, t_occurred, t_expires, t_created, t_valid)
14
14
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
15
- RETURNING rowid`,[i,t.kind,o,t.name??null,null,null,null,1,null,r,"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 au(e,t){const{multiplicity:n}=t.rule;if(n==="n:m")return;if(n==="n:1"){const r=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(r)throw new $n({side:"source",cappedUid:t.srcUid,rel:t.rel,conflictingUid:r.uid});return}const o=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(o)throw new $n({side:"target",cappedUid:t.dstUid,rel:t.rel,conflictingUid:o.uid})}async function x(e,t){const{rule:n}=t;if(n.sourceKind!=="*"&&n.sourceKind!==t.srcKind)throw new Sr(t.rel,"source",n.sourceKind,t.srcKind);if(n.targetKind!==t.dstKind)throw new Sr(t.rel,"target",n.targetKind,t.dstKind);await au(e,t),t.typePolicy.validateEdge?t.typePolicy.validateEdge(t.srcKind,t.rel,t.dstKind):t.typePolicy.validateRel(t.rel);const o=t.at??D(),r=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)
15
+ RETURNING rowid`,[r,e.kind,i,e.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="${e.kind}" name="${e.name??""}"`);return{rowid:a.rowid,uid:r}}async function Lp(t,e){const{multiplicity:n}=e.rule;if(n==="n:m")return;if(n==="n:1"){const o=await t.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`,[e.srcRowid,e.rel,e.dstRowid]);if(o)throw new jo({side:"source",cappedUid:e.srcUid,rel:e.rel,conflictingUid:o.uid});return}const i=await t.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`,[e.dstRowid,e.rel,e.srcRowid]);if(i)throw new jo({side:"target",cappedUid:e.dstUid,rel:e.rel,conflictingUid:i.uid})}async function K(t,e){const{rule:n}=e;if(n.sourceKind!=="*"&&n.sourceKind!==e.srcKind)throw new $r(e.rel,"source",n.sourceKind,e.srcKind);if(n.targetKind!==e.dstKind)throw new $r(e.rel,"target",n.targetKind,e.dstKind);await Lp(t,e),e.typePolicy.validateEdge?e.typePolicy.validateEdge(e.srcKind,e.rel,e.dstKind):e.typePolicy.validateRel(e.rel);const i=e.at??P(),o=e.metadata!==void 0?JSON.stringify(e.metadata):null;await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
18
18
  VALUES (?, ?, ?, ?, 'user_asserted', ?, ?, ?)
19
19
  ON CONFLICT(src, dst, rel) DO UPDATE SET
20
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,r,o,o])}class Sr extends U{constructor(t,n,o,r){super(`"${t}" requires a ${n} of kind "${o}", got "${r}"`),this.code="E_VALIDATION",this.retryable=!1}}async function ge(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 o=t.at??D(),r={...ls(n.meta)??{},invalidatedAt:o,...t.reason!==void 0?{invalidatedReason:t.reason}:{}};await e.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[o,JSON.stringify(r),n.rowid])}const yt=[250,500];function cu(e){return new Promise(t=>setTimeout(t,e))}const du=["immediate","deferred"];function lu(){const e=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(e===void 0)return"immediate";if(du.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 V(e,t){let n=0;for(;;)try{return await e.adapter.transaction(t,{mode:lu()})}catch(o){if(o instanceof U)throw o;const r=tu(o);if(r.code==="E_CONTENTION"){if(n<yt.length){const i=yt[n];n+=1,await cu(i);continue}throw new Xi(yt[yt.length-1],o)}throw r.code==="E_IO"&&r.retryable?new Qi(o):o}}function Y(e){return e.normalize("NFKC").toLowerCase()}function uu(){return new Set([...Ht].map(e=>Y(e)))}function go(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}async function fu(e,t=D()){const{rows:n}=await e.adapter.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind = 'status' AND t_invalid IS NULL ORDER BY rowid ASC"),o=[],r=uu();for(const i of n){const s=Y(i.name??"");if(!r.has(s))continue;const a=go(i.meta);(a==null?void 0:a.terminal)!==!0&&o.push(i.rowid)}return{setTerminalRowids:o,at:t}}async function pu(e,t){return V(e,async n=>{const o=[];for(const r of t.setTerminalRowids){const i=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[r]);if(!i)continue;if(i.kind!=="status")throw new Error(`applyTerminalBackfill: planned rowid ${r} is not a status row (kind="${i.kind}") — plan/DB mismatch, refusing to rewrite it.`);const s=go(i.meta)??{},a=s.terminal===!0;if(a)continue;const c={...s,terminal:!0},d=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(c),r]);if(d.rowsAffected!==1)throw new Error(`applyTerminalBackfill: UPDATE affected ${d.rowsAffected} rows for rowid=${r}, expected exactly 1.`);o.push({rowid:i.rowid,uid:i.uid,hadTerminal:a})}return{entries:o,at:D()}})}async function mu(e,t){await V(e,async n=>{for(const o of t.entries){const r=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[o.rowid]);if(!r)continue;if(r.kind!=="status")throw new Error(`reverseTerminalBackfill: journal rowid ${o.rowid} is not a status row (kind="${r.kind}") — refusing to rewrite it.`);const s={...go(r.meta)??{},terminal:o.hadTerminal},a=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(s),o.rowid]);if(a.rowsAffected!==1)throw new Error(`reverseTerminalBackfill: UPDATE affected ${a.rowsAffected} rows for rowid=${o.rowid}, expected exactly 1.`)}})}function ho(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}async function it(e,t,n){const o=await mo(e,n,{expectedKind:t}),{name:r}=o;if(r===null)throw new W(t,n);return{...o,name:r}}async function Ze(e,t){if(pe(t)){const r=await it(e,"project",t);return{rowid:r.rowid,uid:r.uid,name:r.name,metadata:r.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 W("project",t);let o;if(n.meta!==null)try{o=JSON.parse(n.meta)}catch{o=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??t,metadata:o}}async function yo(e,t){var o;if(pe(t.ref)){const r=await it(e,"component",t.ref);if(((o=r.metadata)==null?void 0:o.projectUid)!==t.projectUid)throw new W("component",t.ref);return{rowid:r.rowid,uid:r.uid,name:r.name}}const n=await e.executeGet(`SELECT rowid, uid, name FROM node
21
+ t_invalid = NULL, t_valid = excluded.t_valid`,[e.srcRowid,e.dstRowid,e.rel,e.weight??1,o,i,i])}class $r extends C{constructor(e,n,i,o){super(`"${e}" requires a ${n} of kind "${i}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function ie(t,e){const n=await t.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e.srcRowid,e.dstRowid,e.rel]);if(!n)return;const i=e.at??P(),o={...wi(n.meta)??{},invalidatedAt:i,...e.reason!==void 0?{invalidatedReason:e.reason}:{}};await t.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[i,JSON.stringify(o),n.rowid])}async function $o(t,e,n,i){const o=await t.executeGet("SELECT rowid, meta FROM node WHERE uid = ?",[e]);if(!o)return null;const r=wi(o.meta)??{};if((typeof r.revision=="number"&&Number.isFinite(r.revision)?r.revision:0)!==i)return null;const a=i+1,c={...r,...n,revision:a};return(await t.executeRun(`UPDATE node SET meta = ?, t_updated = ?
22
+ WHERE uid = ? AND COALESCE(json_extract(meta, '$.revision'), 0) = ?`,[JSON.stringify(c),P(),e,i])).rowsAffected===1?a:null}const en=[250,500];function Up(t){return new Promise(e=>setTimeout(e,t))}const Dp=["immediate","deferred"];function Mp(){const t=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(t===void 0)return"immediate";if(Dp.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${t}" 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 M(t,e){let n=0;for(;;)try{return await t.adapter.transaction(e,{mode:Mp()})}catch(i){if(i instanceof C)throw i;const o=Tp(i);if(o.code==="E_CONTENTION"){if(n<en.length){const r=en[n];n+=1,await Up(r);continue}throw new $a(en[en.length-1],i)}throw o.code==="E_IO"&&o.retryable?new Ca(i):i}}function F(t){return t.normalize("NFKC").toLowerCase()}function xp(){return new Set([...xt].map(t=>F(t)))}function bi(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Fp(t,e=P()){const{rows:n}=await t.adapter.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind = 'status' AND t_invalid IS NULL ORDER BY rowid ASC"),i=[],o=xp();for(const r of n){const s=F(r.name??"");if(!o.has(s))continue;const a=bi(r.meta);(a==null?void 0:a.terminal)!==!0&&i.push(r.rowid)}return{setTerminalRowids:i,at:e}}async function Bp(t,e){return M(t,async n=>{const i=[];for(const o of e.setTerminalRowids){const r=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[o]);if(!r)continue;if(r.kind!=="status")throw new Error(`applyTerminalBackfill: planned rowid ${o} is not a status row (kind="${r.kind}") — plan/DB mismatch, refusing to rewrite it.`);const s=bi(r.meta)??{},a=s.terminal===!0;if(a)continue;const c={...s,terminal:!0},d=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(c),o]);if(d.rowsAffected!==1)throw new Error(`applyTerminalBackfill: UPDATE affected ${d.rowsAffected} rows for rowid=${o}, expected exactly 1.`);i.push({rowid:r.rowid,uid:r.uid,hadTerminal:a})}return{entries:i,at:P()}})}async function Kp(t,e){await M(t,async n=>{for(const i of e.entries){const o=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[i.rowid]);if(!o)continue;if(o.kind!=="status")throw new Error(`reverseTerminalBackfill: journal rowid ${i.rowid} is not a status row (kind="${o.kind}") — refusing to rewrite it.`);const s={...bi(o.meta)??{},terminal:i.hadTerminal},a=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(s),i.rowid]);if(a.rowsAffected!==1)throw new Error(`reverseTerminalBackfill: UPDATE affected ${a.rowsAffected} rows for rowid=${i.rowid}, expected exactly 1.`)}})}function Me(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Mt(t,e,n){const i=await se(t,n,{expectedKind:e}),{name:o}=i;if(o===null)throw new V(e,n);return{...i,name:o}}async function at(t,e){if(pe(e)){const o=await Mt(t,"project",e);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[e]);if(!n)throw new V("project",e);let i;if(n.meta!==null)try{i=JSON.parse(n.meta)}catch{i=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??e,metadata:i}}async function Ei(t,e){var i;if(pe(e.ref)){const o=await Mt(t,"component",e.ref);if(((i=o.metadata)==null?void 0:i.projectUid)!==e.projectUid)throw new V("component",e.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await t.executeGet(`SELECT rowid, uid, name FROM node
22
23
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
23
24
  AND json_extract(meta, '$.projectUid') = ?
24
- LIMIT 1`,[t.ref,t.projectUid]);if(!n)throw new W("component",t.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??t.ref}}async function ps(e,t){const n=await e.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
25
+ LIMIT 1`,[e.ref,e.projectUid]);if(!n)throw new V("component",e.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref}}async function Wa(t,e){const n=await t.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
25
26
  FROM edge e JOIN node c ON c.rowid = e.dst
26
27
  WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
27
28
  AND c.name = '(root)' AND c.t_invalid IS NULL
28
- LIMIT 1`,[t.projectRowid]);if(!n)throw new W("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}const Ht=new Set(["closed","DONE","FIXED","RESOLVED","INVALID","SUPERSEDED"]),gu=new Set([...Ht].map(e=>Y(e)));function hu(e){return gu.has(Y(e))}async function yu(e,t,n){const o=Y(n),{rows:r}=await e.executeAll("SELECT uid, name FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[t]);for(const i of r)if(!(i.name===null||i.name===n)&&Y(i.name)===o)return{uid:i.uid,name:i.name}}async function je(e,t){if(pe(t.ref)){const s=await it(e,t.catalogKind,t.ref);return{rowid:s.rowid,uid:s.uid,name:s.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 o=await yu(e,t.catalogKind,t.ref);if(o)throw new Zl(t.catalogKind,o.name,t.ref);const r=t.mintMetadata?await t.mintMetadata(e):{},i=await J(e,{kind:t.catalogKind,name:t.ref,metadata:r,at:t.at});return{rowid:i.rowid,uid:i.uid,name:t.ref}}async function ms(e,t){return je(e,{catalogKind:"status",ref:t.ref,at:t.at,mintMetadata:async()=>({terminal:hu(t.ref)})})}async function gs(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 wu=[{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"}],Er=new Map(wu.map(e=>[e.rel,e]));async function L(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 r=ho(n.meta)??{},i=typeof r.source_kind=="string"?r.source_kind:void 0,s=typeof r.target_kind=="string"?r.target_kind:void 0,a=r.multiplicity;if(i&&s&&a)return{rel:t,sourceKind:i,targetKind:s,multiplicity:a};const c=Er.get(t);if(!c)throw new W("edge_kind",t);return await e.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[D(),n.rowid]),await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const o=Er.get(t);if(!o)throw new W("edge_kind",t);return await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:o.sourceKind,target_kind:o.targetKind,multiplicity:o.multiplicity}}),o}const ne=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,citationAllowedExternalRoots:Object.freeze([]),dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[]});function se(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}function Fe(e){var o;const t=(o=e.metadata)==null?void 0:o.policy;if(t===null||typeof t!="object")return{...ne,citationAllowedExternalRoots:On()};const n=t;return{transitionRequiresNote:n.transitionRequiresNote??ne.transitionRequiresNote,citationRequired:n.citationRequired??ne.citationRequired,citationRequiresSha:n.citationRequiresSha??ne.citationRequiresSha,citationAllowedExternalRoots:vu(n),defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??ne.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??ne.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??ne.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??ne.allowedStatuses,allowedKinds:n.allowedKinds??ne.allowedKinds,requiredFields:n.requiredFields??ne.requiredFields}}function vu(e){const t=e.citationAllowedExternalRoots;return t===void 0||!Array.isArray(t)||!t.every(n=>typeof n=="string")?On():t}function Vt(e){var n;const t=(n=e.metadata)==null?void 0:n.path;return typeof t=="string"&&t.length>0}function Tt(e,t){const n={...e};for(const[o,r]of Object.entries(t))r!==void 0&&(n[o]=r);return n}async function bu(e,t){return se("name",t.name),se("by",t.by),Z("by",t.by),V(e,n=>Su(n,e,t))}async function Su(e,t,n){const o=D(),r=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(r){const l=Tt(ho(r.meta)??{},i);return await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),r.rowid]),await B({tx:e,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"project",actor:n.by,action:"updated",at:o}),{uid:r.uid,created:!1,project:{uid:r.uid,name:r.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const s=Tt({},i),a=await J(e,{kind:"project",name:n.name,metadata:s,at:o}),c=await J(e,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:o}),d=await L(e,"owns_project");return await x(e,{at:o,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 B({tx:e,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:o}),{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 Eu(e,t){return se("project",t.project),se("name",t.name),se("by",t.by),Z("by",t.by),V(e,n=>ku(n,e,t))}async function ku(e,t,n){const o=D(),r=await Ze(e,n.project),i=await e.executeGet(`SELECT rowid, uid, name, meta FROM node
29
+ LIMIT 1`,[e.projectRowid]);if(!n)throw new V("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}const xt=new Set(["closed","DONE","FIXED","RESOLVED","INVALID","SUPERSEDED"]),qp=new Set([...xt].map(t=>F(t)));function Hp(t){return qp.has(F(t))}const Ja=new Set(["EPIC"]),za=new Map([["EPIC","FEAT"]]),Vp=new Set([...Ja].map(t=>F(t))),Gp=new Map([...za].map(([t,e])=>[F(t),e]));function Wp(t){return Vp.has(F(t))}function Jp(t){return Gp.get(F(t))}async function zp(t,e,n){const i=F(n),{rows:o}=await t.executeAll("SELECT uid, name FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[e]);for(const r of o)if(!(r.name===null||r.name===n)&&F(r.name)===i)return{uid:r.uid,name:r.name}}async function Yp(t,e,n){const i=F(n),{rows:o}=await t.executeAll("SELECT rowid, uid, name, meta FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[e]);for(const r of o)if(r.name!==null&&F(r.name)===i)return{rowid:r.rowid,uid:r.uid,name:r.name,metadata:Me(r.meta)}}function tn(t,e,n,i){if(t!=="kind"||i===!0||!((n==null?void 0:n.lifecycle)==="deprecated")&&!Wp(e))return;const r=(typeof(n==null?void 0:n.replacedBy)=="string"?n.replacedBy:void 0)??Jp(e);throw new T("kind",`"${e}" is a deprecated kind${r?` — use "${r}" instead`:""}. Pass allowDeprecated:true only for a reviewed repair that must still write it.`)}async function xe(t,e){if(pe(e.ref)){const r=await Mt(t,e.catalogKind,e.ref);return tn(e.catalogKind,r.name,r.metadata,e.allowDeprecated),{rowid:r.rowid,uid:r.uid,name:r.name}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[e.catalogKind,e.ref]);if(n){const r=n.name??e.ref;return tn(e.catalogKind,r,Me(n.meta),e.allowDeprecated),{rowid:n.rowid,uid:n.uid,name:r}}if(e.catalogKind==="kind"){const r=await Yp(t,e.catalogKind,e.ref);if(r)return tn(e.catalogKind,r.name,r.metadata,e.allowDeprecated),{rowid:r.rowid,uid:r.uid,name:r.name}}else{const r=await zp(t,e.catalogKind,e.ref);if(r)throw new Np(e.catalogKind,r.name,e.ref)}tn(e.catalogKind,e.ref,void 0,e.allowDeprecated);const i=e.mintMetadata?await e.mintMetadata(t):{},o=await X(t,{kind:e.catalogKind,name:e.ref,metadata:i,at:e.at});return{rowid:o.rowid,uid:o.uid,name:e.ref}}async function Ya(t,e){return xe(t,{catalogKind:"status",ref:e.ref,at:e.at,mintMetadata:async()=>({terminal:Hp(e.ref)})})}async function Xa(t){const e=await t.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(e==null?void 0:e.maxRank)??null;return n===null?0:n+1}const Qa=[{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"},{rel:"attests",sourceKind:"*",targetKind:"attestation",multiplicity:"1:n"},{rel:"has_obligation",sourceKind:"issue",targetKind:"obligation",multiplicity:"1:n"},{rel:"satisfies",sourceKind:"obligation",targetKind:"attestation",multiplicity:"n:m"},{rel:"similar_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"}],Cr=new Map(Qa.map(t=>[t.rel,t]));async function q(t,e){const n=await t.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[e]);if(n){const o=Me(n.meta)??{},r=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(r&&s&&a)return{rel:e,sourceKind:r,targetKind:s,multiplicity:a};const c=Cr.get(e);if(!c)throw new V("edge_kind",e);return await t.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[P(),n.rowid]),await X(t,{kind:"edge_kind",name:e,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const i=Cr.get(e);if(!i)throw new V("edge_kind",e);return await X(t,{kind:"edge_kind",name:e,metadata:{source_kind:i.sourceKind,target_kind:i.targetKind,multiplicity:i.multiplicity}}),i}const ee=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,citationAllowedExternalRoots:Object.freeze([]),dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[],similarityScope:"same-project",similarityCrossProjectThreshold:.92,similarityCrossProjectMargin:.05,similarityCrossProjectTokenOverlap:.5});function de(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}function Se(t){var i;const e=(i=t.metadata)==null?void 0:i.policy;if(e===null||typeof e!="object")return{...ee,citationAllowedExternalRoots:Ao()};const n=e;return{transitionRequiresNote:n.transitionRequiresNote??ee.transitionRequiresNote,citationRequired:n.citationRequired??ee.citationRequired,citationRequiresSha:n.citationRequiresSha??ee.citationRequiresSha,citationAllowedExternalRoots:Xp(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,similarityScope:n.similarityScope??ee.similarityScope,similarityCrossProjectThreshold:n.similarityCrossProjectThreshold??ee.similarityCrossProjectThreshold,similarityCrossProjectMargin:n.similarityCrossProjectMargin??ee.similarityCrossProjectMargin,similarityCrossProjectTokenOverlap:n.similarityCrossProjectTokenOverlap??ee.similarityCrossProjectTokenOverlap}}function Xp(t){const e=t.citationAllowedExternalRoots;return e===void 0||!Array.isArray(e)||!e.every(n=>typeof n=="string")?Ao():e}function Za(t){var n;const e=(n=t.metadata)==null?void 0:n.path;return typeof e=="string"&&e.length>0}function kt(t,e){const n={...t};for(const[i,o]of Object.entries(e))o!==void 0&&(n[i]=o);return n}async function Qp(t,e){return de("name",e.name),de("by",e.by),G("by",e.by),M(t,n=>Zp(n,t,e))}async function Zp(t,e,n){const i=P(),o=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),r={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=kt(Me(o.meta)??{},r);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:i}),{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}}}if(n.repoUrl!==void 0&&n.repoUrl.trim().length>0){const{rows:l}=await t.executeAll("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND t_invalid IS NULL ORDER BY rowid ASC"),u=l.find(f=>{var m;return((m=Me(f.meta))==null?void 0:m.repoUrl)===n.repoUrl});if(u){const f=kt(Me(u.meta)??{},r);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(f),u.rowid]),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:u.rowid,subjectUid:u.uid,subjectKind:"project",actor:n.by,action:"updated",note:"repo-url-dedupe",at:i}),{uid:u.uid,created:!1,project:{uid:u.uid,name:u.name??n.name,path:f.path,repoUrl:f.repoUrl,monorepo:f.monorepo,description:f.description}}}}const s=kt({},r),a=await X(t,{kind:"project",name:n.name,metadata:s,at:i}),c=await X(t,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:i}),d=await q(t,"owns_project");return await K(t,{at:i,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:d,typePolicy:e.typePolicy}),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:i}),{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 em(t,e){return de("project",e.project),de("name",e.name),de("by",e.by),G("by",e.by),M(t,n=>tm(n,t,e))}async function tm(t,e,n){const i=P(),o=await at(t,n.project),r=await t.executeGet(`SELECT rowid, uid, name, meta FROM node
29
30
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
30
31
  AND json_extract(meta, '$.projectUid') = ?
31
- LIMIT 1`,[n.name,r.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(i)u=Tt({...ho(i.meta)??{},projectUid:r.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=Tt({projectUid:r.uid},s);const m=await J(e,{kind:"component",name:n.name,metadata:u,at:o});a=m.rowid,c=m.uid,d=n.name,l=!0}const f=await L(e,"owns_project");return await x(e,{at:o,srcRowid:r.rowid,srcUid:r.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:t.typePolicy}),await B({tx:e,typePolicy:t.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:o}),{uid:c,created:l,component:{uid:c,name:d,projectUid:r.uid,path:u.path,description:u.description}}}const kr=["path","url","tool"];async function Au(e,t){if(se("component",t.component),se("value",t.value),se("by",t.by),Z("by",t.by),!kr.includes(t.locType))throw new T("locType",`must be one of ${kr.join(", ")}`);return V(e,async n=>{const o=D();let r;if(pe(t.component)){const d=await it(n,"component",t.component);r={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(t.project===void 0||t.project.trim().length===0)throw new T("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await Ze(n,t.project);r=await yo(n,{projectUid:d.uid,ref:t.component})}const i=await n.executeGet(`SELECT rowid, uid FROM node
32
+ LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(r)u=kt({...Me(r.meta)??{},projectUid:o.uid},s),await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(u),r.rowid]),a=r.rowid,c=r.uid,d=r.name??n.name,l=!1;else{u=kt({projectUid:o.uid},s);const m=await X(t,{kind:"component",name:n.name,metadata:u,at:i});a=m.rowid,c=m.uid,d=n.name,l=!0}const f=await q(t,"owns_project");return await K(t,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:e.typePolicy}),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:i}),{uid:c,created:l,component:{uid:c,name:d,projectUid:o.uid,path:u.path,description:u.description}}}const Co=["path","url","tool"];async function nm(t,e){if(de("component",e.component),de("value",e.value),de("by",e.by),G("by",e.by),!Co.includes(e.locType))throw new T("locType",`must be one of ${Co.join(", ")}`);return M(t,async n=>{const i=P();let o;if(pe(e.component)){const d=await Mt(n,"component",e.component);o={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(e.project===void 0||e.project.trim().length===0)throw new T("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await at(n,e.project);o=await Ei(n,{projectUid:d.uid,ref:e.component})}const r=await n.executeGet(`SELECT rowid, uid FROM node
32
33
  WHERE kind = 'location' AND t_invalid IS NULL
33
34
  AND json_extract(meta, '$.componentUid') = ?
34
35
  AND json_extract(meta, '$.locType') = ?
35
36
  AND json_extract(meta, '$.value') = ?
36
- LIMIT 1`,[r.uid,t.locType,t.value]);if(i)return{uid:i.uid,created:!1,location:{uid:i.uid,locType:t.locType,value:t.value,componentUid:r.uid}};const s={componentUid:r.uid,locType:t.locType,value:t.value},a=await J(n,{kind:"location",name:t.value,metadata:s,at:o}),c=await L(n,"has_location");return await x(n,{at:o,srcRowid:r.rowid,srcUid:r.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:e.typePolicy}),await B({tx:n,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:t.by,action:"created",at:o}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:t.locType,value:t.value,componentUid:r.uid}}})}async function _u(e,t){return se("uid",t.uid),se("by",t.by),Z("by",t.by),V(e,async n=>{var c;const o=D(),r=await it(n,"location",t.uid),i={...r.metadata??{},...t.reason!==void 0?{invalidatedReason:t.reason}:{},invalidatedAt:o},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[o,JSON.stringify(i),r.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=r.metadata)==null?void 0:c.componentUid)=="string"?r.metadata.componentUid:void 0;if(a!==void 0){const d=await Pn(n,a);(d==null?void 0:d.tInvalid)===null&&await ge(n,{srcRowid:d.rowid,dstRowid:r.rowid,rel:"has_location",reason:t.reason,at:o})}return await B({tx:n,typePolicy:e.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"location",actor:t.by,action:"deleted",note:t.reason,at:o}),{uid:r.uid,invalidated:!0}})}async function B(e){const t=e.at??D(),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},o=po(fs(n)),r={...n,sha:o},i=await J(e.tx,{at:t,kind:"audit",name:e.action,content:e.note??e.action,metadata:r}),s=await L(e.tx,"audits");return await x(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:o}}const ju="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function wo(e,t){return`${e}
37
- ${t}`.trim()}function It(e,t){const n=e.embedding;if(!n)return Promise.resolve();const o=Nu(e,n,t),r={subjectRowid:t.subjectRowid,subjectUid:t.subjectUid,actor:t.actor,action:t.action,settled:o,outcome:"pending"},i=zi(e.adapter).register(r);return o.then(s=>{r.outcome=s,s!=="unrecorded"&&i()},()=>{r.outcome="unrecorded"}),o.then(()=>{})}async function Nu(e,t,n){let o,r;try{if(n.action==="upsert"){const i=await t.embedDocument(n.content);await t.upsertVector(n.subjectRowid,i),o="embedding_upserted"}else await t.deleteVector(n.subjectRowid),o="embedding_deleted"}catch(i){o="embedding_failed",r=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 V(e,async i=>{await B({tx:i,typePolicy:e.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:o,note:r})})}catch(i){return console.error(`scheduleIssueEmbedding: failed to persist "${o}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,i),"unrecorded"}switch(o){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function Ru(e,t){const n=[],o=[];for(const r of t)try{await V(e,async i=>{await B({tx:i,typePolicy:e.typePolicy,subjectRowid:r.subjectRowid,subjectUid:r.subjectUid,subjectKind:"issue",actor:r.actor,action:"embedding_failed",note:ju})}),r.outcome="failed",n.push(r)}catch(i){r.outcome="unrecorded",o.push(r),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${r.subjectUid}" — this embed outcome is UNRECORDED.`,i)}return{recorded:n,unrecorded:o}}async function $t(e,t=5e3){if(e!==":memory:"&&R.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 he.createStoreAdapter({dbPath:e});await n.pragmaSet("busy_timeout",t);const o=Xa.createGraphBackend(n,{typePolicy:vr});await Vl(()=>o.applySchema());try{await co(n)}catch(i){throw await n.close().catch(()=>{}),i}return{adapter:n,graph:o,typePolicy:vr,flushEmbeds:i=>zi(n).drain(i)}}async function hs(e,t){const n=await e.flushEmbeds(t);let o=0,r=[...n.unrecorded];try{if(n.stillPending.length>0){const i=await Ru(e,n.stillPending);o=i.recorded.length,r=[...r,...i.unrecorded]}}finally{await e.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:o,unrecorded:r}}async function xn(e){if(!e)return;let t;try{t=await hs(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 Ln=["SIGINT","SIGTERM"];function ys(e,t=n=>process.exit(n)){let n=!1;const o=i=>{n||(n=!0,e().catch(s=>{console.error(`backlog: signal cleanup failed (${i}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{r(),t(128+z.constants.signals[i])}))},r=()=>{for(const i of Ln)process.removeListener(i,o)};for(const i of Ln)process.on(i,o);return{dispose:r}}function Ou(){return Ln.some(e=>process.listenerCount(e)>0)}const Tu=[".git",".adhd","adhd.environment.yaml"];function sn(e){let t=k.resolve(e);const{root:n}=k.parse(t);for(;;){for(const r of Tu)if(R.existsSync(`${t}/${r}`))return t;if(t===n)return;const o=k.dirname(t);if(o===t)return;t=o}}const Iu=new Set(["system","global","project"]);function $u(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:sn(n)??n}:{scope:e.scope};const o=t.ADHD_ENV_SCOPE;if(o!==void 0&&Iu.has(o)){const i=o;return i==="project"?{scope:"project",projectRoot:sn(n)??n}:{scope:i}}const r=sn(n);return r?{scope:"project",projectRoot:r}:{scope:"global"}}function Ar(e){return`.${e}`}function Cu(e){const t=z.homedir();if(process.platform==="darwin")return k.join(t,"Library","Application Support",e);if(process.platform==="win32"){const o=process.env.APPDATA??k.join(t,"AppData","Roaming");return k.join(o,e)}const n=process.env.XDG_DATA_HOME??k.join(t,".local","share");return k.join(n,e)}function Pu(e){const t=e.orgNamespace,n=e.adhdRoot??k.join(z.homedir(),Ar(t)),o=e.adhdRoot??Cu(t),r={system:k.join(o,e.project,e.namespace),global:k.join(n,e.project,e.namespace)};return e.projectRoot&&(r.project=k.join(e.projectRoot,Ar(t),e.project,e.namespace)),r}function ws(e,t){return t==="project"?e.project??e.global:e[t]}const xu="1.0.0-redesign.1",Lu="adhd",Uu="default",Du="adhd-environment.json",Pe="config.yaml",vs="config.local.yaml",Mu={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class _r 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 jr(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const o=t+1<e.length?e.charCodeAt(t+1):0;if(o<56320||o>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function bs(e,t){const n=Array.from(e),o=Array.from(t),r=Math.min(n.length,o.length);for(let i=0;i<r;i++){const s=n[i].codePointAt(0)??0,a=o[i].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===o.length?0:n.length<o.length?-1:1}function Nr(e){return new TextEncoder().encode(e).length}function Fu(e){const t=Object.keys(e).sort(bs);let n="";for(const r of t){const i=e[r];if(jr(r))throw new _r("key",r);if(jr(i))throw new _r("value",i);n+=`${Nr(r)}:${r}=${Nr(i)}:${i}
38
- `}return`sha256-${Ss(n)}`}function Bu(e){const n=[...e].sort((o,r)=>bs(o.name,r.name)).map(o=>`${o.name}:${o.kind}:${o.scope}`).join(`
39
- `);return`sha256-${Ss(n)}`}function Ku(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function qu(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Hu(e){const t={type:"object",properties:{}},n=e;for(const o of Object.keys(n)){const r=n[o],i=o.split(".");let s=t;i.forEach((a,c)=>{if(c===i.length-1){s.properties[a]=Vu(r);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 Vu(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 Gu="adhd-env-ref:";function Wu(e){return`${Gu}${e}`}const Ju=[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],zu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function oe(e,t){return(e>>>t|e<<32-t)>>>0}function Yu(e){const t=Uint32Array.from(zu),n=e.length*8;let o=e.length+1;for(;o%64!==56;)o++;o+=8;const r=new Uint8Array(o);r.set(e),r[e.length]=128;const i=Math.floor(n/4294967296),s=n>>>0,a=new DataView(r.buffer);a.setUint32(o-8,i,!1),a.setUint32(o-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<o;u+=64){for(let v=0;v<16;v++)c[v]=a.getUint32(u+v*4,!1);for(let v=16;v<64;v++){const S=c[v-15],E=c[v-2],A=oe(S,7)^oe(S,18)^S>>>3,_=oe(E,17)^oe(E,19)^E>>>10;c[v]=c[v-16]+A+c[v-7]+_>>>0}let f=t[0],m=t[1],p=t[2],g=t[3],b=t[4],h=t[5],y=t[6],w=t[7];for(let v=0;v<64;v++){const S=oe(b,6)^oe(b,11)^oe(b,25),E=b&h^~b&y,A=w+S+E+Ju[v]+c[v]>>>0,_=oe(f,2)^oe(f,13)^oe(f,22),N=f&m^f&p^m&p,j=_+N>>>0;w=y,y=h,h=b,b=g+A>>>0,g=p,p=m,m=f,f=A+j>>>0}t[0]=t[0]+f>>>0,t[1]=t[1]+m>>>0,t[2]=t[2]+p>>>0,t[3]=t[3]+g>>>0,t[4]=t[4]+b>>>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 Xu(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Ss(e){const t=new TextEncoder().encode(e);return Xu(Yu(t))}const{parse:Qu}=rc;function Es(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[o,r]of Object.entries(e)){const i=t?`${t}.${o}`:o;r!==null&&typeof r=="object"&&!Array.isArray(r)?Object.assign(n,Es(r,i)):n[i]=r}return n}function wt(e){if(R.existsSync(e))try{const t=R.readFileSync(e,"utf8"),n=Qu(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Es(n)}catch{return}}function Zu(e){return{system:wt(k.join(e.system,Pe)),global:wt(k.join(e.global,Pe)),project:e.project?wt(k.join(e.project,Pe)):void 0,local:e.project?wt(k.join(e.project,vs)):void 0}}function Rr(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function Un(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 ks(e){const t={};for(const n of Object.keys(e)){const o=n.split(".");let r=t;o.forEach((i,s)=>{if(s===o.length-1){r[i]=e[n];return}const a=r[i];(typeof a!="object"||a===null||Array.isArray(a))&&(r[i]={}),r=r[i]})}return t}const ef=[["system","system"],["global","global"],["project","project"],["local","local"]];function tf(e,t,n,o){const r={},i={},s={},a={};for(const c of Object.keys(e)){const d=e[c],l=d.env&&d.env!==""?d.env:qu(o.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??o.activeScope;let m=d.default,p="default";for(const[w,v]of ef){const S=t[w];S&&Object.prototype.hasOwnProperty.call(S,c)&&(m=Un(S[c],d.type),p=v)}const g=n[l];let b,h,y;g!==void 0?(b=Un(g,d.type),h="env",y=l):(b=m,h=p),r[c]=u?Wu(l):b,i[c]=b,s[c]=Rr(u?{source:"env",scope:f,env:l}:{source:h,scope:f,env:y}),a[c]={...d,env:l,live:u,fallbackValue:m}}return{raw:r,nested:ks(r),typedRaw:i,provenance:s,fields:a}}function nf(e,t){return e.replace(/\$\{HOME\}/g,z.homedir()).replace(/\$HOME\b/g,z.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function of(e,t){const n={};for(const[o,r]of Object.entries(e??{})){const i=r.scope??t.activeScope,s=r.share??Mu[r.kind],a=r.path?nf(r.path,t):k.join(ws(t.roots,i),o),c=s==="per-instance"?k.join(a,t.instanceId):a;n[o]={name:o,kind:r.kind,path:c,scope:i,share:s}}return n}function rf(e,t){const n={};for(const[o,r]of Object.entries(e??{})){const i=t[r.in];if(!i)throw new Error(`files.${o}.in references unknown dirs key "${r.in}"`);n[o]={name:o,in:r.in,path:k.join(i.path,r.name),share:r.share??"shared"}}return n}class As 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 sf(e,t){if(!t)return;const n=t,o=n.properties;if(o!==void 0&&Object.keys(o).length===0)return;const i=new ui({allErrors:!0,strict:!1}).compile(n);if(!i(e))throw new As(af(i.errors??[]))}function af(e){return e.map(t=>({field:cf(t),message:t.message??"is invalid",keyword:t.keyword}))}function cf(e){var o;const t=(e.instancePath??"").replace(/^\//,"").replace(/\//g,".");return t||(((o=e.params)==null?void 0:o.missingProperty)??"(root)")}function df(e,t){return k.join(ws(e,t),Du)}const lf=384,uf=448;function ff(e,t,n={}){const o=n.mode??lf,r=n.dirMode??uf,i=k.dirname(e);R.mkdirSync(i,{recursive:!0,mode:r}),R.chmodSync(i,r);const s=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{R.writeFileSync(s,a,{encoding:"utf8",mode:o}),R.chmodSync(s,o),R.renameSync(s,e),R.chmodSync(e,o)}catch(c){try{R.existsSync(s)&&R.unlinkSync(s)}catch{}throw c}}const pf="0.1.0";function Or(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 mf(){return`${process.pid}-${me.randomBytes(3).toString("hex")}`}function vo(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Or(e,"project");const o=t.orgNamespace??Lu,r=t.envPrefixOverride??Ku(e),i=t.namespaces&&t.namespaces.length>0?t.namespaces:[Uu],s=n.namespace??i[0];if(!i.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${e}" (declared: ${i.join(", ")})`);Or(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=$u({scope:n.scope,cwd:n.cwd},a),l=Pu({project:e,namespace:s,orgNamespace:o,projectRoot:d,adhdRoot:n.adhdRoot});return{project:e,namespace:s,orgNamespace:o,envPrefix:r,scope:c,projectRoot:d,roots:l}}function gf(e,t,n={}){const{namespace:o,orgNamespace:r,envPrefix:i,scope:s,projectRoot:a,roots:c}=vo(e,t,n),d=n.processEnv??process.env,l=Zu(c),u=n.instanceId??mf(),{raw:f,nested:m,typedRaw:p,provenance:g,fields:b}=tf(t.config,l,d,{prefix:i,activeScope:s}),h={};for(const E of Object.keys(b)){const A=b[E];A.live&&(h[E]={env:A.env,type:A.type,fallback:A.secret===!0?void 0:A.fallbackValue})}const y=Hu(t.config);sf(ks(p),y);const w=of(t.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:o}),v=rf(t.files,w);return{version:xu,libraryVersion:pf,generatedAt:new Date().toISOString(),project:e,namespace:o,orgNamespace:r,envPrefix:i,scope:s,instanceId:u,config:m,raw:f,liveFields:h,fieldSchema:y,configHash:Fu(Object.fromEntries(Object.entries(p).map(([E,A])=>[E,String(A)]))),structureHash:Bu(Object.values(w).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(w),files:Object.values(v),provenance:g}}class et extends Error{constructor(t){super(t),this.name="EnvironmentError"}}class hf extends et{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class yf extends et{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function wf(e,t){let n=e;for(const o of t.split("."))if(n!==null&&typeof n=="object"&&o in n)n=n[o];else return;return n}function Dn(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Dn(n));const t={};for(const[n,o]of Object.entries(e))t[n]=Dn(o);return t}function vf(e,t){const n=Dn(e);for(const o of Object.keys(t)){const r=t[o],i=o.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[r.env];return c!==void 0?Un(c,r.type):r.fallback}})}return n}function bf(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new et(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class Gt{constructor(t,n,o={}){let r,i;try{r=gf(t,n,o);const s=vo(t,n,o);i=df(s.roots,r.scope)}catch(s){throw s instanceof As||s instanceof et?s:new et(s instanceof Error?s.message:String(s))}return Tr(this,r,i)}static fromSnapshot(t){if(!R.existsSync(t))throw new hf(t);const n=JSON.parse(R.readFileSync(t,"utf8")),o=Object.create(Gt.prototype);return Tr(o,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const o=t.slice(0,n),r=t.slice(n+1);switch(o){case"config":return wf(this.config,r);case"path":return this.paths[r];case"env":return this.resolveEnvName(r);case"provenance":return this._data.provenance[r];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){bf(t);const n=this.paths.run??this._runDirFallback();R.mkdirSync(n,{recursive:!0});const o=k.join(n,`${t}.lock`);let r;try{r=R.openSync(o,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new yf(t,o):s}R.writeSync(r,`${process.pid}
37
+ LIMIT 1`,[o.uid,e.locType,e.value]);if(r)return{uid:r.uid,created:!1,location:{uid:r.uid,locType:e.locType,value:e.value,componentUid:o.uid}};const s={componentUid:o.uid,locType:e.locType,value:e.value},a=await X(n,{kind:"location",name:e.value,metadata:s,at:i}),c=await q(n,"has_location");return await K(n,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:t.typePolicy}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:e.by,action:"created",at:i}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:e.locType,value:e.value,componentUid:o.uid}}})}async function om(t,e){return de("uid",e.uid),de("by",e.by),G("by",e.by),M(t,async n=>{var c;const i=P(),o=await Mt(n,"location",e.uid),r={...o.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:i},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[i,JSON.stringify(r),o.rowid]);if(s.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${s.rowsAffected} rows for uid="${e.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 Be(n,a);(d==null?void 0:d.tInvalid)===null&&await ie(n,{srcRowid:d.rowid,dstRowid:o.rowid,rel:"has_location",reason:e.reason,at:i})}return await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:e.by,action:"deleted",note:e.reason,at:i}),{uid:o.uid,invalidated:!0}})}async function U(t){const e=t.at??P(),n={actor:t.actor,action:t.action,target_uid:t.subjectUid,from:t.from??null,to:t.to??null,note:t.note??null,at:e},i=He(vi(n)),o={...n,sha:i},r=await X(t.tx,{at:e,kind:"audit",name:t.action,content:t.note??t.action,metadata:o}),s=await q(t.tx,"audits");return await K(t.tx,{at:e,srcRowid:t.subjectRowid,srcUid:t.subjectUid,srcKind:t.subjectKind,dstRowid:r.rowid,dstUid:r.uid,dstKind:"audit",rel:"audits",rule:s,typePolicy:t.typePolicy}),{rowid:r.rowid,uid:r.uid,sha:i}}const im="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function Si(t,e){return`${t}
38
+ ${e}`.trim()}function hn(t,e){const n=t.embedding;if(!n)return Promise.resolve();const i=rm(t,n,e),o={subjectRowid:e.subjectRowid,subjectUid:e.subjectUid,actor:e.actor,action:e.action,settled:i,outcome:"pending"},r=ja(t.adapter).register(o);return i.then(s=>{o.outcome=s,s!=="unrecorded"&&r()},()=>{o.outcome="unrecorded"}),i.then(()=>{})}async function rm(t,e,n){let i,o;try{if(n.action==="upsert"){const r=await e.embedDocument(n.content);await e.upsertVector(n.subjectRowid,r),i="embedding_upserted"}else await e.deleteVector(n.subjectRowid),i="embedding_deleted"}catch(r){i="embedding_failed",o=r instanceof Error?r.message:String(r),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,r)}try{await M(t,async r=>{await U({tx:r,typePolicy:t.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:i,note:o})})}catch(r){return console.error(`scheduleIssueEmbedding: failed to persist "${i}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,r),"unrecorded"}switch(i){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function sm(t,e){const n=[],i=[];for(const o of e)try{await M(t,async r=>{await U({tx:r,typePolicy:t.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:im})}),o.outcome="failed",n.push(o)}catch(r){o.outcome="unrecorded",i.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,r)}return{recorded:n,unrecorded:i}}async function yn(t,e=5e3){if(t!==":memory:"&&j.mkdirSync(_.dirname(t),{recursive:!0}),!Number.isInteger(e)||e<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${e}`);const n=await Ne.createStoreAdapter({dbPath:t});await n.pragmaSet("busy_timeout",e);const i=kl.createGraphBackend(n,{typePolicy:Tr});await vp(()=>i.applySchema());try{await pi(n)}catch(r){throw await n.close().catch(()=>{}),r}return{adapter:n,graph:i,typePolicy:Tr,flushEmbeds:r=>ja(n).drain(r)}}async function ec(t,e){const n=await t.flushEmbeds(e);let i=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const r=await sm(t,n.stillPending);i=r.recorded.length,o=[...o,...r.unrecorded]}}finally{await t.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:i,unrecorded:o}}async function Po(t){if(!t)return;let e;try{e=await ec(t)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}e.unrecorded.length>0?(console.error(`backlog: ${e.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)):e.stillPending.length>0&&console.error(`backlog: ${e.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Lo=["SIGINT","SIGTERM"];function tc(t,e=n=>process.exit(n)){let n=!1;const i=r=>{n||(n=!0,t().catch(s=>{console.error(`backlog: signal cleanup failed (${r}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{o(),e(128+te.constants.signals[r])}))},o=()=>{for(const r of Lo)process.removeListener(r,i)};for(const r of Lo)process.on(r,i);return{dispose:o}}function am(){return Lo.some(t=>process.listenerCount(t)>0)}const cm=[".git",".adhd","adhd.environment.yaml"];function Zn(t){let e=_.resolve(t);const{root:n}=_.parse(e);for(;;){for(const o of cm)if(j.existsSync(`${e}/${o}`))return e;if(e===n)return;const i=_.dirname(e);if(i===e)return;e=i}}const dm=new Set(["system","global","project"]);function lm(t,e){const n=t.cwd??process.cwd();if(t.scope)return t.scope==="project"?{scope:"project",projectRoot:Zn(n)??n}:{scope:t.scope};const i=e.ADHD_ENV_SCOPE;if(i!==void 0&&dm.has(i)){const r=i;return r==="project"?{scope:"project",projectRoot:Zn(n)??n}:{scope:r}}const o=Zn(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Pr(t){return`.${t}`}function um(t){const e=te.homedir();if(process.platform==="darwin")return _.join(e,"Library","Application Support",t);if(process.platform==="win32"){const i=process.env.APPDATA??_.join(e,"AppData","Roaming");return _.join(i,t)}const n=process.env.XDG_DATA_HOME??_.join(e,".local","share");return _.join(n,t)}function fm(t){const e=t.orgNamespace,n=t.adhdRoot??_.join(te.homedir(),Pr(e)),i=t.adhdRoot??um(e),o={system:_.join(i,t.project,t.namespace),global:_.join(n,t.project,t.namespace)};return t.projectRoot&&(o.project=_.join(t.projectRoot,Pr(e),t.project,t.namespace)),o}function nc(t,e){return e==="project"?t.project??t.global:t[e]}const pm="1.0.0-redesign.1",mm="adhd",gm="default",hm="adhd-environment.json",Ze="config.yaml",oc="config.local.yaml",ym={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Lr extends Error{constructor(e,n){super(`contentHash: lone surrogate in ${e} (not well-formed Unicode)`),this.location=e,this.offending=n,this.name="LoneSurrogateError"}}function Ur(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const i=e+1<t.length?t.charCodeAt(e+1):0;if(i<56320||i>57343)return!0;e++}else if(n>=56320&&n<=57343)return!0}return!1}function ic(t,e){const n=Array.from(t),i=Array.from(e),o=Math.min(n.length,i.length);for(let r=0;r<o;r++){const s=n[r].codePointAt(0)??0,a=i[r].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===i.length?0:n.length<i.length?-1:1}function Dr(t){return new TextEncoder().encode(t).length}function wm(t){const e=Object.keys(t).sort(ic);let n="";for(const o of e){const r=t[o];if(Ur(o))throw new Lr("key",o);if(Ur(r))throw new Lr("value",r);n+=`${Dr(o)}:${o}=${Dr(r)}:${r}
39
+ `}return`sha256-${rc(n)}`}function vm(t){const n=[...t].sort((i,o)=>ic(i.name,o.name)).map(i=>`${i.name}:${i.kind}:${i.scope}`).join(`
40
+ `);return`sha256-${rc(n)}`}function bm(t){return`ADHD_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Em(t,e){return`${t}_${e.toUpperCase().replace(/[.-]/g,"_")}`}function Sm(t){const e={type:"object",properties:{}},n=t;for(const i of Object.keys(n)){const o=n[i],r=i.split(".");let s=e;r.forEach((a,c)=>{if(c===r.length-1){s.properties[a]=km(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 e}function km(t){const e={type:t.type};return t.default!==void 0&&t.secret!==!0&&(e.default=t.default),t.description!==void 0&&(e.description=t.description),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.enum!==void 0&&(e.enum=t.enum),t.pattern!==void 0&&(e.pattern=t.pattern),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.items!==void 0&&(e.items=t.items),e}const _m="adhd-env-ref:";function Am(t){return`${_m}${t}`}const Nm=[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],Rm=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function ce(t,e){return(t>>>e|t<<32-e)>>>0}function jm(t){const e=Uint32Array.from(Rm),n=t.length*8;let i=t.length+1;for(;i%64!==56;)i++;i+=8;const o=new Uint8Array(i);o.set(t),o[t.length]=128;const r=Math.floor(n/4294967296),s=n>>>0,a=new DataView(o.buffer);a.setUint32(i-8,r,!1),a.setUint32(i-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<i;u+=64){for(let h=0;h<16;h++)c[h]=a.getUint32(u+h*4,!1);for(let h=16;h<64;h++){const S=c[h-15],E=c[h-2],N=ce(S,7)^ce(S,18)^S>>>3,k=ce(E,17)^ce(E,19)^E>>>10;c[h]=c[h-16]+N+c[h-7]+k>>>0}let f=e[0],m=e[1],p=e[2],g=e[3],y=e[4],w=e[5],v=e[6],b=e[7];for(let h=0;h<64;h++){const S=ce(y,6)^ce(y,11)^ce(y,25),E=y&w^~y&v,N=b+S+E+Nm[h]+c[h]>>>0,k=ce(f,2)^ce(f,13)^ce(f,22),R=f&m^f&p^m&p,A=k+R>>>0;b=v,v=w,w=y,y=g+N>>>0,g=p,p=m,m=f,f=N+A>>>0}e[0]=e[0]+f>>>0,e[1]=e[1]+m>>>0,e[2]=e[2]+p>>>0,e[3]=e[3]+g>>>0,e[4]=e[4]+y>>>0,e[5]=e[5]+w>>>0,e[6]=e[6]+v>>>0,e[7]=e[7]+b>>>0}const d=new Uint8Array(32),l=new DataView(d.buffer);for(let u=0;u<8;u++)l.setUint32(u*4,e[u],!1);return d}function Tm(t){let e="";for(const n of t)e+=n.toString(16).padStart(2,"0");return e}function rc(t){const e=new TextEncoder().encode(t);return Tm(jm(e))}const{parse:Om}=Ol;function sc(t,e=""){const n={};if(t===null||typeof t!="object"||Array.isArray(t))return e&&(n[e]=t),n;for(const[i,o]of Object.entries(t)){const r=e?`${e}.${i}`:i;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,sc(o,r)):n[r]=o}return n}function bt(t){if(j.existsSync(t))try{const e=j.readFileSync(t,"utf8"),n=Om(e);return n===null||typeof n!="object"||Array.isArray(n)?void 0:sc(n)}catch{return}}function Im(t){return{system:bt(_.join(t.system,Ze)),global:bt(_.join(t.global,Ze)),project:t.project?bt(_.join(t.project,Ze)):void 0,local:t.project?bt(_.join(t.project,oc)):void 0}}function Mr(t){const e={source:t.source,scope:t.scope};return t.source==="env"&&t.env!==void 0&&(e.env=t.env),e}function Uo(t,e){if(t===void 0)return t;switch(e){case"integer":{if(typeof t=="number")return t;const n=parseInt(String(t),10);return Number.isNaN(n)?t:n}case"number":{if(typeof t=="number")return t;const n=parseFloat(String(t));return Number.isNaN(n)?t:n}case"boolean":{if(typeof t=="boolean")return t;const n=String(t).toLowerCase();return n==="true"?!0:n==="false"?!1:t}case"array":return Array.isArray(t)?t:typeof t=="string"?t.length===0?[]:t.split(",").map(n=>n.trim()):t;case"string":return typeof t=="string"?t:String(t);default:return t}}function ac(t){const e={};for(const n of Object.keys(t)){const i=n.split(".");let o=e;i.forEach((r,s)=>{if(s===i.length-1){o[r]=t[n];return}const a=o[r];(typeof a!="object"||a===null||Array.isArray(a))&&(o[r]={}),o=o[r]})}return e}const $m=[["system","system"],["global","global"],["project","project"],["local","local"]];function Cm(t,e,n,i){const o={},r={},s={},a={};for(const c of Object.keys(t)){const d=t[c],l=d.env&&d.env!==""?d.env:Em(i.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??i.activeScope;let m=d.default,p="default";for(const[b,h]of $m){const S=e[b];S&&Object.prototype.hasOwnProperty.call(S,c)&&(m=Uo(S[c],d.type),p=h)}const g=n[l];let y,w,v;g!==void 0?(y=Uo(g,d.type),w="env",v=l):(y=m,w=p),o[c]=u?Am(l):y,r[c]=y,s[c]=Mr(u?{source:"env",scope:f,env:l}:{source:w,scope:f,env:v}),a[c]={...d,env:l,live:u,fallbackValue:m}}return{raw:o,nested:ac(o),typedRaw:r,provenance:s,fields:a}}function Pm(t,e){return t.replace(/\$\{HOME\}/g,te.homedir()).replace(/\$HOME\b/g,te.homedir()).replace(/\$\{PROJECT_ROOT\}/g,e.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,e.namespace)}function Lm(t,e){const n={};for(const[i,o]of Object.entries(t??{})){const r=o.scope??e.activeScope,s=o.share??ym[o.kind],a=o.path?Pm(o.path,e):_.join(nc(e.roots,r),i),c=s==="per-instance"?_.join(a,e.instanceId):a;n[i]={name:i,kind:o.kind,path:c,scope:r,share:s}}return n}function Um(t,e){const n={};for(const[i,o]of Object.entries(t??{})){const r=e[o.in];if(!r)throw new Error(`files.${i}.in references unknown dirs key "${o.in}"`);n[i]={name:i,in:o.in,path:_.join(r.path,o.name),share:o.share??"shared"}}return n}class cc extends Error{constructor(e){super(e.length>0?`Config validation failed: ${e.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=e,this.name="ValidationError"}}function Dm(t,e){if(!e)return;const n=e,i=n.properties;if(i!==void 0&&Object.keys(i).length===0)return;const r=new qs({allErrors:!0,strict:!1}).compile(n);if(!r(t))throw new cc(Mm(r.errors??[]))}function Mm(t){return t.map(e=>({field:xm(e),message:e.message??"is invalid",keyword:e.keyword}))}function xm(t){var i;const e=(t.instancePath??"").replace(/^\//,"").replace(/\//g,".");return e||(((i=t.params)==null?void 0:i.missingProperty)??"(root)")}function Fm(t,e){return _.join(nc(t,e),hm)}const Bm=384,Km=448;function qm(t,e,n={}){const i=n.mode??Bm,o=n.dirMode??Km,r=_.dirname(t);j.mkdirSync(r,{recursive:!0,mode:o}),j.chmodSync(r,o);const s=`${t}.tmp`,a=typeof e=="string"?e:JSON.stringify(e,null,2);try{j.writeFileSync(s,a,{encoding:"utf8",mode:i}),j.chmodSync(s,i),j.renameSync(s,t),j.chmodSync(t,i)}catch(c){try{j.existsSync(s)&&j.unlinkSync(s)}catch{}throw c}}const Hm="0.1.0";function xr(t,e){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(t)}`)}function Vm(){return`${process.pid}-${ke.randomBytes(3).toString("hex")}`}function ki(t,e,n={}){if(!t)throw new Error("Environment requires a non-empty 'project' name");xr(t,"project");const i=e.orgNamespace??mm,o=e.envPrefixOverride??bm(t),r=e.namespaces&&e.namespaces.length>0?e.namespaces:[gm],s=n.namespace??r[0];if(!r.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${t}" (declared: ${r.join(", ")})`);xr(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=lm({scope:n.scope,cwd:n.cwd},a),l=fm({project:t,namespace:s,orgNamespace:i,projectRoot:d,adhdRoot:n.adhdRoot});return{project:t,namespace:s,orgNamespace:i,envPrefix:o,scope:c,projectRoot:d,roots:l}}function Gm(t,e,n={}){const{namespace:i,orgNamespace:o,envPrefix:r,scope:s,projectRoot:a,roots:c}=ki(t,e,n),d=n.processEnv??process.env,l=Im(c),u=n.instanceId??Vm(),{raw:f,nested:m,typedRaw:p,provenance:g,fields:y}=Cm(e.config,l,d,{prefix:r,activeScope:s}),w={};for(const E of Object.keys(y)){const N=y[E];N.live&&(w[E]={env:N.env,type:N.type,fallback:N.secret===!0?void 0:N.fallbackValue})}const v=Sm(e.config);Dm(ac(p),v);const b=Lm(e.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:i}),h=Um(e.files,b);return{version:pm,libraryVersion:Hm,generatedAt:new Date().toISOString(),project:t,namespace:i,orgNamespace:o,envPrefix:r,scope:s,instanceId:u,config:m,raw:f,liveFields:w,fieldSchema:v,configHash:wm(Object.fromEntries(Object.entries(p).map(([E,N])=>[E,String(N)]))),structureHash:vm(Object.values(b).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(b),files:Object.values(h),provenance:g}}class jt extends Error{constructor(e){super(e),this.name="EnvironmentError"}}class Wm extends jt{constructor(e){super(`adhd-environment snapshot not found: ${e}`),this.snapshotPath=e,this.name="SnapshotNotFoundError"}}class Jm extends jt{constructor(e,n){super(`lock "${e}" is already held (${n})`),this.lockName=e,this.lockPath=n,this.name="LockHeldError"}}function zm(t,e){let n=t;for(const i of e.split("."))if(n!==null&&typeof n=="object"&&i in n)n=n[i];else return;return n}function Do(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Do(n));const e={};for(const[n,i]of Object.entries(t))e[n]=Do(i);return e}function Ym(t,e){const n=Do(t);for(const i of Object.keys(e)){const o=e[i],r=i.split(".");let s=n;for(let c=0;c<r.length-1;c++){const d=r[c],l=s[d];(typeof l!="object"||l===null||Array.isArray(l))&&(s[d]={}),s=s[d]}const a=r[r.length-1];Object.defineProperty(s,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?Uo(c,o.type):o.fallback}})}return n}function Xm(t){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new jt(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(t)}`)}class Cn{constructor(e,n,i={}){let o,r;try{o=Gm(e,n,i);const s=ki(e,n,i);r=Fm(s.roots,o.scope)}catch(s){throw s instanceof cc||s instanceof jt?s:new jt(s instanceof Error?s.message:String(s))}return Fr(this,o,r)}static fromSnapshot(e){if(!j.existsSync(e))throw new Wm(e);const n=JSON.parse(j.readFileSync(e,"utf8")),i=Object.create(Cn.prototype);return Fr(i,n,e)}get(e){const n=e.indexOf(".");if(n===-1)return;const i=e.slice(0,n),o=e.slice(n+1);switch(i){case"config":return zm(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(e){return e.startsWith(this.prefix)}resolveEnvName(e){if(this.isEnvNameAllowed(e))return process.env[e]}lock(e="singleton"){Xm(e);const n=this.paths.run??this._runDirFallback();j.mkdirSync(n,{recursive:!0});const i=_.join(n,`${e}.lock`);let o;try{o=j.openSync(i,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new Jm(e,i):s}j.writeSync(o,`${process.pid}
40
41
  ${this.instanceId}
41
- `),R.closeSync(r);let i=!1;return()=>{if(!i){i=!0;try{R.unlinkSync(o)}catch{}}}}_runDirFallback(){return k.join(k.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))R.mkdirSync(t,{recursive:!0})}write(){return ff(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Tr(e,t,n){const o={};for(const s of t.dirs)o[s.name]=s.path;const r={};for(const s of t.files)r[s.name]=s.path;const i=vf(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:o,enumerable:!0},files:{value:r,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 Be={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 bo(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 xe(e={}){const t={namespace:e.namespace??"production",scope:bo(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 Gt("backlog",Be,t)}function ze(e){return e.config.db.path??e.files.db}function Sf(e,t){return`${e}:${t}`}function Ef(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 o=new Gt("backlog",Be,n);return k.join(o.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function Ir(e){return{raw:e,words:Xe(e)}}function _s(e,t,n,o){for(const r of o??[]){const i=r.path[r.path.length-1];if(r.namespace.raw===e&&(i==null?void 0:i.raw)===t)return r}return{id:`${Xe(e).join("-")}/${Xe(t).join("-")}`,host:"ts",namespace:Ir(e),path:[Ir(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function kf(e){var r;const t=((r=e.input)==null?void 0:r.properties)??{},n=e["x-apigen-envelope"],o={};for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";o[i]=Li(s,i)}return o}function Af(e){const t=ol(e.options.port),n=e.options.routePrefix??"",o=e.options.projection??{},r=tl(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=r[s];i.push(`import * as ${c}_ns from ${de(a.importPath)}`),i.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}i.push(""),i.push(`const schemas: Record<string, unknown> = ${Mi(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=r[s];for(const[d,l]of Object.entries(a.schemas)){const u=_s(a.id,d,l,e.operations),f=be({op:u,schema:l,transport:"http",projection:o}),m=n+f.http.route,p=f.http.verb,g=kf(l),b=Object.entries(g),h=de(`${a.id}:${d}`),y=de(d);if(p==="GET"){if(i.push(`app.get(${de(m)}, async (req) => {`),i.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas[${h}]['schema'] as any)`),b.length>0){const w=b.map(([v,S])=>`${de(v)}: (req.headers as Record<string, unknown>)[${de(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(${de(m)}, async (req) => {`),i.push(" const { data = {} } = req.body as Record<string, unknown>"),b.length>0){const w=b.map(([v,S])=>`${de(v)}: (req.headers as Record<string, unknown>)[${de(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 _f(e){return`data: ${e}
42
+ `),j.closeSync(o);let r=!1;return()=>{if(!r){r=!0;try{j.unlinkSync(i)}catch{}}}}_runDirFallback(){return _.join(_.dirname(this.snapshotPath),"run")}ensureDirs(){for(const e of Object.values(this.paths))j.mkdirSync(e,{recursive:!0})}write(){return qm(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Fr(t,e,n){const i={};for(const s of e.dirs)i[s.name]=s.path;const o={};for(const s of e.files)o[s.name]=s.path;const r=Ym(e.config,e.liveFields??{});return Object.defineProperties(t,{project:{value:e.project,enumerable:!0},namespace:{value:e.namespace,enumerable:!0},orgNamespace:{value:e.orgNamespace,enumerable:!0},scope:{value:e.scope,enumerable:!0},prefix:{value:e.envPrefix,enumerable:!0},instanceId:{value:e.instanceId,enumerable:!0},hash:{value:e.configHash,enumerable:!0},version:{value:{configHash:e.configHash,structureHash:e.structureHash,generatedAt:e.generatedAt,libraryVersion:e.libraryVersion},enumerable:!0},provenance:{value:e.provenance,enumerable:!0},dirs:{value:e.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:r,enumerable:!0},paths:{value:i,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:e,enumerable:!1}}),new Proxy(t,{get(s,a,c){return typeof a=="string"&&!(a in s)?s.get(a):Reflect.get(s,a,c)}})}const Ie={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)."},"service.transport":{type:"string",env:"ADHD_BACKLOG_SERVICE_TRANSPORT",default:"mcp",enum:["mcp","http","both"],description:"Transport(s) `serve` mounts: mcp | http | both."},"service.port":{type:"integer",env:"ADHD_BACKLOG_SERVICE_PORT",default:3300,description:"HTTP listen port (ignored for mcp-only)."},"service.host":{type:"string",env:"ADHD_BACKLOG_SERVICE_HOST",default:"127.0.0.1",description:"HTTP listen host (ignored for mcp-only)."},"service.serverCommand":{type:"string",env:"ADHD_BACKLOG_SERVICE_SERVER_COMMAND",default:"",description:"Absolute path (or PATH-resolvable bin) of the server artifact to verify at load time. Unset ⇒ no drift check (backlog serving itself)."},"service.connectGraceMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_CONNECT_GRACE_MS",default:2e4,description:"Pre-connect deadline extension applied to the FIRST attempt — the cold-start grace window (the fix for host-deadline < cold-start)."},"service.connectBudgetMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_CONNECT_BUDGET_MS",default:6e4,description:"Total wall-clock budget across all connect/handshake attempts (bounded)."},"service.readinessTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_READINESS_TIMEOUT_MS",default:3e4,description:"Timeout for ONE serving-path readiness probe."}}};function Pn(t){if(t)return t;const e=process.env.ADHD_BACKLOG_SCOPE;if(e)return e;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function et(t={}){const e={namespace:t.namespace??"production",scope:Pn(t.scope)};return t.adhdRoot!==void 0&&(e.adhdRoot=t.adhdRoot),t.cwd!==void 0&&(e.cwd=t.cwd),t.instanceId!==void 0&&(e.instanceId=t.instanceId),new Cn("backlog",Ie,e)}function tt(t){return t.config.db.path??t.files.db}function Qm(t,e){return`${t}:${e}`}function Zm(t={}){const e=process.env.APIGEN_IR_CACHE_FILE;if(e)return e;const n={namespace:"production",scope:"global"};t.adhdRoot!==void 0&&(n.adhdRoot=t.adhdRoot),t.instanceId!==void 0&&(n.instanceId=t.instanceId);const i=new Cn("backlog",Ie,n);return _.join(i.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function Br(t){return{raw:t,words:Nt(t)}}function dc(t,e,n,i){for(const o of i??[]){const r=o.path[o.path.length-1];if(o.namespace.raw===t&&(r==null?void 0:r.raw)===e)return o}return{id:`${Nt(t).join("-")}/${Nt(e).join("-")}`,host:"ts",namespace:Br(t),path:[Br(e)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function eg(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i={};for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd";i[r]=ga(s,r)}return i}function tg(t){const e=Of(t.options.port),n=t.options.routePrefix??"",i=t.options.projection??{},o=jf(t.packages.map(s=>s.id)),r=["// 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 t.packages.entries()){const c=o[s];r.push(`import * as ${c}_ns from ${ye(a.importPath)}`),r.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}r.push(""),r.push(`const schemas: Record<string, unknown> = ${wa(JSON.stringify(Object.fromEntries(t.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,{schema:c,pkgId:s.id}]))),null,2))}`),r.push(""),r.push("const app = Fastify()"),r.push("");for(const[s,a]of t.packages.entries()){const c=o[s];for(const[d,l]of Object.entries(a.schemas)){const u=dc(a.id,d,l,t.operations),f=Oe({op:u,schema:l,transport:"http",projection:i}),m=n+f.http.route,p=f.http.verb,g=eg(l),y=Object.entries(g),w=ye(`${a.id}:${d}`),v=ye(d);if(p==="GET"){if(r.push(`app.get(${ye(m)}, async (req) => {`),r.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas[${w}]['schema'] as any)`),y.length>0){const b=y.map(([h,S])=>`${ye(h)}: (req.headers as Record<string, unknown>)[${ye(S)}]`).join(", ");r.push(` const envelope: Record<string, unknown> = { ${b} }`)}else r.push(" const envelope: Record<string, unknown> = {}");r.push(` return dispatch(${c}_fns as any, undefined, schemas[${w}]['schema'] as any, ${v}, envelope, query as any)`),r.push("})")}else{if(r.push(`app.post(${ye(m)}, async (req) => {`),r.push(" const { data = {} } = req.body as Record<string, unknown>"),y.length>0){const b=y.map(([h,S])=>`${ye(h)}: (req.headers as Record<string, unknown>)[${ye(S)}]`).join(", ");r.push(` const envelope: Record<string, unknown> = { ${b} }`)}else r.push(" const envelope: Record<string, unknown> = {}");r.push(` return dispatch(${c}_fns as any, undefined, schemas[${w}]['schema'] as any, ${v}, envelope, data as any)`),r.push("})")}}}return r.push(""),r.push("app.setErrorHandler((err, _req, reply) => {"),r.push(" reply.status(500).send({"),r.push(" code: 'internal',"),r.push(" message: err instanceof Error ? err.message : 'Internal error',"),r.push(" })"),r.push("})"),r.push(""),r.push("async function main(): Promise<void> {"),r.push(" try {"),r.push(` await app.listen({ port: ${e} })`),r.push(" } catch (err) {"),r.push(" app.log.error(err)"),r.push(" process.exit(1)"),r.push(" }"),r.push("}"),r.push(""),r.push("main()"),{files:[{path:"routes.ts",content:r.join(`
43
+ `)}]}}function ng(t){return`data: ${t}
43
44
 
44
- `}function jf(e){return`event: error
45
- data: ${e}
45
+ `}function og(t){return`event: error
46
+ data: ${t}
46
47
 
47
- `}async function Nf(e,t,n){const o=new AbortController;t.raw.once("close",()=>o.abort());const r=n.raw;let i=!1;try{for await(const s of e){if(o.signal.aborted)break;i||(r.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),i=!0),r.write(_f(JSON.stringify(s)))}i||r.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.end()}catch(s){const a=ae(s)?s:new F("internal",s instanceof Error?s.message:String(s));if(i)r.write(jf(JSON.stringify(a.toJSON()))),r.end();else{const c=Of(a.code);r.writeHead(c,{"Content-Type":"application/json"}),r.end(JSON.stringify(a.toJSON()))}}n.hijack()}const Rf={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function Of(e){return Rf[e]??500}function js(e){return ae(e)?$d[e.code]??500:500}function Ns(e){return ae(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function Tf(e,t){if(e)for(const n of t){const o={method:n.method,route:n.route};let r=`${n.method} ${n.route}`;n.params.length&&(o.method==="GET"?r+=` params {${n.text?` ${n.text} `:""}}`:r+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,r)}}class If{constructor(t,n,o){this.app=t,this.routePrefix=n,this.signal=o,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 o=this.routeFor(t),r=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(o,r):this.app.post(o,r)}readCall(t,n){const{req:o}=t,r=o.headers,i={};for(const a of n.envelope){const c=r[a.httpHeader];c!==void 0&&(i[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?o.query??{}:o.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=o.query??{};s=a?Td(c,a):c}else{const{data:c={}}=o.body??{};s=c}}return{envelope:i,domainArgs:s,signal:this.signal}}async writeResult(t,n,o){const{req:r,reply:i}=t;if(Bt(n)){await Nf(n,r,i);return}i.type("application/json"),i.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,o){const{reply:r}=t;r.status(js(n)).send(Ns(n))}}function $f(e,t,n,o,r){var a;const i=[],s={host:n,operations:o};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],r);for(const u of l)u.transports&&!u.transports.includes("http")||i.push(u)}return i}async function Cf(e){var h,y;const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",o=e.options.routePrefix??"",r=e.options.projection??{},i=ro(e.options),s=io(e.options),a=e.logger??no(),c=Qa({logger:a});c.setErrorHandler((w,v,S)=>{S.status(js(w)).send(Ns(w))});const d=new If(c,o,e.signal),l=[],u={},f={};for(const w of e.packages){if(!w.fns)throw new Error(`Package "${w.id}" is missing fns`);const v=w.fns,S=Object.entries(w.schemas).map(([j,O])=>({fnName:j,fnSchema:O,op:_s(w.id,j,O,e.operations)})),E={},A={};for(const{fnName:j,fnSchema:O,op:I}of S)E[I.id]=O,A[I.id]=v[j],u[I.id]=O,f[I.id]=v[j];const _=fe(E,i),N={fns:A,createClient:w.createClient,schemas:E};for(const{fnSchema:j,op:O}of S){const I=be({op:O,schema:j,transport:"http",projection:r});d.bindSchema(O.id,j),d.registerRoute(I,M=>Me(I,_,M,N));const{params:C,text:q}=$i(j);l.push({method:I.http.verb,route:o+I.http.route,text:q,params:C})}}const m=((h=e.packages[0])==null?void 0:h.id)??"ts",p=fe(u,i),g={invoke:(w,v,S)=>p(w,{operation:{id:w},ctx:new rt,domainArgs:v.domainArgs,envelope:v.envelope,signal:v.signal},S),invokeOptions:{fns:f,schemas:u,createClient:(y=e.packages[0])==null?void 0:y.createClient}},b=$f(i,s,m,e.operations??[],g);if(b.length>0){const w=fe({},i),v={fns:{},schemas:{}};for(const S of b){const E=be({op:S,transport:"http",projection:r});d.registerRoute(E,A=>Me(E,w,A,v)),l.push({method:E.http.verb,route:`${o}/${S.id}`,text:"",params:[]})}}return await c.listen({port:t,host:n}),a.info({host:n,port:t},`listening on http://${n}:${t}`),Tf(a,l),new Promise(w=>{e.signal&&e.signal.addEventListener("abort",async()=>{await c.close(),w()})})}const Pf={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 Af(e)},run(e){return Cf(e)}};function xf(e,t={}){const n=t.title??"API",o=t.version??"0.0.0",r={};for(const i of e){const s=Re(i),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:i.id,summary:i.id,responses:{200:Lf(i.output)}};if(a==="GET")l.parameters=Uf(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}}})}r[c]===void 0&&(r[c]={}),r[c][d]=l}return{openapi:"3.1.0",info:{title:n,version:o},paths:r}}function Lf(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Uf(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(([o,r])=>({name:o,in:"query",required:t.includes(o),schema:r}))}function Df(e,t={}){return[{...vi("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>xf(e.operations,{title:t.title,version:t.version})}]}const Mf={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 Df(e,t)}}}};function Ff(){return`// Auto-generated by @adhd/apigen-cli — do not edit
48
+ `}async function ig(t,e,n){const i=new AbortController;e.raw.once("close",()=>i.abort());const o=n.raw;let r=!1;try{for await(const s of t){if(i.signal.aborted)break;r||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),r=!0),o.write(ng(JSON.stringify(s)))}r||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(s){const a=fe(s)?s:new z("internal",s instanceof Error?s.message:String(s));if(r)o.write(og(JSON.stringify(a.toJSON()))),o.end();else{const c=sg(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const rg={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function sg(t){return rg[t]??500}function lc(t){return fe(t)?rf[t.code]??500:500}function uc(t){return fe(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:"Internal error"}}function ag(t,e){if(t)for(const n of e){const i={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(i.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),t.info(n,o)}}class cg{constructor(e,n,i){this.app=e,this.routePrefix=n,this.signal=i,this.schemasByOpId=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}routeFor(e){return e.isMount?`${this.routePrefix}/${e.op.id}`:this.routePrefix+e.http.route}registerRoute(e,n){const i=this.routeFor(e),o=async(r,s)=>{const a={req:r,reply:s};try{const c=await this.readCall(a,e),d=await n(c);await this.writeResult(a,d,e)}catch(c){await this.writeError(a,c,e)}};e.http.verb==="GET"?this.app.get(i,o):this.app.post(i,o)}readCall(e,n){const{req:i}=e,o=i.headers,r={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(r[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?i.query??{}:i.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=i.query??{};s=a?nf(c,a):c}else{const{data:c={}}=i.body??{};s=c}}return{envelope:r,domainArgs:s,signal:this.signal}}async writeResult(e,n,i){const{req:o,reply:r}=e;if($n(n)){await ig(n,o,r);return}r.type("application/json"),r.send(JSON.stringify(n===void 0?null:n))}writeError(e,n,i){const{reply:o}=e;o.status(lc(n)).send(uc(n))}}function dg(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("http")||r.push(u)}return r}async function lg(t){var w,v;const e=t.options.port??3e3,n=t.options.host??"127.0.0.1",i=t.options.routePrefix??"",o=t.options.projection??{},r=di(t.options),s=li(t.options),a=t.logger??ai(),c=_l({logger:a});c.setErrorHandler((b,h,S)=>{S.status(lc(b)).send(uc(b))});const d=new cg(c,i,t.signal),l=[],u={},f={};for(const b of t.packages){if(!b.fns)throw new Error(`Package "${b.id}" is missing fns`);const h=b.fns,S=Object.entries(b.schemas).map(([A,O])=>({fnName:A,fnSchema:O,op:dc(b.id,A,O,t.operations)})),E={},N={};for(const{fnName:A,fnSchema:O,op:I}of S)E[I.id]=O,N[I.id]=h[A],u[I.id]=O,f[I.id]=h[A];const k=Ee(E,r),R={fns:N,createClient:b.createClient,schemas:E};for(const{fnSchema:A,op:O}of S){const I=Oe({op:O,schema:A,transport:"http",projection:o});d.bindSchema(O.id,A),d.registerRoute(I,Y=>st(I,k,Y,R));const{params:L,text:$}=ua(A);l.push({method:I.http.verb,route:i+I.http.route,text:$,params:L})}}const m=((w=t.packages[0])==null?void 0:w.id)??"ts",p=Ee(u,r),g={invoke:(b,h,S)=>p(b,{operation:{id:b},ctx:new Pt,domainArgs:h.domainArgs,envelope:h.envelope,signal:h.signal},S),invokeOptions:{fns:f,schemas:u,createClient:(v=t.packages[0])==null?void 0:v.createClient}},y=dg(r,s,m,t.operations??[],g);if(y.length>0){const b=Ee({},r),h={fns:{},schemas:{}};for(const S of y){const E=Oe({op:S,transport:"http",projection:o});d.registerRoute(E,N=>st(E,b,N,h)),l.push({method:E.http.verb,route:`${i}/${S.id}`,text:"",params:[]})}}return await c.listen({port:e,host:n}),a.info({host:n,port:e},`listening on http://${n}:${e}`),ag(a,l),new Promise(b=>{t.signal&&t.signal.addEventListener("abort",async()=>{await c.close(),b()})})}const ug={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(t){return tg(t)},run(t){return lg(t)}};function fg(t,e={}){const n=e.title??"API",i=e.version??"0.0.0",o={};for(const r of t){const s=qe(r),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:r.id,summary:r.id,responses:{200:pg(r.output)}};if(a==="GET")l.parameters=mg(r.input);else{const u=r.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:i},paths:o}}function pg(t){return typeof t=="object"&&t!==null&&Object.keys(t).length>0?{description:"Success",content:{"application/json":{schema:t}}}:{description:"Success"}}function mg(t){if(typeof t!="object"||t===null||typeof t.properties!="object"||t.properties===null)return[];const e=Array.isArray(t.required)?t.required:[],n=t.properties;return Object.entries(n).map(([i,o])=>({name:i,in:"query",required:e.includes(i),schema:o}))}function gg(t,e={}){return[{...Qs("_meta/openapi",t,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>fg(t.operations,{title:e.title,version:e.version})}]}const hg={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(t,e){return gg(t,e)}}}};function yg(){return`// Auto-generated by @adhd/apigen-cli — do not edit
48
49
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
49
50
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
50
51
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
@@ -118,10 +119,10 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
118
119
 
119
120
  const transport = new StdioServerTransport()
120
121
  server.connect(transport)
121
- `}function Bf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
122
+ `}function wg(t,e){return`// Auto-generated by @adhd/apigen-cli — do not edit
122
123
  import { createServer } from 'node:http'
123
124
  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
+ ${t==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
125
126
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
126
127
  import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
127
128
  import { toolMetas, groupFns, groupCreateClient } from './index.js'
@@ -191,35 +192,71 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
191
192
  }
192
193
  })
193
194
 
194
- const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
195
+ const mcpTransport = new ${t==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
195
196
  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 Mn(e){return{raw:e,words:Xe(e)}}function Kf(e){return Mn(el(fn.basename(e)))}function Rs(e,t,n){if(n){const r=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(!r)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 r}const o=Mn(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Mn(e.id),path:e.dropFileSegment?[o]:[Kf(e.importPath),o],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function qf(e,t,n){const o=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const r of e)o.push(`import * as ${r.id}_ns from '${r.importPath}'`),o.push(`const ${r.id}_fns = buildFnTable(${r.id}_ns as Record<string, unknown>)`);o.push(""),o.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const r of e)for(const[i,s]of Object.entries(r.schemas)){const a=Rs({id:r.id,importPath:r.importPath},i,n),d=be({op:a,schema:s,transport:"mcp"}).mcp.name,l=jn(d,s,t[d]??t[i]);o.push(` ${JSON.stringify(d)}: { group: '${r.id}', fnName: ${JSON.stringify(i)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}o.push("}"),o.push(""),o.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const r of e)o.push(` '${r.id}': ${r.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);o.push("}"),o.push(""),o.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const r of e)o.push(` '${r.id}': undefined, // injected at startup if createClient provided`);return o.push("}"),o.join(`
198
- `)}function Hf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,o=e.options.toolDescriptions??{},r=e.operations,i=qf(e.packages,o,r),s=t==="stdio"?Ff():Bf(t,n);return{files:[{path:"index.ts",content:i},{path:"server.ts",content:s}]}}async function Vf(e){const t=await Ci(e);if(t.ok){const r=t.chunks.map(i=>({type:"text",text:JSON.stringify(i)}));return r.push({type:"text",text:"[stream complete]"}),{content:r}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const o={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(o)}],isError:!0}}const Gf=Object.freeze({type:"object",properties:{}});class Wf{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 o=this.toolMeta.get(n);return Object.freeze({name:n,description:(o==null?void 0:o.description)??n,inputSchema:(o==null?void 0:o.inputSchema)??Gf,...o!=null&&o.outputSchema?{outputSchema:o.outputSchema}:{}})});return this.cachedList=Object.freeze(t),this.cachedList}readCall(t,n){const o={};for(const i of n.envelope){const s=t.meta[i.mcpMetaKey];s!==void 0&&(o[i.field]=s)}const r=n.isMount?t.args:t.args.data??{};return{envelope:o,domainArgs:r}}async writeResult(t,n,o){if(Bt(n)){t.output=await Vf(n);return}const r=this.schemasByOpId.get(o.op.id),{wrapped:i}=xi(r==null?void 0:r.output),s=Wd(i,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(t,n,o){throw ae(n)&&n.code,n}}function Jf(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 o=null;for(const r of t){if(!r||typeof r!="object")continue;const i=r,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:[];o=o===null?[...a]:o.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...o&&o.length>0?{required:o}:{}}}return{type:"object",properties:{}}}function zf(e,t,n,o,r){var a;const i=[],s={host:n,operations:o};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],r);for(const u of l)u.transports&&!u.transports.includes("mcp")||i.push(u)}return i}function Yf(e,t){var f,m;const n=e.options.projection??{},o=e.options.toolDescriptions??{},r=ro(e.options),i=io(e.options),s={},a={};for(const p of e.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const g=p.fns,b=Object.entries(p.schemas).map(([S,E])=>({fnName:S,fnSchema:E,op:Rs({id:p.id,importPath:p.importPath},S,e.operations)})),h={},y={};for(const{fnName:S,fnSchema:E,op:A}of b)h[A.id]=E,y[A.id]=g[S],s[A.id]=E,a[A.id]=g[S];const w=fe(h,r),v={fns:y,createClient:p.createClient,schemas:h};for(const{fnName:S,fnSchema:E,op:A}of b){const _=be({op:A,schema:E,transport:"mcp",projection:n});t.bindSchema(A.id,E);const{outputSchema:N}=xi(E.output),j=jn(_.mcp.name,E,o[_.mcp.name]??o[S]);t.bindToolMeta(_.mcp.name,{description:j,inputSchema:E.input,outputSchema:N}),t.registerRoute(_,O=>Me(_,w,O,v))}}const c=((f=e.packages[0])==null?void 0:f.id)??"ts",d=fe(s,r),l={invoke:(p,g,b)=>d(p,{operation:{id:p},ctx:new rt,domainArgs:g.domainArgs,envelope:g.envelope,signal:g.signal},b),invokeOptions:{fns:a,schemas:s,createClient:(m=e.packages[0])==null?void 0:m.createClient}},u=zf(r,i,c,e.operations??[],l);if(u.length>0){const p=fe({},r),g={fns:{},schemas:{}};for(const b of u){const h=be({op:b,transport:"mcp",projection:n}),y=Jf(b.input),w=jn(h.mcp.name,{input:y},o[h.mcp.name]);t.bindToolMeta(h.mcp.name,{description:w,inputSchema:y}),t.registerRoute(h,v=>Me(h,p,v,g))}}}function Xf(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 an(e,t,n){const o=new Za.Server(n,{capabilities:{tools:{}}});return o.setRequestHandler(Fo.ListToolsRequestSchema,async()=>({tools:e.listTools()})),o.setRequestHandler(Fo.CallToolRequestSchema,async r=>{const{name:i,arguments:s={}}=r.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 m=await e.readCall(u,a),p=await c(m);return await e.writeResult(u,p,a),t.info({tool:i,ms:Date.now()-f},`→ ${i}`),u.output}catch(m){throw ae(m)&&m.code!=="internal"?t.error({tool:i,ms:Date.now()-f,code:m.code,message:m.message},`✗ ${i}`):t.error({tool:i,ms:Date.now()-f,err:m},`✗ ${i}`),e.writeError(u,m,a),m}}),o}function $r(e,t){return async(n,o)=>{try{await t(n,o)}catch(r){e.error({err:r},"mcp http transport handler error"),o.headersSent||o.writeHead(500),o.writableEnded||o.end("Internal Server Error")}}}function Cr(e,t){const n=e.signal;if(!n)throw new F("invalid_argument",`apigen mcp transport "${t}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function Pr(e,t,n,o,r,i){return new Promise((s,a)=>{const c=d=>{a(new F("internal",`failed to bind mcp ${o} server on ${n}:${t}: ${d.message}`,{cause:d}))};e.once("error",c),e.listen(t,n,()=>{e.removeListener("error",c),e.on("error",l=>r.error({err:l},"mcp http server error")),r.info({host:n,port:t},`listening on http://${n}:${t}`);const d=()=>{r.info("mcp server shutting down"),e.close(()=>s()),e.closeAllConnections()};if(i.aborted){d();return}i.addEventListener("abort",d,{once:!0})})})}function Qf(e,t,n,o=process.stdin){return new Promise(r=>{let i=!1;function s(l){i||(i=!0,o.off("end",a),o.off("close",a),n==null||n.removeEventListener("abort",c),t.info(l),r())}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")},o.once("end",a),o.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function Zf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,o=e.options.host??"127.0.0.1",r=e.logger??no();r.info(`mcp server starting (${t})`);const i=new Wf;Yf(e,i);const a=i.listTools().map(u=>u.name);r.info({tools:a},`${a.length} tools available`);for(const u of a){const f=i.getPlan(u),m=(f==null?void 0:f.params)??[],p=m.map(g=>`${g.name}${g.required?"":"?"}: ${g.type}`).join(", ");r.info({tool:u,args:{data:m}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}const c=Xf(e);if(r.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),t==="stdio"){const u=an(i,r,c),f=new ec.StdioServerTransport;return await u.connect(f),r.info("stdio transport ready"),Qf(f,r,e.signal)}if(t==="sse"){const u=Cr(e,t),f=new Map,m=Mo.createServer($r(r,async(p,g)=>{const b=p.url??"";if(p.method==="GET"&&b==="/sse"){const h=an(i,r,c),y=new tc.SSEServerTransport("/messages",g);f.set(y.sessionId,y),y.onclose=()=>f.delete(y.sessionId),await h.connect(y)}else if(p.method==="POST"&&b.startsWith("/messages")){const h=new URLSearchParams(b.split("?")[1]??"").get("sessionId"),y=h?f.get(h):void 0;if(!y){g.writeHead(404),g.end("Session not found");return}await y.handlePostMessage(p,g)}else g.writeHead(404),g.end("Not found")}));return Pr(m,n,o,t,r,u)}const d=Cr(e,t),l=Mo.createServer($r(r,async(u,f)=>{const m=an(i,r,c),p=new nc.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await m.connect(p),await p.handleRequest(u,f)}));return Pr(l,n,o,t,r,d)}const ep={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 Hf(e)},run(e){return Zf(e)}},Os=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Ts=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],tp=new Set([...Os,...Ts]);function np(e){return tp.has(e)}const st=["uid","kind","title","status","priority"],re=1e3,Is=50;async function $s(e,t,n){const o=await e.getNodeByUid(t);if(o)return o.tInvalid!==void 0||n!==void 0&&o.kind!==n?null:o;if(Qe(t)!=="prefix")return null;const r=await e.transaction(c=>as(c,t)),i=n!==void 0?r.filter(c=>c.kind===n):r,s=cs(t,i);if(!s)return null;const a=await e.getNodeByUid(s.uid);return a&&a.tInvalid===void 0?a:null}async function Cs(e,t,n){if(Qe(t)==="too-short")throw ds(t);const o=await $s(e,t,n==null?void 0:n.expectedKind);if(!o)throw Ce(n==null?void 0:n.expectedKind,t,Qe(t)==="prefix");return o}async function op(e,t,n){return Qe(t)==="too-short"?null:$s(e,t,n==null?void 0:n.expectedKind)}async function So(e,t){const n=await Cs(e,t,{expectedKind:"issue"});if(n.isSuperseded)throw new Kt(t,await rp(e,n));return n}async function rp(e,t){const n=new Set([t.id]);let o,r=t;for(;;){const s=(await e.getEdges({dst:r.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return o==null?void 0:o.uid;n.add(s.src);const a=(await e.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return o==null?void 0:o.uid;if(o=a,!a.isSuperseded)return a.uid;r=a}}async function K(e,t,n){if(pe(n)||qt(n)){const i=await op(e,n,{expectedKind:t});if(i)return{id:i.id,uid:i.uid,name:i.name??n,record:i};if(pe(n))return null}const r=(await e.queryNodes({kind:t,name:n,liveOnly:!0,limit:1}))[0];return r?{id:r.id,uid:r.uid,name:r.name??n,record:r}:null}async function qe(e,t,n){var i;if(pe(n)||qt(n)){const s=await K(e,"component",n);return!s||((i=s.record.metadata)==null?void 0:i.projectUid)!==t?null:s}const r=(await e.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:t}},limit:1}))[0];return r?{id:r.id,uid:r.uid,name:r.name??n,record:r}:null}function Ke(e,t){return e.getEdges({src:t})}async function Ps(e,t){var c,d;const o=(c=(await e.getEdges({dst:t,rel:"owns_component"}))[0])==null?void 0:c.src;if(o===void 0)return{};const[r]=await e.getNodesByIds([o]);if(!r)return{};const s=(d=(await e.getEdges({dst:o,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:r};const[a]=await e.getNodesByIds([s]);return{component:r,project:a}}async function ip(e,t){const n=t.expectedKind==="component"&&t.projectUid!==void 0?await qe(e,t.projectUid,t.ref):await K(e,t.expectedKind,t.ref);if(!n)return;if(await sp(e,t.rel,t.expectedKind)){const r=await e.getEdges({src:n.id,rel:t.rel});return new Set(r.map(i=>i.dst))}const o=await e.getEdges({dst:n.id,rel:t.rel});return new Set(o.map(r=>r.src))}async function sp(e,t,n){var i;const r=(i=(await e.queryNodes({kind:"edge_kind",name:t,liveOnly:!0,limit:1}))[0])==null?void 0:i.metadata;return typeof(r==null?void 0:r.source_kind)=="string"&&r.source_kind===n}async function ap(e,t){return(await e.queryNodes({kind:t,liveOnly:!0})).map(o=>o.name).filter(o=>typeof o=="string")}function cp(e,t){const n=e.length+1,o=t.length+1,r=Array.from({length:n},()=>new Array(o).fill(0));for(let i=0;i<n;i+=1)r[i][0]=i;for(let i=0;i<o;i+=1)r[0][i]=i;for(let i=1;i<n;i+=1)for(let s=1;s<o;s+=1)r[i][s]=e[i-1]===t[s-1]?r[i-1][s-1]:1+Math.min(r[i-1][s],r[i][s-1],r[i-1][s-1]);return r[e.length][t.length]}function xs(e,t,n=3){const o=Math.max(2,Math.ceil(e.length/2));return t.map(r=>({candidate:r,distance:cp(e.toLowerCase(),r.toLowerCase())})).filter(r=>r.distance<=o).sort((r,i)=>r.distance-i.distance).slice(0,n).map(r=>r.candidate)}async function Le(e,t){const n=await ap(e,t.catalogKind),o=new Set,r=[];for(const i of t.refs){const s=await K(e,t.catalogKind,i);if(!s){r.push(i);continue}const a=await e.getEdges({dst:s.id,rel:t.rel});for(const c of a)o.add(c.src)}if(r.length>0){const i=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=r.map(a=>{const c=xs(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new Oe(t.field,`unknown ${t.catalogKind} value(s): ${s} — no live "${t.catalogKind}" catalog row matches (existing ${t.catalogKind} values: ${i})`)}return o}function dp(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const o=new Set;for(const r of t)n.has(r)&&o.add(r);t=o}return t}function Eo(e){if(e){for(const t of e)if(!np(t))throw new Oe("fields",`unknown field "${t}" — known fields: ${[...Os,...Ts].join(", ")}`)}}function Te(e){var t;return((t=e==null?void 0:e.metadata)==null?void 0:t.terminal)===!0}async function lp(e,t,n){const o=n.find(l=>l.rel==="has_kind"&&l.src===t),r=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=[o==null?void 0:o.dst,r==null?void 0:r.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:o?d.get(o.dst):void 0,status:r?d.get(r.dst):void 0,priority:i?d.get(i.dst):void 0,author:s?d.get(s.dst):void 0}}async function up(e,t,n){const o=n.filter(i=>i.rel==="has_citation"&&i.src===t);return o.length===0?[]:(await e.getNodesByIds(o.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 fp(e,t,n){const o=n.filter(i=>i.rel==="has_note"&&i.src===t);return o.length===0?[]:(await e.getNodesByIds(o.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 pp(e,t,n){const o=(n??await Ke(e,t)).filter(s=>s.rel==="audits"&&s.src===t);return o.length===0?[]:(await e.getNodesByIds(o.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,m;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((m=s.metadata)==null?void 0:m.at)=="string"?s.metadata.at:s.tCreated}}).sort((s,a)=>s.at.localeCompare(a.at))}async function mp(e,t){const n=await e.getEdges({dst:t,rel:"blocks"});if(n.length===0)return[];const o=n.map(s=>s.src),r=await e.getNodesByIds(o),i=await Ls(e,r);return r.filter(s=>!Te(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 gp(e,t,n){const o=(n??await Ke(e,t)).filter(c=>c.rel==="relates_to"&&c.src===t),r=await e.getEdges({dst:t,rel:"relates_to"}),i=new Set([...o.map(c=>c.dst),...r.map(c=>c.src)]);if(i.size===0)return[];const s=await e.getNodesByIds([...i]),a=await Ls(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 Ls(e,t){if(t.length===0)return new Map;const n=new Set(t.map(d=>d.id)),o=await e.getEdges({rel:"has_status"}),r=new Map;for(const d of o)n.has(d.src)&&!r.has(d.src)&&r.set(d.src,d.dst);const i=[...new Set(r.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 r){const u=a.get(l);u&&c.set(d,u)}return c}async function Us(e,t,n,o={}){var p,g,b;const r={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"),m=o.outgoingEdges??(s||c||d||l||f?await Ke(e,t.id):void 0);if(i("title")&&(r.title=t.name??""),i("createdAt")&&(r.createdAt=t.tCreated),i("updatedAt")&&(r.updatedAt=t.tValid),i("assignee")){const h=(p=t.metadata)==null?void 0:p.assignee;typeof h=="string"&&(r.assignee=h)}if(i("gitContext")){const h=(g=t.metadata)==null?void 0:g.gitContext;typeof h=="string"&&h.length>0&&(r.gitContext=h)}if(i("closedAt")){const h=(b=t.metadata)==null?void 0:b.closedAt;typeof h=="string"&&(r.closedAt=h)}if(i("body")&&(r.body=t.content),s&&m){const h=await lp(e,t.id,m);i("kind")&&h.kind&&(r.kind=h.kind.name??""),i("status")&&h.status&&(r.status=h.status.name??""),i("priority")&&h.priority&&(r.priority=h.priority.name??""),i("author")&&h.author&&(r.author=h.author.name??"")}if(a){const{project:h,component:y}=await Ps(e,t.id);i("project")&&h&&(r.project=h.uid),i("component")&&y&&(r.component=y.uid)}return c&&m&&(r.citations=await up(e,t.id,m)),d&&m&&(r.notes=await fp(e,t.id,m)),l&&m&&(r.auditTrail=await pp(e,t.id,m)),u&&(r.blockers=await mp(e,t.id)),f&&m&&(r.related=await gp(e,t.id,m)),i("_score")&&o.score!==void 0&&(r._score=o.score),r}async function tt(e,t,n,o){return Promise.all(t.map(r=>Us(e,r,n,{score:o==null?void 0:o.get(r.uid)})))}const hp=.0050125;function yp(e){if(e===void 0)return Is;if(!Number.isInteger(e)||e<=0||e>re)throw new Oe("limit",`must be a positive integer ≤ ${re}, got ${e}`);return e}async function wp(e,t){const n=new Set;for(const o of t.refs){const r=await ip(e,{rel:t.rel,expectedKind:t.expectedKind,ref:o});if(r)for(const i of r)n.add(i)}return n}async function vp(e,t){const o=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),r=new Set;for(const i of o){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)r.add(a.src)}return r}async function bp(e,t){if(t.project===void 0&&t.component===void 0)return;let n,o;if(t.project!==void 0){const c=await K(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 m of f)l.add(m.dst)}o=l}if(t.component===void 0)return o;const r=n!==void 0?await qe(e,n,t.component):await K(e,"component",t.component);if(!r)return new Set;const i=await e.getEdges({src:r.id,rel:"owns_component"}),s=new Set(i.map(c=>c.dst));if(!o)return s;const a=new Set;for(const c of s)o.has(c)&&a.add(c);return a}function Sp(e){var o,r,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),(o=e.createdAt)!=null&&o.since&&(n.tCreatedAfter=e.createdAt.since),(r=e.createdAt)!=null&&r.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 Ds(e,t){if(!t)return;const n=[],o=await bp(e,t);if(o!==void 0&&n.push(o),t.kind!==void 0){const c=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Le(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 vp(e,t.status));else{const c=Array.isArray(t.status)?t.status:[t.status];n.push(await Le(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 Le(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}t.author!==void 0&&n.push(await wp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]}));const r=Sp(t);if(n.length===0&&!r)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]}:{},...r},a=await e.queryNodes(s);return new Set(a.map(c=>c.id))}const Ep=4;async function kp(e,t){if(t.length===0)return[];const n=t.map(s=>s.id),o={ids:n,isSuperseded:!1,limit:n.length},r=await e.queryNodes(o),i=new Set(r.map(s=>s.id));return t.filter(s=>i.has(s.id))}async function Ap(e,t){var s;if(!e.search)throw new T("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"},o={text:t.text,vec:t.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:t.decayPerHour??hp}],filters:n},r=[];let i=t.limit;for(let a=0;a<Ep;a++){const c=await e.search.backend.searchRanked(o,i);if(r.length=0,r.push(...await kp(e.graph,c)),r.length>=t.limit||c.length<i)break;i*=2}return r.slice(0,t.limit)}async function _p(e,t){var b,h;const{graph:n}=e;if(!e.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");Eo(t.fields);const o=t.fields??st,r=yp(t.limit);let i,s;if(((b=t.filter)==null?void 0:b.anchor)!==void 0)s=await So(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 T("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await Ds(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?r+1:r,l=await Ap(e,{text:i,vec:c,candidateIds:a,limit:d}),u=(s?l.filter(y=>y.id!==s.id):l).slice(0,r);if(u.length===0)return[];const f=await n.getNodesByIds(u.map(y=>y.id)),m=new Map(f.map(y=>[y.id,y])),p=u.map(y=>m.get(y.id)).filter(y=>y!==void 0),g=new Map(u.map(y=>{var w;return[(w=m.get(y.id))==null?void 0:w.uid,y.score]}).filter(y=>y[0]!==void 0));return tt(n,p,o,g)}function jp(e){return e.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function Np(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 o=["",t!==void 0?`Citations: [${jp(t)}]`:"Citations:"];for(const r of n){const i=r.lines?`${r.file}:${r.lines}`:r.file;o.push(`- [${i} sha:${r.sha}]`)}return o}function Rp(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 Op(e){const t=[`## ${e.title??"(untitled)"}`],n=Rp(e);return n!==void 0&&t.push(n),e.body!==void 0&&e.body.length>0&&t.push("",e.body),t.push(...Np(e)),t.join(`
200
- `)}function Tp(e){return e.length===0?`_No matching issues._
201
- `:`${e.map(Op).join(`
197
+ httpServer.listen(${e}, () => console.error('MCP ${t} server on port ${e}'))
198
+ `}function Mo(t){return{raw:t,words:Nt(t)}}function vg(t){return Mo(Rf(ao.basename(t)))}function fc(t,e,n){if(n){const o=n.find(r=>{var s;return r.kind==="action"&&r.namespace.raw===t.id&&((s=r.path[r.path.length-1])==null?void 0:s.raw)===e});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${t.id}" fn "${e}" 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 i=Mo(e);return{id:`${t.id}/${e}`,host:"ts",namespace:Mo(t.id),path:t.dropFileSegment?[i]:[vg(t.importPath),i],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function bg(t,e,n){const i=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of t)i.push(`import * as ${o.id}_ns from '${o.importPath}'`),i.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);i.push(""),i.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of t)for(const[r,s]of Object.entries(o.schemas)){const a=fc({id:o.id,importPath:o.importPath},r,n),d=Oe({op:a,schema:s,transport:"mcp"}).mcp.name,l=So(d,s,e[d]??e[r]);i.push(` ${JSON.stringify(d)}: { group: '${o.id}', fnName: ${JSON.stringify(r)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}i.push("}"),i.push(""),i.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of t)i.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);i.push("}"),i.push(""),i.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of t)i.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return i.push("}"),i.join(`
199
+ `)}function Eg(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,i=t.options.toolDescriptions??{},o=t.operations,r=bg(t.packages,i,o),s=e==="stdio"?yg():wg(e,n);return{files:[{path:"index.ts",content:r},{path:"server.ts",content:s}]}}async function Sg(t){const e=await fa(t);if(e.ok){const o=e.chunks.map(r=>({type:"text",text:JSON.stringify(r)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=e;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const i={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(i)}],isError:!0}}const kg=Object.freeze({type:"object",properties:{}});class _g{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}bindToolMeta(e,n){this.cachedList=void 0,this.toolMeta.set(e,n)}registerRoute(e,n){this.cachedList=void 0,this.plans.set(e.mcp.name,e),this.dispatchers.set(e.mcp.name,n)}getPlan(e){return this.plans.get(e)}getDispatch(e){return this.dispatchers.get(e)}listTools(){if(this.cachedList)return this.cachedList;const e=[...this.plans.keys()].map(n=>{const i=this.toolMeta.get(n);return Object.freeze({name:n,description:(i==null?void 0:i.description)??n,inputSchema:(i==null?void 0:i.inputSchema)??kg,...i!=null&&i.outputSchema?{outputSchema:i.outputSchema}:{}})});return this.cachedList=Object.freeze(e),this.cachedList}readCall(e,n){const i={};for(const r of n.envelope){const s=e.meta[r.mcpMetaKey];s!==void 0&&(i[r.field]=s)}const o=n.isMount?e.args:e.args.data??{};return{envelope:i,domainArgs:o}}async writeResult(e,n,i){if($n(n)){e.output=await Sg(n);return}const o=this.schemasByOpId.get(i.op.id),{wrapped:r}=ma(o==null?void 0:o.output),s=bf(r,n);e.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(e,n,i){throw fe(n)&&n.code,n}}function Ag(t){if(t&&typeof t=="object"&&t.type==="object")return t;const e=t==null?void 0:t.oneOf;if(Array.isArray(e)&&e.length>0){const n={};let i=null;for(const o of e){if(!o||typeof o!="object")continue;const r=o,s=r.properties;if(s&&typeof s=="object")for(const[c,d]of Object.entries(s))c in n||(n[c]=d);const a=Array.isArray(r.required)?r.required:[];i=i===null?[...a]:i.filter(c=>a.includes(c))}return{...t,type:"object",properties:n,...i&&i.length>0?{required:i}:{}}}return{type:"object",properties:{}}}function Ng(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("mcp")||r.push(u)}return r}function Rg(t,e){var f,m;const n=t.options.projection??{},i=t.options.toolDescriptions??{},o=di(t.options),r=li(t.options),s={},a={};for(const p of t.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const g=p.fns,y=Object.entries(p.schemas).map(([S,E])=>({fnName:S,fnSchema:E,op:fc({id:p.id,importPath:p.importPath},S,t.operations)})),w={},v={};for(const{fnName:S,fnSchema:E,op:N}of y)w[N.id]=E,v[N.id]=g[S],s[N.id]=E,a[N.id]=g[S];const b=Ee(w,o),h={fns:v,createClient:p.createClient,schemas:w};for(const{fnName:S,fnSchema:E,op:N}of y){const k=Oe({op:N,schema:E,transport:"mcp",projection:n});e.bindSchema(N.id,E);const{outputSchema:R}=ma(E.output),A=So(k.mcp.name,E,i[k.mcp.name]??i[S]);e.bindToolMeta(k.mcp.name,{description:A,inputSchema:E.input,outputSchema:R}),e.registerRoute(k,O=>st(k,b,O,h))}}const c=((f=t.packages[0])==null?void 0:f.id)??"ts",d=Ee(s,o),l={invoke:(p,g,y)=>d(p,{operation:{id:p},ctx:new Pt,domainArgs:g.domainArgs,envelope:g.envelope,signal:g.signal},y),invokeOptions:{fns:a,schemas:s,createClient:(m=t.packages[0])==null?void 0:m.createClient}},u=Ng(o,r,c,t.operations??[],l);if(u.length>0){const p=Ee({},o),g={fns:{},schemas:{}};for(const y of u){const w=Oe({op:y,transport:"mcp",projection:n}),v=Ag(y.input),b=So(w.mcp.name,{input:v},i[w.mcp.name]);e.bindToolMeta(w.mcp.name,{description:b,inputSchema:v}),e.registerRoute(w,h=>st(w,p,h,g))}}}function jg(t){const e=t.packages[0];return{name:(e==null?void 0:e.id)??"apigen-mcp",version:(e==null?void 0:e.version)??"1.0.0"}}function eo(t,e,n){const i=new Al.Server(n,{capabilities:{tools:{}}});return i.setRequestHandler(Yi.ListToolsRequestSchema,async()=>({tools:t.listTools()})),i.setRequestHandler(Yi.CallToolRequestSchema,async o=>{const{name:r,arguments:s={}}=o.params,a=t.getPlan(r),c=t.getDispatch(r);if(!a||!c)throw new Error(`Unknown tool: ${r}`);const d=s,l=d._meta??{},u={args:d,meta:l},f=Date.now();try{const m=await t.readCall(u,a),p=await c(m);return await t.writeResult(u,p,a),e.info({tool:r,ms:Date.now()-f},`→ ${r}`),u.output}catch(m){throw fe(m)&&m.code!=="internal"?e.error({tool:r,ms:Date.now()-f,code:m.code,message:m.message},`✗ ${r}`):e.error({tool:r,ms:Date.now()-f,err:m},`✗ ${r}`),t.writeError(u,m,a),m}}),i}function Kr(t,e){return async(n,i)=>{try{await e(n,i)}catch(o){t.error({err:o},"mcp http transport handler error"),i.headersSent||i.writeHead(500),i.writableEnded||i.end("Internal Server Error")}}}function qr(t,e){const n=t.signal;if(!n)throw new z("invalid_argument",`apigen mcp transport "${e}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function Hr(t,e,n,i,o,r){return new Promise((s,a)=>{const c=d=>{a(new z("internal",`failed to bind mcp ${i} server on ${n}:${e}: ${d.message}`,{cause:d}))};t.once("error",c),t.listen(e,n,()=>{t.removeListener("error",c),t.on("error",l=>o.error({err:l},"mcp http server error")),o.info({host:n,port:e},`listening on http://${n}:${e}`);const d=()=>{o.info("mcp server shutting down"),t.close(()=>s()),t.closeAllConnections()};if(r.aborted){d();return}r.addEventListener("abort",d,{once:!0})})})}function Tg(t,e,n,i=process.stdin){return new Promise(o=>{let r=!1;function s(l){r||(r=!0,i.off("end",a),i.off("close",a),n==null||n.removeEventListener("abort",c),e.info(l),o())}function a(){s("stdio transport closed (stdin EOF)")}function c(){s("mcp server shutting down")}const d=t.onclose;if(t.onclose=()=>{d==null||d(),s("stdio transport closed")},i.once("end",a),i.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function Og(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,i=t.options.host??"127.0.0.1",o=t.logger??ai();o.info(`mcp server starting (${e})`);const r=new _g;Rg(t,r);const a=r.listTools().map(u=>u.name);o.info({tools:a},`${a.length} tools available`);for(const u of a){const f=r.getPlan(u),m=(f==null?void 0:f.params)??[],p=m.map(g=>`${g.name}${g.required?"":"?"}: ${g.type}`).join(", ");o.info({tool:u,args:{data:m}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}const c=jg(t);if(o.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),e==="stdio"){const u=eo(r,o,c),f=new Nl.StdioServerTransport;return await u.connect(f),o.info("stdio transport ready"),Tg(f,o,t.signal)}if(e==="sse"){const u=qr(t,e),f=new Map,m=zi.createServer(Kr(o,async(p,g)=>{const y=p.url??"";if(p.method==="GET"&&y==="/sse"){const w=eo(r,o,c),v=new Rl.SSEServerTransport("/messages",g);f.set(v.sessionId,v),v.onclose=()=>f.delete(v.sessionId),await w.connect(v)}else if(p.method==="POST"&&y.startsWith("/messages")){const w=new URLSearchParams(y.split("?")[1]??"").get("sessionId"),v=w?f.get(w):void 0;if(!v){g.writeHead(404),g.end("Session not found");return}await v.handlePostMessage(p,g)}else g.writeHead(404),g.end("Not found")}));return Hr(m,n,i,e,o,u)}const d=qr(t,e),l=zi.createServer(Kr(o,async(u,f)=>{const m=eo(r,o,c),p=new jl.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await m.connect(p),await p.handleRequest(u,f)}));return Hr(l,n,i,e,o,d)}const Ig={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(t){return Eg(t)},run(t){return Og(t)}},_i=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Ai=["body","citations","notes","auditTrail","blockers","related","_score","_vector","blocksOut","dependents","partOf","obligations","verdict","spec","similar"],$g=new Set([..._i,...Ai]);function Cg(t){return $g.has(t)}const Ft=["uid","kind","title","status","priority"],le=1e3,Ln=50;function Pg(t,e,n){return{target:t.file,target_type:"path",sha:e,line:t.lines??null,at:n,symbol:t.symbol??null,blastRadius:t.blastRadius??null,revision:t.revision??null}}function Lg(t){const e=t.metadata??{};return{uid:t.uid,file:typeof e.target=="string"?e.target:t.name??"",lines:typeof e.line=="string"?e.line:void 0,context:t.content||void 0,symbol:typeof e.symbol=="string"?e.symbol:void 0,blastRadius:e.blastRadius??void 0,revision:typeof e.revision=="string"?e.revision:void 0,sha:typeof e.sha=="string"?e.sha:"unverified",at:typeof e.at=="string"?e.at:t.tCreated,targetType:typeof e.target_type=="string"?e.target_type:void 0}}function Vr(t){return`${t.file}\0${t.lines??""}\0${t.revision??""}`}function Ug(t){const e=t??{},n=typeof e.target=="string"?e.target:"",i=typeof e.line=="string"?e.line:"",o=typeof e.revision=="string"?e.revision:"";return`${n}\0${i}\0${o}`}function $e(t){const e=t==null?void 0:t.revision;return typeof e=="number"&&Number.isFinite(e)?e:0}function re(t){return $e(t)+1}const Gr="redirectTo";async function pc(t,e){var r,s;const n=(r=e.metadata)==null?void 0:r[Gr];if(typeof n!="string"||n.length===0)return null;const i=await t.getNodeByUid(n);if(!i||i.tInvalid!==void 0)throw new T("redirectTo",`node "${e.uid}" redirects to "${n}", which is not a live node`);const o=(s=i.metadata)==null?void 0:s[Gr];if(typeof o=="string"&&o.length>0)throw new T("redirectTo",`redirect chain longer than one hop: "${e.uid}" -> "${n}" -> "${o}"`);return i}async function mc(t,e,n){const i=await t.getNodeByUid(e);if(i)return i.tInvalid!==void 0||n!==void 0&&i.kind!==n?null:i;if(Rt(e)!=="prefix")return null;const o=await t.transaction(c=>qa(c,e)),r=n!==void 0?o.filter(c=>c.kind===n):o,s=Ha(e,r);if(!s)return null;const a=await t.getNodeByUid(s.uid);return a&&a.tInvalid===void 0?a:null}async function Un(t,e,n){if(Rt(e)==="too-short")throw Va(e);const i=await mc(t,e,n==null?void 0:n.expectedKind);if(!i)throw ze(n==null?void 0:n.expectedKind,e,Rt(e)==="prefix");return i}async function Dg(t,e,n){return Rt(e)==="too-short"?null:mc(t,e,n==null?void 0:n.expectedKind)}async function Dn(t,e){const n=await Un(t,e,{expectedKind:"issue"});if(n.isSuperseded)throw new Ut(e,await hc(t,n));return n}async function gc(t,e){const n=await Un(t,e),o=await pc(t,n)??n;if(!o.isSuperseded)return o;const r=await hc(t,o);if(r===void 0)return o;const s=await t.getNodeByUid(r);return s&&s.tInvalid===void 0?s:o}async function hc(t,e){const n=new Set([e.id]);let i,o=e;for(;;){const s=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return i==null?void 0:i.uid;n.add(s.src);const a=(await t.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return i==null?void 0:i.uid;if(i=a,!a.isSuperseded)return a.uid;o=a}}async function x(t,e,n){if(pe(n)||Dt(n)){const r=await Dg(t,n,{expectedKind:e});if(r)return{id:r.id,uid:r.uid,name:r.name??n,record:r};if(pe(n))return null}const o=(await t.queryNodes({kind:e,name:n,liveOnly:!0,limit:1}))[0];if(o)return{id:o.id,uid:o.uid,name:o.name??n,record:o};if(e==="project"||e==="component"){const r=await t.queryNodes({kind:e,name:n,liveOnly:!1,metadata:{redirectTo:{exists:!0}},limit:5});for(const s of r){const a=await pc(t,s);if(a)return{id:a.id,uid:a.uid,name:a.name??n,record:a}}}return null}async function Ve(t,e,n){var r;if(pe(n)||Dt(n)){const s=await x(t,"component",n);return!s||((r=s.record.metadata)==null?void 0:r.projectUid)!==e?null:s}const o=(await t.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:e}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function me(t,e){return t.getEdges({src:e})}function yc(t,e){return t.getEdges({dst:e})}async function Ge(t,e){var c,d;const i=(c=(await t.getEdges({dst:e,rel:"owns_component"}))[0])==null?void 0:c.src;if(i===void 0)return{};const[o]=await t.getNodesByIds([i]);if(!o)return{};const s=(d=(await t.getEdges({dst:i,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:o};const[a]=await t.getNodesByIds([s]);return{component:o,project:a}}async function wc(t,e){const n=e.expectedKind==="component"&&e.projectUid!==void 0?await Ve(t,e.projectUid,e.ref):await x(t,e.expectedKind,e.ref);if(!n)return;if(await Mg(t,e.rel,e.expectedKind)){const o=await t.getEdges({src:n.id,rel:e.rel});return new Set(o.map(r=>r.dst))}const i=await t.getEdges({dst:n.id,rel:e.rel});return new Set(i.map(o=>o.src))}async function Mg(t,e,n){var r;const o=(r=(await t.queryNodes({kind:"edge_kind",name:e,liveOnly:!0,limit:1}))[0])==null?void 0:r.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function xg(t,e){return(await t.queryNodes({kind:e,liveOnly:!0})).map(i=>i.name).filter(i=>typeof i=="string")}function Fg(t,e){const n=t.length+1,i=e.length+1,o=Array.from({length:n},()=>new Array(i).fill(0));for(let r=0;r<n;r+=1)o[r][0]=r;for(let r=0;r<i;r+=1)o[0][r]=r;for(let r=1;r<n;r+=1)for(let s=1;s<i;s+=1)o[r][s]=t[r-1]===e[s-1]?o[r-1][s-1]:1+Math.min(o[r-1][s],o[r][s-1],o[r-1][s-1]);return o[t.length][e.length]}function Ni(t,e,n=3){const i=Math.max(2,Math.ceil(t.length/2));return e.map(o=>({candidate:o,distance:Fg(t.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=i).sort((o,r)=>o.distance-r.distance).slice(0,n).map(o=>o.candidate)}async function nt(t,e){const n=await xg(t,e.catalogKind),i=new Set,o=[];for(const r of e.refs){const s=await x(t,e.catalogKind,r);if(!s){o.push(r);continue}const a=await t.getEdges({dst:s.id,rel:e.rel});for(const c of a)i.add(c.src)}if(o.length>0){const r=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=o.map(a=>{const c=Ni(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new _e(e.field,`unknown ${e.catalogKind} value(s): ${s} — no live "${e.catalogKind}" catalog row matches (existing ${e.catalogKind} values: ${r})`)}return i}function Bg(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const i=new Set;for(const o of e)n.has(o)&&i.add(o);e=i}return e}const Wr=["evidence","blockers_terminal","relation","all_of","any_of","not"];function gt(t,e,n){for(const i of Object.keys(t))if(!e.includes(i))throw new ve(`${n} predicate has unexpected key "${i}" (allowed: ${e.join(", ")})`)}function Jr(t,e){if(typeof t!="string"||t.trim().length===0)throw new ve(`${e} must be a non-empty string`)}function wn(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new ve('a predicate must be an object with an "op" discriminator');const e=t,n=e.op;if(typeof n!="string")throw new ve('a predicate is missing its "op" discriminator');if(!Wr.includes(n))throw new ve(`unknown op "${n}" — the core is closed to ${Wr.map(i=>`"${i}"`).join(", ")}`);switch(n){case"evidence":{gt(e,["op","kind","min"],n),Jr(e.kind,"evidence.kind");const i=e.min;if(i!==void 0&&(typeof i!="number"||!Number.isInteger(i)||i<1))throw new ve("evidence.min must be an integer >= 1 when present");return}case"blockers_terminal":{gt(e,["op"],n);return}case"relation":{gt(e,["op","type","direction"],n),Jr(e.type,"relation.type");const i=e.direction;if(i!=="in"&&i!=="out")throw new ve('relation.direction must be "in" or "out"');return}case"all_of":case"any_of":{gt(e,["op","of"],n);const i=e.of;if(!Array.isArray(i))throw new ve(`${n}.of must be an array of predicates`);for(const o of i)wn(o);return}case"not":{gt(e,["op","of"],n),wn(e.of);return}}}async function ue(t,e){switch(t.op){case"evidence":return await e.countVerifiedAttestations(t.kind)>=(t.min??1);case"blockers_terminal":return e.blockersAllTerminal();case"relation":return e.relationExists(t.type,t.direction);case"all_of":{if(t.of.length===0)return!0;for(const n of t.of)if(!await ue(n,e))return!1;return!0}case"any_of":{if(t.of.length===0)return!1;for(const n of t.of)if(await ue(n,e))return!0;return!1}case"not":return!await ue(t.of,e)}}function vn(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}function Kg(t){if(t==null||typeof t!="object"||Array.isArray(t))throw new T("applies_to","is required");const e=t,n=e.to;if(typeof n!="string"||n.trim().length===0)throw new T("applies_to.to",'is required — a concrete status name or "*" for any terminal transition; omitting it is a validation error, not a silent default');const i=e.from;if(i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new T("applies_to.from","must be a non-empty string when present");return i===void 0?{to:n}:{to:n,from:i}}function qg(t){if(t===void 0)return;const e=t==null?void 0:t.actors;if(!Array.isArray(e)||e.length===0||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new T("override.actors","must be a non-empty array of non-blank identities when an override is present");return{actors:[...e]}}async function Hg(t,e){try{const n=await se(t,e,{expectedKind:"obligation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new Fa(e):n}}async function Vg(t,e){vn("uid",e.uid),vn("by",e.by),G("by",e.by);const n=Kg(e.applies_to);if(e.on_fail!=="block"&&e.on_fail!=="warn")throw new T("on_fail",'must be "block" or "warn"');const i=qg(e.override);wn(e.requirement);const o=P(),r=e.requirement;return M(t,async s=>{const a=await ae(s,e.uid),c={applies_to:n,requirement:r,on_fail:e.on_fail,...i!==void 0?{override:i}:{}},d=await X(s,{at:o,kind:"obligation",name:e.requirement.op,content:vi(r),metadata:c}),l=await q(s,"has_obligation");return await K(s,{at:o,srcRowid:a.rowid,srcUid:a.uid,srcKind:"issue",dstRowid:d.rowid,dstUid:d.uid,dstKind:"obligation",rel:"has_obligation",rule:l,typePolicy:t.typePolicy}),await U({tx:s,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"issue",actor:e.by,action:"obligated",to:d.uid,note:e.requirement.op,at:o}),{uid:a.uid,obligationUid:d.uid}})}async function Gg(t,e){return vn("obligationUid",e.obligationUid),vn("by",e.by),G("by",e.by),M(t,async n=>{const i=await Hg(n,e.obligationUid),o=P(),r=await n.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_obligation' AND t_invalid IS NULL",[i.rowid]),s={...i.metadata??{},invalidatedReason:"unobligated",invalidatedAt:o},a=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[o,JSON.stringify(s),i.rowid]);if(a.rowsAffected!==1)throw new Error(`unobligate: invalidate UPDATE affected ${a.rowsAffected} rows for uid="${e.obligationUid}", expected exactly 1.`);return r&&await ie(n,{srcRowid:r.src,dstRowid:i.rowid,rel:"has_obligation",reason:"unobligated",at:o}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"obligation",actor:e.by,action:"unobligated",at:o}),{obligationUid:i.uid,invalidated:!0}})}const to=["path","url","query","registry","commit","revision"];function Mn(t){if(typeof t!="string"||t.trim().length===0)throw new Ue(t,"locator is required");const e=t.indexOf(":");if(e<1)throw new Ue(t,`expected one of ${to.map(o=>`"${o}:"`).join(", ")}`);const n=t.slice(0,e),i=t.slice(e+1);if(!to.includes(n))throw new Ue(t,`unknown scheme "${n}" — expected one of ${to.map(o=>`"${o}:"`).join(", ")}`);if(i.trim().length===0)throw new Ue(t,`"${n}:" anchor has an empty body`);if(n==="path"){const o=/^(.*?)(?::(\d+))?$/.exec(i),r=(o==null?void 0:o[1])??i;if(r.trim().length===0)throw new Ue(t,"path anchor names no file");const s=(o==null?void 0:o[2])===void 0?void 0:Number(o[2]);return s===void 0?{scheme:"path",target:r}:{scheme:"path",target:r,line:s}}return{scheme:n,target:i}}function Ke(t,e){var n,i;try{return{status:0,stdout:Hs.execFileSync("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),stderr:""}}catch(o){const r=o;return{status:typeof r.status=="number"?r.status:-1,stdout:((n=r.stdout)==null?void 0:n.toString())??"",stderr:((i=r.stderr)==null?void 0:i.toString())??""}}}function bn(t){const e=Ke(t,["rev-parse","--is-inside-work-tree"]);return e.status===0&&e.stdout.trim()==="true"}function vc(t,e){return Ke(t,["cat-file","-e",`HEAD:${e}`]).status===0}function Wg(t,e,n){const i=Ke(t,["log","--oneline",`--since=${n}`,"--",e]);return i.status===0&&i.stdout.trim().length>0}function Jg(t,e){const n=Ke(t,["cat-file","-p",`HEAD:${e}`]);if(n.status===0)return ke.createHash("sha256").update(n.stdout).digest("hex")}const xo="default_branch_ancestor";function zg(t,e){const n=Ke(t,["symbolic-ref","-q","--short","refs/remotes/origin/HEAD"]);if(n.status===0){const r=n.stdout.trim();if(r.length>0)return r.replace(/^origin\//,"")}const i=Ke(t,["rev-parse","--abbrev-ref","HEAD"]),o=i.status===0?i.stdout.trim():"";if(o.length>0&&o!=="HEAD")return o}function bc(t,e,n){const i=xo;if(typeof e!="string"||e.trim().length===0||typeof t!="string"||t.trim().length===0)return{onDefaultBranch:!1,performed:i};if(!bn(t))return{onDefaultBranch:!1,performed:i};const o=zg(t);return o===void 0?{onDefaultBranch:!1,performed:i}:{onDefaultBranch:Ke(t,["merge-base","--is-ancestor",e.trim(),o]).status===0,performed:i}}async function Yg(t,e,n){return bc(t,e)}function Xg(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e),o=_.relative(n,i);if(!(o===""||o===".."||o.startsWith(`..${_.sep}`)||_.isAbsolute(o)))return o}function Ri(t,e){const n={checked_at:e.now,checked_by:e.by},i=Mn(t.locator);if(i.scheme==="commit"){const s=e.root;if(!s)return{state:"unknown",method:"none",...n,reason:"no project root could be resolved for the subject"};if(!bn(s))return{state:"unknown",method:"none",...n,reason:`no git work tree at "${s}"`};const a=bc(s,i.target);return a.onDefaultBranch?{state:"verified",method:a.performed,...n}:{state:"stale",method:a.performed,...n,reason:`commit "${i.target}" is not an ancestor of the default branch`}}if(i.scheme!=="path")return{state:"unverified",method:"none",...n,reason:`no mechanical checker is wired for "${i.scheme}:" anchors yet`};const o=e.root;if(!o)return{state:"unknown",method:"none",...n,reason:"no project root could be resolved for the subject"};if(!bn(o))return{state:"unknown",method:"none",...n,reason:`no git work tree at "${o}"`};const r=Xg(o,i.target);if(r===void 0)return{state:"unknown",method:"none",...n,reason:`anchor path "${i.target}" lies outside the project root`};if(!vc(o,r))return{state:"stale",method:"exists_at_head",...n,reason:`"${r}" is not present at HEAD`};if(e.sinceISO!==void 0&&Wg(o,r,e.sinceISO)){if(e.full!==!0)return{state:"stale",method:"changed_since",...n,reason:`"${r}" changed since ${e.sinceISO}`};const s=Jg(o,r);return s!==void 0&&s===t.digest.toLowerCase()?{state:"verified",method:"full_resolve",...n}:{state:"stale",method:"full_resolve",...n,reason:`"${r}" content no longer matches the anchor digest`}}return{state:"verified",method:"changed_since",...n}}function xn(t){const e=t??{};return{claimedBy:typeof e.claimedBy=="string"?e.claimedBy:void 0,claimedAt:typeof e.claimedAt=="string"?e.claimedAt:void 0}}function Ec(t,e){return t!==void 0?(Date.parse(e)-Date.parse(t))/6e4:Number.POSITIVE_INFINITY}function Fn(t,e,n){return Ec(t,e)>=n}function Sc(t){let e=!1;for(const n of t)if(n.severity==="block"){if(n.status==="True")return!1;n.status==="Unknown"&&(e=!0)}return e?"unknown":!0}function kc(t){const e=n=>n.severity==="block"?0:1;return[...t].sort((n,i)=>{const o=e(n)-e(i);if(o!==0)return o;const r=n.code.localeCompare(i.code);return r!==0?r:(n.subject??"").localeCompare(i.subject??"")})}const Qg=30;function Zg(t,e){return{type:"Budget",status:"Unknown",severity:"block",code:"Unknown",message:e}}function Fo(t,e=[]){switch(t.op){case"evidence":return e.includes(t.kind)||e.push(t.kind),e;case"all_of":case"any_of":for(const n of t.of)Fo(n,e);return e;case"not":return Fo(t.of,e),e;default:return e}}async function _c(t,e){switch(t.op){case"evidence":case"blockers_terminal":case"relation":return t.op;case"all_of":case"any_of":{for(const n of t.of)if(!await ue(n,e))return _c(n,e);return t.op}case"not":return t.op}}function eh(t){switch(t){case"evidence":return{code:"EvidenceUnverified",type:"Evidence"};case"blockers_terminal":return{code:"BlockedBy",type:"Blocked"};case"relation":return{code:"ReferenceUnresolved",type:"Reference"};default:return{code:"Unknown",type:"Obligation"}}}function th(t,e,n){return{async countVerifiedAttestations(i){const o=await t.getEdges({src:e.id,rel:"attests"});if(o.length===0)return 0;const r=await t.getNodesByIds(o.map(a=>a.dst));let s=0;for(const a of r){const c=a.metadata,d=c==null?void 0:c.claim,l=c==null?void 0:c.check,u=d!==null&&typeof d=="object"?d.kind:void 0,f=l!==null&&typeof l=="object"?l.state:void 0;u===i&&f==="verified"&&(s+=1)}return s},async blockersAllTerminal(){return n.length===0},async relationExists(i,o){return(o==="in"?await t.getEdges({dst:e.id,rel:i}):await t.getEdges({src:e.id,rel:i})).length>0}}}async function nh(t){const e=await t.queryNodes({kind:"status",liveOnly:!0}),n=new Set,i=new Set;for(const o of e)typeof o.name=="string"&&(n.add(o.name),Ae(o)&&i.add(o.name));return{all:n,terminal:i}}function oh(t){var i;const e=(i=t.applies_to)==null?void 0:i.to,n=t.on_fail;return t.requirement===void 0||typeof e!="string"||e.trim().length===0||n!=="block"&&n!=="warn"}async function ih(t,e){var o;const{project:n}=await Ge(t,e),i=(o=n==null?void 0:n.metadata)==null?void 0:o.path;return typeof i=="string"&&i.length>0?i:void 0}async function rh(t,e,n){const i=await t.getEdges({src:e,rel:"attests"});if(i.length===0)return;const o=await t.getNodesByIds(i.map(r=>r.dst));for(const r of o){const s=r.metadata,a=s==null?void 0:s.claim,c=s==null?void 0:s.check,d=s==null?void 0:s.anchor,l=a!==null&&typeof a=="object"?a.kind:void 0,u=c!==null&&typeof c=="object"?c.state:void 0;if(l!==n||u!=="verified")continue;const f={uid:r.uid};if(d!==null&&typeof d=="object"){const p=d.locator,g=d.digest;typeof p=="string"&&typeof g=="string"&&(f.anchor={locator:p,digest:g})}const m=a!==null&&typeof a=="object"?a.asserted_at:void 0;return typeof m=="string"&&(f.assertedAt=m),f}}function sh(t){try{return Mn(t)}catch{return}}async function ah(t,e,n,i,o){var s,a,c;const r=[];for(const d of i){const l=await rh(t,e,d);if((l==null?void 0:l.anchor)===void 0){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:`no stored-verified "${d}" attestation with a readable anchor`});continue}const u=sh(l.anchor.locator);if((u==null?void 0:u.scheme)!=="path"&&(u==null?void 0:u.scheme)!=="commit"){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:`no mechanical checker is wired for "${(u==null?void 0:u.scheme)??"unknown"}:" anchors yet`});continue}const f=await ih(t,e);if(f===void 0){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"no project root could be resolved for the subject"});continue}(s=o.onRung)==null||s.call(o,3),o.maxRung>=4&&u.scheme==="path"&&((a=o.onRung)==null||a.call(o,4)),o.maxRung>=5&&((c=o.onRung)==null||c.call(o,5));const m=Ri(l.anchor,{root:f,...o.maxRung>=4&&l.assertedAt!==void 0?{sinceISO:l.assertedAt}:{},...o.maxRung>=5?{full:!0}:{},now:o.at,by:"verdict"});if(m.state==="stale"){r.push({type:"Evidence",status:"True",severity:n.on_fail,code:"EvidenceStale",subject:l.uid,message:`the "${d}" anchor is stale (${m.reason??m.method})`});continue}m.state==="verified"&&o.maxRung>=4||r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:m.state==="unknown"||m.state==="unverified"?`the "${d}" anchor could not be mechanically resolved (${m.reason??m.method})`:`the "${d}" anchor presence was confirmed but freshness was not re-resolved at this rung`})}return r}async function ch(t,e,n,i,o){let r;try{r=await ue(n.requirement,i)}catch{return[{type:"Obligation",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"the obligation predicate could not be evaluated"}]}if(!r){const a=eh(await _c(n.requirement,i));return[{type:a.type,status:"True",severity:n.on_fail,code:a.code,subject:n.uid,message:`obligation unsatisfied: ${a.code}`}]}const s=Fo(n.requirement);return s.length===0?[]:o.maxRung<3?[{type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"evidence anchor not re-resolved at this rung — actionability is genuinely unknown"}]:ah(t,e.id,n,s,o)}async function dh(t,e,n={}){var d,l;const i=n.maxRung??2,o=n.at??P(),r=n.claimStaleAfterMin??Qg,s=[];(d=n.onRung)==null||d.call(n,1);const a=await $c(t,e.id);for(const u of a)s.push({type:"Blocked",status:"True",severity:"block",code:"BlockedBy",subject:u.uid,message:`blocked by ${u.uid}`});if(i<2)s.push(Zg(void 0,"obligations were not evaluated at this rung"));else{(l=n.onRung)==null||l.call(n,2);const u=await Pc(t,e.id);u.length===0&&s.push({type:"Obligation",status:"True",severity:"warn",code:"MissingObligation",message:"no obligations are declared on this item"});const f=th(t,e,a),m=await nh(t),p={maxRung:i,at:o,...n.onRung?{onRung:n.onRung}:{}};for(const w of u){if(oh(w)){s.push({type:"Obligation",status:"True",severity:w.on_fail==="warn"?"warn":"block",code:"MissingObligation",subject:w.uid,message:"the obligation is malformed and cannot be evaluated"});continue}const v=w.applies_to.to;v==="*"||m.terminal.has(v)||!m.all.has(v)||s.push(...await ch(t,e,w,f,p))}const{claimedBy:g,claimedAt:y}=xn(e.metadata);g!==void 0&&Fn(y,o,r)&&s.push({type:"Claim",status:"True",severity:"warn",code:"ClaimStale",subject:g,message:`claim by "${g}" is stale (threshold ${r}min)`})}const c=kc(s);return{actionable:Sc(c),evaluated_at:o,revision:$e(e.metadata),conditions:c}}const lh="sha256:";function uh(t){return`${lh}${He(t)}`}function fh(t,e){const n=t==null?void 0:t[e];return typeof n=="string"&&n.length>0?n:void 0}function ph(t,e){const n=t==null?void 0:t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}const zr=["normal","force","snapshot"];function mh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_APPEND;if(t===void 0)return"normal";if(zr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_APPEND="${t}" is not a recognized mode (expected ${zr.join(", ")}). 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.`)}const Yr=["normal","raw-kind-only"];function gh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_DISCOVERY;if(t===void 0)return"normal";if(Yr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_DISCOVERY="${t}" is not a recognized mode (expected ${Yr.join(", ")}). 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.`)}function Ac(){return gh()==="raw-kind-only"}async function hh(t,e){const n=await se(t,e,{expectedKind:"issue"}),i=new Set([n.uid]),o=new Set([n.rowid]);let r=n;for(;;){const s=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL LIMIT 1",[r.rowid,"SUPERSEDES"]);if(!s)break;const a=await Q(t,s.src);if(a===null||a.tInvalid!==null||o.has(a.rowid))break;o.add(a.rowid),i.add(a.uid),r=a}return{head:r,chainUids:i}}async function Nc(t){return wc(t,{rel:"has_kind",expectedKind:"kind",ref:"SPEC"})}async function Rc(t){const e=new Map;for(const i of await t.queryNodes({kind:"SPEC",liveOnly:!0}))e.set(i.uid,i);const n=await Nc(t);if(n!==void 0&&n.size>0){const i=await t.getNodesByIds([...n],{liveOnly:!0});for(const o of i)e.set(o.uid,o)}return[...e.values()]}async function yh(t,e,n){const i=[...e];if(i.length===0)return;const o=i.map(()=>"?").join(", "),r=[];let s="kind = 'SPEC'";const a=n===void 0?[]:[...n];a.length>0&&(s=`(kind = 'SPEC' OR rowid IN (${a.map(()=>"?").join(", ")}))`,r.push(...a));const c=await t.executeGet(`SELECT uid FROM node
200
+ WHERE ${s} AND t_invalid IS NULL
201
+ AND json_extract(meta, '$.spec_of') IN (${o})
202
+ ORDER BY json_extract(meta, '$.revision_seq') DESC
203
+ LIMIT 1`,[...r,...i]);return c?await Be(t,c.uid)??void 0:void 0}async function wh(t,e){const n=[],i=new Set;let o=e;for(;o&&!i.has(o.uid);){i.add(o.uid),n.push(o.content);const r=fh(o.metadata,"prev_revision");o=r?await Be(t,r)??void 0:void 0}return n.reverse().join("")}async function vh(t,e){if(typeof e.uid!="string"||e.uid.trim().length===0)throw new T("uid","is required");if(typeof e.fragment!="string")throw new T("fragment","must be a string");if(typeof e.base_revision!="string")throw new T("base_revision","is required");if(typeof e.by!="string"||e.by.trim().length===0)throw new T("by","is required");G("by",e.by);const n=mh(),i=Ac()?void 0:await Nc(t.graph);return M(t,async o=>{const{head:r,chainUids:s}=await hh(o,e.uid),a=P(),c=await yh(o,s,i),d=(c==null?void 0:c.uid)??"",l=c?ph(c.metadata,"revision_seq")??0:0;if(n!=="force"&&e.base_revision!==d)throw new To(e.base_revision,d);const u=l+1,f=(c==null?void 0:c.uid)??null,m=c?await wh(o,c):"",p=n==="snapshot"?`${m}${e.fragment}`:e.fragment,g=`${m}${e.fragment}`,y=uh(g),w=e.anchor??{locator:"",digest:""},v={spec_of:r.uid,revision_seq:u,revision_token:y,prev_revision:f,anchor:w,appended_by:e.by,appended_at:a},b=await X(o,{at:a,kind:"SPEC",content:p,metadata:v});if(await $o(o,r.uid,{spec_revision:b.uid,spec_revision_token:y,spec_revision_seq:u},$e(r.metadata))===null)throw new To(e.base_revision,d);return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"spec-appended",to:b.uid,note:`seq ${u}`,at:a}),{uid:r.uid,spec_revision:b.uid,spec_revision_token:y,revision_seq:u}})}async function jc(t,e){let n;try{n=await gc(t,e)}catch{return}const i=new Set([e,n.uid]);let o=n;const r=new Set([n.id]);for(;;){const a=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(d=>!r.has(d.src));if(!a)break;r.add(a.src);const[c]=await t.getNodesByIds([a.src]);if(!c||c.tInvalid)break;i.add(c.uid),o=c}return{uid:n.uid,chainUids:i}}async function Tc(t,e){var s,a;const n=await jc(t,e);if(!n)return;const o=(Ac()?await t.queryNodes({kind:"SPEC",liveOnly:!0}):await Rc(t)).filter(c=>{var l;const d=(l=c.metadata)==null?void 0:l.spec_of;return typeof d=="string"&&n.chainUids.has(d)});if(o.length===0)return;o.sort((c,d)=>{var l,u;return(typeof((l=d.metadata)==null?void 0:l.revision_seq)=="number"?d.metadata.revision_seq:0)-(typeof((u=c.metadata)==null?void 0:u.revision_seq)=="number"?c.metadata.revision_seq:0)});const r=o[0];return{revision_uid:r.uid,revision_token:typeof((s=r.metadata)==null?void 0:s.revision_token)=="string"?r.metadata.revision_token:"",revision_seq:typeof((a=r.metadata)==null?void 0:a.revision_seq)=="number"?r.metadata.revision_seq:0}}async function Oc(t,e){var r,s,a;const n=await jc(t,e);if(!n)return;const i=await t.getNodeByUid(n.uid);if(!i)return;const o=typeof((r=i.metadata)==null?void 0:r.spec_revision)=="string"?i.metadata.spec_revision:void 0;if(o)return{revision_uid:o,revision_token:typeof((s=i.metadata)==null?void 0:s.spec_revision_token)=="string"?i.metadata.spec_revision_token:"",revision_seq:typeof((a=i.metadata)==null?void 0:a.spec_revision_seq)=="number"?i.metadata.spec_revision_seq:0}}async function bh(t,e){return await Oc(t,e)??await Tc(t,e)}const Xr=["normal","default-fresh"];function Eh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_STALENESS;if(t===void 0)return"normal";if(Xr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_STALENESS="${t}" is not a recognized mode (expected ${Xr.join(", ")}). This variable exists solely for negative-control test runs and must never be set in normal operation.`)}function Qr(t){return t.startsWith("sha256:")?t.slice(7):t}async function Ic(t,e){const n=Eh(),i=await Oc(t,e.uid),o=await Tc(t,e.uid);if(i!==void 0&&o!==void 0&&i.revision_uid!==o.revision_uid)return{current_revision:o.revision_uid,current_token:o.revision_token,state:"stale",method:"none",reason:"revision-drift"};const r=i??o;return r===void 0?{current_revision:"",current_token:"",state:"unknown",method:"none",reason:"no-revision"}:e.token===void 0||e.token===""?n==="default-fresh"?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"token"}:{current_revision:r.revision_uid,current_token:r.revision_token,state:"stale",method:"none",reason:"no-token-supplied"}:e.token===r.revision_token?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"token"}:Qr(e.token)===Qr(r.revision_token)?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"content_hash"}:{current_revision:r.revision_uid,current_token:r.revision_token,state:"stale",method:"token",reason:"older-token"}}function ji(t){if(t){for(const e of t)if(!Cg(e))throw new _e("fields",`unknown field "${e}" — known fields: ${[..._i,...Ai].join(", ")}`)}}function Ae(t){var e;return((e=t==null?void 0:t.metadata)==null?void 0:e.terminal)===!0}async function Sh(t,e,n){const i=n.find(l=>l.rel==="has_kind"&&l.src===e),o=n.find(l=>l.rel==="has_status"&&l.src===e),r=n.find(l=>l.rel==="has_priority"&&l.src===e),s=n.find(l=>l.rel==="authored_by"&&l.src===e),a=[i==null?void 0:i.dst,o==null?void 0:o.dst,r==null?void 0:r.dst,s==null?void 0:s.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await t.getNodesByIds(a),d=new Map(c.map(l=>[l.id,l]));return{kind:i?d.get(i.dst):void 0,status:o?d.get(o.dst):void 0,priority:r?d.get(r.dst):void 0,author:s?d.get(s.dst):void 0}}async function kh(t,e,n){const i=n.filter(r=>r.rel==="has_citation"&&r.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(r=>r.dst))).map(r=>Lg({uid:r.uid,name:r.name,content:r.content,metadata:r.metadata,tCreated:r.tCreated}))}async function _h(t,e,n){const i=n.filter(r=>r.rel==="has_note"&&r.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(r=>r.dst))).map(r=>{var s,a,c;return{uid:r.uid,author:typeof((s=r.metadata)==null?void 0:s.author)=="string"?r.metadata.author:"",text:typeof((a=r.metadata)==null?void 0:a.text)=="string"?r.metadata.text:r.content,at:typeof((c=r.metadata)==null?void 0:c.at)=="string"?r.metadata.at:r.tCreated}})}async function Ah(t,e,n){const i=(n??await me(t,e)).filter(s=>s.rel==="audits"&&s.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,m;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((m=s.metadata)==null?void 0:m.at)=="string"?s.metadata.at:s.tCreated}}).sort((s,a)=>s.at.localeCompare(a.at))}async function $c(t,e){const n=await t.getEdges({dst:e,rel:"blocks"});if(n.length===0)return[];const i=n.map(s=>s.src),o=await t.getNodesByIds(i),r=await Bt(t,o);return o.filter(s=>!Ae(r.get(s.id))).map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=r.get(s.id))==null?void 0:a.name)??""}})}async function Nh(t,e,n){const i=n??await me(t,e),o=await yc(t,e),r=new Map,s=(d,l)=>{r.has(d)||r.set(d,l)};for(const d of i)d.rel==="relates_to"?s(d.dst,"relates_to"):d.rel==="part_of"?s(d.dst,"part_of"):d.rel==="blocks"&&s(d.dst,"blocks");for(const d of o)d.rel==="relates_to"?s(d.src,"relates_to"):d.rel==="part_of"?s(d.src,"part_of"):d.rel==="blocks"&&s(d.src,"blocked_by");if(r.size===0)return[];const a=await t.getNodesByIds([...r.keys()]),c=await Bt(t,a);return a.map(d=>{var l;return{uid:d.uid,title:d.name??"",status:((l=c.get(d.id))==null?void 0:l.name)??"",rel:r.get(d.id)}})}async function Rh(t,e,n){const i=n??await me(t,e),o=await yc(t,e),r=i.filter(p=>p.rel==="similar_to"&&p.src===e),s=o.filter(p=>p.rel==="similar_to"&&p.dst===e),a=[...new Set([...r.map(p=>p.dst),...s.map(p=>p.src)])];if(a.length===0)return{similarTo:[],similarFrom:[]};const c=await t.getNodesByIds(a),d=new Map(c.map(p=>[p.id,p])),l=await Bt(t,c),u=async p=>{var v,b;const g=d.get(p);if(!g)return;const{project:y}=await Ge(t,g.id),w={uid:g.uid,title:g.name??"",status:((v=l.get(g.id))==null?void 0:v.name)??""};return y&&(w.projectUid=y.uid,typeof((b=y.metadata)==null?void 0:b.repoUrl)=="string"&&(w.repoUrl=y.metadata.repoUrl)),w},f=[];for(const p of r){const g=await u(p.dst);g&&f.push(g)}const m=[];for(const p of s){const g=await u(p.src);g&&m.push(g)}return{similarTo:f,similarFrom:m}}async function jh(t,e,n){const i=(n??await me(t,e)).filter(s=>s.rel==="blocks"&&s.src===e);if(i.length===0)return[];const o=await t.getNodesByIds(i.map(s=>s.dst));if(o.length===0)return[];const r=await Bt(t,o);return o.map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=r.get(s.id))==null?void 0:a.name)??"",rel:"blocks"}})}async function Cc(t,e,n){const i=new Set,o=[e];for(;o.length>0;){const r=o.shift(),s=await t.getEdges({src:r,rel:"blocks"});for(const a of s)a.dst===e||i.has(a.dst)||n&&!n.has(a.dst)||(i.add(a.dst),o.push(a.dst))}return i.size}async function Th(t,e,n){var s;const i=(n??await me(t,e)).find(a=>a.rel==="part_of"&&a.src===e);if(!i)return null;const[o]=await t.getNodesByIds([i.dst]);if(!o)return null;const r=await Bt(t,[o]);return{uid:o.uid,title:o.name??"",status:((s=r.get(o.id))==null?void 0:s.name)??"",rel:"part_of"}}async function Pc(t,e,n){const i=(n??await me(t,e)).filter(a=>a.rel==="has_obligation"&&a.src===e);if(i.length===0)return[];const o=await t.getNodesByIds(i.map(a=>a.dst)),r=new Map(o.map(a=>[a.id,a])),s=[];for(const a of i){const c=r.get(a.dst);if(!c)continue;const d=c.metadata,l=d==null?void 0:d.applies_to,u=d==null?void 0:d.requirement,f=d==null?void 0:d.on_fail;if(l===void 0||u===void 0||f===void 0)continue;const m={uid:c.uid,applies_to:l,requirement:u,on_fail:f},p=d==null?void 0:d.override;p!==void 0&&(m.override=p),s.push(m)}return s}async function Bt(t,e){if(e.length===0)return new Map;const n=new Set(e.map(d=>d.id)),i=await t.getEdges({rel:"has_status"}),o=new Map;for(const d of i)n.has(d.src)&&!o.has(d.src)&&o.set(d.src,d.dst);const r=[...new Set(o.values())];if(r.length===0)return new Map;const s=await t.getNodesByIds(r),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}function nn(t,e){if(!e)return t;let n=t;if(e.after!==void 0){const i=n.findIndex(o=>o.uid===e.after);i>=0&&(n=n.slice(i+1))}return e.lastN!==void 0&&(n=n.slice(-e.lastN)),n}async function Lc(t,e,n,i={}){var S,E,N;const o={uid:e.uid},r=k=>n.includes(k),s=r("kind")||r("status")||r("priority")||r("author"),a=r("project")||r("component"),c=r("citations"),d=r("notes"),l=r("auditTrail"),u=r("blockers"),f=r("related"),m=r("blocksOut"),p=r("dependents"),g=r("partOf"),y=r("obligations"),w=r("verdict"),v=r("spec"),b=r("similar"),h=i.outgoingEdges??(s||c||d||l||f||m||g||y||b?await me(t,e.id):void 0);if(r("title")&&(o.title=e.name??""),r("createdAt")&&(o.createdAt=e.tCreated),r("updatedAt")&&(o.updatedAt=e.tValid),r("assignee")){const k=(S=e.metadata)==null?void 0:S.assignee;typeof k=="string"&&(o.assignee=k)}if(r("gitContext")){const k=(E=e.metadata)==null?void 0:E.gitContext;typeof k=="string"&&k.length>0&&(o.gitContext=k)}if(r("closedAt")){const k=(N=e.metadata)==null?void 0:N.closedAt;typeof k=="string"&&(o.closedAt=k)}if(r("body")&&(o.body=e.content),s&&h){const k=await Sh(t,e.id,h);r("kind")&&k.kind&&(o.kind=k.kind.name??""),r("status")&&k.status&&(o.status=k.status.name??""),r("priority")&&k.priority&&(o.priority=k.priority.name??""),r("author")&&k.author&&(o.author=k.author.name??"")}if(a){const{project:k,component:R}=await Ge(t,e.id);r("project")&&k&&(o.project=k.uid),r("component")&&R&&(o.component=R.uid)}if(c&&h&&(o.citations=nn(await kh(t,e.id,h),i.bounds)),d&&h&&(o.notes=await _h(t,e.id,h)),l&&h&&(o.auditTrail=nn(await Ah(t,e.id,h),i.bounds)),u&&(o.blockers=nn(await $c(t,e.id),i.bounds)),f&&h&&(o.related=nn(await Nh(t,e.id,h),i.bounds)),m&&h&&(o.blocksOut=await jh(t,e.id,h)),p&&(o.dependents=await Cc(t,e.id,i.scope)),g&&h&&(o.partOf=await Th(t,e.id,h)),y&&h&&(o.obligations=await Pc(t,e.id,h)),w)try{o.verdict=await dh(t,e,{...i.verdictRung!==void 0?{maxRung:i.verdictRung}:{},...i.onVerdictRung!==void 0?{onRung:i.onVerdictRung}:{}})}catch(k){const R=P();o.verdict={actionable:"unknown",evaluated_at:R,revision:$e(e.metadata),conditions:[{type:"Budget",status:"Unknown",severity:"block",code:"Unknown",message:`verdict derivation failed: ${k instanceof Error?k.message:String(k)}`}]}}if(v){const k=await bh(t,e.uid);k&&(o.spec={spec_revision:k.revision_uid,spec_revision_token:k.revision_token,revision_seq:k.revision_seq},i.specToken!==void 0&&(o.spec.freshness=(await Ic(t,{uid:e.uid,token:i.specToken})).state))}return b&&h&&(o.similar=await Rh(t,e.id,h)),r("_score")&&i.score!==void 0&&(o._score=i.score,i.scoreKind!==void 0&&(o._score_kind=i.scoreKind)),o}async function Tt(t,e,n,i,o,r){const s=new Set(e.map(a=>a.id));return Promise.all(e.map(a=>Lc(t,a,n,{score:i==null?void 0:i.get(a.uid),scoreKind:o==null?void 0:o.get(a.uid),scope:s,...(r==null?void 0:r.rung)!==void 0?{verdictRung:r.rung}:{},...(r==null?void 0:r.onRung)!==void 0?{onVerdictRung:r.onRung}:{}})))}const Oh=.0050125;function Ih(t){if(t===void 0)return Ln;if(!Number.isInteger(t)||t<=0||t>le)throw new _e("limit",`must be a positive integer ≤ ${le}, got ${t}`);return t}async function $h(t,e){const n=new Set;for(const i of e.refs){const o=await wc(t,{rel:e.rel,expectedKind:e.expectedKind,ref:i});if(o)for(const r of o)n.add(r)}return n}async function Ch(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function Ph(t,e){if(e.project===void 0&&e.component===void 0)return;let n,i;if(e.project!==void 0){const c=await x(t,"project",e.project);if(!c)return new Set;n=c.uid;const d=await t.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const u of d){const f=await t.getEdges({src:u.dst,rel:"owns_component"});for(const m of f)l.add(m.dst)}i=l}if(e.component===void 0)return i;const o=n!==void 0?await Ve(t,n,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"}),s=new Set(r.map(c=>c.dst));if(!i)return s;const a=new Set;for(const c of s)i.has(c)&&a.add(c);return a}function Lh(t){var i,o,r,s;const e={};t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until}));const n={};return Object.keys(e).length>0&&(n.metadata=e),(i=t.createdAt)!=null&&i.since&&(n.tCreatedAfter=t.createdAt.since),(o=t.createdAt)!=null&&o.until&&(n.tCreatedBefore=t.createdAt.until),(r=t.updatedAt)!=null&&r.since&&(n.tUpdatedAfter=t.updatedAt.since),(s=t.updatedAt)!=null&&s.until&&(n.tUpdatedBefore=t.updatedAt.until),Object.keys(n).length>0?n:void 0}async function Bn(t,e){if(!e)return;const n=[],i=await Ph(t,e);if(i!==void 0&&n.push(i),e.kind!==void 0){const c=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await nt(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await Ch(t,e.status));else{const c=Array.isArray(e.status)?e.status:[e.status];n.push(await nt(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(e.priority!==void 0){const c=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await nt(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}if(e.author!==void 0&&n.push(await $h(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.similarTo!==void 0){const c=await x(t,"issue",e.similarTo);if(!c)return new Set;const d=await t.getEdges({dst:c.id,rel:"similar_to"});n.push(new Set(d.map(l=>l.src)))}if(e.hasSimilar===!0){const c=await t.getEdges({rel:"similar_to"});n.push(new Set(c.map(d=>d.dst)))}const o=Lh(e);if(n.length===0&&!o)return;let r;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(r=c,r.size===0)return new Set}const s={kind:"issue",liveOnly:!0,isSuperseded:!1,...r?{ids:[...r]}:{},...o},a=await t.queryNodes(s);return new Set(a.map(c=>c.id))}const Uh=4;async function Dh(t,e){if(e.length===0)return[];const n=e.map(s=>s.id),i={ids:n,isSuperseded:!1,limit:n.length},o=await t.queryNodes(i),r=new Set(o.map(s=>s.id));return e.filter(s=>r.has(s.id))}async function Mh(t,e){var s;if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(((s=e.candidateIds)==null?void 0:s.size)===0)return[];const n=e.candidateIds?{ids:[...e.candidateIds]}:{kind:"issue"},i={text:e.text,vec:e.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:e.decayPerHour??Oh}],filters:n},o=[];let r=e.limit;for(let a=0;a<Uh;a++){const c=await t.search.backend.searchRanked(i,r);if(o.length=0,o.push(...await Dh(t.graph,c)),o.length>=e.limit||c.length<r)break;r*=2}return o.slice(0,e.limit)}async function xh(t,e){var h,S;const{graph:n}=t;if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");ji(e.fields);const i=e.fields??Ft,o=Ih(e.limit);let r,s;if(((h=e.filter)==null?void 0:h.anchor)!==void 0)s=await Dn(n,e.filter.anchor),r=`${s.name??""}
204
+ ${s.content}`.trim();else if(((S=e.filter)==null?void 0:S.semantic)!==void 0)r=e.filter.semantic;else throw new T("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await Bn(n,e.filter);if(a&&s&&a.delete(s.id),(a==null?void 0:a.size)===0)return{items:[],hasMore:!1,limit:o};const c=await t.search.embedQuery(r),d=s?o+2:o+1,l=await Mh(t,{text:r,vec:c,candidateIds:a,limit:d}),u=s?l.filter(E=>E.id!==s.id):l,f=u.length>o,m=u.slice(0,o);if(m.length===0)return{items:[],hasMore:!1,limit:o};const p=await n.getNodesByIds(m.map(E=>E.id)),g=new Map(p.map(E=>[E.id,E])),y=m.map(E=>g.get(E.id)).filter(E=>E!==void 0),w=new Map(m.map(E=>{var N;return[(N=g.get(E.id))==null?void 0:N.uid,E.score]}).filter(E=>E[0]!==void 0)),v=new Map([...w.keys()].map(E=>[E,"rrf"]));return{items:await Tt(n,y,i,w,v),hasMore:f,limit:o}}const Fh=new Set(["a","an","and","are","as","at","be","but","by","for","from","has","have","in","is","it","its","of","on","or","that","the","this","to","was","were","will","with"]);function En(t){return t.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0&&!Fh.has(e))}function Bh(t,e){const n=new Set(En(t)),i=new Set(En(e));if(n.size===0||i.size===0)return 0;let o=0;for(const s of n)i.has(s)&&(o+=1);const r=n.size+i.size-o;return r===0?0:o/r}function Zr(t){if(t===void 0)return;const e=t.trim().replace(/\\/g,"/").toLowerCase();if(e.length!==0)return e.endsWith("/")?e.slice(0,-1):e}function Kh(t,e){const n=new Set((t.citationTokens??[]).flatMap(s=>En(s))),i=new Set((e.citationTokens??[]).flatMap(s=>En(s)));for(const s of n)if(i.has(s))return!0;const o=Zr(t.componentPath),r=Zr(e.componentPath);return!!(o&&r&&(o===r||o.startsWith(`${r}/`)||r.startsWith(`${o}/`)))}const qh=5;async function Hh(t,e){return e===void 0?void 0:Bn(t,{project:e})}async function Vh(t,e){var c,d,l,u;if(e===void 0)return;const n=await x(t,"project",e);if(!n)return;const i=typeof((c=n.record.metadata)==null?void 0:c.repoUrl)=="string"&&n.record.metadata.repoUrl.length>0?n.record.metadata.repoUrl:void 0,o=new Set;for(const f of await t.getEdges({src:n.id,rel:"owns_project"})){const[m]=await t.getNodesByIds([f.dst]),p=(d=m==null?void 0:m.metadata)==null?void 0:d.path;typeof p=="string"&&p.length>0&&o.add(p)}const r=[],s=await t.queryNodes({kind:"project",liveOnly:!0});for(const f of s){if(f.uid===n.uid)continue;const m=(l=f.metadata)==null?void 0:l.repoUrl;if(i!==void 0&&typeof m=="string"&&m===i){r.push(f.uid);continue}if(o.size!==0)for(const p of await t.getEdges({src:f.id,rel:"owns_project"})){const[g]=await t.getNodesByIds([p.dst]),y=(u=g==null?void 0:g.metadata)==null?void 0:u.path;if(typeof y=="string"&&y.length>0&&o.has(y)){r.push(f.uid);break}}}if(r.length===0)return;const a=new Set;for(const f of[n.uid,...r]){const m=await Bn(t,{project:f});if(m)for(const p of m)a.add(p)}return a}async function Gh(t,e,n){if(e!=="store-wide")return e==="multi-project"?Vh(t,n):Hh(t,n)}async function Uc(t,e){var s,a;const n=[],i=await t.getEdges({src:e,rel:"has_citation"});if(i.length>0){const c=await t.getNodesByIds(i.map(d=>d.dst));for(const d of c)for(const l of["target","symbol","errorText","blastRadius"]){const u=(s=d.metadata)==null?void 0:s[l];typeof u=="string"&&n.push(u)}}const{component:o}=await Ge(t,e),r=typeof((a=o==null?void 0:o.metadata)==null?void 0:a.path)=="string"?o.metadata.path:void 0;return{citationTokens:n,componentPath:r}}function Wh(t,e){var n;if(t)return{projectUid:t.uid,projectName:t.name??"",...e?{componentUid:e.uid}:{},...typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?{repoUrl:t.metadata.repoUrl}:{}}}async function Dc(t,e){var w,v;const{search:n,graph:i}=t;if(!i)return{candidates:[],degraded:!0,degradedReason:"no-search-backend"};const o=await Gh(i,e.scope,e.projectUid);if((o==null?void 0:o.size)===0)return{candidates:[],degraded:!1};if(o&&e.excludeIds){for(const b of e.excludeIds)o.delete(b);if(o.size===0)return{candidates:[],degraded:!1}}if(!n)return{candidates:[],degraded:!0,degradedReason:"no-search-backend"};if(typeof n.embedQuery!="function")return{candidates:[],degraded:!0,degradedReason:"no-embed-query"};const r=Si(e.title,e.body),s=await n.embedQuery(r),c={text:r,vec:s,signals:[{kind:"text"},{kind:"vec"}],filters:o?{ids:[...o]}:{kind:"issue"}},d=e.limit??qh,l=d*4,u=await n.backend.search(c,l);if(u.length===0)return{candidates:[],degraded:!0,degradedReason:"no-vector-scores"};const f=await i.getNodesByIds(u.map(b=>b.id)),m=new Map(f.map(b=>[b.id,b])),p=[];let g=!1;for(const b of u){const h=m.get(b.id);if(!h||h.tInvalid!==void 0||h.isSuperseded||(w=e.excludeIds)!=null&&w.has(b.id)||o&&!o.has(b.id))continue;const S=b.vecScore;S!==void 0&&(g=!0,p.push({node:h,score:S}))}if(!g)return{candidates:[],degraded:!0,degradedReason:"no-vector-scores"};p.sort((b,h)=>h.score-b.score);const y=[];for(let b=0;b<p.length;b+=1){const{node:h,score:S}=p[b],E=await Ge(i,h.id),N=(v=E.project)==null?void 0:v.uid,k=e.projectUid!==void 0&&N===e.projectUid,R=Wh(E.project,E.component);if(k){if(S<e.sameProjectThreshold)continue;y.push({uid:h.uid,title:h.name??"",score:S,scope:"same-project",provenance:R});continue}if(S<e.crossProjectThreshold)continue;const A=await Uc(i,h.id),O=Bh(e.title,h.name??""),I=Kh({title:e.title,citationTokens:e.citationTokens,componentPath:e.componentPath},{title:h.name??"",citationTokens:A.citationTokens,componentPath:A.componentPath});if(!(O>=e.tokenOverlapMin||I))continue;const L=p[b+1];if(L&&S-L.score<e.margin)continue;const $=["cosine"];O>=e.tokenOverlapMin&&$.push("title-tokens"),I&&$.push("structural"),y.push({uid:h.uid,title:h.name??"",score:S,scope:"cross-project",provenance:R,signals:$})}return y.sort((b,h)=>h.score-b.score),{candidates:y.slice(0,d),degraded:!1}}async function Jh(t,e){return(await Dc(t,e)).candidates}async function zh(t,e){const n=await t.getNodeByUid(e);if(!n||n.tInvalid!==void 0)return;const i=Se({uid:n.uid,rowid:n.id,name:n.name??"",metadata:n.metadata});return{projectUid:n.uid,policy:i}}async function es(t,e,n){var o;if(e.length===0)return[];const i=[];for(const r of e){const s=await t.getNodeByUid(r);if(!s||s.tInvalid!==void 0)continue;const{project:a,component:c}=await Ge(t,s.id),d=n.get(r)??{};i.push({uid:s.uid,title:s.name??"",projectUid:(a==null?void 0:a.uid)??"",projectName:(a==null?void 0:a.name)??"",...c?{componentUid:c.uid}:{},...a&&typeof((o=a.metadata)==null?void 0:o.repoUrl)=="string"?{repoUrl:a.metadata.repoUrl}:{},...d.score!==void 0?{score:d.score}:{},...d.signals!==void 0?{signals:d.signals}:{},...d.linkedTo!==void 0?{linkedTo:d.linkedTo}:{}})}return i}function ts(t){const e=new Map,n=r=>{let s=r;for(;e.get(s)!==s;)s=e.get(s);let a=r;for(;e.get(a)!==s;){const c=e.get(a);e.set(a,s),a=c}return s},i=r=>{e.has(r)||e.set(r,r)};for(const{a:r,b:s}of t){i(r),i(s);const a=n(r),c=n(s);a!==c&&e.set(a,c)}const o=new Map;for(const r of e.keys()){const s=n(r),a=o.get(s);a?a.push(r):o.set(s,[r])}return o}async function Yh(t,e){var y,w;const{graph:n}=t;if(!n)return;const i=e.filter;if(!i||i.project===void 0&&i.component===void 0)return;const o=new Date().toISOString(),r=e.limit??Ln,s=await Bn(n,i),a=new Set;let c=[];if(s&&s.size>0){c=await n.getNodesByIds([...s]);for(const v of c)a.add(v.uid)}let d;if(i.project!==void 0)d=(y=await x(n,"project",i.project))==null?void 0:y.uid;else if(i.component!==void 0){const v=await x(n,"component",i.component),b=(w=v==null?void 0:v.record.metadata)==null?void 0:w.projectUid;typeof b=="string"&&(d=b)}const l=d!==void 0?await zh(n,d):void 0,u=[];let f=0;if(t.search)for(const v of c.slice(0,r)){const b=await Uc(n,v.id),h=await Jh(t,{title:v.name??"",body:v.content??"",scope:"same-project",projectUid:d,sameProjectThreshold:(l==null?void 0:l.policy.dedupeThreshold)??.8,crossProjectThreshold:(l==null?void 0:l.policy.similarityCrossProjectThreshold)??.92,margin:(l==null?void 0:l.policy.similarityCrossProjectMargin)??.05,tokenOverlapMin:(l==null?void 0:l.policy.similarityCrossProjectTokenOverlap)??.5,citationTokens:b.citationTokens,componentPath:b.componentPath,limit:r,excludeIds:new Set([v.id])});f+=1;for(const S of h)u.push({a:v.uid,b:S.uid,score:S.score,...S.signals!==void 0?{signals:S.signals}:{}})}const m=[];if(u.length>0){const v=new Map,b=new Map,h=new Map;for(const E of u)v.set(E.a,Math.max(v.get(E.a)??0,E.score)),v.set(E.b,Math.max(v.get(E.b)??0,E.score)),E.signals!==void 0&&b.set(E.b,E.signals),h.set(E.b,E.a);const S=ts(u);for(const E of S.values()){if(E.length<2)continue;let N=E[0],k=-1;for(const A of E){const O=v.get(A)??0;O>k&&(k=O,N=A)}const R=await es(n,[N,...E.filter(A=>A!==N)],new Map(E.map(A=>[A,{score:v.get(A),signals:b.get(A),linkedTo:h.get(A)}])));m.push({seedUid:N,members:R,linked:!1})}}const p=[];for(const v of await n.getEdges({rel:"similar_to"})){const[b]=await n.getNodesByIds([v.src]),[h]=await n.getNodesByIds([v.dst]);!b||!h||a.size>0&&!a.has(b.uid)&&!a.has(h.uid)||p.push({a:b.uid,b:h.uid})}const g=[];if(p.length>0){const v=new Map;for(const h of p)v.set(h.a,h.b);const b=ts(p);for(const h of b.values()){if(h.length<2)continue;const S=await es(n,h,new Map(h.map(E=>[E,{linkedTo:v.get(E)}])));g.push({seedUid:h[0],members:S,linked:!0})}}return{candidate:m,linked:g,scanned:f,computedAt:o}}function Xh(t){return t.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function Qh(t){const e=typeof t.gitContext=="string"&&t.gitContext.length>0?t.gitContext:void 0,n=t.citations??[];if(e===void 0&&n.length===0)return[];const i=["",e!==void 0?`Citations: [${Xh(e)}]`:"Citations:"];for(const o of n){const r=o.lines?`${o.file}:${o.lines}`:o.file;i.push(`- [${r} sha:${o.sha}]`)}return i}function Zh(t){const e=[];return t.kind!==void 0&&e.push(`kind: ${t.kind}`),t.status!==void 0&&e.push(`status: ${t.status}`),t.priority!==void 0&&e.push(`priority: ${t.priority}`),t.assignee!==void 0&&e.push(`assignee: ${t.assignee}`),t.project!==void 0&&e.push(`project: ${t.project}`),t.component!==void 0&&e.push(`component: ${t.component}`),e.length>0?e.join(" · "):void 0}function ey(t){const e=[`## ${t.title??"(untitled)"}`],n=Zh(t);return n!==void 0&&e.push(n),t.body!==void 0&&t.body.length>0&&e.push("",t.body),e.push(...Qh(t)),e.join(`
205
+ `)}function ty(t){return t.length===0?`_No matching issues._
206
+ `:`${t.map(ey).join(`
202
207
 
203
208
  `)}
204
- `}function Fn(e){var t,n,o,r;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((o=e.metadata)==null?void 0:o.monorepo)=="boolean"?e.metadata.monorepo:void 0,description:typeof((r=e.metadata)==null?void 0:r.description)=="string"?e.metadata.description:void 0}}function Bn(e){var t,n,o;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((o=e.metadata)==null?void 0:o.description)=="string"?e.metadata.description:void 0}}function Kn(e){var t,n,o;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((o=e.metadata)==null?void 0:o.componentUid)=="string"?e.metadata.componentUid:""}}async function Ip(e,t){if((t==null?void 0:t.project)!==void 0){const o=await K(e,"project",t.project);return o?[Fn(o.record)]:[]}return(await e.queryNodes({kind:"project",liveOnly:!0})).map(Fn)}async function $p(e,t){if((t==null?void 0:t.project)!==void 0){const o=await K(e,"project",t.project);return o?(await e.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:o.uid}}})).map(Bn):[]}return(await e.queryNodes({kind:"component",liveOnly:!0})).map(Bn)}async function Cp(e,t){if((t==null?void 0:t.component)!==void 0){const o=t.project!==void 0?await(async()=>{const i=await K(e,"project",t.project);return i?qe(e,i.uid,t.component):null})():await K(e,"component",t.component);return o?(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:o.uid}}})).map(Kn):[]}return(await e.queryNodes({kind:"location",liveOnly:!0})).map(Kn)}async function cn(e,t){var d,l,u,f,m,p,g,b,h;if(t.registry==="project"){const y=await K(e,"project",t.name);if(!y)throw new W("project",t.name);const w=await e.getEdges({src:y.id,rel:"owns_project"}),v=w.length>0?await e.getNodesByIds(w.map(_=>_.dst),{liveOnly:!0}):[],E=(await Promise.all(v.map(_=>e.getEdges({src:_.id,rel:"has_location"})))).flatMap(_=>_.map(N=>N.dst)),A=E.length>0?await e.getNodesByIds(E,{liveOnly:!0}):[];return{...Fn(y.record),components:v.map(_=>{var N;return{name:_.name??"",path:typeof((N=_.metadata)==null?void 0:N.path)=="string"?_.metadata.path:void 0}}),locations:A.map(_=>{var N,j;return{locType:typeof((N=_.metadata)==null?void 0:N.locType)=="string"?_.metadata.locType:"path",value:typeof((j=_.metadata)==null?void 0:j.value)=="string"?_.metadata.value:_.name??""}})}}if(t.registry==="component"){const y=(d=t.filter)==null?void 0:d.project,w=y!==void 0?await(async()=>{const N=await K(e,"project",y);if(!N)throw new W("project",y);return qe(e,N.uid,t.name)})():await K(e,"component",t.name);if(!w)throw new W("component",t.name);const v=typeof((l=w.record.metadata)==null?void 0:l.projectUid)=="string"?w.record.metadata.projectUid:void 0,S=v?await e.getNodeByUid(v):null,E=S&&!S.tInvalid?S:null,A=await e.getEdges({src:w.id,rel:"has_location"}),_=A.length>0?await e.getNodesByIds(A.map(N=>N.dst),{liveOnly:!0}):[];return{...Bn(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:_.map(N=>{var j,O;return{locType:typeof((j=N.metadata)==null?void 0:j.locType)=="string"?N.metadata.locType:"path",value:typeof((O=N.metadata)==null?void 0:O.value)=="string"?N.metadata.value:N.name??""}})}}if(!pe(t.name)&&!qt(t.name))throw new T("name","a location has no name — pass its uid");const n=await Cs(e,t.name,{expectedKind:"location"}),o=typeof((m=n.metadata)==null?void 0:m.componentUid)=="string"?n.metadata.componentUid:void 0,r=o?await e.getNodeByUid(o):null,i=r&&!r.tInvalid?r: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{...Kn(n),component:{name:(i==null?void 0:i.name)??"",path:typeof((g=i==null?void 0:i.metadata)==null?void 0:g.path)=="string"?i.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((b=c==null?void 0:c.metadata)==null?void 0:b.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 Pp(e){try{return new URL(e),!0}catch{return!1}}function xp(e){return Pp(e)?"url":e.includes("/")||e.includes(".")||e.startsWith("~")?"path":"tool"}async function Lp(e,t){var f,m,p,g,b,h;const n=xp(t);let o=(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:t}},limit:1}))[0],r,i=!1;if(!o&&n==="path"){const y=await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:re+1});i=y.length>re;const v=(i?y.slice(0,re):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)});v&&(o=v,r="matched by path suffix/prefix fallback, not an exact value match")}if(!o)throw new W("location",i?`${t} (path suffix/prefix fallback scanned only the first ${re} live path locations; a match may exist beyond this cap)`:t);const s=typeof((f=o.metadata)==null?void 0:f.componentUid)=="string"?o.metadata.componentUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new W("component",s??"(unresolved)");const d=typeof((m=c.metadata)==null?void 0:m.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((g=u.metadata)==null?void 0:g.repoUrl)=="string"?u.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((b=c.metadata)==null?void 0:b.path)=="string"?c.metadata.path:void 0},location:{uid:o.uid,locType:n,value:typeof((h=o.metadata)==null?void 0:h.value)=="string"?o.metadata.value:t},hint:r}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:o.uid,locType:n,value:t},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function at(e){if(e===void 0)return Is;if(!Number.isInteger(e)||e<=0||e>re)throw new Oe("limit",`must be a positive integer ≤ ${re}, got ${e}`);return e}function Up(e){var t,n;if(e.after!==void 0){if(e.sort!==void 0)throw new T("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 T("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 Dp(e,t){const n=new Set;for(const o of t.refs){const r=await K(e,t.expectedKind,o);if(!r)continue;const i=await e.getEdges({dst:r.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function Ms(e,t){const o=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),r=new Set;for(const i of o){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)r.add(a.src)}return r}async function ct(e,t){if(!t)return;const n=[];let o;if(t.project!==void 0){const r=await K(e,"project",t.project);if(!r)return new Set;o=r.uid;const i=await e.getEdges({src:r.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 r=o!==void 0?await qe(e,o,t.component):await K(e,"component",t.component);if(!r)return new Set;const i=await e.getEdges({src:r.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const r=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Le(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:r}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await Ms(e,t.status));else{const r=Array.isArray(t.status)?t.status:[t.status];n.push(await Le(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:r}))}if(t.priority!==void 0){const r=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Le(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:r}))}if(t.author!==void 0&&n.push(await Dp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]})),t.plan!==void 0){const r=await K(e,"issue",t.plan);if(!r)return new Set;const i=await e.getEdges({dst:r.id,rel:"part_of"});n.push(new Set(i.map(s=>s.src)))}if(t.projectPath!==void 0){const r=await e.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:t.projectPath}}});if(r.length===0)return new Set;const i=new Set;for(const s of r){const a=await e.getEdges({src:s.id,rel:"owns_component"});for(const c of a)i.add(c.dst)}n.push(i)}return dp(n)}function Mp(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 Fp(e){if(e==="created")return"tCreated";if(e==="updated")return"tValid"}async function Bp(e,t,n){const o=await Promise.all(t.map(d=>e.getEdges({src:d.id,rel:"has_priority"}))),r=[...new Set(o.flatMap(d=>d.map(l=>l.dst)))],i=r.length>0?await e.getNodesByIds(r):[],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=o[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 Kp(e,t){var w,v,S,E,A,_,N,j,O,I,C,q;const{graph:n}=e;Up(t),Eo(t.fields);const o=at(t.limit),r=t.fields??st;if((t.sort==="relevance"||t.sort==="textMatch")&&((w=t.filter)==null?void 0:w.grep)===void 0&&((v=t.filter)==null?void 0:v.semantic)===void 0)throw new Oe("sort",`"${t.sort}" requires filter.grep or filter.semantic`);const i=await ct(n,t.filter);if((i==null?void 0:i.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:o}};const s=Mp(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}:{},...(_=(A=t.filter)==null?void 0:A.createdAt)!=null&&_.since?{tCreatedAfter:t.filter.createdAt.since}:{},...(j=(N=t.filter)==null?void 0:N.createdAt)!=null&&j.until?{tCreatedBefore:t.filter.createdAt.until}:{},...(I=(O=t.filter)==null?void 0:O.updatedAt)!=null&&I.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 M,P;const X=t.offset??0,Yt=X+o;if(a!==void 0){const H=await n.searchNodes(a,{limit:Yt,filter:d});P=new Set(H.map(ce=>ce.id))}if(c!==void 0){if(!e.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const ce={vec:await e.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Do=await e.search.backend.searchRanked(ce,Yt);M=P?Do.filter(za=>P.has(za.id)):Do}else P&&(M=(await n.searchNodes(a,{limit:Yt,filter:d})).map(ce=>({id:ce.id,score:ce.score,fields:{}})));const Xt=(M??[]).map(H=>H.id).slice(X,X+o),Ha=Xt.length>0?await n.getNodesByIds(Xt):[],Lo=new Map(Ha.map(H=>[H.id,H])),Va=Xt.map(H=>Lo.get(H)).filter(H=>H!==void 0),Ga=new Map((M??[]).map(H=>{var ce;return[(ce=Lo.get(H.id))==null?void 0:ce.uid,H.score]}).filter(H=>H[0]!==void 0)),Uo=await tt(n,Va,r,Ga),Qt=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Zt=Uo.length,Wa=Zt<Math.min(Qt-X,o),Ja=X+Zt<Qt;return{page:{items:Uo,hasMore:Ja},meta:{total:Qt,returned:Zt,limit:o,...t.offset!==void 0?{offset:t.offset}:{},...Wa?{truncated:!0}:{}}}}const l=Fp(t.sort),u={...d,limit:o+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 Bp(n,f,t.direction??"asc"));const m=f.length>o,p=m?f.slice(0,o):f,g=m?String(p[p.length-1].id):void 0,b=await tt(n,p,r),h=await n.countNodes(d),y=t.after===void 0?t.offset:void 0;return{page:{items:b,nextCursor:g,hasMore:m},meta:{total:h,returned:b.length,limit:o,...y!==void 0?{offset:y}:{}}}}async function qp(e,t){var y;const{graph:n}=e,o=at(t.limit),r=t.fields??st,i=await Ms(n,"open"),s=await ct(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 v=l.get(w.dst);v?v.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)),m=await n.getEdges({rel:"has_status"}),p=new Map;for(const w of m)p.has(w.src)||p.set(w.src,w.dst);const g=[...new Set(p.values())],b=new Map((g.length>0?await n.getNodesByIds(g):[]).map(w=>[w.id,w])),h=[];for(const w of c){if(h.length>=o)break;if(typeof((y=w.metadata)==null?void 0:y.claimedBy)=="string")continue;const v=(l.get(w.id)??[]).filter(E=>f.has(E));if(v.length===0){h.push(w);continue}v.every(E=>{const A=p.get(E);return A!==void 0&&Te(b.get(A))})&&h.push(w)}return tt(n,h,r)}async function Hp(e,t){const{graph:n}=e,o=at(t.limit),r=t.fields??st,i=t.staleAfterMin??30,s=new Date(Date.now()-i*6e4).toISOString(),a=await ct(n,t.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:o},d=await n.queryNodes(c);return tt(n,d,r)}const Vp=["blocks","relates_to","part_of"];function Gp(e){return Vp.includes(e)}async function Wp(e,t){var u;const{graph:n}=e,o=at(t.limit??re),r=await ct(n,t.filter),i={kind:"issue",isSuperseded:!1,...r?{ids:[...r]}:{},limit:o},s=await n.queryNodes(i),a=new Set(s.map(f=>f.id)),c=await Jp(n,s),d=s.map(f=>{var m;return{uid:f.uid,title:f.name??"",status:((m=c.get(f.id))==null?void 0:m.name)??""}}),l=[];for(const f of s){const m=await Ke(n,f.id);for(const p of m)if(Gp(p.rel)&&a.has(p.dst)){const g=(u=(await n.getNodesByIds([p.dst]))[0])==null?void 0:u.uid;g&&l.push({from:f.uid,to:g,rel:p.rel})}}return{nodes:d,edges:l}}async function Jp(e,t){const n=await Promise.all(t.map(a=>e.getEdges({src:a.id,rel:"has_status"}))),o=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],r=o.length>0?await e.getNodesByIds(o):[],i=new Map(r.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 zp(e,t){const{graph:n}=e,o=at(t.limit??re),r=await ct(n,t.filter),i={kind:"issue",isSuperseded:!1,...r?{ids:[...r]}:{},limit:o},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 g=await n.getEdges({src:p.id,rel:"blocks"});for(const b of g)a.has(b.dst)&&(l.get(p.id).push(b.dst),d.set(b.dst,(d.get(b.dst)??0)+1))}const u=s.filter(p=>(d.get(p.id)??0)===0).map(p=>p.id),f=[],m=new Map(d);for(;u.length>0;){const p=u.shift();f.push(p);for(const g of l.get(p)??[]){const b=(m.get(g)??0)-1;m.set(g,b),b===0&&u.push(g)}}return f.length!==s.length?{ok:!1,cycle:s.filter(g=>!f.includes(g.id)).map(g=>c.get(g.id))}:{ok:!0,order:f.map(p=>c.get(p))}}async function Yp(e,t){var s;const{graph:n}=e,o=t.overlapAxis,r=t.overlapUids;if(!o)throw new T("overlapAxis",'required for view:"overlap"');if(!r||r.length<2)throw new T("overlapUids","requires at least 2 uids to detect an overlap");const i=new Map;for(const a of r){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(o==="file"){const m=(await Ke(n,c.id)).filter(g=>g.rel==="has_citation"),p=m.length>0?await n.getNodesByIds(m.map(g=>g.dst)):[];for(const g of p){const b=typeof((s=g.metadata)==null?void 0:s.target)=="string"?g.metadata.target:void 0;b&&(i.has(b)||i.set(b,new Set),i.get(b).add(a))}continue}if(o==="author"){const m=(await Ke(n,c.id)).find(g=>g.rel==="authored_by");if(!m)continue;const[p]=await n.getNodesByIds([m.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=o==="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 Xp(e,t){return Ip(e.graph,t.filter)}async function Qp(e,t){return $p(e.graph,t.filter)}async function Zp(e,t){return Cp(e.graph,t.filter)}function em(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 tm(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 T("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 T("text","must not be blank");const n=e.search!==void 0&&e.spacePopulated===!0,{text:o,...r}=t;return{...r,sort:r.sort??(n?"relevance":"textMatch"),filter:{...r.filter,...n?{semantic:o}:{grep:o}}}}async function nm(e,t){const n=t.view??"list";switch(n){case"list":{const{page:o,meta:r}=await Kp(e,t);return{result:{view:"list",...o},meta:r}}case"ready":return{result:{view:"ready",items:await qp(e,t)}};case"graph":return{result:{view:"graph",graph:await Wp(e,t)}};case"order":return{result:{view:"order",order:await zp(e,t)}};case"stale":return{result:{view:"stale",items:await Hp(e,t)}};case"similar":return{result:{view:"similar",items:await _p(e,t)}};case"overlap":return{result:{view:"overlap",groups:await Yp(e,t)}};case"projects":return{result:{view:"projects",items:await Xp(e,t)}};case"components":return{result:{view:"components",items:await Qp(e,t)}};case"locations":return{result:{view:"locations",items:await Zp(e,t)}};default:{const o=n;throw new Oe("view",`unknown view "${o}"`)}}}const om=["list","ready","stale","similar"];async function rm(e,t={}){var a;await((a=e.assertVocabulary)==null?void 0:a.call(e));const n=tm(e,t),o=await nm(e,n);if(n.format!=="markdown")return o;const{result:r}=o,{view:i}=r;if(i!=="list"&&i!=="ready"&&i!=="stale"&&i!=="similar")throw new T("format",`"markdown" is only supported for view:${om.map(c=>`"${c}"`).join("/")} — view:"${i}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=r.items;return{result:{view:i,format:"markdown",markdown:Tp(s)},meta:o.meta}}const Fs=["not_found","item_not_found","ambiguous_reference","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],im=new Set(Fs);function Bs(e){return typeof e=="string"&&im.has(e)}const ko={not_found:4,item_not_found:1,ambiguous_reference:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function sm(e){return e.ok===!0}function am(e){return e.ok===!1&&typeof e.error=="object"&&e.error!==null&&Bs(e.error.code)}function Ao(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 ie(e,t,n){const o={code:e,message:t},r={...n??{}};return e==="store_busy"&&r.retryable===void 0&&(r.retryable=!0),Object.keys(r).length>0&&(o.details=r),{ok:!1,error:o}}function we(e){return e.ok?0:ko[e.error.code]}function Ks(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 o=n.code;return typeof o=="string"&&o in ko}class qs 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 cm extends Error{constructor(t,n,o,r){super(`backlog embedding: ${t} produced a ${r}-dimensional vector but space "${n}" is ${o}-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=o,this.actual=r,this.name="PermanentEmbeddingDimensionError"}}let xr=!1,Lr=!1,Ur=!1;const Ct=new WeakMap;async function dm(e,t){const n=e;return typeof n.hasVectors!="function"?(xr||(xr=!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 Dr(e){try{return{mod:await import(e)}}catch(t){return{err:t}}}const vt=e=>e instanceof Error?e.message:String(e),We=new WeakMap;async function lm(e,t,n,o=i=>console.error(i),r){const i=We.get(e);if(i)return i;const s=pm(e,t,n,o,r);We.set(e,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?We.delete(e):Ct.set(e,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw We.delete(e),Ct.delete(e),a}}function um(e){const t=Ct.get(e);if(t)return{present:!0,embedding:t.embedding,search:t.search}}function fm(e){We.delete(e),Ct.delete(e)}function Mr(e){return e&&e.length>0?e.join(", "):"(no config layer files found on disk)"}async function pm(e,t,n,o,r){var p;if(!(n!=null&&n.enabled))return(r==null?void 0:r.configuredEnabled)===!0?Ur||(Ur=!0,o(`backlog: embedding.enabled is TRUE in the on-disk config but this process is still running with it DISABLED (startup configHash ${r.startupHash??"unknown"}, on-disk configHash ${r.configuredHash??"unknown"}). The next semantic verb adopts it without a restart; if it does not, restart the process. Resolved config layers: ${Mr(r.configPaths)}.`)):Lr||(Lr=!0,o(`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: ${Mr(r==null?void 0:r.configPaths)}.`)),{};const i=(p=e.capabilities)==null?void 0:p.nativeVectors;if(i!==!0)return o(`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([Dr("@adhd/sox-vector-store"),Dr("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const g=[..."err"in s?[`@adhd/sox-vector-store (${vt(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${vt(a.err)})`]:[]];return o(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${g.join("; ")}. Continuing WITHOUT semantic search.`),{}}let c;try{c=await a.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(g){return o(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${vt(g)}. 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(g){return o(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${vt(g)}. Continuing WITHOUT semantic search.`),{}}const u=(g,b)=>{if(g.length!==d.dim)throw new cm(b,d.modelId,d.dim,g.length);return g},f={modelId:d.modelId,async embedDocument(g){return u(await c.embedSingle(g,"document"),"embedDocument")},async upsertVector(g,b){await l.upsert(g,u(b,"upsertVector"),d)},async deleteVector(g){await l.delete(g,d.modelId)}};return{search:{backend:new oc.StoreSearchBackend(l,t),async embedQuery(g){return u(await c.embedSingle(g,"query"),"embedQuery")},async spacePopulated(){return dm(l,d.modelId)}},embedding:f}}const Fr=["status","priority"],mm="run the terminal-flag repair — `write/catalog-repair.ts`'s `planTerminalBackfill` + `applyTerminalBackfill` — which sets `metadata.terminal = true` on each named status row.",gm="run the case-fragment repair — `write/catalog-merge.ts`'s `planCaseFragmentMerge` + `applyCaseFragmentMerge` — which collapses each folded group to one live row, re-points its edges, and records the merged-away spelling as an alias.";function hm(e){const t=e.filter(r=>r.kind==="unflagged-terminal"),n=e.filter(r=>r.kind==="case-fragment-duplicate"),o=["backlog: status/priority catalog invariant violated (ADR-0002: correct the source, never work around it)."];if(o.push(" This is a NAMED check: it reports the rows below and the repair. It never gates reads or unrelated writes — a drifted catalog is a bounded data problem, never an availability outage — and neither condition may be papered over with a read-time fallback."),t.length>0){o.push(` unflagged-terminal (${t.length}): a live status row whose name is a reserved terminal name but whose metadata.terminal is not true reads as NON-terminal, so closed items are returned under an open filter.`);for(const r of t)o.push(` - status "${r.name}" (uid ${r.uid})`);o.push(` remediation: ${mm}`)}if(n.length>0){o.push(` case-fragment-duplicate (${n.length}): two or more live rows of the SAME catalog kind share a case-folded name, so a name-keyed reader splits one value across two rows.`);for(const r of n){const i=r.names.map((s,a)=>`"${s}" (uid ${r.uids[a]})`).join(", ");o.push(` - fold "${r.fold}": ${i}`)}o.push(` remediation: ${gm}`)}return o.join(`
205
- `)}class Hs extends Error{constructor(t){super(hm(t)),this.violations=t,this.name="CatalogInvariantError"}}const ym=new Set([...Ht].map(e=>Y(e)));function wm(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}async function vm(e){var o;const{rows:t}=await e.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind IN (?, ?) AND t_invalid IS NULL ORDER BY kind ASC, rowid ASC",[...Fr]),n=[];for(const r of t){if(r.kind!=="status")continue;const i=Y(r.name??"");ym.has(i)&&((o=wm(r.meta))==null?void 0:o.terminal)!==!0&&n.push({kind:"unflagged-terminal",name:r.name??"",uid:r.uid})}for(const r of Fr){const i=new Map;for(const s of t){if(s.kind!==r)continue;const a=Y(s.name??""),c=i.get(a);c?c.push(s):i.set(a,[s])}for(const[s,a]of i)a.length<2||n.push({kind:"case-fragment-duplicate",fold:s,names:a.map(c=>c.name??""),uids:a.map(c=>c.uid)})}return n}async function Vs(e){const t=await vm(e);if(t.length!==0)throw new Hs(t)}async function bm(e,t){Eo(t.fields);const n=t.fields??st,o=await So(e,t.uid);return Us(e,o,n)}function Sm(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}const Em=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function Gs(e,t,n){if(e){for(const o of Em)if(e[o]!==void 0&&!t.has(o))throw new T(`filter.${o}`,`not supported by ${n} — this view scopes by ${[...t].join("/")} only`)}}async function Ws(e,t){const n=new Set;for(const o of t.refs){const r=await K(e,t.expectedKind,o);if(!r)continue;const i=await e.getEdges({dst:r.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function km(e,t){const o=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),r=new Set;for(const i of o){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)r.add(a.src)}return r}function Js(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const o=new Set;for(const r of t)n.has(r)&&o.add(r);t=o}return t}async function zs(e,t){if(!t)return;const n=[];let o;if(t.project!==void 0){const r=await K(e,"project",t.project);if(!r)return new Set;o=r.uid;const i=await e.getEdges({src:r.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 r=o!==void 0?await qe(e,o,t.component):await K(e,"component",t.component);if(!r)return new Set;const i=await e.getEdges({src:r.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const r=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ws(e,{rel:"has_kind",expectedKind:"kind",refs:r}))}return Js(n)}const Am=new Set(["project","component","kind","status"]);async function _m(e,t){const n=t??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await km(e,n),scope:n};const o=Array.isArray(n)?n:[n];return{candidates:await Ws(e,{rel:"has_status",expectedKind:"status",refs:o}),scope:n}}async function jm(e,t={}){var f,m,p;const{graph:n}=e;Gs(t.filter,Am,"priorityMatrix");const o=await zs(n,t.filter);if((o==null?void 0:o.size)===0)return{rows:[],unassigned:0,statusScope:((f=t.filter)==null?void 0:f.status)??"open"};const{candidates:r,scope:i}=await _m(n,(m=t.filter)==null?void 0:m.status),s=Js([o,r].filter(g=>g!==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(g=>g.id)),c=await n.queryNodes({kind:"priority",liveOnly:!0}),d=new Set,l=[];for(const g of c){const b=await n.getEdges({dst:g.id,rel:"has_priority"});let h=0;for(const w of b)a.has(w.src)&&(h+=1,d.add(w.src));const y=typeof((p=g.metadata)==null?void 0:p.rank)=="number"?g.metadata.rank:void 0;l.push({priority:g.name??"",priorityUid:g.uid,rank:y,count:h})}l.sort((g,b)=>(g.rank??Number.MAX_SAFE_INTEGER)-(b.rank??Number.MAX_SAFE_INTEGER));let u=0;for(const g of a)d.has(g)||(u+=1);return{rows:l,unassigned:u,statusScope:i}}async function Nm(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"}))),o=new Map;n.forEach((c,d)=>{const l=c[0];l&&o.set(t[d].id,l.dst)});const r=[...new Set(o.values())];if(r.length===0)return new Map;const i=await e.getNodesByIds(r),s=new Map(i.map(c=>[c.id,c])),a=new Map;for(const[c,d]of o){const l=s.get(d);l&&a.set(c,l)}return a}async function Rm(e,t){const{graph:n}=e,o=await So(n,t.uid),i=(await n.getSubgraph(o.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==o.id&&l.kind==="issue"&&!l.tInvalid),s=await Nm(n,i);let a=0,c=0;const d=[];for(const l of i)Te(s.get(l.id))?c+=1:(a+=1,d.push(l.uid));return{uid:o.uid,childrenTotal:i.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:d}}const Om=new Set(["project","component","kind"]);function Tm(e,t,n){var i;const o=e.filter(s=>s.to!==void 0);if(o.length===0)return n;let r;for(const s of o)if(s.at<=t)r=s;else break;return r?r.to:(i=o[0])==null?void 0:i.from}async function Im(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 o=[...new Set(n.values())],r=new Map((o.length>0?await e.getNodesByIds(o):[]).map(f=>[f.id,f])),i=new Map;for(const[f,m]of n)i.set(f,(u=r.get(m))==null?void 0:u.name);const s=await e.getEdges({rel:"audits"}),a=new Map;for(const f of s){const m=a.get(f.src);m?m.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,m]of a){const p=m.map(g=>d.get(g)).filter(g=>g!==void 0).map(g=>{var b,h,y,w,v,S,E;return{uid:g.uid,actor:typeof((b=g.metadata)==null?void 0:b.actor)=="string"?g.metadata.actor:"",action:typeof((h=g.metadata)==null?void 0:h.action)=="string"?g.metadata.action:g.name??"",from:typeof((y=g.metadata)==null?void 0:y.from)=="string"?g.metadata.from:void 0,to:typeof((w=g.metadata)==null?void 0:w.to)=="string"?g.metadata.to:void 0,note:typeof((v=g.metadata)==null?void 0:v.note)=="string"?g.metadata.note:void 0,sha:typeof((S=g.metadata)==null?void 0:S.sha)=="string"?g.metadata.sha:"",at:typeof((E=g.metadata)==null?void 0:E.at)=="string"?g.metadata.at:g.tCreated}}).sort((g,b)=>g.at.localeCompare(b.at));l.set(f,p)}return{currentStatusNameByIssue:i,auditTrailByIssue:l}}async function $m(e,t){var u;const{graph:n}=e;if(Gs(t.filter,Om,"openCurve"),t.at.length===0)throw new T("at","requires at least one ISO-8601 instant to sample");const o=t.at.map(f=>{const m=new Date(f);if(Number.isNaN(m.getTime()))throw new T("at",`"${f}" is not a parsable ISO-8601 instant`);return m.toISOString()}),r=await zs(n,t.filter);if((r==null?void 0:r.size)===0)return{points:o.map(f=>({at:f,existed:0,open:0,closed:0}))};const i=await n.queryNodes({kind:"status",liveOnly:!0}),s=new Map;for(const f of i){const m=Te(f);f.name&&s.set(f.name,m);for(const p of Sm((u=f.metadata)==null?void 0:u.aliases))s.set(p,m)}const{currentStatusNameByIssue:a,auditTrailByIssue:c}=await Im(n),d=new Map;for(const f of await n.getEdges({rel:"SUPERSEDES"})){const m=d.get(f.dst);(m===void 0||f.tCreated<m)&&d.set(f.dst,f.tCreated)}const l=[];for(const f of o){const m={kind:"issue",validAt:f,liveOnly:!1,...r?{ids:[...r]}:{}},p=await n.queryNodes(m);let g=0,b=0;for(const h of p){const y=d.get(h.id);if(y!==void 0&&y<=f)continue;b+=1;const w=a.get(h.id),v=c.get(h.id)??[],S=Tm(v,f,w);(S!==void 0?s.get(S)??!1:!1)||(g+=1)}l.push({at:f,existed:b,open:g,closed:b-g})}return{points:l}}const Br=["abort","force","comment"];function Ve(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}const Kr=512;function Ys(e){if(typeof e=="string"&&e.length>Kr)throw new T("gitContext",`must be at most ${Kr} characters, got ${e.length}`)}async function Cm(e,t,n){if(!Vt(e))return"unverified";try{const{accepted:o,candidate:r}=await Yi(e.metadata.path,t,n);if(!o)return"unverified";const i=await Lt.readFile(r);return me.createHash("sha256").update(i).digest("hex")}catch(o){if(lo(o))return"unverified";throw os(o,t)}}function qr(e,t,n){if(e.length>0&&!e.includes(n))throw new T(t,`"${n}" is not in this project's allowed ${t} set`)}function Pm(e,t){for(const n of e){const o=t[n];if(o==null||typeof o=="string"&&o.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function xm(e,t,n,o,r){if(!n.dedupeScanEnabled)return[];const{search:i,graph:s}=e;if(!i||!s)return[];const a={project:t.uid},c=await Ds(s,a);if(!c||c.size===0)return[];const d=wo(o,r),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]}},m=5,p=m*4,g=await i.backend.search(f,p);if(g.length===0)return[];const b=await s.getNodesByIds(g.map(w=>w.id)),h=new Map(b.map(w=>[w.id,w])),y=[];for(const w of g){const v=h.get(w.id);if(!v||v.tInvalid!==void 0||v.isSuperseded)continue;const S=w.vecScore;S!==void 0&&c.has(w.id)&&S>=n.dedupeThreshold&&y.push({uid:v.uid,title:v.name??"",score:S})}return y.sort((w,v)=>v.score-w.score),y.slice(0,m)}async function Lm(e,t){Ve("title",t.title),Ve("body",t.body),Ve("project",t.project),Ve("by",t.by),Z("by",t.by),Ys(t.gitContext);const n=t.citations??[];n.forEach((u,f)=>Ve(`citations[${f}].file`,u.file));const o=typeof t.gitContext=="string"&&t.gitContext.trim().length>0?t.gitContext:void 0,r=t.duplicateAction??"abort";if(t.duplicateAction!==void 0&&!Br.includes(t.duplicateAction))throw new T("duplicateAction",`must be one of ${Br.map(u=>`'${u}'`).join("|")}, got "${t.duplicateAction}"`);const i=await Ze(e.adapter,t.project),s=Fe(i),a=[];for(const u of n){const f=await Cm(i,u.file,s.citationAllowedExternalRoots);if(f==="unverified"&&s.citationRequiresSha){if(Vt(i))throw new uo(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 xm(e,i,s,t.title,t.body);if(c.length>0&&r==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let d;const l=await V(e,async u=>{const f=D();if(c.length>0&&r==="comment"){const[C]=c,q=await Se(u,C.uid),M=`${t.title}
209
+ `}const Ti=["not_found","item_not_found","ambiguous_reference","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],ny=new Set(Ti);function Mc(t){return typeof t=="string"&&ny.has(t)}const Oi={not_found:4,item_not_found:1,ambiguous_reference:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function oy(t){return t.ok===!0}function iy(t){return t.ok===!1&&typeof t.error=="object"&&t.error!==null&&Mc(t.error.code)}function Ii(t,e){const n={ok:!0,data:t};return e!=null&&e.warnings&&e.warnings.length>0&&(n.warnings=e.warnings),e!=null&&e.meta&&(n.meta=e.meta),n}function ne(t,e,n){const i={code:t,message:e},o={...n??{}};return t==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(i.details=o),{ok:!1,error:i}}function je(t){return t.ok?0:Oi[t.error.code]}function xc(t){if(t===null||typeof t!="object")return!1;const e=t;if(typeof e.ok!="boolean")return!1;if(e.ok)return!0;const n=e.error;if(n===null||typeof n!="object")return!1;const i=n.code;return typeof i=="string"&&i in Oi}class Fc extends Error{constructor(e,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${e}" 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: "${e}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}const Bc=["get","query","priority-matrix","part-of-rollup","open-curve","report","lookup","create","update","add-citation","remove-citation","transition","attest","recheck","obligate","unobligate","spec-append","spec-check","claim","relate","move","upsert-project","upsert-component","upsert-location","rm-location","delete","embedding-status","merge-project","rm-project"],no=["kind","status","priority","relation","field","error_code","location_type","verb"],ry=[{catalog:"kind",rel:"has_kind"},{catalog:"status",rel:"has_status"},{catalog:"priority",rel:"has_priority"}],sy=new Set([...Ja].map(t=>F(t))),ay=new Map([...za].map(([t,e])=>[F(t),e]));function cy(t){const e=F(t);if(!sy.has(e))return{lifecycle:"active"};const n=ay.get(e);return{lifecycle:"deprecated",...n?{replacedBy:n}:{}}}function dy(t,e){const n=e.metadata??{},i=n.lifecycle==="deprecated"?"deprecated":"active",o=typeof n.replacedBy=="string"?n.replacedBy:void 0;return i==="deprecated"?{lifecycle:i,...o?{replacedBy:o}:{}}:t==="kind"?cy(e.name??""):{lifecycle:"active"}}async function ly(t,e){const n=await t.getEdges({rel:e}),i=new Map;for(const o of n)i.set(o.dst,(i.get(o.dst)??0)+1);return i}async function uy(t,e,n){const i=await t.queryNodes({kind:e,liveOnly:!0}),o=await ly(t,n);return i.map(r=>{const{lifecycle:s,replacedBy:a}=dy(e,r);return{name:r.name??"",uid:r.uid,catalog:e,source:"store",lifecycle:s,...a?{replacedBy:a}:{},usageCount:o.get(r.id)??0}})}function fy(t){const e=[];for(const n of xt)t.has(F(n))||e.push({name:n,catalog:"status",source:"reserved_terminal_status_names",lifecycle:"active"});return e}function ht(t,e,n){return n.map(i=>({name:i,catalog:t,source:e,lifecycle:"active"}))}function py(t){const e=new Map;for(const n of t){const i=e.get(n.catalog)??new Set,o=F(n.name);if(i.has(o))return!0;i.add(o),e.set(n.catalog,i)}return!1}async function Bo(t){const e=[],n=new Set;for(const{catalog:i,rel:o}of ry){const r=await uy(t,i,o);if(i==="status")for(const s of r)n.add(F(s.name));e.push(...r)}return e.push(...fy(n)),e.push(...ht("relation","edge_kind_table",Qa.map(i=>i.rel))),e.push(...ht("field","issue_field_union",[..._i,...Ai])),e.push(...ht("error_code","error_code_union",Ti)),e.push(...ht("location_type","valid_location_types",Co)),e.push(...ht("verb","mounted_verb_surface",Bc)),e.sort((i,o)=>{const r=no.indexOf(i.catalog)-no.indexOf(o.catalog);if(r!==0)return r;const s=i.name.localeCompare(o.name);return s!==0?s:(i.uid??"").localeCompare(o.uid??"")}),{catalogs:[...no],terms:e,hasCaseCollisions:py(e)}}async function my(t,e){return(await Bo(t)).terms.filter(i=>i.catalog===e)}function Ot(t){var e,n,i,o;return{uid:t.uid,name:t.name??"",path:typeof((e=t.metadata)==null?void 0:e.path)=="string"?t.metadata.path:void 0,repoUrl:typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?t.metadata.repoUrl:void 0,monorepo:typeof((i=t.metadata)==null?void 0:i.monorepo)=="boolean"?t.metadata.monorepo:void 0,description:typeof((o=t.metadata)==null?void 0:o.description)=="string"?t.metadata.description:void 0}}function Sn(t){var e,n,i;return{uid:t.uid,name:t.name??"",projectUid:typeof((e=t.metadata)==null?void 0:e.projectUid)=="string"?t.metadata.projectUid:"",path:typeof((n=t.metadata)==null?void 0:n.path)=="string"?t.metadata.path:void 0,description:typeof((i=t.metadata)==null?void 0:i.description)=="string"?t.metadata.description:void 0}}function Ko(t){var e,n,i;return{uid:t.uid,locType:typeof((e=t.metadata)==null?void 0:e.locType)=="string"?t.metadata.locType:"path",value:typeof((n=t.metadata)==null?void 0:n.value)=="string"?t.metadata.value:t.name??"",componentUid:typeof((i=t.metadata)==null?void 0:i.componentUid)=="string"?t.metadata.componentUid:""}}async function gy(t,e){if((e==null?void 0:e.project)!==void 0){const i=await x(t,"project",e.project);return i?[Ot(i.record)]:[]}return(await t.queryNodes({kind:"project",liveOnly:!0})).map(Ot)}async function hy(t,e){if((e==null?void 0:e.project)!==void 0){const i=await x(t,"project",e.project);return i?(await t.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:i.uid}}})).map(Sn):[]}return(await t.queryNodes({kind:"component",liveOnly:!0})).map(Sn)}async function yy(t,e){if((e==null?void 0:e.component)!==void 0){const i=e.project!==void 0?await(async()=>{const r=await x(t,"project",e.project);return r?Ve(t,r.uid,e.component):null})():await x(t,"component",e.component);return i?(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:i.uid}}})).map(Ko):[]}return(await t.queryNodes({kind:"location",liveOnly:!0})).map(Ko)}async function oo(t,e){var d,l,u,f,m,p,g,y,w;if(e.registry==="project"){const v=await x(t,"project",e.name);if(!v)throw new V("project",e.name);const b=await t.getEdges({src:v.id,rel:"owns_project"}),h=b.length>0?await t.getNodesByIds(b.map(k=>k.dst),{liveOnly:!0}):[],E=(await Promise.all(h.map(k=>t.getEdges({src:k.id,rel:"has_location"})))).flatMap(k=>k.map(R=>R.dst)),N=E.length>0?await t.getNodesByIds(E,{liveOnly:!0}):[];return{...Ot(v.record),components:h.map(k=>{var R;return{name:k.name??"",path:typeof((R=k.metadata)==null?void 0:R.path)=="string"?k.metadata.path:void 0}}),locations:N.map(k=>{var R,A;return{locType:typeof((R=k.metadata)==null?void 0:R.locType)=="string"?k.metadata.locType:"path",value:typeof((A=k.metadata)==null?void 0:A.value)=="string"?k.metadata.value:k.name??""}})}}if(e.registry==="component"){const v=(d=e.filter)==null?void 0:d.project,b=v!==void 0?await(async()=>{const R=await x(t,"project",v);if(!R)throw new V("project",v);return Ve(t,R.uid,e.name)})():await x(t,"component",e.name);if(!b)throw new V("component",e.name);const h=typeof((l=b.record.metadata)==null?void 0:l.projectUid)=="string"?b.record.metadata.projectUid:void 0,S=h?await t.getNodeByUid(h):null,E=S&&!S.tInvalid?S:null,N=await t.getEdges({src:b.id,rel:"has_location"}),k=N.length>0?await t.getNodesByIds(N.map(R=>R.dst),{liveOnly:!0}):[];return{...Sn(b.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:k.map(R=>{var A,O;return{locType:typeof((A=R.metadata)==null?void 0:A.locType)=="string"?R.metadata.locType:"path",value:typeof((O=R.metadata)==null?void 0:O.value)=="string"?R.metadata.value:R.name??""}})}}if(!pe(e.name)&&!Dt(e.name))throw new T("name","a location has no name — pass its uid");const n=await Un(t,e.name,{expectedKind:"location"}),i=typeof((m=n.metadata)==null?void 0:m.componentUid)=="string"?n.metadata.componentUid:void 0,o=i?await t.getNodeByUid(i):null,r=o&&!o.tInvalid?o:null,s=typeof((p=r==null?void 0:r.metadata)==null?void 0:p.projectUid)=="string"?r.metadata.projectUid:void 0,a=s?await t.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;return{...Ko(n),component:{name:(r==null?void 0:r.name)??"",path:typeof((g=r==null?void 0:r.metadata)==null?void 0:g.path)=="string"?r.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((y=c==null?void 0:c.metadata)==null?void 0:y.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((w=c==null?void 0:c.metadata)==null?void 0:w.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function wy(t){try{return new URL(t),!0}catch{return!1}}function vy(t){return wy(t)?"url":t.includes("/")||t.includes(".")||t.startsWith("~")?"path":"tool"}async function by(t,e){var f,m,p,g,y,w;const n=vy(e);let i=(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:e}},limit:1}))[0],o,r=!1;if(!i&&n==="path"){const v=await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:le+1});r=v.length>le;const h=(r?v.slice(0,le):v).find(S=>{var N;const E=typeof((N=S.metadata)==null?void 0:N.value)=="string"?S.metadata.value:"";return E.endsWith(e)||e.endsWith(E)});h&&(i=h,o="matched by path suffix/prefix fallback, not an exact value match")}if(!i)return{ok:!1,truncated:r};const s=typeof((f=i.metadata)==null?void 0:f.componentUid)=="string"?i.metadata.componentUid:void 0,a=s?await t.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new V("component",s??"(unresolved)");const d=typeof((m=c.metadata)==null?void 0:m.projectUid)=="string"?c.metadata.projectUid:void 0,l=d?await t.getNodeByUid(d):null,u=l&&!l.tInvalid?l:null;return u?{ok:!0,result:{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((g=u.metadata)==null?void 0:g.repoUrl)=="string"?u.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((y=c.metadata)==null?void 0:y.path)=="string"?c.metadata.path:void 0},location:{uid:i.uid,locType:n,value:typeof((w=i.metadata)==null?void 0:w.value)=="string"?i.metadata.value:e},hint:o}}:{ok:!0,result:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:i.uid,locType:n,value:e},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}}async function Ey(t,e){var d;const n=typeof e=="string"?e:e.q,i=typeof e=="string"?void 0:e.kind,o=i===void 0||i==="issue",r=i===void 0||i==="location",s=i===void 0||i==="project",a=i===void 0||i==="component";if(pe(n)||Dt(n)){const l=await Un(t,n);return{project:{uid:"",name:""},redirect:{verb:"get",uid:l.uid}}}if(o){const l=n.toLowerCase().split(/\s+/).filter(f=>f.length>0),u=(await t.searchNodes(n,{filter:{kind:"issue",liveOnly:!0,isSuperseded:!1},limit:20})).filter(f=>l.some(m=>(f.name??"").toLowerCase().includes(m)));if(u.length===1)return{project:{uid:"",name:""},redirect:{verb:"get",uid:u[0].uid}};if(u.length>1)throw new mi(n,u.map(f=>({uid:f.uid,kind:f.kind,name:f.name??""})))}let c=!1;if(r){const l=await by(t,n);if(l.ok)return l.result;c=l.truncated}if(s){const u=(await t.queryNodes({kind:"project",name:n,liveOnly:!0,limit:1}))[0]??(await t.queryNodes({kind:"project",liveOnly:!0,metadata:{repoUrl:{eq:n}},limit:1}))[0];if(u)return{project:Ot(u),hint:"matched a project by name/repoUrl — no component or location was requested"}}if(a&&i==="component"){const l=await x(t,"component",n);if(l){const u=typeof((d=l.record.metadata)==null?void 0:d.projectUid)=="string"?l.record.metadata.projectUid:void 0,f=u?await t.getNodeByUid(u):null;return{project:f&&!f.tInvalid?Ot(f):{uid:"",name:""},component:Sn(l.record),hint:"matched a component by name/uid"}}}throw new V("location",c?`${n} (path suffix/prefix fallback scanned only the first ${le} live path locations; a match may exist beyond this cap)`:n)}function Kt(t){if(t===void 0)return Ln;if(!Number.isInteger(t)||t<=0||t>le)throw new _e("limit",`must be a positive integer ≤ ${le}, got ${t}`);return t}function Sy(t){var e,n;if(t.after!==void 0){if(t.sort!==void 0)throw new T("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(((e=t.filter)==null?void 0:e.grep)!==void 0||((n=t.filter)==null?void 0:n.semantic)!==void 0)throw new T("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 ky(t,e){const n=new Set;for(const i of e.refs){const o=await x(t,e.expectedKind,i);if(!o)continue;const r=await t.getEdges({dst:o.id,rel:e.rel});for(const s of r)n.add(s.src)}return n}async function Kc(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function qt(t,e){if(!e)return;const n=[];let i;if(e.project!==void 0){const o=await x(t,"project",e.project);if(!o)return new Set;i=o.uid;const r=await t.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of r){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(e.component!==void 0){const o=i!==void 0?await Ve(t,i,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(r.map(s=>s.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await nt(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await Kc(t,e.status));else{const o=Array.isArray(e.status)?e.status:[e.status];n.push(await nt(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(e.priority!==void 0){const o=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await nt(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(e.author!==void 0&&n.push(await ky(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.similarTo!==void 0){const o=await x(t,"issue",e.similarTo);if(!o)return new Set;const r=await t.getEdges({dst:o.id,rel:"similar_to"});n.push(new Set(r.map(s=>s.src)))}if(e.hasSimilar===!0){const o=await t.getEdges({rel:"similar_to"});n.push(new Set(o.map(r=>r.dst)))}if(e.plan!==void 0){const o=await x(t,"issue",e.plan);if(!o)return new Set;const r=await t.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(r.map(s=>s.src)))}if(e.projectPath!==void 0){const o=await t.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:e.projectPath}}});if(o.length===0)return new Set;const r=new Set;for(const s of o){const a=await t.getEdges({src:s.id,rel:"owns_component"});for(const c of a)r.add(c.dst)}n.push(r)}return Bg(n)}function _y(t){if(!t)return;const e={};return t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until})),Object.keys(e).length>0?e:void 0}function Ay(t){if(t==="created")return"tCreated";if(t==="updated")return"tValid"}async function qc(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_priority"}))),i=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=i.length>0?await t.getNodesByIds(i):[],r=new Map(o.map(a=>{var c;return[a.id,typeof((c=a.metadata)==null?void 0:c.rank)=="number"?a.metadata.rank:Number.MAX_SAFE_INTEGER]})),s=new Map;return e.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;s.set(a.id,d!==void 0?r.get(d)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)}),s}async function Ny(t,e,n){const i=await qc(t,e),o=[...e].sort((r,s)=>i.get(r.id)-i.get(s.id));return n==="desc"?o.reverse():o}function It(t,e,n){return{total:n?t+1:t,total_relation:n?"gte":"eq",returned:t,limit:e,has_more:n}}async function Ry(t,e){var b,h,S,E,N,k,R,A,O,I,L,$;const{graph:n}=t;Sy(e),ji(e.fields);const i=Kt(e.limit),o=e.fields??Ft;if((e.sort==="relevance"||e.sort==="textMatch")&&((b=e.filter)==null?void 0:b.grep)===void 0&&((h=e.filter)==null?void 0:h.semantic)===void 0)throw new _e("sort",`"${e.sort}" requires filter.grep or filter.semantic`);const r=await qt(n,e.filter);if((r==null?void 0:r.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:i}};const s=_y(e.filter),a=(S=e.filter)==null?void 0:S.grep,c=(E=e.filter)==null?void 0:E.semantic,d={kind:"issue",isSuperseded:!1,...r?{ids:[...r]}:{},...s?{metadata:s}:{},...(k=(N=e.filter)==null?void 0:N.createdAt)!=null&&k.since?{tCreatedAfter:e.filter.createdAt.since}:{},...(A=(R=e.filter)==null?void 0:R.createdAt)!=null&&A.until?{tCreatedBefore:e.filter.createdAt.until}:{},...(I=(O=e.filter)==null?void 0:O.updatedAt)!=null&&I.since?{tUpdatedAfter:e.filter.updatedAt.since}:{},...($=(L=e.filter)==null?void 0:L.updatedAt)!=null&&$.until?{tUpdatedBefore:e.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let Y,H;const ge=e.offset??0,lt=ge+i;if(a!==void 0){const J=await n.searchNodes(a,{limit:lt,filter:d});H=new Set(J.map(he=>he.id))}if(c!==void 0){if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const he={vec:await t.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Ji=await t.search.backend.searchRanked(he,lt);Y=H?Ji.filter(El=>H.has(El.id)):Ji}else H&&(Y=(await n.searchNodes(a,{limit:lt,filter:d})).map(he=>({id:he.id,score:he.score,fields:{}})));const Z=(Y??[]).map(J=>J.id).slice(ge,ge+i),ut=Z.length>0?await n.getNodesByIds(Z):[],ft=new Map(ut.map(J=>[J.id,J])),pt=Z.map(J=>ft.get(J)).filter(J=>J!==void 0),Vt=new Map((Y??[]).map(J=>{var he;return[(he=ft.get(J.id))==null?void 0:he.uid,J.score]}).filter(J=>J[0]!==void 0)),vl=c!==void 0?"rrf":"bm25",bl=new Map([...Vt.keys()].map(J=>[J,vl])),Vi=await Tt(n,pt,o,Vt,bl,{rung:2,onRung:t.onVerdictRung}),Gn=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Wn=Vi.length,Gi=Wn<Math.min(Gn-ge,i),Wi=ge+Wn<Gn;return{page:{items:Vi,hasMore:Wi},meta:{total:Gn,returned:Wn,limit:i,...e.offset!==void 0?{offset:e.offset}:{},...Gi?{truncated:!0}:{},has_more:Wi,total_relation:Gi?"gte":"eq"}}}const l=Ay(e.sort),u={...d,limit:i+1,...e.after!==void 0?{after:Number(e.after)}:{},...l&&e.after===void 0?{orderBy:l,orderDir:e.direction??"desc"}:{},...e.after===void 0&&e.offset!==void 0?{offset:e.offset}:{}};let f=await n.queryNodes(u);e.sort==="priority"&&e.after===void 0&&(f=await Ny(n,f,e.direction??"asc"));const m=f.length>i,p=m?f.slice(0,i):f,g=m?String(p[p.length-1].id):void 0,y=await Tt(n,p,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung}),w=await n.countNodes(d),v=e.after===void 0?e.offset:void 0;return{page:{items:y,nextCursor:g,hasMore:m},meta:{total:w,returned:y.length,limit:i,...v!==void 0?{offset:v}:{}}}}async function jy(t,e){var S;const{graph:n}=t,i=Kt(e.limit),o=e.fields??Ft,r=await Kc(n,"open"),s=await qt(n,e.filter),a=s?[...r].filter(E=>s.has(E)):[...r];if(a.length===0)return{items:[],meta:It(0,i,!1)};const c=await n.getNodesByIds(a),d=await n.getEdges({rel:"blocks"}),l=new Map;for(const E of d){const N=l.get(E.dst);N?N.push(E.src):l.set(E.dst,[E.src])}const u=[...new Set(d.map(E=>E.src))],f=new Set((u.length>0?await n.getNodesByIds(u):[]).map(E=>E.id)),m=await n.getEdges({rel:"has_status"}),p=new Map;for(const E of m)p.has(E.src)||p.set(E.src,E.dst);const g=[...new Set(p.values())],y=new Map((g.length>0?await n.getNodesByIds(g):[]).map(E=>[E.id,E])),w=[];for(const E of c){if(w.length>=i+1)break;if(typeof((S=E.metadata)==null?void 0:S.claimedBy)=="string")continue;const N=(l.get(E.id)??[]).filter(R=>f.has(R));if(N.length===0){w.push(E);continue}N.every(R=>{const A=p.get(R);return A!==void 0&&Ae(y.get(A))})&&w.push(E)}const v=w.length>i,b=v?w.slice(0,i):w,h=await Tt(n,b,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung});return{items:h,meta:It(h.length,i,v)}}async function Ty(t,e){const{graph:n}=t,i=Kt(e.limit),o=e.fields??Ft,r=e.staleAfterMin??30,s=new Date(Date.now()-r*6e4).toISOString(),a=await qt(n,e.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:i+1},d=await n.queryNodes(c),l=d.length>i,u=l?d.slice(0,i):d,f=await Tt(n,u,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung});return{items:f,meta:It(f.length,i,l)}}const Oy=["blocks","relates_to","part_of"];function Iy(t){return Oy.includes(t)}async function $y(t,e){var u;const{graph:n}=t,i=Kt(e.limit??le),o=await qt(n,e.filter),r={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:i},s=await n.queryNodes(r),a=new Set(s.map(f=>f.id)),c=await Cy(n,s),d=s.map(f=>{var m;return{uid:f.uid,title:f.name??"",status:((m=c.get(f.id))==null?void 0:m.name)??""}}),l=[];for(const f of s){const m=await me(n,f.id);for(const p of m)if(Iy(p.rel)&&a.has(p.dst)){const g=(u=(await n.getNodesByIds([p.dst]))[0])==null?void 0:u.uid;g&&l.push({from:f.uid,to:g,rel:p.rel})}}return{nodes:d,edges:l}}async function Cy(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_status"}))),i=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=i.length>0?await t.getNodesByIds(i):[],r=new Map(o.map(a=>[a.id,a])),s=new Map;return e.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=r.get(d);u&&s.set(a.id,u)}}),s}async function Py(t,e){var h,S,E,N;const{graph:n}=t,i=Kt(e.limit??le),o=await qt(n,e.filter),r=((h=e.filter)==null?void 0:h.plan)!==void 0||((S=e.filter)==null?void 0:S.project)!==void 0||((E=e.filter)==null?void 0:E.component)!==void 0||((N=e.filter)==null?void 0:N.kind)!==void 0;if((o==null?void 0:o.size)===0)return{ok:!0,order:[]};const s={...r?{}:{kind:"issue"},isSuperseded:!1,...o?{ids:[...o]}:{},limit:i},a=await n.queryNodes(s),c=new Set(a.map(k=>k.id)),d=new Map(a.map(k=>[k.id,k.uid])),l=new Map,u=new Map;for(const k of a)l.set(k.id,0),u.set(k.id,[]);for(const k of a){const R=await n.getEdges({src:k.id,rel:"blocks"});for(const A of R)c.has(A.dst)&&(u.get(k.id).push(A.dst),l.set(A.dst,(l.get(A.dst)??0)+1))}const f=new Map;for(const k of a)f.set(k.id,await Cc(n,k.id,c));const m=await qc(n,a),p=(k,R)=>{const A=f.get(k)??0,O=f.get(R)??0;if(A!==O)return O-A;const I=m.get(k)??Number.MAX_SAFE_INTEGER,L=m.get(R)??Number.MAX_SAFE_INTEGER;if(I!==L)return I-L;const $=d.get(k),Y=d.get(R);return $<Y?-1:$>Y?1:0},g=[],y=k=>{g.push(k);let R=g.length-1;for(;R>0;){const A=R-1>>1;if(p(g[R],g[A])<0)[g[R],g[A]]=[g[A],g[R]],R=A;else break}},w=()=>{const k=g[0],R=g.pop();if(g.length>0){g[0]=R;let A=0;for(;;){const O=2*A+1,I=O+1;let L=A;if(O<g.length&&p(g[O],g[L])<0&&(L=O),I<g.length&&p(g[I],g[L])<0&&(L=I),L===A)break;[g[A],g[L]]=[g[L],g[A]],A=L}}return k};for(const k of a)(l.get(k.id)??0)===0&&y(k.id);const v=[],b=new Map(l);for(;g.length>0;){const k=w();v.push(k);for(const R of u.get(k)??[]){const A=(b.get(R)??0)-1;b.set(R,A),A===0&&y(R)}}return v.length!==a.length?{ok:!1,cycle:a.filter(R=>!v.includes(R.id)).map(R=>d.get(R.id))}:{ok:!0,order:v.map(k=>d.get(k))}}async function Ly(t,e){var s;const{graph:n}=t,i=e.overlapAxis,o=e.overlapUids;if(!i)throw new T("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new T("overlapUids","requires at least 2 uids to detect an overlap");const r=new Map;for(const a of o){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(i==="file"){const m=(await me(n,c.id)).filter(g=>g.rel==="has_citation"),p=m.length>0?await n.getNodesByIds(m.map(g=>g.dst)):[];for(const g of p){const y=typeof((s=g.metadata)==null?void 0:s.target)=="string"?g.metadata.target:void 0;y&&(r.has(y)||r.set(y,new Set),r.get(y).add(a))}continue}if(i==="author"){const m=(await me(n,c.id)).find(g=>g.rel==="authored_by");if(!m)continue;const[p]=await n.getNodesByIds([m.dst]);if(!p)continue;r.has(p.uid)||r.set(p.uid,new Set),r.get(p.uid).add(a);continue}const{project:d,component:l}=await Ge(n,c.id),u=i==="project"?d:l;u&&(r.has(u.uid)||r.set(u.uid,new Set),r.get(u.uid).add(a))}return[...r.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function Uy(t,e){return gy(t.graph,e.filter)}async function Dy(t,e){return hy(t.graph,e.filter)}async function My(t,e){return yy(t.graph,e.filter)}function xy(t){var e,n;return t.text!==void 0||((e=t.filter)==null?void 0:e.semantic)!==void 0||((n=t.filter)==null?void 0:n.anchor)!==void 0||t.view==="similar"||t.sort==="relevance"||(t.fields??[]).includes("_vector")}function Fy(t,e){var r,s;if(e.text===void 0)return e;if(((r=e.filter)==null?void 0:r.semantic)!==void 0||((s=e.filter)==null?void 0:s.grep)!==void 0)throw new T("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(e.text.trim().length===0)throw new T("text","must not be blank");const n=t.search!==void 0&&t.spacePopulated===!0,{text:i,...o}=e;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:i}:{grep:i}}}}async function By(t,e){var i,o,r,s;const n=e.view??"list";switch(n){case"list":{const{page:a,meta:c}=await Ry(t,e);return{result:{view:"list",...a},meta:c}}case"ready":{const{items:a,meta:c}=await jy(t,e);return{result:{view:"ready",items:a},meta:c}}case"graph":return{result:{view:"graph",graph:await $y(t,e)}};case"order":return{result:{view:"order",order:await Py(t,e)}};case"stale":{const{items:a,meta:c}=await Ty(t,e);return{result:{view:"stale",items:a},meta:c}}case"similar":{const a=((i=e.filter)==null?void 0:i.project)!==void 0||((o=e.filter)==null?void 0:o.component)!==void 0,c=((r=e.filter)==null?void 0:r.anchor)!==void 0||((s=e.filter)==null?void 0:s.semantic)!==void 0,d=a?await Yh(t,e):void 0;if(a&&!c){const m=e.limit??Ln;return{result:{view:"similar",items:[],...d?{clusters:d}:{}},meta:It(0,m,!1)}}const{items:l,hasMore:u,limit:f}=await xh(t,e);return{result:{view:"similar",items:l,...d?{clusters:d}:{}},meta:It(l.length,f,u)}}case"overlap":return{result:{view:"overlap",groups:await Ly(t,e)}};case"projects":return{result:{view:"projects",items:await Uy(t,e)}};case"components":return{result:{view:"components",items:await Dy(t,e)}};case"locations":return{result:{view:"locations",items:await My(t,e)}};case"kinds":return{result:{view:"kinds",catalogs:await Bo(t.graph)}};case"catalogs":return{result:{view:"catalogs",terms:e.catalog!==void 0?await my(t.graph,e.catalog):(await Bo(t.graph)).terms}};default:{const a=n;throw new _e("view",`unknown view "${a}"`)}}}const Ky=["list","ready","stale","similar"];async function qy(t,e={}){var a;await((a=t.assertVocabulary)==null?void 0:a.call(t));const n=Fy(t,e),i=await By(t,n);if(n.format!=="markdown")return i;const{result:o}=i,{view:r}=o;if(r!=="list"&&r!=="ready"&&r!=="stale"&&r!=="similar")throw new T("format",`"markdown" is only supported for view:${Ky.map(c=>`"${c}"`).join("/")} — view:"${r}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=o.items;return{result:{view:r,format:"markdown",markdown:ty(s)},meta:i.meta}}class Hy extends Error{constructor(e,n,i,o){super(`backlog embedding: ${e} produced a ${o}-dimensional vector but space "${n}" is ${i}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=e,this.modelId=n,this.expected=i,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let ns=!1,os=!1,is=!1;const kn=new WeakMap;async function Vy(t,e){const n=t;return typeof n.hasVectors!="function"?(ns||(ns=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${e}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(e)}async function rs(t){try{return{mod:await import(t)}}catch(e){return{err:e}}}const on=t=>t instanceof Error?t.message:String(t),Et=new WeakMap;async function Gy(t,e,n,i=r=>console.error(r),o){const r=Et.get(t);if(r)return r;const s=zy(t,e,n,i,o);Et.set(t,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?Et.delete(t):kn.set(t,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw Et.delete(t),kn.delete(t),a}}function Wy(t){const e=kn.get(t);if(e)return{present:!0,embedding:e.embedding,search:e.search}}function Jy(t){Et.delete(t),kn.delete(t)}function ss(t){return t&&t.length>0?t.join(", "):"(no config layer files found on disk)"}async function zy(t,e,n,i,o){var p;if(!(n!=null&&n.enabled))return(o==null?void 0:o.configuredEnabled)===!0?is||(is=!0,i(`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: ${ss(o.configPaths)}.`)):os||(os=!0,i(`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: ${ss(o==null?void 0:o.configPaths)}.`)),{};const r=(p=t.capabilities)==null?void 0:p.nativeVectors;if(r!==!0)return i(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(r)}) — 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([rs("@adhd/sox-vector-store"),rs("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const g=[..."err"in s?[`@adhd/sox-vector-store (${on(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${on(a.err)})`]:[]];return i(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${g.join("; ")}. Continuing WITHOUT semantic search.`),{}}let c;try{c=await a.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(g){return i(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${on(g)}. Continuing WITHOUT semantic search.`),{}}const d={modelId:c.metadata.modelId,dim:c.metadata.dimensions};let l;try{l=await s.mod.openTursoVectorStore(t,{dim:d.dim,modelId:d.modelId}),await l.ensureSpace(d)}catch(g){return i(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${on(g)}. Continuing WITHOUT semantic search.`),{}}const u=(g,y)=>{if(g.length!==d.dim)throw new Hy(y,d.modelId,d.dim,g.length);return g},f={modelId:d.modelId,async embedDocument(g){return u(await c.embedSingle(g,"document"),"embedDocument")},async upsertVector(g,y){await l.upsert(g,u(y,"upsertVector"),d)},async deleteVector(g){await l.delete(g,d.modelId)}};return{search:{backend:new Tl.StoreSearchBackend(l,e),async embedQuery(g){return u(await c.embedSingle(g,"query"),"embedQuery")},async spacePopulated(){return Vy(l,d.modelId)}},embedding:f}}const as=["status","priority","kind"],Yy="run the terminal-flag repair — `write/catalog-repair.ts`'s `planTerminalBackfill` + `applyTerminalBackfill` — which sets `metadata.terminal = true` on each named status row.",Xy="run the case-fragment repair — `write/catalog-merge.ts`'s `planCaseFragmentMerge` + `applyCaseFragmentMerge` — which collapses each folded group to one live row, re-points its edges, and records the merged-away spelling as an alias.";function Qy(t){const e=t.filter(o=>o.kind==="unflagged-terminal"),n=t.filter(o=>o.kind==="case-fragment-duplicate"),i=["backlog: status/priority/kind catalog invariant violated (ADR-0002: correct the source, never work around it)."];if(i.push(" This is a NAMED check: it reports the rows below and the repair. It never gates reads or unrelated writes — a drifted catalog is a bounded data problem, never an availability outage — and neither condition may be papered over with a read-time fallback."),e.length>0){i.push(` unflagged-terminal (${e.length}): a live status row whose name is a reserved terminal name but whose metadata.terminal is not true reads as NON-terminal, so closed items are returned under an open filter.`);for(const o of e)i.push(` - status "${o.name}" (uid ${o.uid})`);i.push(` remediation: ${Yy}`)}if(n.length>0){i.push(` case-fragment-duplicate (${n.length}): two or more live rows of the SAME catalog kind share a case-folded name, so a name-keyed reader splits one value across two rows.`);for(const o of n){const r=o.names.map((s,a)=>`"${s}" (uid ${o.uids[a]})`).join(", ");i.push(` - fold "${o.fold}": ${r}`)}i.push(` remediation: ${Xy}`)}return i.join(`
210
+ `)}class Hc extends Error{constructor(e){super(Qy(e)),this.violations=e,this.name="CatalogInvariantError"}}const Zy=new Set([...xt].map(t=>F(t)));function ew(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function tw(t){var i;const{rows:e}=await t.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind IN (?, ?, ?) AND t_invalid IS NULL ORDER BY kind ASC, rowid ASC",[...as]),n=[];for(const o of e){if(o.kind!=="status")continue;const r=F(o.name??"");Zy.has(r)&&((i=ew(o.meta))==null?void 0:i.terminal)!==!0&&n.push({kind:"unflagged-terminal",name:o.name??"",uid:o.uid})}for(const o of as){const r=new Map;for(const s of e){if(s.kind!==o)continue;const a=F(s.name??""),c=r.get(a);c?c.push(s):r.set(a,[s])}for(const[s,a]of r)a.length<2||n.push({kind:"case-fragment-duplicate",fold:s,names:a.map(c=>c.name??""),uids:a.map(c=>c.uid)})}return n}async function Vc(t){const e=await tw(t);if(e.length!==0)throw new Hc(e)}async function nw(t,e){if(ji(e.fields),e.lastN!==void 0&&(!Number.isInteger(e.lastN)||e.lastN<=0))throw new _e("lastN",`must be a positive integer, got ${e.lastN}`);const n=e.fields??Ft,i=await Dn(t,e.uid),o=e.lastN!==void 0||e.after!==void 0?{lastN:e.lastN,after:e.after}:void 0;return Lc(t,i,n,{bounds:o,verdictRung:e.deriveThrough??3})}function ow(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):[]}const iw=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function Gc(t,e,n){if(t){for(const i of iw)if(t[i]!==void 0&&!e.has(i))throw new T(`filter.${i}`,`not supported by ${n} — this view scopes by ${[...e].join("/")} only`)}}async function Wc(t,e){const n=new Set;for(const i of e.refs){const o=await x(t,e.expectedKind,i);if(!o)continue;const r=await t.getEdges({dst:o.id,rel:e.rel});for(const s of r)n.add(s.src)}return n}async function rw(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}function Jc(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const i=new Set;for(const o of e)n.has(o)&&i.add(o);e=i}return e}async function zc(t,e){if(!e)return;const n=[];let i;if(e.project!==void 0){const o=await x(t,"project",e.project);if(!o)return new Set;i=o.uid;const r=await t.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of r){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(e.component!==void 0){const o=i!==void 0?await Ve(t,i,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(r.map(s=>s.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Wc(t,{rel:"has_kind",expectedKind:"kind",refs:o}))}return Jc(n)}const sw=new Set(["project","component","kind","status"]);async function aw(t,e){const n=e??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await rw(t,n),scope:n};const i=Array.isArray(n)?n:[n];return{candidates:await Wc(t,{rel:"has_status",expectedKind:"status",refs:i}),scope:n}}async function Yc(t,e){const n=await zc(t,e),{candidates:i,scope:o}=await aw(t,e==null?void 0:e.status),r=Jc([n,i].filter(a=>a!==void 0));return(n==null?void 0:n.size)===0||(i==null?void 0:i.size)===0||(r==null?void 0:r.size)===0?{nodes:[],statusScope:o}:{nodes:await t.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...r?{ids:[...r]}:{}}),statusScope:o}}async function Xc(t,e={}){var l;const{graph:n}=t;Gc(e.filter,sw,"priorityMatrix");const{nodes:i,statusScope:o}=await Yc(n,e.filter);if(i.length===0)return{rows:[],unassigned:0,statusScope:o};const r=new Set(i.map(u=>u.id)),s=await n.queryNodes({kind:"priority",liveOnly:!0}),a=new Set,c=[];for(const u of s){const f=await n.getEdges({dst:u.id,rel:"has_priority"});let m=0;for(const g of f)r.has(g.src)&&(m+=1,a.add(g.src));const p=typeof((l=u.metadata)==null?void 0:l.rank)=="number"?u.metadata.rank:void 0;c.push({priority:u.name??"",priorityUid:u.uid,rank:p,count:m})}c.sort((u,f)=>(u.rank??Number.MAX_SAFE_INTEGER)-(f.rank??Number.MAX_SAFE_INTEGER));let d=0;for(const u of r)a.has(u)||(d+=1);return{rows:c,unassigned:d,statusScope:o}}const cw=50,cs=1e3;async function dw(t,e){if(e.length===0)return new Map;const n=await Promise.all(e.map(c=>t.getEdges({src:c.id,rel:"has_status"}))),i=new Map;n.forEach((c,d)=>{const l=c[0];l&&i.set(e[d].id,l.dst)});const o=[...new Set(i.values())];if(o.length===0)return new Map;const r=await t.getNodesByIds(o),s=new Map(r.map(c=>[c.id,c])),a=new Map;for(const[c,d]of i){const l=s.get(d);l&&a.set(c,l)}return a}async function lw(t,e){const{graph:n}=t,i=await Dn(n,e.uid);if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<=0||e.limit>cs))throw new _e("limit",`must be a positive integer ≤ ${cs}, got ${e.limit}`);const o=e.limit??cw,s=(await n.getSubgraph(i.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(g=>g.id!==i.id&&g.kind==="issue"&&!g.tInvalid),a=await dw(n,s);let c=0,d=0;const l=[];for(const g of s)Ae(a.get(g.id))?d+=1:(c+=1,l.push(g.uid));const u={uid:i.uid,childrenTotal:s.length,childrenOpen:c,childrenClosed:d};if(e.countOnly)return u;let f=l;if(e.after!==void 0){const g=f.findIndex(y=>y===e.after);g>=0&&(f=f.slice(g+1))}const m=f.slice(0,o),p=f.length>o;return{...u,childrenOpenUids:m,hasMore:p,...p&&m.length>0?{nextCursor:m[m.length-1]}:{}}}const uw=new Set(["project","component","kind"]);function fw(t,e,n){var r;const i=t.filter(s=>s.to!==void 0);if(i.length===0)return n;let o;for(const s of i)if(s.at<=e)o=s;else break;return o?o.to:(r=i[0])==null?void 0:r.from}async function pw(t){var u;const e=await t.getEdges({rel:"has_status"}),n=new Map;for(const f of e)n.has(f.src)||n.set(f.src,f.dst);const i=[...new Set(n.values())],o=new Map((i.length>0?await t.getNodesByIds(i):[]).map(f=>[f.id,f])),r=new Map;for(const[f,m]of n)r.set(f,(u=o.get(m))==null?void 0:u.name);const s=await t.getEdges({rel:"audits"}),a=new Map;for(const f of s){const m=a.get(f.src);m?m.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 t.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,m]of a){const p=m.map(g=>d.get(g)).filter(g=>g!==void 0).map(g=>{var y,w,v,b,h,S,E;return{uid:g.uid,actor:typeof((y=g.metadata)==null?void 0:y.actor)=="string"?g.metadata.actor:"",action:typeof((w=g.metadata)==null?void 0:w.action)=="string"?g.metadata.action:g.name??"",from:typeof((v=g.metadata)==null?void 0:v.from)=="string"?g.metadata.from:void 0,to:typeof((b=g.metadata)==null?void 0:b.to)=="string"?g.metadata.to:void 0,note:typeof((h=g.metadata)==null?void 0:h.note)=="string"?g.metadata.note:void 0,sha:typeof((S=g.metadata)==null?void 0:S.sha)=="string"?g.metadata.sha:"",at:typeof((E=g.metadata)==null?void 0:E.at)=="string"?g.metadata.at:g.tCreated}}).sort((g,y)=>g.at.localeCompare(y.at));l.set(f,p)}return{currentStatusNameByIssue:r,auditTrailByIssue:l}}async function mw(t,e){var u;const{graph:n}=t;if(Gc(e.filter,uw,"openCurve"),e.at.length===0)throw new T("at","requires at least one ISO-8601 instant to sample");const i=e.at.map(f=>{const m=new Date(f);if(Number.isNaN(m.getTime()))throw new T("at",`"${f}" is not a parsable ISO-8601 instant`);return m.toISOString()}),o=await zc(n,e.filter);if((o==null?void 0:o.size)===0)return{points:i.map(f=>({at:f,existed:0,open:0,closed:0}))};const r=await n.queryNodes({kind:"status",liveOnly:!0}),s=new Map;for(const f of r){const m=Ae(f);f.name&&s.set(f.name,m);for(const p of ow((u=f.metadata)==null?void 0:u.aliases))s.set(p,m)}const{currentStatusNameByIssue:a,auditTrailByIssue:c}=await pw(n),d=new Map;for(const f of await n.getEdges({rel:"SUPERSEDES"})){const m=d.get(f.dst);(m===void 0||f.tCreated<m)&&d.set(f.dst,f.tCreated)}const l=[];for(const f of i){const m={kind:"issue",validAt:f,liveOnly:!1,...o?{ids:[...o]}:{}},p=await n.queryNodes(m);let g=0,y=0;for(const w of p){const v=d.get(w.id);if(v!==void 0&&v<=f)continue;y+=1;const b=a.get(w.id),h=c.get(w.id)??[],S=fw(h,f,b);(S!==void 0?s.get(S)??!1:!1)||(g+=1)}l.push({at:f,existed:y,open:g,closed:y-g})}return{points:l}}async function gw(t,e){const n=new Map;if(e.length===0)return n;const i=new Set(e.map(a=>a.id)),o=new Map;for(const a of await t.getEdges({rel:"has_kind"}))i.has(a.src)&&!o.has(a.src)&&o.set(a.src,a.dst);const r=[...new Set(o.values())],s=new Map((r.length>0?await t.getNodesByIds(r):[]).map(a=>[a.id,a.name??""]));for(const[a,c]of o){const d=s.get(c);d!==void 0&&n.set(a,d)}return n}async function hw(t,e){const n=new Map;if(e.length===0)return n;const i=new Set(e.map(a=>a.id)),o=new Map;for(const a of await t.getEdges({rel:"has_status"}))i.has(a.src)&&!o.has(a.src)&&o.set(a.src,a.dst);const r=[...new Set(o.values())],s=new Map((r.length>0?await t.getNodesByIds(r):[]).map(a=>[a.id,{name:a.name??"",terminal:Ae(a)}]));for(const[a,c]of o){const d=s.get(c);d&&n.set(a,d)}return n}async function yw(t,e){const{graph:n}=t,i=new Date().toISOString(),{nodes:o,statusScope:r}=await Yc(n,e.filter),a=(await Xc(t,{filter:e.filter})).rows.map(v=>({priority:v.priority,...v.rank!==void 0?{rank:v.rank}:{},count:v.count})),c=await gw(n,o),d=await hw(n,o),l=new Map,u=new Map,f=Date.parse(i);let m=0,p=0;for(const v of o){const b=c.get(v.id)??v.kind;l.set(b,(l.get(b)??0)+1);const h=d.get(v.id),S=(h==null?void 0:h.name)??"",E=(h==null?void 0:h.terminal)??!1,N=u.get(S)??{terminal:E,count:0};if(N.count+=1,u.set(S,N),!E){m+=1;const k=Date.parse(v.tCreated);Number.isNaN(k)||(p+=f-k)}}const g=[...l.entries()].map(([v,b])=>({kind:v,count:b})).sort((v,b)=>v.kind.localeCompare(b.kind)),y=[...u.entries()].map(([v,b])=>({status:v,terminal:b.terminal,count:b.count})).sort((v,b)=>v.status.localeCompare(b.status)),w=m>0?p/m/864e5:0;return{byKind:g,byPriority:a,byStatus:y,avgAgeDays:w,statusScope:r,computedAt:i}}function _t(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function ww(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`citation: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`citation: 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 Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`citation: resolved project rowid=${i.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}}const vw=/^[A-Za-z0-9][A-Za-z0-9._/@{}~^-]*$/;function bw(t){return t.length>0&&t.length<=256&&vw.test(t)&&!t.includes("..")}function Ew(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e),o=_.relative(n,i);if(!(o===""||o===".."||o.startsWith(`..${_.sep}`)||_.isAbsolute(o)))return o.split(_.sep).join("/")}function Sw(t,e,n){if(bw(e))try{const i=Hs.execFileSync("git",["-C",t,"show",`${e}:${n}`],{stdio:["ignore","pipe","pipe"],maxBuffer:67108864});return He(i)}catch{return}}async function kw(t,e,n,i,o=[]){if(!Za(t))return"unverified";if(n!==void 0){const r=Ew(t.metadata.path,e);return r===void 0?"unverified":Sw(t.metadata.path,n,r)??"unverified"}try{const{accepted:r,candidate:s}=await _p(t.metadata.path,e,[...i,...Ia(),...o]);if(!r)return"unverified";const a=await zo.readFile(s);return He(a)}catch(r){if(Oa(r))return"unverified";throw jp(r,e)}}async function Qc(t,e,n,i=[]){const o=[];for(const r of e)o.push(await kw(t,r.file,r.revision,n,i));return o}function Zc(t,e,n,i,o){for(let r=0;r<n.length;r+=1)if(i[r]==="unverified"&&e.citationRequiresSha){if(Za(t))throw new Ua(n[r].file,e.citationAllowedExternalRoots);console.error(`${o}: citation_requires_sha waived for path-less project uid="${t.uid}" — cannot verify citation "${n[r].file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}}async function $i(t,e,n,i,o){const r=await Qc(t,n,e.citationAllowedExternalRoots,i);return Zc(t,e,n,r,o),r}async function Kn(t,e,n){const i=await X(t,{at:n.at,kind:"citation",name:n.citation.file,content:n.citation.context??n.citation.file,metadata:Pg(n.citation,n.sha,n.at)}),o=await q(t,"has_citation");return await K(t,{at:n.at,srcRowid:n.issueRowid,srcUid:n.issueUid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"citation",rel:"has_citation",rule:o,typePolicy:e.typePolicy}),i}async function _w(t,e){const{rows:n}=await t.executeAll("SELECT dst FROM edge WHERE src = ? AND rel = 'has_citation' AND t_invalid IS NULL",[e]),i=[];for(const o of n){const r=await Q(t,o.dst);r&&r.tInvalid===null&&i.push({rowid:r.rowid,uid:r.uid,key:Ug(r.metadata)})}return i}async function ed(t,e){const n=await Q(t,e.citationRowid);if(!n)throw new Error(`removeCitation: citation rowid=${e.citationRowid} vanished mid-transaction.`);const i={...n.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:e.at},o=await t.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[e.at,JSON.stringify(i),n.rowid]);if(o.rowsAffected!==1)throw new Error(`removeCitation: invalidate UPDATE affected ${o.rowsAffected} rows for uid="${e.citationUid}", expected exactly 1.`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_citation' AND t_invalid IS NULL",[n.rowid]);r&&await ie(t,{srcRowid:r.src,dstRowid:n.rowid,rel:"has_citation",reason:e.reason,at:e.at})}async function Aw(t,e){try{const n=await se(t,e,{expectedKind:"citation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new Ba(e):n}}async function Nw(t,e){var a;_t("uid",e.uid),_t("by",e.by),G("by",e.by),_t("citation.file",(a=e.citation)==null?void 0:a.file);const n=await ae(t.adapter,e.uid),i=await ww(t.adapter,n.rowid),o=Se(i),r=await Lt(t.adapter,i.uid),s=await $i(i,o,[e.citation],r,"addCitation");return M(t,async c=>{const d=P(),l=await ae(c,e.uid),u=await Kn(c,t,{issueRowid:l.rowid,issueUid:l.uid,citation:e.citation,sha:s[0],at:d});return await U({tx:c,typePolicy:t.typePolicy,subjectRowid:l.rowid,subjectUid:l.uid,subjectKind:"issue",actor:e.by,action:"citation-added",to:u.uid,note:e.citation.file,at:d}),{uid:u.uid,issueUid:l.uid,citation:{uid:u.uid,file:e.citation.file,lines:e.citation.lines,context:e.citation.context,symbol:e.citation.symbol,blastRadius:e.citation.blastRadius,revision:e.citation.revision,sha:s[0],at:d,targetType:"path"}}})}async function Rw(t,e){return _t("uid",e.uid),_t("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await Aw(n,e.uid),r=await n.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_citation' AND t_invalid IS NULL",[o.rowid]);let s=o.rowid,a=o.uid,c="citation";if(r){const d=await Q(n,r.src);(d==null?void 0:d.kind)==="issue"&&d.tInvalid===null&&(s=d.rowid,a=d.uid,c="issue")}return await ed(n,{citationRowid:o.rowid,citationUid:o.uid,at:i,reason:e.reason}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:s,subjectUid:a,subjectKind:c,actor:e.by,action:"citation-removed",from:o.uid,note:e.reason,at:i}),{uid:o.uid,invalidated:!0}})}const ds=["abort","force","comment"];function yt(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}const ls=512;function td(t){if(typeof t=="string"&&t.length>ls)throw new T("gitContext",`must be at most ${ls} characters, got ${t.length}`)}function us(t,e,n){if(t.length>0&&!t.includes(n))throw new T(e,`"${n}" is not in this project's allowed ${e} set`)}function jw(t,e){for(const n of t){const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Tw(t,e){var r;const n=await Dn(t,e),i=new Set([n.id]);let o=n;for(;;){const a=(r=(await t.getEdges({src:o.id,rel:"part_of"}))[0])==null?void 0:r.dst;if(a===void 0||i.has(a))break;const[c]=await t.getNodesByIds([a]);if(!c||c.tInvalid!==void 0)break;i.add(c.id),o=c}return i}async function Ow(t,e,n,i){var s,a;const o=[];for(const c of n)o.push(c.file),typeof c.symbol=="string"&&o.push(c.symbol),typeof c.blastRadius=="string"&&o.push(c.blastRadius);let r;if(i!==void 0){const c=await Ve(t,e.uid,i);r=(s=c==null?void 0:c.record.metadata)==null?void 0:s.path}else{const c=await t.getEdges({src:e.rowid,rel:"owns_project"}),l=(await t.getNodesByIds(c.map(u=>u.dst))).find(u=>u.tInvalid===void 0&&u.name==="(root)");r=(a=l==null?void 0:l.metadata)==null?void 0:a.path}return{citationTokens:o,...typeof r=="string"?{componentPath:r}:{}}}async function Iw(t,e,n,i,o,r,s,a){const c=a!==void 0&&t.graph!==void 0?await Tw(t.graph,a):void 0;if(!n.dedupeScanEnabled)return{candidates:[],similarCandidates:[],degraded:!1};const d=t.graph!==void 0?await Ow(t.graph,e,r,s):void 0,l=await Dc(t,{title:i,body:o,scope:n.similarityScope,projectUid:e.uid,sameProjectThreshold:n.dedupeThreshold,crossProjectThreshold:n.similarityCrossProjectThreshold,margin:n.similarityCrossProjectMargin,tokenOverlapMin:n.similarityCrossProjectTokenOverlap,citationTokens:d==null?void 0:d.citationTokens,componentPath:d==null?void 0:d.componentPath,excludeIds:c}),u=l.candidates.filter(m=>m.scope==="same-project").map(m=>({uid:m.uid,title:m.title,score:m.score})),f=l.candidates.filter(m=>m.scope==="cross-project");return{candidates:u,similarCandidates:f,degraded:l.degraded,...l.degradedReason!==void 0?{degradedReason:l.degradedReason}:{}}}async function $w(t,e){var g;yt("title",e.title),yt("body",e.body),yt("project",e.project),yt("by",e.by),G("by",e.by),td(e.gitContext);const n=e.citations??[];n.forEach((y,w)=>yt(`citations[${w}].file`,y.file));const i=typeof e.gitContext=="string"&&e.gitContext.trim().length>0?e.gitContext:void 0,o=e.duplicateAction??"abort";if(e.duplicateAction!==void 0&&!ds.includes(e.duplicateAction))throw new T("duplicateAction",`must be one of ${ds.map(y=>`'${y}'`).join("|")}, got "${e.duplicateAction}"`);const r=await at(t.adapter,e.project),s=Se(r),a=await Lt(t.adapter,r.uid),c=await $i(r,s,n,a,"createIssue"),d=await Iw(t,r,s,e.title,e.body,n,e.component,e.dedupeExcludeUid),{candidates:l}=d,u=d.similarCandidates??[];if(o==="comment"){const y=l[0],w=u[0];if(w&&(!y||w.score>y.score))throw new T("duplicateAction",`"comment" cannot target a cross-project candidate (top cross-project match uid="${w.uid}", project "${((g=w.provenance)==null?void 0:g.projectUid)??"?"}") — a reviewed similar_to link is written with relate; comment may only attach to a same-project duplicate`)}if(d.degraded&&d.degradedReason==="no-embed-query"&&o==="abort")return{created:!1,reason:"duplicate-scan-degraded",duplicateScanDegraded:!0,...d.degradedReason!==void 0?{duplicateScanDegradedReason:d.degradedReason}:{}};if(l.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:l,...u.length>0?{similarCandidates:u}:{}};const f=d.degraded?{duplicateScanDegraded:!0,...d.degradedReason!==void 0?{duplicateScanDegradedReason:d.degradedReason}:{}}:{};let m;const p=await M(t,async y=>{const w=P();if(l.length>0&&o==="comment"){const[Z]=l,ut=await ae(y,Z.uid),ft=`${e.title}
206
211
 
207
- ${t.body}`,P=await J(u,{kind:"note",content:M,metadata:{author:t.by,text:M,at:f},at:f}),X=await L(u,"has_note");return await x(u,{at:f,srcRowid:q.rowid,srcUid:q.uid,srcKind:"issue",dstRowid:P.rowid,dstUid:P.uid,dstKind:"note",rel:"has_note",rule:X,typePolicy:e.typePolicy}),{created:!1,commentedOn:{uid:q.uid,noteId:P.uid},duplicateCandidates:c}}const m=await Ze(u,t.project),p=Fe(m),g=t.component!==void 0?await yo(u,{projectUid:m.uid,ref:t.component}):await ps(u,{projectRowid:m.rowid}),b=t.kind??p.defaultKind??"issue",h=await je(u,{catalogKind:"kind",ref:b,at:f});qr(p.allowedKinds,"kind",h.name);const y=t.status??p.defaultStatus??"open",w=await ms(u,{ref:y,at:f});qr(p.allowedStatuses,"status",w.name);let v;t.priority!==void 0&&(v=await je(u,{catalogKind:"priority",ref:t.priority,at:f,mintMetadata:async C=>({rank:await gs(C)})}));const S=t.author??t.by,E=await je(u,{catalogKind:"agent",ref:S,at:f});Pm(p.requiredFields,{...t,component:g.name,kind:h.name,status:w.name,priority:v==null?void 0:v.name});const A={};t.assignee!==void 0&&(A.assignee=t.assignee),o!==void 0&&(A.gitContext=o);const _=await J(u,{kind:"issue",name:t.title,content:t.body,metadata:A,at:f});d={rowid:_.rowid,uid:_.uid};const N=await L(u,"owns_component");await x(u,{at:f,srcRowid:g.rowid,srcUid:g.uid,srcKind:"component",dstRowid:_.rowid,dstUid:_.uid,dstKind:"issue",rel:"owns_component",rule:N,typePolicy:e.typePolicy});const j=await L(u,"has_kind");await x(u,{at:f,srcRowid:_.rowid,srcUid:_.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"kind",rel:"has_kind",rule:j,typePolicy:e.typePolicy});const O=await L(u,"has_status");if(await x(u,{at:f,srcRowid:_.rowid,srcUid:_.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"status",rel:"has_status",rule:O,typePolicy:e.typePolicy}),v){const C=await L(u,"has_priority");await x(u,{at:f,srcRowid:_.rowid,srcUid:_.uid,srcKind:"issue",dstRowid:v.rowid,dstUid:v.uid,dstKind:"priority",rel:"has_priority",rule:C,typePolicy:e.typePolicy})}const I=await L(u,"authored_by");if(await x(u,{at:f,srcRowid:_.rowid,srcUid:_.uid,srcKind:"issue",dstRowid:E.rowid,dstUid:E.uid,dstKind:"agent",rel:"authored_by",rule:I,typePolicy:e.typePolicy}),n.length>0){const C=await L(u,"has_citation");for(let q=0;q<n.length;q+=1){const M=n[q],P=a[q],X=await J(u,{at:f,kind:"citation",name:M.file,content:M.context??M.file,metadata:{target:M.file,target_type:"path",sha:P,line:M.lines??null,at:f,symbol:M.symbol??null,blastRadius:M.blastRadius??null}});await x(u,{at:f,srcRowid:_.rowid,srcUid:_.uid,srcKind:"issue",dstRowid:X.rowid,dstUid:X.uid,dstKind:"citation",rel:"has_citation",rule:C,typePolicy:e.typePolicy})}}return await B({tx:u,typePolicy:e.typePolicy,subjectRowid:_.rowid,subjectUid:_.uid,subjectKind:"issue",actor:t.by,action:"created",at:f}),{created:!0,uid:_.uid,item:{uid:_.uid,title:t.title,kind:h.name,status:w.name,priority:v==null?void 0:v.name,project:m.uid,component:g.uid,createdAt:f,assignee:t.assignee,author:E.name,...o!==void 0?{gitContext:o}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(d){const u=It(e,{action:"upsert",subjectRowid:d.rowid,subjectUid:d.uid,actor:t.by,content:wo(t.title,t.body)});t.awaitEmbed?await u:u.catch(()=>{})}return l}function bt(e,t){if(typeof t!="string"||t.trim().length===0)throw new T(e,"is required")}async function Um(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 o=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!o)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 r=await ee(e,o.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`update: resolved project rowid=${o.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??"",metadata:r.metadata}}function Dm(e,t){if(e.length>0&&!e.includes(t))throw new T("kind",`"${t}" is not in this project's allowed kind set`)}function Mm(e,t){for(const n of e){if(!(n in t))continue;const o=t[n];if(o==null||typeof o=="string"&&o.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Hr(e,t,n,o){const r=[],i=[];n.name!==void 0&&(r.push("name = ?"),i.push(n.name)),n.metadata!==void 0&&(r.push("meta = ?"),i.push(JSON.stringify(n.metadata))),r.push("t_updated = ?"),i.push(o);const s=await e.executeRun(`UPDATE node SET ${r.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 St(e,t,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const r=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&&r){const a=await ee(e,r.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}r&&await ge(e,{srcRowid:n.oldSrcRowid,dstRowid:r.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await L(e,n.rel);await x(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 Fm(e,t,n){if(n.oldIssueRowid===n.newIssueRowid)return;const o=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!o)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 r=await ee(e,o.src);if((r==null?void 0:r.kind)!=="component"||r.tInvalid!==null)throw new Error(`update: resolved component rowid=${o.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await ge(e,{srcRowid:o.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const i=await L(e,"owns_component");await x(e,{at:n.at,srcRowid:o.src,srcUid:r.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:i,typePolicy:t.typePolicy})}const Vr=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Bm(e,t){if(t.oldIssueRowid===t.newIssueRowid)return;const n=Vr.map(()=>"?").join(", ");for(const o of["outgoing","incoming"]){const r=o==="outgoing"?"src":"dst",i=o==="outgoing"?"dst":"src",{rows:s}=await e.executeAll(`SELECT ${i} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${r} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[t.oldIssueRowid,...Vr]);for(const a of s){const c=o==="outgoing"?t.oldIssueRowid:a.other,d=o==="outgoing"?a.other:t.oldIssueRowid,l=o==="outgoing"?t.newIssueRowid:a.other,u=o==="outgoing"?a.other:t.newIssueRowid;await ge(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)
212
+ ${e.body}`,pt=await X(y,{kind:"note",content:ft,metadata:{author:e.by,text:ft,at:w},at:w}),Vt=await q(y,"has_note");return await K(y,{at:w,srcRowid:ut.rowid,srcUid:ut.uid,srcKind:"issue",dstRowid:pt.rowid,dstUid:pt.uid,dstKind:"note",rel:"has_note",rule:Vt,typePolicy:t.typePolicy}),{created:!1,commentedOn:{uid:ut.uid,noteId:pt.uid},duplicateCandidates:l,...u.length>0?{similarCandidates:u}:{},...f}}const v=await at(y,e.project),b=Se(v),h=e.component!==void 0?await Ei(y,{projectUid:v.uid,ref:e.component}):await Wa(y,{projectRowid:v.rowid}),S=e.component!==void 0?"explicit":"default-root",E=e.kind??b.defaultKind??"issue",N=await xe(y,{catalogKind:"kind",ref:E,at:w});us(b.allowedKinds,"kind",N.name);const k=e.status??b.defaultStatus??"open",R=await Ya(y,{ref:k,at:w});us(b.allowedStatuses,"status",R.name);let A;e.priority!==void 0&&(A=await xe(y,{catalogKind:"priority",ref:e.priority,at:w,mintMetadata:async Z=>({rank:await Xa(Z)})}));const O=e.author??e.by,I=await xe(y,{catalogKind:"agent",ref:O,at:w});jw(b.requiredFields,{...e,component:h.name,kind:N.name,status:R.name,priority:A==null?void 0:A.name});const L={revision:0};e.assignee!==void 0&&(L.assignee=e.assignee),i!==void 0&&(L.gitContext=i);const $=await X(y,{kind:"issue",name:e.title,content:e.body,metadata:L,at:w});m={rowid:$.rowid,uid:$.uid};const Y=await q(y,"owns_component");await K(y,{at:w,srcRowid:h.rowid,srcUid:h.uid,srcKind:"component",dstRowid:$.rowid,dstUid:$.uid,dstKind:"issue",rel:"owns_component",rule:Y,typePolicy:t.typePolicy});const H=await q(y,"has_kind");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:N.rowid,dstUid:N.uid,dstKind:"kind",rel:"has_kind",rule:H,typePolicy:t.typePolicy});const ge=await q(y,"has_status");if(await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:R.rowid,dstUid:R.uid,dstKind:"status",rel:"has_status",rule:ge,typePolicy:t.typePolicy}),A){const Z=await q(y,"has_priority");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:A.rowid,dstUid:A.uid,dstKind:"priority",rel:"has_priority",rule:Z,typePolicy:t.typePolicy})}const lt=await q(y,"authored_by");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:I.rowid,dstUid:I.uid,dstKind:"agent",rel:"authored_by",rule:lt,typePolicy:t.typePolicy});for(let Z=0;Z<n.length;Z+=1)await Kn(y,t,{issueRowid:$.rowid,issueUid:$.uid,citation:n[Z],sha:c[Z],at:w});return await U({tx:y,typePolicy:t.typePolicy,subjectRowid:$.rowid,subjectUid:$.uid,subjectKind:"issue",actor:e.by,action:"created",at:w}),{created:!0,uid:$.uid,item:{uid:$.uid,title:e.title,kind:N.name,status:R.name,priority:A==null?void 0:A.name,project:v.uid,component:h.uid,createdAt:w,assignee:e.assignee,author:I.name,...i!==void 0?{gitContext:i}:{}},...l.length>0?{duplicateCandidates:l}:{},...u.length>0?{similarCandidates:u}:{},...f,placementResolved:S}});if(m){const y=hn(t,{action:"upsert",subjectRowid:m.rowid,subjectUid:m.uid,actor:e.by,content:Si(e.title,e.body)});e.awaitEmbed?await y:y.catch(()=>{})}return p}function wt(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}async function fs(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)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 Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${i.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 Cw(t,e){if(t.length>0&&!t.includes(e))throw new T("kind",`"${e}" is not in this project's allowed kind set`)}function Pw(t,e){for(const n of t){if(!(n in e))continue;const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function ps(t,e,n,i){const o=[],r=[];n.name!==void 0&&(o.push("name = ?"),r.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),r.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),r.push(i);const s=await t.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...r,e]);if(s.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${s.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function rn(t,e,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let r=n.override;if(!r&&o){const a=await Q(t,o.dst);(a==null?void 0:a.tInvalid)===null&&(r={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!r){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 ie(t,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await q(t,n.rel);await K(t,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:r.rowid,dstUid:r.uid,dstKind:r.kind,rel:n.rel,rule:s,typePolicy:e.typePolicy})}async function Lw(t,e,n){if(n.oldIssueRowid===n.newIssueRowid)return;const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!i)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 Q(t,i.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${i.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await ie(t,{srcRowid:i.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const r=await q(t,"owns_component");await K(t,{at:n.at,srcRowid:i.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:r,typePolicy:e.typePolicy})}const ms=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Uw(t,e){if(e.oldIssueRowid===e.newIssueRowid)return;const n=ms.map(()=>"?").join(", ");for(const i of["outgoing","incoming"]){const o=i==="outgoing"?"src":"dst",r=i==="outgoing"?"dst":"src",{rows:s}=await t.executeAll(`SELECT ${r} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[e.oldIssueRowid,...ms]);for(const a of s){const c=i==="outgoing"?e.oldIssueRowid:a.other,d=i==="outgoing"?a.other:e.oldIssueRowid,l=i==="outgoing"?e.newIssueRowid:a.other,u=i==="outgoing"?a.other:e.newIssueRowid;await ie(t,{srcRowid:c,dstRowid:d,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:e.at}),await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
208
213
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
209
214
  ON CONFLICT(src, dst, rel) DO UPDATE SET
210
215
  weight = excluded.weight, confidence = excluded.confidence,
211
216
  origin = excluded.origin, meta = excluded.meta,
212
- 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 Km(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 qm(e,t){const n=["title","body","kind","priority","assignee","author"];for(const o of n)if(e[o]!==void 0&&!t.includes(o))throw new Error(`update: patch key "${o}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function Hm(e,t){if(bt("uid",t.uid),bt("by",t.by),Z("by",t.by),t.status!==void 0)throw new Oe("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");t.title!==void 0&&bt("title",t.title),t.body!==void 0&&bt("body",t.body);const o=Km(t);if(o.length===0)throw new T("patch","update requires at least one of title/body/kind/priority/assignee/author");qm(t,o);let r;const i=await V(e,async s=>{const a=D(),c=await Se(s,t.uid),d=await Um(s,c.rowid),l=Fe(d);let u;if(t.kind!==void 0){const y=await je(s,{catalogKind:"kind",ref:t.kind,at:a});Dm(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 je(s,{catalogKind:"priority",ref:t.priority,at:a,mintMetadata:async w=>({rank:await gs(w)})});f={rowid:y.rowid,uid:y.uid,kind:"priority",name:y.name}}let m;if(t.author!==void 0){const y=await je(s,{catalogKind:"agent",ref:t.author,at:a});m={rowid:y.rowid,uid:y.uid,kind:"agent",name:y.name}}const p={...t};u&&(p.kind=u.name),f&&(p.priority=f.name),m&&(p.author=m.name),Mm(l.requiredFields,p);let g=c.rowid,b=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 Kt(t.uid);const w=t.title??c.name??void 0,v={...c.metadata??{}};t.assignee!==void 0&&(v.assignee=t.assignee);const S=await J(s,{kind:"issue",name:w,content:t.body,metadata:v,at:a});await s.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
217
+ t_invalid = NULL, t_valid = excluded.t_valid`,[l,u,a.rel,a.weight,a.confidence,a.origin,a.meta,e.at,e.at])}}}function Dw(t){const e=[];return t.title!==void 0&&e.push("title"),t.body!==void 0&&e.push("body"),t.kind!==void 0&&e.push("kind"),t.priority!==void 0&&e.push("priority"),t.assignee!==void 0&&e.push("assignee"),t.author!==void 0&&e.push("author"),t.citations!==void 0&&e.push("citations"),e}function Mw(t,e){const n=["title","body","kind","priority","assignee","author","citations"];for(const i of n)if(t[i]!==void 0&&!e.includes(i))throw new Error(`update: patch key "${i}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function xw(t,e){if(wt("uid",e.uid),wt("by",e.by),G("by",e.by),e.status!==void 0)throw new _e("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");e.title!==void 0&&wt("title",e.title),e.body!==void 0&&wt("body",e.body);const i=Dw(e);if(i.length===0)throw new T("patch","update requires at least one of title/body/kind/priority/assignee/author/citations");Mw(e,i),e.citations!==void 0&&e.citations.forEach((a,c)=>wt(`citations[${c}].file`,a.file));let o=[];if(e.citations!==void 0&&e.citations.length>0){const a=await se(t.adapter,e.uid,{expectedKind:"issue"}),c=await fs(t.adapter,a.rowid),d=Se(c),l=await Lt(t.adapter,c.uid);o=await Qc(c,e.citations,d.citationAllowedExternalRoots,l)}let r;const s=await M(t,async a=>{const c=P(),d=await ae(a,e.uid),l=await fs(a,d.rowid),u=Se(l);let f;if(e.kind!==void 0){const b=await xe(a,{catalogKind:"kind",ref:e.kind,at:c});Cw(u.allowedKinds,b.name),f={rowid:b.rowid,uid:b.uid,kind:"kind",name:b.name}}let m;if(e.priority!==void 0){const b=await xe(a,{catalogKind:"priority",ref:e.priority,at:c,mintMetadata:async h=>({rank:await Xa(h)})});m={rowid:b.rowid,uid:b.uid,kind:"priority",name:b.name}}let p;if(e.author!==void 0){const b=await xe(a,{catalogKind:"agent",ref:e.author,at:c});p={rowid:b.rowid,uid:b.uid,kind:"agent",name:b.name}}const g={...e};f&&(g.kind=f.name),m&&(g.priority=m.name),p&&(g.author=p.name),Pw(u.requiredFields,g);let y=d.rowid,w=d.uid,v=!1;if(e.body!==void 0){if((await a.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[d.rowid])).rowsAffected!==1)throw new Ut(e.uid);const h=e.title??d.name??void 0,S={...d.metadata??{},revision:re(d.metadata)};e.assignee!==void 0&&(S.assignee=e.assignee);const E=await X(a,{kind:"issue",name:h,content:e.body,metadata:S,at:c});await a.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
213
218
  VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
214
219
  ON CONFLICT(src, dst, rel) DO UPDATE SET
215
220
  meta = excluded.meta, weight = excluded.weight,
216
- t_invalid = NULL, t_valid = excluded.t_valid`,[S.rowid,c.rowid,a,a]),await Hr(s,S.rowid,{},a),r={oldRowid:c.rowid,oldUid:c.uid,newRowid:S.rowid,newUid:S.uid,newTitle:w??"",newBody:t.body},g=S.rowid,b=S.uid,h=!0}else{const y=t.assignee!==void 0?{...c.metadata??{},assignee:t.assignee}:void 0;await Hr(s,c.rowid,{name:t.title,metadata:y},a)}return await Fm(s,e,{oldIssueRowid:c.rowid,newIssueRowid:g,newIssueUid:b,at:a}),await St(s,e,{rel:"has_status",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,reason:"superseded — status carried forward to the new node (update never changes status)",at:a,required:!0}),await St(s,e,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:u,reason:"kind changed via update",at:a}),await St(s,e,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:f,reason:"priority changed via update",at:a}),await St(s,e,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:m,reason:"author changed via update",at:a}),await Bm(s,{oldIssueRowid:c.rowid,newIssueRowid:g,at:a}),await B({tx:s,typePolicy:e.typePolicy,subjectRowid:g,subjectUid:b,subjectKind:"issue",actor:t.by,action:"updated",from:h?c.uid:void 0,to:h?b:void 0,note:`fields changed: ${o.join(", ")}`,at:a}),{uid:b,changed:o}});if(r){const{oldRowid:s,oldUid:a,newRowid:c,newUid:d,newTitle:l,newBody:u}=r,f=Promise.all([It(e,{action:"delete",subjectRowid:s,subjectUid:a,actor:t.by}),It(e,{action:"upsert",subjectRowid:c,subjectUid:d,actor:t.by,content:wo(l,u)})]);t.awaitEmbed?await f:f.catch(()=>{})}return i}function Xs(e){const t=e??{};return{claimedBy:typeof t.claimedBy=="string"?t.claimedBy:void 0,claimedAt:typeof t.claimedAt=="string"?t.claimedAt:void 0}}function Qs(e,t){return e!==void 0?(Date.parse(t)-Date.parse(e))/6e4:Number.POSITIVE_INFINITY}function Zs(e,t,n){return Qs(e,t)>=n}async function ea(e,t,n){const o=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[t,"has_status"]);if(!o)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 r=await ee(e,o.dst);if((r==null?void 0:r.kind)!=="status"||r.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${o.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return r}function Et(e,t){if(typeof t!="string"||t.trim().length===0)throw new T(e,"is required")}async function Gr(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 o=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!o)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 r=await ee(e,o.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`transition: resolved project rowid=${o.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??"",metadata:r.metadata}}async function Vm(e,t,n){if(!Vt(e))return"unverified";try{const{accepted:o,candidate:r}=await Yi(e.metadata.path,t,n);if(!o)return"unverified";const i=await Lt.readFile(r);return me.createHash("sha256").update(i).digest("hex")}catch(o){if(lo(o))return"unverified";throw os(o,t)}}function Gm(e,t){if(e.length>0&&!e.includes(t))throw new T("toStatus",`"${t}" is not in this project's allowed status set`)}function Wm(e,t){for(const n of e){if(!(n in t))continue;const o=t[n];if(o==null||typeof o=="string"&&o.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Jm(e,t){Et("uid",t.uid),Et("by",t.by),Z("by",t.by),Et("toStatus",t.toStatus),Ys(t.gitContext);const n=t.citations??[];n.forEach((r,i)=>Et(`citations[${i}].file`,r.file));const o=[];if(n.length>0){const r=await mo(e.adapter,t.uid,{expectedKind:"issue"}),i=await Gr(e.adapter,r.rowid),s=Fe(i);for(const a of n){const c=await Vm(i,a.file,s.citationAllowedExternalRoots);if(c==="unverified"&&s.citationRequiresSha){if(Vt(i))throw new uo(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).`)}o.push(c)}}return V(e,async r=>{var _;const i=D(),s=await Se(r,t.uid),a=await Gr(r,s.rowid),c=Fe(a),{claimedBy:d,claimedAt:l}=Xs(s.metadata);if(d!==void 0&&d!==t.by&&!Zs(l,i,c.claimStaleAfterMin))throw new Ot(d,l??i);const u=await ea(r,s.rowid,"transition"),f=u.name??"",m=await ms(r,{ref:t.toStatus,at:i});Gm(c.allowedStatuses,m.name),Wm(c.requiredFields,{status:m.name,note:t.note});const p=await ee(r,m.rowid),g=((_=p==null?void 0:p.metadata)==null?void 0:_.terminal)===!0;if(!(typeof t.note=="string"&&t.note.trim().length>0)&&c.transitionRequiresNote)throw new rs(s.uid);if(g&&c.citationRequired&&n.length===0)throw new is(s.uid);const h={target_uid:s.uid,from:f,to:m.name,agent:t.by,note:t.note??null,at:i},y=po(fs(h)),w=await J(r,{kind:"transition",content:t.note??"",metadata:{from_status:f,to_status:m.name,agent:t.by,note:t.note??null,sha:y,at:i},at:i}),v=await L(r,"has_transition");await x(r,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"transition",rel:"has_transition",rule:v,typePolicy:e.typePolicy}),await ge(r,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${m.name}"`,at:i});const S=await L(r,"has_status");if(await x(r,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:m.rowid,dstUid:m.uid,dstKind:"status",rel:"has_status",rule:S,typePolicy:e.typePolicy}),n.length>0){const N=await L(r,"has_citation");for(let j=0;j<n.length;j+=1){const O=n[j],I=o[j],C=await J(r,{at:i,kind:"citation",name:O.file,content:O.context??O.file,metadata:{target:O.file,target_type:"path",sha:I,line:O.lines??null,at:i,symbol:O.symbol??null,blastRadius:O.blastRadius??null}});await x(r,{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??{}};g?E.closedAt=i:delete E.closedAt,typeof t.gitContext=="string"&&t.gitContext.trim().length>0&&(E.gitContext=t.gitContext);const A=await r.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 B({tx:r,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"transitioned",from:f,to:m.name,note:t.note,at:i}),{uid:s.uid,fromStatus:f,toStatus:m.name,closedAt:g?i:void 0,transitionUid:w.uid}})}function Wr(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function zm(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 o=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!o)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 r=await ee(e,o.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`claim: resolved project rowid=${o.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const i={rowid:r.rowid,uid:r.uid,name:r.name??"",metadata:r.metadata};return Fe(i)}async function Ge(e,t,n,o){const r=await e.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),o,t]);if(r.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${r.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function Ym(e,t){if(Wr("uid",t.uid),Wr("by",t.by),Z("by",t.by),t.action!=="claim"&&t.action!=="release"&&t.action!=="renew")throw new T("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(t.action)})`);const n=t.force===!0;return V(e,async o=>{var d;const r=D(),i=await Se(o,t.uid),s={...i.metadata??{}},{claimedBy:a,claimedAt:c}=Xs(s);if(t.action==="claim"){const l=await ea(o,i.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new ns(i.uid,l.name??"");if(a===void 0){const g={...s,claimedBy:t.by,claimedAt:r};return await Ge(o,i.rowid,g,r),await B({tx:o,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",to:t.by,at:r}),{uid:i.uid,status:"claimed",claimedBy:t.by,claimedAt:r}}if(a===t.by){const g={...s,claimedAt:r};return await Ge(o,i.rowid,g,r),await B({tx:o,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:r}),{uid:i.uid,status:"held",heldBy:t.by,claimedBy:t.by,claimedAt:r}}const u=await zm(o,i.rowid),f=Qs(c,r),m=Zs(c,r,u.claimStaleAfterMin);if(!m&&!n)throw new Ot(a,c??r);const p={...s,claimedBy:t.by,claimedAt:r,previousClaimant:a};return await Ge(o,i.rowid,p,r),await B({tx:o,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"reclaimed-stale",from:a,to:t.by,note:m?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${u.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:r}),{uid:i.uid,status:"reclaimed-stale",claimedBy:t.by,claimedAt:r,previousClaimant:a}}if(t.action==="release"){if(a===t.by){const l={...s};return delete l.claimedBy,delete l.claimedAt,await Ge(o,i.rowid,l,r),await B({tx:o,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"released",from:t.by,at:r}),{uid:i.uid,status:"released"}}return{uid:i.uid,status:"release-noop",wasClaimedBy:a}}if(a===t.by){const l={...s,claimedAt:r};return await Ge(o,i.rowid,l,r),await B({tx:o,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"renewed",from:t.by,to:t.by,at:r}),{uid:i.uid,status:"renewed",claimedBy:t.by,claimedAt:r}}throw new Ot(a??"",c??"")})}const Jr=["relates_to","supersedes","blocks","duplicate_of","part_of"];function dn(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function Xm(e,t,n,o){const r=await e.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t,n,o]);return r?r.rowid:null}async function Qm(e,t){if(dn("sourceUid",t.sourceUid),dn("targetUid",t.targetUid),dn("by",t.by),Z("by",t.by),!Jr.includes(t.rel))throw new T("rel",`must be one of ${Jr.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.rel)})`);if(t.action!=="add"&&t.action!=="remove")throw new T("action",`must be "add" or "remove" (got ${JSON.stringify(t.action)})`);if(t.sourceUid===t.targetUid)throw new T("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return V(e,async n=>{const o=D(),r=await Se(n,t.sourceUid),i=await Se(n,t.targetUid),s=await Xm(n,r.rowid,i.rowid,t.rel);if(t.action==="add"){if(s!==null)return{sourceUid:r.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!0};const a=await L(n,t.rel);return await x(n,{at:o,srcRowid:r.rowid,srcUid:r.uid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"issue",rel:t.rel,rule:a,typePolicy:e.typePolicy}),await B({tx:n,typePolicy:e.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:t.by,action:"related",to:i.uid,note:t.rel,at:o}),{sourceUid:r.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!1}}return s===null?{sourceUid:r.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!0}:(await ge(n,{srcRowid:r.rowid,dstRowid:i.rowid,rel:t.rel,reason:`relate: removed by "${t.by}"`,at:o}),await B({tx:n,typePolicy:e.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:t.by,action:"unrelated",to:i.uid,note:t.rel,at:o}),{sourceUid:r.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!1})})}function zr(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function Zm(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 o=await ee(e,n.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??""}}async function eg(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 o=await ee(e,n.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??""}}async function tg(e,t){return zr("uid",t.uid),zr("by",t.by),Z("by",t.by),V(e,async n=>{const o=D(),r=await Se(n,t.uid),i=await Zm(n,r.rowid),s=await eg(n,i.rowid);let a;if(t.toProject!==void 0){const l=await Ze(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 yo(n,{projectUid:a.uid,ref:t.toComponent}):c=await ps(n,{projectRowid:a.rowid}),c.rowid===i.rowid)return{uid:r.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid};await ge(n,{srcRowid:i.rowid,dstRowid:r.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:o});const d=await L(n,"owns_component");return await x(n,{at:o,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:r.rowid,dstUid:r.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:e.typePolicy}),await B({tx:n,typePolicy:e.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:t.by,action:"moved",from:i.uid,to:c.uid,at:o}),{uid:r.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid}})}function ln(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function ng(e,t){ln("uid",t.uid),ln("by",t.by),Z("by",t.by),ln("reason",t.reason);let n;const o=await V(e,async r=>{const i=D(),s=await Se(r,t.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:t.reason,invalidatedAt:i},c=await r.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 B({tx:r,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 r=It(e,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:t.by});t.awaitEmbed?await r:r.catch(()=>{})}return o}function Pt(e){var t;return(t=e.env.version)==null?void 0:t.configHash}async function ta(e){const t=e.embeddingConfig;t!=null&&t.refresh().changed&&fm(e.store.adapter);const n=t?t.current():e.env.config.embedding;return lm(e.store.adapter,e.store.graph,n,void 0,{configuredEnabled:t?t.configured().enabled:n==null?void 0:n.enabled,startupHash:Pt(e),configuredHash:t?t.fingerprint().configHash:Pt(e),configPaths:t?t.fingerprint().files.map(o=>o.path):void 0})}async function te(e,t){await co(e.store.adapter);const{search:n,embedding:o}=t.needsSemantic?await ta(e):{};return{adapter:e.store.adapter,typePolicy:e.store.typePolicy,graph:e.store.graph,...n!==void 0?{search:n}:{},...o!==void 0?{embedding:o}:{}}}async function Wt(e,t){const{search:n}=t.needsSemantic?await ta(e):{},o=n!==void 0&&t.probeSpace?await n.spacePopulated():void 0;return{graph:e.store.graph,assertVocabulary:()=>co(e.store.adapter),assertCatalogInvariants:()=>Vs(e.store.adapter),...n!==void 0?{search:n}:{},...o!==void 0?{spacePopulated:o}:{}}}const og=[[ts,"item_not_found"],[es,"ambiguous_reference"],[W,"not_found"],[T,"invalid_argument"],[Ot,"conflict"],[$n,"conflict"],[Kt,"conflict"],[ns,"precondition_failed"],[is,"precondition_failed"],[rs,"precondition_failed"],[uo,"precondition_failed"],[Xi,"store_busy"],[qs,"rag_not_configured"]],rg={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function na(e){for(const[t,n]of og)if(e instanceof t){const o=e instanceof U?{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}:void 0;return ie(n,e.message,o)}return e instanceof U?ie(rg[e.code]??"internal",e.message,{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}):ie("internal",e instanceof Error?e.message:String(e))}async function G(e){try{return Ao(await e())}catch(t){return na(t)}}async function oa(e,t){return G(()=>"registry"in t?t.registry==="project"?cn(e.store.graph,{registry:"project",name:t.name}):t.registry==="component"?cn(e.store.graph,{registry:"component",name:t.name,filter:t.filter}):cn(e.store.graph,{registry:"location",name:t.name}):bm(e.store.graph,t))}async function ra(e,t){try{const{result:n,meta:o}=await rm(await Wt(e,{needsSemantic:em(t),probeSpace:t.text!==void 0}),t);return Ao(n,o?{meta:o}:void 0)}catch(n){return na(n)}}async function ia(e,t){return G(async()=>jm(await Wt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function sa(e,t){return G(async()=>Rm(await Wt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function aa(e,t){return G(async()=>$m(await Wt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function ca(e){return G(async()=>{const t=e.embeddingConfig,n=t?t.configured():e.env.config.embedding,o=t?t.current():e.env.config.embedding,r=um(e.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(o==null?void 0:o.enabled)===!0,provider:(o==null?void 0:o.provider)??"",model:(o==null?void 0:o.model)??"",membersPresent:{embedding:(r==null?void 0:r.embedding)??!1,search:(r==null?void 0:r.search)??!1},divergent:(n==null?void 0:n.enabled)===!0!=((o==null?void 0:o.enabled)===!0),startupHash:Pt(e)??"",currentHash:t?t.fingerprint().configHash:Pt(e)??""}})}async function da(e,t){return G(()=>Lp(e.store.graph,t.q))}async function la(e,t){return G(async()=>Lm(await te(e,{needsSemantic:!0}),t))}async function ua(e,t){return G(async()=>Hm(await te(e,{needsSemantic:!0}),t))}async function fa(e,t){return G(async()=>Jm(await te(e,{needsSemantic:!1}),t))}async function pa(e,t){return G(async()=>Ym(await te(e,{needsSemantic:!1}),t))}async function ma(e,t){return G(async()=>Qm(await te(e,{needsSemantic:!1}),t))}async function ga(e,t){return G(async()=>tg(await te(e,{needsSemantic:!1}),t))}async function ha(e,t){return G(async()=>ng(await te(e,{needsSemantic:!1}),t))}async function ya(e,t){return G(async()=>bu(await te(e,{needsSemantic:!1}),t))}async function wa(e,t){return G(async()=>Eu(await te(e,{needsSemantic:!1}),t))}async function va(e,t){return G(async()=>Au(await te(e,{needsSemantic:!1}),t))}async function ba(e,t){return G(async()=>_u(await te(e,{needsSemantic:!1}),t))}const ig=Object.freeze(Object.defineProperty({__proto__:null,claim:pa,create:la,delete:ha,embeddingStatus:ca,get:oa,lookup:da,move:ga,openCurve:aa,partOfRollup:sa,priorityMatrix:ia,query:ra,relate:ma,rmLocation:ba,transition:fa,update:ua,upsertComponent:wa,upsertLocation:va,upsertProject:ya},Symbol.toStringTag,{value:"Module"}));async function sg(e){let t;try{t=await ve.open(e,"r"),await t.sync()}catch{}finally{t&&await t.close().catch(()=>{})}}async function Sa(e,t){const n=k.dirname(e);await ve.mkdir(n,{recursive:!0});const o=`${e}.${process.pid}.${me.randomUUID()}.tmp`;let r;try{r=await ve.open(o,"w"),await r.writeFile(JSON.stringify(t),"utf8"),await r.sync(),await r.close(),r=void 0,await ve.rename(o,e),await sg(n)}catch(i){throw r&&await r.close().catch(()=>{}),await ve.unlink(o).catch(()=>{}),i}}function ag(e){return{async get(){try{const t=await ve.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await Sa(e,n)}}}const nt=1;function cg(e){return me.createHash("sha256").update(e).digest("hex")}async function Yr(e){return cg(await ve.readFile(e,"utf8"))}async function xt(e){try{return(await ve.stat(e)).mtimeMs}catch{return}}async function Xr(e,t){const n=await Yr(e.source),o=me.createHash("sha256");o.update(`formatVersion:${nt}
217
- `),o.update(`extractorVersion:${t}
218
- `),o.update(`host:${e.host}
219
- `),o.update(`namespace:${e.namespace??""}
220
- `),o.update(`source:${n}
221
- `);for(const r of ki(e.source))r!==e.source&&o.update(`dep:${r}:${await Yr(r)}
222
- `);return o.digest("hex")}async function Qr(e,t){const n=await xt(e.source)??0,o=[];for(const r of ki(e.source)){if(r===e.source)continue;const i=await xt(r);i!==void 0&&o.push({path:r,mtimeMs:i})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:o}}async function dg(e,t){if(t.source.path!==e.source)return!1;const n=await xt(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const o of t.deps){const r=await xt(o.path);if(r===void 0||r!==o.mtimeMs)return!1}return!0}function lg(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=ag(e.cache),n=e.extractorVersion;async function o(r,i,s){const a=s??await Xr(r,n),c=await Qr(r,a);await t.put(e.cache,{formatVersion:nt,operations:i,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(r,i)=>{const s=await t.get(e.cache);if((s==null?void 0:s.formatVersion)!==nt||s.extractorVersion!==n||!s.staleness){const d=await i();try{await o(r,d)}catch{}return d}if(await dg(r,s.staleness))return s.operations;const a=await Xr(r,n);if(a===s.staleness.contentKey)return Qr(r,a).then(d=>t.put(e.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await i();try{await o(r,c,a)}catch{}return c}}Vn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);const ug="api.ir.json",fg=Vn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href),_o=fg("@adhd/apigen-core-client/package.json").version;function Jt(){const e=k.dirname(ot.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href));return R.existsSync(k.join(e,"api.d.ts"))?e:k.join(e,"..","dist")}function pg(e){return k.join(e,ug)}function jo(e){return me.createHash("sha256").update(e).digest("hex")}function Ea(e){const t=[],n=r=>{let i;try{i=R.readdirSync(r,{withFileTypes:!0})}catch{return}for(const s of i){const a=k.join(r,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&t.push(a)}};n(e),t.sort();const o={};for(const r of t)o[k.relative(e,r).split(k.sep).join("/")]=jo(R.readFileSync(r));return o}function mg(e,t){const n=Object.keys(e).sort(),o=Object.keys(t).sort();if(n.length!==o.length)return!1;for(let r=0;r<n.length;r++){const i=n[r];if(i!==o[r]||e[i]!==t[i])return!1}return!0}function gg(e){try{const t=pg(e);if(!R.existsSync(t))return;const n=JSON.parse(R.readFileSync(t,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==nt||n.extractorVersion!==_o)return;const o=n.artifactSource;if(!o||typeof o.sha256!="string"||typeof o.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const r=k.join(e,"api.d.ts");if(!R.existsSync(r))return;const i=R.readFileSync(r);if(i.byteLength!==o.bytes||jo(i)!==o.sha256)return;const s=o.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return mg(s,Ea(e))?n.operations:void 0}catch{return}}async function hg(e){const t=R.readFileSync(e.apiDts),n={formatVersion:nt,operations:e.operations,extractorVersion:e.extractorVersion,createdAt:new Date().toISOString(),artifactSource:{path:e.apiDts,sha256:jo(t),bytes:t.byteLength,deps:Ea(k.dirname(e.apiDts))}};await Sa(e.outFile,n)}function yg(e={}){const t=vo("backlog",Be,{namespace:e.namespace??"production",scope:bo(e.scope),...e.adhdRoot!==void 0?{adhdRoot:e.adhdRoot}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),n=[k.join(t.roots.system,Pe),k.join(t.roots.global,Pe)];return t.roots.project&&(n.push(k.join(t.roots.project,Pe)),n.push(k.join(t.roots.project,vs))),[...new Set(n)]}const wg=e=>e instanceof Error?e.message:String(e),Zr=e=>({enabled:e.enabled===!0,provider:e.provider,model:e.model}),vg=(e,t)=>e.enabled===t.enabled&&e.provider===t.provider&&e.model===t.model;function bg(e){const t=()=>e.layerFiles().map(a=>{try{const c=R.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 o=Zr(e.baseline.config.embedding),r=o,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 (${wg(d)}) — continuing with the last known effective embedding settings`),!1}return i={configHash:c.version.configHash,files:a},r=Zr(c.config.embedding),!0};return{current:()=>o,configured:()=>(s(),r),divergent:()=>(s(),r.enabled&&!o.enabled),refresh:()=>{const a=o;return s(),vg(r,o)?{changed:!1,from:a,to:o}:(o=r,e.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${o.enabled}, provider ${o.provider}, model ${o.model}); adopting without restart`),{changed:!0,from:a,to:o})},fingerprint:()=>i}}function Sg(){const e=k.dirname(ot.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 R.existsSync(t)?t:k.join(e,"..","package.json")}function No(){const e=Sg(),t=JSON.parse(R.readFileSync(e,"utf8"));return{name:t.name,version:t.version}}function qn(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function ka(){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 ei=["install","install-skill","serve"];function Aa(e){return e.filter(t=>t.kind==="action").map(t=>{const n=Re(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 Eg(e){const t=e.filter(n=>{const o=n.cliPath[n.cliPath.length-1]??"";return ei.includes(o)||ei.some(r=>n.mcpTool.endsWith(`_${r.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 kg(e,t=[Rt]){const n=Aa(e),o=new Set(n.map(i=>i.mcpTool)),r={host:"backlog",operations:e};for(const i of t){const s=i.capabilities.mount;if(s)for(const a of s.operations(r,void 0,void 0))o.add(Re(a).mcp.name)}return[...o].sort()}function ti(e){if(!e||typeof e!="object")return e;const t={},n=r=>{if(Array.isArray(r)){for(const s of r)n(s);return}if(!r||typeof r!="object")return;const i=r;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 o=(r,i)=>{if(Array.isArray(r))return r.map(d=>o(d,i));if(!r||typeof r!="object")return r;const s=r,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return i.has(d)||!(d in t)?{}:o(t[d],new Set([...i,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=o(l,i));return c};return o(e,new Set)}async function Ag(e={}){const t=Jt(),n=k.join(t,"api.d.ts");if(!R.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 o=gg(t);return o||(await Promise.resolve().then(()=>qa)).extractApiOperationsLive(e)}async function Ro(e,t={}){const n=typeof e=="function"?e:()=>e,o=await Ag(t),r={schemas:Object.fromEntries(o.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:ti(c.input),output:ti(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},i=Tc(r,[]),s=Aa(o);Eg(s);const{version:a}=No();return{pkg:{id:"backlog",version:a,schemas:i,importPath:k.join(Jt(),"api.js"),fns:ig,createClient:async()=>n()},operations:o,surface:s}}async function _a(e){const t=xe({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace});t.ensureDirs();let n,o;const r=ze(t),i=()=>(n||(n=xn(o)),n),s=Ou()?void 0:ys(i);try{o=await $t(r,t.config.db.busyTimeoutMs)}catch(c){throw s==null||s.dispose(),c}const a={store:o,env:t,embeddingConfig:bg({baseline:t,rebuild:()=>xe({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),layerFiles:()=>yg({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 Ro(a,{adhdRoot:e.adhdRoot}),l=ka(),u=[];(e.transport==="http"||e.transport==="both")&&u.push(qn(Pf)({packages:[c],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[Mf,Rt]},signal:e.signal,operations:d,logger:l})),(e.transport==="mcp"||e.transport==="both")&&u.push(qn(ep)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[Rt]},signal:e.signal,operations:d,logger:l})),await Promise.all(u)}finally{s==null||s.dispose(),await i()}}const Ue=["claude","codex","opencode"],_g={claude:".claude",codex:".codex",opencode:".opencode"};function ja(e,t){return t?k.join(e,".codex"):process.env.CODEX_HOME??k.join(e,".codex")}function jg(e,t,n,o){if(t==="project")return k.join(n,_g[e],"skills");const r=o??z.homedir();return e==="claude"?k.join(r,".claude","skills"):e==="codex"?k.join(ja(r,o),"skills"):k.join(r,".config","opencode","skills")}function Ng(){const e=k.dirname(ot.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 R.existsSync(t)?t:k.join(e,"..","skill","SKILL.md")}class Q extends Error{constructor(t){super(t),this.name="BacklogUsageError"}}function Oo(e,t){console.error(JSON.stringify({code:"invalid_argument",message:e.message})),console.error(""),console.error(t),process.exitCode=2}const ni=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
221
+ t_invalid = NULL, t_valid = excluded.t_valid`,[E.rowid,d.rowid,c,c]),await ps(a,E.rowid,{},c),r={oldRowid:d.rowid,oldUid:d.uid,newRowid:E.rowid,newUid:E.uid,newTitle:h??"",newBody:e.body},y=E.rowid,w=E.uid,v=!0}else{const b={...d.metadata??{},...e.assignee!==void 0?{assignee:e.assignee}:{},revision:re(d.metadata)};await ps(a,d.rowid,{name:e.title,metadata:b},c)}if(await Lw(a,t,{oldIssueRowid:d.rowid,newIssueRowid:y,newIssueUid:w,at:c}),await rn(a,t,{rel:"has_status",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,reason:"superseded — status carried forward to the new node (update never changes status)",at:c,required:!0}),await rn(a,t,{rel:"has_kind",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:f,reason:"kind changed via update",at:c}),await rn(a,t,{rel:"has_priority",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:m,reason:"priority changed via update",at:c}),await rn(a,t,{rel:"authored_by",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:p,reason:"author changed via update",at:c}),await Uw(a,{oldIssueRowid:d.rowid,newIssueRowid:y,at:c}),e.citations!==void 0){const b=e.citations,h=await _w(a,y),S=new Set(h.map(k=>k.key)),E=[];for(let k=0;k<b.length;k+=1)S.has(Vr(b[k]))||E.push({citation:b[k],sha:o[k]});Zc(l,u,E.map(k=>k.citation),E.map(k=>k.sha),"update");const N=new Set(b.map(k=>Vr(k)));for(const k of h)N.has(k.key)||await ed(a,{citationRowid:k.rowid,citationUid:k.uid,at:c,reason:"removed via update citations diff"});for(const k of E)await Kn(a,t,{issueRowid:y,issueUid:w,citation:k.citation,sha:k.sha,at:c})}return await U({tx:a,typePolicy:t.typePolicy,subjectRowid:y,subjectUid:w,subjectKind:"issue",actor:e.by,action:"updated",from:v?d.uid:void 0,to:v?w:void 0,note:`fields changed: ${i.join(", ")}`,at:c}),{uid:w,changed:i}});if(r){const{oldRowid:a,oldUid:c,newRowid:d,newUid:l,newTitle:u,newBody:f}=r,m=Promise.all([hn(t,{action:"delete",subjectRowid:a,subjectUid:c,actor:e.by}),hn(t,{action:"upsert",subjectRowid:d,subjectUid:l,actor:e.by,content:Si(u,f)})]);e.awaitEmbed?await m:m.catch(()=>{})}return s}async function nd(t,e,n){const i=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[e,"has_status"]);if(!i)throw new Error(`${n}: issue rowid=${e} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await Q(t,i.dst);if((o==null?void 0:o.kind)!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${i.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function dt(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function od(t,e){return{async countVerifiedAttestations(n){const i=await t.executeGet(`SELECT COUNT(DISTINCT n.uid) AS n
222
+ FROM edge e JOIN node n ON n.rowid = e.dst
223
+ WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
224
+ AND n.kind = 'attestation' AND n.t_invalid IS NULL
225
+ AND json_extract(n.meta,'$.claim.kind') = ?
226
+ AND json_extract(n.meta,'$.check.state') = 'verified'`,[e,n]);return(i==null?void 0:i.n)??0},async blockersAllTerminal(){const n=await t.executeAll("SELECT src FROM edge WHERE dst = ? AND rel = 'blocks' AND t_invalid IS NULL",[e]);for(const{src:i}of n.rows){const o=await t.executeGet(`SELECT s.meta AS meta FROM edge se JOIN node s ON s.rowid = se.dst
227
+ WHERE se.src = ? AND se.rel = 'has_status' AND se.t_invalid IS NULL
228
+ ORDER BY se.rowid LIMIT 1`,[i]);if(!o||(dt(o.meta)??{}).terminal!==!0)return!1}return!0},async relationExists(n,i){const o=i==="in"?"SELECT 1 AS x FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL LIMIT 1":"SELECT 1 AS x FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL LIMIT 1",r=await t.executeGet(o,[e,n]);return r!=null}}}async function id(t,e){const n=await t.executeAll(`SELECT o.rowid AS rowid, o.uid AS uid, o.meta AS meta
229
+ FROM edge e JOIN node o ON o.rowid = e.dst
230
+ WHERE e.src = ? AND e.rel = 'has_obligation' AND e.t_invalid IS NULL
231
+ AND o.kind = 'obligation' AND o.t_invalid IS NULL
232
+ ORDER BY o.rowid`,[e]),i=[];for(const o of n.rows){const r=dt(o.meta),s=r==null?void 0:r.applies_to,a=r==null?void 0:r.requirement,c=r==null?void 0:r.on_fail,d=r==null?void 0:r.override,l=s!==null&&typeof s=="object"?s:void 0,u=l==null?void 0:l.to,f=l==null?void 0:l.from;if(a===void 0||typeof u!="string"||u.trim().length===0||c!=="block"&&c!=="warn"){i.push({rowid:o.rowid,uid:o.uid,appliesTo:{to:typeof u=="string"?u:""},requirement:a,onFail:c==="warn"?"warn":"block",malformed:!0});continue}const m=d!==null&&typeof d=="object"&&Array.isArray(d.actors)?{actors:d.actors.filter(p=>typeof p=="string")}:void 0;i.push({rowid:o.rowid,uid:o.uid,appliesTo:typeof f=="string"&&f.trim().length>0?{to:u,from:f}:{to:u},requirement:a,onFail:c,...m!==void 0?{override:m}:{}})}return i}function qo(t,e=[]){switch(t.op){case"evidence":return e.includes(t.kind)||e.push(t.kind),e;case"all_of":case"any_of":for(const n of t.of)qo(n,e);return e;case"not":return qo(t.of,e),e;default:return e}}async function Fw(t,e,n){const i=await t.executeGet(`SELECT n.uid AS uid
233
+ FROM edge e JOIN node n ON n.rowid = e.dst
234
+ WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
235
+ AND n.kind = 'attestation' AND n.t_invalid IS NULL
236
+ AND json_extract(n.meta,'$.claim.kind') = ?
237
+ AND json_extract(n.meta,'$.check.state') = 'verified'
238
+ ORDER BY n.rowid LIMIT 1`,[e,n]);return i==null?void 0:i.uid}async function Bw(t,e){return(await t.executeAll(`SELECT n.uid AS uid, n.meta AS meta
239
+ FROM edge e JOIN node n ON n.rowid = e.dst
240
+ WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
241
+ AND n.kind = 'attestation' AND n.t_invalid IS NULL
242
+ ORDER BY n.rowid`,[e])).rows.map(i=>{const o=dt(i.meta),r=o==null?void 0:o.claim,s=o==null?void 0:o.anchor,a=o==null?void 0:o.check,c=r!==null&&typeof r=="object"?r.kind:void 0,d=s!==null&&typeof s=="object"?s.locator:void 0,l=a!==null&&typeof a=="object"?a.state:void 0;return{uid:i.uid,claimKind:typeof c=="string"?c:"attestation",...typeof d=="string"?{anchorLocator:d}:{},...typeof l=="string"?{checkState:l}:{}}})}async function Kw(t,e){var s;const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)return;const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)return;const o=await t.executeGet("SELECT kind, t_invalid, meta FROM node WHERE rowid = ?",[i.src]);if((o==null?void 0:o.kind)!=="project"||o.t_invalid!==null)return;const r=(s=dt(o.meta))==null?void 0:s.path;return typeof r=="string"&&r.length>0?r:void 0}async function Ho(t,e){switch(t.op){case"evidence":case"blockers_terminal":case"relation":return t;case"all_of":{for(const n of t.of)if(!await ue(n,e))return Ho(n,e);return t}case"any_of":{for(const n of t.of)if(!await ue(n,e))return Ho(n,e);return t}case"not":return t;default:return t}}async function ln(t,e,n,i,o){var s,a,c;let r;try{r=await Ho(i,o)}catch{return{code:"Unknown",message:"the obligation predicate could not be evaluated",obligationUid:n}}if((r==null?void 0:r.op)==="evidence"){const d=r.kind,l=await Bw(t,e),u=l.filter(g=>g.claimKind===d),f=(s=l.find(g=>{var y;return(y=g.anchorLocator)==null?void 0:y.startsWith("commit:")}))==null?void 0:s.anchorLocator,m=(a=l.find(g=>{var y;return(y=g.anchorLocator)==null?void 0:y.startsWith("commit:")}))==null?void 0:a.uid,p={code:"EvidenceUnverified",obligationUid:n,required_kind:d,message:`no verified attestation of kind "${d}" satisfies this obligation`};if(f!==void 0){p.performed_check=xo;const g=await Kw(t,e),y=f.slice(7);m!==void 0&&(p.subject=m),((c=l.find(v=>v.uid===m))==null?void 0:c.checkState)==="stale"&&(p.code="EvidenceStale"),g!==void 0&&y.length>0&&((await Yg(g,y)).onDefaultBranch||(p.message=`commit "${y}" is asserted as evidence of kind "${d}" but is not an ancestor of the default branch (${xo}); a bare commit ref never satisfies a published-artifact obligation`))}else if(u.length>0){const g=u[0];g!==void 0&&(p.subject=g.uid),u.some(y=>y.checkState==="stale")&&(p.code="EvidenceStale",p.message=`the attestation of kind "${d}" is stale`)}return p}return(r==null?void 0:r.op)==="blockers_terminal"?{code:"BlockedBy",obligationUid:n,message:"a blocker is not terminal"}:(r==null?void 0:r.op)==="relation"?{code:"ReferenceUnresolved",obligationUid:n,message:`the required relation "${r.type}" (${r.direction}) is absent`}:{code:"Unknown",obligationUid:n,message:"the obligation is unsatisfied for a reason this gate does not name"}}function qw(t,e,n){const i=t.to==="*"||t.to===n,o=t.from===void 0||t.from===e;return i&&o}async function Hw(t,e){var a;const n=od(t,e.issueRowid),i=[],o=[],r=[],s=await id(t,e.issueRowid);for(const c of s){if(c.malformed){const u={code:"MissingObligation",obligationUid:c.uid,message:"the obligation is malformed and cannot be evaluated"};c.onFail==="warn"?o.push(u):i.push(u);continue}if(!qw(c.appliesTo,e.fromStatus,e.toStatus))continue;let d;try{d=await ue(c.requirement,n)}catch{const u={code:"Unknown",obligationUid:c.uid,message:"the obligation predicate could not be evaluated"};c.onFail==="warn"?o.push(u):i.push(u);continue}if(d){for(const u of qo(c.requirement)){const f=await Fw(t,e.issueRowid,u);f!==void 0&&r.push({obligationUid:c.uid,attestationUid:f})}continue}if(c.onFail==="warn"){o.push(await ln(t,e.issueRowid,c.uid,c.requirement,n));continue}if(((a=c.override)==null?void 0:a.actors.includes(e.effectiveActor))??!1){if(e.override===void 0){i.push(await ln(t,e.issueRowid,c.uid,c.requirement,n));continue}const u=e.override.reason;if(typeof u=="string"&&u.trim().length>0)continue;throw new Oo(c.uid,e.effectiveActor)}if(e.override!==void 0)throw new Oo(c.uid,e.effectiveActor);i.push(await ln(t,e.issueRowid,c.uid,c.requirement,n))}return{satisfied:i.length===0,refusals:i,satisfiedBy:r,warnings:o}}async function Vw(t,e){return(await t.executeAll(`SELECT n.uid AS uid, s.meta AS status_meta
243
+ FROM edge e
244
+ JOIN node n ON n.rowid = e.src
245
+ LEFT JOIN edge se
246
+ ON se.src = n.rowid AND se.rel = 'has_status' AND se.t_invalid IS NULL
247
+ LEFT JOIN node s ON s.rowid = se.dst
248
+ WHERE e.dst = ? AND e.rel = 'blocks' AND e.t_invalid IS NULL
249
+ AND n.t_invalid IS NULL`,[e])).rows.map(i=>{const o=dt(i.status_meta)??{},r=i.status_meta!==null?o.terminal===!0:!1;return{uid:i.uid,terminal:r}})}async function Gw(t){const e=await t.executeAll("SELECT name, meta FROM node WHERE kind = 'status' AND t_invalid IS NULL"),n=new Set,i=new Set;for(const o of e.rows){if(typeof o.name!="string")continue;n.add(o.name),(dt(o.meta)??{}).terminal===!0&&i.add(o.name)}return{all:n,terminal:i}}function Ww(t){switch(t){case"BlockedBy":return"Blocked";case"EvidenceUnverified":case"EvidenceStale":return"Evidence";case"ReferenceUnresolved":return"Reference";case"ClaimStale":return"Claim";default:return"Obligation"}}async function Jw(t,e,n){const i=[],o=await Vw(t,e.rowid);for(const u of o)u.terminal||i.push({type:"Blocked",status:"True",severity:"block",code:"BlockedBy",subject:u.uid,message:`blocked by ${u.uid}`});const r=od(t,e.rowid),s=await Gw(t),a=await id(t,e.rowid);a.length===0&&i.push({type:"Obligation",status:"True",severity:"warn",code:"MissingObligation",message:"no obligations are declared on this item"});for(const u of a){if(u.malformed){i.push({type:"Obligation",status:"True",severity:u.onFail,code:"MissingObligation",subject:u.uid,message:"the obligation is malformed and cannot be evaluated"});continue}const f=u.appliesTo.to;if(f==="*"||s.terminal.has(f)||!s.all.has(f))continue;let p;try{p=await ue(u.requirement,r)}catch{i.push({type:"Obligation",status:"Unknown",severity:u.onFail,code:"Unknown",subject:u.uid,message:"the obligation predicate could not be evaluated"});continue}if(p)continue;const g=await ln(t,e.rowid,u.uid,u.requirement,r);i.push({type:Ww(g.code),status:"True",severity:u.onFail,code:g.code,subject:g.subject??u.uid,message:g.message})}const{claimedBy:c,claimedAt:d}=xn(e.metadata);c!==void 0&&Fn(d,n.at,n.claimStaleAfterMin)&&i.push({type:"Claim",status:"True",severity:"warn",code:"ClaimStale",subject:c,message:`claim by "${c}" is stale (threshold ${n.claimStaleAfterMin}min)`});const l=kc(i);return{actionable:Sc(l),evaluated_at:n.at,revision:$e(e.metadata),conditions:l}}function sn(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}async function gs(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)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 Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${i.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 zw(t,e){if(t.length>0&&!t.includes(e))throw new T("toStatus",`"${e}" is not in this project's allowed status set`)}function Yw(t,e){for(const n of t){if(!(n in e))continue;const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Xw(t,e){sn("uid",e.uid),sn("by",e.by),G("by",e.by),sn("toStatus",e.toStatus),td(e.gitContext);const n=e.citations??[];n.forEach((o,r)=>sn(`citations[${r}].file`,o.file));let i=[];if(n.length>0){const o=await se(t.adapter,e.uid,{expectedKind:"issue"}),r=await gs(t.adapter,o.rowid),s=Se(r),a=await Lt(t.adapter,r.uid);i=await $i(r,s,n,a,"transition")}return M(t,async o=>{var O;const r=P(),s=await ae(o,e.uid),a=await gs(o,s.rowid),c=Se(a),{claimedBy:d,claimedAt:l}=xn(s.metadata);if(d!==void 0&&d!==e.by&&!Fn(l,r,c.claimStaleAfterMin))throw new gn(d,l??r);const u=await nd(o,s.rowid,"transition"),f=u.name??"",m=await Ya(o,{ref:e.toStatus,at:r});zw(c.allowedStatuses,m.name),Yw(c.requiredFields,{status:m.name,note:e.note});const p=await Q(o,m.rowid),g=((O=p==null?void 0:p.metadata)==null?void 0:O.terminal)===!0;if(!(typeof e.note=="string"&&e.note.trim().length>0)&&c.transitionRequiresNote)throw new Da(s.uid);if(g&&c.citationRequired&&n.length===0)throw new Ma(s.uid);let w;if(g&&(w=await Hw(o,{issueRowid:s.rowid,fromStatus:f,toStatus:m.name,effectiveActor:e.by,...e.override!==void 0?{override:e.override}:{}}),!w.satisfied))throw new gi(w.refusals[0]);const v={target_uid:s.uid,from:f,to:m.name,agent:e.by,note:e.note??null,at:r},b=He(vi(v)),h=await X(o,{kind:"transition",content:e.note??"",metadata:{from_status:f,to_status:m.name,agent:e.by,note:e.note??null,sha:b,at:r,...w!==void 0&&w.satisfiedBy.length>0?{satisfied_by:w.satisfiedBy}:{}},at:r}),S=await q(o,"has_transition");await K(o,{at:r,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"transition",rel:"has_transition",rule:S,typePolicy:t.typePolicy}),await ie(o,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${m.name}"`,at:r});const E=await q(o,"has_status");await K(o,{at:r,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:m.rowid,dstUid:m.uid,dstKind:"status",rel:"has_status",rule:E,typePolicy:t.typePolicy});for(let I=0;I<n.length;I+=1)await Kn(o,t,{issueRowid:s.rowid,issueUid:s.uid,citation:n[I],sha:i[I],at:r});if(w!==void 0&&w.satisfiedBy.length>0){const I=await q(o,"satisfies");for(const{obligationUid:L,attestationUid:$}of w.satisfiedBy){const Y=await se(o,L,{expectedKind:"obligation"}),H=await se(o,$,{expectedKind:"attestation"});await K(o,{at:r,srcRowid:Y.rowid,srcUid:Y.uid,srcKind:"obligation",dstRowid:H.rowid,dstUid:H.uid,dstKind:"attestation",rel:"satisfies",rule:I,typePolicy:t.typePolicy})}}const N={...s.metadata??{}};N.revision=re(s.metadata),g?N.closedAt=r:delete N.closedAt,typeof e.gitContext=="string"&&e.gitContext.trim().length>0&&(N.gitContext=e.gitContext),w!==void 0&&w.satisfiedBy.length>0&&(N.satisfied_by=w.satisfiedBy);const k=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(N),r,s.rowid]);if(k.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${k.rowsAffected} rows for rowid=${s.rowid}, expected exactly 1.`);const R=e.override!==void 0&&typeof e.override.reason=="string"&&e.override.reason.trim().length>0?`override: ${e.override.reason}`:void 0,A=R===void 0?e.note:[e.note,R].filter(I=>typeof I=="string"&&I.length>0).join(" — ");return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"transitioned",from:f,to:m.name,note:A,at:r}),{uid:s.uid,fromStatus:f,toStatus:m.name,closedAt:g?r:void 0,transitionUid:h.uid}})}function hs(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function ys(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)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 Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const r={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Se(r)}async function vt(t,e,n,i){const o=await t.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),i,e]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function Qw(t,e){if(hs("uid",e.uid),hs("by",e.by),G("by",e.by),e.action!=="claim"&&e.action!=="release"&&e.action!=="renew")throw new T("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(e.action)})`);const n=e.force===!0;return M(t,async i=>{var d;const o=P(),r=await ae(i,e.uid),s={...r.metadata??{}},{claimedBy:a,claimedAt:c}=xn(s);if(e.action==="claim"){const l=await nd(i,r.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new La(r.uid,l.name??"");const u=await ys(i,r.rowid),p=(await Jw(i,r,{at:o,claimStaleAfterMin:u.claimStaleAfterMin})).conditions.filter(S=>S.severity==="block"&&S.status==="True")[0];if(p!==void 0&&!n)throw new hi(p);const g=p!==void 0?`force-claimed despite ${p.code}${p.subject!==void 0?` ${p.subject}`:""}`:void 0;if(a===void 0){const S={...s,claimedBy:e.by,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,S,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"claimed",to:e.by,note:g,at:o}),{uid:r.uid,status:"claimed",claimedBy:e.by,claimedAt:o}}if(a===e.by){const S={...s,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,S,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"claimed",from:e.by,to:e.by,note:g===void 0?"re-affirmed (held)":`${g} — re-affirmed (held)`,at:o}),{uid:r.uid,status:"held",heldBy:e.by,claimedBy:e.by,claimedAt:o}}const y=await ys(i,r.rowid),w=Ec(c,o),v=Fn(c,o,y.claimStaleAfterMin);if(!v&&!n)throw new gn(a,c??o);const b={...s,claimedBy:e.by,claimedAt:o,previousClaimant:a,revision:re(s)};await vt(i,r.rowid,b,o);const h=v?`stale claim reclaimed after ~${Math.floor(w)}min (threshold ${y.claimStaleAfterMin}min)`:"force override of a non-stale claim";return await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"reclaimed-stale",from:a,to:e.by,note:g===void 0?h:`${g} — ${h}`,at:o}),{uid:r.uid,status:"reclaimed-stale",claimedBy:e.by,claimedAt:o,previousClaimant:a}}if(e.action==="release"){if(a===e.by){const l={...s,revision:re(s)};return delete l.claimedBy,delete l.claimedAt,await vt(i,r.rowid,l,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"released",from:e.by,at:o}),{uid:r.uid,status:"released"}}return{uid:r.uid,status:"release-noop",wasClaimedBy:a}}if(a===e.by){const l={...s,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,l,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"renewed",from:e.by,to:e.by,at:o}),{uid:r.uid,status:"renewed",claimedBy:e.by,claimedAt:o}}throw new gn(a??"",c??"")})}const ws=["relates_to","supersedes","blocks","duplicate_of","part_of","similar_to"];function io(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function Zw(t,e,n,i){const o=await t.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e,n,i]);return o?o.rowid:null}async function ev(t,e){if(io("sourceUid",e.sourceUid),io("targetUid",e.targetUid),io("by",e.by),G("by",e.by),!ws.includes(e.rel))throw new T("rel",`must be one of ${ws.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.rel)})`);if(e.action!=="add"&&e.action!=="remove")throw new T("action",`must be "add" or "remove" (got ${JSON.stringify(e.action)})`);if(e.sourceUid===e.targetUid)throw new T("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return M(t,async n=>{const i=P(),o=await ae(n,e.sourceUid),r=await ae(n,e.targetUid),s=await Zw(n,o.rowid,r.rowid,e.rel);if(e.action==="add"){if(s!==null)return{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"add",noop:!0};const a=await q(n,e.rel);return await K(n,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:r.rowid,dstUid:r.uid,dstKind:"issue",rel:e.rel,rule:a,typePolicy:t.typePolicy}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"related",to:r.uid,note:e.rel,at:i}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"add",noop:!1}}return s===null?{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"remove",noop:!0}:(await ie(n,{srcRowid:o.rowid,dstRowid:r.rowid,rel:e.rel,reason:`relate: removed by "${e.by}"`,at:i}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"unrelated",to:r.uid,note:e.rel,at:i}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"remove",noop:!1})})}function vs(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function tv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await Q(t,n.src);if((i==null?void 0:i.kind)!=="component"||i.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:i.rowid,uid:i.uid,name:i.name??""}}async function nv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_project"]);if(!n)throw new Error(`move: component rowid=${e} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const i=await Q(t,n.src);if((i==null?void 0:i.kind)!=="project"||i.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:i.rowid,uid:i.uid,name:i.name??""}}async function ov(t,e){return vs("uid",e.uid),vs("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await ae(n,e.uid),r=await tv(n,o.rowid),s=await nv(n,r.rowid);let a;if(e.toProject!==void 0){const l=await at(n,e.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=s;let c;if(e.toComponent!==void 0?c=await Ei(n,{projectUid:a.uid,ref:e.toComponent}):c=await Wa(n,{projectRowid:a.rowid}),c.rowid===r.rowid)return{uid:o.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:r.uid,toComponent:c.uid};await ie(n,{srcRowid:r.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:i});const d=await q(n,"owns_component");return await K(n,{at:i,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:t.typePolicy}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"moved",from:r.uid,to:c.uid,at:i}),{uid:o.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:r.uid,toComponent:c.uid}})}function ro(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function iv(t,e){ro("uid",e.uid),ro("by",e.by),G("by",e.by),ro("reason",e.reason);let n;const i=await M(t,async o=>{const r=P(),s=await ae(o,e.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:e.reason,invalidatedAt:r},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(a),s.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"deleted",note:e.reason,at:r}),{uid:s.uid,invalidated:!0}});if(n){const o=hn(t,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:e.by});e.awaitEmbed?await o:o.catch(()=>{})}return i}async function bs(t,e){let n;try{n=await se(t,e)}catch(i){throw i instanceof V?new mn(e):i}if(n.kind!=="issue"&&n.kind!=="SPEC")throw new mn(e);if(n.kind==="issue"&&n.isSuperseded)throw new Ut(e);return{rowid:n.rowid,uid:n.uid,kind:n.kind,metadata:n.metadata}}function Xe(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}function rv(t){if(typeof t=="number"){if(Number.isFinite(t))return;throw new T("subject.revision","must be a finite number or a non-empty string")}if(!(typeof t=="string"&&t.trim().length>0))throw new T("subject.revision","must be a finite number or a non-empty string")}async function rd(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`attestation: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`attestation: 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 t.executeGet("SELECT uid, kind, t_invalid, meta FROM node WHERE rowid = ?",[i.src]);if((o==null?void 0:o.kind)!=="project"||o.t_invalid!==null)throw new Error(`attestation: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const r=av(o.meta),s=r==null?void 0:r.path;return{uid:o.uid,path:typeof s=="string"&&s.length>0?s:void 0}}function sv(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e);if(!Ta(n,i))return;const o=_.relative(n,i);return o.length===0?void 0:o}async function sd(t,e,n,i){const o=Mn(e.locator);if(o.scheme!=="path")return n;const r=i===void 0?[]:await Lt(t,i),s=[...new Set([...n!==void 0?[n]:[],...r])];let a;for(const c of s){if(!bn(c))continue;const d=sv(c,o.target);if(d!==void 0){if(vc(c,d))return c;a===void 0&&(a=c)}}return a??n}function av(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Es(t,e){try{const n=await se(t,e,{expectedKind:"attestation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new xa(e):n}}async function cv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"attests"]);return n==null?void 0:n.src}function dv(t){const e=t==null?void 0:t.anchor;if(e===null||typeof e!="object")return;const n=e,i=n.locator,o=n.digest;if(!(typeof i!="string"||typeof o!="string"))return{locator:i,digest:o}}function Ss(t){const e=t==null?void 0:t.checks;return Array.isArray(e)?e:[]}function lv(t){const e=t==null?void 0:t.claim;if(e!==null&&typeof e=="object"){const n=e.kind;if(typeof n=="string")return n}return"attestation"}async function uv(t,e){var a,c,d,l;if(Xe("subject.id",(a=e.subject)==null?void 0:a.id),rv((c=e.subject)==null?void 0:c.revision),Xe("claim.kind",(d=e.claim)==null?void 0:d.kind),Xe("anchor.locator",(l=e.anchor)==null?void 0:l.locator),Xe("by",e.by),G("by",e.by),typeof e.anchor.digest!="string"||e.anchor.digest.trim().length===0)throw new Ue(e.anchor.locator,"a path anchor requires a content digest");Mn(e.anchor.locator);const n=await bs(t.adapter,e.subject.id),i=n.kind==="issue"?await rd(t.adapter,n.rowid):void 0,o=await sd(t.adapter,e.anchor,i==null?void 0:i.path,i==null?void 0:i.uid),r=P();let s=Ri(e.anchor,{...o!==void 0?{root:o}:{},sinceISO:r,full:!1,now:r,by:e.by});return M(t,async u=>{const f=await bs(u,e.subject.id);typeof e.subject.revision=="number"&&$e(f.metadata)!==e.subject.revision&&(s={...s,state:"unknown",reason:"revision-drift"});const m={subject:{id:f.uid,revision:e.subject.revision},claim:{kind:e.claim.kind,...e.claim.body!==void 0?{body:e.claim.body}:{},asserted_by:e.by,asserted_at:r},anchor:{locator:e.anchor.locator,digest:e.anchor.digest},check:s,checks:[s],lifecycle:{status:"active",supersedes:null,part_of:null}},p=await X(u,{at:r,kind:"attestation",name:e.claim.kind,content:e.claim.body??"",metadata:m}),g=await q(u,"attests");return await K(u,{at:r,srcRowid:f.rowid,srcUid:f.uid,srcKind:f.kind,dstRowid:p.rowid,dstUid:p.uid,dstKind:"attestation",rel:"attests",rule:g,typePolicy:t.typePolicy}),await U({tx:u,typePolicy:t.typePolicy,subjectRowid:f.rowid,subjectUid:f.uid,subjectKind:f.kind,actor:e.by,action:"attested",to:p.uid,note:e.claim.kind,at:r}),{attestationUid:p.uid,subject:{id:f.uid,revision:e.subject.revision},check:s}})}async function fv(t,e){Xe("attestationUid",e.attestationUid),Xe("by",e.by),G("by",e.by);const n=await Es(t.adapter,e.attestationUid),i=await cv(t.adapter,n.rowid),o=i===void 0?void 0:await rd(t.adapter,i),r=dv(n.metadata),s=Ss(n.metadata),a=s.length>0?s[s.length-1].checked_at:pv(n.metadata),c=P(),d=r?await sd(t.adapter,r,o==null?void 0:o.path,o==null?void 0:o.uid):void 0,l=r?Ri(r,{...d!==void 0?{root:d}:{},...a!==void 0?{sinceISO:a}:{},full:!0,now:c,by:e.by}):{state:"unknown",method:"none",checked_at:c,checked_by:e.by,reason:"attestation carries no readable anchor"};return M(t,async u=>{const f=await Es(u,e.attestationUid),m=f.metadata??{},p=[...Ss(m),l],g={...m,check:l,checks:p},y=await u.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(g),c,f.rowid]);if(y.rowsAffected!==1)throw new Error(`recheck: touch UPDATE affected ${y.rowsAffected} rows for rowid=${f.rowid}, expected exactly 1.`);return await U({tx:u,typePolicy:t.typePolicy,subjectRowid:f.rowid,subjectUid:f.uid,subjectKind:"attestation",actor:e.by,action:"rechecked",note:lv(m),at:c}),{attestationUid:f.uid,checks:p}})}function pv(t){const e=t==null?void 0:t.claim;if(e!==null&&typeof e=="object"){const n=e.asserted_at;if(typeof n=="string")return n}}function ot(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}function mv(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function gv(t,e){return ot("fromUid",e.fromUid),ot("toUid",e.toUid),ot("by",e.by),G("by",e.by),M(t,async n=>{var l,u;const i=P(),o=await Be(n,e.fromUid);if((o==null?void 0:o.kind)!=="project")throw new V("project",e.fromUid);const r=await at(n,e.toUid);if(o.uid===r.uid)throw new T("toUid","must differ from fromUid");if(o.tInvalid!==null){const f=(l=o.metadata)==null?void 0:l.redirectTo;if(f===r.uid)return{survivorUid:r.uid,retiredUid:o.uid,movedIssues:0,retired:!0};throw new T("fromUid",`"${o.uid}" is already retired`+(typeof f=="string"?` (redirectTo "${f}")`:"")+" and cannot be re-merged onto a different survivor")}const s=await q(n,"owns_project"),{rows:a}=await n.executeAll(`SELECT c.rowid AS rowid, c.uid AS uid, c.meta AS meta
250
+ FROM edge e JOIN node c ON c.rowid = e.dst
251
+ WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
252
+ AND c.t_invalid IS NULL`,[o.rowid]);let c=0;for(const f of a){const{rows:m}=await n.executeAll("SELECT COUNT(*) AS n FROM edge WHERE src = ? AND rel = 'owns_component' AND t_invalid IS NULL",[f.rowid]);c+=((u=m[0])==null?void 0:u.n)??0,await ie(n,{srcRowid:o.rowid,dstRowid:f.rowid,rel:"owns_project",reason:"project-merge",at:i}),await K(n,{at:i,srcRowid:r.rowid,srcUid:r.uid,srcKind:"project",dstRowid:f.rowid,dstUid:f.uid,dstKind:"component",rel:"owns_project",rule:s,typePolicy:t.typePolicy});const p=mv(f.meta)??{};await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify({...p,projectUid:r.uid}),f.rowid])}const d={...o.metadata??{},redirectTo:r.uid,retiredAt:i,retiredReason:"project-merge"};return await n.executeRun("UPDATE node SET meta = ?, t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(d),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:e.by,action:"merged",to:r.uid,note:`merged into ${r.uid}`,at:i}),{survivorUid:r.uid,retiredUid:o.uid,movedIssues:c,retired:!0}})}async function hv(t,e){return ot("uid",e.uid),ot("reason",e.reason),ot("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await Be(n,e.uid);if((o==null?void 0:o.kind)!=="project")throw new V("project",e.uid);if(o.tInvalid!==null)return{uid:o.uid,retired:!0};const r={...o.metadata??{},retiredAt:i,retiredReason:e.reason};return await n.executeRun("UPDATE node SET meta = ?, t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(r),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:e.by,action:"removed",note:e.reason,at:i}),{uid:o.uid,retired:!0}})}function _n(t){var e;return(e=t.env.version)==null?void 0:e.configHash}async function ad(t){const e=t.embeddingConfig;e!=null&&e.refresh().changed&&Jy(t.store.adapter);const n=e?e.current():t.env.config.embedding;return Gy(t.store.adapter,t.store.graph,n,void 0,{configuredEnabled:e?e.configured().enabled:n==null?void 0:n.enabled,startupHash:_n(t),configuredHash:e?e.fingerprint().configHash:_n(t),configPaths:e?e.fingerprint().files.map(i=>i.path):void 0})}async function W(t,e){await pi(t.store.adapter);const{search:n,embedding:i}=e.needsSemantic?await ad(t):{};return{adapter:t.store.adapter,typePolicy:t.store.typePolicy,graph:t.store.graph,...n!==void 0?{search:n}:{},...i!==void 0?{embedding:i}:{}}}async function Ht(t,e){const{search:n}=e.needsSemantic?await ad(t):{},i=n!==void 0&&e.probeSpace?await n.spacePopulated():void 0;return{graph:t.store.graph,assertVocabulary:()=>pi(t.store.adapter),assertCatalogInvariants:()=>Vc(t.store.adapter),...n!==void 0?{search:n}:{},...i!==void 0?{spacePopulated:i}:{}}}const yv=[[mn,"item_not_found"],[xa,"item_not_found"],[Fa,"item_not_found"],[Ba,"item_not_found"],[mi,"ambiguous_reference"],[V,"not_found"],[T,"invalid_argument"],[Ue,"invalid_argument"],[ve,"invalid_argument"],[gn,"conflict"],[jo,"conflict"],[Ut,"conflict"],[La,"precondition_failed"],[Ma,"precondition_failed"],[Da,"precondition_failed"],[Ua,"precondition_failed"],[gi,"precondition_failed"],[Oo,"precondition_failed"],[hi,"precondition_failed"],[To,"precondition_failed"],[$a,"store_busy"],[Fc,"rag_not_configured"]],wv={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function cd(t){for(const[e,n]of yv)if(t instanceof e){const i=t instanceof C?{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}:void 0;return t instanceof gi?ne(n,t.message,{...i??{},refusal:t.refusal}):t instanceof hi?ne(n,t.message,{...i??{},refusal:t.refusal}):ne(n,t.message,i)}return t instanceof C?ne(wv[t.code]??"internal",t.message,{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}):ne("internal",t instanceof Error?t.message:String(t))}async function D(t){try{return Ii(await t())}catch(e){return cd(e)}}async function dd(t,e){return D(()=>"registry"in e?e.registry==="project"?oo(t.store.graph,{registry:"project",name:e.name}):e.registry==="component"?oo(t.store.graph,{registry:"component",name:e.name,filter:e.filter}):oo(t.store.graph,{registry:"location",name:e.name}):nw(t.store.graph,e))}async function ld(t,e){try{const{result:n,meta:i}=await qy(await Ht(t,{needsSemantic:xy(e),probeSpace:e.text!==void 0}),e);return Ii(n,i?{meta:i}:void 0)}catch(n){return cd(n)}}async function ud(t,e){return D(async()=>Xc(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function fd(t,e){return D(async()=>lw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function pd(t,e){return D(async()=>mw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function md(t,e){return D(async()=>yw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function gd(t){return D(async()=>{const e=t.embeddingConfig,n=e?e.configured():t.env.config.embedding,i=e?e.current():t.env.config.embedding,o=Wy(t.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(i==null?void 0:i.enabled)===!0,provider:(i==null?void 0:i.provider)??"",model:(i==null?void 0:i.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!=((i==null?void 0:i.enabled)===!0),startupHash:_n(t)??"",currentHash:e?e.fingerprint().configHash:_n(t)??""}})}async function hd(t,e){return D(()=>Ey(t.store.graph,e))}async function yd(t,e){return D(async()=>$w(await W(t,{needsSemantic:!0}),e))}async function wd(t,e){return D(async()=>xw(await W(t,{needsSemantic:!0}),e))}async function vd(t,e){return D(async()=>Nw(await W(t,{needsSemantic:!1}),e))}async function bd(t,e){return D(async()=>Rw(await W(t,{needsSemantic:!1}),e))}async function Ed(t,e){return D(async()=>Xw(await W(t,{needsSemantic:!1}),e))}async function Sd(t,e){return D(async()=>uv(await W(t,{needsSemantic:!1}),e))}async function kd(t,e){return D(async()=>fv(await W(t,{needsSemantic:!1}),e))}async function _d(t,e){return D(async()=>Vg(await W(t,{needsSemantic:!1}),e))}async function Ad(t,e){return D(async()=>Gg(await W(t,{needsSemantic:!1}),e))}async function Nd(t,e){return D(async()=>vh(await W(t,{needsSemantic:!1}),e))}async function Rd(t,e){return D(()=>Ic(t.store.graph,e))}async function jd(t,e){return D(async()=>Qw(await W(t,{needsSemantic:!1}),e))}async function Td(t,e){return D(async()=>ev(await W(t,{needsSemantic:!1}),e))}async function Od(t,e){return D(async()=>ov(await W(t,{needsSemantic:!1}),e))}async function Id(t,e){return D(async()=>iv(await W(t,{needsSemantic:!1}),e))}async function $d(t,e){return D(async()=>Qp(await W(t,{needsSemantic:!1}),e))}async function Cd(t,e){return D(async()=>em(await W(t,{needsSemantic:!1}),e))}async function Pd(t,e){return D(async()=>nm(await W(t,{needsSemantic:!1}),e))}async function Ld(t,e){return D(async()=>om(await W(t,{needsSemantic:!1}),e))}async function Ud(t,e){return D(async()=>gv(await W(t,{needsSemantic:!1}),e))}async function Dd(t,e){return D(async()=>hv(await W(t,{needsSemantic:!1}),e))}const vv=Object.freeze(Object.defineProperty({__proto__:null,addCitation:vd,attest:Sd,claim:jd,create:yd,delete:Id,embeddingStatus:gd,get:dd,lookup:hd,mergeProject:Ud,move:Od,obligate:_d,openCurve:pd,partOfRollup:fd,priorityMatrix:ud,query:ld,recheck:kd,relate:Td,removeCitation:bd,report:md,rmLocation:Ld,rmProject:Dd,specAppend:Nd,specCheck:Rd,transition:Ed,unobligate:Ad,update:wd,upsertComponent:Cd,upsertLocation:Pd,upsertProject:$d},Symbol.toStringTag,{value:"Module"}));async function bv(t){let e;try{e=await Te.open(t,"r"),await e.sync()}catch{}finally{e&&await e.close().catch(()=>{})}}async function Md(t,e){const n=_.dirname(t);await Te.mkdir(n,{recursive:!0});const i=`${t}.${process.pid}.${ke.randomUUID()}.tmp`;let o;try{o=await Te.open(i,"w"),await o.writeFile(JSON.stringify(e),"utf8"),await o.sync(),await o.close(),o=void 0,await Te.rename(i,t),await bv(n)}catch(r){throw o&&await o.close().catch(()=>{}),await Te.unlink(i).catch(()=>{}),r}}function Ev(t){return{async get(){try{const e=await Te.readFile(t,"utf8");return JSON.parse(e)}catch{return}},async put(e,n){await Md(t,n)}}}const $t=1;function Sv(t){return ke.createHash("sha256").update(t).digest("hex")}async function ks(t){return Sv(await Te.readFile(t,"utf8"))}async function An(t){try{return(await Te.stat(t)).mtimeMs}catch{return}}async function _s(t,e){const n=await ks(t.source),i=ke.createHash("sha256");i.update(`formatVersion:${$t}
253
+ `),i.update(`extractorVersion:${e}
254
+ `),i.update(`host:${t.host}
255
+ `),i.update(`namespace:${t.namespace??""}
256
+ `),i.update(`source:${n}
257
+ `);for(const o of na(t.source))o!==t.source&&i.update(`dep:${o}:${await ks(o)}
258
+ `);return i.digest("hex")}async function As(t,e){const n=await An(t.source)??0,i=[];for(const o of na(t.source)){if(o===t.source)continue;const r=await An(o);r!==void 0&&i.push({path:o,mtimeMs:r})}return{contentKey:e,source:{path:t.source,mtimeMs:n},deps:i}}async function kv(t,e){if(e.source.path!==t.source)return!1;const n=await An(e.source.path);if(n===void 0||n!==e.source.mtimeMs)return!1;for(const i of e.deps){const o=await An(i.path);if(o===void 0||o!==i.mtimeMs)return!1}return!0}function _v(t){if(t.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 e=Ev(t.cache),n=t.extractorVersion;async function i(o,r,s){const a=s??await _s(o,n),c=await As(o,a);await e.put(t.cache,{formatVersion:$t,operations:r,extractorVersion:n,staleness:c})}return async(o,r)=>{const s=await e.get(t.cache);if((s==null?void 0:s.formatVersion)!==$t||s.extractorVersion!==n||!s.staleness){const d=await r();try{await i(o,d)}catch{}return d}if(await kv(o,s.staleness))return s.operations;const a=await _s(o,n);if(a===s.staleness.contentKey)return As(o,a).then(d=>e.put(t.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await r();try{await i(o,c,a)}catch{}return c}}Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href);const Av="api.ir.json",Nv=Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href),Ci=Nv("@adhd/apigen-core-client/package.json").version;function ct(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href));return j.existsSync(_.join(t,"api.d.ts"))?t:_.join(t,"..","dist")}function Rv(t){return _.join(t,Av)}function Pi(t){return ke.createHash("sha256").update(t).digest("hex")}function xd(t){const e=[],n=o=>{let r;try{r=j.readdirSync(o,{withFileTypes:!0})}catch{return}for(const s of r){const a=_.join(o,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&e.push(a)}};n(t),e.sort();const i={};for(const o of e)i[_.relative(t,o).split(_.sep).join("/")]=Pi(j.readFileSync(o));return i}function jv(t,e){const n=Object.keys(t).sort(),i=Object.keys(e).sort();if(n.length!==i.length)return!1;for(let o=0;o<n.length;o++){const r=n[o];if(r!==i[o]||t[r]!==e[r])return!1}return!0}function Fd(t){try{const e=Rv(t);if(!j.existsSync(e))return;const n=JSON.parse(j.readFileSync(e,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==$t||n.extractorVersion!==Ci)return;const i=n.artifactSource;if(!i||typeof i.sha256!="string"||typeof i.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const o=_.join(t,"api.d.ts");if(!j.existsSync(o))return;const r=j.readFileSync(o);if(r.byteLength!==i.bytes||Pi(r)!==i.sha256)return;const s=i.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return jv(s,xd(t))?n.operations:void 0}catch{return}}async function Tv(t){const e=j.readFileSync(t.apiDts),n=_.dirname(t.apiDts),i={formatVersion:$t,operations:t.operations,extractorVersion:t.extractorVersion,artifactSource:{path:_.relative(n,t.apiDts).split(_.sep).join("/"),sha256:Pi(e),bytes:e.byteLength,deps:xd(n)}};await Md(t.outFile,i)}function Bd(t={}){const e=ki("backlog",Ie,{namespace:t.namespace??"production",scope:Pn(t.scope),...t.adhdRoot!==void 0?{adhdRoot:t.adhdRoot}:{},...t.cwd!==void 0?{cwd:t.cwd}:{}}),n=[_.join(e.roots.system,Ze),_.join(e.roots.global,Ze)];return e.roots.project&&(n.push(_.join(e.roots.project,Ze)),n.push(_.join(e.roots.project,oc))),[...new Set(n)]}const Ov=t=>t instanceof Error?t.message:String(t),Ns=t=>({enabled:t.enabled===!0,provider:t.provider,model:t.model}),Iv=(t,e)=>t.enabled===e.enabled&&t.provider===e.provider&&t.model===e.model;function $v(t){const e=()=>t.layerFiles().map(a=>{try{const c=j.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 i=Ns(t.baseline.config.embedding),o=i,r={configHash:t.baseline.version.configHash,files:e()};const s=()=>{const a=e();if(n(a,r.files))return!1;let c;try{c=t.rebuild()}catch(d){return t.log("warn",`backlog: could not re-read the embedding config layers (${Ov(d)}) — continuing with the last known effective embedding settings`),!1}return r={configHash:c.version.configHash,files:a},o=Ns(c.config.embedding),!0};return{current:()=>i,configured:()=>(s(),o),divergent:()=>(s(),o.enabled&&!i.enabled),refresh:()=>{const a=i;return s(),Iv(o,i)?{changed:!1,from:a,to:i}:(i=o,t.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${i.enabled}, provider ${i.provider}, model ${i.model}); adopting without restart`),{changed:!0,from:a,to:i})},fingerprint:()=>r}}function Cv(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),e=_.join(t,"package.json");return j.existsSync(e)?e:_.join(t,"..","package.json")}function Li(){const t=Cv(),e=JSON.parse(j.readFileSync(t,"utf8"));return{name:e.name,version:e.version}}function Kd(t={}){const e=t.now??(()=>Date.now()),n=()=>new Date(e()).toISOString();let i="starting",o=n(),r,s;const a=new Promise(d=>{s=d}),c=d=>{i!==d&&(i=d,o=n())};return{state:()=>i,report:()=>{const d={state:i,since:o,degraded:r!==void 0};return r!==void 0&&(d.failure={...r}),d},markLive:()=>c("live"),markReady:()=>{c("ready"),s==null||s()},fail:d=>(r={...d},{action:d.kind==="liveness"?"restart":"report"}),whenReady:()=>a}}const Pv={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Lv=/embedding[_-]?status$/i;function Uv(t){return t.replace(/-([a-z])/g,(e,n)=>n.toUpperCase())}function Dv(t){return async()=>{const e=t.pkg.fns,n=t.operations.find(a=>Lv.test(a.id)),i=(n==null?void 0:n.id.split("/").pop())??"embedding-status",o=[i,Uv(i),"embeddingStatus"].find(a=>typeof e[a]=="function")??"embeddingStatus",r=e[o];if(typeof r!="function")throw new Error(`readiness: no embedding-status operation is mounted (looked for ${o})`);const s=await t.pkg.createClient();return r(s)}}function Mv(t){var e,n;if(t!==null&&typeof t=="object"&&"ok"in t){const i=t;return i.ok===!0?{ready:!0}:{ready:!1,failure:{kind:"readiness",code:((e=i.error)==null?void 0:e.code)??"probe_failed",message:((n=i.error)==null?void 0:n.message)??"serving-path probe returned ok:false (transport answered, op did not)"}}}return{ready:!0}}async function qd(t,e){const n=e.timer??Pv,i=e.invoke??Dv(t);let o;const r=new Promise(c=>{o=n.setTimeout(()=>c({ready:!1,failure:{kind:"readiness",code:"probe_timeout",message:`serving-path probe did not answer within ${e.timeoutMs}ms`}}),e.timeoutMs)}),s=i().then(c=>Mv(c),c=>({ready:!1,failure:{kind:"readiness",code:"probe_error",message:c instanceof Error?c.message:String(c)}})),a=await Promise.race([s,r]);return n.clearTimeout(o),a}class Hd extends C{constructor(e,n){super(`Unknown config key "service.${e}" in ${n}. An unknown key is a hard error (a host would otherwise silently ignore it). Known keys are the service.* contract — see SERVICE_CONFIG_KEYS / the backlog docs.`),this.code="E_VALIDATION",this.retryable=!1,this.key=e,this.file=n}}class qn extends C{constructor(e,n){super(`Config field "${e}" must be an absolute path (or a PATH-resolvable bin such as "npx"/"node"), got "${n}". A relative path resolves against an unpredictable cwd and is refused.`),this.code="E_VALIDATION",this.retryable=!1,this.field=e,this.value=n}}class Vo extends C{constructor(e,n,i){super(`Unknown MCP config key "${n}" in ${e}`+(i?` (did you mean "${i}"?)`:"")+'. Allowed keys are type/command/args/env/url. An unknown key is a HARD ERROR: a host silently ignores it, so a server "configured" with it looks configured and is absent.'),this.code="E_VALIDATION",this.retryable=!1,this.entry=e,this.key=n,i!==void 0&&(this.suggestion=i)}}class Ye extends C{constructor(e,n,i){super(`Server artifact drift at ${i}: expected ${e}, got ${n}. Refusing to start — a config pointing at a missing or changed artifact must fail loudly, not launch a phantom.`),this.code="E_VALIDATION",this.retryable=!1,this.expected=e,this.actual=n,this.resolvedPath=i}}class Qe extends C{constructor(e,n){super(`Service not ready (state=${e})`+(n?`: ${n}`:"")+". The connect/handshake did not succeed inside its bounded budget."),this.code="E_VALIDATION",this.retryable=!0,this.state=e,n!==void 0&&(this.failure=n)}}const Go=Object.freeze(["service.transport","service.port","service.host","service.serverCommand","service.connectGraceMs","service.connectBudgetMs","service.readinessTimeoutMs"]),Rs="service.",xv={"service.transport":"mcp","service.port":3300,"service.host":"127.0.0.1","service.serverCommand":"","service.connectGraceMs":2e4,"service.connectBudgetMs":6e4,"service.readinessTimeoutMs":3e4};function Vd(t){const e=process.env.PATH;if(!e)return!1;for(const n of e.split(_.delimiter))if(n!=="")try{return j.accessSync(_.join(n,t),j.constants.X_OK),!0}catch{}return!1}function Nn(t,e){if(!(e===""||e===":memory:")&&!_.isAbsolute(e)&&!Vd(e))throw new qn(t,e)}function js(t,e){const n=Ie.config[t],i=n==null?void 0:n.type;if(e!==void 0){if(i==="integer"||i==="number"){const o=typeof e=="number"?e:Number(e);return Number.isFinite(o)?o:void 0}return i==="boolean"?typeof e=="boolean"?e:e==="true"||e==="1":e}}function Gd(t,e){var a;const n={scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace},i={...xv};for(const c of Bd(n)){const d=bt(c);if(d)for(const[l,u]of Object.entries(d)){if(!l.startsWith(Rs))continue;if(!Go.includes(l))throw new Hd(l.slice(Rs.length),c);const f=js(l,u);f!==void 0&&(i[l]=f)}}for(const c of Go){const d=(a=Ie.config[c])==null?void 0:a.env;if(!d)continue;const l=process.env[d];if(l===void 0)continue;const u=js(c,l);u!==void 0&&(i[c]=u)}t.transport!==void 0&&(i["service.transport"]=t.transport),t.port!==void 0&&(i["service.port"]=t.port),t.host!==void 0&&(i["service.host"]=t.host);const o=tt(e);Nn("service.dbPath",o);const r=String(i["service.serverCommand"]??"");Nn("server.command",r);const s=i["service.transport"];if(s!=="mcp"&&s!=="http"&&s!=="both")throw new qn("service.transport",String(i["service.transport"]));return{transport:s,port:Number(i["service.port"]),host:String(i["service.host"]),scope:Pn(t.scope),dbPath:o,busyTimeoutMs:e.config.db.busyTimeoutMs,server:{command:r,identity:{kind:"path"}},readiness:{timeoutMs:Number(i["service.readinessTimeoutMs"])},connect:{graceMs:Number(i["service.connectGraceMs"]),budgetMs:Number(i["service.connectBudgetMs"]),maxAttempts:4,baseMs:250,maxMs:5e3,breakerFailureThreshold:3,breakerResetMs:3e4}}}const Ts=["type","command","args","env","url"];function Ui(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Vo(e,"<non-object entry>");const n=t;for(const o of Object.keys(n)){if(Ts.includes(o))continue;const r=Ni(o,[...Ts]);throw new Vo(e,o,r[0])}const i=n.command;if(typeof i=="string")Nn("server.command",i);else if(Array.isArray(i)&&typeof i[0]=="string")Nn("server.command",i[0]);else if(i!==void 0)throw new qn("server.command",JSON.stringify(i))}function Fv(t){const e=process.env.PATH;if(e)for(const n of e.split(_.delimiter)){if(n==="")continue;const i=_.join(n,t);try{return j.accessSync(i,j.constants.X_OK),i}catch{}}}function Bv(t){return ke.createHash("sha256").update(j.readFileSync(t)).digest("hex")}function Kv(t,e){let n=_.dirname(t);for(let i=0;i<8;i++){const o=_.join(n,"node_modules",e,"package.json");if(j.existsSync(o))try{return JSON.parse(j.readFileSync(o,"utf8")).version}catch{return}const r=_.dirname(n);if(r===n)break;n=r}}function Wd(t){const{command:e,identity:n}=t;if(e==="")return;const i=_.isAbsolute(e)?e:Fv(e)??e,o=n.kind==="package"?`package ${n.name??""}@${n.version??""}`:`sha256 ${n.sha256??"(unspecified)"}`;if(!j.existsSync(i))throw new Ye(o,"missing",i);try{j.accessSync(i,j.constants.X_OK)}catch{throw new Ye(o,"not executable",i)}if(!_.isAbsolute(i))throw new Ye(o,"not found on PATH",i);if(n.kind==="path"&&n.sha256){const r=Bv(i);if(r!==n.sha256)throw new Ye(`sha256:${n.sha256}`,`sha256:${r}`,i)}else if(n.kind==="package"&&n.name&&n.version){const r=Kv(i,n.name)??"(unknown)";if(r!==n.version)throw new Ye(`version ${n.version}`,`version ${r}`,i)}}function Jd(t,e,n){const i=Math.min(e.maxMs,e.baseMs*2**t);return Math.floor(n()*i)}class zd{constructor(e){this.failures=0,this.probing=!1,this.failureThreshold=e.failureThreshold,this.resetMs=e.resetMs,this.now=e.now??(()=>Date.now())}state(){return this.openedAt===void 0?"closed":this.now()-this.openedAt>=this.resetMs?"half-open":"open"}tryPass(){const e=this.state();return e==="open"?!1:(e==="half-open"&&(this.probing=!0),!0)}onSuccess(){this.failures=0,this.openedAt=void 0,this.probing=!1}onFailure(){this.failures+=1,(this.probing||this.failures>=this.failureThreshold)&&(this.openedAt=this.now()),this.probing=!1}}async function Yd(t,e,n,i){const o=i.now();let r;for(let s=0;s<e.maxAttempts;s++){if(!n.tryPass())throw new Qe(n.state(),"circuit breaker open — refusing the attempt");if(i.now()-o>=e.budgetMs)throw new Qe("starting",`wall-clock budget ${e.budgetMs}ms exhausted after ${s} attempt(s)`);const a=s===0?Math.min(i.graceMs,e.budgetMs):e.maxMs;try{const c=await t(s,a);return n.onSuccess(),c}catch(c){if(r=c,n.onFailure(),s===e.maxAttempts-1)break;const d=Jd(s,e,i.rand);if(i.now()-o+d>e.budgetMs)break;await i.sleep(d)}}throw r instanceof Qe?r:new Qe(n.state(),r instanceof Error?r.message:String(r))}function Wo(t){if(!t.run)throw new Error(`@adhd/backlog: apigen plugin "${t.id}" declares no run() — cannot mount live`);return t.run}function Xd(){if(!process.env.VITEST)return;const t=()=>{},e={info:t,error:t,debug:t,fatal:t,warn:t,trace:t};return e.child=()=>e,e}const Os=["install","install-skill","serve"];function Hn(t){return t.filter(e=>e.kind==="action").map(e=>{const n=qe(e);return{id:e.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((e,n)=>e.id.localeCompare(n.id))}function qv(t){const e=t.filter(n=>{const i=n.cliPath[n.cliPath.length-1]??"";return Os.includes(i)||Os.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(e.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${e.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 Hv(t,e=[pn]){const n=Hn(t),i=new Set(n.map(r=>r.mcpTool)),o={host:"backlog",operations:t};for(const r of e){const s=r.capabilities.mount;if(s)for(const a of s.operations(o,void 0,void 0))i.add(qe(a).mcp.name)}return[...i].sort()}function Vv(t){return{id:`backlog/${t}`,host:"ts",namespace:{raw:"backlog",words:["backlog"]},path:[{raw:t,words:t.split("-")}],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function Qd(){return Bc.map(Vv).flatMap(t=>Hn([t])).sort((t,e)=>t.id.localeCompare(e.id))}function Gv(){const t=Fd(ct());if(!t)throw new Error(`@adhd/backlog: assertSurfaceIsReal cannot verify the surface — no valid baked IR artifact at ${ct()} (run "nx build backlog" first). Refusing to pass an unverifiable surface.`);const e=Hn(t),n=Qd(),i=new Set(e.map(c=>c.id)),o=new Set(n.map(c=>c.id)),r=[...o].filter(c=>!i.has(c)).sort(),s=[...i].filter(c=>!o.has(c)).sort();if(r.length===0&&s.length===0)return;const a=["@adhd/backlog: mounted-surface self-check failed — an advertised verb is not the surface the built package mounts."];throw r.length>0&&a.push(` advertised but absent from the built package (the \`enrich\` class): ${r.join(", ")}`),s.length>0&&a.push(` mounted but not in the pinned BACKLOG_VERBS list (split brain): ${s.join(", ")}`),new Error(a.join(`
259
+ `))}function Is(t){if(!t||typeof t!="object")return t;const e={},n=o=>{if(Array.isArray(o)){for(const s of o)n(s);return}if(!o||typeof o!="object")return;const r=o;for(const s of["definitions","$defs"]){const a=r[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,d]of Object.entries(a))c in e||(e[c]=d)}for(const[s,a]of Object.entries(r))s==="definitions"||s==="$defs"||n(a)};if(n(t),n(e),Object.keys(e).length===0)return t;const i=(o,r)=>{if(Array.isArray(o))return o.map(d=>i(d,r));if(!o||typeof o!="object")return o;const s=o,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return r.has(d)||!(d in e)?{}:i(e[d],new Set([...r,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=i(l,r));return c};return i(t,new Set)}async function Wv(t={}){const e=ct(),n=_.join(e,"api.d.ts");if(!j.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 i=Fd(e);return i||(await Promise.resolve().then(()=>wl)).extractApiOperationsLive(t)}async function Di(t,e={}){const n=typeof t=="function"?t:()=>t,i=await Wv(e),o={schemas:Object.fromEntries(i.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:Is(c.input),output:Is(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},r=nu(o,[]),s=Hn(i);qv(s);const{version:a}=Li();return{pkg:{id:"backlog",version:a,schemas:r,importPath:_.join(ct(),"api.js"),fns:vv,createClient:async()=>n()},operations:i,surface:s}}async function Rn(t){const e=et({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace});e.ensureDirs();const n=Gd(t,e);Wd(n.server);const i=Kd(),o=()=>{var f;return(f=t.onStateChange)==null?void 0:f.call(t,i.report())},r=new AbortController;t.signal.aborted?r.abort():t.signal.addEventListener("abort",()=>r.abort(),{once:!0});let s,a;const c=tt(e),d=()=>(s||(s=Po(a)),s),l=am()?void 0:tc(d);try{a=await yn(c,e.config.db.busyTimeoutMs)}catch(f){throw l==null||l.dispose(),f}const u={store:a,env:e,embeddingConfig:$v({baseline:e,rebuild:()=>et({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace}),layerFiles:()=>Bd({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace}),log:(f,m)=>console.error(m)})};try{const{pkg:f,operations:m}=await Di(u,{adhdRoot:t.adhdRoot}),p=Xd(),g=[];!t.probeOnly&&(n.transport==="http"||n.transport==="both")&&g.push(Wo(ug)({packages:[f],outputDir:"",options:{port:n.port,host:n.host,usePlugins:[hg,pn]},signal:r.signal,operations:m,logger:p})),!t.probeOnly&&(n.transport==="mcp"||n.transport==="both")&&g.push(Wo(Ig)({packages:[f],outputDir:"",options:{transport:"stdio",usePlugins:[pn]},signal:r.signal,operations:m,logger:p})),i.markLive(),o();const y={maxAttempts:n.connect.maxAttempts,baseMs:n.connect.baseMs,maxMs:n.connect.maxMs,budgetMs:n.connect.budgetMs,breakerFailureThreshold:n.connect.breakerFailureThreshold,breakerResetMs:n.connect.breakerResetMs},w=new zd({failureThreshold:n.connect.breakerFailureThreshold,resetMs:n.connect.breakerResetMs}),v={pkg:f,operations:m,store:a};let b;try{b=await Yd(async(N,k)=>{var A;const R=await qd(v,{timeoutMs:Math.min(k,n.readiness.timeoutMs)});if(!R.ready)throw new Qe("starting",((A=R.failure)==null?void 0:A.message)??"serving-path probe not ready");return R},y,w,{graceMs:n.connect.graceMs,rand:Math.random,now:Date.now,sleep:N=>new Promise(k=>setTimeout(k,N))})}catch(N){b={ready:!1,failure:{kind:"readiness",code:"probe_unavailable",message:N instanceof Error?N.message:String(N)}}}b.ready?i.markReady():b.failure&&i.fail(b.failure),o();const h=Promise.all(g);let S;const E=()=>(S||(r.abort(),S=(async()=>{try{await h}catch{}l==null||l.dispose(),await d()})()),S);return{report:()=>i.report(),whenReady:()=>i.whenReady(),whenClosed:async()=>{try{await h}finally{await E()}},close:E}}catch(f){throw r.abort(),l==null||l.dispose(),await d(),f}}async function Jv(t){await(await Rn(t)).whenClosed()}const it=["claude","codex","opencode"],zv={claude:".claude",codex:".codex",opencode:".opencode"};function Zd(t,e){return e?_.join(t,".codex"):process.env.CODEX_HOME??_.join(t,".codex")}function Yv(t,e,n,i){if(e==="project")return _.join(n,zv[t],"skills");const o=i??te.homedir();return t==="claude"?_.join(o,".claude","skills"):t==="codex"?_.join(Zd(o,i),"skills"):_.join(o,".config","opencode","skills")}function Xv(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),e=_.join(t,"skill","SKILL.md");return j.existsSync(e)?e:_.join(t,"..","skill","SKILL.md")}class oe extends Error{constructor(e){super(e),this.name="BacklogUsageError"}}function Mi(t,e){console.error(JSON.stringify({code:"invalid_argument",message:t.message})),console.error(""),console.error(e),process.exitCode=2}const $s=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
223
260
 
224
261
  Copies the packaged backlog SKILL.md into an agent host's skills directory.
225
262
  (\`backlog install\` is the richer successor — it also registers the MCP server.)
@@ -233,16 +270,16 @@ Examples:
233
270
  backlog install-skill
234
271
  backlog install-skill --host opencode --scope user
235
272
  backlog install-skill --host claude --scope project
236
- `;function Rg(e){let t="all",n="user";for(let r=0;r<e.length;r++){const i=e[r];if(i==="--host")t=e[++r]??"all";else if(i==="--scope")n=e[++r]??"user";else throw new Q(`backlog install-skill: unknown argument "${i}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const r=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new Q(`backlog install-skill: --scope must be "user" or "project", got "${n}"${r}`)}const o=t==="all"?[...Ue]:[t];for(const r of o)if(!Ue.includes(r))throw new Q(`backlog install-skill: --host must be one of ${Ue.join("|")}|all, got "${t}"`);return{hosts:o,scope:n}}function Na(e,t=process.cwd(),n){const{hosts:o,scope:r}=Rg(e);return Ra(o,r,t,n)}function Ra(e,t,n,o){const r=Ng();if(!R.existsSync(r))throw new Error(`backlog install-skill: packaged skill file not found at ${r} — was @adhd/backlog built/installed correctly?`);const i=R.readFileSync(r,"utf8"),s=k.dirname(ot.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=R.existsSync(a)?a:k.join(s,"..","package.json"),d=JSON.parse(R.readFileSync(c,"utf8")),l=[];for(const u of e){const f=k.join(jg(u,t,n,o),"backlog");R.mkdirSync(f,{recursive:!0});const m=k.join(f,"SKILL.md");R.writeFileSync(m,i,"utf8"),R.writeFileSync(k.join(f,"extension.json"),JSON.stringify({name:d.name,version:d.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
237
- `,"utf8"),l.push({host:u,scope:t,path:m})}return l}async function Oa(e){if(e.includes("--help")||e.includes("-h")){console.log(ni);return}let t;try{t=Na(e)}catch(n){if(n instanceof Q)return Oo(n,ni);throw n}console.log(JSON.stringify({installed:t}))}const To=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Og(e){if(!R.existsSync(e))return{};const t=R.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 Ta(e,t,n,o){const r=Og(e),i=r[t],s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};s[n]=o,r[t]=s,R.mkdirSync(k.dirname(e),{recursive:!0}),R.writeFileSync(e,JSON.stringify(r,null,2)+`
238
- `,"utf8")}function Tg(e,t,n){if(e==="project")return k.join(t,".mcp.json");const o=z.homedir();return k.join(o,".claude.json")}function Ig(e,t,n){if(e==="project")return k.join(t,"opencode.json");const o=z.homedir();return k.join(o,".config","opencode","opencode.json")}function $g(e,t,n){if(e==="project")return k.join(t,".codex","config.toml");const o=z.homedir();return k.join(ja(o,n),"config.toml")}function Cg(e,t,n){var d,l;const o=`[${t}]`,r=e.length>0?e.split(`
239
- `):[],i=r.findIndex(u=>u.trim()===o),s=[o,...n];if(i===-1){if(r.length===0||r.every(u=>u.trim()===""))return s.join(`
273
+ `;function Qv(t){let e="all",n="user";for(let o=0;o<t.length;o++){const r=t[o];if(r==="--host")e=t[++o]??"all";else if(r==="--scope")n=t[++o]??"user";else throw new oe(`backlog install-skill: unknown argument "${r}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new oe(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const i=e==="all"?[...it]:[e];for(const o of i)if(!it.includes(o))throw new oe(`backlog install-skill: --host must be one of ${it.join("|")}|all, got "${e}"`);return{hosts:i,scope:n}}function el(t,e=process.cwd(),n){const{hosts:i,scope:o}=Qv(t);return tl(i,o,e,n)}function tl(t,e,n,i){const o=Xv();if(!j.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const r=j.readFileSync(o,"utf8"),s=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),a=_.join(s,"package.json"),c=j.existsSync(a)?a:_.join(s,"..","package.json"),d=JSON.parse(j.readFileSync(c,"utf8")),l=[];for(const u of t){const f=_.join(Yv(u,e,n,i),"backlog");j.mkdirSync(f,{recursive:!0});const m=_.join(f,"SKILL.md");j.writeFileSync(m,r,"utf8"),j.writeFileSync(_.join(f,"extension.json"),JSON.stringify({name:d.name,version:d.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
274
+ `,"utf8"),l.push({host:u,scope:e,path:m})}return l}async function nl(t){if(t.includes("--help")||t.includes("-h")){console.log($s);return}let e;try{e=el(t)}catch(n){if(n instanceof oe)return Mi(n,$s);throw n}console.log(JSON.stringify({installed:e}))}const xi=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Zv(t){if(!j.existsSync(t))return{};const e=j.readFileSync(t,"utf8").trim();if(e==="")return{};const n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${t} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function ol(t,e,n,i){const o=Zv(t),r=o[e],s=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};s[n]=i,o[e]=s,j.mkdirSync(_.dirname(t),{recursive:!0}),j.writeFileSync(t,JSON.stringify(o,null,2)+`
275
+ `,"utf8")}function eb(t,e,n){if(t==="project")return _.join(e,".mcp.json");const i=te.homedir();return _.join(i,".claude.json")}function tb(t,e,n){if(t==="project")return _.join(e,"opencode.json");const i=te.homedir();return _.join(i,".config","opencode","opencode.json")}function nb(t,e,n){if(t==="project")return _.join(e,".codex","config.toml");const i=te.homedir();return _.join(Zd(i,n),"config.toml")}function ob(t,e,n){var d,l;const i=`[${e}]`,o=t.length>0?t.split(`
276
+ `):[],r=o.findIndex(u=>u.trim()===i),s=[i,...n];if(r===-1){if(o.length===0||o.every(u=>u.trim()===""))return s.join(`
240
277
  `)+`
241
- `;for(;r.length>0&&((d=r[r.length-1])==null?void 0:d.trim())==="";)r.pop();return[...r,"",...s].join(`
278
+ `;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
242
279
  `)+`
243
- `}let a=i+1;for(;a<r.length&&!(((l=r[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...r.slice(0,i),...s,...r.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
280
+ `}let a=r+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,r),...s,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
244
281
  `)+`
245
- `}function Pg(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function xg(e,t,n){const o=Tg(e,t);return Ta(o,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...To]}),{host:"claude",scope:e,configPath:o,status:"written"}}function Lg(e,t,n){const o=Ig(e,t);return Ta(o,"mcp","backlog",{type:"local",command:["npx",...To]}),{host:"opencode",scope:e,configPath:o,status:"written"}}function Ug(e,t,n){const o=$g(e,t,n),r=R.existsSync(o)?R.readFileSync(o,"utf8"):"",i=Cg(r,"mcp_servers.backlog",['command = "npx"',`args = ${Pg(To)}`]);return R.mkdirSync(k.dirname(o),{recursive:!0}),R.writeFileSync(o,i,"utf8"),{host:"codex",scope:e,configPath:o,status:"written"}}function Dg(e,t,n,o){return e==="claude"?xg(t,n):e==="opencode"?Lg(t,n):Ug(t,n,o)}function Mg(e,t){let n="all",o="user",r=!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")o=e[++a]??"user";else if(c==="--skill-only")r=!0;else if(c==="--mcp-only")i=!0;else throw new Q(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(r&&i)throw new Q(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(o!=="user"&&o!=="project"){const a=o==="global"?' — the machine-wide scope is spelled "user"':"";throw new Q(`backlog ${t}: --scope must be "user" or "project", got "${o}"${a}`)}const s=n==="all"?[...Ue]:[n];for(const a of s)if(!Ue.includes(a))throw new Q(`backlog ${t}: --host must be one of ${Ue.join("|")}|all, got "${n}"`);return{hosts:s,scope:o,skillOnly:r,mcpOnly:i}}const oi=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
282
+ `}function ib(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}function rb(t,e,n){const i=eb(t,e),o={type:"stdio",command:"npx",args:[...xi]};return Ui(o,i),ol(i,"mcpServers","backlog",o),{host:"claude",scope:t,configPath:i,status:"written"}}function sb(t,e,n){const i=tb(t,e),o={type:"local",command:["npx",...xi]};return Ui(o,i),ol(i,"mcp","backlog",o),{host:"opencode",scope:t,configPath:i,status:"written"}}function ab(t,e,n){const i=nb(t,e,n),o=j.existsSync(i)?j.readFileSync(i,"utf8"):"",r=ob(o,"mcp_servers.backlog",['command = "npx"',`args = ${ib(xi)}`]);return j.mkdirSync(_.dirname(i),{recursive:!0}),j.writeFileSync(i,r,"utf8"),{host:"codex",scope:t,configPath:i,status:"written"}}function cb(t,e,n,i){return t==="claude"?rb(e,n):t==="opencode"?sb(e,n):ab(e,n,i)}function db(t,e){let n="all",i="user",o=!1,r=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--host")n=t[++a]??"all";else if(c==="--scope")i=t[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")r=!0;else throw new oe(`backlog ${e}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&r)throw new oe(`backlog ${e}: --skill-only and --mcp-only are mutually exclusive`);if(i!=="user"&&i!=="project"){const a=i==="global"?' — the machine-wide scope is spelled "user"':"";throw new oe(`backlog ${e}: --scope must be "user" or "project", got "${i}"${a}`)}const s=n==="all"?[...it]:[n];for(const a of s)if(!it.includes(a))throw new oe(`backlog ${e}: --host must be one of ${it.join("|")}|all, got "${n}"`);return{hosts:s,scope:i,skillOnly:o,mcpOnly:r}}const Cs=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
246
283
 
247
284
  Installs the backlog skill AND registers the backlog MCP server into an agent
248
285
  host's config, in one step.
@@ -259,26 +296,37 @@ Examples:
259
296
 
260
297
  Back-compat: \`backlog install-skill\` remains available and behaves exactly
261
298
  like \`backlog install --skill-only\` (original --host/--scope grammar only).
262
- `;function Fg(e,t=process.cwd(),n){const{hosts:o,scope:r,skillOnly:i,mcpOnly:s}=Mg(e,"install"),a=s?[]:Ra(o,r,t,n),c=i?[]:o.map(d=>Dg(d,r,t,n));return{skill:a,mcp:c}}async function Bg(e){if(e.includes("--help")||e.includes("-h")){console.log(oi);return}let t;try{t=Fg(e)}catch(n){if(n instanceof Q)return Oo(n,oi);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 o=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${o}`)}console.log(JSON.stringify(t))}const ri=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
299
+ `;function lb(t,e=process.cwd(),n){const{hosts:i,scope:o,skillOnly:r,mcpOnly:s}=db(t,"install"),a=s?[]:tl(i,o,e,n),c=r?[]:i.map(d=>cb(d,o,e,n));return{skill:a,mcp:c}}async function ub(t){if(t.includes("--help")||t.includes("-h")){console.log(Cs);return}let e;try{e=lb(t)}catch(n){if(n instanceof oe)return Mi(n,Cs);throw n}for(const n of e.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of e.mcp){const i=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${i}`)}console.log(JSON.stringify(e))}const Ps=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
263
300
 
264
301
  Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
265
302
  process's own configured transports to the way an agent host or a script
266
303
  expects to reach it.
267
304
 
268
- --transport <name> mcp | http | both (default: mcp)
269
- --port <N> HTTP listen port (default: 3300; ignored for mcp-only)
270
- --host <name> HTTP listen host (default: 127.0.0.1; ignored for mcp-only)
305
+ --transport <name> mcp | http | both (default: from ADHD_BACKLOG_SERVICE_TRANSPORT
306
+ / the service.* config, else mcp)
307
+ --port <N> HTTP listen port (default: from ADHD_BACKLOG_SERVICE_PORT
308
+ / the service.* config, else 3300; ignored for mcp-only)
309
+ --host <name> HTTP listen host (default: from ADHD_BACKLOG_SERVICE_HOST
310
+ / the service.* config, else 127.0.0.1; ignored for mcp-only)
311
+ --ready-file <path> Write the service report to <path> once the server is
312
+ READY (the serving path answered), atomically, and
313
+ again on every state change.
314
+ --probe Run the serving-path readiness probe once, print the
315
+ report as JSON, and exit 0 (ready) / 1 (not ready).
271
316
 
272
317
  Examples:
273
318
  backlog serve
274
319
  backlog serve --transport http --port 3300
275
320
  backlog serve --transport both --host 0.0.0.0
276
- `;function Kg(e){let t="mcp",n,o;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")o=e[++i];else throw new Q(`backlog serve: unknown argument "${s}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Q(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const r={transport:t};return n!==void 0&&(r.port=n),o!==void 0&&(r.host=o),r}async function Ia(e,t={}){if(e.includes("--help")||e.includes("-h")){console.log(ri);return}let n;try{n=Kg(e)}catch(s){if(s instanceof Q)return Oo(s,ri);throw s}const o=new AbortController;process.on("SIGTERM",()=>o.abort()),process.on("SIGINT",()=>o.abort());const r=_a({...n,...t,signal:o.signal}),i=t.namespace==="sandbox"?R.mkdtempSync(k.join(z.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Hn.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 r}const qg=["input","data"];function Hg(e){let t;for(let n=0;n<e.length;n++){const o=e[n];if(o!==void 0)if(o==="--input"){const r=e[n+1];r!==void 0&&(t=r)}else o.startsWith("--input=")&&(t=o.slice(8))}return t}function Vg(e){let t;try{t=JSON.parse(e)}catch{return}if(!(t===null||typeof t!="object"||Array.isArray(t)))return t}function Gg(e,t){let n=0;for(;n<e.length&&e[n]!==void 0&&!e[n].startsWith("-");)n++;for(let o=n;o>=1;o--){const r=e.slice(0,o).join(" ");for(const i of t){const s=Re(i).cli.path;if(s.join(" ")===r)return{op:i,path:s}}}}function Wg(e,t){var a,c,d;const n=(a=e.path[e.path.length-1])==null?void 0:a.raw;if(!n)return;const o=t[n];if(!o)return;const r=o.input,i=(c=r.properties)==null?void 0:c.data,s=(d=i==null?void 0:i.properties)==null?void 0:d.input;if(s)return{schema:s,root:r}}function Jg(e,t,n){if(e.includes("--help")||e.includes("-h"))return;const o=Hg(e);if(o===void 0)return;const r=Vg(o);if(!r)return;const i=Gg(e,t);if(!i)return;const s=Wg(i.op,n),a=(s==null?void 0:s.schema.properties)??{},c=qg.filter(d=>Object.prototype.hasOwnProperty.call(r,d)&&!Object.prototype.hasOwnProperty.call(a,d));if(c.length!==0)return{wrapperKeys:[...c],commandLabel:i.path.join(" "),exampleJson:s?JSON.stringify(De(s.schema,s.root)):void 0}}function zg(e){const t=e.wrapperKeys.map(o=>`"${o}"`).join(" and "),n=e.exampleJson??"{ …the params… }";return`--input expects the CLI's bare params object, but was given the MCP envelope shape (a top-level ${t} wrapper). The CLI never wraps params in an "input"/"data" object — that envelope is the MCP calling convention (mcp__backlog__*) and does not apply here. Pass the params directly, e.g. ${e.commandLabel} --input '${n}'`}const Io=["limit","offset","sort","direction"],$a=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],$o=["status","priority"],zt=["fields"],Yg={"claimed-by":"claimedBy","project-path":"projectPath"},Ca=[...Io,...zt,...$a,...$o].map(e=>`--${e}`).sort(),Xg=new Set([...Io,...zt]),Qg=new Set([...$o,...zt]),Zg=new Set([...Io,...zt,...$a,...$o]),eh=new Set(["limit","offset"]),Pa=['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(`
277
- `);function ii(e,t,n,o){if(!o){e[t]=n;return}const r=e[t]??[];e[t]=[...r,...n.split(",").map(i=>i.trim()).filter(i=>i.length>0)]}function xa(e){if(e.includes("--help")||e.includes("-h"))return{kind:"help",text:Pa};const t={},n={};let o,r=0;for(;r<e.length;){const a=e[r];if(!a.startsWith("--")){if(o!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};o=a,r+=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(!Zg.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${Ca.join(", ")}`};r+=1;let u;if(d!==void 0)u=d;else{if(r>=e.length)return{kind:"error",message:`Missing value for --${c}`};u=e[r],r+=1}const f=Qg.has(c);Xg.has(c)?ii(t,c,u,f):ii(n,Yg[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 eh){const c=t[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(t[a]=Number(c))}const i=n.anchor;if(i!==void 0&&o!==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&&o===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=o,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function La(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 Re(t).cli.path.slice(0,-1)}const si=[Rt];function th(e,t,n){const o={host:n,operations:t},r=new Set;for(const i of e){const s=i.capabilities.mount;if(!s)continue;const a=s.operations(o,void 0,void 0);for(const c of a){const[d]=Re(c).cli.path;d!==void 0&&r.add(d)}}return r}function Ua(e,t,n){var r;return e.length===0?[...e]:(r=e[0])!=null&&r.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 Co(e){const t=[],n=[];let o=!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===""?o=!0:t.push(a);continue}if(s==="--namespace"){const a=e[i+1];a===void 0||a.startsWith("-")?o=!0:(t.push(a),i++);continue}n.push(s)}}const r=new Set(t);return{argv:n,namespace:t[t.length-1],missingValue:o,conflicting:r.size>1}}async function nh(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=ie("invalid_argument","ir-artifact: --out <path> is required");console.error(JSON.stringify(s)),process.exitCode=we(s);return}const n=k.join(Jt(),"api.d.ts");if(!R.existsSync(n)){const s=ie("internal",`ir-artifact: ${n} does not exist — run "nx build backlog" first`);console.error(JSON.stringify(s)),process.exitCode=we(s);return}const o=k.resolve(t),{buildBakedOperations:r}=await Promise.resolve().then(()=>qa),i=await r(n);await hg({apiDts:n,outFile:o,extractorVersion:_o,operations:i}),console.log(JSON.stringify({ok:!0,out:o,operations:i.length}))}async function Da(e,t={}){var b;const{argv:n,namespace:o,missingValue:r,conflicting:i}=Co(e??process.argv.slice(2)),s={...t};if(r){const h=ie("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=we(h);return}if(i){const h=e??process.argv.slice(2),y=new Set;for(let v=0;v<h.length;v++){const S=h[v];S!==void 0&&(S.startsWith("--namespace=")?y.add(S.slice(12)):S==="--namespace"&&h[v+1]!==void 0&&y.add(h[v+1]))}const w=ie("invalid_argument",`Invalid argument "namespace": conflicting values ${[...y].map(v=>`"${v}"`).join(", ")}`);console.log(JSON.stringify(w)),process.exitCode=we(w);return}if(o!==void 0&&!((b=Be.namespaces)!=null&&b.includes(o))){const h=Be.namespaces??[],y=xs(o,h),w=`must be one of ${h.map(S=>`"${S}"`).join(", ")}`+(y.length>0?` (did you mean ${y.map(S=>`"${S}"`).join(" or ")}?)`:""),v=ie("invalid_argument",`Invalid argument "namespace": ${w}`);console.log(JSON.stringify(v)),process.exitCode=we(v);return}o!==void 0&&(s.namespace=o);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=R.mkdtempSync(k.join(z.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");R.mkdirSync(h,{recursive:!0}),R.writeFileSync(k.join(h,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
321
+ backlog serve --transport mcp --ready-file /run/backlog/ready.json
322
+ backlog serve --probe
323
+ `;function fb(t){let e,n,i,o,r=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--transport")e=t[++a];else if(c==="--port")n=Number(t[++a]);else if(c==="--host")i=t[++a];else if(c==="--ready-file")o=t[++a];else if(c==="--probe")r=!0;else throw new oe(`backlog serve: unknown argument "${c}" (expected --transport/--port/--host/--ready-file/--probe)`)}if(e!==void 0&&e!=="mcp"&&e!=="http"&&e!=="both")throw new oe(`backlog serve: --transport must be mcp|http|both, got "${e}"`);const s={probe:r};return e!==void 0&&(s.transport=e),n!==void 0&&(s.port=n),i!==void 0&&(s.host=i),o!==void 0&&(s.readyFile=o),s}function pb(t,e){j.mkdirSync(_.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;j.writeFileSync(n,`${JSON.stringify(t,null,2)}
324
+ `,"utf8"),j.renameSync(n,e)}async function il(t,e={}){if(t.includes("--help")||t.includes("-h")){console.log(Ps);return}let n;try{n=fb(t)}catch(d){if(d instanceof oe)return Mi(d,Ps);throw d}const i=new AbortController;process.on("SIGTERM",()=>i.abort()),process.on("SIGINT",()=>i.abort());const o={...n.transport!==void 0?{transport:n.transport}:{},...n.port!==void 0?{port:n.port}:{},...n.host!==void 0?{host:n.host}:{},...e,signal:i.signal};if(n.probe){const d=await Rn({...o,probeOnly:!0}),l=d.report();console.log(JSON.stringify(l)),await d.close(),l.state!=="ready"&&(process.exitCode=1);return}const r=n.readyFile,s=Rn({...o,...r!==void 0?{onStateChange:d=>{try{pb(d,r)}catch(l){console.error(`[backlog] WARNING: failed to write --ready-file ${r}: ${l instanceof Error?l.message:String(l)}`)}}}:{}}),a=e.namespace==="sandbox"?j.mkdtempSync(_.join(te.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Jo.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...a!==void 0?{logDir:a}:{}})}catch(d){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${d instanceof Error?d.message:String(d)}); telemetry records will be silently dropped this process`)}const c=await s;try{await c.whenClosed()}finally{await c.close()}}const mb=["input","data"];function gb(t){let e;for(let n=0;n<t.length;n++){const i=t[n];if(i!==void 0)if(i==="--input"){const o=t[n+1];o!==void 0&&(e=o)}else i.startsWith("--input=")&&(e=i.slice(8))}return e}function hb(t){let e;try{e=JSON.parse(t)}catch{return}if(!(e===null||typeof e!="object"||Array.isArray(e)))return e}function yb(t,e){let n=0;for(;n<t.length&&t[n]!==void 0&&!t[n].startsWith("-");)n++;for(let i=n;i>=1;i--){const o=t.slice(0,i).join(" ");for(const r of e){const s=qe(r).cli.path;if(s.join(" ")===o)return{op:r,path:s}}}}function wb(t,e){var a,c,d;const n=(a=t.path[t.path.length-1])==null?void 0:a.raw;if(!n)return;const i=e[n];if(!i)return;const o=i.input,r=(c=o.properties)==null?void 0:c.data,s=(d=r==null?void 0:r.properties)==null?void 0:d.input;if(s)return{schema:s,root:o}}function vb(t,e,n){if(t.includes("--help")||t.includes("-h"))return;const i=gb(t);if(i===void 0)return;const o=hb(i);if(!o)return;const r=yb(t,e);if(!r)return;const s=wb(r.op,n),a=(s==null?void 0:s.schema.properties)??{},c=mb.filter(d=>Object.prototype.hasOwnProperty.call(o,d)&&!Object.prototype.hasOwnProperty.call(a,d));if(c.length!==0)return{wrapperKeys:[...c],commandLabel:r.path.join(" "),exampleJson:s?JSON.stringify(rt(s.schema,s.root)):void 0}}function bb(t){const e=t.wrapperKeys.map(i=>`"${i}"`).join(" and "),n=t.exampleJson??"{ …the params… }";return`--input expects the CLI's bare params object, but was given the MCP envelope shape (a top-level ${e} wrapper). The CLI never wraps params in an "input"/"data" object — that envelope is the MCP calling convention (mcp__backlog__*) and does not apply here. Pass the params directly, e.g. ${t.commandLabel} --input '${n}'`}const Fi=["limit","offset","sort","direction"],rl=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],Bi=["status","priority"],Vn=["fields"],Eb={"claimed-by":"claimedBy","project-path":"projectPath"},sl=[...Fi,...Vn,...rl,...Bi].map(t=>`--${t}`).sort(),Sb=new Set([...Fi,...Vn]),kb=new Set([...Bi,...Vn]),_b=new Set([...Fi,...Vn,...rl,...Bi]),Ab=new Set(["limit","offset"]),al=['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(`
325
+ `);function Ls(t,e,n,i){if(!i){t[e]=n;return}const o=t[e]??[];t[e]=[...o,...n.split(",").map(r=>r.trim()).filter(r=>r.length>0)]}function cl(t){if(t.includes("--help")||t.includes("-h"))return{kind:"help",text:al};const e={},n={};let i,o=0;for(;o<t.length;){const a=t[o];if(!a.startsWith("--")){if(i!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};i=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(!_b.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${sl.join(", ")}`};o+=1;let u;if(d!==void 0)u=d;else{if(o>=t.length)return{kind:"error",message:`Missing value for --${c}`};u=t[o],o+=1}const f=kb.has(c);Sb.has(c)?Ls(e,c,u,f):Ls(n,Eb[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 Ab){const c=e[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(e[a]=Number(c))}const r=n.anchor;if(r!==void 0&&i!==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(r===void 0&&i===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const s={...e};return r!==void 0?s.view="similar":s.text=i,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function dl(t){const e=t.find(n=>n.kind==="action");if(!e)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return qe(e).cli.path.slice(0,-1)}const Us=[pn];function Nb(t,e,n){const i={host:n,operations:e},o=new Set;for(const r of t){const s=r.capabilities.mount;if(!s)continue;const a=s.operations(i,void 0,void 0);for(const c of a){const[d]=qe(c).cli.path;d!==void 0&&o.add(d)}}return o}function ll(t,e,n){var o;return t.length===0?[...t]:(o=t[0])!=null&&o.startsWith("-")?[...t]:t[0]!==void 0&&n.has(t[0])?[...t]:e.length>0&&e.every((r,s)=>t[s]===r)?[...t]:[...e,...t]}function Ki(t){const e=[],n=[];let i=!1;for(let r=0;r<t.length;r++){const s=t[r];if(s!==void 0){if(s.startsWith("--namespace=")){const a=s.slice(12);a===""?i=!0:e.push(a);continue}if(s==="--namespace"){const a=t[r+1];a===void 0||a.startsWith("-")?i=!0:(e.push(a),r++);continue}n.push(s)}}const o=new Set(e);return{argv:n,namespace:e[e.length-1],missingValue:i,conflicting:o.size>1}}async function Rb(t){let e;for(let s=0;s<t.length;s++){const a=t[s];if(a!==void 0){if(a==="--out"||a==="-o"){const c=t[s+1];c!==void 0&&!c.startsWith("-")&&(e=c,s++)}else if(a.startsWith("--out=")){const c=a.slice(6);c!==""&&(e=c)}}}if(!e){const s=ne("invalid_argument","ir-artifact: --out <path> is required");console.error(JSON.stringify(s)),process.exitCode=je(s);return}const n=_.join(ct(),"api.d.ts");if(!j.existsSync(n)){const s=ne("internal",`ir-artifact: ${n} does not exist — run "nx build backlog" first`);console.error(JSON.stringify(s)),process.exitCode=je(s);return}const i=_.resolve(e),{buildBakedOperations:o}=await Promise.resolve().then(()=>wl),r=await o(n);await Tv({apiDts:n,outFile:i,extractorVersion:Ci,operations:r}),console.log(JSON.stringify({ok:!0,out:i,operations:r.length}))}async function ul(t,e={}){var y;const{argv:n,namespace:i,missingValue:o,conflicting:r}=Ki(t??process.argv.slice(2)),s={...e};if(o){const w=ne("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(w)),process.exitCode=je(w);return}if(r){const w=t??process.argv.slice(2),v=new Set;for(let h=0;h<w.length;h++){const S=w[h];S!==void 0&&(S.startsWith("--namespace=")?v.add(S.slice(12)):S==="--namespace"&&w[h+1]!==void 0&&v.add(w[h+1]))}const b=ne("invalid_argument",`Invalid argument "namespace": conflicting values ${[...v].map(h=>`"${h}"`).join(", ")}`);console.log(JSON.stringify(b)),process.exitCode=je(b);return}if(i!==void 0&&!((y=Ie.namespaces)!=null&&y.includes(i))){const w=Ie.namespaces??[],v=Ni(i,w),b=`must be one of ${w.map(S=>`"${S}"`).join(", ")}`+(v.length>0?` (did you mean ${v.map(S=>`"${S}"`).join(" or ")}?)`:""),h=ne("invalid_argument",`Invalid argument "namespace": ${b}`);console.log(JSON.stringify(h)),process.exitCode=je(h);return}i!==void 0&&(s.namespace=i);const a=s.namespace??"production";s.adhdRoot===void 0&&process.env.ADHD_ROOT&&(s.adhdRoot=process.env.ADHD_ROOT);const c=w=>w.includes(`${_.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=j.mkdtempSync(_.join(te.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 w=_.join(s.adhdRoot,"backlog","sandbox");j.mkdirSync(w,{recursive:!0}),j.writeFileSync(_.join(w,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
278
326
  # an absence-of-file default. embedding.enabled is off so a sandboxed
279
327
  # run never pays a real model-load cost or opens a real vector store.
280
328
  embedding:
281
329
  enabled: false
282
- `)}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=xe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:ze(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await nh(n.slice(1));return}if(n[0]==="store-check"){const h=xe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=ze(h);let w;try{w=await $t(y,h.config.db.busyTimeoutMs),await Vs(w.adapter);const{total:v,observed:S}=await Ji(w.adapter);console.log(JSON.stringify({ok:!0,dbPath:y,total:v,kinds:S,expectedKinds:[...ao]}));return}catch(v){if(v instanceof Wi){console.error(JSON.stringify({ok:!1,dbPath:y,error:{code:"store_vocabulary_mismatch",message:v.message},observed:v.observed,expectedKinds:v.recognized})),process.exitCode=1;return}if(v instanceof Hs){console.error(v.message),console.error(JSON.stringify({ok:!1,dbPath:y,error:{code:"catalog_invariant_violation",message:v.message},violations:v.violations})),process.exitCode=1;return}throw v}finally{w&&await xn(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, and assert the status/priority catalog invariants; non-zero on a mismatch or a catalog violation"),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 Oa(n.slice(1));return}if(n[0]==="install"){await Bg(n.slice(1));return}if(n[0]==="serve"){await Ia(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(No()));return}let l;if(n[0]==="search"){const h=xa(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=xe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=await $t(ze(h),h.config.db.busyTimeoutMs);u={store:y,ctx:{store:y,env:h}}}return u.ctx};let m;const p=()=>(m||(m=xn(u==null?void 0:u.store)),m),g=ys(p);try{const{pkg:h,operations:y}=await Ro(f,{adhdRoot:s.adhdRoot}),w=l??n,v=La(y),S=th(si,y,h.id),E=Ua(w,v,S),A=Jg(E,y,h.schemas);if(A){const N=ie("invalid_argument",zg(A));console.error(JSON.stringify(N)),process.exitCode=we(N);return}await qn(Ll)({packages:[h],operations:y,outputDir:"",options:{argv:E,usePlugins:[...si],exitCode:N=>Ks(N)?we(N):void 0},signal:s.signal??new AbortController().signal,logger:ka()});const _=w.length>1&&w[0]!=="batch"&&(w.includes("--help")||w.includes("-h"));_&&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)."),_&&w[0]==="query"&&console.log(`Notes:
330
+ `)}if(s.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=_.join(s.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:tt(w),embeddingEnabled:w.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await Rb(n.slice(1));return}if(n[0]==="store-check"){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});w.ensureDirs();const v=tt(w);let b;try{b=await yn(v,w.config.db.busyTimeoutMs),await Vc(b.adapter);const{total:h,observed:S}=await Ra(b.adapter);console.log(JSON.stringify({ok:!0,dbPath:v,total:h,kinds:S,expectedKinds:[...fi]}));return}catch(h){if(h instanceof Na){console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"store_vocabulary_mismatch",message:h.message},observed:h.observed,expectedKinds:h.recognized})),process.exitCode=1;return}if(h instanceof Hc){console.error(h.message),console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"catalog_invariant_violation",message:h.message},violations:h.violations})),process.exitCode=1;return}throw h}finally{b&&await Po(b)}}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, and assert the status/priority catalog invariants; non-zero on a mismatch or a catalog violation"),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 nl(n.slice(1));return}if(n[0]==="install"){await ub(n.slice(1));return}if(n[0]==="serve"){await il(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(Li()));return}let l;if(n[0]==="search"){const w=cl(n.slice(1));if(w.kind==="help"){console.log(w.text);return}if(w.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:w.message})),process.exitCode=2;return}l=w.argv}let u;const f=async()=>{if(!u){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});w.ensureDirs();const v=await yn(tt(w),w.config.db.busyTimeoutMs);u={store:v,ctx:{store:v,env:w}}}return u.ctx};let m;const p=()=>(m||(m=Po(u==null?void 0:u.store)),m),g=tc(p);try{const{pkg:w,operations:v}=await Di(f,{adhdRoot:s.adhdRoot}),b=l??n,h=dl(v),S=Nb(Us,v,w.id),E=ll(b,h,S),N=vb(E,v,w.schemas);if(N){const R=ne("invalid_argument",bb(N));console.error(JSON.stringify(R)),process.exitCode=je(R);return}await Wo(lp)({packages:[w],operations:v,outputDir:"",options:{argv:E,usePlugins:[...Us],exitCode:R=>xc(R)?je(R):void 0},signal:s.signal??new AbortController().signal,logger:Xd()});const k=b.length>1&&b[0]!=="batch"&&(b.includes("--help")||b.includes("-h"));k&&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)."),k&&b[0]==="query"&&console.log(`Notes:
283
331
  - view:"similar" additionally requires filter.anchor (uid of the reference issue) OR filter.semantic (free text) — neither given throws invalid_argument.
284
- - 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{g.dispose(),await p()}}function Ma(e){return e==="status"?"has_status":"has_priority"}function Fa(e){return new RegExp("\\p{L}","u").test(e)&&e===e.toUpperCase()}function oh(e){return e===e.toLowerCase()}function Ba(e,t){return e==="status"?oh(t):Fa(t)}function ai(e){if(e===null)return{};try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:{}}catch{return{}}}function ci(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}async function di(e,t){return await e.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ? AND t_invalid IS NULL",[t])??null}async function un(e,t){return await e.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ?",[t])??null}function rh(e,t){const n=[],o=[],r=[["status",e],["priority",t]];for(const[i,s]of r){const a=new Map;for(const c of s){const d=Y(c.name??""),l=a.get(d);l?l.push(c):a.set(d,[c])}for(const c of a.values()){if(c.length<2)continue;const d=[...c].sort((m,p)=>m.id-p.id),l=d.find(m=>Ba(i,m.name??""));if(l===void 0&&i==="status"){o.push({kind:i,names:d.map(m=>m.name??"")});continue}const u=l??d[0],f=d.filter(m=>m.uid!==u.uid).map(m=>m.uid);f.length!==0&&n.push({canonicalUid:u.uid,fragmentUids:f})}}return{groups:n,unmergeable:o,at:D()}}function Ka(e,t){if(e!=="status"&&e!=="priority")throw new Error(`applyCaseFragmentMerge: uid ${t} is kind "${e}" — only "status"/"priority" catalog rows are mergeable.`)}async function ih(e,t){return V(e,async n=>{const o=[];for(const r of t.groups){const i=await di(n,r.canonicalUid);if(!i)continue;Ka(i.kind,i.uid);const s=Ma(i.kind),a=await L(n,s),c=Y(i.name??""),d=ai(i.meta),l=i.name??"";if(i.kind==="status"&&!Ba("status",l))throw new Error(`applyCaseFragmentMerge: refusing to merge into status uid ${i.uid} named "${l}" — a status canonical must carry the write path's lowercase spelling.`);const u=[];for(const v of r.fragmentUids){const S=await di(n,v);if(S&&S.rowid!==i.rowid){if(S.kind!==i.kind)throw new Error(`applyCaseFragmentMerge: refusing to merge uid ${S.uid} (kind "${S.kind}") into uid ${i.uid} (kind "${i.kind}") — kinds must match.`);if(Y(S.name??"")!==c)throw new Error(`applyCaseFragmentMerge: refusing to merge "${S.name??""}" into "${i.name??""}" — not a case-variant of the same token (they do not fold together).`);u.push(S)}}if(u.length===0)continue;let f;const m=[];let p=d;if(i.kind==="priority"&&!Fa(l)){const v=l.toUpperCase();v!==l&&(await n.executeRun("UPDATE node SET name = ? WHERE rowid = ? AND t_invalid IS NULL",[v,i.rowid]),f={uid:i.uid,from:l,to:v},l.length>0&&m.push(l))}for(const v of u){const S=ai(v.meta),E=typeof S.rank=="number"?S.rank:void 0,{rows:A}=await n.executeAll("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[v.rowid,s]),_=[];for(const j of A){await ge(n,{srcRowid:j.src,dstRowid:v.rowid,rel:s,reason:"catalog-case-fragment-merge",at:t.at});const O=await ee(n,j.src);O&&(await x(n,{at:t.at,srcRowid:j.src,srcUid:O.uid,srcKind:O.kind,dstRowid:i.rowid,dstUid:i.uid,dstKind:i.kind,rel:s,rule:a,typePolicy:e.typePolicy}),_.push({srcRowid:j.src,rel:s,fragmentDstRowid:v.rowid}))}(typeof p.rank=="number"?p.rank:void 0)===void 0&&E!==void 0&&(p={...p,rank:E});for(const j of[v.name??"",...ci(S.aliases)])j.length>0&&m.push(j);await n.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[t.at,v.rowid]),o.push({fragmentUid:v.uid,canonicalUid:i.uid,fragmentMeta:S,repointedEdges:_,...E!==void 0?{retainedRank:E}:{},...f!==void 0?{renamed:f}:{},canonicalMetaBefore:d})}const g=f?f.to:l,h=[...ci(p.aliases)];let y=!1;for(const v of m)v!==g&&(h.includes(v)||(h.push(v),y=!0));y&&(p={...p,aliases:h}),(y||p!==d)&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(p),i.rowid])}return{entries:o,at:t.at}})}async function sh(e,t){await V(e,async n=>{const o=D(),r=new Map;for(const i of t.entries)i.canonicalMetaBefore!==void 0&&!r.has(i.canonicalUid)&&r.set(i.canonicalUid,i.canonicalMetaBefore);for(const i of t.entries){const s=await un(n,i.fragmentUid),a=await un(n,i.canonicalUid);if(!s||!a)continue;Ka(s.kind,s.uid);const c=Ma(s.kind),d=await L(n,c);for(const l of i.repointedEdges){await ge(n,{srcRowid:l.srcRowid,dstRowid:a.rowid,rel:l.rel,reason:"catalog-case-fragment-merge-reverse",at:o});const u=await ee(n,l.srcRowid);u&&await x(n,{at:o,srcRowid:l.srcRowid,srcUid:u.uid,srcKind:u.kind,dstRowid:s.rowid,dstUid:s.uid,dstKind:s.kind,rel:l.rel,rule:d,typePolicy:e.typePolicy})}await n.executeRun("UPDATE node SET meta = ?, t_invalid = NULL WHERE rowid = ?",[JSON.stringify(i.fragmentMeta??{}),s.rowid])}for(const[i,s]of r){const a=await un(n,i);a&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(s??{}),a.rowid])}for(const i of t.entries)i.renamed&&await n.executeRun("UPDATE node SET name = ? WHERE uid = ?",[i.renamed.from,i.renamed.uid])})}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)===ot.pathToFileURL(R.realpathSync(process.argv[1])).href){const{namespace:e,argv:t}=Co(process.argv.slice(2)),n=t[0]==="ir-artifact",o=e==="sandbox"?R.mkdtempSync(k.join(z.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{Hn.initTelemetry({service:"backlog",role:"cli",logSink:"file",...o!==void 0?{logDir:o}:{}})}catch(r){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${r instanceof Error?r.message:String(r)}); telemetry records will be silently dropped this process`)}Da().catch(r=>{console.error(r instanceof Error?r.stack??r.message:String(r)),process.exitCode=1})}const ah=_o,Po="backlog";function xo(e,t){return{sourceFile:e,namespace:Po,tsconfig:t,dropFileSegment:!0}}function ch(e={}){return Ef(e)}function dh(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function lh(e={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:lg({cache:ch(e),extractorVersion:ah})}}}}let li;function uh(e={}){return li??(li=vd(dh()?[lh(e)]:[],t=>{var n;return Ti(xo(t.source,typeof((n=t.extractorOptions)==null?void 0:n.tsconfig)=="string"?t.extractorOptions.tsconfig:void 0))})),li}async function fh(e){return Ti(xo(e))}async function ph(e={}){const t=k.join(Jt(),"api.d.ts");return uh(e)({source:t,host:"ts",namespace:Po,extractorOptions:{}})}const qa=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:Po,buildBacklogExtractOptions:xo,buildBakedOperations:fh,extractApiOperationsLive:ph},Symbol.toStringTag,{value:"Module"}));exports.BACKLOG_ERROR_CODES=Fs;exports.BACKLOG_EXIT_CODE=ko;exports.RESERVED_TERMINAL_STATUS_NAMES=Ht;exports.RagNotConfiguredError=qs;exports.SEARCH_FLAGS=Ca;exports.SEARCH_HELP=Pa;exports.applyCaseFragmentMerge=ih;exports.applyTerminalBackfill=pu;exports.backlogEnvironmentSpec=Be;exports.buildBacklogApigenPackage=Ro;exports.buildBacklogEnv=xe;exports.buildSearchArgv=xa;exports.catalogNameFold=Y;exports.claim=pa;exports.closeGraphBacklogStore=hs;exports.create=la;exports.delete=ha;exports.embeddingStatus=ca;exports.errorEnvelope=ie;exports.exitCodeForEnvelope=we;exports.get=oa;exports.installSkill=Na;exports.isBacklogErrorCode=Bs;exports.isOutcomeEnvelope=Ks;exports.isOutcomeError=am;exports.isOutcomeOk=sm;exports.lookup=da;exports.move=ga;exports.okEnvelope=Ao;exports.openCurve=aa;exports.openGraphBacklogStore=$t;exports.partOfRollup=sa;exports.planCaseFragmentMerge=rh;exports.planTerminalBackfill=fu;exports.prefixCommand=Ua;exports.priorityMatrix=ia;exports.query=ra;exports.readBacklogVersionInfo=No;exports.relate=ma;exports.resolveBacklogDbPath=ze;exports.resolveBacklogScope=bo;exports.resolveCommandPrefix=La;exports.resolveExpectedMcpToolNames=kg;exports.reverseCaseFragmentMerge=sh;exports.reverseTerminalBackfill=mu;exports.rmLocation=ba;exports.runBacklogCli=Da;exports.runInstallSkillCommand=Oa;exports.runServeCommand=Ia;exports.startBacklogServer=_a;exports.stripNamespaceFlag=Co;exports.suggestClaimantIdentity=Sf;exports.transition=fa;exports.update=ua;exports.upsertComponent=wa;exports.upsertLocation=va;exports.upsertProject=ya;
332
+ - 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{g.dispose(),await p()}}const fl="spec_of_seq",jb=`CREATE INDEX IF NOT EXISTS ${fl} ON node (json_extract(meta,'$.spec_of'), json_extract(meta,'$.revision_seq'))`,Tb="sha256:";function Ds(t){if(t)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}const Ms=["normal","raw-kind-only"];function Ob(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_RECONCILE;if(t===void 0)return"normal";if(Ms.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_RECONCILE="${t}" is not a recognized mode (expected ${Ms.join(", ")}). 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.`)}async function Ib(t,e){return e==="raw-kind-only"?t.graph.queryNodes({kind:"SPEC",liveOnly:!0}):Rc(t.graph)}async function pl(t){var c;const e=await Ib(t,Ob()),n=new Map,i=[];for(const d of e){const u=(c=(await t.graph.getEdges({src:d.id,rel:"part_of"}))[0])==null?void 0:c.dst,[f]=u===void 0?[]:await t.graph.getNodesByIds([u]);if(!f||f.tInvalid){i.push(d.uid);continue}const m=n.get(f.uid)??{parent:f,specs:[]};m.specs.push(d),n.set(f.uid,m)}const o=[],r=[];let s=0;for(const{parent:d,specs:l}of n.values()){const u=await gc(t.graph,d.uid),f=[...l].sort((g,y)=>g.tCreated.localeCompare(y.tCreated));let m="",p=null;f.forEach((g,y)=>{var h,S,E,N,k;const w=y+1;m=`${m}${g.content}`;const v=`${Tb}${He(m)}`,b=!(((h=g.metadata)==null?void 0:h.spec_of)===u.uid&&((S=g.metadata)==null?void 0:S.revision_seq)===w&&((E=g.metadata)==null?void 0:E.revision_token)===v);if(b||(s+=1),o.push({revisionUid:g.uid,specOf:u.uid,revisionSeq:w,prevRevision:p,revisionToken:v,needsStamp:b}),p=g.uid,y===f.length-1){const R=((N=d.metadata)==null?void 0:N.spec_revision)===g.uid&&((k=d.metadata)==null?void 0:k.spec_revision_token)===v;r.push({ticketUid:u.uid,revisionUid:g.uid,revisionToken:v,revisionSeq:w,needsPointer:!R})}})}let a=!1;try{const{rows:d}=await t.adapter.executeAll("PRAGMA index_list('node')");a=d.some(l=>String(l.name)===fl)}catch{a=!1}return{scanned:e.length,stamps:o,heads:r,alreadyStamped:s,orphaned:i,indexCreated:a}}async function $b(t){const e=await pl(t);return await M(t,async n=>{await n.executeRun(jb);const i=P();for(const o of e.stamps){if(!o.needsStamp)continue;const r=await n.executeGet("SELECT meta FROM node WHERE uid = ?",[o.revisionUid]);await $o(n,o.revisionUid,{spec_of:o.specOf,revision_seq:o.revisionSeq,prev_revision:o.prevRevision,revision_token:o.revisionToken,anchor:{locator:"",digest:o.revisionToken},appended_by:"spec-revision.reconcile",appended_at:i},$e(Ds((r==null?void 0:r.meta)??null)))}for(const o of e.heads){if(!o.needsPointer)continue;const r=await n.executeGet("SELECT meta FROM node WHERE uid = ?",[o.ticketUid]);await $o(n,o.ticketUid,{spec_revision:o.revisionUid,spec_revision_token:o.revisionToken,spec_revision_seq:o.revisionSeq},$e(Ds((r==null?void 0:r.meta)??null)))}}),{...e,indexCreated:!0}}function ml(t){switch(t){case"status":return"has_status";case"priority":return"has_priority";case"kind":return"has_kind"}}function gl(t){return new RegExp("\\p{L}","u").test(t)&&t===t.toUpperCase()}function Cb(t){return t===t.toLowerCase()}function hl(t,e){return t==="priority"?gl(e):Cb(e)}function xs(t){if(t===null)return{};try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:{}}catch{return{}}}function Fs(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):[]}async function Bs(t,e){return await t.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ? AND t_invalid IS NULL",[e])??null}async function so(t,e){return await t.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ?",[e])??null}function Pb(t,e,n=[]){const i=[],o=[],r=[["kind",n],["status",t],["priority",e]];for(const[s,a]of r){const c=new Map;for(const d of a){const l=F(d.name??""),u=c.get(l);u?u.push(d):c.set(l,[d])}for(const d of c.values()){if(d.length<2)continue;const l=[...d].sort((p,g)=>p.id-g.id),u=l.find(p=>hl(s,p.name??""));if(u===void 0&&(s==="status"||s==="kind")){o.push({kind:s,names:l.map(p=>p.name??"")});continue}const f=u??l[0],m=l.filter(p=>p.uid!==f.uid).map(p=>p.uid);m.length!==0&&i.push({canonicalUid:f.uid,fragmentUids:m})}}return{groups:i,unmergeable:o,at:P()}}function yl(t,e){if(t!=="status"&&t!=="priority"&&t!=="kind")throw new Error(`applyCaseFragmentMerge: uid ${e} is kind "${t}" — only "status"/"priority"/"kind" catalog rows are mergeable.`)}async function Lb(t,e){return M(t,async n=>{const i=[];for(const o of e.groups){const r=await Bs(n,o.canonicalUid);if(!r)continue;yl(r.kind,r.uid);const s=ml(r.kind),a=await q(n,s),c=F(r.name??""),d=xs(r.meta),l=r.name??"";if((r.kind==="status"||r.kind==="kind")&&!hl(r.kind,l))throw new Error(`applyCaseFragmentMerge: refusing to merge into ${r.kind} uid ${r.uid} named "${l}" — a ${r.kind} canonical must carry the canonical lowercase spelling.`);const u=[];for(const h of o.fragmentUids){const S=await Bs(n,h);if(S&&S.rowid!==r.rowid){if(S.kind!==r.kind)throw new Error(`applyCaseFragmentMerge: refusing to merge uid ${S.uid} (kind "${S.kind}") into uid ${r.uid} (kind "${r.kind}") — kinds must match.`);if(F(S.name??"")!==c)throw new Error(`applyCaseFragmentMerge: refusing to merge "${S.name??""}" into "${r.name??""}" — not a case-variant of the same token (they do not fold together).`);u.push(S)}}if(u.length===0)continue;let f;const m=[];let p=d;if(r.kind==="priority"&&!gl(l)){const h=l.toUpperCase();h!==l&&(await n.executeRun("UPDATE node SET name = ? WHERE rowid = ? AND t_invalid IS NULL",[h,r.rowid]),f={uid:r.uid,from:l,to:h},l.length>0&&m.push(l))}for(const h of u){const S=xs(h.meta),E=typeof S.rank=="number"?S.rank:void 0,{rows:N}=await n.executeAll("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[h.rowid,s]),k=[];for(const A of N){await ie(n,{srcRowid:A.src,dstRowid:h.rowid,rel:s,reason:"catalog-case-fragment-merge",at:e.at});const O=await Q(n,A.src);O&&(await K(n,{at:e.at,srcRowid:A.src,srcUid:O.uid,srcKind:O.kind,dstRowid:r.rowid,dstUid:r.uid,dstKind:r.kind,rel:s,rule:a,typePolicy:t.typePolicy}),k.push({srcRowid:A.src,rel:s,fragmentDstRowid:h.rowid}))}(typeof p.rank=="number"?p.rank:void 0)===void 0&&E!==void 0&&(p={...p,rank:E});for(const A of[h.name??"",...Fs(S.aliases)])A.length>0&&m.push(A);await n.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[e.at,h.rowid]),i.push({fragmentUid:h.uid,canonicalUid:r.uid,fragmentMeta:S,repointedEdges:k,...E!==void 0?{retainedRank:E}:{},...f!==void 0?{renamed:f}:{},canonicalMetaBefore:d})}const g=f?f.to:l,w=[...Fs(p.aliases)];let v=!1;for(const h of m)h!==g&&(w.includes(h)||(w.push(h),v=!0));v&&(p={...p,aliases:w}),(v||p!==d)&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(p),r.rowid])}return{entries:i,at:e.at}})}async function Ub(t,e){await M(t,async n=>{const i=P(),o=new Map;for(const r of e.entries)r.canonicalMetaBefore!==void 0&&!o.has(r.canonicalUid)&&o.set(r.canonicalUid,r.canonicalMetaBefore);for(const r of e.entries){const s=await so(n,r.fragmentUid),a=await so(n,r.canonicalUid);if(!s||!a)continue;yl(s.kind,s.uid);const c=ml(s.kind),d=await q(n,c);for(const l of r.repointedEdges){await ie(n,{srcRowid:l.srcRowid,dstRowid:a.rowid,rel:l.rel,reason:"catalog-case-fragment-merge-reverse",at:i});const u=await Q(n,l.srcRowid);u&&await K(n,{at:i,srcRowid:l.srcRowid,srcUid:u.uid,srcKind:u.kind,dstRowid:s.rowid,dstUid:s.uid,dstKind:s.kind,rel:l.rel,rule:d,typePolicy:t.typePolicy})}await n.executeRun("UPDATE node SET meta = ?, t_invalid = NULL WHERE rowid = ?",[JSON.stringify(r.fragmentMeta??{}),s.rowid])}for(const[r,s]of o){const a=await so(n,r);a&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(s??{}),a.rowid])}for(const r of e.entries)r.renamed&&await n.executeRun("UPDATE node SET name = ? WHERE uid = ?",[r.renamed.from,r.renamed.uid])})}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)===Ct.pathToFileURL(j.realpathSync(process.argv[1])).href){const{namespace:t,argv:e}=Ki(process.argv.slice(2)),n=e[0]==="ir-artifact",i=t==="sandbox"?j.mkdtempSync(_.join(te.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{Jo.initTelemetry({service:"backlog",role:"cli",logSink:"file",...i!==void 0?{logDir:i}:{}})}catch(o){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${o instanceof Error?o.message:String(o)}); telemetry records will be silently dropped this process`)}ul().catch(o=>{console.error(o instanceof Error?o.stack??o.message:String(o)),process.exitCode=1})}const Db=Ci,qi="backlog";function Hi(t,e){return{sourceFile:t,namespace:qi,tsconfig:e,dropFileSegment:!0}}function Mb(t={}){return Zm(t)}function xb(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function Fb(t={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:_v({cache:Mb(t),extractorVersion:Db})}}}}let Ks;function Bb(t={}){return Ks??(Ks=Vu(xb()?[Fb(t)]:[],e=>{var n;return da(Hi(e.source,typeof((n=e.extractorOptions)==null?void 0:n.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0))})),Ks}async function Kb(t){return da(Hi(t))}async function qb(t={}){const e=_.join(ct(),"api.d.ts");return Bb(t)({source:e,host:"ts",namespace:qi,extractorOptions:{}})}const wl=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:qi,buildBacklogExtractOptions:Hi,buildBakedOperations:Kb,extractApiOperationsLive:qb},Symbol.toStringTag,{value:"Module"}));exports.ArtifactDriftError=Ye;exports.BACKLOG_ERROR_CODES=Ti;exports.BACKLOG_EXIT_CODE=Oi;exports.CircuitBreaker=zd;exports.NonAbsolutePathError=qn;exports.RESERVED_TERMINAL_STATUS_NAMES=xt;exports.RagNotConfiguredError=Fc;exports.SEARCH_FLAGS=sl;exports.SEARCH_HELP=al;exports.SERVICE_CONFIG_KEYS=Go;exports.ServiceNotReadyError=Qe;exports.UnknownConfigKeyError=Hd;exports.UnknownMcpConfigKeyError=Vo;exports.addCitation=vd;exports.applyCaseFragmentMerge=Lb;exports.applySpecRevisionReconcile=$b;exports.applyTerminalBackfill=Bp;exports.assertMcpEntryValid=Ui;exports.assertServerArtifact=Wd;exports.assertSurfaceIsReal=Gv;exports.assertValidPredicate=wn;exports.attest=Sd;exports.backlogEnvironmentSpec=Ie;exports.buildBacklogApigenPackage=Di;exports.buildBacklogEnv=et;exports.buildSearchArgv=cl;exports.catalogNameFold=F;exports.claim=jd;exports.closeGraphBacklogStore=ec;exports.create=yd;exports.createBacklogServer=Rn;exports.createLifecycle=Kd;exports.delete=Id;exports.describeBacklogSurface=Qd;exports.embeddingStatus=gd;exports.errorEnvelope=ne;exports.evaluatePredicate=ue;exports.exitCodeForEnvelope=je;exports.fullJitterDelay=Jd;exports.get=dd;exports.installSkill=el;exports.isBacklogErrorCode=Mc;exports.isOutcomeEnvelope=xc;exports.isOutcomeError=iy;exports.isOutcomeOk=oy;exports.isPathResolvableBin=Vd;exports.lookup=hd;exports.mergeProject=Ud;exports.move=Od;exports.obligate=_d;exports.okEnvelope=Ii;exports.openCurve=pd;exports.openGraphBacklogStore=yn;exports.partOfRollup=fd;exports.planCaseFragmentMerge=Pb;exports.planSpecRevisionReconcile=pl;exports.planTerminalBackfill=Fp;exports.prefixCommand=ll;exports.priorityMatrix=ud;exports.probeReadiness=qd;exports.query=ld;exports.readBacklogVersionInfo=Li;exports.recheck=kd;exports.relate=Td;exports.removeCitation=bd;exports.report=md;exports.resolveBacklogDbPath=tt;exports.resolveBacklogScope=Pn;exports.resolveCommandPrefix=dl;exports.resolveExpectedMcpToolNames=Hv;exports.resolveServiceConfig=Gd;exports.reverseCaseFragmentMerge=Ub;exports.reverseTerminalBackfill=Kp;exports.rmLocation=Ld;exports.rmProject=Dd;exports.runBacklogCli=ul;exports.runInstallSkillCommand=nl;exports.runServeCommand=il;exports.specAppend=Nd;exports.specCheck=Rd;exports.startBacklogServer=Jv;exports.stripNamespaceFlag=Ki;exports.suggestClaimantIdentity=Qm;exports.transition=Ed;exports.unobligate=Ad;exports.update=wd;exports.upsertComponent=Cd;exports.upsertLocation=Pd;exports.upsertProject=$d;exports.withResilience=Yd;