@adhd/backlog 1.0.3 → 1.0.4
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/CHANGELOG.md +10 -0
- package/api.ir.json +1 -1
- package/index.js +41 -41
- package/index.mjs +1107 -1080
- package/package.json +1 -1
- package/write/catalog.d.ts +23 -11
- package/write/errors.d.ts +37 -1
package/index.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("node:fs"),z=require("node:os"),k=require("node:path"),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"),Ma=require("@adhd/sox-graph-store"),Pt=require("node:fs/promises"),pe=require("node:crypto"),Da=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 Mo 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 Mo(`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 Mo("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",Ja="0.1.0";function Do(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 Je(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 Je(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?Je(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=Wa(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 Wa(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 Je(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=>Je(o,{},n));if(ui(e)){const o={};for(const[i,s]of Object.entries(e))s!==void 0&&(o[i]=Je(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=Do(e,r);return Ie(t,n,o)},decode(t,n,r){const o=Do(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)}},Jn={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 Wn={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,Jn,Wn,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,Jn.id,Wn.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 le=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=le("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"}},Jo={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Wo(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(Jo,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:Jo[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=le("ts-json-schema-generator"),dt)}let Ke;function Ic(){if(Ke)return Ke;try{const e=k.dirname(le.resolve("ts-json-schema-generator/package.json"));Ke=le(le.resolve("typescript",{paths:[e]}))}catch{Ke=le("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 Mc(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 Dc(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}=le("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}=le("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 Mc(d),Dc(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??Wo(t),f||o.aliasCache.set(t,s)}else s=Wo(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 Jc(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 Wc(){return lt||(lt=le("ts-morph").SyntaxKind,lt)}function xt(e){try{if(!e)return;const t=Wc();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=de(ed(c)),l=o?null:d,u=de(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]:[],de(g),de(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]:[],de("default"),de(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]:[],de(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=de(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&&Jc(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=de(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 de(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 D 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 se(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 Mt=new ci({allErrors:!0});Ua(Mt);for(const e of[je,Hn,pn,mn,"discriminator"])Mt.addKeyword({keyword:e,valid:!0});Mt.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=Mt.compile(i.input);if(!a(s)){const d=a.errors??[];throw new D("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=se(n)?n:new D("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 Dt(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,Jn,Wn,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:Ja,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 se(e)?e:e instanceof Error?new D("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 Md(){}function Dd(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Md};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=Dd(r.signal,i);try{const a=s.signal?{...r,signal:s.signal}:r,c=await e(t,a,o);if(Dt(c)){const d=await 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 ce(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 Jd(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 Wd(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)||Jd(i))&&(s="json");const a=Wd(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 ue(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 Me(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
|
|
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
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
|
|
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(" ")}
|
|
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
|
|
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.
|
|
8
8
|
expected node kind(s): ${n.join(", ")}
|
|
9
9
|
found in store: ${r}
|
|
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
|
|
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,
|
|
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
|
|
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
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
|
|
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)
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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({...
|
|
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
|
|
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
|
|
37
|
-
`)}class
|
|
38
|
-
${t}`.trim()}function Ot(e,t){const n=e.embedding;if(!n)return Promise.resolve();const r=
|
|
39
|
-
`}return`sha256-${fs(n)}`}function
|
|
40
|
-
`);return`sha256-${fs(n)}`}function $u(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function Cu(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Pu(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]=Lu(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 Lu(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 xu="adhd-env-ref:";function Uu(e){return`${xu}${e}`}const Mu=[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],Du=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function ne(e,t){return(e>>>t|e<<32-t)>>>0}function Fu(e){const t=Uint32Array.from(Du),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=ne(S,7)^ne(S,18)^S>>>3,_=ne(E,17)^ne(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=ne(b,6)^ne(b,11)^ne(b,25),E=b&h^~b&y,A=w+S+E+Mu[v]+c[v]>>>0,_=ne(f,2)^ne(f,13)^ne(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 Bu(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 Bu(Fu(t))}const{parse:qu}=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=qu(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:ps(n)}catch{return}}function Ku(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 Hu=[["system","system"],["global","global"],["project","project"],["local","local"]];function Vu(e,t,n,r){const o={},i={},s={},a={};for(const c of Object.keys(e)){const d=e[c],l=d.env&&d.env!==""?d.env:Cu(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 Hu){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?Uu(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 Gu(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 Ju(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=o.scope??t.activeScope,s=o.share??Ou[o.kind],a=o.path?Gu(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 Wu(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 zu(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(Yu(i.errors??[]))}function Yu(e){return e.map(t=>({field:Xu(t),message:t.message??"is invalid",keyword:t.keyword}))}function Xu(e){var r;const t=(e.instancePath??"").replace(/^\//,"").replace(/\//g,".");return t||(((r=e.params)==null?void 0:r.missingProperty)??"(root)")}function Qu(e,t){return k.join(ds(e,t),Ru)}const Zu=384,ef=448;function tf(e,t,n={}){const r=n.mode??Zu,o=n.dirMode??ef,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 nf="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 of(){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??ju,o=t.envPrefixOverride??$u(e),i=t.namespaces&&t.namespaces.length>0?t.namespaces:[Nu],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}=Eu({scope:n.scope,cwd:n.cwd},a),l=Au({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 rf(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=Ku(c),u=n.instanceId??of(),{raw:f,nested:m,typedRaw:p,provenance:g,fields:b}=Vu(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=Pu(t.config);zu(ms(p),y);const w=Ju(t.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:r}),v=Wu(t.files,w);return{version:_u,libraryVersion:nf,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:Tu(Object.fromEntries(Object.entries(p).map(([E,A])=>[E,String(A)]))),structureHash:Iu(Object.values(w).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(w),files:Object.values(v),provenance:g}}class Qe extends Error{constructor(t){super(t),this.name="EnvironmentError"}}class sf extends Qe{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class af extends Qe{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function cf(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 df(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 lf(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=rf(t,n,r);const s=ho(t,n,r);i=Qu(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 sf(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 cf(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"){lf(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 af(t,r):s}R.writeSync(o,`${process.pid}
|
|
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}
|
|
41
41
|
${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
|
|
43
|
-
`)}]}}function
|
|
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}
|
|
44
44
|
|
|
45
|
-
`}function
|
|
45
|
+
`}function vf(e){return`event: error
|
|
46
46
|
data: ${e}
|
|
47
47
|
|
|
48
|
-
`}async function
|
|
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
|
|
49
49
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
50
50
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
51
51
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
@@ -119,7 +119,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
119
119
|
|
|
120
120
|
const transport = new StdioServerTransport()
|
|
121
121
|
server.connect(transport)
|
|
122
|
-
`}function
|
|
122
|
+
`}function Pf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
123
123
|
import { createServer } from 'node:http'
|
|
124
124
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
125
125
|
${e==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
|
|
@@ -195,31 +195,31 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
195
195
|
const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
|
|
196
196
|
const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
|
|
197
197
|
httpServer.listen(${t}, () => console.error('MCP ${e} server on port ${t}'))
|
|
198
|
-
`}function Un(e){return{raw:e,words:Ye(e)}}function
|
|
199
|
-
`)}function Pf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.toolDescriptions??{},o=e.operations,i=Cf(e.packages,r,o),s=t==="stdio"?Tf():If(t,n);return{files:[{path:"index.ts",content:i},{path:"server.ts",content:s}]}}async function Lf(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 xf=Object.freeze({type:"object",properties:{}});class Uf{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.cachedList=void 0,this.toolMeta.set(t,n)}registerRoute(t,n){this.cachedList=void 0,this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){if(this.cachedList)return this.cachedList;const t=[...this.plans.keys()].map(n=>{const r=this.toolMeta.get(n);return Object.freeze({name:n,description:(r==null?void 0:r.description)??n,inputSchema:(r==null?void 0:r.inputSchema)??xf,...r!=null&&r.outputSchema?{outputSchema:r.outputSchema}:{}})});return this.cachedList=Object.freeze(t),this.cachedList}readCall(t,n){const r={};for(const i of n.envelope){const s=t.meta[i.mcpMetaKey];s!==void 0&&(r[i.field]=s)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(Dt(n)){t.output=await Lf(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 se(n)&&n.code,n}}function Mf(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 Df(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 Ff(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=ue(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=>Me(_,w,O,v))}}const c=((f=e.packages[0])==null?void 0:f.id)??"ts",d=ue(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=Df(o,i,c,e.operations??[],l);if(u.length>0){const p=ue({},o),g={fns:{},schemas:{}};for(const b of u){const h=ve({op:b,transport:"mcp",projection:n}),y=Mf(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=>Me(h,p,v,g))}}}function Bf(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 se(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 D("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 D("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 qf(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 Kf(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 Uf;Ff(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=Bf(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"),qf(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 Hf={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 Pf(e)},run(e){return Kf(e)}},bs=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Ss=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],Vf=new Set([...bs,...Ss]);function Gf(e){return Vf.has(e)}const rt=["uid","kind","title","status","priority"],oe=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 Jf(e,n));return n}async function Jf(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 Wf(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 zf(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 zf(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 Yf(e,t){return(await e.queryNodes({kind:t,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function Xf(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:Xf(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 Yf(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 Qf(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(!Gf(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 Zf(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 ep(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 tp(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 np(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 op(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 rp(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 Zf(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 ep(e,t.id,m)),d&&m&&(o.notes=await tp(e,t.id,m)),l&&m&&(o.auditTrail=await np(e,t.id,m)),u&&(o.blockers=await op(e,t.id)),f&&m&&(o.related=await rp(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 ip=.0050125;function sp(e){if(e===void 0)return Es;if(!Number.isInteger(e)||e<=0||e>oe)throw new Re("limit",`must be a positive integer ≤ ${oe}, got ${e}`);return e}async function ap(e,t){const n=new Set;for(const r of t.refs){const o=await Wf(e,{rel:t.rel,expectedKind:t.expectedKind,ref:r});if(o)for(const i of o)n.add(i)}return n}async function cp(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 dp(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 lp(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 dp(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 cp(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 ap(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]}));const o=lp(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 up=4;async function fp(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 pp(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??ip}],filters:n},o=[];let i=t.limit;for(let a=0;a<up;a++){const c=await e.search.backend.searchRanked(r,i);if(o.length=0,o.push(...await fp(e.graph,c)),o.length>=t.limit||c.length<i)break;i*=2}return o.slice(0,t.limit)}async function mp(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=sp(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
|
|
201
|
-
`)}function
|
|
202
|
-
`:`${e.map(
|
|
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(`
|
|
203
203
|
|
|
204
204
|
`)}
|
|
205
|
-
`}function Mn(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 Dn(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 bp(e,t){if((t==null?void 0:t.project)!==void 0){const r=await B(e,"project",t.project);return r?[Mn(r.record)]:[]}return(await e.queryNodes({kind:"project",liveOnly:!0})).map(Mn)}async function Sp(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(Dn):[]}return(await e.queryNodes({kind:"component",liveOnly:!0})).map(Dn)}async function Ep(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 J("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{...Mn(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 J("project",y);return qe(e,N.uid,t.name)})():await B(e,"component",t.name);if(!w)throw new J("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{...Dn(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 J("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 kp(e){try{return new URL(e),!0}catch{return!1}}function Ap(e){return kp(e)?"url":e.includes("/")||e.includes(".")||e.startsWith("~")?"path":"tool"}async function _p(e,t){var f,m,p,g,b,h;const n=Ap(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:oe+1});i=y.length>oe;const v=(i?y.slice(0,oe):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 J("location",i?`${t} (path suffix/prefix fallback scanned only the first ${oe} 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 J("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>oe)throw new Re("limit",`must be a positive integer ≤ ${oe}, got ${e}`);return e}function jp(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 Np(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 Np(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 Qf(n)}function Rp(e){if(!e)return;const t={};return e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until})),Object.keys(t).length>0?t:void 0}function Op(e){if(e==="created")return"tCreated";if(e==="updated")return"tValid"}async function Tp(e,t,n){const r=await Promise.all(t.map(d=>e.getEdges({src:d.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(d=>d.map(l=>l.dst)))],i=o.length>0?await e.getNodesByIds(o):[],s=new Map(i.map(d=>{var l;return[d.id,typeof((l=d.metadata)==null?void 0:l.rank)=="number"?d.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;t.forEach((d,l)=>{var f;const u=(f=r[l][0])==null?void 0:f.dst;a.set(d.id,u!==void 0?s.get(u)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...t].sort((d,l)=>a.get(d.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function Ip(e,t){var w,v,S,E,A,_,N,j,O,I,C,K;const{graph:n}=e;jp(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=Rp(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 M,P;const Y=t.offset??0,zt=Y+r;if(a!==void 0){const H=await n.searchNodes(a,{limit:zt,filter:d});P=new Set(H.map(ae=>ae.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 ae={vec:await e.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Lo=await e.search.backend.searchRanked(ae,zt);M=P?Lo.filter(xa=>P.has(xa.id)):Lo}else P&&(M=(await n.searchNodes(a,{limit:zt,filter:d})).map(ae=>({id:ae.id,score:ae.score,fields:{}})));const Yt=(M??[]).map(H=>H.id).slice(Y,Y+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((M??[]).map(H=>{var ae;return[(ae=Co.get(H.id))==null?void 0:ae.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-Y,r),La=Y+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=Op(t.sort),u={...d,limit:r+1,...t.after!==void 0?{after:Number(t.after)}:{},...l&&t.after===void 0?{orderBy:l,orderDir:t.direction??"desc"}:{},...t.after===void 0&&t.offset!==void 0?{offset:t.offset}:{}};let f=await n.queryNodes(u);t.sort==="priority"&&t.after===void 0&&(f=await Tp(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 $p(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 Cp(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 Pp=["blocks","relates_to","part_of"];function Lp(e){return Pp.includes(e)}async function xp(e,t){var u;const{graph:n}=e,r=it(t.limit??oe),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 Up(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(Lp(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 Up(e,t){const n=await Promise.all(t.map(a=>e.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await e.getNodesByIds(r):[],i=new Map(o.map(a=>[a.id,a])),s=new Map;return t.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=i.get(d);u&&s.set(a.id,u)}}),s}async function Mp(e,t){const{graph:n}=e,r=it(t.limit??oe),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 Dp(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 Fp(e,t){return bp(e.graph,t.filter)}async function Bp(e,t){return Sp(e.graph,t.filter)}async function qp(e,t){return Ep(e.graph,t.filter)}function Kp(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 Hp(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 Vp(e,t){const n=t.view??"list";switch(n){case"list":{const{page:r,meta:o}=await Ip(e,t);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await $p(e,t)}};case"graph":return{result:{view:"graph",graph:await xp(e,t)}};case"order":return{result:{view:"order",order:await Mp(e,t)}};case"stale":return{result:{view:"stale",items:await Cp(e,t)}};case"similar":return{result:{view:"similar",items:await mp(e,t)}};case"overlap":return{result:{view:"overlap",groups:await Dp(e,t)}};case"projects":return{result:{view:"projects",items:await Fp(e,t)}};case"components":return{result:{view:"components",items:await Bp(e,t)}};case"locations":return{result:{view:"locations",items:await qp(e,t)}};default:{const r=n;throw new Re("view",`unknown view "${r}"`)}}}const Gp=["list","ready","stale","similar"];async function Jp(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=Hp(e,t),r=await Vp(e,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:i}=o;if(i!=="list"&&i!=="ready"&&i!=="stale"&&i!=="similar")throw new T("format",`"markdown" is only supported for view:${Gp.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:vp(s)},meta:r.meta}}const Os=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],Wp=new Set(Os);function Ts(e){return typeof e=="string"&&Wp.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 zp(e){return e.ok===!0}function Yp(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 re(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 Xp 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 Qp(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 Zp(e,t,n,r=i=>console.error(i),o){const i=Ge.get(e);if(i)return i;const s=nm(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 em(e){const t=It.get(e);if(t)return{present:!0,embedding:t.embedding,search:t.search}}function tm(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 nm(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 Xp(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 Qp(l,d.modelId)}},embedding:f}}async function om(e,t){vo(t.fields);const n=t.fields??rt,r=await wo(e,t.uid);return js(e,r,n)}function rm(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}const im=["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 im)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 sm(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 am=new Set(["project","component","kind","status"]);async function cm(e,t){const n=t??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await sm(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 dm(e,t={}){var f,m,p;const{graph:n}=e;Cs(t.filter,am,"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 cm(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 lm(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 um(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 lm(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 fm=new Set(["project","component","kind"]);function pm(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 mm(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 gm(e,t){var u;const{graph:n}=e;if(Cs(t.filter,fm,"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 rm((u=f.metadata)==null?void 0:u.aliases))s.set(p,m)}const{currentStatusNameByIssue:a,auditTrailByIssue:c}=await mm(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=pm(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 Mr=["abort","force","comment"];function He(e,t){if(t===void 0||t.trim().length===0)throw new T(e,"is required")}const Dr=512;function Us(e){if(typeof e=="string"&&e.length>Dr)throw new T("gitContext",`must be at most ${Dr} characters, got ${e.length}`)}async function hm(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 ym(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 wm(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 vm(e,t){He("title",t.title),He("body",t.body),He("project",t.project),He("by",t.by),Q("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&&!Mr.includes(t.duplicateAction))throw new T("duplicateAction",`must be one of ${Mr.map(u=>`'${u}'`).join("|")}, got "${t.duplicateAction}"`);const i=await Xe(e.adapter,t.project),s=De(i),a=[];for(const u of n){const f=await hm(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 wm(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),M=`${t.title}
|
|
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}
|
|
206
206
|
|
|
207
|
-
${t.body}`,P=await
|
|
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)
|
|
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
|
|
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)
|
|
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 km(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 Am(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 Ms(e){const t=e??{};return{claimedBy:typeof t.claimedBy=="string"?t.claimedBy:void 0,claimedAt:typeof t.claimedAt=="string"?t.claimedAt:void 0}}function Ds(e,t){return e!==void 0?(Date.parse(t)-Date.parse(e))/6e4:Number.POSITIVE_INFINITY}function Fs(e,t,n){return Ds(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 Z(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 Z(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 Rm(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 Om(e,t){if(e.length>0&&!e.includes(t))throw new T("toStatus",`"${t}" is not in this project's allowed status set`)}function Tm(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 Im(e,t){bt("uid",t.uid),bt("by",t.by),Q("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=De(i);for(const a of n){const c=await Rm(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=De(a),{claimedBy:d,claimedAt:l}=Ms(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});Om(c.allowedStatuses,m.name),Tm(c.requiredFields,{status:m.name,note:t.note});const p=await Z(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 W(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 W(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 $m(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 Z(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 De(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 Cm(e,t){if(Hr("uid",t.uid),Hr("by",t.by),Q("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}=Ms(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 $m(r,i.rowid),f=Ds(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 Pm(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 Lm(e,t){if(cn("sourceUid",t.sourceUid),cn("targetUid",t.targetUid),cn("by",t.by),Q("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 Pm(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 xm(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 Z(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 Um(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 Z(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 Mm(e,t){return Gr("uid",t.uid),Gr("by",t.by),Q("by",t.by),V(e,async n=>{const r=U(),o=await be(n,t.uid),i=await xm(n,o.rowid),s=await Um(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 fo(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 Dm(e,t){dn("uid",t.uid),dn("by",t.by),Q("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&&tm(e.store.adapter);const n=t?t.current():e.env.config.embedding;return Zp(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 ee(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 Fm=[[Bt,"item_not_found"],[J,"not_found"],[T,"invalid_argument"],[Nt,"conflict"],[In,"conflict"],[Ft,"conflict"],[Yi,"precondition_failed"],[Zi,"precondition_failed"],[Qi,"precondition_failed"],[co,"precondition_failed"],[Ji,"store_busy"],[$s,"rag_not_configured"]],Bm={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function Ks(e){for(const[t,n]of Fm)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 re(n,e.message,r)}return e instanceof q?re(Bm[e.code]??"internal",e.message,{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}):re("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}):om(e.store.graph,t))}async function Vs(e,t){try{const{result:n,meta:r}=await Jp(await Gt(e,{needsSemantic:Kp(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()=>dm(await Gt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Js(e,t){return G(async()=>um(await Gt(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ws(e,t){return G(async()=>gm(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=em(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(()=>_p(e.store.graph,t.q))}async function Xs(e,t){return G(async()=>vm(await ee(e,{needsSemantic:!0}),t))}async function Qs(e,t){return G(async()=>Nm(await ee(e,{needsSemantic:!0}),t))}async function Zs(e,t){return G(async()=>Im(await ee(e,{needsSemantic:!1}),t))}async function ea(e,t){return G(async()=>Cm(await ee(e,{needsSemantic:!1}),t))}async function ta(e,t){return G(async()=>Lm(await ee(e,{needsSemantic:!1}),t))}async function na(e,t){return G(async()=>Mm(await ee(e,{needsSemantic:!1}),t))}async function oa(e,t){return G(async()=>Dm(await ee(e,{needsSemantic:!1}),t))}async function ra(e,t){return G(async()=>Yl(await ee(e,{needsSemantic:!1}),t))}async function ia(e,t){return G(async()=>Ql(await ee(e,{needsSemantic:!1}),t))}async function sa(e,t){return G(async()=>eu(await ee(e,{needsSemantic:!1}),t))}async function aa(e,t){return G(async()=>tu(await ee(e,{needsSemantic:!1}),t))}const qm=Object.freeze(Object.defineProperty({__proto__:null,claim:ea,create:Xs,delete:oa,embeddingStatus:zs,get:Hs,lookup:Ys,move:na,openCurve:Ws,partOfRollup:Js,priorityMatrix:Gs,query:Vs,relate:ta,rmLocation:aa,transition:Zs,update:Qs,upsertComponent:ia,upsertLocation:sa,upsertProject:ra},Symbol.toStringTag,{value:"Module"}));async function Km(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 Km(n)}catch(i){throw o&&await o.close().catch(()=>{}),await we.unlink(r).catch(()=>{}),i}}function Hm(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 Vm(e){return pe.createHash("sha256").update(e).digest("hex")}async function Jr(e){return Vm(await we.readFile(e,"utf8"))}async function Ct(e){try{return(await we.stat(e)).mtimeMs}catch{return}}async function Wr(e,t){const n=await Jr(e.source),r=pe.createHash("sha256");r.update(`formatVersion:${et}
|
|
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
217
|
`),r.update(`extractorVersion:${t}
|
|
218
218
|
`),r.update(`host:${e.host}
|
|
219
219
|
`),r.update(`namespace:${e.namespace??""}
|
|
220
220
|
`),r.update(`source:${n}
|
|
221
|
-
`);for(const o of bi(e.source))o!==e.source&&r.update(`dep:${o}:${await
|
|
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 Gm(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 Jm(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=Hm(e.cache),n=e.extractorVersion;async function r(o,i,s){const a=s??await Wr(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 Gm(o,s.staleness))return s.operations;const a=await Wr(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 Wm="api.ir.json",zm=Kn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href),Eo=zm("@adhd/apigen-core-client/package.json").version;function Jt(){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 Ym(e){return k.join(e,Wm)}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 Xm(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 Qm(e){try{const t=Ym(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 Xm(s,da(e))?n.operations:void 0}catch{return}}async function Zm(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 eg(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 tg=e=>e instanceof Error?e.message:String(e),Yr=e=>({enabled:e.enabled===!0,provider:e.provider,model:e.model}),ng=(e,t)=>e.enabled===t.enabled&&e.provider===t.provider&&e.model===t.model;function og(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 (${tg(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(),ng(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 rg(){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=rg(),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 ig(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 sg(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 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 r=Qm(t);return r||(await Promise.resolve().then(()=>Ta)).extractApiOperationsLive(e)}async function _o(e,t={}){const n=typeof e=="function"?e:()=>e,r=await ag(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);ig(s);const{version:a}=Ao();return{pkg:{id:"backlog",version:a,schemas:i,importPath:k.join(Jt(),"api.js"),fns:qm,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=We(t),i=()=>(n||(n=Cn(r)),n),s=vu()?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:og({baseline:t,rebuild:()=>Pe({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),layerFiles:()=>eg({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(Af)({packages:[c],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[Of,jt]},signal:e.signal,operations:d,logger:l})),(e.transport==="mcp"||e.transport==="both")&&u.push(Bn(Hf)({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"],cg={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 dg(e,t,n,r){if(t==="project")return k.join(n,cg[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 lg(){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 X 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]
|
|
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]
|
|
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
|
|
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
|
|
238
|
-
`,"utf8")}function
|
|
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
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(`
|
|
240
240
|
`)+`
|
|
241
241
|
`;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
|
|
242
242
|
`)+`
|
|
243
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(`
|
|
244
244
|
`)+`
|
|
245
|
-
`}function
|
|
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]
|
|
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
|
|
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]
|
|
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
|
|
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(!
|
|
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
|
|
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:
|
|
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:
|
|
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
|
|
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;
|