@adhd/backlog 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,51 +1,50 @@
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"),tt=require("node:url"),qn=require("@adhd/sox-telemetry"),at=require("pino"),ci=require("ajv"),Ua=require("ajv-formats"),ge=require("@adhd/sox-store-adapter"),Da=require("@adhd/sox-graph-store"),Pt=require("node:fs/promises"),pe=require("node:crypto"),Ma=require("fastify"),xo=require("node:http"),Fa=require("@modelcontextprotocol/sdk/server/index.js"),Ba=require("@modelcontextprotocol/sdk/server/stdio.js"),qa=require("@modelcontextprotocol/sdk/server/sse.js"),Ka=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Uo=require("@modelcontextprotocol/sdk/types.js"),Ha=require("@adhd/sox-hybrid-search"),Kn=require("node:module"),Va=require("yaml");var $=typeof document<"u"?document.currentScript:null;function di(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const un=di(k),we=di(Pt),fn="$apigen";class Do extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Ga(e){const t=new Map;return{register(r,o){if(t.has(r.id)&&!(o!=null&&o.override))throw new Do(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const o of t.values())if(o.matches(r))return o},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),o={register(){throw new Do("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(i){for(const s of r.values())if(s.matches(i))return s},get(i){return r.get(i)},ids(){return[...r.keys()]},freeze(){return o}};return o}}}const je="x-apigen-logical",Hn="x-apigen-codec",pn="x-apigen-ctor",mn="x-apigen-tojson",Wa="0.1.0";function Mo(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 r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ie(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=li(e,i,t,n);return Ie(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return We(e,t,n);const a=t.items;if(!a)return e.map(d=>Ae(d));const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?Ae(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 We(e,t,n);const a=t.properties;if(!a)return Ae(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?We(e,t,n):Ae(e)}function $e(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return $e(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=li(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?gn(e,n):e}function li(e,t,n,r){var c;const o=n.discriminator;if(o!=null&&o.propertyName){const d=o.propertyName,l=e!==null&&typeof e=="object"?e[d]:void 0;if(typeof l=="string"){if(o.mapping){const u=o.mapping[l];if(u){const f=t.find(m=>m.$ref===u);if(f)return f}}for(const u of t){const m=(c=At(u,r).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=Ja(e,t,r);if(i)return i;let s,a=-1;for(const d of t){const l=At(d,r),u=Vn(e,l,r);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:t[0]??{}}function At(e,t){const n=e.$ref;return typeof n=="string"?t.resolve(n):e}function Fo(e){if("const"in e)return e.const;const t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function Ja(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return;const r=e,o=t.map(s=>At(s,n)),i=new Set;for(const s of o){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))Fo(d)!==void 0&&i.add(c)}for(const s of i){const a=o.map(f=>{const m=f.properties,p=m==null?void 0:m[s];return p?Fo(p):void 0}),c=a.filter(f=>f!==void 0),d=new Set(c);if(c.length<2||d.size!==c.length)continue;const l=r[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&Vn(e,o[u],n)!==null)return t[u]}}function za(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 Vn(e,t,n){const r=t.oneOf;if(Array.isArray(r)){let l=null;for(const u of r){const f=Vn(e,At(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=t.type,i=za(e);if(typeof o=="string"){if(!(o===i||o==="number"&&i==="integer"))return null}else if(Array.isArray(o)&&!o.some(u=>u===i||u==="number"&&i==="integer"))return null;if(e===null||typeof e!="object"||Array.isArray(e))return typeof o=="string"?1:0;const s=e,a=t.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(s[l]===void 0)return null;c+=2}}const d=t.properties;if(d){for(const l of Object.keys(d))s[l]!==void 0&&(c+=1);for(const l of Object.keys(s))d[l]===void 0&&(c-=1)}return c}function We(e,t,n){var r;for(const o of n.registry.ids()){const i=n.registry.get(o);if((r=i==null?void 0:i.ownsValue)!=null&&r.call(i,e))return{[fn]:o,v:i.encode(e,i.schema,n)}}if(Array.isArray(e))return e.map(o=>We(o,{},n));if(ui(e)){const o={};for(const[i,s]of Object.entries(e))s!==void 0&&(o[i]=We(s,{},n));return o}return Ae(e)}function ui(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function gn(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&fn in e){const n=e,r=n[fn],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}if(Array.isArray(e))return e.map(n=>gn(n,t));if(ui(e)){const n={};for(const[r,o]of Object.entries(e))n[r]=gn(o,t);return n}return e}function Ae(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Ae);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Ae(r));return t}return null}function Bo(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const u=t[i];if(!u){const f=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${f}`)}r.push(u)}continue}const s=o.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&r.push(u);const a=o.properties;if(a)for(const u of Object.values(a))r.push(u);const c=o.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&r.push(u);else typeof c=="object"&&c!==null&&r.push(c);const d=o.additionalProperties;typeof d=="object"&&d!==null&&r.push(d);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}function Ya(e){return{encode(t,n,r){const o=Mo(e,r);return Ie(t,n,o)},decode(t,n,r){const o=Mo(e,r);return $e(t,n,o)}}}const Gn={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)}},Wn={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 Jn={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}},zn={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"))}},Xa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Yn={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"&&!Xa.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},hn="NaN",yn="Infinity",wn="-Infinity",Qa=new Set([hn,yn,wn]),Xn={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)?hn:e===1/0?yn:e===-1/0?wn:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===hn)return NaN;if(e===yn)return 1/0;if(e===wn)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Qa].join(", ")}.`);return NaN}},Za=[Gn,Wn,Jn,zn,Yn,Xn];function ec(e,t={}){for(const n of Za)e.register(n,{override:t.override??!1})}const tc=12;function nc(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,i=r==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(o)]}function qo(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function oc(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 rc(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 Ko(e,t,n){const r=e.properties??{},o=e.required??[],i={};for(const s of o){const a=r[s];i[s]=a!==void 0?Ue(a,t,n+1):`<${s}>`}return i}function ic(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Ue(r,t,n+1)]:[]}function Ue(e,t=e??{},n=0){if(!e||n>tc)return null;if(typeof e.$ref=="string"){const i=nc(e.$ref,t);return i!==void 0?Ue(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 Ko({...e,properties:i,required:s},t,n)}const r=qo(e.oneOf)??qo(e.anyOf);if(r)return Ue(r,t,n+1);switch(oc(e)){case"object":return Ko(e,t,n);case"array":return ic(e,t,n);case"string":return rc(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function fi(e){if(!e)return;const t=Ue(e);return`Example: ${JSON.stringify(t)}`}Gn.id,Wn.id,Jn.id,zn.id,Yn.id,Xn.id;const pi=Ga();ec(pi);const mi=Ya(pi.freeze());function gi(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function vn(e){var n,r;const t=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data;return Object.keys((t==null?void 0:t.properties)??{})}function sc(e,t){var o,i,s;const n=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,r=n==null?void 0:n[t];return r!==void 0?r:void 0}function ac(e,t){return t===void 0||e===void 0?e:mi.decode(e,t)}function Zt(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:mi.encode(e,n)}async function cc(e,t,n,r,o,i){const a=vn(n).map(d=>ac(i[d],sc(n,d)));if(gi(n,"session")&&t){const d=await t({session:o.session}),l=await e[r](d,...a);return Zt(l,n)}if(n.hasCtx){const d=t?await t(o):void 0,l=await e[r](d,...a);return Zt(l,n)}const c=await e[r](...a);return Zt(c,n)}class nt{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 dc(e=[]){return async function(n,r,o){const i=o.schemas[n];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>cc(o.fns,o.createClient,i,n,r.envelope,r.domainArgs);return e.reduceRight((c,d)=>()=>d(r,c),s)()}}function Ho(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function hi(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(d=>d.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...i]=r,s=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Ho(s),path:i.map(Ho),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=Kn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);let ct;function yi(){return ct||(ct=ue("ts-morph").Project,ct)}const wi=Symbol.for("adhd.apigen.extraction-session");function Qn(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}Qn(r,t)}}}function vi(e){try{const t=R.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const St=new Map,Vo=new Map;function lc(e,t,n){const r=t??"",o=St.get(r);let i=n;if(o&&o.fileVersions.size>0){const c=[n],d=[...o.fileVersions.entries()].sort(([l],[u])=>l.localeCompare(u));for(const[l,u]of d)l!==e&&c.push(`${l}:${u}`);i=c.join("|")}const s=`${e}\0${t??""}`;let a=Vo.get(s);return(a==null?void 0:a.version)!==i&&(a={version:i,schemas:new Map},Vo.set(s,a)),a.schemas}let en;function uc(){if(!en){const e=yi();en=new e({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return en}function bi(e){const t=uc(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return Qn(r,o),[...o].sort()}function fc(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[wi]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(o){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const i=o??"",s=o?this.statVersion(o):"";let a=St.get(i);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=yi();a={project:o?new c({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},St.set(i,a),e.projectsBuilt++}return a.project},sourceFileFor(o,i){const s=this.projectFor(i),a=St.get(i??""),c=this.statVersion(o);let d=s.getSourceFile(o);if(d===void 0?d=s.addSourceFileAtPath(o):a&&a.fileVersions.get(o)!==c&&d.refreshFromFileSystemSync(),a==null||a.fileVersions.set(o,c),a){const l=new Set([o]);Qn(d,l);for(const u of l)u!==o&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(o){let i=t.get(o);return i===void 0&&(i=vi(o),t.set(o,i)),i},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function pc(e){const t=e;if(t[wi]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Go=new Set(["string","number","boolean","integer"]);function mc(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"?Go.has(n):Array.isArray(n)?n.every(r=>Go.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Si(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(mc)}function gc(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const i=r[o];if(i)for(const[s,a]of Object.entries(i)){const c=s.startsWith("#/")?s:`#/${o}/${s}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{Bo(o.input,t),Bo(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`)}}function hc(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function yc(e,t,n){gc(e);const r={};for(const[o,i]of Object.entries(e.schemas)){const s={},a=i.input.properties??{},c=i.input.required??[],d={},l=[],u={};for(const 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||Si(i.input),p=i.input.definitions,g=i.input.$defs;r[o]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:hc(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 r}const wc=8;function vc(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let bc=0;async function Sc(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${bc++}`;let i;try{i=t.addTypeAlias({name:o,type:n});const s=i.getType();return await r(s)}catch{return}finally{try{i==null||i.remove()}catch{}}}async function Ei(e,t,n){if(n>wc)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean",const:e.getText()==="true"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.getUnionTypes(),o=r.filter(p=>p.isBooleanLiteral()),i=o.some(p=>p.getText()==="true"),s=o.some(p=>p.getText()==="false");let a=!1;const c=r.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(r.every(p=>p.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(p=>p.getLiteralValue())};if(r.every(p=>p.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?i&&s?{type:"boolean"}:{type:"boolean",const:i}:Ei(p,t,n+1))),f=Lt(u);return{oneOf:_c(Ac(u)),...f?{discriminator:f}:{},[je]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(i=>t(i.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),i=r??o,s=e.getProperties();if(i&&s.length===0)return{type:"object",additionalProperties:await t(i.getText())};const a={},c=[];for(const d of s){const l=d.getName(),f=d.getDeclarations()[0];let 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?vc(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 Ec(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 kc=new Set(["required","enum","type"]);function bn(e,t){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e)){const o=e.map(i=>bn(i));return t!==void 0&&kc.has(t)&&o.sort(),`[${o.join(",")}]`}const n=e;return`{${Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>`${JSON.stringify(o)}:${bn(n[o],o)}`).join(",")}}`}function Ac(e){const t=new Set,n=[];for(const r of e){const o=bn(r);t.has(o)||(t.add(o),n.push(r))}return n}function _c(e){if(e.length<2)return e.slice();const t=e.map(Ec),n=e.map((o,i)=>t[i]?i:-1).filter(o=>o>=0);if(n.length===0||n.length===e.length)return e.slice();const r=e.map((o,i)=>t[i]?-1:i).filter(o=>o>=0);return e.map((o,i)=>{if(!t[i])return o;const s=e.filter((a,c)=>c!==i&&(r.includes(c)||t[c]&&c<i));return{allOf:[o,{not:{anyOf:s}}]}})}function Lt(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let i=!0;for(const a of t){const c=a[r],d=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!d||!Array.isArray(l)||l.length!==1){i=!1;break}o.push(String(l[0]))}if(!i||new Set(o).size!==o.length)continue;const s={};return o.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:s}}}function Et(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=Sn[r];if(o!==void 0)return o;if(n!=null&&n.size){const i=n.get(r);if(i!==void 0){const s=Sn[i];if(s!==void 0)return s}}if(r.endsWith("[]"))return{type:"array",items:Et(r.slice(0,-2),t+1,n)};if(r.includes("|")){const i=r.split("|").map(c=>c.trim());if(i.every(c=>c.startsWith("'")))return{type:"string",enum:i.map(c=>c.replace(/'/g,""))};const s=i.map(c=>Et(c,t+1,n)),a=Lt(s);return{oneOf:s,...a?{discriminator:a}:{},[je]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const i=r.slice(1,-1).trim(),s={};for(const a of i.split(";").filter(Boolean)){const[c,d]=a.split(":").map(l=>l.trim());c&&d&&(s[c.replace("?","")]=Et(d,t+1,n))}return{type:"object",properties:s}}return{}}function ki(e){const t=[];let n=0,r=0;for(let i=0;i<e.length;i++){const s=e[i];s==="<"||s==="["||s==="{"||s==="("?n++:s===">"||s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function jc(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function Nc(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function Rc(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 ki(n)}async function Oc(e,t){const n=e.trim(),r=jc(n);if(r!==void 0){const s=ki(r);if(s.length===2){const[a,c]=await Promise.all([t(s[0]),t(s[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=Nc(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const i=Rc(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 Ai={"decimal.js":"Decimal"},Sn={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"}},Wo={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Jo(e){var n;const t=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),i=Ai[o];if(!i)continue;const s=r.getDefaultImport();if(s){const a=s.getText();a!==i&&t.set(a,i)}for(const a of r.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==i&&t.set(c,i)}}return t}function Tc(e,t){return n=>{n.addNodeParser({supportsNode(r){var i,s,a;if(r.kind!==t)return!1;const o=((i=r.typeName)==null?void 0:i.escapedText)??((a=(s=r.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return o!==void 0&&Object.prototype.hasOwnProperty.call(Wo,o)},createType(r){var a,c,d;const o=((a=r.typeName)==null?void 0:a.escapedText)??((d=(c=r.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:i,StringType:s}=En();return new i(new s,{format:Wo[o]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){const{AnnotatedType:r,StringType:o}=En();return new r(new o,{format:"int64"},!1)}})}}let dt;function En(){return dt||(dt=ue("ts-json-schema-generator"),dt)}let Ke;function Ic(){if(Ke)return Ke;try{const e=k.dirname(ue.resolve("ts-json-schema-generator/package.json"));Ke=ue(ue.resolve("typescript",{paths:[e]}))}catch{Ke=ue("typescript")}return Ke}const he=new Map;function $c(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function Cc(e){const t=he.get(e);return t&&(he.delete(e),he.set(e,t)),t}function Pc(e,t){const n=$c();if(n!==0)for(he.delete(e),he.set(e,t);he.size>n;){const r=he.keys().next().value;he.delete(r)}}function Lc(e,t){return`${e}\0${t??""}`}const xc=new Set(["zod",/^zod\/./]);function Uc(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of xc)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function Dc(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(i=>/zod/i.test(i)));for(const[i,s]of Object.entries(n)){if(o.has(i)||typeof s!="object"||s===null)continue;const a=s,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const d of o)if(c.includes(d)){o.add(i);break}}}for(const i of o)delete n[i]}kn(e)}function kn(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&kn(o,n);else kn(r,n)}}function Mc(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const i of Object.keys(o))t.add(i)}const n=An(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 An(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const i=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);i&&!t.has(i[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const i of o)typeof i=="object"&&i!==null&&n.push(...An(i,t));else n.push(...An(o,t));return n}function Fc(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=Lt(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[je]:o[je]??"union"}}function Bc(e,t,n){const{DEFAULT_CONFIG:r}=ue("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},i=o.path,s=Lc(i,o.tsconfig);let a;a=n?n.statVersion(i):vi(i);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??Cc(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}=En(),p=Ic(),g=Tc(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),b=l(o),h=u(b,o,g),y=f(o);if(c=new m(b,h,y,o),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const w={version:a,gen:c};Pc(s,w),n==null||n.generatorCache.set(s,w)}}const d=c.createSchema(o.type);return Dc(d),Mc(d),d}function qc(e,t){let n=e.trim();if(n=ji(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function _i(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Kc=Object.entries(Ai).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${_i(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ji(e){let t=e;for(const{pattern:n,key:r}of Kc)t=t.replace(n,r);return t}function Hc(e,t){let n=ji(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${_i(r)}\\b`,"g"),o);return n}async function ze(e,t,n,r,o,i){const s=t.getFilePath(),a=`${s}\0${r??""}\0${n}`,c=i??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),zo(e,t,n,r,void 0,p)}const d=o.schemaCache.get(a);if(d!==void 0)return o.stats.schemaCacheHits++,d;const l=lc(s,r,o.statVersion(s)),u=l.get(n);if(u!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(u)),u;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const m=zo(e,t,n,r,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,m),m}async function zo(e,t,n,r,o,i){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(o){const f=o.aliasCache.get(t);s=f??Jo(t),f||o.aliasCache.set(t,s)}else s=Jo(t);const a=qc(n,s),c=Sn[a];if(c!==void 0)return c;const d=await Oc(a,f=>ze(e,t,f,r,o,i));if(d!==void 0)return d;const l=(o==null?void 0:o.zodImportCache.get(t))??Uc(t);if(o&&o.zodImportCache.set(t,l),!l)try{const f={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},m=Bc(f,!0,o);return Fc(m)}catch{}try{const f=await Sc(e,t,a,m=>Ei(m,p=>ze(e,t,p,r,o,i),0));if(f!==void 0)return f}catch{}const u=Hc(a,s);return Et(u,0,s)}function Zn(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return Vc(n,t)}function Vc(e,t){var s;const n=e,r=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${o}\\s*=\\s*([^\\]]+)\\]`);for(const a of r)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(i);if(d)return d[1].trim()}}function Gc(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 Wc(e,t){const n=Gc(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}let lt;function Jc(){return lt||(lt=ue("ts-morph").SyntaxKind,lt)}function xt(e){try{if(!e)return;const t=Jc();if(e.getKind()!==t.TypeReference)return;const n=e;if(n.getTypeArguments().length>0)return;const r=n.getTypeName();if(r.getKind()!==t.Identifier)return;const i=r.getSymbol();if(!i)return;const s=i.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const a=s,c=a.getType();if(!(c.isString()||c.isNumber()||c.isBoolean()))return;const l=a.getJsDocs();for(const u of l)for(const f of u.getTags())if(f.getTagName()==="format"){const m=f.getCommentText();if(m!==void 0)return m.trim()}return}catch{return}}const zc=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function Yc(e){const t=[];let n=0,r="";for(const o of e)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(t.push(r.trim()),r=""):r+=o;return r.trim().length>0&&t.push(r.trim()),t}function Xc(e){const t=e.trim(),n=t.indexOf("<");if(n===-1||!t.endsWith(">"))return null;const r=t.slice(0,n),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!zc.has(o))return null;let i=0;for(let c=n;c<t.length;c++){const d=t[c];if(d==="<")i++;else if(d===">"&&(i--,i===0&&c!==t.length-1))return null}if(i!==0)return null;const s=t.slice(n+1,-1),a=Yc(s);return a.length>0?a[0]:null}async function Ni(e){const t=e.session===void 0,n=pc(e.session??fc());try{return await Qc(e,n)}finally{t&&n.dispose()}}async function Qc(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:i}=e,s=t.projectFor(i),a=t.sourceFileFor(n,i),c=k.basename(n),d=le(ed(c)),l=o?null:d,u=le(r),f=[];for(const[g,b]of a.getExportedDeclarations()){if(g==="default"||ft(g))continue;const h=nd(b);if(h){const S=h.getSignature(),E=Qo(S,h),A=S.getReturnType().getText(),_=Se(S);f.push(await ut(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],_=Zo(A,y,y.getVariableStatement()),N=A.getReturnType().getText(),j=Se(A),O=w.isAsync();f.push(await ut(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(ft(A))continue;const N=E.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const j=N[0],O=Zo(j,y,y.getVariableStatement()),I=j.getReturnType().getText(),C=Se(j),K=[...l?[l]:[],le(g),le(A)];f.push(await kt(s,a,u,K,A,O,I,!1,i,t,C))}}else{const S=y.getType(),E=S.getText();if(ke(S,y)){const A=await ze(s,a,E,i,t);f.push(Zc(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=tn(v,g),E=v.getReturnType().getText(),A=Se(v),_=b.isAsync();f.push(await ut(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(ft(v))continue;const E=w.getTypeAtLocation(g).getCallSignatures();if(E.length===0)continue;const A=E[0],_=tn(A,g),N=A.getReturnType().getText(),j=Se(A),O=[...l?[l]:[],le("default"),le(v)];f.push(await kt(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=Qo(S,y),A=S.getReturnType().getText(),_=Se(S);f.push(await ut(s,a,u,l,v,E,A,y.isAsync(),i,t,_))}}}const p=td(a);if(p.length>0)for(const{name:g,sig:b}of p){if(ft(g))continue;const h=tn(b),y=b.getReturnType().getText(),w=Se(b),v=[...l?[l]:[],le(g)];f.push(await kt(s,a,u,v,g,h,y,!1,i,t,w))}return f}function Yo(e,t,n,r){const o=new Set,i=s=>{if(Array.isArray(s))return s.map(i);if(!s||typeof s!="object"||o.has(s))return s;o.add(s);try{const a=s,c={};for(const[d,l]of Object.entries(a)){if(d==="definitions"||d==="$defs"){const u=d,f=t[u];for(const[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 "${r}" 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{o.delete(s)}};return i(e)}function Xo(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 Se(e){var t;try{return xt((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function ut(e,t,n,r,o,i,s,a,c,d,l){const u=le(o);return kt(e,t,n,r?[r,u]:[u],o,i,s,a,c,d,l)}async function kt(e,t,n,r,o,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 ze(e,t,j.type,c,d),I=Yo(O,g,o,j.name);j.defaultValue!==void 0&&Wc(I,j.defaultValue),Xo(I,j.format),p[j.name]=I}const b=s.replace(/^Promise<(.+)>$/,"$1").trim(),h=Xc(b),y=h!==null,w=y?h:b,v=await ze(e,t,w,c,d),S={definitions:{},$defs:{}},E=Yo(v,S,o,"<return>"),A=l?{...E}:E;Xo(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:Ri(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:y,safe:!1,input:_,output:A,envelope:{},typeText:{lang:"ts",input:od(i),output:w},...u?{hasCtx:!0}:{}}}function Zc(e,t,n,r){const o=le(n),i=t?[t,o]:[o];return{id:Ri(e,i),host:"ts",namespace:e,path:i,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function Ri(e,t){return(e.raw?[e,...t]:t).map(r=>r.words.join("-")).join("/")}function Ye(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:Ye(e)}}function ed(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function td(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),a=s.getType();for(const c of a.getProperties()){const l=c.getTypeAtLocation(s).getCallSignatures();l.length!==0&&t.push({name:c.getName(),sig:l[0]})}}return t}function nd(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function Qo(e,t){return e.getParameters().map(n=>{var s;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:Zn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function Zo(e,t,n){return e.getParameters().map(r=>{var a;const o=r.getDeclarations(),i=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,s=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((a=i==null?void 0:i.hasQuestionToken)==null?void 0:a.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:s,defaultValue:Zn(i,r.getName(),n??t),format:xt(i==null?void 0:i.getTypeNode())}})}function tn(e,t){return e.getParameters().map(n=>{var s,a,c;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:o?o.getType().getText():((c=(a=n.getValueDeclaration())==null?void 0:a.getType())==null?void 0:c.getText())??"unknown",optional:i,defaultValue:Zn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function od(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function ft(e){return!!(e==="__samples__"||e.startsWith("__"))}function ke(e,t,n=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const r=e.getArrayElementType();return r?ke(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>ke(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>ke(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>ke(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),i=e.getNumberIndexType();if(o||i)return[o,i].every(a=>!a||ke(a,t,n));const s=e.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(t);return ke(c,t,n)})}return!1}function rd(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const i=e[o],s=r;r=()=>i(n,s)}return r()}}function id(e,t){return rd(e,t)}function sd(e,t,n={}){const r=e.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return id(r,t)}function ad(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 cd(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:ad(e.output)}}function dd(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const i=r.get(o.kind);i?i.push(o):r.set(o.kind,[o])}return r}function er(e){return{type:"string",enum:[e]}}function tr(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 nr(e,t){const n={},r={},o=[["definitions",n],["$defs",r]];for(const i of e){const s=t(i);for(const[a,c]of o){const d=s[a];if(d)for(const[l,u]of Object.entries(d)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(u))throw new Error(`[apigen-core-client] _batch mount: operation "${i.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=u}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(r).length>0?{$defs:r}:{}}}function ld(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(cd),n=nr(e,s=>s.input),r=nr(e,s=>s.output);if(e.length===1){const[s]=e,[a]=t;return{input:{...tr(a,er(s.id)),...n},output:{type:"array",items:a.resultSchema,...r}}}const o=e.map((s,a)=>tr(t[a],er(s.id))),i=Lt(o);return{input:{oneOf:o,...i?{discriminator:i}:{},...n},output:{oneOf:t.map(s=>({type:"array",items:s.resultSchema})),...r},...i?{discriminator:i}:{}}}function ud(e,t={}){const n=dd(e.operations,t),r=[];for(const[o,i]of n){const{input:s,output:a}=ld(i),c=hi(`_batch/${o}`,e,{kind:o,safe:o==="query",input:s,output:a});r.push({...c,operationIds:i.map(d=>d.id)})}return r}function eo(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},at(i);const s=n?at.destination({dest:e.destination,mkdir:!0,sync:!0}):at.destination(2);return at(i,s)}function fd(e){if((e==null?void 0:e.type)!=="object"||!e.properties)return;const t=Object.entries(e.properties);if(t.length===0)return;const n=new Set(e.required??[]);return`{ ${t.map(([o,i])=>`${o}${n.has(o)?"":"?"}: ${Ut(i)}`).join(", ")} }`}function pd(e){return typeof e=="string"?`'${e}'`:JSON.stringify(e)}function md(e){const t=e.enum??[];return t.length===0?"unknown":t.map(pd).join("|")}function gd(e,t){return e.map(n=>Ut(n,t)).join(" | ")}function Ut(e,t=0){if(!e)return"unknown";if(e.type==="array")return`${Ut(e.items,0)}[]`;if(e.enum)return md(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?gd(n,t-1):"union":t>=1&&e.type==="object"?fd(e)??"object":e.type??"object"}function Oi(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),i=Object.entries(r).map(([c,d])=>({name:c,type:Ut(d,2),required:o.has(c)})),s=i.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:i,text:s}}function hd(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function yd(e,t){var i,s;const r=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,c]of Object.entries(r)){const d=o[a];if(typeof d!="string")continue;const l=hd(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 wd=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],vd={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},or={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class M extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function ae(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&wd.includes(e.code)&&typeof e.toJSON=="function"}function rr(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Dt=new ci({allErrors:!0});Ua(Dt);for(const e of[je,Hn,pn,mn,"discriminator"])Dt.addKeyword({keyword:e,valid:!0});Dt.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function bd(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Sd(e,t){const n=fi(t),r=[`Validation failed: ${bd(e)}`];return n&&r.push(n),r.join(" — ")}function Ed(e){return async function(n,r){const o=n.operation.id,i=e[o];if(i===void 0)return r();const s={data:n.domainArgs,...n.envelope},a=Dt.compile(i.input);if(!a(s)){const d=a.errors??[];throw new M("invalid_argument",Sd(d,i.input),d)}return r()}}async function Ti(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=ae(n)?n:new M("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:rr("before-first-chunk",r)}:{ok:!1,carrier:rr("after-first-chunk",r,t.length)}}}function Mt(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class Ee extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function nn(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Ii(e,t){const n=e[Hn];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function kd(e,t,n){const r=Ii(t,n);return r?r.encode(e,t,n):e}function Ad(e,t,n){const r=Ii(t,n);return r?r.decode(e,t,n):e}function _d(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[je]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:nn(r)!==void 0},encode(r,o,i){const s=nn(o);if(!s)throw new Ee("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=s,d=r[a];if(d==null)throw new Ee("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 Ee("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 kd(r,f,{...i,path:`${i.path}[${l}]`})},decode(r,o,i){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Ee("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=r,a=nn(o);if(!a)throw new Ee("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 Ee("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 Ee("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 Ad(r,m,{...i,path:`${i.path}[${u}]`})}}}const jd="x-apigen-instances";class pt extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function ir(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Nd(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function sr(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function Rd(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Od(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[je]==="nominal"?!0:o[Hn]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new pt("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=ir(i),c=typeof i[mn]=="string"?i[mn]:"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[b,h]of Object.entries(p))g[b]=sr(h,a[b],{...s,path:`${s.path}/${b}`});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]=sr(g,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new pt("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=o;for(const l of Nd(i))if(!(l in a))throw new pt("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${s.path}".`);if(i[jd]===!1)throw new pt("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=ir(i),d={};for(const[l,u]of Object.entries(a))d[l]=Rd(u,c[l],{...s,path:`${s.path}/${l}`});if(r){const l=typeof i[pn]=="string"?i[pn]:"fromJSON",u=r[l];if(typeof u=="function")return u.call(r,d);const f=r;return new f(d)}return d}}}const Td=[Gn,Wn,Jn,zn,Yn,Xn],Id={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ar=Od({id:"ts.NominalSentinel",schema:Id}),$d={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},cr=_d({id:"ts.UnionSentinel",schema:$d});function Cd(){const e=[...Td.map(t=>[t.id,t]),[ar.id,ar],[cr.id,cr]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Wa,codecs:Cd()});function _n(e,t,n){var s;const r=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,o=fi(t==null?void 0:t.input),i=[n,r,o].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function $i(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 Pd(e,t){if(e)return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Ld=4,xd=32;function jn(e){return ae(e)?e:e instanceof Error?new M("internal",e.message):e}function Ud(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Ld;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),xd)}function Dd(){}function Md(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Dd};const n=new AbortController,r=()=>{n.abort(e==null?void 0:e.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener("abort",r,{once:!0}));let o;return t!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:n.signal,dispose(){e&&e.removeEventListener("abort",r),o&&clearTimeout(o)}}}async function dr(e,t,n,r,o,i){const s=Md(r.signal,i);try{const a=s.signal?{...r,signal:s.signal}:r,c=await e(t,a,o);if(Mt(c)){const d=await Ti(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:jn(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:jn(a)}}finally{s.dispose()}}async function Fd(e,t,n,r,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=Ud(i,o.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:jn(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 dr(e,t,g,n[g],r,o.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 dr(e,t,p,n[p],r,o.itemTimeoutMs);c[p]=g,g.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(m),c}function lr(e){return e.words.join("-")}function ur(e){return e.words.map(Kd).join("")}function fr(e){return e.words.join("_")}function Bd(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Ne(e,t={}){var f,m;const n=[e.namespace,...e.path],r=e.safe||Si(e.input)?"GET":"POST",o=((m=(f=t.http)==null?void 0:f.verb)==null?void 0:m[e.id])??r,i="/"+n.map(p=>lr(p)).join("/"),s=n.map(p=>fr(p)).join("_"),c=n.map(p=>fr(p)).slice(0,-1).join("."),d=ur(n[n.length-2]??n[0]),l=ur(n[n.length-1]),u=n.map(p=>lr(p));return{http:{verb:o,route:i},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function Ci(e,t){return`x-${e}-${t}`}function Pi(e,t){return`--${e}-${t}`}function Li(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function _t(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}function qd(e){const t=new Set,n=[];for(const r of e){const o=_t(r);let i=o,s=2;for(;t.has(i);)i=`${o}_${s}`,s+=1;t.add(i),n.push(i)}return n}function Kd(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function xi(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function de(e){return xi(JSON.stringify(e))}function Hd(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 to(e){return e.anyOf??e.oneOf}function Vd(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=to(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Gd(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=to(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Wd(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=to(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function Jd(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function zd(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function pr(e){return typeof e.handler=="function"}function Yd(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd",a=Ci(s,i);r.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:Pi(s,i),envVar:Li(s,i)})}return r}function Xd(e,t,n,r){t===n||e.has(t)||e.set(t,{...r,aliasOf:n})}function Qd(e,t){const n=new Map,{props:r}=zd(e);for(const[o,i]of Object.entries(r)){let s="string";Gd(i)?s="boolean":(Vd(i)||Wd(i))&&(s="json");const a=Jd(o),c={camelKey:o,kind:"domain",valueKind:s};n.set(a,c),Xd(n,o,a,c)}for(const o of t){const i=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(i,s)}return n}function ve(e){const{op:t,schema:n,transport:r,projection:o}=e,i=Ne(t,o),s=n?Yd(n):[],a=n?Qd(n,s):new Map,c=n?Oi(n).params:void 0,d={op:t,transport:r,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:c,envelope:s,cliFlags:a,streaming:t.streaming,isMount:pr(t)};if(pr(t)){const l=t.handler;d.mountHandler=async u=>l(u)}return d}function no(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Zd(e){const t=e.exitCode;return typeof t=="function"?t:void 0}function oo(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function el(e){return async function(n,r){const o=Object.assign(n,{data:n.domainArgs});return await e.layer(o,r)}}function fe(e,t){var r;const n=[];for(const o of t){const i=(r=o.capabilities)==null?void 0:r.layer;i&&n.push(el(i))}return n.push(Ed(e)),dc(n)}function tl(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const nl={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function De(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new nt};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:tl(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:nl}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}function Ui(e){return e.anyOf??e.oneOf}function ol(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r.push({field:i,pluginId:s,flag:Pi(s,i),envVar:Li(s,i)})}return r}function Nn(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ui(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function rl(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ui(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function mr(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function il(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function sl(e){const n=ro(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function on(e){var i,s;const t=(s=(i=e.input)==null?void 0:i.properties)==null?void 0:s.data;if(!t)return;const n=t.oneOf,r=t.discriminator;if(!n||!r)return;const o=[];for(const[a,c]of Object.entries(r.mapping)){const d=il(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:sl(a),props:u,required:f})}if(o.length!==0)return{discriminatorProperty:r.propertyName,branches:o}}function ro(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function al(e,t){if(!un.isAbsolute(t))return t;const n=un.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const cl=["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 Di(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Mi(e,t,n,r){var o;for(const i of t){const s=ro(i),a=rl(n[i]),c=r.includes(i);a?(e.push(` .option('--${s}')`),((o=n[i])==null?void 0:o.default)===!0&&e.push(` .option('--no-${s}')`)):c?e.push(` .requiredOption('--${s} <${s}>')`):e.push(` .option('--${s} <${s}>')`)}}function Fi(e,t,n){return`${e}:${t}::${n}`}function Bi(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([m,p])=>`'${m}': ${p}`),f=a.map(m=>Nn(c[m])?`'${m}': __apigenParseJsonArg('${ro(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, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function dl(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,rootUnion:a}=t,c=_t(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const d of a.branches){const l=Object.keys(d.props).filter(f=>f!==a.discriminatorProperty),u=d.required.filter(f=>f!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${d.commandName}')`),Di(e,i,s),Mi(e,l,d.props,u),Bi(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Fi(r,o,d.commandName),bindings:i,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function ll(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(s=>Object.values(s.schemas).some(a=>{const c=on(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>Nn(l.props[u])));const{props:d}=mr(a);return vn(a).some(l=>Nn(d[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const s of e.packages){const a=_t(s.id),c=al(e.outputDir,s.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(cl),o.push(""));const i=Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,c])));for(const s of e.packages)for(const[a,c]of Object.entries(s.schemas)){const d=on(c);if(d)for(const l of d.branches){const u=Fi(s.id,a,l.commandName);i[u]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(i,null,2)}`),o.push(""),o.push(`const program = new Command().name('${t}').version('${n}')`),o.push("");for(const s of e.packages){const a=_t(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=gi(d,"session"),u=ol(d),f=on(d);if(f){dl(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const m=vn(d),{props:p,required:g}=mr(d);o.push("program"),o.push(` .command('${c}')`),Di(o,u,l),Mi(o,m,p,g),Bi(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 ul(e){return{props:e.properties??{},required:e.required??[]}}function fl(e){const t=e??{},r=Array.isArray(t.oneOf)&&t.oneOf.length>0?t.oneOf:[t],o={},i=new Map;for(const a of r){const{props:c,required:d}=ul(a);for(const[l,u]of Object.entries(c))l in o||(o[l]=u);for(const l of d)i.set(l,(i.get(l)??0)+1)}const s=[...i.entries()].filter(([,a])=>a===r.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:o,required:s}},required:["data"]},output:{}}}function pl(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function ml(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?pl(t):process.argv.slice(2)}function gl(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 hl(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,i]of Object.entries(r.schemas)){const s=t.get(`${r.id}:${o}`)??gl(o,i),a=ve({op:s,schema:i,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:i,cliPath:c,plan:a})}return n}function yl(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function qi(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function gr(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const i=qi(o.params);t.push(` ${r}${i?` { ${i} }`:""}`)}return t.join(`
5
- `)}function mt(e){return new M("invalid_argument",e)}function wl(e,t){var i;const n={},r={};let o=0;for(;o<e.length;){const s=e[o];if(!s.startsWith("--"))throw mt(`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 mt(`Unknown option: --${a}. Available: ${[...t.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:e[o++];if(p===void 0)throw mt(`Missing value for --${a}`);if(f.valueKind==="json")try{m=JSON.parse(p)}catch(g){throw mt(`Invalid JSON for --${a}: ${g.message}`)}else m=p}f.kind==="domain"?n[f.camelKey]=m:r[f.camelKey]=m}for(const s of t.values()){if(s.kind!=="envelope"||!s.envVar||r[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(r[s.camelKey]=a)}return{domainArgs:n,envelope:r}}function Ki(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)?or[e.code]:or.internal}function vl(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 bl{constructor(t,n){this.signal=t,this.exitCodeHook=n,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=wl(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){var i;if(Mt(n))throw new M("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const o=(i=this.exitCodeHook)==null?void 0:i.call(this,n);typeof o=="number"&&o!==0&&(process.exitCode=o)}writeError(t,n,r){Ki(n)}}function Sl(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("cli")||i.push(u)}return i}async function El(e){var E,A,_;const t=e.logger??eo();if((E=e.signal)!=null&&E.aborted){t.info("cli run: signal already aborted before dispatch — skipping");return}let n=ml(e.options);n[0]==="--"&&(n=n.slice(1));const r=no(e.options),o=oo(e.options),i=new bl(e.signal,Zd(e.options)),s=hl(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 K=fe(I,r),D={fns:C,createClient:N.createClient,schemas:I};for(const P of j)i.registerRoute(P.plan,X=>De(P.plan,K,X,D))}const l=((A=e.packages[0])==null?void 0:A.id)??"ts",u=fe(c,r),f={invoke:(N,j,O)=>u(N,{operation:{id:N},ctx:new nt,domainArgs:j.domainArgs,envelope:j.envelope,signal:j.signal},O),invokeOptions:{fns:d,schemas:c,createClient:(_=e.packages[0])==null?void 0:_.createClient}},m=Sl(r,o,l,e.operations??[],f);if(m.length>0){const N=fe({},r),j={fns:{},schemas:{}};for(const O of m){const I=ve({op:O,schema:fl(O.input),transport:"cli"});i.registerRoute(I,C=>De(I,N,C,j))}}const p=i.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(gr(p));return}const g=yl(n,p);if(!g){Ki(new M("not_found",`Unknown command: ${n.join(" ")}
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(" ")}
6
6
 
7
- ${gr(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=qi(y.params);console.log(`${v}${N?` { ${N} }`:""}`);return}const S={rest:h};try{if(y.streaming)throw new M("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){vl(t,v,N),await i.writeError(S,N,y)}}const kl={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 ll(e)},run(e){return El(e)}};function Al(e,t){const n=e.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const r=n,o=r.operation;if(typeof o!="string"||o.length===0)throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!t.includes(o))throw new M("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${t.join(", ")}`);const i=r.items;if(!Array.isArray(i))throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=r.concurrency;if(s!==void 0&&typeof s!="number")throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=r.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=r.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=r.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new M("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:i,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function _l(e,t){return async n=>{if(!t)throw new M("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=Al(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},i=r.items.map(s=>({operation:{id:r.operation},ctx:new nt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return Fd(t.invoke,r.operation,i,t.invokeOptions,o)}}function jl(e,t={},n){return ud(e,t).map(o=>({...o,handler:_l(o.operationIds,n)}))}const jt={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(e,t,n){return jl(e,t,n)}}}},hr={validateKind(){},validateRel(){},validateEdge(){}},Nl=5,Rl=20,Ol=500;function Tl(e){return ge.isBusyError(e)||ge.isConcurrentConflict(e)}function Il(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function $l(e,t={}){const n=t.maxAttempts??Nl;for(let r=0;;r++)try{return await e()}catch(o){if(!Tl(o)||r>=n-1)throw o;const i=Math.min(Ol,Rl*2**r);await Il(i*(.5+Math.random()*.5))}}const io=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class Hi extends Error{constructor(t,n){const r=t.length>0?t.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
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.
8
8
  expected node kind(s): ${n.join(", ")}
9
- found in store: ${r}
9
+ found in store: ${o}
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 Vi(e){const{rows:t}=await e.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=t.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,i)=>o+i.count,0),observed:n}}async function Cl(e){const t=[...io],n=t.map(()=>"?").join(", "),{rows:r}=await e.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,t);return r.length>0}async function so(e){if(await Cl(e))return;const{total:t,observed:n}=await Vi(e);if(t!==0)throw new Hi(n,[...io])}function Rn(){return[]}function Pl(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 Ll(e,t){if(e===t)return!0;const n=k.relative(e,t);return n!==".."&&!n.startsWith(`..${k.sep}`)&&!k.isAbsolute(n)}function ao(e){const t=e==null?void 0:e.code;return t==="ENOENT"||t==="ENOTDIR"}async function On(e){const t=k.resolve(e);try{return await Pt.realpath(t)}catch(n){if(!ao(n))throw n;const r=k.dirname(t);if(r===t)throw n;return k.join(await On(r),k.basename(t))}}async function Gi(e,t,n){const r=k.isAbsolute(t)?k.resolve(t):k.resolve(e,t),o=await On(r);return{accepted:(await Promise.all([e,...n].map(a=>On(a)))).some(a=>Ll(a,o)),candidate:o}}class q extends Error{constructor(t,n=void 0,r){super(t),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class Wi extends q{constructor(t,n){super(`Write contention: exhausted the retry budget (last backoff ${t}ms)`,n,t),this.code="E_CONTENTION",this.retryable=!0}}class Ji extends q{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 xl="backlog.write.io_failure";function Tn(e,t,n){const r=zi(e);qn.log.error(xl,{origin:t,retryable:n,error:r.message,...r.code!==void 0?{error_code:r.code}:{},...r.stack!==void 0?{stack:r.stack}:{}})}class Ft extends q{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 q{constructor(t,n){super(`${t} "${n}" was not found`),this.catalogKind=t,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class Ul extends q{constructor(t,n,r){super(`${t} "${r}" 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=r,this.code="E_VALIDATION",this.retryable=!1}}class T extends q{constructor(t,n){super(n?`Invalid argument "${t}": ${n}`:`Invalid argument "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}class Bt extends q{constructor(t){super(`No live issue found for uid "${t}"`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Nt extends q{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 Yi extends q{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 In extends q{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 co extends q{constructor(t,n){const r=n.length===0?"the project root":n.map(Pl).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots";super(`Citation target "${t}" could not be verified and this project requires a real sha — accepted only under: ${r} (${o})`),this.target=t,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class Dl extends q{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 Xi(e,t){return(e==null?void 0:e.code)==="EISDIR"?new Dl(t):(Tn(e,"citation_sha",!0),new Ji(e))}class Qi extends q{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 Zi extends q{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 Re extends q{constructor(t,n){super(n?`Invalid "${t}": ${n}`:`Invalid "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}function Ml(e){const t=e instanceof Error?e.message:String(e);return ge.isBusyError(e)||ge.isConcurrentConflict(e)?{code:"E_CONTENTION",retryable:!0,message:t,cause:e}:ge.isUniqueConstraintError(e)||ge.isForeignKeyError(e)?{code:"E_CONSTRAINT",retryable:!1,message:t,cause:e}:ge.isDatabaseError(e)?(Tn(e,"transaction",!0),{code:"E_IO",retryable:!0,message:t,cause:e}):(Tn(e,"transaction",!1),{code:"E_IO",retryable:!1,message:t,cause:e})}const Fl=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function Z(e,t){if(Fl.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`)}function es(e){if(e!=null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}function ts(e){return{rowid:e.rowid,uid:e.uid,kind:e.kind,name:e.name,content:e.content??"",metadata:es(e.meta),tInvalid:e.t_invalid,isSuperseded:e.is_superseded===1}}function U(){return new Date().toISOString()}function lo(e){return pe.createHash("sha256").update(e).digest("hex")}function ns(e){return JSON.stringify($n(e))}function $n(e){if(Array.isArray(e))return e.map($n);if(e!==null&&typeof e=="object"){const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=$n(t[r]));return n}return e}async function qt(e,t){const n=await e.executeGet("SELECT * FROM node WHERE uid = ?",[t]);return n?ts(n):null}async function be(e,t){const n=await qt(e,t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid!==null)throw new Bt(t);if(n.isSuperseded)throw new Ft(t);return n}async function ee(e,t){const n=await e.executeGet("SELECT * FROM node WHERE rowid = ?",[t]);return n?ts(n):null}const Bl=["off","on"];function ql(){const e=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(e===void 0)return"off";if(Bl.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??U(),r=t.content??t.name??"",o=lo(r.trim().toLowerCase());if(ql()==="on"){const c=await e.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const i=pe.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=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,
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,r,t.name??null,null,null,null,1,null,o,"global",s,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${t.kind}" name="${t.name??""}"`);return{rowid:a.rowid,uid:i}}async function Kl(e,t){const{multiplicity:n}=t.rule;if(n==="n:m")return;if(n==="n:1"){const o=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
16
- WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[t.srcRowid,t.rel,t.dstRowid]);if(o)throw new In({side:"source",cappedUid:t.srcUid,rel:t.rel,conflictingUid:o.uid});return}const r=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
17
- WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[t.dstRowid,t.rel,t.srcRowid]);if(r)throw new In({side:"target",cappedUid:t.dstUid,rel:t.rel,conflictingUid:r.uid})}async function L(e,t){const{rule:n}=t;if(n.sourceKind!=="*"&&n.sourceKind!==t.srcKind)throw new yr(t.rel,"source",n.sourceKind,t.srcKind);if(n.targetKind!==t.dstKind)throw new yr(t.rel,"target",n.targetKind,t.dstKind);await Kl(e,t),t.typePolicy.validateEdge?t.typePolicy.validateEdge(t.srcKind,t.rel,t.dstKind):t.typePolicy.validateRel(t.rel);const r=t.at??U(),o=t.metadata!==void 0?JSON.stringify(t.metadata):null;await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
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)
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,o,r,r])}class yr extends q{constructor(t,n,r,o){super(`"${t}" requires a ${n} of kind "${r}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function me(e,t){const n=await e.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t.srcRowid,t.dstRowid,t.rel]);if(!n)return;const r=t.at??U(),o={...es(n.meta)??{},invalidatedAt:r,...t.reason!==void 0?{invalidatedReason:t.reason}:{}};await e.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(o),n.rowid])}const gt=[250,500];function Hl(e){return new Promise(t=>setTimeout(t,e))}const Vl=["immediate","deferred"];function Gl(){const e=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(e===void 0)return"immediate";if(Vl.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:Gl()})}catch(r){if(r instanceof q)throw r;const o=Ml(r);if(o.code==="E_CONTENTION"){if(n<gt.length){const i=gt[n];n+=1,await Hl(i);continue}throw new Wi(gt[gt.length-1],r)}throw o.code==="E_IO"&&o.retryable?new Ji(r):r}}function Y(e){return e.normalize("NFKC").toLowerCase()}function Wl(){return new Set([...Kt].map(e=>Y(e)))}function uo(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}async function Jl(e,t=U()){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"),r=[],o=Wl();for(const i of n){const s=Y(i.name??"");if(!o.has(s))continue;const a=uo(i.meta);(a==null?void 0:a.terminal)!==!0&&r.push(i.rowid)}return{setTerminalRowids:r,at:t}}async function zl(e,t){return V(e,async n=>{const r=[];for(const o of t.setTerminalRowids){const i=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[o]);if(!i)continue;if(i.kind!=="status")throw new Error(`applyTerminalBackfill: planned rowid ${o} is not a status row (kind="${i.kind}") — plan/DB mismatch, refusing to rewrite it.`);const s=uo(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),o]);if(d.rowsAffected!==1)throw new Error(`applyTerminalBackfill: UPDATE affected ${d.rowsAffected} rows for rowid=${o}, expected exactly 1.`);r.push({rowid:i.rowid,uid:i.uid,hadTerminal:a})}return{entries:r,at:U()}})}async function Yl(e,t){await V(e,async n=>{for(const r of t.entries){const o=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[r.rowid]);if(!o)continue;if(o.kind!=="status")throw new Error(`reverseTerminalBackfill: journal rowid ${r.rowid} is not a status row (kind="${o.kind}") — refusing to rewrite it.`);const s={...uo(o.meta)??{},terminal:r.hadTerminal},a=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(s),r.rowid]);if(a.rowsAffected!==1)throw new Error(`reverseTerminalBackfill: UPDATE affected ${a.rowsAffected} rows for rowid=${r.rowid}, expected exactly 1.`)}})}async function F(e){const t=e.at??U(),n={actor:e.actor,action:e.action,target_uid:e.subjectUid,from:e.from??null,to:e.to??null,note:e.note??null,at:t},r=lo(ns(n)),o={...n,sha:r},i=await J(e.tx,{at:t,kind:"audit",name:e.action,content:e.note??e.action,metadata:o}),s=await x(e.tx,"audits");return await L(e.tx,{at:t,srcRowid:e.subjectRowid,srcUid:e.subjectUid,srcKind:e.subjectKind,dstRowid:i.rowid,dstUid:i.uid,dstKind:"audit",rel:"audits",rule:s,typePolicy:e.typePolicy}),{rowid:i.rowid,uid:i.uid,sha:r}}function fo(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}const Xl=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Oe(e){return Xl.test(e)}async function ot(e,t,n){const r=await qt(e,n);if((r==null?void 0:r.tInvalid)!==null||r.kind!==t)throw new W(t,n);const{name:o}=r;if(o===null)throw new W(t,n);return{...r,name:o}}async function Xe(e,t){if(Oe(t)){const o=await ot(e,"project",t);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[t]);if(!n)throw new W("project",t);let r;if(n.meta!==null)try{r=JSON.parse(n.meta)}catch{r=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??t,metadata:r}}async function po(e,t){var r;if(Oe(t.ref)){const o=await ot(e,"component",t.ref);if(((r=o.metadata)==null?void 0:r.projectUid)!==t.projectUid)throw new W("component",t.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await e.executeGet(`SELECT rowid, uid, name FROM node
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
22
22
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
23
23
  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 os(e,t){const n=await e.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
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
25
  FROM edge e JOIN node c ON c.rowid = e.dst
26
26
  WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
27
27
  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 Kt=new Set(["closed","DONE","FIXED","RESOLVED","INVALID","SUPERSEDED"]),Ql=new Set([...Kt].map(e=>Y(e)));function Zl(e){return Ql.has(Y(e))}async function eu(e,t,n){const r=Y(n),{rows:o}=await e.executeAll("SELECT uid, name FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[t]);for(const i of o)if(!(i.name===null||i.name===n)&&Y(i.name)===r)return{uid:i.uid,name:i.name}}async function _e(e,t){if(Oe(t.ref)){const s=await ot(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 r=await eu(e,t.catalogKind,t.ref);if(r)throw new Ul(t.catalogKind,r.name,t.ref);const o=t.mintMetadata?await t.mintMetadata(e):{},i=await J(e,{kind:t.catalogKind,name:t.ref,metadata:o,at:t.at});return{rowid:i.rowid,uid:i.uid,name:t.ref}}async function rs(e,t){return _e(e,{catalogKind:"status",ref:t.ref,at:t.at,mintMetadata:async()=>({terminal:Zl(t.ref)})})}async function is(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 tu=[{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"}],wr=new Map(tu.map(e=>[e.rel,e]));async function x(e,t){const n=await e.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[t]);if(n){const o=fo(n.meta)??{},i=typeof o.source_kind=="string"?o.source_kind:void 0,s=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(i&&s&&a)return{rel:t,sourceKind:i,targetKind:s,multiplicity:a};const c=wr.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",[U(),n.rowid]),await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const r=wr.get(t);if(!r)throw new W("edge_kind",t);return await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:r.sourceKind,target_kind:r.targetKind,multiplicity:r.multiplicity}}),r}const 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 Me(e){var r;const t=(r=e.metadata)==null?void 0:r.policy;if(t===null||typeof t!="object")return{...ne,citationAllowedExternalRoots:Rn()};const n=t;return{transitionRequiresNote:n.transitionRequiresNote??ne.transitionRequiresNote,citationRequired:n.citationRequired??ne.citationRequired,citationRequiresSha:n.citationRequiresSha??ne.citationRequiresSha,citationAllowedExternalRoots:nu(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 nu(e){const t=e.citationAllowedExternalRoots;return t===void 0||!Array.isArray(t)||!t.every(n=>typeof n=="string")?Rn():t}function Ht(e){var n;const t=(n=e.metadata)==null?void 0:n.path;return typeof t=="string"&&t.length>0}function Rt(e,t){const n={...e};for(const[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}async function ou(e,t){return se("name",t.name),se("by",t.by),Z("by",t.by),V(e,n=>ru(n,e,t))}async function ru(e,t,n){const r=U(),o=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),i={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=Rt(fo(o.meta)??{},i);return await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await F({tx:e,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:r}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const s=Rt({},i),a=await J(e,{kind:"project",name:n.name,metadata:s,at:r}),c=await J(e,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:r}),d=await x(e,"owns_project");return await L(e,{at:r,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:d,typePolicy:t.typePolicy}),await F({tx:e,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:r}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function iu(e,t){return se("project",t.project),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 r=U(),o=await Xe(e,n.project),i=await e.executeGet(`SELECT rowid, uid, name, meta FROM node
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
29
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
30
30
  AND json_extract(meta, '$.projectUid') = ?
31
- LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(i)u=Rt({...fo(i.meta)??{},projectUid:o.uid},s),await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(u),i.rowid]),a=i.rowid,c=i.uid,d=i.name??n.name,l=!1;else{u=Rt({projectUid:o.uid},s);const m=await J(e,{kind:"component",name:n.name,metadata:u,at:r});a=m.rowid,c=m.uid,d=n.name,l=!0}const f=await x(e,"owns_project");return await L(e,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:t.typePolicy}),await F({tx:e,typePolicy:t.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:r}),{uid:c,created:l,component:{uid:c,name:d,projectUid:o.uid,path:u.path,description:u.description}}}const vr=["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),!vr.includes(t.locType))throw new T("locType",`must be one of ${vr.join(", ")}`);return V(e,async n=>{const r=U();let o;if(Oe(t.component)){const d=await ot(n,"component",t.component);o={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(t.project===void 0||t.project.trim().length===0)throw new T("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await Xe(n,t.project);o=await po(n,{projectUid:d.uid,ref:t.component})}const i=await n.executeGet(`SELECT rowid, uid FROM node
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
32
  WHERE kind = 'location' AND t_invalid IS NULL
33
33
  AND json_extract(meta, '$.componentUid') = ?
34
34
  AND json_extract(meta, '$.locType') = ?
35
35
  AND json_extract(meta, '$.value') = ?
36
- LIMIT 1`,[o.uid,t.locType,t.value]);if(i)return{uid:i.uid,created:!1,location:{uid:i.uid,locType:t.locType,value:t.value,componentUid:o.uid}};const s={componentUid:o.uid,locType:t.locType,value:t.value},a=await J(n,{kind:"location",name:t.value,metadata:s,at:r}),c=await x(n,"has_location");return await L(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:e.typePolicy}),await F({tx:n,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:t.by,action:"created",at:r}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:t.locType,value:t.value,componentUid:o.uid}}})}async function cu(e,t){return se("uid",t.uid),se("by",t.by),Z("by",t.by),V(e,async n=>{var c;const r=U(),o=await ot(n,"location",t.uid),i={...o.metadata??{},...t.reason!==void 0?{invalidatedReason:t.reason}:{},invalidatedAt:r},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[r,JSON.stringify(i),o.rowid]);if(s.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${s.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const d=await qt(n,a);(d==null?void 0:d.tInvalid)===null&&await me(n,{srcRowid:d.rowid,dstRowid:o.rowid,rel:"has_location",reason:t.reason,at:r})}return await F({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:t.by,action:"deleted",note:t.reason,at:r}),{uid:o.uid,invalidated:!0}})}const br=["status","priority"],du="run the terminal-flag repair — `write/catalog-repair.ts`'s `planTerminalBackfill` + `applyTerminalBackfill` — which sets `metadata.terminal = true` on each named status row.",lu="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 uu(e){const t=e.filter(o=>o.kind==="unflagged-terminal"),n=e.filter(o=>o.kind==="case-fragment-duplicate"),r=["backlog: status/priority catalog invariant violated — refusing to read or write this store (ADR-0002: correct the source, never work around it)."];if(r.push(" Every row below must be repaired before this store can be served; neither condition may be papered over with a read-time fallback."),t.length>0){r.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 o of t)r.push(` - status "${o.name}" (uid ${o.uid})`);r.push(` remediation: ${du}`)}if(n.length>0){r.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 i=o.names.map((s,a)=>`"${s}" (uid ${o.uids[a]})`).join(", ");r.push(` - fold "${o.fold}": ${i}`)}r.push(` remediation: ${lu}`)}return r.join(`
37
- `)}class fu extends Error{constructor(t){super(uu(t)),this.violations=t,this.name="CatalogInvariantError"}}const pu=new Set([...Kt].map(e=>Y(e)));function mu(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}async function gu(e){var r;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",[...br]),n=[];for(const o of t){if(o.kind!=="status")continue;const i=Y(o.name??"");pu.has(i)&&((r=mu(o.meta))==null?void 0:r.terminal)!==!0&&n.push({kind:"unflagged-terminal",name:o.name??"",uid:o.uid})}for(const o of br){const i=new Map;for(const s of t){if(s.kind!==o)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 mo(e){const t=await gu(e);if(t.length!==0)throw new fu(t)}const hu=3e4,Sr=new WeakMap;function yu(e){let t=Sr.get(e);return t||(t=new Set,Sr.set(e,t)),t}function ss(e){const t=yu(e);return{register(n){t.add(n);let r=!1;return()=>{r||(r=!0,t.delete(n))}},get size(){return t.size},snapshot(){return[...t]},async drain(n){const r=(n==null?void 0:n.timeoutMs)??hu,o=Date.now()+r;let i=0;for(;;){const a=[...t].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const d=await wu(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 wu(e,t){let n;const r=new Promise(o=>{n=setTimeout(()=>o("timeout"),t),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([e,r])}finally{n!==void 0&&clearTimeout(n)}}const vu="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function go(e,t){return`${e}
38
- ${t}`.trim()}function Ot(e,t){const n=e.embedding;if(!n)return Promise.resolve();const r=bu(e,n,t),o={subjectRowid:t.subjectRowid,subjectUid:t.subjectUid,actor:t.actor,action:t.action,settled:r,outcome:"pending"},i=ss(e.adapter).register(o);return r.then(s=>{o.outcome=s,s!=="unrecorded"&&i()},()=>{o.outcome="unrecorded"}),r.then(()=>{})}async function bu(e,t,n){let r,o;try{if(n.action==="upsert"){const i=await t.embedDocument(n.content);await t.upsertVector(n.subjectRowid,i),r="embedding_upserted"}else await t.deleteVector(n.subjectRowid),r="embedding_deleted"}catch(i){r="embedding_failed",o=i instanceof Error?i.message:String(i),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,i)}try{await V(e,async i=>{await F({tx:i,typePolicy:e.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:r,note:o})})}catch(i){return console.error(`scheduleIssueEmbedding: failed to persist "${r}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,i),"unrecorded"}switch(r){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function Su(e,t){const n=[],r=[];for(const o of t)try{await V(e,async i=>{await F({tx:i,typePolicy:e.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:vu})}),o.outcome="failed",n.push(o)}catch(i){o.outcome="unrecorded",r.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,i)}return{recorded:n,unrecorded:r}}async function Tt(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 ge.createStoreAdapter({dbPath:e});await n.pragmaSet("busy_timeout",t);const r=Da.createGraphBackend(n,{typePolicy:hr});await $l(()=>r.applySchema());try{await so(n),await mo(n)}catch(i){throw await n.close().catch(()=>{}),i}return{adapter:n,graph:r,typePolicy:hr,flushEmbeds:i=>ss(n).drain(i)}}async function as(e,t){const n=await e.flushEmbeds(t);let r=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const i=await Su(e,n.stillPending);r=i.recorded.length,o=[...o,...i.unrecorded]}}finally{await e.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:r,unrecorded:o}}async function Cn(e){if(!e)return;let t;try{t=await as(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 Pn=["SIGINT","SIGTERM"];function cs(e,t=n=>process.exit(n)){let n=!1;const r=i=>{n||(n=!0,e().catch(s=>{console.error(`backlog: signal cleanup failed (${i}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{o(),t(128+z.constants.signals[i])}))},o=()=>{for(const i of Pn)process.removeListener(i,r)};for(const i of Pn)process.on(i,r);return{dispose:o}}function Eu(){return Pn.some(e=>process.listenerCount(e)>0)}const ku=[".git",".adhd","adhd.environment.yaml"];function rn(e){let t=k.resolve(e);const{root:n}=k.parse(t);for(;;){for(const o of ku)if(R.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=k.dirname(t);if(r===t)return;t=r}}const Au=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:rn(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&Au.has(r)){const i=r;return i==="project"?{scope:"project",projectRoot:rn(n)??n}:{scope:i}}const o=rn(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Er(e){return`.${e}`}function ju(e){const t=z.homedir();if(process.platform==="darwin")return k.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??k.join(t,"AppData","Roaming");return k.join(r,e)}const n=process.env.XDG_DATA_HOME??k.join(t,".local","share");return k.join(n,e)}function Nu(e){const t=e.orgNamespace,n=e.adhdRoot??k.join(z.homedir(),Er(t)),r=e.adhdRoot??ju(t),o={system:k.join(r,e.project,e.namespace),global:k.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=k.join(e.projectRoot,Er(t),e.project,e.namespace)),o}function ds(e,t){return t==="project"?e.project??e.global:e[t]}const Ru="1.0.0-redesign.1",Ou="adhd",Tu="default",Iu="adhd-environment.json",Ce="config.yaml",ls="config.local.yaml",$u={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class kr 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 Ar(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function us(e,t){const n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i++){const s=n[i].codePointAt(0)??0,a=r[i].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function _r(e){return new TextEncoder().encode(e).length}function Cu(e){const t=Object.keys(e).sort(us);let n="";for(const o of t){const i=e[o];if(Ar(o))throw new kr("key",o);if(Ar(i))throw new kr("value",i);n+=`${_r(o)}:${o}=${_r(i)}:${i}
39
- `}return`sha256-${fs(n)}`}function Pu(e){const n=[...e].sort((r,o)=>us(r.name,o.name)).map(r=>`${r.name}:${r.kind}:${r.scope}`).join(`
40
- `);return`sha256-${fs(n)}`}function Lu(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function xu(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Uu(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],i=r.split(".");let s=t;i.forEach((a,c)=>{if(c===i.length-1){s.properties[a]=Du(o);return}const l=s.properties[a];if(l===void 0){const u={type:"object",properties:{}};s.properties[a]=u,s=u}else s=l})}return t}function Du(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const Mu="adhd-env-ref:";function Fu(e){return`${Mu}${e}`}const Bu=[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],qu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function oe(e,t){return(e>>>t|e<<32-t)>>>0}function Ku(e){const t=Uint32Array.from(qu),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const i=Math.floor(n/4294967296),s=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,i,!1),a.setUint32(r-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let 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+Bu[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 Hu(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function fs(e){const t=new TextEncoder().encode(e);return Hu(Ku(t))}const{parse:Vu}=Va;function ps(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const i=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,ps(o,i)):n[i]=o}return n}function ht(e){if(R.existsSync(e))try{const t=R.readFileSync(e,"utf8"),n=Vu(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:ps(n)}catch{return}}function Gu(e){return{system:ht(k.join(e.system,Ce)),global:ht(k.join(e.global,Ce)),project:e.project?ht(k.join(e.project,Ce)):void 0,local:e.project?ht(k.join(e.project,ls)):void 0}}function jr(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function Ln(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 ms(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((i,s)=>{if(s===r.length-1){o[i]=e[n];return}const a=o[i];(typeof a!="object"||a===null||Array.isArray(a))&&(o[i]={}),o=o[i]})}return t}const Wu=[["system","system"],["global","global"],["project","project"],["local","local"]];function Ju(e,t,n,r){const o={},i={},s={},a={};for(const c of Object.keys(e)){const d=e[c],l=d.env&&d.env!==""?d.env:xu(r.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??r.activeScope;let m=d.default,p="default";for(const[w,v]of Wu){const S=t[w];S&&Object.prototype.hasOwnProperty.call(S,c)&&(m=Ln(S[c],d.type),p=v)}const g=n[l];let b,h,y;g!==void 0?(b=Ln(g,d.type),h="env",y=l):(b=m,h=p),o[c]=u?Fu(l):b,i[c]=b,s[c]=jr(u?{source:"env",scope:f,env:l}:{source:h,scope:f,env:y}),a[c]={...d,env:l,live:u,fallbackValue:m}}return{raw:o,nested:ms(o),typedRaw:i,provenance:s,fields:a}}function zu(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 Yu(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=o.scope??t.activeScope,s=o.share??$u[o.kind],a=o.path?zu(o.path,t):k.join(ds(t.roots,i),r),c=s==="per-instance"?k.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:i,share:s}}return n}function Xu(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=t[o.in];if(!i)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:k.join(i.path,o.name),share:o.share??"shared"}}return n}class gs 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 Qu(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const i=new ci({allErrors:!0,strict:!1}).compile(n);if(!i(e))throw new gs(Zu(i.errors??[]))}function Zu(e){return e.map(t=>({field:ef(t),message:t.message??"is invalid",keyword:t.keyword}))}function ef(e){var r;const t=(e.instancePath??"").replace(/^\//,"").replace(/\//g,".");return t||(((r=e.params)==null?void 0:r.missingProperty)??"(root)")}function tf(e,t){return k.join(ds(e,t),Iu)}const nf=384,of=448;function rf(e,t,n={}){const r=n.mode??nf,o=n.dirMode??of,i=k.dirname(e);R.mkdirSync(i,{recursive:!0,mode:o}),R.chmodSync(i,o);const s=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{R.writeFileSync(s,a,{encoding:"utf8",mode:r}),R.chmodSync(s,r),R.renameSync(s,e),R.chmodSync(e,r)}catch(c){try{R.existsSync(s)&&R.unlinkSync(s)}catch{}throw c}}const sf="0.1.0";function Nr(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 af(){return`${process.pid}-${pe.randomBytes(3).toString("hex")}`}function ho(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Nr(e,"project");const r=t.orgNamespace??Ou,o=t.envPrefixOverride??Lu(e),i=t.namespaces&&t.namespaces.length>0?t.namespaces:[Tu],s=n.namespace??i[0];if(!i.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${e}" (declared: ${i.join(", ")})`);Nr(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=_u({scope:n.scope,cwd:n.cwd},a),l=Nu({project:e,namespace:s,orgNamespace:r,projectRoot:d,adhdRoot:n.adhdRoot});return{project:e,namespace:s,orgNamespace:r,envPrefix:o,scope:c,projectRoot:d,roots:l}}function cf(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:i,scope:s,projectRoot:a,roots:c}=ho(e,t,n),d=n.processEnv??process.env,l=Gu(c),u=n.instanceId??af(),{raw:f,nested:m,typedRaw:p,provenance:g,fields:b}=Ju(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=Uu(t.config);Qu(ms(p),y);const w=Yu(t.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:r}),v=Xu(t.files,w);return{version:Ru,libraryVersion:sf,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:i,scope:s,instanceId:u,config:m,raw:f,liveFields:h,fieldSchema:y,configHash:Cu(Object.fromEntries(Object.entries(p).map(([E,A])=>[E,String(A)]))),structureHash:Pu(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 Qe extends Error{constructor(t){super(t),this.name="EnvironmentError"}}class df extends Qe{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class lf extends Qe{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function uf(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function xn(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>xn(n));const t={};for(const[n,r]of Object.entries(e))t[n]=xn(r);return t}function ff(e,t){const n=xn(e);for(const r of Object.keys(t)){const o=t[r],i=r.split(".");let s=n;for(let c=0;c<i.length-1;c++){const d=i[c],l=s[d];(typeof l!="object"||l===null||Array.isArray(l))&&(s[d]={}),s=s[d]}const a=i[i.length-1];Object.defineProperty(s,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?Ln(c,o.type):o.fallback}})}return n}function pf(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Qe(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class Vt{constructor(t,n,r={}){let o,i;try{o=cf(t,n,r);const s=ho(t,n,r);i=tf(s.roots,o.scope)}catch(s){throw s instanceof gs||s instanceof Qe?s:new Qe(s instanceof Error?s.message:String(s))}return Rr(this,o,i)}static fromSnapshot(t){if(!R.existsSync(t))throw new df(t);const n=JSON.parse(R.readFileSync(t,"utf8")),r=Object.create(Vt.prototype);return Rr(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return uf(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){pf(t);const n=this.paths.run??this._runDirFallback();R.mkdirSync(n,{recursive:!0});const r=k.join(n,`${t}.lock`);let o;try{o=R.openSync(r,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new lf(t,r):s}R.writeSync(o,`${process.pid}
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}
41
40
  ${this.instanceId}
42
- `),R.closeSync(o);let i=!1;return()=>{if(!i){i=!0;try{R.unlinkSync(r)}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 rf(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Rr(e,t,n){const r={};for(const s of t.dirs)r[s.name]=s.path;const o={};for(const s of t.files)o[s.name]=s.path;const i=ff(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:i,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(s,a,c){return typeof a=="string"&&!(a in s)?s.get(a):Reflect.get(s,a,c)}})}const Fe={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 yo(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 Pe(e={}){const t={namespace:e.namespace??"production",scope:yo(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 Vt("backlog",Fe,t)}function Je(e){return e.config.db.path??e.files.db}function mf(e,t){return`${e}:${t}`}function gf(e={}){const t=process.env.APIGEN_IR_CACHE_FILE;if(t)return t;const n={namespace:"production",scope:"global"};e.adhdRoot!==void 0&&(n.adhdRoot=e.adhdRoot),e.instanceId!==void 0&&(n.instanceId=e.instanceId);const r=new Vt("backlog",Fe,n);return k.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function Or(e){return{raw:e,words:Ye(e)}}function hs(e,t,n,r){for(const o of r??[]){const i=o.path[o.path.length-1];if(o.namespace.raw===e&&(i==null?void 0:i.raw)===t)return o}return{id:`${Ye(e).join("-")}/${Ye(t).join("-")}`,host:"ts",namespace:Or(e),path:[Or(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function hf(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r={};for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r[i]=Ci(s,i)}return r}function yf(e){const t=Hd(e.options.port),n=e.options.routePrefix??"",r=e.options.projection??{},o=qd(e.packages.map(s=>s.id)),i=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const[s,a]of e.packages.entries()){const c=o[s];i.push(`import * as ${c}_ns from ${de(a.importPath)}`),i.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}i.push(""),i.push(`const schemas: Record<string, unknown> = ${xi(JSON.stringify(Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,{schema:c,pkgId:s.id}]))),null,2))}`),i.push(""),i.push("const app = Fastify()"),i.push("");for(const[s,a]of e.packages.entries()){const c=o[s];for(const[d,l]of Object.entries(a.schemas)){const u=hs(a.id,d,l,e.operations),f=ve({op:u,schema:l,transport:"http",projection:r}),m=n+f.http.route,p=f.http.verb,g=hf(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(`
43
- `)}]}}function wf(e){return`data: ${e}
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}
44
43
 
45
- `}function vf(e){return`event: error
44
+ `}function jf(e){return`event: error
46
45
  data: ${e}
47
46
 
48
- `}async function bf(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let i=!1;try{for await(const s of e){if(r.signal.aborted)break;i||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),i=!0),o.write(wf(JSON.stringify(s)))}i||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(s){const a=ae(s)?s:new M("internal",s instanceof Error?s.message:String(s));if(i)o.write(vf(JSON.stringify(a.toJSON()))),o.end();else{const c=Ef(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const Sf={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function Ef(e){return Sf[e]??500}function ys(e){return ae(e)?vd[e.code]??500:500}function ws(e){return ae(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function kf(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}class Af{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(i,s)=>{const a={req:i,reply:s};try{const c=await this.readCall(a,t),d=await n(c);await this.writeResult(a,d,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,i={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(i[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};s=a?yd(c,a):c}else{const{data:c={}}=r.body??{};s=c}}return{envelope:i,domainArgs:s,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:i}=t;if(Mt(n)){await bf(n,o,i);return}i.type("application/json"),i.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(ys(n)).send(ws(n))}}function _f(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("http")||i.push(u)}return i}async function jf(e){var h,y;const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",r=e.options.routePrefix??"",o=e.options.projection??{},i=no(e.options),s=oo(e.options),a=e.logger??eo(),c=Ma({logger:a});c.setErrorHandler((w,v,S)=>{S.status(ys(w)).send(ws(w))});const d=new Af(c,r,e.signal),l=[],u={},f={};for(const w of e.packages){if(!w.fns)throw new Error(`Package "${w.id}" is missing fns`);const v=w.fns,S=Object.entries(w.schemas).map(([j,O])=>({fnName:j,fnSchema:O,op:hs(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=ve({op:O,schema:j,transport:"http",projection:o});d.bindSchema(O.id,j),d.registerRoute(I,D=>De(I,_,D,N));const{params:C,text:K}=Oi(j);l.push({method:I.http.verb,route:r+I.http.route,text:K,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 nt,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=ve({op:S,transport:"http",projection:o});d.registerRoute(E,A=>De(E,w,A,v)),l.push({method:E.http.verb,route:`${r}/${S.id}`,text:"",params:[]})}}return await c.listen({port:t,host:n}),a.info({host:n,port:t},`listening on http://${n}:${t}`),kf(a,l),new Promise(w=>{e.signal&&e.signal.addEventListener("abort",async()=>{await c.close(),w()})})}const Nf={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 yf(e)},run(e){return jf(e)}};function Rf(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const i of e){const s=Ne(i),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:i.id,summary:i.id,responses:{200:Of(i.output)}};if(a==="GET")l.parameters=Tf(i.input);else{const u=i.input;typeof u=="object"&&u!==null&&Object.keys(u).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:u}}})}o[c]===void 0&&(o[c]={}),o[c][d]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Of(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function Tf(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function If(e,t={}){return[{...hi("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>Rf(e.operations,{title:t.title,version:t.version})}]}const $f={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 If(e,t)}}}};function Cf(){return`// Auto-generated by @adhd/apigen-cli — do not edit
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
49
48
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
50
49
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
51
50
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
@@ -119,7 +118,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
119
118
 
120
119
  const transport = new StdioServerTransport()
121
120
  server.connect(transport)
122
- `}function Pf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
121
+ `}function Bf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
123
122
  import { createServer } from 'node:http'
124
123
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
125
124
  ${e==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
@@ -195,31 +194,32 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
195
194
  const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
196
195
  const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
197
196
  httpServer.listen(${t}, () => console.error('MCP ${e} server on port ${t}'))
198
- `}function Un(e){return{raw:e,words:Ye(e)}}function Lf(e){return Un(Bd(un.basename(e)))}function vs(e,t,n){if(n){const o=n.find(i=>{var s;return i.kind==="action"&&i.namespace.raw===e.id&&((s=i.path[i.path.length-1])==null?void 0:s.raw)===t});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=Un(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Un(e.id),path:e.dropFileSegment?[r]:[Lf(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function xf(e,t,n){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of e)r.push(`import * as ${o.id}_ns from '${o.importPath}'`),r.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of e)for(const[i,s]of Object.entries(o.schemas)){const a=vs({id:o.id,importPath:o.importPath},i,n),d=ve({op:a,schema:s,transport:"mcp"}).mcp.name,l=_n(d,s,t[d]??t[i]);r.push(` ${JSON.stringify(d)}: { group: '${o.id}', fnName: ${JSON.stringify(i)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of e)r.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);r.push("}"),r.push(""),r.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of e)r.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
199
- `)}function Uf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.toolDescriptions??{},o=e.operations,i=xf(e.packages,r,o),s=t==="stdio"?Cf():Pf(t,n);return{files:[{path:"index.ts",content:i},{path:"server.ts",content:s}]}}async function Df(e){const t=await Ti(e);if(t.ok){const o=t.chunks.map(i=>({type:"text",text:JSON.stringify(i)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}const Mf=Object.freeze({type:"object",properties:{}});class Ff{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.cachedList=void 0,this.toolMeta.set(t,n)}registerRoute(t,n){this.cachedList=void 0,this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){if(this.cachedList)return this.cachedList;const t=[...this.plans.keys()].map(n=>{const r=this.toolMeta.get(n);return Object.freeze({name:n,description:(r==null?void 0:r.description)??n,inputSchema:(r==null?void 0:r.inputSchema)??Mf,...r!=null&&r.outputSchema?{outputSchema:r.outputSchema}:{}})});return this.cachedList=Object.freeze(t),this.cachedList}readCall(t,n){const r={};for(const i of n.envelope){const s=t.meta[i.mcpMetaKey];s!==void 0&&(r[i.field]=s)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(Mt(n)){t.output=await Df(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:i}=$i(o==null?void 0:o.output),s=Pd(i,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(t,n,r){throw ae(n)&&n.code,n}}function Bf(e){if(e&&typeof e=="object"&&e.type==="object")return e;const t=e==null?void 0:e.oneOf;if(Array.isArray(t)&&t.length>0){const n={};let r=null;for(const o of t){if(!o||typeof o!="object")continue;const i=o,s=i.properties;if(s&&typeof s=="object")for(const[c,d]of Object.entries(s))c in n||(n[c]=d);const a=Array.isArray(i.required)?i.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function qf(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("mcp")||i.push(u)}return i}function Kf(e,t){var f,m;const n=e.options.projection??{},r=e.options.toolDescriptions??{},o=no(e.options),i=oo(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:vs({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,o),v={fns:y,createClient:p.createClient,schemas:h};for(const{fnName:S,fnSchema:E,op:A}of b){const _=ve({op:A,schema:E,transport:"mcp",projection:n});t.bindSchema(A.id,E);const{outputSchema:N}=$i(E.output),j=_n(_.mcp.name,E,r[_.mcp.name]??r[S]);t.bindToolMeta(_.mcp.name,{description:j,inputSchema:E.input,outputSchema:N}),t.registerRoute(_,O=>De(_,w,O,v))}}const c=((f=e.packages[0])==null?void 0:f.id)??"ts",d=fe(s,o),l={invoke:(p,g,b)=>d(p,{operation:{id:p},ctx:new nt,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=qf(o,i,c,e.operations??[],l);if(u.length>0){const p=fe({},o),g={fns:{},schemas:{}};for(const b of u){const h=ve({op:b,transport:"mcp",projection:n}),y=Bf(b.input),w=_n(h.mcp.name,{input:y},r[h.mcp.name]);t.bindToolMeta(h.mcp.name,{description:w,inputSchema:y}),t.registerRoute(h,v=>De(h,p,v,g))}}}function Hf(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 sn(e,t,n){const r=new Fa.Server(n,{capabilities:{tools:{}}});return r.setRequestHandler(Uo.ListToolsRequestSchema,async()=>({tools:e.listTools()})),r.setRequestHandler(Uo.CallToolRequestSchema,async o=>{const{name:i,arguments:s={}}=o.params,a=e.getPlan(i),c=e.getDispatch(i);if(!a||!c)throw new Error(`Unknown tool: ${i}`);const d=s,l=d._meta??{},u={args:d,meta:l},f=Date.now();try{const 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}}),r}function Tr(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}function Ir(e,t){const n=e.signal;if(!n)throw new M("invalid_argument",`apigen mcp transport "${t}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function $r(e,t,n,r,o,i){return new Promise((s,a)=>{const c=d=>{a(new M("internal",`failed to bind mcp ${r} server on ${n}:${t}: ${d.message}`,{cause:d}))};e.once("error",c),e.listen(t,n,()=>{e.removeListener("error",c),e.on("error",l=>o.error({err:l},"mcp http server error")),o.info({host:n,port:t},`listening on http://${n}:${t}`);const d=()=>{o.info("mcp server shutting down"),e.close(()=>s()),e.closeAllConnections()};if(i.aborted){d();return}i.addEventListener("abort",d,{once:!0})})})}function Vf(e,t,n,r=process.stdin){return new Promise(o=>{let i=!1;function s(l){i||(i=!0,r.off("end",a),r.off("close",a),n==null||n.removeEventListener("abort",c),t.info(l),o())}function a(){s("stdio transport closed (stdin EOF)")}function c(){s("mcp server shutting down")}const d=e.onclose;if(e.onclose=()=>{d==null||d(),s("stdio transport closed")},r.once("end",a),r.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function Gf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??eo();o.info(`mcp server starting (${t})`);const i=new Ff;Kf(e,i);const a=i.listTools().map(u=>u.name);o.info({tools:a},`${a.length} tools available`);for(const u of a){const f=i.getPlan(u),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=Hf(e);if(o.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),t==="stdio"){const u=sn(i,o,c),f=new Ba.StdioServerTransport;return await u.connect(f),o.info("stdio transport ready"),Vf(f,o,e.signal)}if(t==="sse"){const u=Ir(e,t),f=new Map,m=xo.createServer(Tr(o,async(p,g)=>{const b=p.url??"";if(p.method==="GET"&&b==="/sse"){const h=sn(i,o,c),y=new qa.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 $r(m,n,r,t,o,u)}const d=Ir(e,t),l=xo.createServer(Tr(o,async(u,f)=>{const m=sn(i,o,c),p=new Ka.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await m.connect(p),await p.handleRequest(u,f)}));return $r(l,n,r,t,o,d)}const Wf={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(e){return Uf(e)},run(e){return Gf(e)}},bs=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Ss=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],Jf=new Set([...bs,...Ss]);function zf(e){return Jf.has(e)}const rt=["uid","kind","title","status","priority"],re=1e3,Es=50;async function wo(e,t){const n=await e.getNodeByUid(t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid)throw new Bt(t);if(n.isSuperseded)throw new Ft(t,await Yf(e,n));return n}async function Yf(e,t){const n=new Set([t.id]);let r,o=t;for(;;){const s=(await e.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return r==null?void 0:r.uid;n.add(s.src);const a=(await e.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return r==null?void 0:r.uid;if(r=a,!a.isSuperseded)return a.uid;o=a}}async function B(e,t,n){if(Oe(n)){const i=await e.getNodeByUid(n);return(i==null?void 0:i.kind)!==t||i.tInvalid?null:{id:i.id,uid:i.uid,name:i.name??n,record:i}}const o=(await e.queryNodes({kind:t,name:n,liveOnly:!0,limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}async function qe(e,t,n){var i;if(Oe(n)){const s=await B(e,"component",n);return!s||((i=s.record.metadata)==null?void 0:i.projectUid)!==t?null:s}const o=(await e.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:t}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function Be(e,t){return e.getEdges({src:t})}async function ks(e,t){var c,d;const r=(c=(await e.getEdges({dst:t,rel:"owns_component"}))[0])==null?void 0:c.src;if(r===void 0)return{};const[o]=await e.getNodesByIds([r]);if(!o)return{};const s=(d=(await e.getEdges({dst:r,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:o};const[a]=await e.getNodesByIds([s]);return{component:o,project:a}}async function Xf(e,t){const n=t.expectedKind==="component"&&t.projectUid!==void 0?await qe(e,t.projectUid,t.ref):await B(e,t.expectedKind,t.ref);if(!n)return;if(await Qf(e,t.rel,t.expectedKind)){const o=await e.getEdges({src:n.id,rel:t.rel});return new Set(o.map(i=>i.dst))}const r=await e.getEdges({dst:n.id,rel:t.rel});return new Set(r.map(o=>o.src))}async function Qf(e,t,n){var i;const o=(i=(await e.queryNodes({kind:"edge_kind",name:t,liveOnly:!0,limit:1}))[0])==null?void 0:i.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function Zf(e,t){return(await e.queryNodes({kind:t,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function ep(e,t){const n=e.length+1,r=t.length+1,o=Array.from({length:n},()=>new Array(r).fill(0));for(let i=0;i<n;i+=1)o[i][0]=i;for(let i=0;i<r;i+=1)o[0][i]=i;for(let i=1;i<n;i+=1)for(let s=1;s<r;s+=1)o[i][s]=e[i-1]===t[s-1]?o[i-1][s-1]:1+Math.min(o[i-1][s],o[i][s-1],o[i-1][s-1]);return o[e.length][t.length]}function As(e,t,n=3){const r=Math.max(2,Math.ceil(e.length/2));return t.map(o=>({candidate:o,distance:ep(e.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=r).sort((o,i)=>o.distance-i.distance).slice(0,n).map(o=>o.candidate)}async function Le(e,t){const n=await Zf(e,t.catalogKind),r=new Set,o=[];for(const i of t.refs){const s=await B(e,t.catalogKind,i);if(!s){o.push(i);continue}const a=await e.getEdges({dst:s.id,rel:t.rel});for(const c of a)r.add(c.src)}if(o.length>0){const i=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=o.map(a=>{const c=As(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new Re(t.field,`unknown ${t.catalogKind} value(s): ${s} — no live "${t.catalogKind}" catalog row matches (existing ${t.catalogKind} values: ${i})`)}return r}function tp(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}function vo(e){if(e){for(const t of e)if(!zf(t))throw new Re("fields",`unknown field "${t}" — known fields: ${[...bs,...Ss].join(", ")}`)}}function Te(e){var t;return((t=e==null?void 0:e.metadata)==null?void 0:t.terminal)===!0}async function np(e,t,n){const r=n.find(l=>l.rel==="has_kind"&&l.src===t),o=n.find(l=>l.rel==="has_status"&&l.src===t),i=n.find(l=>l.rel==="has_priority"&&l.src===t),s=n.find(l=>l.rel==="authored_by"&&l.src===t),a=[r==null?void 0:r.dst,o==null?void 0:o.dst,i==null?void 0:i.dst,s==null?void 0:s.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await e.getNodesByIds(a),d=new Map(c.map(l=>[l.id,l]));return{kind:r?d.get(r.dst):void 0,status:o?d.get(o.dst):void 0,priority:i?d.get(i.dst):void 0,author:s?d.get(s.dst):void 0}}async function op(e,t,n){const r=n.filter(i=>i.rel==="has_citation"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c,d,l;return{uid:i.uid,file:typeof((s=i.metadata)==null?void 0:s.target)=="string"?i.metadata.target:i.name??"",lines:typeof((a=i.metadata)==null?void 0:a.line)=="string"?i.metadata.line:void 0,context:i.content||void 0,symbol:typeof((c=i.metadata)==null?void 0:c.symbol)=="string"?i.metadata.symbol:void 0,sha:typeof((d=i.metadata)==null?void 0:d.sha)=="string"?i.metadata.sha:"unverified",at:typeof((l=i.metadata)==null?void 0:l.at)=="string"?i.metadata.at:i.tCreated}})}async function rp(e,t,n){const r=n.filter(i=>i.rel==="has_note"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c;return{uid:i.uid,author:typeof((s=i.metadata)==null?void 0:s.author)=="string"?i.metadata.author:"",text:typeof((a=i.metadata)==null?void 0:a.text)=="string"?i.metadata.text:i.content,at:typeof((c=i.metadata)==null?void 0:c.at)=="string"?i.metadata.at:i.tCreated}})}async function ip(e,t,n){const r=(n??await Be(e,t)).filter(s=>s.rel==="audits"&&s.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,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 sp(e,t){const n=await e.getEdges({dst:t,rel:"blocks"});if(n.length===0)return[];const r=n.map(s=>s.src),o=await e.getNodesByIds(r),i=await _s(e,o);return o.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 ap(e,t,n){const r=(n??await Be(e,t)).filter(c=>c.rel==="relates_to"&&c.src===t),o=await e.getEdges({dst:t,rel:"relates_to"}),i=new Set([...r.map(c=>c.dst),...o.map(c=>c.src)]);if(i.size===0)return[];const s=await e.getNodesByIds([...i]),a=await _s(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 _s(e,t){if(t.length===0)return new Map;const n=new Set(t.map(d=>d.id)),r=await e.getEdges({rel:"has_status"}),o=new Map;for(const d of r)n.has(d.src)&&!o.has(d.src)&&o.set(d.src,d.dst);const i=[...new Set(o.values())];if(i.length===0)return new Map;const s=await e.getNodesByIds(i),a=new Map(s.map(d=>[d.id,d])),c=new Map;for(const[d,l]of o){const u=a.get(l);u&&c.set(d,u)}return c}async function js(e,t,n,r={}){var p,g,b;const o={uid:t.uid},i=h=>n.includes(h),s=i("kind")||i("status")||i("priority")||i("author"),a=i("project")||i("component"),c=i("citations"),d=i("notes"),l=i("auditTrail"),u=i("blockers"),f=i("related"),m=r.outgoingEdges??(s||c||d||l||f?await Be(e,t.id):void 0);if(i("title")&&(o.title=t.name??""),i("createdAt")&&(o.createdAt=t.tCreated),i("updatedAt")&&(o.updatedAt=t.tValid),i("assignee")){const h=(p=t.metadata)==null?void 0:p.assignee;typeof h=="string"&&(o.assignee=h)}if(i("gitContext")){const h=(g=t.metadata)==null?void 0:g.gitContext;typeof h=="string"&&h.length>0&&(o.gitContext=h)}if(i("closedAt")){const h=(b=t.metadata)==null?void 0:b.closedAt;typeof h=="string"&&(o.closedAt=h)}if(i("body")&&(o.body=t.content),s&&m){const h=await np(e,t.id,m);i("kind")&&h.kind&&(o.kind=h.kind.name??""),i("status")&&h.status&&(o.status=h.status.name??""),i("priority")&&h.priority&&(o.priority=h.priority.name??""),i("author")&&h.author&&(o.author=h.author.name??"")}if(a){const{project:h,component:y}=await ks(e,t.id);i("project")&&h&&(o.project=h.uid),i("component")&&y&&(o.component=y.uid)}return c&&m&&(o.citations=await op(e,t.id,m)),d&&m&&(o.notes=await rp(e,t.id,m)),l&&m&&(o.auditTrail=await ip(e,t.id,m)),u&&(o.blockers=await sp(e,t.id)),f&&m&&(o.related=await ap(e,t.id,m)),i("_score")&&r.score!==void 0&&(o._score=r.score),o}async function Ze(e,t,n,r){return Promise.all(t.map(o=>js(e,o,n,{score:r==null?void 0:r.get(o.uid)})))}const cp=.0050125;function dp(e){if(e===void 0)return Es;if(!Number.isInteger(e)||e<=0||e>re)throw new Re("limit",`must be a positive integer ≤ ${re}, got ${e}`);return e}async function lp(e,t){const n=new Set;for(const r of t.refs){const o=await Xf(e,{rel:t.rel,expectedKind:t.expectedKind,ref:r});if(o)for(const i of o)n.add(i)}return n}async function up(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function fp(e,t){if(t.project===void 0&&t.component===void 0)return;let n,r;if(t.project!==void 0){const c=await B(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)}r=l}if(t.component===void 0)return r;const o=n!==void 0?await qe(e,n,t.component):await B(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"}),s=new Set(i.map(c=>c.dst));if(!r)return s;const a=new Set;for(const c of s)r.has(c)&&a.add(c);return a}function pp(e){var r,o,i,s;const t={};e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until}));const n={};return Object.keys(t).length>0&&(n.metadata=t),(r=e.createdAt)!=null&&r.since&&(n.tCreatedAfter=e.createdAt.since),(o=e.createdAt)!=null&&o.until&&(n.tCreatedBefore=e.createdAt.until),(i=e.updatedAt)!=null&&i.since&&(n.tUpdatedAfter=e.updatedAt.since),(s=e.updatedAt)!=null&&s.until&&(n.tUpdatedBefore=e.updatedAt.until),Object.keys(n).length>0?n:void 0}async function Ns(e,t){if(!t)return;const n=[],r=await fp(e,t);if(r!==void 0&&n.push(r),t.kind!==void 0){const c=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await 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 up(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 lp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]}));const o=pp(t);if(n.length===0&&!o)return;let i;if(n.length>0){let[c]=n;for(const d of n.slice(1)){const l=new Set;for(const u of c)d.has(u)&&l.add(u);c=l}if(i=c,i.size===0)return new Set}const s={kind:"issue",liveOnly:!0,isSuperseded:!1,...i?{ids:[...i]}:{},...o},a=await e.queryNodes(s);return new Set(a.map(c=>c.id))}const mp=4;async function gp(e,t){if(t.length===0)return[];const n=t.map(s=>s.id),r={ids:n,isSuperseded:!1,limit:n.length},o=await e.queryNodes(r),i=new Set(o.map(s=>s.id));return t.filter(s=>i.has(s.id))}async function hp(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"},r={text:t.text,vec:t.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:t.decayPerHour??cp}],filters:n},o=[];let i=t.limit;for(let a=0;a<mp;a++){const c=await e.search.backend.searchRanked(r,i);if(o.length=0,o.push(...await gp(e.graph,c)),o.length>=t.limit||c.length<i)break;i*=2}return o.slice(0,t.limit)}async function yp(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)");vo(t.fields);const r=t.fields??rt,o=dp(t.limit);let i,s;if(((b=t.filter)==null?void 0:b.anchor)!==void 0)s=await wo(n,t.filter.anchor),i=`${s.name??""}
200
- ${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 Ns(n,t.filter);if(a&&s&&a.delete(s.id),(a==null?void 0:a.size)===0)return[];const c=await e.search.embedQuery(i),d=s?o+1:o,l=await hp(e,{text:i,vec:c,candidateIds:a,limit:d}),u=(s?l.filter(y=>y.id!==s.id):l).slice(0,o);if(u.length===0)return[];const f=await n.getNodesByIds(u.map(y=>y.id)),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 Ze(n,p,r,g)}function wp(e){return e.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function vp(e){const t=typeof e.gitContext=="string"&&e.gitContext.length>0?e.gitContext:void 0,n=e.citations??[];if(t===void 0&&n.length===0)return[];const r=["",t!==void 0?`Citations: [${wp(t)}]`:"Citations:"];for(const o of n){const i=o.lines?`${o.file}:${o.lines}`:o.file;r.push(`- [${i} sha:${o.sha}]`)}return r}function bp(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 Sp(e){const t=[`## ${e.title??"(untitled)"}`],n=bp(e);return n!==void 0&&t.push(n),e.body!==void 0&&e.body.length>0&&t.push("",e.body),t.push(...vp(e)),t.join(`
201
- `)}function Ep(e){return e.length===0?`_No matching issues._
202
- `:`${e.map(Sp).join(`
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(`
203
202
 
204
203
  `)}
205
- `}function Dn(e){var t,n,r,o;return{uid:e.uid,name:e.name??"",path:typeof((t=e.metadata)==null?void 0:t.path)=="string"?e.metadata.path:void 0,repoUrl:typeof((n=e.metadata)==null?void 0:n.repoUrl)=="string"?e.metadata.repoUrl:void 0,monorepo:typeof((r=e.metadata)==null?void 0:r.monorepo)=="boolean"?e.metadata.monorepo:void 0,description:typeof((o=e.metadata)==null?void 0:o.description)=="string"?e.metadata.description:void 0}}function Mn(e){var t,n,r;return{uid:e.uid,name:e.name??"",projectUid:typeof((t=e.metadata)==null?void 0:t.projectUid)=="string"?e.metadata.projectUid:"",path:typeof((n=e.metadata)==null?void 0:n.path)=="string"?e.metadata.path:void 0,description:typeof((r=e.metadata)==null?void 0:r.description)=="string"?e.metadata.description:void 0}}function Fn(e){var t,n,r;return{uid:e.uid,locType:typeof((t=e.metadata)==null?void 0:t.locType)=="string"?e.metadata.locType:"path",value:typeof((n=e.metadata)==null?void 0:n.value)=="string"?e.metadata.value:e.name??"",componentUid:typeof((r=e.metadata)==null?void 0:r.componentUid)=="string"?e.metadata.componentUid:""}}async function kp(e,t){if((t==null?void 0:t.project)!==void 0){const r=await B(e,"project",t.project);return r?[Dn(r.record)]:[]}return(await e.queryNodes({kind:"project",liveOnly:!0})).map(Dn)}async function Ap(e,t){if((t==null?void 0:t.project)!==void 0){const r=await B(e,"project",t.project);return r?(await e.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:r.uid}}})).map(Mn):[]}return(await e.queryNodes({kind:"component",liveOnly:!0})).map(Mn)}async function _p(e,t){if((t==null?void 0:t.component)!==void 0){const r=t.project!==void 0?await(async()=>{const i=await B(e,"project",t.project);return i?qe(e,i.uid,t.component):null})():await B(e,"component",t.component);return r?(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:r.uid}}})).map(Fn):[]}return(await e.queryNodes({kind:"location",liveOnly:!0})).map(Fn)}async function an(e,t){var d,l,u,f,m,p,g,b,h;if(t.registry==="project"){const y=await B(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{...Dn(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 B(e,"project",y);if(!N)throw new W("project",y);return qe(e,N.uid,t.name)})():await B(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{...Mn(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(!Oe(t.name))throw new T("name","a location has no name — pass its uid");const n=await e.getNodeByUid(t.name);if((n==null?void 0:n.kind)!=="location"||n.tInvalid)throw new W("location",t.name);const r=typeof((m=n.metadata)==null?void 0:m.componentUid)=="string"?n.metadata.componentUid:void 0,o=r?await e.getNodeByUid(r):null,i=o&&!o.tInvalid?o:null,s=typeof((p=i==null?void 0:i.metadata)==null?void 0:p.projectUid)=="string"?i.metadata.projectUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;return{...Fn(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 jp(e){try{return new URL(e),!0}catch{return!1}}function Np(e){return jp(e)?"url":e.includes("/")||e.includes(".")||e.startsWith("~")?"path":"tool"}async function Rp(e,t){var f,m,p,g,b,h;const n=Np(t);let r=(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:t}},limit:1}))[0],o,i=!1;if(!r&&n==="path"){const y=await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit: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&&(r=v,o="matched by path suffix/prefix fallback, not an exact value match")}if(!r)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=r.metadata)==null?void 0:f.componentUid)=="string"?r.metadata.componentUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new 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:r.uid,locType:n,value:typeof((h=r.metadata)==null?void 0:h.value)=="string"?r.metadata.value:t},hint:o}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:r.uid,locType:n,value:t},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function it(e){if(e===void 0)return Es;if(!Number.isInteger(e)||e<=0||e>re)throw new Re("limit",`must be a positive integer ≤ ${re}, got ${e}`);return e}function Op(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 Tp(e,t){const n=new Set;for(const r of t.refs){const o=await B(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function Rs(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function st(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await B(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await qe(e,r,t.component):await B(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Le(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await Rs(e,t.status));else{const o=Array.isArray(t.status)?t.status:[t.status];n.push(await Le(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(t.priority!==void 0){const o=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Le(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(t.author!==void 0&&n.push(await Tp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]})),t.plan!==void 0){const o=await B(e,"issue",t.plan);if(!o)return new Set;const i=await e.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(i.map(s=>s.src)))}if(t.projectPath!==void 0){const o=await e.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:t.projectPath}}});if(o.length===0)return new Set;const i=new Set;for(const s of o){const a=await e.getEdges({src:s.id,rel:"owns_component"});for(const c of a)i.add(c.dst)}n.push(i)}return tp(n)}function Ip(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 $p(e){if(e==="created")return"tCreated";if(e==="updated")return"tValid"}async function Cp(e,t,n){const r=await Promise.all(t.map(d=>e.getEdges({src:d.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(d=>d.map(l=>l.dst)))],i=o.length>0?await e.getNodesByIds(o):[],s=new Map(i.map(d=>{var l;return[d.id,typeof((l=d.metadata)==null?void 0:l.rank)=="number"?d.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;t.forEach((d,l)=>{var f;const u=(f=r[l][0])==null?void 0:f.dst;a.set(d.id,u!==void 0?s.get(u)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...t].sort((d,l)=>a.get(d.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function Pp(e,t){var w,v,S,E,A,_,N,j,O,I,C,K;const{graph:n}=e;Op(t),vo(t.fields);const r=it(t.limit),o=t.fields??rt;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 Re("sort",`"${t.sort}" requires filter.grep or filter.semantic`);const i=await st(n,t.filter);if((i==null?void 0:i.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:r}};const s=Ip(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}:{},...(K=(C=t.filter)==null?void 0:C.updatedAt)!=null&&K.until?{tUpdatedBefore:t.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let D,P;const X=t.offset??0,zt=X+r;if(a!==void 0){const H=await n.searchNodes(a,{limit:zt,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},Lo=await e.search.backend.searchRanked(ce,zt);D=P?Lo.filter(xa=>P.has(xa.id)):Lo}else P&&(D=(await n.searchNodes(a,{limit:zt,filter:d})).map(ce=>({id:ce.id,score:ce.score,fields:{}})));const Yt=(D??[]).map(H=>H.id).slice(X,X+r),Ia=Yt.length>0?await n.getNodesByIds(Yt):[],Co=new Map(Ia.map(H=>[H.id,H])),$a=Yt.map(H=>Co.get(H)).filter(H=>H!==void 0),Ca=new Map((D??[]).map(H=>{var ce;return[(ce=Co.get(H.id))==null?void 0:ce.uid,H.score]}).filter(H=>H[0]!==void 0)),Po=await Ze(n,$a,o,Ca),Xt=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Qt=Po.length,Pa=Qt<Math.min(Xt-X,r),La=X+Qt<Xt;return{page:{items:Po,hasMore:La},meta:{total:Xt,returned:Qt,limit:r,...t.offset!==void 0?{offset:t.offset}:{},...Pa?{truncated:!0}:{}}}}const l=$p(t.sort),u={...d,limit:r+1,...t.after!==void 0?{after:Number(t.after)}:{},...l&&t.after===void 0?{orderBy:l,orderDir:t.direction??"desc"}:{},...t.after===void 0&&t.offset!==void 0?{offset:t.offset}:{}};let f=await n.queryNodes(u);t.sort==="priority"&&t.after===void 0&&(f=await Cp(n,f,t.direction??"asc"));const m=f.length>r,p=m?f.slice(0,r):f,g=m?String(p[p.length-1].id):void 0,b=await Ze(n,p,o),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:r,...y!==void 0?{offset:y}:{}}}}async function Lp(e,t){var y;const{graph:n}=e,r=it(t.limit),o=t.fields??rt,i=await Rs(n,"open"),s=await st(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>=r)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 Ze(n,h,o)}async function xp(e,t){const{graph:n}=e,r=it(t.limit),o=t.fields??rt,i=t.staleAfterMin??30,s=new Date(Date.now()-i*6e4).toISOString(),a=await st(n,t.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:r},d=await n.queryNodes(c);return Ze(n,d,o)}const Up=["blocks","relates_to","part_of"];function Dp(e){return Up.includes(e)}async function Mp(e,t){var u;const{graph:n}=e,r=it(t.limit??re),o=await st(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(f=>f.id)),c=await Fp(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 Be(n,f.id);for(const p of m)if(Dp(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 Fp(e,t){const n=await Promise.all(t.map(a=>e.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await e.getNodesByIds(r):[],i=new Map(o.map(a=>[a.id,a])),s=new Map;return t.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=i.get(d);u&&s.set(a.id,u)}}),s}async function Bp(e,t){const{graph:n}=e,r=it(t.limit??re),o=await st(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(p=>p.id)),c=new Map(s.map(p=>[p.id,p.uid])),d=new Map,l=new Map;for(const p of s)d.set(p.id,0),l.set(p.id,[]);for(const p of s){const 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 qp(e,t){var s;const{graph:n}=e,r=t.overlapAxis,o=t.overlapUids;if(!r)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 i=new Map;for(const a of o){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(r==="file"){const m=(await Be(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(r==="author"){const m=(await Be(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 ks(n,c.id),u=r==="project"?d:l;u&&(i.has(u.uid)||i.set(u.uid,new Set),i.get(u.uid).add(a))}return[...i.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function Kp(e,t){return kp(e.graph,t.filter)}async function Hp(e,t){return Ap(e.graph,t.filter)}async function Vp(e,t){return _p(e.graph,t.filter)}function Gp(e){var t,n;return e.text!==void 0||((t=e.filter)==null?void 0:t.semantic)!==void 0||((n=e.filter)==null?void 0:n.anchor)!==void 0||e.view==="similar"||e.sort==="relevance"||(e.fields??[]).includes("_vector")}function Wp(e,t){var i,s;if(t.text===void 0)return t;if(((i=t.filter)==null?void 0:i.semantic)!==void 0||((s=t.filter)==null?void 0:s.grep)!==void 0)throw new 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:r,...o}=t;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:r}:{grep:r}}}}async function Jp(e,t){const n=t.view??"list";switch(n){case"list":{const{page:r,meta:o}=await Pp(e,t);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await Lp(e,t)}};case"graph":return{result:{view:"graph",graph:await Mp(e,t)}};case"order":return{result:{view:"order",order:await Bp(e,t)}};case"stale":return{result:{view:"stale",items:await xp(e,t)}};case"similar":return{result:{view:"similar",items:await yp(e,t)}};case"overlap":return{result:{view:"overlap",groups:await qp(e,t)}};case"projects":return{result:{view:"projects",items:await Kp(e,t)}};case"components":return{result:{view:"components",items:await Hp(e,t)}};case"locations":return{result:{view:"locations",items:await Vp(e,t)}};default:{const r=n;throw new Re("view",`unknown view "${r}"`)}}}const zp=["list","ready","stale","similar"];async function Yp(e,t={}){var a,c;await((a=e.assertVocabulary)==null?void 0:a.call(e)),await((c=e.assertCatalogInvariants)==null?void 0:c.call(e));const n=Wp(e,t),r=await Jp(e,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:i}=o;if(i!=="list"&&i!=="ready"&&i!=="stale"&&i!=="similar")throw new T("format",`"markdown" is only supported for view:${zp.map(d=>`"${d}"`).join("/")} — view:"${i}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=o.items;return{result:{view:i,format:"markdown",markdown:Ep(s)},meta:r.meta}}const Os=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],Xp=new Set(Os);function Ts(e){return typeof e=="string"&&Xp.has(e)}const bo={not_found:4,item_not_found:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function Qp(e){return e.ok===!0}function Zp(e){return e.ok===!1&&typeof e.error=="object"&&e.error!==null&&Ts(e.error.code)}function So(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 r={code:e,message:t},o={...n??{}};return e==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(r.details=o),{ok:!1,error:r}}function ye(e){return e.ok?0:bo[e.error.code]}function Is(e){if(e===null||typeof e!="object")return!1;const t=e;if(typeof t.ok!="boolean")return!1;if(t.ok)return!0;const n=t.error;if(n===null||typeof n!="object")return!1;const r=n.code;return typeof r=="string"&&r in bo}class $s 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 em extends Error{constructor(t,n,r,o){super(`backlog embedding: ${t} produced a ${o}-dimensional vector but space "${n}" is ${r}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=t,this.modelId=n,this.expected=r,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let Cr=!1,Pr=!1,Lr=!1;const It=new WeakMap;async function tm(e,t){const n=e;return typeof n.hasVectors!="function"?(Cr||(Cr=!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 xr(e){try{return{mod:await import(e)}}catch(t){return{err:t}}}const yt=e=>e instanceof Error?e.message:String(e),Ge=new WeakMap;async function nm(e,t,n,r=i=>console.error(i),o){const i=Ge.get(e);if(i)return i;const s=im(e,t,n,r,o);Ge.set(e,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?Ge.delete(e):It.set(e,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw Ge.delete(e),It.delete(e),a}}function om(e){const t=It.get(e);if(t)return{present:!0,embedding:t.embedding,search:t.search}}function rm(e){Ge.delete(e),It.delete(e)}function Ur(e){return e&&e.length>0?e.join(", "):"(no config layer files found on disk)"}async function im(e,t,n,r,o){var p;if(!(n!=null&&n.enabled))return(o==null?void 0:o.configuredEnabled)===!0?Lr||(Lr=!0,r(`backlog: embedding.enabled is TRUE in the on-disk config but this process is still running with it DISABLED (startup configHash ${o.startupHash??"unknown"}, on-disk configHash ${o.configuredHash??"unknown"}). The next semantic verb adopts it without a restart; if it does not, restart the process. Resolved config layers: ${Ur(o.configPaths)}.`)):Pr||(Pr=!0,r(`backlog: embedding is DISABLED (the default) — semantic/RAG features are OFF for this process. Set embedding.enabled: true in a resolved config layer to opt in (adopted without a restart). Resolved config layers: ${Ur(o==null?void 0:o.configPaths)}.`)),{};const i=(p=e.capabilities)==null?void 0:p.nativeVectors;if(i!==!0)return r(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(i)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,a]=await Promise.all([xr("@adhd/sox-vector-store"),xr("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const g=[..."err"in s?[`@adhd/sox-vector-store (${yt(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${yt(a.err)})`]:[]];return r(`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 r(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${yt(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 r(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${yt(g)}. Continuing WITHOUT semantic search.`),{}}const u=(g,b)=>{if(g.length!==d.dim)throw new em(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 Ha.StoreSearchBackend(l,t),async embedQuery(g){return u(await c.embedSingle(g,"query"),"embedQuery")},async spacePopulated(){return tm(l,d.modelId)}},embedding:f}}async function sm(e,t){vo(t.fields);const n=t.fields??rt,r=await wo(e,t.uid);return js(e,r,n)}function am(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}const cm=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function Cs(e,t,n){if(e){for(const r of cm)if(e[r]!==void 0&&!t.has(r))throw new T(`filter.${r}`,`not supported by ${n} — this view scopes by ${[...t].join("/")} only`)}}async function Ps(e,t){const n=new Set;for(const r of t.refs){const o=await B(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function dm(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Te(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}function Ls(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}async function xs(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await B(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await qe(e,r,t.component):await B(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ps(e,{rel:"has_kind",expectedKind:"kind",refs:o}))}return Ls(n)}const lm=new Set(["project","component","kind","status"]);async function um(e,t){const n=t??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await dm(e,n),scope:n};const r=Array.isArray(n)?n:[n];return{candidates:await Ps(e,{rel:"has_status",expectedKind:"status",refs:r}),scope:n}}async function fm(e,t={}){var f,m,p;const{graph:n}=e;Cs(t.filter,lm,"priorityMatrix");const r=await xs(n,t.filter);if((r==null?void 0:r.size)===0)return{rows:[],unassigned:0,statusScope:((f=t.filter)==null?void 0:f.status)??"open"};const{candidates:o,scope:i}=await um(n,(m=t.filter)==null?void 0:m.status),s=Ls([r,o].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 pm(e,t){if(t.length===0)return new Map;const n=await Promise.all(t.map(c=>e.getEdges({src:c.id,rel:"has_status"}))),r=new Map;n.forEach((c,d)=>{const l=c[0];l&&r.set(t[d].id,l.dst)});const o=[...new Set(r.values())];if(o.length===0)return new Map;const i=await e.getNodesByIds(o),s=new Map(i.map(c=>[c.id,c])),a=new Map;for(const[c,d]of r){const l=s.get(d);l&&a.set(c,l)}return a}async function mm(e,t){const{graph:n}=e,r=await wo(n,t.uid),i=(await n.getSubgraph(r.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==r.id&&l.kind==="issue"&&!l.tInvalid),s=await pm(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:r.uid,childrenTotal:i.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:d}}const gm=new Set(["project","component","kind"]);function hm(e,t,n){var i;const r=e.filter(s=>s.to!==void 0);if(r.length===0)return n;let o;for(const s of r)if(s.at<=t)o=s;else break;return o?o.to:(i=r[0])==null?void 0:i.from}async function ym(e){var u;const t=await e.getEdges({rel:"has_status"}),n=new Map;for(const f of t)n.has(f.src)||n.set(f.src,f.dst);const r=[...new Set(n.values())],o=new Map((r.length>0?await e.getNodesByIds(r):[]).map(f=>[f.id,f])),i=new Map;for(const[f,m]of n)i.set(f,(u=o.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 wm(e,t){var u;const{graph:n}=e;if(Cs(t.filter,gm,"openCurve"),t.at.length===0)throw new T("at","requires at least one ISO-8601 instant to sample");const r=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()}),o=await xs(n,t.filter);if((o==null?void 0:o.size)===0)return{points:r.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 am((u=f.metadata)==null?void 0:u.aliases))s.set(p,m)}const{currentStatusNameByIssue:a,auditTrailByIssue:c}=await ym(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 r){const m={kind:"issue",validAt:f,liveOnly:!1,...o?{ids:[...o]}:{}},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=hm(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 Dr=["abort","force","comment"];function He(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}const Mr=512;function Us(e){if(typeof e=="string"&&e.length>Mr)throw new T("gitContext",`must be at most ${Mr} characters, got ${e.length}`)}async function vm(e,t,n){if(!Ht(e))return"unverified";try{const{accepted:r,candidate:o}=await Gi(e.metadata.path,t,n);if(!r)return"unverified";const i=await Pt.readFile(o);return pe.createHash("sha256").update(i).digest("hex")}catch(r){if(ao(r))return"unverified";throw Xi(r,t)}}function Fr(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 bm(e,t){for(const n of e){const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Sm(e,t,n,r,o){if(!n.dedupeScanEnabled)return[];const{search:i,graph:s}=e;if(!i||!s)return[];const a={project:t.uid},c=await Ns(s,a);if(!c||c.size===0)return[];const d=go(r,o),l=typeof i.embedQuery=="function"?await i.embedQuery(d):void 0,f={text:d,vec:l,signals:l?[{kind:"text"},{kind:"vec"}]:[{kind:"text"}],filters:{ids:[...c]}},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 Em(e,t){He("title",t.title),He("body",t.body),He("project",t.project),He("by",t.by),Z("by",t.by),Us(t.gitContext);const n=t.citations??[];n.forEach((u,f)=>He(`citations[${f}].file`,u.file));const r=typeof t.gitContext=="string"&&t.gitContext.trim().length>0?t.gitContext:void 0,o=t.duplicateAction??"abort";if(t.duplicateAction!==void 0&&!Dr.includes(t.duplicateAction))throw new T("duplicateAction",`must be one of ${Dr.map(u=>`'${u}'`).join("|")}, got "${t.duplicateAction}"`);const i=await Xe(e.adapter,t.project),s=Me(i),a=[];for(const u of n){const f=await vm(i,u.file,s.citationAllowedExternalRoots);if(f==="unverified"&&s.citationRequiresSha){if(Ht(i))throw new co(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 Sm(e,i,s,t.title,t.body);if(c.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let d;const l=await V(e,async u=>{const f=U();if(c.length>0&&o==="comment"){const[C]=c,K=await be(u,C.uid),D=`${t.title}
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}
206
206
 
207
- ${t.body}`,P=await J(u,{kind:"note",content:D,metadata:{author:t.by,text:D,at:f},at:f}),X=await x(u,"has_note");return await L(u,{at:f,srcRowid:K.rowid,srcUid:K.uid,srcKind:"issue",dstRowid:P.rowid,dstUid:P.uid,dstKind:"note",rel:"has_note",rule:X,typePolicy:e.typePolicy}),{created:!1,commentedOn:{uid:K.uid,noteId:P.uid},duplicateCandidates:c}}const m=await Xe(u,t.project),p=Me(m),g=t.component!==void 0?await po(u,{projectUid:m.uid,ref:t.component}):await os(u,{projectRowid:m.rowid}),b=t.kind??p.defaultKind??"issue",h=await _e(u,{catalogKind:"kind",ref:b,at:f});Fr(p.allowedKinds,"kind",h.name);const y=t.status??p.defaultStatus??"open",w=await rs(u,{ref:y,at:f});Fr(p.allowedStatuses,"status",w.name);let v;t.priority!==void 0&&(v=await _e(u,{catalogKind:"priority",ref:t.priority,at:f,mintMetadata:async C=>({rank:await is(C)})}));const S=t.author??t.by,E=await _e(u,{catalogKind:"agent",ref:S,at:f});bm(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),r!==void 0&&(A.gitContext=r);const _=await J(u,{kind:"issue",name:t.title,content:t.body,metadata:A,at:f});d={rowid:_.rowid,uid:_.uid};const N=await x(u,"owns_component");await L(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 x(u,"has_kind");await L(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 x(u,"has_status");if(await L(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 x(u,"has_priority");await L(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 x(u,"authored_by");if(await L(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 x(u,"has_citation");for(let K=0;K<n.length;K+=1){const D=n[K],P=a[K],X=await J(u,{at:f,kind:"citation",name:D.file,content:D.context??D.file,metadata:{target:D.file,target_type:"path",sha:P,line:D.lines??null,at:f,symbol:D.symbol??null,blastRadius:D.blastRadius??null}});await L(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 F({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,...r!==void 0?{gitContext:r}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(d){const u=Ot(e,{action:"upsert",subjectRowid:d.rowid,subjectUid:d.uid,actor:t.by,content:go(t.title,t.body)});t.awaitEmbed?await u:u.catch(()=>{})}return l}function wt(e,t){if(typeof t!="string"||t.trim().length===0)throw new T(e,"is required")}async function km(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await ee(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Am(e,t){if(e.length>0&&!e.includes(t))throw new T("kind",`"${t}" is not in this project's allowed kind set`)}function _m(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Br(e,t,n,r){const o=[],i=[];n.name!==void 0&&(o.push("name = ?"),i.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),i.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),i.push(r);const s=await e.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...i,t]);if(s.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${s.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function vt(e,t,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let i=n.override;if(!i&&o){const a=await ee(e,o.dst);(a==null?void 0:a.tInvalid)===null&&(i={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!i){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await me(e,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await x(e,n.rel);await L(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 jm(e,t,n){if(n.oldIssueRowid===n.newIssueRowid)return;const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!r)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await ee(e,r.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${r.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await me(e,{srcRowid:r.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const i=await x(e,"owns_component");await L(e,{at:n.at,srcRowid:r.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:i,typePolicy:t.typePolicy})}const qr=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Nm(e,t){if(t.oldIssueRowid===t.newIssueRowid)return;const n=qr.map(()=>"?").join(", ");for(const r of["outgoing","incoming"]){const o=r==="outgoing"?"src":"dst",i=r==="outgoing"?"dst":"src",{rows:s}=await e.executeAll(`SELECT ${i} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[t.oldIssueRowid,...qr]);for(const a of s){const c=r==="outgoing"?t.oldIssueRowid:a.other,d=r==="outgoing"?a.other:t.oldIssueRowid,l=r==="outgoing"?t.newIssueRowid:a.other,u=r==="outgoing"?a.other:t.newIssueRowid;await me(e,{srcRowid:c,dstRowid:d,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:t.at}),await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
207
+ ${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)
208
208
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
209
209
  ON CONFLICT(src, dst, rel) DO UPDATE SET
210
210
  weight = excluded.weight, confidence = excluded.confidence,
211
211
  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 Rm(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 Om(e,t){const n=["title","body","kind","priority","assignee","author"];for(const r of n)if(e[r]!==void 0&&!t.includes(r))throw new Error(`update: patch key "${r}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function Tm(e,t){if(wt("uid",t.uid),wt("by",t.by),Z("by",t.by),t.status!==void 0)throw new Re("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");t.title!==void 0&&wt("title",t.title),t.body!==void 0&&wt("body",t.body);const r=Rm(t);if(r.length===0)throw new T("patch","update requires at least one of title/body/kind/priority/assignee/author");Om(t,r);let o;const i=await V(e,async s=>{const a=U(),c=await be(s,t.uid),d=await km(s,c.rowid),l=Me(d);let u;if(t.kind!==void 0){const y=await _e(s,{catalogKind:"kind",ref:t.kind,at:a});Am(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 _e(s,{catalogKind:"priority",ref:t.priority,at:a,mintMetadata:async w=>({rank:await is(w)})});f={rowid:y.rowid,uid:y.uid,kind:"priority",name:y.name}}let m;if(t.author!==void 0){const y=await _e(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),_m(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 Ft(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)
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)
213
213
  VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
214
214
  ON CONFLICT(src, dst, rel) DO UPDATE SET
215
215
  meta = excluded.meta, weight = excluded.weight,
216
- t_invalid = NULL, t_valid = excluded.t_valid`,[S.rowid,c.rowid,a,a]),await Br(s,S.rowid,{},a),o={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 Br(s,c.rowid,{name:t.title,metadata:y},a)}return await jm(s,e,{oldIssueRowid:c.rowid,newIssueRowid:g,newIssueUid:b,at:a}),await vt(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 vt(s,e,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:u,reason:"kind changed via update",at:a}),await vt(s,e,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:f,reason:"priority changed via update",at:a}),await vt(s,e,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:g,newSrcUid:b,override:m,reason:"author changed via update",at:a}),await Nm(s,{oldIssueRowid:c.rowid,newIssueRowid:g,at:a}),await F({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: ${r.join(", ")}`,at:a}),{uid:b,changed:r}});if(o){const{oldRowid:s,oldUid:a,newRowid:c,newUid:d,newTitle:l,newBody:u}=o,f=Promise.all([Ot(e,{action:"delete",subjectRowid:s,subjectUid:a,actor:t.by}),Ot(e,{action:"upsert",subjectRowid:c,subjectUid:d,actor:t.by,content:go(l,u)})]);t.awaitEmbed?await f:f.catch(()=>{})}return i}function Ds(e){const t=e??{};return{claimedBy:typeof t.claimedBy=="string"?t.claimedBy:void 0,claimedAt:typeof t.claimedAt=="string"?t.claimedAt:void 0}}function Ms(e,t){return e!==void 0?(Date.parse(t)-Date.parse(e))/6e4:Number.POSITIVE_INFINITY}function Fs(e,t,n){return Ms(e,t)>=n}async function Bs(e,t,n){const r=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[t,"has_status"]);if(!r)throw new Error(`${n}: issue rowid=${t} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await ee(e,r.dst);if((o==null?void 0:o.kind)!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${r.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function bt(e,t){if(typeof t!="string"||t.trim().length===0)throw new T(e,"is required")}async function Kr(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await ee(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}async function Im(e,t,n){if(!Ht(e))return"unverified";try{const{accepted:r,candidate:o}=await Gi(e.metadata.path,t,n);if(!r)return"unverified";const i=await Pt.readFile(o);return pe.createHash("sha256").update(i).digest("hex")}catch(r){if(ao(r))return"unverified";throw Xi(r,t)}}function $m(e,t){if(e.length>0&&!e.includes(t))throw new T("toStatus",`"${t}" is not in this project's allowed status set`)}function Cm(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Pm(e,t){bt("uid",t.uid),bt("by",t.by),Z("by",t.by),bt("toStatus",t.toStatus),Us(t.gitContext);const n=t.citations??[];n.forEach((o,i)=>bt(`citations[${i}].file`,o.file));const r=[];if(n.length>0){const o=await qt(e.adapter,t.uid);if((o==null?void 0:o.kind)!=="issue"||o.tInvalid!==null)throw new Bt(t.uid);const i=await Kr(e.adapter,o.rowid),s=Me(i);for(const a of n){const c=await Im(i,a.file,s.citationAllowedExternalRoots);if(c==="unverified"&&s.citationRequiresSha){if(Ht(i))throw new co(a.file,s.citationAllowedExternalRoots);console.error(`transition: citation_requires_sha waived for path-less project uid="${i.uid}" — cannot verify citation "${a.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}r.push(c)}}return V(e,async o=>{var _;const i=U(),s=await be(o,t.uid),a=await Kr(o,s.rowid),c=Me(a),{claimedBy:d,claimedAt:l}=Ds(s.metadata);if(d!==void 0&&d!==t.by&&!Fs(l,i,c.claimStaleAfterMin))throw new Nt(d,l??i);const u=await Bs(o,s.rowid,"transition"),f=u.name??"",m=await rs(o,{ref:t.toStatus,at:i});$m(c.allowedStatuses,m.name),Cm(c.requiredFields,{status:m.name,note:t.note});const p=await ee(o,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 Qi(s.uid);if(g&&c.citationRequired&&n.length===0)throw new Zi(s.uid);const h={target_uid:s.uid,from:f,to:m.name,agent:t.by,note:t.note??null,at:i},y=lo(ns(h)),w=await J(o,{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 x(o,"has_transition");await L(o,{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 me(o,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${m.name}"`,at:i});const S=await x(o,"has_status");if(await L(o,{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 x(o,"has_citation");for(let j=0;j<n.length;j+=1){const O=n[j],I=r[j],C=await J(o,{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 L(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:C.rowid,dstUid:C.uid,dstKind:"citation",rel:"has_citation",rule:N,typePolicy:e.typePolicy})}}const E={...s.metadata??{}};g?E.closedAt=i:delete E.closedAt,typeof t.gitContext=="string"&&t.gitContext.trim().length>0&&(E.gitContext=t.gitContext);const A=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(E),i,s.rowid]);if(A.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${A.rowsAffected} rows for rowid=${s.rowid}, expected exactly 1.`);return await F({tx:o,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 Hr(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function Lm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await ee(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const i={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Me(i)}async function Ve(e,t,n,r){const o=await e.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),r,t]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function xm(e,t){if(Hr("uid",t.uid),Hr("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 r=>{var d;const o=U(),i=await be(r,t.uid),s={...i.metadata??{}},{claimedBy:a,claimedAt:c}=Ds(s);if(t.action==="claim"){const l=await Bs(r,i.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new Yi(i.uid,l.name??"");if(a===void 0){const g={...s,claimedBy:t.by,claimedAt:o};return await Ve(r,i.rowid,g,o),await F({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",to:t.by,at:o}),{uid:i.uid,status:"claimed",claimedBy:t.by,claimedAt:o}}if(a===t.by){const g={...s,claimedAt:o};return await Ve(r,i.rowid,g,o),await F({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",from:t.by,to:t.by,note:"re-affirmed (held)",at:o}),{uid:i.uid,status:"held",heldBy:t.by,claimedBy:t.by,claimedAt:o}}const u=await Lm(r,i.rowid),f=Ms(c,o),m=Fs(c,o,u.claimStaleAfterMin);if(!m&&!n)throw new Nt(a,c??o);const p={...s,claimedBy:t.by,claimedAt:o,previousClaimant:a};return await Ve(r,i.rowid,p,o),await F({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"reclaimed-stale",from:a,to:t.by,note:m?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${u.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:o}),{uid:i.uid,status:"reclaimed-stale",claimedBy:t.by,claimedAt:o,previousClaimant:a}}if(t.action==="release"){if(a===t.by){const l={...s};return delete l.claimedBy,delete l.claimedAt,await Ve(r,i.rowid,l,o),await F({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"released",from:t.by,at:o}),{uid:i.uid,status:"released"}}return{uid:i.uid,status:"release-noop",wasClaimedBy:a}}if(a===t.by){const l={...s,claimedAt:o};return await Ve(r,i.rowid,l,o),await F({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"renewed",from:t.by,to:t.by,at:o}),{uid:i.uid,status:"renewed",claimedBy:t.by,claimedAt:o}}throw new Nt(a??"",c??"")})}const Vr=["relates_to","supersedes","blocks","duplicate_of","part_of"];function cn(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function Um(e,t,n,r){const o=await e.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t,n,r]);return o?o.rowid:null}async function Dm(e,t){if(cn("sourceUid",t.sourceUid),cn("targetUid",t.targetUid),cn("by",t.by),Z("by",t.by),!Vr.includes(t.rel))throw new T("rel",`must be one of ${Vr.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 r=U(),o=await be(n,t.sourceUid),i=await be(n,t.targetUid),s=await Um(n,o.rowid,i.rowid,t.rel);if(t.action==="add"){if(s!==null)return{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!0};const a=await x(n,t.rel);return await L(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"issue",rel:t.rel,rule:a,typePolicy:e.typePolicy}),await F({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"related",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!1}}return s===null?{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!0}:(await me(n,{srcRowid:o.rowid,dstRowid:i.rowid,rel:t.rel,reason:`relate: removed by "${t.by}"`,at:r}),await F({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"unrelated",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!1})})}function Gr(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function Mm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await ee(e,n.src);if((r==null?void 0:r.kind)!=="component"||r.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function Fm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_project"]);if(!n)throw new Error(`move: component rowid=${t} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const r=await ee(e,n.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function Bm(e,t){return Gr("uid",t.uid),Gr("by",t.by),Z("by",t.by),V(e,async n=>{const r=U(),o=await be(n,t.uid),i=await Mm(n,o.rowid),s=await Fm(n,i.rowid);let a;if(t.toProject!==void 0){const l=await Xe(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 po(n,{projectUid:a.uid,ref:t.toComponent}):c=await os(n,{projectRowid:a.rowid}),c.rowid===i.rowid)return{uid:o.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid};await me(n,{srcRowid:i.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:r});const d=await x(n,"owns_component");return await L(n,{at:r,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:e.typePolicy}),await F({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"moved",from:i.uid,to:c.uid,at:r}),{uid:o.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid}})}function dn(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}async function qm(e,t){dn("uid",t.uid),dn("by",t.by),Z("by",t.by),dn("reason",t.reason);let n;const r=await V(e,async o=>{const i=U(),s=await be(o,t.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:t.reason,invalidatedAt:i},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[i,JSON.stringify(a),s.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);return await F({tx:o,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"deleted",note:t.reason,at:i}),{uid:s.uid,invalidated:!0}});if(n){const o=Ot(e,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:t.by});t.awaitEmbed?await o:o.catch(()=>{})}return r}function $t(e){var t;return(t=e.env.version)==null?void 0:t.configHash}async function qs(e){const t=e.embeddingConfig;t!=null&&t.refresh().changed&&rm(e.store.adapter);const n=t?t.current():e.env.config.embedding;return nm(e.store.adapter,e.store.graph,n,void 0,{configuredEnabled:t?t.configured().enabled:n==null?void 0:n.enabled,startupHash:$t(e),configuredHash:t?t.fingerprint().configHash:$t(e),configPaths:t?t.fingerprint().files.map(r=>r.path):void 0})}async function te(e,t){await so(e.store.adapter),await mo(e.store.adapter);const{search:n,embedding:r}=t.needsSemantic?await qs(e):{};return{adapter:e.store.adapter,typePolicy:e.store.typePolicy,graph:e.store.graph,...n!==void 0?{search:n}:{},...r!==void 0?{embedding:r}:{}}}async function Gt(e,t){const{search:n}=t.needsSemantic?await qs(e):{},r=n!==void 0&&t.probeSpace?await n.spacePopulated():void 0;return{graph:e.store.graph,assertVocabulary:()=>so(e.store.adapter),assertCatalogInvariants:()=>mo(e.store.adapter),...n!==void 0?{search:n}:{},...r!==void 0?{spacePopulated:r}:{}}}const Km=[[Bt,"item_not_found"],[W,"not_found"],[T,"invalid_argument"],[Nt,"conflict"],[In,"conflict"],[Ft,"conflict"],[Yi,"precondition_failed"],[Zi,"precondition_failed"],[Qi,"precondition_failed"],[co,"precondition_failed"],[Wi,"store_busy"],[$s,"rag_not_configured"]],Hm={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function Ks(e){for(const[t,n]of Km)if(e instanceof t){const r=e instanceof q?{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}:void 0;return ie(n,e.message,r)}return e instanceof q?ie(Hm[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 So(await e())}catch(t){return Ks(t)}}async function Hs(e,t){return G(()=>"registry"in t?t.registry==="project"?an(e.store.graph,{registry:"project",name:t.name}):t.registry==="component"?an(e.store.graph,{registry:"component",name:t.name,filter:t.filter}):an(e.store.graph,{registry:"location",name:t.name}):sm(e.store.graph,t))}async function Vs(e,t){try{const{result:n,meta:r}=await Yp(await Gt(e,{needsSemantic:Gp(t),probeSpace:t.text!==void 0}),t);return So(n,r?{meta:r}:void 0)}catch(n){return Ks(n)}}async function Gs(e,t){return G(async()=>fm(await Gt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ws(e,t){return G(async()=>mm(await Gt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Js(e,t){return G(async()=>wm(await Gt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function zs(e){return G(async()=>{const t=e.embeddingConfig,n=t?t.configured():e.env.config.embedding,r=t?t.current():e.env.config.embedding,o=om(e.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(r==null?void 0:r.enabled)===!0,provider:(r==null?void 0:r.provider)??"",model:(r==null?void 0:r.model)??"",membersPresent:{embedding:(o==null?void 0:o.embedding)??!1,search:(o==null?void 0:o.search)??!1},divergent:(n==null?void 0:n.enabled)===!0!=((r==null?void 0:r.enabled)===!0),startupHash:$t(e)??"",currentHash:t?t.fingerprint().configHash:$t(e)??""}})}async function Ys(e,t){return G(()=>Rp(e.store.graph,t.q))}async function Xs(e,t){return G(async()=>Em(await te(e,{needsSemantic:!0}),t))}async function Qs(e,t){return G(async()=>Tm(await te(e,{needsSemantic:!0}),t))}async function Zs(e,t){return G(async()=>Pm(await te(e,{needsSemantic:!1}),t))}async function ea(e,t){return G(async()=>xm(await te(e,{needsSemantic:!1}),t))}async function ta(e,t){return G(async()=>Dm(await te(e,{needsSemantic:!1}),t))}async function na(e,t){return G(async()=>Bm(await te(e,{needsSemantic:!1}),t))}async function oa(e,t){return G(async()=>qm(await te(e,{needsSemantic:!1}),t))}async function ra(e,t){return G(async()=>ou(await te(e,{needsSemantic:!1}),t))}async function ia(e,t){return G(async()=>iu(await te(e,{needsSemantic:!1}),t))}async function sa(e,t){return G(async()=>au(await te(e,{needsSemantic:!1}),t))}async function aa(e,t){return G(async()=>cu(await te(e,{needsSemantic:!1}),t))}const Vm=Object.freeze(Object.defineProperty({__proto__:null,claim:ea,create:Xs,delete:oa,embeddingStatus:zs,get:Hs,lookup:Ys,move:na,openCurve:Js,partOfRollup:Ws,priorityMatrix:Gs,query:Vs,relate:ta,rmLocation:aa,transition:Zs,update:Qs,upsertComponent:ia,upsertLocation:sa,upsertProject:ra},Symbol.toStringTag,{value:"Module"}));async function Gm(e){let t;try{t=await we.open(e,"r"),await t.sync()}catch{}finally{t&&await t.close().catch(()=>{})}}async function ca(e,t){const n=k.dirname(e);await we.mkdir(n,{recursive:!0});const r=`${e}.${process.pid}.${pe.randomUUID()}.tmp`;let o;try{o=await we.open(r,"w"),await o.writeFile(JSON.stringify(t),"utf8"),await o.sync(),await o.close(),o=void 0,await we.rename(r,e),await Gm(n)}catch(i){throw o&&await o.close().catch(()=>{}),await we.unlink(r).catch(()=>{}),i}}function Wm(e){return{async get(){try{const t=await we.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await ca(e,n)}}}const et=1;function Jm(e){return pe.createHash("sha256").update(e).digest("hex")}async function Wr(e){return Jm(await we.readFile(e,"utf8"))}async function Ct(e){try{return(await we.stat(e)).mtimeMs}catch{return}}async function Jr(e,t){const n=await Wr(e.source),r=pe.createHash("sha256");r.update(`formatVersion:${et}
217
- `),r.update(`extractorVersion:${t}
218
- `),r.update(`host:${e.host}
219
- `),r.update(`namespace:${e.namespace??""}
220
- `),r.update(`source:${n}
221
- `);for(const o of bi(e.source))o!==e.source&&r.update(`dep:${o}:${await Wr(o)}
222
- `);return r.digest("hex")}async function zr(e,t){const n=await Ct(e.source)??0,r=[];for(const o of bi(e.source)){if(o===e.source)continue;const i=await Ct(o);i!==void 0&&r.push({path:o,mtimeMs:i})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function zm(e,t){if(t.source.path!==e.source)return!1;const n=await Ct(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await Ct(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function Ym(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=Wm(e.cache),n=e.extractorVersion;async function r(o,i,s){const a=s??await Jr(o,n),c=await zr(o,a);await t.put(e.cache,{formatVersion:et,operations:i,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,i)=>{const s=await t.get(e.cache);if((s==null?void 0:s.formatVersion)!==et||s.extractorVersion!==n||!s.staleness){const d=await i();try{await r(o,d)}catch{}return d}if(await zm(o,s.staleness))return s.operations;const a=await Jr(o,n);if(a===s.staleness.contentKey)return zr(o,a).then(d=>t.put(e.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await i();try{await r(o,c,a)}catch{}return c}}Kn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);const Xm="api.ir.json",Qm=Kn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href),Eo=Qm("@adhd/apigen-core-client/package.json").version;function Wt(){const e=k.dirname(tt.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 Zm(e){return k.join(e,Xm)}function ko(e){return pe.createHash("sha256").update(e).digest("hex")}function da(e){const t=[],n=o=>{let i;try{i=R.readdirSync(o,{withFileTypes:!0})}catch{return}for(const s of i){const a=k.join(o,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&t.push(a)}};n(e),t.sort();const r={};for(const o of t)r[k.relative(e,o).split(k.sep).join("/")]=ko(R.readFileSync(o));return r}function eg(e,t){const n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++){const i=n[o];if(i!==r[o]||e[i]!==t[i])return!1}return!0}function tg(e){try{const t=Zm(e);if(!R.existsSync(t))return;const n=JSON.parse(R.readFileSync(t,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==et||n.extractorVersion!==Eo)return;const r=n.artifactSource;if(!r||typeof r.sha256!="string"||typeof r.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const o=k.join(e,"api.d.ts");if(!R.existsSync(o))return;const i=R.readFileSync(o);if(i.byteLength!==r.bytes||ko(i)!==r.sha256)return;const s=r.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return eg(s,da(e))?n.operations:void 0}catch{return}}async function ng(e){const t=R.readFileSync(e.apiDts),n={formatVersion:et,operations:e.operations,extractorVersion:e.extractorVersion,createdAt:new Date().toISOString(),artifactSource:{path:e.apiDts,sha256:ko(t),bytes:t.byteLength,deps:da(k.dirname(e.apiDts))}};await ca(e.outFile,n)}function og(e={}){const t=ho("backlog",Fe,{namespace:e.namespace??"production",scope:yo(e.scope),...e.adhdRoot!==void 0?{adhdRoot:e.adhdRoot}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),n=[k.join(t.roots.system,Ce),k.join(t.roots.global,Ce)];return t.roots.project&&(n.push(k.join(t.roots.project,Ce)),n.push(k.join(t.roots.project,ls))),[...new Set(n)]}const rg=e=>e instanceof Error?e.message:String(e),Yr=e=>({enabled:e.enabled===!0,provider:e.provider,model:e.model}),ig=(e,t)=>e.enabled===t.enabled&&e.provider===t.provider&&e.model===t.model;function sg(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 r=Yr(e.baseline.config.embedding),o=r,i={configHash:e.baseline.version.configHash,files:t()};const s=()=>{const a=t();if(n(a,i.files))return!1;let c;try{c=e.rebuild()}catch(d){return e.log("warn",`backlog: could not re-read the embedding config layers (${rg(d)}) — continuing with the last known effective embedding settings`),!1}return i={configHash:c.version.configHash,files:a},o=Yr(c.config.embedding),!0};return{current:()=>r,configured:()=>(s(),o),divergent:()=>(s(),o.enabled&&!r.enabled),refresh:()=>{const a=r;return s(),ig(o,r)?{changed:!1,from:a,to:r}:(r=o,e.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${r.enabled}, provider ${r.provider}, model ${r.model}); adopting without restart`),{changed:!0,from:a,to:r})},fingerprint:()=>i}}function ag(){const e=k.dirname(tt.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 Ao(){const e=ag(),t=JSON.parse(R.readFileSync(e,"utf8"));return{name:t.name,version:t.version}}function Bn(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function la(){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 Xr=["install","install-skill","serve"];function ua(e){return e.filter(t=>t.kind==="action").map(t=>{const n=Ne(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 cg(e){const t=e.filter(n=>{const r=n.cliPath[n.cliPath.length-1]??"";return Xr.includes(r)||Xr.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(t.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${t.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function dg(e,t=[jt]){const n=ua(e),r=new Set(n.map(i=>i.mcpTool)),o={host:"backlog",operations:e};for(const i of t){const s=i.capabilities.mount;if(s)for(const a of s.operations(o,void 0,void 0))r.add(Ne(a).mcp.name)}return[...r].sort()}function Qr(e){if(!e||typeof e!="object")return e;const t={},n=o=>{if(Array.isArray(o)){for(const s of o)n(s);return}if(!o||typeof o!="object")return;const i=o;for(const s of["definitions","$defs"]){const a=i[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,d]of Object.entries(a))c in t||(t[c]=d)}for(const[s,a]of Object.entries(i))s==="definitions"||s==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;const r=(o,i)=>{if(Array.isArray(o))return o.map(d=>r(d,i));if(!o||typeof o!="object")return o;const s=o,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return i.has(d)||!(d in t)?{}:r(t[d],new Set([...i,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=r(l,i));return c};return r(e,new Set)}async function lg(e={}){const t=Wt(),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 r=tg(t);return r||(await Promise.resolve().then(()=>Ta)).extractApiOperationsLive(e)}async function _o(e,t={}){const n=typeof e=="function"?e:()=>e,r=await lg(t),o={schemas:Object.fromEntries(r.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:Qr(c.input),output:Qr(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},i=yc(o,[]),s=ua(r);cg(s);const{version:a}=Ao();return{pkg:{id:"backlog",version:a,schemas:i,importPath:k.join(Wt(),"api.js"),fns:Vm,createClient:async()=>n()},operations:r,surface:s}}async function fa(e){const t=Pe({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace});t.ensureDirs();let n,r;const o=Je(t),i=()=>(n||(n=Cn(r)),n),s=Eu()?void 0:cs(i);try{r=await Tt(o,t.config.db.busyTimeoutMs)}catch(c){throw s==null||s.dispose(),c}const a={store:r,env:t,embeddingConfig:sg({baseline:t,rebuild:()=>Pe({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),layerFiles:()=>og({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 _o(a,{adhdRoot:e.adhdRoot}),l=la(),u=[];(e.transport==="http"||e.transport==="both")&&u.push(Bn(Nf)({packages:[c],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[$f,jt]},signal:e.signal,operations:d,logger:l})),(e.transport==="mcp"||e.transport==="both")&&u.push(Bn(Wf)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[jt]},signal:e.signal,operations:d,logger:l})),await Promise.all(u)}finally{s==null||s.dispose(),await i()}}const xe=["claude","codex","opencode"],ug={claude:".claude",codex:".codex",opencode:".opencode"};function pa(e,t){return t?k.join(e,".codex"):process.env.CODEX_HOME??k.join(e,".codex")}function fg(e,t,n,r){if(t==="project")return k.join(n,ug[e],"skills");const o=r??z.homedir();return e==="claude"?k.join(o,".claude","skills"):e==="codex"?k.join(pa(o,r),"skills"):k.join(o,".config","opencode","skills")}function pg(){const e=k.dirname(tt.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 jo(e,t){console.error(JSON.stringify({code:"invalid_argument",message:e.message})),console.error(""),console.error(t),process.exitCode=2}const Zr=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
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]
223
223
 
224
224
  Copies the packaged backlog SKILL.md into an agent host's skills directory.
225
225
  (\`backlog install\` is the richer successor — it also registers the MCP server.)
@@ -233,16 +233,16 @@ Examples:
233
233
  backlog install-skill
234
234
  backlog install-skill --host opencode --scope user
235
235
  backlog install-skill --host claude --scope project
236
- `;function mg(e){let t="all",n="user";for(let o=0;o<e.length;o++){const i=e[o];if(i==="--host")t=e[++o]??"all";else if(i==="--scope")n=e[++o]??"user";else throw new Q(`backlog install-skill: unknown argument "${i}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new Q(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const r=t==="all"?[...xe]:[t];for(const o of r)if(!xe.includes(o))throw new Q(`backlog install-skill: --host must be one of ${xe.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function ma(e,t=process.cwd(),n){const{hosts:r,scope:o}=mg(e);return ga(r,o,t,n)}function ga(e,t,n,r){const o=pg();if(!R.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const i=R.readFileSync(o,"utf8"),s=k.dirname(tt.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(fg(u,t,n,r),"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 ha(e){if(e.includes("--help")||e.includes("-h")){console.log(Zr);return}let t;try{t=ma(e)}catch(n){if(n instanceof Q)return jo(n,Zr);throw n}console.log(JSON.stringify({installed:t}))}const No=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function gg(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 ya(e,t,n,r){const o=gg(e),i=o[t],s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};s[n]=r,o[t]=s,R.mkdirSync(k.dirname(e),{recursive:!0}),R.writeFileSync(e,JSON.stringify(o,null,2)+`
238
- `,"utf8")}function hg(e,t,n){if(e==="project")return k.join(t,".mcp.json");const r=z.homedir();return k.join(r,".claude.json")}function yg(e,t,n){if(e==="project")return k.join(t,"opencode.json");const r=z.homedir();return k.join(r,".config","opencode","opencode.json")}function wg(e,t,n){if(e==="project")return k.join(t,".codex","config.toml");const r=z.homedir();return k.join(pa(r,n),"config.toml")}function vg(e,t,n){var d,l;const r=`[${t}]`,o=e.length>0?e.split(`
239
- `):[],i=o.findIndex(u=>u.trim()===r),s=[r,...n];if(i===-1){if(o.length===0||o.every(u=>u.trim()===""))return s.join(`
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(`
240
240
  `)+`
241
- `;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
241
+ `;for(;r.length>0&&((d=r[r.length-1])==null?void 0:d.trim())==="";)r.pop();return[...r,"",...s].join(`
242
242
  `)+`
243
- `}let a=i+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,i),...s,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
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(`
244
244
  `)+`
245
- `}function bg(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Sg(e,t,n){const r=hg(e,t);return ya(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...No]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Eg(e,t,n){const r=yg(e,t);return ya(r,"mcp","backlog",{type:"local",command:["npx",...No]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function kg(e,t,n){const r=wg(e,t,n),o=R.existsSync(r)?R.readFileSync(r,"utf8"):"",i=vg(o,"mcp_servers.backlog",['command = "npx"',`args = ${bg(No)}`]);return R.mkdirSync(k.dirname(r),{recursive:!0}),R.writeFileSync(r,i,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function Ag(e,t,n,r){return e==="claude"?Sg(t,n):e==="opencode"?Eg(t,n):kg(t,n,r)}function _g(e,t){let n="all",r="user",o=!1,i=!1;for(let a=0;a<e.length;a++){const c=e[a];if(c==="--host")n=e[++a]??"all";else if(c==="--scope")r=e[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")i=!0;else throw new Q(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&i)throw new Q(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project"){const a=r==="global"?' — the machine-wide scope is spelled "user"':"";throw new Q(`backlog ${t}: --scope must be "user" or "project", got "${r}"${a}`)}const s=n==="all"?[...xe]:[n];for(const a of s)if(!xe.includes(a))throw new Q(`backlog ${t}: --host must be one of ${xe.join("|")}|all, got "${n}"`);return{hosts:s,scope:r,skillOnly:o,mcpOnly:i}}const ei=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
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]
246
246
 
247
247
  Installs the backlog skill AND registers the backlog MCP server into an agent
248
248
  host's config, in one step.
@@ -259,7 +259,7 @@ Examples:
259
259
 
260
260
  Back-compat: \`backlog install-skill\` remains available and behaves exactly
261
261
  like \`backlog install --skill-only\` (original --host/--scope grammar only).
262
- `;function jg(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:i,mcpOnly:s}=_g(e,"install"),a=s?[]:ga(r,o,t,n),c=i?[]:r.map(d=>Ag(d,o,t,n));return{skill:a,mcp:c}}async function Ng(e){if(e.includes("--help")||e.includes("-h")){console.log(ei);return}let t;try{t=jg(e)}catch(n){if(n instanceof Q)return jo(n,ei);throw n}for(const n of t.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of t.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(t))}const ti=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
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]
263
263
 
264
264
  Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
265
265
  process's own configured transports to the way an agent host or a script
@@ -273,12 +273,12 @@ Examples:
273
273
  backlog serve
274
274
  backlog serve --transport http --port 3300
275
275
  backlog serve --transport both --host 0.0.0.0
276
- `;function Rg(e){let t="mcp",n,r;for(let i=0;i<e.length;i++){const s=e[i];if(s==="--transport")t=e[++i];else if(s==="--port")n=Number(e[++i]);else if(s==="--host")r=e[++i];else throw new 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 o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function wa(e,t={}){if(e.includes("--help")||e.includes("-h")){console.log(ti);return}let n;try{n=Rg(e)}catch(s){if(s instanceof Q)return jo(s,ti);throw s}const r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=fa({...n,...t,signal:r.signal}),i=t.namespace==="sandbox"?R.mkdtempSync(k.join(z.tmpdir(),"backlog-sandbox-logs-")):void 0;try{qn.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...i!==void 0?{logDir:i}:{}})}catch(s){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${s instanceof Error?s.message:String(s)}); telemetry records will be silently dropped this process`)}await o}const Og=["input","data"];function Tg(e){let t;for(let n=0;n<e.length;n++){const r=e[n];if(r!==void 0)if(r==="--input"){const o=e[n+1];o!==void 0&&(t=o)}else r.startsWith("--input=")&&(t=r.slice(8))}return t}function Ig(e){let t;try{t=JSON.parse(e)}catch{return}if(!(t===null||typeof t!="object"||Array.isArray(t)))return t}function $g(e,t){let n=0;for(;n<e.length&&e[n]!==void 0&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=e.slice(0,r).join(" ");for(const i of t){const s=Ne(i).cli.path;if(s.join(" ")===o)return{op:i,path:s}}}}function Cg(e,t){var a,c,d;const n=(a=e.path[e.path.length-1])==null?void 0:a.raw;if(!n)return;const r=t[n];if(!r)return;const o=r.input,i=(c=o.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:o}}function Pg(e,t,n){if(e.includes("--help")||e.includes("-h"))return;const r=Tg(e);if(r===void 0)return;const o=Ig(r);if(!o)return;const i=$g(e,t);if(!i)return;const s=Cg(i.op,n),a=(s==null?void 0:s.schema.properties)??{},c=Og.filter(d=>Object.prototype.hasOwnProperty.call(o,d)&&!Object.prototype.hasOwnProperty.call(a,d));if(c.length!==0)return{wrapperKeys:[...c],commandLabel:i.path.join(" "),exampleJson:s?JSON.stringify(Ue(s.schema,s.root)):void 0}}function Lg(e){const t=e.wrapperKeys.map(r=>`"${r}"`).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 Ro=["limit","offset","sort","direction"],va=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],Oo=["status","priority"],Jt=["fields"],xg={"claimed-by":"claimedBy","project-path":"projectPath"},ba=[...Ro,...Jt,...va,...Oo].map(e=>`--${e}`).sort(),Ug=new Set([...Ro,...Jt]),Dg=new Set([...Oo,...Jt]),Mg=new Set([...Ro,...Jt,...va,...Oo]),Fg=new Set(["limit","offset"]),Sa=['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 ni(e,t,n,r){if(!r){e[t]=n;return}const o=e[t]??[];e[t]=[...o,...n.split(",").map(i=>i.trim()).filter(i=>i.length>0)]}function Ea(e){if(e.includes("--help")||e.includes("-h"))return{kind:"help",text:Sa};const t={},n={};let r,o=0;for(;o<e.length;){const a=e[o];if(!a.startsWith("--")){if(r!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};r=a,o+=1;continue}let c=a.slice(2),d;const l=c.indexOf("=");if(l!==-1&&(d=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!Mg.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${ba.join(", ")}`};o+=1;let u;if(d!==void 0)u=d;else{if(o>=e.length)return{kind:"error",message:`Missing value for --${c}`};u=e[o],o+=1}const f=Dg.has(c);Ug.has(c)?ni(t,c,u,f):ni(n,xg[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 Fg){const c=t[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(t[a]=Number(c))}const i=n.anchor;if(i!==void 0&&r!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(i===void 0&&r===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const s={...t};return i!==void 0?s.view="similar":s.text=r,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function ka(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 Ne(t).cli.path.slice(0,-1)}const oi=[jt];function Bg(e,t,n){const r={host:n,operations:t},o=new Set;for(const i of e){const s=i.capabilities.mount;if(!s)continue;const a=s.operations(r,void 0,void 0);for(const c of a){const[d]=Ne(c).cli.path;d!==void 0&&o.add(d)}}return o}function Aa(e,t,n){var o;return e.length===0?[...e]:(o=e[0])!=null&&o.startsWith("-")?[...e]:e[0]!==void 0&&n.has(e[0])?[...e]:t.length>0&&t.every((i,s)=>e[s]===i)?[...e]:[...t,...e]}function To(e){const t=[],n=[];let r=!1;for(let i=0;i<e.length;i++){const s=e[i];if(s!==void 0){if(s.startsWith("--namespace=")){const a=s.slice(12);a===""?r=!0:t.push(a);continue}if(s==="--namespace"){const a=e[i+1];a===void 0||a.startsWith("-")?r=!0:(t.push(a),i++);continue}n.push(s)}}const o=new Set(t);return{argv:n,namespace:t[t.length-1],missingValue:r,conflicting:o.size>1}}async function qg(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=ye(s);return}const n=k.join(Wt(),"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=ye(s);return}const r=k.resolve(t),{buildBakedOperations:o}=await Promise.resolve().then(()=>Ta),i=await o(n);await ng({apiDts:n,outFile:r,extractorVersion:Eo,operations:i}),console.log(JSON.stringify({ok:!0,out:r,operations:i.length}))}async function _a(e,t={}){var b;const{argv:n,namespace:r,missingValue:o,conflicting:i}=To(e??process.argv.slice(2)),s={...t};if(o){const h=ie("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=ye(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=ye(w);return}if(r!==void 0&&!((b=Fe.namespaces)!=null&&b.includes(r))){const h=Fe.namespaces??[],y=As(r,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=ye(v);return}r!==void 0&&(s.namespace=r);const a=s.namespace??"production";s.adhdRoot===void 0&&process.env.ADHD_ROOT&&(s.adhdRoot=process.env.ADHD_ROOT);const c=h=>h.includes(`${k.sep}backlog-sandbox-`);if(a==="sandbox"){s.adhdRoot!==void 0&&!c(s.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${s.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),s.adhdRoot=void 0),s.adhdRoot===void 0&&(s.adhdRoot=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
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
278
278
  # an absence-of-file default. embedding.enabled is off so a sandboxed
279
279
  # run never pays a real model-load cost or opens a real vector store.
280
280
  embedding:
281
281
  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=Pe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:Je(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await qg(n.slice(1));return}if(n[0]==="store-check"){const h=Pe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=Je(h);let w;try{w=await Tt(y,h.config.db.busyTimeoutMs);const{total:v,observed:S}=await Vi(w.adapter);console.log(JSON.stringify({ok:!0,dbPath:y,total:v,kinds:S,expectedKinds:[...io]}));return}catch(v){if(v instanceof Hi){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}throw v}finally{w&&await Cn(w)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present; non-zero on a mismatch"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await ha(n.slice(1));return}if(n[0]==="install"){await Ng(n.slice(1));return}if(n[0]==="serve"){await wa(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(Ao()));return}let l;if(n[0]==="search"){const h=Ea(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=Pe({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=await Tt(Je(h),h.config.db.busyTimeoutMs);u={store:y,ctx:{store:y,env:h}}}return u.ctx};let m;const p=()=>(m||(m=Cn(u==null?void 0:u.store)),m),g=cs(p);try{const{pkg:h,operations:y}=await _o(f,{adhdRoot:s.adhdRoot}),w=l??n,v=ka(y),S=Bg(oi,y,h.id),E=Aa(w,v,S),A=Pg(E,y,h.schemas);if(A){const N=ie("invalid_argument",Lg(A));console.error(JSON.stringify(N)),process.exitCode=ye(N);return}await Bn(kl)({packages:[h],operations:y,outputDir:"",options:{argv:E,usePlugins:[...oi],exitCode:N=>Is(N)?ye(N):void 0},signal:s.signal??new AbortController().signal,logger:la()});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:
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:
283
283
  - 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 ja(e){return e==="status"?"has_status":"has_priority"}function Na(e){return new RegExp("\\p{L}","u").test(e)&&e===e.toUpperCase()}function Kg(e){return e===e.toLowerCase()}function Ra(e,t){return e==="status"?Kg(t):Na(t)}function ri(e){if(e===null)return{};try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:{}}catch{return{}}}function ii(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}async function si(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 ln(e,t){return await e.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ?",[t])??null}function Hg(e,t){const n=[],r=[],o=[["status",e],["priority",t]];for(const[i,s]of o){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=>Ra(i,m.name??""));if(l===void 0&&i==="status"){r.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:r,at:U()}}function Oa(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 Vg(e,t){return V(e,async n=>{const r=[];for(const o of t.groups){const i=await si(n,o.canonicalUid);if(!i)continue;Oa(i.kind,i.uid);const s=ja(i.kind),a=await x(n,s),c=Y(i.name??""),d=ri(i.meta),l=i.name??"";if(i.kind==="status"&&!Ra("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 o.fragmentUids){const S=await si(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"&&!Na(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=ri(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 me(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 L(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??"",...ii(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]),r.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=[...ii(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:r,at:t.at}})}async function Gg(e,t){await V(e,async n=>{const r=U(),o=new Map;for(const i of t.entries)i.canonicalMetaBefore!==void 0&&!o.has(i.canonicalUid)&&o.set(i.canonicalUid,i.canonicalMetaBefore);for(const i of t.entries){const s=await ln(n,i.fragmentUid),a=await ln(n,i.canonicalUid);if(!s||!a)continue;Oa(s.kind,s.uid);const c=ja(s.kind),d=await x(n,c);for(const l of i.repointedEdges){await me(n,{srcRowid:l.srcRowid,dstRowid:a.rowid,rel:l.rel,reason:"catalog-case-fragment-merge-reverse",at:r});const u=await ee(n,l.srcRowid);u&&await L(n,{at:r,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 o){const a=await ln(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)===tt.pathToFileURL(R.realpathSync(process.argv[1])).href){const{namespace:e,argv:t}=To(process.argv.slice(2)),n=t[0]==="ir-artifact",r=e==="sandbox"?R.mkdtempSync(k.join(z.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{qn.initTelemetry({service:"backlog",role:"cli",logSink:"file",...r!==void 0?{logDir:r}:{}})}catch(o){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${o instanceof Error?o.message:String(o)}); telemetry records will be silently dropped this process`)}_a().catch(o=>{console.error(o instanceof Error?o.stack??o.message:String(o)),process.exitCode=1})}const Wg=Eo,Io="backlog";function $o(e,t){return{sourceFile:e,namespace:Io,tsconfig:t,dropFileSegment:!0}}function Jg(e={}){return gf(e)}function zg(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function Yg(e={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:Ym({cache:Jg(e),extractorVersion:Wg})}}}}let ai;function Xg(e={}){return ai??(ai=sd(zg()?[Yg(e)]:[],t=>{var n;return Ni($o(t.source,typeof((n=t.extractorOptions)==null?void 0:n.tsconfig)=="string"?t.extractorOptions.tsconfig:void 0))})),ai}async function Qg(e){return Ni($o(e))}async function Zg(e={}){const t=k.join(Wt(),"api.d.ts");return Xg(e)({source:t,host:"ts",namespace:Io,extractorOptions:{}})}const Ta=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:Io,buildBacklogExtractOptions:$o,buildBakedOperations:Qg,extractApiOperationsLive:Zg},Symbol.toStringTag,{value:"Module"}));exports.BACKLOG_ERROR_CODES=Os;exports.BACKLOG_EXIT_CODE=bo;exports.RESERVED_TERMINAL_STATUS_NAMES=Kt;exports.RagNotConfiguredError=$s;exports.SEARCH_FLAGS=ba;exports.SEARCH_HELP=Sa;exports.applyCaseFragmentMerge=Vg;exports.applyTerminalBackfill=zl;exports.backlogEnvironmentSpec=Fe;exports.buildBacklogApigenPackage=_o;exports.buildBacklogEnv=Pe;exports.buildSearchArgv=Ea;exports.catalogNameFold=Y;exports.claim=ea;exports.closeGraphBacklogStore=as;exports.create=Xs;exports.delete=oa;exports.embeddingStatus=zs;exports.errorEnvelope=ie;exports.exitCodeForEnvelope=ye;exports.get=Hs;exports.installSkill=ma;exports.isBacklogErrorCode=Ts;exports.isOutcomeEnvelope=Is;exports.isOutcomeError=Zp;exports.isOutcomeOk=Qp;exports.lookup=Ys;exports.move=na;exports.okEnvelope=So;exports.openCurve=Js;exports.openGraphBacklogStore=Tt;exports.partOfRollup=Ws;exports.planCaseFragmentMerge=Hg;exports.planTerminalBackfill=Jl;exports.prefixCommand=Aa;exports.priorityMatrix=Gs;exports.query=Vs;exports.readBacklogVersionInfo=Ao;exports.relate=ta;exports.resolveBacklogDbPath=Je;exports.resolveBacklogScope=yo;exports.resolveCommandPrefix=ka;exports.resolveExpectedMcpToolNames=dg;exports.reverseCaseFragmentMerge=Gg;exports.reverseTerminalBackfill=Yl;exports.rmLocation=aa;exports.runBacklogCli=_a;exports.runInstallSkillCommand=ha;exports.runServeCommand=wa;exports.startBacklogServer=fa;exports.stripNamespaceFlag=To;exports.suggestClaimantIdentity=mf;exports.transition=Zs;exports.update=Qs;exports.upsertComponent=ia;exports.upsertLocation=sa;exports.upsertProject=ra;
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;