@adhd/backlog 1.0.4 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/README.md +194 -39
- package/api.d.ts +87 -0
- package/api.ir.json +1 -1
- package/citation.d.ts +176 -0
- package/envelope.d.ts +36 -2
- package/index.d.ts +23 -3
- package/index.js +105 -57
- package/index.mjs +11450 -6758
- package/ir-artifact.d.ts +7 -3
- package/lifecycle.d.ts +49 -0
- package/package.json +5 -5
- package/query/canonical.d.ts +16 -0
- package/query/card.d.ts +116 -4
- package/query/get.d.ts +8 -1
- package/query/index.d.ts +1 -0
- package/query/query.d.ts +32 -22
- package/query/redirect.d.ts +30 -0
- package/query/resolve.d.ts +75 -0
- package/query/similar-clusters.d.ts +8 -0
- package/query/similarity-signals.d.ts +47 -0
- package/query/spec-staleness.d.ts +21 -0
- package/query/types.d.ts +249 -34
- package/query/verdict-core.d.ts +21 -0
- package/query/verdict.d.ts +22 -0
- package/query/views/catalog.d.ts +47 -0
- package/query/views/registry.d.ts +27 -7
- package/query/views/report.d.ts +49 -0
- package/query/views/semantic.d.ts +28 -5
- package/query/views/stats.d.ts +38 -2
- package/readiness.d.ts +29 -0
- package/retry-policy.d.ts +44 -0
- package/serve.d.ts +1 -1
- package/server.d.ts +71 -3
- package/service-config.d.ts +109 -0
- package/service-errors.d.ts +51 -0
- package/skill/SKILL.md +688 -81
- package/store/catalog-invariant-guard.d.ts +13 -7
- package/vocabulary.d.ts +48 -0
- package/write/anchor-check.d.ts +139 -0
- package/write/attestation.d.ts +64 -0
- package/write/catalog-merge.d.ts +15 -8
- package/write/catalog.d.ts +72 -2
- package/write/citation-path.d.ts +31 -0
- package/write/citation.d.ts +157 -0
- package/write/create-issue.d.ts +143 -29
- package/write/errors.d.ts +196 -1
- package/write/gate.d.ts +67 -0
- package/write/merge-project.d.ts +54 -0
- package/write/obligation.d.ts +133 -0
- package/write/relate.d.ts +1 -1
- package/write/revision.d.ts +27 -0
- package/write/similarity-scan.d.ts +84 -0
- package/write/spec-revision.d.ts +131 -0
- package/write/spec-revision.reconcile.d.ts +48 -0
- package/write/transition.d.ts +13 -2
- package/write/tx.d.ts +44 -2
- package/write/uid-prefix.d.ts +78 -0
- package/write/update.d.ts +23 -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"),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
|
|
4
|
-
`)}]}}function
|
|
5
|
-
`)}function
|
|
2
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("node:fs"),te=require("node:os"),_=require("node:path"),Ct=require("node:url"),Jo=require("@adhd/sox-telemetry"),Gt=require("pino"),qs=require("ajv"),Sl=require("ajv-formats"),Ne=require("@adhd/sox-store-adapter"),kl=require("@adhd/sox-graph-store"),zo=require("node:fs/promises"),ke=require("node:crypto"),_l=require("fastify"),zi=require("node:http"),Al=require("@modelcontextprotocol/sdk/server/index.js"),Nl=require("@modelcontextprotocol/sdk/server/stdio.js"),Rl=require("@modelcontextprotocol/sdk/server/sse.js"),jl=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Yi=require("@modelcontextprotocol/sdk/types.js"),Hs=require("node:child_process"),Tl=require("@adhd/sox-hybrid-search"),Yo=require("node:module"),Ol=require("yaml");var B=typeof document<"u"?document.currentScript:null;function Vs(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const ao=Vs(_),Te=Vs(zo),co="$apigen";class Xi extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Il(t){const e=new Map;return{register(i,o){if(e.has(i.id)&&!(o!=null&&o.override))throw new Xi(`E_DUP_CODEC: a codec is already registered for id "${i.id}"`);e.set(i.id,i)},resolve(i){for(const o of e.values())if(o.matches(i))return o},get(i){return e.get(i)},ids(){return[...e.keys()]},freeze(){const i=new Map(e),o={register(){throw new Xi("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(r){for(const s of i.values())if(s.matches(r))return s},get(r){return i.get(r)},ids(){return[...i.keys()]},freeze(){return o}};return o}}}const Fe="x-apigen-logical",Xo="x-apigen-codec",lo="x-apigen-ctor",uo="x-apigen-tojson",$l="0.1.0";function Qi(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...e}}function We(t,e,n){const i=n.registry.resolve(e);if(i)return i.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return We(t,a,n)}const r=e.oneOf;if(Array.isArray(r)){const a=Gs(t,r,e,n);return We(t,a,n)}const s=e.type;if(s==="array"){if(!Array.isArray(t))return St(t,e,n);const a=e.items;if(!a)return t.map(d=>De(d));const c=n.path;return Array.isArray(a)?t.map((d,l)=>{const u=a[l];return u===void 0?De(d):We(d,u,{...n,path:`${c}/${l}`})}):t.map((d,l)=>We(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return St(t,e,n);const a=e.properties;if(!a)return De(t);const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=t[l];f!==void 0&&(d[l]=We(f,u,{...n,path:`${c}/${l}`}))}return d}return s==null?St(t,e,n):De(t)}function Je(t,e,n){const i=n.registry.resolve(e);if(i)return i.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Je(t,a,n)}const r=e.oneOf;if(Array.isArray(r)){const a=Gs(t,r,e,n);return Je(t,a,n)}const s=e.type;if(s==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((d,l)=>{const u=a[l];return u===void 0?d:Je(d,u,{...n,path:`${c}/${l}`})}):t.map((d,l)=>Je(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=t[l];f!==void 0&&(d[l]=Je(f,u,{...n,path:`${c}/${l}`}))}for(const[l,u]of Object.entries(t))!(l in a)&&u!==void 0&&(d[l]=u);return d}return s==null?fo(t,n):t}function Gs(t,e,n,i){var c;const o=n.discriminator;if(o!=null&&o.propertyName){const d=o.propertyName,l=t!==null&&typeof t=="object"?t[d]:void 0;if(typeof l=="string"){if(o.mapping){const u=o.mapping[l];if(u){const f=e.find(m=>m.$ref===u);if(f)return f}}for(const u of e){const m=(c=un(u,i).properties)==null?void 0:c[d];if(!m)continue;const p=m.enum;if(m.const===l||Array.isArray(p)&&p.includes(l))return u}}}const r=Cl(t,e,i);if(r)return r;let s,a=-1;for(const d of e){const l=un(d,i),u=Qo(t,l,i);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:e[0]??{}}function un(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Zi(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function Cl(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const i=t,o=e.map(s=>un(s,n)),r=new Set;for(const s of o){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))Zi(d)!==void 0&&r.add(c)}for(const s of r){const a=o.map(f=>{const m=f.properties,p=m==null?void 0:m[s];return p?Zi(p):void 0}),c=a.filter(f=>f!==void 0),d=new Set(c);if(c.length<2||d.size!==c.length)continue;const l=i[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&Qo(t,o[u],n)!==null)return e[u]}}function Pl(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function Qo(t,e,n){const i=e.oneOf;if(Array.isArray(i)){let l=null;for(const u of i){const f=Qo(t,un(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,r=Pl(t);if(typeof o=="string"){if(!(o===r||o==="number"&&r==="integer"))return null}else if(Array.isArray(o)&&!o.some(u=>u===r||u==="number"&&r==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const s=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(s[l]===void 0)return null;c+=2}}const d=e.properties;if(d){for(const l of Object.keys(d))s[l]!==void 0&&(c+=1);for(const l of Object.keys(s))d[l]===void 0&&(c-=1)}return c}function St(t,e,n){var i;for(const o of n.registry.ids()){const r=n.registry.get(o);if((i=r==null?void 0:r.ownsValue)!=null&&i.call(r,t))return{[co]:o,v:r.encode(t,r.schema,n)}}if(Array.isArray(t))return t.map(o=>St(o,{},n));if(Ws(t)){const o={};for(const[r,s]of Object.entries(t))s!==void 0&&(o[r]=St(s,{},n));return o}return De(t)}function Ws(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function fo(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&co in t){const n=t,i=n[co],o=e.registry.get(i);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>fo(n,e));if(Ws(t)){const n={};for(const[i,o]of Object.entries(t))n[i]=fo(o,e);return n}return t}function De(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(De);if(typeof t=="object"){const e={};for(const[n,i]of Object.entries(t))i!==void 0&&(e[n]=De(i));return e}return null}function er(t,e){const n=new Set,i=[t];for(;i.length>0;){const o=i.pop();if(!o||n.has(o))continue;n.add(o);const r=o.$ref;if(typeof r=="string"){if(e){const u=e[r];if(!u){const f=Object.keys(e).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved. Available $defs: ${f}`)}i.push(u)}continue}const s=o.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&i.push(u);const a=o.properties;if(a)for(const u of Object.values(a))i.push(u);const c=o.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&i.push(u);else typeof c=="object"&&c!==null&&i.push(c);const d=o.additionalProperties;typeof d=="object"&&d!==null&&i.push(d);const l=o.propertyNames;typeof l=="object"&&l!==null&&i.push(l)}}function Ll(t){return{encode(e,n,i){const o=Qi(t,i);return We(e,n,o)},decode(e,n,i){const o=Qi(t,i);return Je(e,n,o)}}}const Zo={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},ei={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}};const ti={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},ni={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},Ul=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,oi={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!Ul.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},po="NaN",mo="Infinity",go="-Infinity",Dl=new Set([po,mo,go]),ii={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?po:t===1/0?mo:t===-1/0?go:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===po)return NaN;if(t===mo)return 1/0;if(t===go)return-1/0;const i=Number(t);if(!Number.isNaN(i))return i}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...Dl].join(", ")}.`);return NaN}},Ml=[Zo,ei,ti,ni,oi,ii];function xl(t,e={}){for(const n of Ml)t.register(n,{override:e.override??!1})}const Fl=12;function Bl(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,i,o]=n,r=i==="$defs"?e.$defs:e.definitions;return r==null?void 0:r[decodeURIComponent(o)]}function tr(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function Kl(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function ql(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function nr(t,e,n){const i=t.properties??{},o=t.required??[],r={};for(const s of o){const a=i[s];r[s]=a!==void 0?rt(a,e,n+1):`<${s}>`}return r}function Hl(t,e,n){const i=Array.isArray(t.items)?t.items[0]:t.items;return i?[rt(i,e,n+1)]:[]}function rt(t,e=t??{},n=0){if(!t||n>Fl)return null;if(typeof t.$ref=="string"){const r=Bl(t.$ref,e);return r!==void 0?rt(r,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const r={},s=[];for(const a of t.allOf){Object.assign(r,a.properties??{});for(const c of a.required??[])s.includes(c)||s.push(c)}return nr({...t,properties:r,required:s},e,n)}const i=tr(t.oneOf)??tr(t.anyOf);if(i)return rt(i,e,n+1);switch(Kl(t)){case"object":return nr(t,e,n);case"array":return Hl(t,e,n);case"string":return ql(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Js(t){if(!t)return;const e=rt(t);return`Example: ${JSON.stringify(e)}`}Zo.id,ei.id,ti.id,ni.id,oi.id,ii.id;const zs=Il();xl(zs);const Ys=Ll(zs.freeze());function Xs(t,e){var i;const n=((i=t.input)==null?void 0:i.properties)??{};return e in n}function ho(t){var n,i;const e=(i=(n=t.input)==null?void 0:n.properties)==null?void 0:i.data;return Object.keys((e==null?void 0:e.properties)??{})}function Vl(t,e){var o,r,s;const n=(s=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data)==null?void 0:s.properties,i=n==null?void 0:n[e];return i!==void 0?i:void 0}function Gl(t,e){return e===void 0||t===void 0?t:Ys.decode(t,e)}function Jn(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:Ys.encode(t,n)}async function Wl(t,e,n,i,o,r){const a=ho(n).map(d=>Gl(r[d],Vl(n,d)));if(Xs(n,"session")&&e){const d=await e({session:o.session}),l=await t[i](d,...a);return Jn(l,n)}if(n.hasCtx){const d=e?await e(o):void 0,l=await t[i](d,...a);return Jn(l,n)}const c=await t[i](...a);return Jn(c,n)}class Pt{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}}function Jl(t=[]){return async function(n,i,o){const r=o.schemas[n];if(!r)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>Wl(o.fns,o.createClient,r,n,i.envelope,i.domainArgs);return t.reduceRight((c,d)=>()=>d(i,c),s)()}}function or(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function Qs(t,e,n={}){const i=t.split("/");if(i.length<2||i.some(d=>d.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...r]=i,s=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:or(s),path:r.map(or),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}const be=Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href);let Wt;function Zs(){return Wt||(Wt=be("ts-morph").Project,Wt)}const ea=Symbol.for("adhd.apigen.extraction-session");function ri(t,e){const n=[...t.getImportDeclarations().map(i=>i.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(i=>i.getModuleSpecifierSourceFile())];for(const i of n){if(!i)continue;const o=i.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{i.refreshFromFileSystemSync()}catch{}ri(i,e)}}}function ta(t){try{const e=j.statSync(t);return`${e.mtimeMs}:${e.size}`}catch{return"nostat"}}const an=new Map,ir=new Map;function zl(t,e,n){const i=e??"",o=an.get(i);let r=n;if(o&&o.fileVersions.size>0){const c=[n],d=[...o.fileVersions.entries()].sort(([l],[u])=>l.localeCompare(u));for(const[l,u]of d)l!==t&&c.push(`${l}:${u}`);r=c.join("|")}const s=`${t}\0${e??""}`;let a=ir.get(s);return(a==null?void 0:a.version)!==r&&(a={version:r,schemas:new Map},ir.set(s,a)),a.schemas}let zn;function Yl(){if(!zn){const t=Zs();zn=new t({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return zn}function na(t){const e=Yl(),n=e.getSourceFile(t),i=n??e.addSourceFileAtPath(t);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([t]);return ri(i,o),[...o].sort()}function Xl(){const t={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},e=new Map;let n=!1;return{[ea]:!0,stats:t,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(o){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const r=o??"",s=o?this.statVersion(o):"";let a=an.get(r);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=Zs();a={project:o?new c({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},an.set(r,a),t.projectsBuilt++}return a.project},sourceFileFor(o,r){const s=this.projectFor(r),a=an.get(r??""),c=this.statVersion(o);let d=s.getSourceFile(o);if(d===void 0?d=s.addSourceFileAtPath(o):a&&a.fileVersions.get(o)!==c&&d.refreshFromFileSystemSync(),a==null||a.fileVersions.set(o,c),a){const l=new Set([o]);ri(d,l);for(const u of l)u!==o&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(o){let r=e.get(o);return r===void 0&&(r=ta(o),e.set(o,r)),r},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),e.clear()}}}function Ql(t){const e=t;if(e[ea]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return e}const rr=new Set(["string","number","boolean","integer"]);function Zl(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?rr.has(n):Array.isArray(n)?n.every(i=>rr.has(i)||i==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(i=>["string","number","boolean"].includes(typeof i)):!1}function oa(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(Zl)}function eu(t){const e={},n=i=>{for(const o of["definitions","$defs"]){const r=i[o];if(r)for(const[s,a]of Object.entries(r)){const c=s.startsWith("#/")?s:`#/${o}/${s}`;e[c]=a}}};for(const i of Object.values(t.schemas))n(i.input),n(i.output);if(Object.keys(e).length!==0)for(const[i,o]of Object.entries(t.schemas))try{er(o.input,e),er(o.output,e)}catch(r){throw new Error(`[apigen-core-client] Schema validation failed for function "${i}": ${r.message}`)}}function tu(t,e){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(e?".":" (an empty object for this zero-parameter tool).")];return t.length>0&&n.push(`Field(s) ${t.map(i=>`"${i}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function nu(t,e,n){eu(t);const i={};for(const[o,r]of Object.entries(t.schemas)){const s={},a=r.input.properties??{},c=r.input.required??[],d={},l=[],u={};for(const y of e)if(y.envelope&&s[y.id]!==!1)for(const[w,v]of Object.entries(y.envelope))d[w]=v,u[w]=y.id,l.includes(w)||l.push(w);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},m=r.safe===!0||oa(r.input),p=r.input.definitions,g=r.input.$defs;i[o]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:tu(Object.keys(d),Object.keys(a).length>0),...p?{definitions:p}:{},...g?{$defs:g}:{}},output:r.output,...r.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return i}const ou=8;function iu(t,e){try{return e?t.getText(e):t.getText()}catch{try{return t.getText()}catch{return}}}let ru=0;async function su(t,e,n,i){const o=`__ApigenProbe_${process.pid}_${ru++}`;let r;try{r=e.addTypeAlias({name:o,type:n});const s=r.getType();return await i(s)}catch{return}finally{try{r==null||r.remove()}catch{}}}async function ia(t,e,n){if(n>ou)return{};if(t.isString()||t.isStringLiteral())return t.isStringLiteral()?{type:"string",enum:[t.getLiteralValue()]}:{type:"string"};if(t.isNumber()||t.isNumberLiteral())return t.isNumberLiteral()?{type:"number",enum:[t.getLiteralValue()]}:{type:"number"};if(t.isBoolean())return{type:"boolean"};if(t.isBooleanLiteral())return{type:"boolean",const:t.getText()==="true"};if(t.isNull()||t.isUndefined()||t.isVoid())return{type:"null"};if(t.isUnion()){const i=t.getUnionTypes(),o=i.filter(p=>p.isBooleanLiteral()),r=o.some(p=>p.getText()==="true"),s=o.some(p=>p.getText()==="false");let a=!1;const c=i.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(i.every(p=>p.isStringLiteral())&&i.length>0)return{type:"string",enum:i.map(p=>p.getLiteralValue())};if(i.every(p=>p.isNumberLiteral())&&i.length>0)return{type:"number",enum:i.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?r&&s?{type:"boolean"}:{type:"boolean",const:r}:ia(p,e,n+1))),f=jn(u);return{oneOf:lu(du(u)),...f?{discriminator:f}:{},[Fe]:"union"}}if(t.isArray()){const i=t.getArrayElementType();return{type:"array",items:i?await e(i.getText()):{}}}if(t.isTuple()){const i=t.getTupleElements(),o=await Promise.all(i.map(r=>e(r.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(t.isObject()){const i=t.getStringIndexType(),o=t.getNumberIndexType(),r=i??o,s=t.getProperties();if(r&&s.length===0)return{type:"object",additionalProperties:await e(r.getText())};const a={},c=[];for(const d of s){const l=d.getName(),f=d.getDeclarations()[0];let m;if(f)try{m=d.getTypeAtLocation(f)}catch{m=void 0}if(m!==void 0&&m.getCallSignatures().length>0)continue;const p=m!==void 0?iu(m,f):void 0;a[l]=p!==void 0?await e(p):{},d.isOptional()||c.push(l)}if(Object.keys(a).length>0){const d=r?await e(r.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:d}}return{}}return{}}function au(t){return Object.keys(t).length===0?!0:t.type==="object"&&t.additionalProperties!==void 0&&t.additionalProperties!==!1&&(t.properties===void 0||Object.keys(t.properties).length===0)}const cu=new Set(["required","enum","type"]);function yo(t,e){if(t===null||typeof t!="object")return JSON.stringify(t)??"undefined";if(Array.isArray(t)){const o=t.map(r=>yo(r));return e!==void 0&&cu.has(e)&&o.sort(),`[${o.join(",")}]`}const n=t;return`{${Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>`${JSON.stringify(o)}:${yo(n[o],o)}`).join(",")}}`}function du(t){const e=new Set,n=[];for(const i of t){const o=yo(i);e.has(o)||(e.add(o),n.push(i))}return n}function lu(t){if(t.length<2)return t.slice();const e=t.map(au),n=t.map((o,r)=>e[r]?r:-1).filter(o=>o>=0);if(n.length===0||n.length===t.length)return t.slice();const i=t.map((o,r)=>e[r]?-1:r).filter(o=>o>=0);return t.map((o,r)=>{if(!e[r])return o;const s=t.filter((a,c)=>c!==r&&(i.includes(c)||e[c]&&c<r));return{allOf:[o,{not:{anyOf:s}}]}})}function jn(t){if(t.length<2)return;const e=[];for(const i of t){if(i.type!=="object")return;const o=i.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(i=>e.every(o=>Object.prototype.hasOwnProperty.call(o,i)));for(const i of n){const o=[];let r=!0;for(const a of e){const c=a[i],d=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!d||!Array.isArray(l)||l.length!==1){r=!1;break}o.push(String(l[0]))}if(!r||new Set(o).size!==o.length)continue;const s={};return o.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:i,mapping:s}}}function cn(t,e,n){if(e>6)return{};const i=t.trim();if(i==="string")return{type:"string"};if(i==="number")return{type:"number"};if(i==="boolean")return{type:"boolean"};if(i==="null")return{type:"null"};if(i==="undefined")return{type:"null"};const o=wo[i];if(o!==void 0)return o;if(n!=null&&n.size){const r=n.get(i);if(r!==void 0){const s=wo[r];if(s!==void 0)return s}}if(i.endsWith("[]"))return{type:"array",items:cn(i.slice(0,-2),e+1,n)};if(i.includes("|")){const r=i.split("|").map(c=>c.trim());if(r.every(c=>c.startsWith("'")))return{type:"string",enum:r.map(c=>c.replace(/'/g,""))};const s=r.map(c=>cn(c,e+1,n)),a=jn(s);return{oneOf:s,...a?{discriminator:a}:{},[Fe]:"union"}}if(i.startsWith("{")&&i.endsWith("}")){const r=i.slice(1,-1).trim(),s={};for(const a of r.split(";").filter(Boolean)){const[c,d]=a.split(":").map(l=>l.trim());c&&d&&(s[c.replace("?","")]=cn(d,e+1,n))}return{type:"object",properties:s}}return{}}function ra(t){const e=[];let n=0,i=0;for(let r=0;r<t.length;r++){const s=t[r];s==="<"||s==="["||s==="{"||s==="("?n++:s===">"||s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(e.push(t.slice(i,r).trim()),i=r+1)}const o=t.slice(i).trim();return o.length>0&&e.push(o),e}function uu(t){const e=/^(?:Readonly)?Map<(.+)>$/.exec(t);return e?e[1]:void 0}function fu(t){const e=/^(?:Readonly)?Set<(.+)>$/.exec(t);return e?e[1]:void 0}function pu(t){let e=t.trim();if(e.startsWith("readonly ")&&(e=e.slice(9).trim()),!e.startsWith("[")||!e.endsWith("]"))return;const n=e.slice(1,-1).trim();if(n.length!==0)return ra(n)}async function mu(t,e){const n=t.trim(),i=uu(n);if(i!==void 0){const s=ra(i);if(s.length===2){const[a,c]=await Promise.all([e(s[0]),e(s[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=fu(n);if(o!==void 0)return{type:"array",items:await e(o),uniqueItems:!0};const r=pu(n);if(r!==void 0){const s=await Promise.all(r.map(a=>e(a)));return{type:"array",items:s,minItems:s.length,maxItems:s.length}}}const sa={"decimal.js":"Decimal"},wo={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},sr={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function ar(t){var n;const e=new Map;for(const i of t.getImportDeclarations()){const o=i.getModuleSpecifierValue(),r=sa[o];if(!r)continue;const s=i.getDefaultImport();if(s){const a=s.getText();a!==r&&e.set(a,r)}for(const a of i.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==r&&e.set(c,r)}}return e}function gu(t,e){return n=>{n.addNodeParser({supportsNode(i){var r,s,a;if(i.kind!==e)return!1;const o=((r=i.typeName)==null?void 0:r.escapedText)??((a=(s=i.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return o!==void 0&&Object.prototype.hasOwnProperty.call(sr,o)},createType(i){var a,c,d;const o=((a=i.typeName)==null?void 0:a.escapedText)??((d=(c=i.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:r,StringType:s}=vo();return new r(new s,{format:sr[o]},!1)}}),n.addNodeParser({supportsNode(i){return i.kind===t},createType(){const{AnnotatedType:i,StringType:o}=vo();return new i(new o,{format:"int64"},!1)}})}}let Jt;function vo(){return Jt||(Jt=be("ts-json-schema-generator"),Jt)}let mt;function hu(){if(mt)return mt;try{const t=_.dirname(be.resolve("ts-json-schema-generator/package.json"));mt=be(be.resolve("typescript",{paths:[t]}))}catch{mt=be("typescript")}return mt}const Re=new Map;function yu(){const t=process.env.APIGEN_PROGRAM_CACHE,e=t===void 0?NaN:Number(t);return Number.isFinite(e)&&e>=0?e:8}function wu(t){const e=Re.get(t);return e&&(Re.delete(t),Re.set(t,e)),e}function vu(t,e){const n=yu();if(n!==0)for(Re.delete(t),Re.set(t,e);Re.size>n;){const i=Re.keys().next().value;Re.delete(i)}}function bu(t,e){return`${t}\0${e??""}`}const Eu=new Set(["zod",/^zod\/./]);function Su(t){for(const e of t.getImportDeclarations()){const n=e.getModuleSpecifierValue();for(const i of Eu)if(typeof i=="string"){if(n===i)return!0}else if(i.test(n))return!0}return!1}function ku(t){for(const e of["$defs","definitions"]){const n=t[e];if(!n||typeof n!="object")continue;const i=Object.keys(n);if(i.length===0)continue;const o=new Set(i.filter(r=>/zod/i.test(r)));for(const[r,s]of Object.entries(n)){if(o.has(r)||typeof s!="object"||s===null)continue;const a=s,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const d of o)if(c.includes(d)){o.add(r);break}}}for(const r of o)delete n[r]}bo(t)}function bo(t,e){if(!t||typeof t!="object")return;const n=e??new WeakSet;if(!n.has(t)){n.add(t);for(const i of Object.keys(t))if(i==="$ref"&&typeof t[i]=="string"){const o=t[i];/zod/i.test(o)&&delete t[i]}for(const[,i]of Object.entries(t))if(typeof i=="object"&&i!==null)if(Array.isArray(i))for(const o of i)typeof o=="object"&&o!==null&&bo(o,n);else bo(i,n)}}function _u(t){const e=new Set;for(const i of["$defs","definitions"]){const o=t[i];if(o&&typeof o=="object")for(const r of Object.keys(o))e.add(r)}const n=Eo(t,e);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function Eo(t,e){if(!t||typeof t!="object")return[];const n=[];for(const[i,o]of Object.entries(t))if(i==="$ref"&&typeof o=="string"){const r=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);r&&!e.has(r[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const r of o)typeof r=="object"&&r!==null&&n.push(...Eo(r,e));else n.push(...Eo(o,e));return n}function Au(t){const e=t.anyOf;if(!Array.isArray(e)||e.length<2)return t;const n=e,i=jn(n),o={...t};return delete o.anyOf,{...o,oneOf:n,...i?{discriminator:i}:{},[Fe]:o[Fe]??"union"}}function Nu(t,e,n){const{DEFAULT_CONFIG:i}=be("ts-json-schema-generator/dist/src/Config.js"),o={...i,...t},r=o.path,s=bu(r,o.tsconfig);let a;a=n?n.statVersion(r):ta(r);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??wu(s);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=be("ts-json-schema-generator/dist/factory/program.js"),{createParser:u,createFormatter:f,SchemaGenerator:m}=vo(),p=hu(),g=gu(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),y=l(o),w=u(y,o,g),v=f(o);if(c=new m(y,w,v,o),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const b={version:a,gen:c};vu(s,b),n==null||n.generatorCache.set(s,b)}}const d=c.createSchema(o.type);return ku(d),_u(d),d}function Ru(t,e){let n=t.trim();if(n=ca(n),e!=null&&e.size){const o=e.get(n);if(o!==void 0)return o}const i=n.match(/^ReadonlyArray<(.+)>$/);for(i&&(n=`${i[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function aa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const ju=Object.entries(sa).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${aa(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ca(t){let e=t;for(const{pattern:n,key:i}of ju)e=e.replace(n,i);return e}function Tu(t,e){let n=ca(t);for(const[i,o]of e)n=n.replace(new RegExp(`\\b${aa(i)}\\b`,"g"),o);return n}async function At(t,e,n,i,o,r){const s=e.getFilePath(),a=`${s}\0${i??""}\0${n}`,c=r??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),cr(t,e,n,i,void 0,p)}const d=o.schemaCache.get(a);if(d!==void 0)return o.stats.schemaCacheHits++,d;const l=zl(s,i,o.statVersion(s)),u=l.get(n);if(u!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(u)),u;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const m=cr(t,e,n,i,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,m),m}async function cr(t,e,n,i,o,r){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(o){const f=o.aliasCache.get(e);s=f??ar(e),f||o.aliasCache.set(e,s)}else s=ar(e);const a=Ru(n,s),c=wo[a];if(c!==void 0)return c;const d=await mu(a,f=>At(t,e,f,i,o,r));if(d!==void 0)return d;const l=(o==null?void 0:o.zodImportCache.get(e))??Su(e);if(o&&o.zodImportCache.set(e,l),!l)try{const f={path:e.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:i,topRef:!1},m=Nu(f,!0,o);return Au(m)}catch{}try{const f=await su(t,e,a,m=>ia(m,p=>At(t,e,p,i,o,r),0));if(f!==void 0)return f}catch{}const u=Tu(a,s);return cn(u,0,s)}function si(t,e,n){if(t!=null&&t.hasInitializer()){const i=t.getInitializer();if(i)return i.getText()}return Ou(n,e)}function Ou(t,e){var s;const n=t,i=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],o=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\[\\s*${o}\\s*=\\s*([^\\]]+)\\]`);for(const a of i)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(r);if(d)return d[1].trim()}}function Iu(t){const e=t.trim(),n=e.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(e))return Number(e);try{return JSON.parse(e)}catch{return e}}}function $u(t,e){const n=Iu(e);if(n===void 0)return;t.default=n;const i=typeof n=="string"?n:JSON.stringify(n),o=typeof t.description=="string"?t.description:void 0;t.description=o?`${o} (default: ${i})`:`(default: ${i})`}let zt;function Cu(){return zt||(zt=be("ts-morph").SyntaxKind,zt)}function Tn(t){try{if(!t)return;const e=Cu();if(t.getKind()!==e.TypeReference)return;const n=t;if(n.getTypeArguments().length>0)return;const i=n.getTypeName();if(i.getKind()!==e.Identifier)return;const r=i.getSymbol();if(!r)return;const s=r.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const a=s,c=a.getType();if(!(c.isString()||c.isNumber()||c.isBoolean()))return;const l=a.getJsDocs();for(const u of l)for(const f of u.getTags())if(f.getTagName()==="format"){const m=f.getCommentText();if(m!==void 0)return m.trim()}return}catch{return}}const Pu=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function Lu(t){const e=[];let n=0,i="";for(const o of t)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(e.push(i.trim()),i=""):i+=o;return i.trim().length>0&&e.push(i.trim()),e}function Uu(t){const e=t.trim(),n=e.indexOf("<");if(n===-1||!e.endsWith(">"))return null;const i=e.slice(0,n),o=i.includes(".")?i.slice(i.lastIndexOf(".")+1):i;if(!Pu.has(o))return null;let r=0;for(let c=n;c<e.length;c++){const d=e[c];if(d==="<")r++;else if(d===">"&&(r--,r===0&&c!==e.length-1))return null}if(r!==0)return null;const s=e.slice(n+1,-1),a=Lu(s);return a.length>0?a[0]:null}async function da(t){const e=t.session===void 0,n=Ql(t.session??Xl());try{return await Du(t,n)}finally{e&&n.dispose()}}async function Du(t,e){const{sourceFile:n,namespace:i="",dropFileSegment:o=!1,tsconfig:r}=t,s=e.projectFor(r),a=e.sourceFileFor(n,r),c=_.basename(n),d=we(xu(c)),l=o?null:d,u=we(i),f=[];for(const[g,y]of a.getExportedDeclarations()){if(g==="default"||Xt(g))continue;const w=Bu(y);if(w){const S=w.getSignature(),E=ur(S,w),N=S.getReturnType().getText(),k=Ce(S);f.push(await Yt(s,a,u,l,g,E,N,w.isAsync(),r,e,k));continue}const v=y.find(S=>S.getKindName()==="VariableDeclaration");if(!v)continue;const b=v.getInitializer(),h=b==null?void 0:b.getKindName();if(b&&["ArrowFunction","FunctionExpression"].includes(h??"")){const E=v.getType().getCallSignatures();if(E.length===0)continue;const N=E[0],k=fr(N,v,v.getVariableStatement()),R=N.getReturnType().getText(),A=Ce(N),O=b.isAsync();f.push(await Yt(s,a,u,l,g,k,R,O,r,e,A))}else if(h==="ObjectLiteralExpression"){const S=v.getType();for(const E of S.getProperties()){const N=E.getName();if(Xt(N))continue;const R=E.getTypeAtLocation(v).getCallSignatures();if(R.length===0)continue;const A=R[0],O=fr(A,v,v.getVariableStatement()),I=A.getReturnType().getText(),L=Ce(A),$=[...l?[l]:[],we(g),we(N)];f.push(await dn(s,a,u,$,N,O,I,!1,r,e,L))}}else{const S=v.getType(),E=S.getText();if(Le(S,v)){const N=await At(s,a,E,r,e);f.push(Mu(u,l,g,N))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${g}`)}}const m=a.getDefaultExportSymbol();if(m){const g=a.getExportAssignment(y=>!y.isExportEquals());if(g){const y=g.getExpression(),w=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes(w)){const b=y.getType().getCallSignatures();if(b.length>0){const h=b[0],S=Yn(h,g),E=h.getReturnType().getText(),N=Ce(h),k=y.isAsync();f.push(await Yt(s,a,u,l,"default",S,E,k,r,e,N))}}else{const v=y.getType();for(const b of v.getProperties()){const h=b.getName();if(Xt(h))continue;const E=b.getTypeAtLocation(g).getCallSignatures();if(E.length===0)continue;const N=E[0],k=Yn(N,g),R=N.getReturnType().getText(),A=Ce(N),O=[...l?[l]:[],we("default"),we(h)];f.push(await dn(s,a,u,O,h,k,R,!1,r,e,A))}}}else{const y=m.getDeclarations();for(const w of y){if(w.getKindName()!=="FunctionDeclaration")continue;const v=w,b=v.getName(),h=b&&b.length>0?b:"default",S=v.getSignature(),E=ur(S,v),N=S.getReturnType().getText(),k=Ce(S);f.push(await Yt(s,a,u,l,h,E,N,v.isAsync(),r,e,k))}}}const p=Fu(a);if(p.length>0)for(const{name:g,sig:y}of p){if(Xt(g))continue;const w=Yn(y),v=y.getReturnType().getText(),b=Ce(y),h=[...l?[l]:[],we(g)];f.push(await dn(s,a,u,h,g,w,v,!1,r,e,b))}return f}function dr(t,e,n,i){const o=new Set,r=s=>{if(Array.isArray(s))return s.map(r);if(!s||typeof s!="object"||o.has(s))return s;o.add(s);try{const a=s,c={};for(const[d,l]of Object.entries(a)){if(d==="definitions"||d==="$defs"){const u=d,f=e[u];for(const[m,p]of Object.entries(l)){const g=r(p),y=f[m];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(g))throw new Error(`[apigen-core-client] Function "${n}": param "${i}" contributes a "${u}.${m}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);f[m]=g}continue}c[d]=r(l)}return c}finally{o.delete(s)}};return r(t)}function lr(t,e){if(!e||t.format!==void 0||"$ref"in t||"properties"in t||"items"in t)return;const n=t.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(t.format=e)}function Ce(t){var e;try{return Tn((e=t.getDeclaration())==null?void 0:e.getReturnTypeNode())}catch{return}}async function Yt(t,e,n,i,o,r,s,a,c,d,l){const u=we(o);return dn(t,e,n,i?[i,u]:[u],o,r,s,a,c,d,l)}async function dn(t,e,n,i,o,r,s,a,c,d,l){const u=r.length>0&&r[0].name==="ctx",f=r.filter(A=>A.name!=="ctx"),m=f.filter(A=>!A.optional).map(A=>A.name),p={},g={definitions:{},$defs:{}};for(const A of f){const O=await At(t,e,A.type,c,d),I=dr(O,g,o,A.name);A.defaultValue!==void 0&&$u(I,A.defaultValue),lr(I,A.format),p[A.name]=I}const y=s.replace(/^Promise<(.+)>$/,"$1").trim(),w=Uu(y),v=w!==null,b=v?w:y,h=await At(t,e,b,c,d),S={definitions:{},$defs:{}},E=dr(h,S,o,"<return>"),N=l?{...E}:E;lr(N,l),Object.keys(S.definitions).length>0&&(N.definitions={...N.definitions,...S.definitions}),Object.keys(S.$defs).length>0&&(N.$defs={...N.$defs,...S.$defs});const k={type:"object",properties:p,required:m,...Object.keys(g.definitions).length>0?{definitions:g.definitions}:{},...Object.keys(g.$defs).length>0?{$defs:g.$defs}:{}};return{id:la(n,i),host:"ts",namespace:n,path:i,kind:"action",async:a,streaming:v,safe:!1,input:k,output:N,envelope:{},typeText:{lang:"ts",input:Ku(r),output:b},...u?{hasCtx:!0}:{}}}function Mu(t,e,n,i){const o=we(n),r=e?[e,o]:[o];return{id:la(t,r),host:"ts",namespace:t,path:r,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:i,envelope:{},typeText:null}}function la(t,e){return(t.raw?[t,...e]:e).map(i=>i.words.join("-")).join("/")}function Nt(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function we(t){return{raw:t,words:Nt(t)}}function xu(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Fu(t){const e=[];for(const n of t.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const i=n.getExpression();if(i.getKindName()!=="BinaryExpression")continue;const o=i;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),a=s.getType();for(const c of a.getProperties()){const l=c.getTypeAtLocation(s).getCallSignatures();l.length!==0&&e.push({name:c.getName(),sig:l[0]})}}return e}function Bu(t){let e;for(const n of t){if(n.getKindName()!=="FunctionDeclaration")continue;const i=n;if(e||(e=i),i.getBody())return i}return e}function ur(t,e){return t.getParameters().map(n=>{var s;const i=n.getDeclarations(),o=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,r=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:n.getTypeAtLocation(t.getDeclaration()).getText(),optional:r,defaultValue:si(o,n.getName(),e),format:Tn(o==null?void 0:o.getTypeNode())}})}function fr(t,e,n){return t.getParameters().map(i=>{var a;const o=i.getDeclarations(),r=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,s=i.isOptional()||((r==null?void 0:r.hasInitializer())??!1)||(((a=r==null?void 0:r.hasQuestionToken)==null?void 0:a.call(r))??!1);return{name:i.getName(),type:i.getTypeAtLocation(e).getText(),optional:s,defaultValue:si(r,i.getName(),n??e),format:Tn(r==null?void 0:r.getTypeNode())}})}function Yn(t,e){return t.getParameters().map(n=>{var s,a,c;const i=n.getDeclarations(),o=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,r=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:o?o.getType().getText():((c=(a=n.getValueDeclaration())==null?void 0:a.getType())==null?void 0:c.getText())??"unknown",optional:r,defaultValue:si(o,n.getName(),e),format:Tn(o==null?void 0:o.getTypeNode())}})}function Ku(t){const e=t.filter(n=>n.name!=="ctx");return e.length===0?"()":"("+e.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Xt(t){return!!(t==="__samples__"||t.startsWith("__"))}function Le(t,e,n=new Set){if(t.getCallSignatures().length>0||t.getConstructSignatures().length>0)return!1;if(t.isString()||t.isNumber()||t.isBoolean()||t.isNull()||t.isUndefined()||t.isStringLiteral()||t.isNumberLiteral()||t.isBooleanLiteral()||t.isEnumLiteral())return!0;if(t.isArray()||t.isReadonlyArray()){const i=t.getArrayElementType();return i?Le(i,e,n):!1}if(t.isTuple())return t.getTupleElements().every(i=>Le(i,e,n));if(t.isUnion())return t.getUnionTypes().every(i=>Le(i,e,n));if(t.isIntersection())return t.getIntersectionTypes().every(i=>Le(i,e,n));if(t.isObject()){const i=t.getText(e);if(n.has(i))return!0;n.add(i);const o=t.getStringIndexType(),r=t.getNumberIndexType();if(o||r)return[o,r].every(a=>!a||Le(a,e,n));const s=t.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(e);return Le(c,e,n)})}return!1}function qu(t,e){return async n=>{let i=()=>e(n);for(let o=t.length-1;o>=0;o--){const r=t[o],s=i;i=()=>r(n,s)}return i()}}function Hu(t,e){return qu(t,e)}function Vu(t,e,n={}){const i=t.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return Hu(i,e)}function Gu(t){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:t}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function Wu(t){return{operationConst:t.id,itemsSchema:t.input,resultSchema:Gu(t.output)}}function Ju(t,e={}){const n=new Set(e.exclude??[]),i=new Map;for(const o of t){if(n.has(o.id))continue;const r=i.get(o.kind);r?r.push(o):i.set(o.kind,[o])}return i}function pr(t){return{type:"string",enum:[t]}}function mr(t,e){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:e,items:{type:"array",items:t.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}},additionalProperties:!1}}function gr(t,e){const n={},i={},o=[["definitions",n],["$defs",i]];for(const r of t){const s=e(r);for(const[a,c]of o){const d=s[a];if(d)for(const[l,u]of Object.entries(d)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(u))throw new Error(`[apigen-core-client] _batch mount: operation "${r.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=u}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(i).length>0?{$defs:i}:{}}}function zu(t){if(t.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const e=t.map(Wu),n=gr(t,s=>s.input),i=gr(t,s=>s.output);if(t.length===1){const[s]=t,[a]=e;return{input:{...mr(a,pr(s.id)),...n},output:{type:"array",items:a.resultSchema,...i}}}const o=t.map((s,a)=>mr(e[a],pr(s.id))),r=jn(o);return{input:{oneOf:o,...r?{discriminator:r}:{},...n},output:{oneOf:e.map(s=>({type:"array",items:s.resultSchema})),...i},...r?{discriminator:r}:{}}}function Yu(t,e={}){const n=Ju(t.operations,e),i=[];for(const[o,r]of n){const{input:s,output:a}=zu(r),c=Qs(`_batch/${o}`,t,{kind:o,safe:o==="query",input:s,output:a});i.push({...c,operationIds:r.map(d=>d.id)})}return i}function ai(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,i=!n&&!!process.stderr.isTTY,o=t.format??(i?"pretty":"json"),r={level:e};if(o==="pretty")return r.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},Gt(r);const s=n?Gt.destination({dest:t.destination,mkdir:!0,sync:!0}):Gt.destination(2);return Gt(r,s)}function Xu(t){if((t==null?void 0:t.type)!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([o,r])=>`${o}${n.has(o)?"":"?"}: ${On(r)}`).join(", ")} }`}function Qu(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function Zu(t){const e=t.enum??[];return e.length===0?"unknown":e.map(Qu).join("|")}function ef(t,e){return t.map(n=>On(n,e)).join(" | ")}function On(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${On(t.items,0)}[]`;if(t.enum)return Zu(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?ef(n,e-1):"union":e>=1&&t.type==="object"?Xu(t)??"object":t.type??"object"}function ua(t){var a;const n=(a=((t==null?void 0:t.input)??{}).properties)==null?void 0:a.data,i=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),r=Object.entries(i).map(([c,d])=>({name:c,type:On(d,2),required:o.has(c)})),s=r.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:r,text:s}}function tf(t){let e;return Array.isArray(t)?e=t:t?e=[t]:e=[],e.find(n=>n==="number"||n==="integer"||n==="boolean")}function nf(t,e){var r,s;const i=((s=(r=((e==null?void 0:e.input)??{}).properties)==null?void 0:r.data)==null?void 0:s.properties)??{},o={...t};for(const[a,c]of Object.entries(i)){const d=o[a];if(typeof d!="string")continue;const l=tf(c==null?void 0:c.type);if(l==="number"||l==="integer"){const u=Number(d);!Number.isNaN(u)&&d.trim()!==""&&(o[a]=u)}else l==="boolean"&&(d==="true"?o[a]=!0:d==="false"&&(o[a]=!1))}return o}const of=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],rf={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},hr={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class z extends Error{constructor(e,n,i){super(n),this.name="ApiError",this.code=e,this.details=i,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}}function fe(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&of.includes(t.code)&&typeof t.toJSON=="function"}function yr(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const In=new qs({allErrors:!0});Sl(In);for(const t of[Fe,Xo,lo,uo,"discriminator"])In.addKeyword({keyword:t,valid:!0});In.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function sf(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function af(t,e){const n=Js(e),i=[`Validation failed: ${sf(t)}`];return n&&i.push(n),i.join(" — ")}function cf(t){return async function(n,i){const o=n.operation.id,r=t[o];if(r===void 0)return i();const s={data:n.domainArgs,...n.envelope},a=In.compile(r.input);if(!a(s)){const d=a.errors??[];throw new z("invalid_argument",af(d,r.input),d)}return i()}}async function fa(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const i=fe(n)?n:new z("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:yr("before-first-chunk",i)}:{ok:!1,carrier:yr("after-first-chunk",i,e.length)}}}function $n(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Pe extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function Xn(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const i=n.mapping;if(!(i===null||typeof i!="object"||Array.isArray(i)))return{propertyName:n.propertyName,mapping:i}}function pa(t,e){const n=t[Xo];if(typeof n=="string"){const i=e.registry.get(n);if(i)return i}return e.registry.resolve(t)}function df(t,e,n){const i=pa(e,n);return i?i.encode(t,e,n):t}function lf(t,e,n){const i=pa(e,n);return i?i.decode(t,e,n):t}function uf(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(i){if(i[Fe]==="union")return!0;const o=i.oneOf;return!Array.isArray(o)||o.length===0?!1:Xn(i)!==void 0},encode(i,o,r){const s=Xn(o);if(!s)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=s,d=i[a];if(d==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${r.path}" is missing the discriminator property "${a}".`);const l=String(d),u=c[l];if(!u)throw new Pe("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${r.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=r.resolve(u);return df(i,f,{...r,path:`${r.path}[${l}]`})},decode(i,o,r){if(i===null||typeof i!="object"||Array.isArray(i)){let p;throw i===null?p="null":Array.isArray(i)?p="array":p=typeof i,new Pe("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${r.path}", got ${p}.`)}const s=i,a=Xn(o);if(!a)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:d}=a,l=s[c];if(l==null)throw new Pe("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${r.path}" is missing the discriminator property "${c}".`);const u=String(l),f=d[u];if(!f)throw new Pe("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${u}" on the wire at "${r.path}" is not in the mapping (known: ${Object.keys(d).join(", ")}).`);const m=r.resolve(f);return lf(i,m,{...r,path:`${r.path}[${u}]`})}}}const ff="x-apigen-instances";class Qt extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}}function wr(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function pf(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function vr(t,e,n){if(e){const i=n.registry.resolve(e);if(i)return i.encode(t,e,n)}return t}function mf(t,e,n){if(e){const i=n.registry.resolve(e);if(i)return i.decode(t,e,n)}return t}function gf(t){const{id:e,schema:n,ctor:i}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Fe]==="nominal"?!0:o[Xo]===e},encode(o,r,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new Qt("E_NOMINAL_CYCLE",`[${e}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=wr(r),c=typeof r[uo]=="string"?r[uo]:"toJSON",d=o[c];if(typeof d=="function"){const p=d.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const g={};for(const[y,w]of Object.entries(p))g[y]=vr(w,a[y],{...s,path:`${s.path}/${y}`});return g}return p}const l={},u=Object.keys(a),f=o,m=u.length>0?u:Object.keys(f);for(const p of m){const g=f[p];g!==void 0&&(l[p]=vr(g,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(o)}},decode(o,r,s){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Qt("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=o;for(const l of pf(r))if(!(l in a))throw new Qt("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${s.path}".`);if(r[ff]===!1)throw new Qt("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=wr(r),d={};for(const[l,u]of Object.entries(a))d[l]=mf(u,c[l],{...s,path:`${s.path}/${l}`});if(i){const l=typeof r[lo]=="string"?r[lo]:"fromJSON",u=i[l];if(typeof u=="function")return u.call(i,d);const f=i;return new f(d)}return d}}}const hf=[Zo,ei,ti,ni,oi,ii],yf={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},br=gf({id:"ts.NominalSentinel",schema:yf}),wf={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Er=uf({id:"ts.UnionSentinel",schema:wf});function vf(){const t=[...hf.map(e=>[e.id,e]),[br.id,br],[Er.id,Er]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:$l,codecs:vf()});function So(t,e,n){var s;const i=typeof((s=e==null?void 0:e.input)==null?void 0:s.description)=="string"?e.input.description:void 0,o=Js(e==null?void 0:e.input),r=[n,i,o].filter(a=>typeof a=="string"&&a.length>0);return r.length>0?r.join(" — "):t}function ma(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length===0)return{outputSchema:void 0,wrapped:!1};const e=t;return e.type==="object"?{outputSchema:e,wrapped:!0}:{outputSchema:void 0,wrapped:!1}}function bf(t,e){if(t)return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}const Ef=4,Sf=32;function ko(t){return fe(t)?t:t instanceof Error?new z("internal",t.message):t}function kf(t,e){if(t==="serial"||t==="chained")return 1;const n=e??Ef;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Sf)}function _f(){}function Af(t,e){var r;if(!t&&!e)return{signal:void 0,dispose:_f};const n=new AbortController,i=()=>{n.abort(t==null?void 0:t.reason)};t&&(t.aborted?n.abort(t.reason):t.addEventListener("abort",i,{once:!0}));let o;return e!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${e}ms`,"TimeoutError"))},e),(r=o.unref)==null||r.call(o)),{signal:n.signal,dispose(){t&&t.removeEventListener("abort",i),o&&clearTimeout(o)}}}async function Sr(t,e,n,i,o,r){const s=Af(i.signal,r);try{const a=s.signal?{...i,signal:s.signal}:i,c=await t(e,a,o);if($n(c)){const d=await fa(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:ko(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",chunks:d.chunks}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:ko(a)}}finally{s.dispose()}}async function Nf(t,e,n,i,o={}){const r=o.mode??"parallel",s=o.onItemError??"continue",a=kf(r,o.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:ko(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(r==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(r==="serial"||r==="chained"){let p=!1;for(let g=0;g<n.length;g++){if(p){c[g]=d(g);continue}const y=await Sr(t,e,g,n[g],i,o.itemTimeoutMs);c[g]=y,y.status==="rejected"&&(r==="chained"||s==="abort")&&(p=!0)}return c}let l=0,u=!1;const f=Math.max(1,Math.min(a,n.length)),m=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(u){c[p]=d(p);continue}const g=await Sr(t,e,p,n[p],i,o.itemTimeoutMs);c[p]=g,g.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(m),c}function kr(t){return t.words.join("-")}function _r(t){return t.words.map(Tf).join("")}function Ar(t){return t.words.join("_")}function Rf(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function qe(t,e={}){var f,m;const n=[t.namespace,...t.path],i=t.safe||oa(t.input)?"GET":"POST",o=((m=(f=e.http)==null?void 0:f.verb)==null?void 0:m[t.id])??i,r="/"+n.map(p=>kr(p)).join("/"),s=n.map(p=>Ar(p)).join("_"),c=n.map(p=>Ar(p)).slice(0,-1).join("."),d=_r(n[n.length-2]??n[0]),l=_r(n[n.length-1]),u=n.map(p=>kr(p));return{http:{verb:o,route:r},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function ga(t,e){return`x-${t}-${e}`}function ha(t,e){return`--${t}-${e}`}function ya(t,e){const n=i=>i.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function fn(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}function jf(t){const e=new Set,n=[];for(const i of t){const o=fn(i);let r=o,s=2;for(;e.has(r);)r=`${o}_${s}`,s+=1;e.add(r),n.push(r)}return n}function Tf(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function wa(t){return t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ye(t){return wa(JSON.stringify(t))}function Of(t,e=3e3){if(t==null)return e;if(typeof t!="string"&&typeof t!="number")throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);if(typeof t=="string"&&t.trim()==="")throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);const n=Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new TypeError(`apigen: invalid port option ${JSON.stringify(t)} — expected an integer in [0, 65535]`);return n}function ci(t){return t.anyOf??t.oneOf}function If(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="array"||i.type==="object")}return!1}function $f(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="boolean")}return!1}function Cf(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=ci(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="number"||i.type==="integer")}return!1}function Pf(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function Lf(t){var o,r;const e=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data,n=(e==null?void 0:e.properties)??{},i=(e==null?void 0:e.required)??[];return{props:n,required:i}}function Nr(t){return typeof t.handler=="function"}function Uf(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i=[];for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd",a=ga(s,r);i.push({field:r,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:ha(s,r),envVar:ya(s,r)})}return i}function Df(t,e,n,i){e===n||t.has(e)||t.set(e,{...i,aliasOf:n})}function Mf(t,e){const n=new Map,{props:i}=Lf(t);for(const[o,r]of Object.entries(i)){let s="string";$f(r)?s="boolean":(If(r)||Cf(r))&&(s="json");const a=Pf(o),c={camelKey:o,kind:"domain",valueKind:s};n.set(a,c),Df(n,o,a,c)}for(const o of e){const r=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(r,s)}return n}function Oe(t){const{op:e,schema:n,transport:i,projection:o}=t,r=qe(e,o),s=n?Uf(n):[],a=n?Mf(n,s):new Map,c=n?ua(n).params:void 0,d={op:e,transport:i,http:r.http,mcp:r.mcp,cli:r.cli,grpc:r.grpc,params:c,envelope:s,cliFlags:a,streaming:e.streaming,isMount:Nr(e)};if(Nr(e)){const l=e.handler;d.mountHandler=async u=>l(u)}return d}function di(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function xf(t){const e=t.exitCode;return typeof e=="function"?e:void 0}function li(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function Ff(t){return async function(n,i){const o=Object.assign(n,{data:n.domainArgs});return await t.layer(o,i)}}function Ee(t,e){var i;const n=[];for(const o of e){const r=(i=o.capabilities)==null?void 0:i.layer;r&&n.push(Ff(r))}return n.push(cf(t)),Jl(n)}function Bf(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const Kf={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function st(t,e,n,i){const o={...n,operation:{id:t.op.id},ctx:new Pt};if(t.isMount){const r=t.mountHandler;if(!r)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const s={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:Bf(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...i,fns:{[t.op.id]:()=>r(s)},schemas:{[t.op.id]:Kf}};return e(t.op.id,o,a)}return e(t.op.id,o,i)}function va(t){return t.anyOf??t.oneOf}function qf(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i=[];for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd";i.push({field:r,pluginId:s,flag:ha(s,r),envVar:ya(s,r)})}return i}function _o(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=va(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="array"||i.type==="object")}return!1}function Hf(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=va(t);if(e){const n=e.filter(i=>i.type!=="null");return n.length>0&&n.every(i=>i.type==="boolean")}return!1}function Rr(t){var o,r;const e=(r=(o=t.input)==null?void 0:o.properties)==null?void 0:r.data,n=(e==null?void 0:e.properties)??{},i=(e==null?void 0:e.required)??[];return{props:n,required:i}}function Vf(t){const e=/^#\/oneOf\/(\d+)$/.exec(t);if(e)return Number(e[1])}function Gf(t){const n=ui(t).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function Qn(t){var r,s;const e=(s=(r=t.input)==null?void 0:r.properties)==null?void 0:s.data;if(!e)return;const n=e.oneOf,i=e.discriminator;if(!n||!i)return;const o=[];for(const[a,c]of Object.entries(i.mapping)){const d=Vf(c);if(d===void 0)continue;const l=n[d];if(!l)continue;const u=l.properties??{},f=l.required??[];o.push({value:a,commandName:Gf(a),props:u,required:f})}if(o.length!==0)return{discriminatorProperty:i.propertyName,branches:o}}function ui(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function Wf(t,e){if(!ao.isAbsolute(e))return e;const n=ao.relative(t,e);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Jf=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
|
|
3
|
+
`);function ba(t,e,n){for(const i of e){const o=i.flag.replace(/^--/,"");t.push(` .option('${i.flag} <${o}>', '${i.field} (env: ${i.envVar})')`)}n&&!e.some(i=>i.field==="session")&&t.push(" .option('--session <key>', 'Session key')")}function Ea(t,e,n,i){var o;for(const r of e){const s=ui(r),a=Hf(n[r]),c=i.includes(r);a?(t.push(` .option('--${s}')`),((o=n[r])==null?void 0:o.default)===!0&&t.push(` .option('--no-${s}')`)):c?t.push(` .requiredOption('--${s} <${s}>')`):t.push(` .option('--${s} <${s}>')`)}}function Sa(t,e,n){return`${t}:${e}::${n}`}function ka(t,e){const{varName:n,pkgId:i,fnName:o,bindings:r,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=e,l=e.dispatchSchemaKey??`${i}:${o}`;t.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([m,p])=>`'${m}': ${p}`),f=a.map(m=>_o(c[m])?`'${m}': __apigenParseJsonArg('${ui(m)}', opts['${m}'])`:`'${m}': opts['${m}']`);if(t.push(` const domainArgs: Record<string, unknown> = { ${[...u,...f].join(", ")} }`),r.length>0){const m=r.map(p=>{const y=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(w,v)=>v.toUpperCase());return`'${p.field}': opts['${y}'] ?? process.env['${p.envVar}']`});t.push(` const envelope: Record<string, unknown> = { ${m.join(", ")} }`)}else s?t.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):t.push(" const envelope: Record<string, unknown> = {}");t.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),t.push(" console.log(JSON.stringify(result))"),t.push(" })")}function zf(t,e){const{varName:n,pkgId:i,fnName:o,bindings:r,needsSession:s,rootUnion:a}=e,c=fn(`${i}_${o}_cmd`);t.push(`const ${c} = program.command('${o}')`);for(const d of a.branches){const l=Object.keys(d.props).filter(f=>f!==a.discriminatorProperty),u=d.required.filter(f=>f!==a.discriminatorProperty);t.push(`${c}`),t.push(` .command('${d.commandName}')`),ba(t,r,s),Ea(t,l,d.props,u),ka(t,{varName:n,pkgId:i,fnName:o,dispatchSchemaKey:Sa(i,o,d.commandName),bindings:r,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function Yf(t){const e=t.options.name??"cli",n=t.options.version??"0.1.0",i=t.packages.some(s=>Object.values(s.schemas).some(a=>{const c=Qn(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>_o(l.props[u])));const{props:d}=Rr(a);return ho(a).some(l=>_o(d[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const s of t.packages){const a=fn(s.id),c=Wf(t.outputDir,s.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),i&&(o.push(Jf),o.push(""));const r=Object.fromEntries(t.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,c])));for(const s of t.packages)for(const[a,c]of Object.entries(s.schemas)){const d=Qn(c);if(d)for(const l of d.branches){const u=Sa(s.id,a,l.commandName);r[u]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(r,null,2)}`),o.push(""),o.push(`const program = new Command().name('${e}').version('${n}')`),o.push("");for(const s of t.packages){const a=fn(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=Xs(d,"session"),u=qf(d),f=Qn(d);if(f){zf(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const m=ho(d),{props:p,required:g}=Rr(d);o.push("program"),o.push(` .command('${c}')`),ba(o,u,l),Ea(o,m,p,g),ka(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,paramNames:m,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
|
|
4
|
+
`)}]}}function Xf(t){return{props:t.properties??{},required:t.required??[]}}function Qf(t){const e=t??{},i=Array.isArray(e.oneOf)&&e.oneOf.length>0?e.oneOf:[e],o={},r=new Map;for(const a of i){const{props:c,required:d}=Xf(a);for(const[l,u]of Object.entries(c))l in o||(o[l]=u);for(const l of d)r.set(l,(r.get(l)??0)+1)}const s=[...r.entries()].filter(([,a])=>a===i.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:o,required:s}},required:["data"]},output:{}}}function Zf(t){const e=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let i;for(;i=n.exec(t);)e.push(i[1]??i[2]??i[3]);return e}function ep(t){const e=t.argv;return Array.isArray(e)?e.map(String):typeof e=="string"?Zf(e):process.argv.slice(2)}function tp(t,e){return{id:t,host:"ts",namespace:{raw:t,words:[t]},path:[],kind:"action",async:!1,streaming:!1,safe:e["x-apigen-safe"]??!1,input:e.input??{},output:e.output??{},envelope:{},typeText:null}}function np(t){const e=new Map;for(const i of t.operations??[]){const o=i.path[i.path.length-1];o&&e.set(`${i.namespace.raw}:${o.raw}`,i)}const n=new Map;for(const i of t.packages)for(const[o,r]of Object.entries(i.schemas)){const s=e.get(`${i.id}:${o}`)??tp(o,r),a=Oe({op:s,schema:r,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:i.id,fnName:o,schema:r,cliPath:c,plan:a})}return n}function op(t,e){let n=0;for(;n<t.length&&!t[n].startsWith("-");)n++;for(let i=n;i>=1;i--){const o=e.get(t.slice(0,i).join(" "));if(o)return{entry:o,rest:t.slice(i)}}return null}function _a(t){return!t||t.length===0?"":t.map(e=>`${e.name}${e.required?"":"?"}: ${e.type}`).join(", ")}function ip(t){return[...t.cliFlags.entries()].filter(([,e])=>e.aliasOf===void 0).map(([e])=>e).sort()}function jr(t){const e=[...t.entries()].sort(([s],[a])=>s.localeCompare(a)),n=[],i=[];for(const s of e)(s[1].plan.isMount?n:i).push(s);const o=([s,{plan:a}])=>{const c=_a(a.params),d=ip(a),l=d.length?` [${d.map(u=>`--${u}`).join(", ")}]`:" (no flags)";return` ${s}${c?` { ${c} }`:""}${l}`},r=["Available commands:","","Namespaced verbs (namespace + verb):"];if(n.length===0)r.push(" (none)");else for(const s of n)r.push(o(s));if(r.push(""),r.push("Verbs (one-token):"),i.length===0)r.push(" (none)");else for(const s of i)r.push(o(s));return r.push(""),r.push("Each command lists the flags it accepts in [brackets]."),r.join(`
|
|
5
|
+
`)}function Zt(t){return new z("invalid_argument",t)}function rp(t,e){var r;const n={},i={};let o=0;for(;o<t.length;){const s=t[o];if(!s.startsWith("--"))throw Zt(`Unexpected positional argument: "${s}"`);let a=s.slice(2),c;const d=a.indexOf("=");d!==-1&&(c=a.slice(d+1),a=a.slice(0,d));let l=!1,u=a;a.startsWith("no-")&&((r=e.get(a.slice(3)))==null?void 0:r.valueKind)==="boolean"&&(l=!0,u=a.slice(3));const f=e.get(u);if(!f)throw Zt(`Unknown option: --${a}. Available: ${[...e.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);o++;let m;if(f.valueKind==="boolean")l?m=!1:c===void 0?m=!0:m=c!=="false";else{const p=c!==void 0?c:t[o++];if(p===void 0)throw Zt(`Missing value for --${a}`);if(f.valueKind==="json")try{m=JSON.parse(p)}catch(g){throw Zt(`Invalid JSON for --${a}: ${g.message}`)}else m=p}f.kind==="domain"?n[f.camelKey]=m:i[f.camelKey]=m}for(const s of e.values()){if(s.kind!=="envelope"||!s.envVar||i[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(i[s.camelKey]=a)}return{domainArgs:n,envelope:i}}function Aa(t){const e=fe(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:String(t)};console.error(JSON.stringify(e)),process.exitCode=fe(t)?hr[t.code]:hr.internal}function sp(t,e,n){if(fe(n)&&n.code!=="internal"){t.error({command:e,code:n.code,message:n.message},`✗ ${e}`);return}t.error({command:e,err:n},`✗ ${e}`)}class ap{constructor(e,n){this.signal=e,this.exitCodeHook=n,this.routes=new Map}registerRoute(e,n){this.routes.set(e.cli.path.join(" "),{plan:e,dispatch:n})}routeTable(){return this.routes}readCall(e,n){const{domainArgs:i,envelope:o}=rp(e.rest,n.cliFlags);return{domainArgs:i,envelope:o,signal:this.signal}}writeResult(e,n,i){var r;if($n(n))throw new z("invalid_argument",`Command "${i.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const o=(r=this.exitCodeHook)==null?void 0:r.call(this,n);typeof o=="number"&&o!==0&&(process.exitCode=o)}writeError(e,n,i){Aa(n)}}function cp(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("cli")||r.push(u)}return r}async function dp(t){var E,N,k;const e=t.logger??ai();if((E=t.signal)!=null&&E.aborted){e.info("cli run: signal already aborted before dispatch — skipping");return}let n=ep(t.options);n[0]==="--"&&(n=n.slice(1));const i=di(t.options),o=li(t.options),r=new ap(t.signal,xf(t.options)),s=np(t),a=new Map;for(const R of s.values()){const A=a.get(R.pkgId);A?A.push(R):a.set(R.pkgId,[R])}const c={},d={};for(const R of t.packages){const A=a.get(R.id);if(!A||A.length===0)continue;if(!R.fns)throw new Error(`apigen-plugin-cli-output: package "${R.id}" has no functions`);const O=R.fns,I={},L={};for(const H of A)I[H.plan.op.id]=H.schema,L[H.plan.op.id]=O[H.fnName],c[H.plan.op.id]=H.schema,d[H.plan.op.id]=O[H.fnName];const $=Ee(I,i),Y={fns:L,createClient:R.createClient,schemas:I};for(const H of A)r.registerRoute(H.plan,ge=>st(H.plan,$,ge,Y))}const l=((N=t.packages[0])==null?void 0:N.id)??"ts",u=Ee(c,i),f={invoke:(R,A,O)=>u(R,{operation:{id:R},ctx:new Pt,domainArgs:A.domainArgs,envelope:A.envelope,signal:A.signal},O),invokeOptions:{fns:d,schemas:c,createClient:(k=t.packages[0])==null?void 0:k.createClient}},m=cp(i,o,l,t.operations??[],f);if(m.length>0){const R=Ee({},i),A={fns:{},schemas:{}};for(const O of m){const I=Oe({op:O,schema:Qf(O.input),transport:"cli"});r.registerRoute(I,L=>st(I,R,L,A))}}const p=r.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(jr(p));return}const g=op(n,p);if(!g){Aa(new z("not_found",`Unknown command: ${n.join(" ")}
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${jr(p)}`));return}const{entry:y,rest:w}=g,{plan:v,dispatch:b}=y,h=v.cli.path.join(" ");if(w.includes("--help")||w.includes("-h")){const R=_a(v.params);console.log(`${h}${R?` { ${R} }`:""}`);return}const S={rest:w};try{if(v.streaming)throw new z("invalid_argument",`Command "${h}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const R=await r.readCall(S,v),A=Date.now(),O=await b(R);await r.writeResult(S,O,v),e.info({command:h,ms:Date.now()-A},`→ ${h}`)}catch(R){sp(e,h,R),await r.writeError(S,R,v)}}const lp={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(t){return Yf(t)},run(t){return dp(t)}};function up(t,e){const n=t.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const i=n,o=i.operation;if(typeof o!="string"||o.length===0)throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!e.includes(o))throw new z("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${e.join(", ")}`);const r=i.items;if(!Array.isArray(r))throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=i.concurrency;if(s!==void 0&&typeof s!="number")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=i.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=i.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=i.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new z("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:r,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function fp(t,e){return async n=>{if(!e)throw new z("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const i=up(n.data,t),o={concurrency:i.concurrency,mode:i.mode,onItemError:i.onItemError,itemTimeoutMs:i.itemTimeoutMs},r=i.items.map(s=>({operation:{id:i.operation},ctx:new Pt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return Nf(e.invoke,i.operation,r,e.invokeOptions,o)}}function pp(t,e={},n){return Yu(t,e).map(o=>({...o,handler:fp(o.operationIds,n)}))}const pn={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(t,e,n){return pp(t,e,n)}}}},Tr={validateKind(){},validateRel(){},validateEdge(){}},mp=5,gp=20,hp=500;function yp(t){return Ne.isBusyError(t)||Ne.isConcurrentConflict(t)}function wp(t){return new Promise(e=>setTimeout(e,Math.max(0,Math.round(t))))}async function vp(t,e={}){const n=e.maxAttempts??mp;for(let i=0;;i++)try{return await t()}catch(o){if(!yp(o)||i>=n-1)throw o;const r=Math.min(hp,gp*2**i);await wp(r*(.5+Math.random()*.5))}}const fi=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit","attestation","obligation","SPEC"]);class Na extends Error{constructor(e,n){const i=e.length>0?e.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
|
|
8
8
|
expected node kind(s): ${n.join(", ")}
|
|
9
|
-
found in store: ${
|
|
9
|
+
found in store: ${i}
|
|
10
10
|
The store holds live node(s) but none of a kind this build recognizes, so every item read would match zero rows and report a misleading "0 items".
|
|
11
|
-
Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=t,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function Vi(e){const{rows:t}=await e.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=t.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,i)=>o+i.count,0),observed:n}}async function Cl(e){const t=[...io],n=t.map(()=>"?").join(", "),{rows:r}=await e.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,t);return r.length>0}async function so(e){if(await Cl(e))return;const{total:t,observed:n}=await Vi(e);if(t!==0)throw new Hi(n,[...io])}function Rn(){return[]}function Pl(e){const t=z.homedir();if(e===t)return"~";const n=t.endsWith(k.sep)?t:t+k.sep;return e.startsWith(n)?"~"+e.slice(t.length):e}function Ll(e,t){if(e===t)return!0;const n=k.relative(e,t);return n!==".."&&!n.startsWith(`..${k.sep}`)&&!k.isAbsolute(n)}function ao(e){const t=e==null?void 0:e.code;return t==="ENOENT"||t==="ENOTDIR"}async function On(e){const t=k.resolve(e);try{return await Pt.realpath(t)}catch(n){if(!ao(n))throw n;const r=k.dirname(t);if(r===t)throw n;return k.join(await On(r),k.basename(t))}}async function Gi(e,t,n){const r=k.isAbsolute(t)?k.resolve(t):k.resolve(e,t),o=await On(r);return{accepted:(await Promise.all([e,...n].map(a=>On(a)))).some(a=>Ll(a,o)),candidate:o}}class q extends Error{constructor(t,n=void 0,r){super(t),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class Wi extends q{constructor(t,n){super(`Write contention: exhausted the retry budget (last backoff ${t}ms)`,n,t),this.code="E_CONTENTION",this.retryable=!0}}class Ji extends q{constructor(t){const n=zi(t);super(`Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction: ${n.message}`,t),this.code="E_IO",this.retryable=!0,this.causeMessage=n.message,n.code!==void 0&&(this.causeCode=n.code)}}function zi(e){if(e instanceof Error){const t=e.code;return{message:e.message,...typeof t=="string"?{code:t}:{},...e.stack!==void 0?{stack:e.stack}:{}}}if(typeof e=="object"&&e!==null){const t=e;return{message:typeof t.message=="string"?t.message:JSON.stringify(e),...typeof t.code=="string"?{code:t.code}:{}}}return{message:String(e)}}const xl="backlog.write.io_failure";function Tn(e,t,n){const r=zi(e);qn.log.error(xl,{origin:t,retryable:n,error:r.message,...r.code!==void 0?{error_code:r.code}:{},...r.stack!==void 0?{stack:r.stack}:{}})}class Ft extends q{constructor(t,n){super(n===void 0?`Issue "${t}" was already superseded by a concurrent write; re-get and retry`:`Issue "${t}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=t,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class W extends q{constructor(t,n){super(`${t} "${n}" was not found`),this.catalogKind=t,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class Ul extends q{constructor(t,n,r){super(`${t} "${r}" differs only by letter case from the existing live ${t} "${n}"; catalog identity is exact-case, so accepting it would mint a duplicate row. Use the existing spelling "${n}".`),this.catalogKind=t,this.canonicalName=n,this.offendingName=r,this.code="E_VALIDATION",this.retryable=!1}}class T extends q{constructor(t,n){super(n?`Invalid argument "${t}": ${n}`:`Invalid argument "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}class Bt extends q{constructor(t){super(`No live issue found for uid "${t}"`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Nt extends q{constructor(t,n){super(`Claim already held by "${t}" since ${n}`),this.heldBy=t,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class Yi extends q{constructor(t,n){super(`Issue "${t}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=t,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class In extends q{constructor(t){const n=t.side==="source"?`"${t.rel}" already has a single target (${t.conflictingUid}) for source "${t.cappedUid}"`:`"${t.rel}" already has a single source (${t.conflictingUid}) for target "${t.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=t.side,this.cappedUid=t.cappedUid,this.rel=t.rel,this.conflictingUid=t.conflictingUid}}class co extends q{constructor(t,n){const r=n.length===0?"the project root":n.map(Pl).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots";super(`Citation target "${t}" could not be verified and this project requires a real sha — accepted only under: ${r} (${o})`),this.target=t,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class Dl extends q{constructor(t){super(`Citation target "${t}" is a directory, not a file — a citation must name a file inside it (use the citation's \`lines\` field for a range) so its content can be hashed`),this.target=t,this.code="E_VALIDATION",this.retryable=!1}}function Xi(e,t){return(e==null?void 0:e.code)==="EISDIR"?new Dl(t):(Tn(e,"citation_sha",!0),new Ji(e))}class Qi extends q{constructor(t){super(`A note is required to transition issue "${t}" (project_policy.transition_requires_note)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Zi extends q{constructor(t){super(`At least one citation is required to close issue "${t}" (project_policy.citation_required)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Re extends q{constructor(t,n){super(n?`Invalid "${t}": ${n}`:`Invalid "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}function Ml(e){const t=e instanceof Error?e.message:String(e);return ge.isBusyError(e)||ge.isConcurrentConflict(e)?{code:"E_CONTENTION",retryable:!0,message:t,cause:e}:ge.isUniqueConstraintError(e)||ge.isForeignKeyError(e)?{code:"E_CONSTRAINT",retryable:!1,message:t,cause:e}:ge.isDatabaseError(e)?(Tn(e,"transaction",!0),{code:"E_IO",retryable:!0,message:t,cause:e}):(Tn(e,"transaction",!1),{code:"E_IO",retryable:!1,message:t,cause:e})}const Fl=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function Z(e,t){if(Fl.has(t.trim().toLowerCase()))throw new T(e,`"${t}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}function es(e){if(e!=null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}function ts(e){return{rowid:e.rowid,uid:e.uid,kind:e.kind,name:e.name,content:e.content??"",metadata:es(e.meta),tInvalid:e.t_invalid,isSuperseded:e.is_superseded===1}}function U(){return new Date().toISOString()}function lo(e){return pe.createHash("sha256").update(e).digest("hex")}function ns(e){return JSON.stringify($n(e))}function $n(e){if(Array.isArray(e))return e.map($n);if(e!==null&&typeof e=="object"){const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=$n(t[r]));return n}return e}async function qt(e,t){const n=await e.executeGet("SELECT * FROM node WHERE uid = ?",[t]);return n?ts(n):null}async function be(e,t){const n=await qt(e,t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid!==null)throw new Bt(t);if(n.isSuperseded)throw new Ft(t);return n}async function ee(e,t){const n=await e.executeGet("SELECT * FROM node WHERE rowid = ?",[t]);return n?ts(n):null}const Bl=["off","on"];function ql(){const e=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(e===void 0)return"off";if(Bl.includes(e))return e;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${e}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function J(e,t){const n=t.at??U(),r=t.content??t.name??"",o=lo(r.trim().toLowerCase());if(ql()==="on"){const c=await e.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const i=pe.randomUUID(),s=t.metadata!==void 0?JSON.stringify(t.metadata):null,a=await e.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
|
|
11
|
+
Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=e,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function Ra(t){const{rows:e}=await t.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=e.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,r)=>o+r.count,0),observed:n}}async function bp(t){const e=[...fi],n=e.map(()=>"?").join(", "),{rows:i}=await t.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,e);return i.length>0}async function pi(t){if(await bp(t))return;const{total:e,observed:n}=await Ra(t);if(e!==0)throw new Na(n,[...fi])}const Ep=3e4,Or=new WeakMap;function Sp(t){let e=Or.get(t);return e||(e=new Set,Or.set(t,e)),e}function ja(t){const e=Sp(t);return{register(n){e.add(n);let i=!1;return()=>{i||(i=!0,e.delete(n))}},get size(){return e.size},snapshot(){return[...e]},async drain(n){const i=(n==null?void 0:n.timeoutMs)??Ep,o=Date.now()+i;let r=0;for(;;){const a=[...e].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const d=await kp(Promise.allSettled(a.map(l=>l.settled)),c);if(r+=a.filter(l=>l.outcome!=="pending").length,d==="timeout")break}const s=[...e];return{drained:r,stillPending:s.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:s.filter(a=>a.outcome==="unrecorded")}}}}async function kp(t,e){let n;const i=new Promise(o=>{n=setTimeout(()=>o("timeout"),e),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([t,i])}finally{n!==void 0&&clearTimeout(n)}}function Ao(){return[]}function Ir(t){const e=te.homedir();if(t===e)return"~";const n=e.endsWith(_.sep)?e:e+_.sep;return t.startsWith(n)?"~"+t.slice(e.length):t}function Ta(t,e){if(t===e)return!0;const n=_.relative(t,e);return n!==".."&&!n.startsWith(`..${_.sep}`)&&!_.isAbsolute(n)}function Oa(t){const e=t==null?void 0:t.code;return e==="ENOENT"||e==="ENOTDIR"}async function No(t){const e=_.resolve(t);try{return await zo.realpath(e)}catch(n){if(!Oa(n))throw n;const i=_.dirname(e);if(i===e)throw n;return _.join(await No(i),_.basename(e))}}async function _p(t,e,n){const i=_.isAbsolute(e)?_.resolve(e):_.resolve(t,e),o=await No(i);return{accepted:(await Promise.all([t,...n].map(a=>No(a)))).some(a=>Ta(a,o)),candidate:o}}function Ia(t){const e=te.homedir();return[_.join(e,".claude","skills","backlog"),_.join(process.env.CODEX_HOME??_.join(e,".codex"),"skills","backlog"),_.join(e,".config","opencode","skills","backlog")]}async function Lt(t,e){const{rows:n}=await t.executeAll("SELECT uid, meta FROM node WHERE kind = 'project' AND t_invalid IS NULL"),i=[];for(const o of n){if(o.uid===e||o.meta===null)continue;let r;try{r=JSON.parse(o.meta)}catch{continue}if(r===null||typeof r!="object")continue;const s=r.path;typeof s=="string"&&s.length>0&&i.push(s)}return i}class C extends Error{constructor(e,n=void 0,i){super(e),this.name=new.target.name,this.cause=n,this.retry_after_ms=i}}class $a extends C{constructor(e,n){super(`Write contention: exhausted the retry budget (last backoff ${e}ms)`,n,e),this.code="E_CONTENTION",this.retryable=!0}}class Ca extends C{constructor(e){const n=Pa(e);super(`Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction: ${n.message}`,e),this.code="E_IO",this.retryable=!0,this.causeMessage=n.message,n.code!==void 0&&(this.causeCode=n.code)}}function Pa(t){if(t instanceof Error){const e=t.code;return{message:t.message,...typeof e=="string"?{code:e}:{},...t.stack!==void 0?{stack:t.stack}:{}}}if(typeof t=="object"&&t!==null){const e=t;return{message:typeof e.message=="string"?e.message:JSON.stringify(t),...typeof e.code=="string"?{code:e.code}:{}}}return{message:String(t)}}const Ap="backlog.write.io_failure";function Ro(t,e,n){const i=Pa(t);Jo.log.error(Ap,{origin:e,retryable:n,error:i.message,...i.code!==void 0?{error_code:i.code}:{},...i.stack!==void 0?{stack:i.stack}:{}})}class Ut extends C{constructor(e,n){super(n===void 0?`Issue "${e}" was already superseded by a concurrent write; re-get and retry`:`Issue "${e}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=e,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class V extends C{constructor(e,n){super(`${e} "${n}" was not found`),this.catalogKind=e,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class mi extends C{constructor(e,n){super(`uid prefix "${e}" is ambiguous — ${n.length} items match: `+n.map(i=>`${i.uid} (${i.kind} "${i.name}")`).join(", ")+". Re-run with a longer prefix or the full uid."),this.ref=e,this.candidates=n,this.code="E_VALIDATION",this.retryable=!1}}class Np extends C{constructor(e,n,i){super(`${e} "${i}" differs only by letter case from the existing live ${e} "${n}"; catalog identity is exact-case, so accepting it would mint a duplicate row. Use the existing spelling "${n}".`),this.catalogKind=e,this.canonicalName=n,this.offendingName=i,this.code="E_VALIDATION",this.retryable=!1}}class T extends C{constructor(e,n){super(n?`Invalid argument "${e}": ${n}`:`Invalid argument "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class mn extends C{constructor(e,n=!1){super(n?`No live issue found — no item matches the uid prefix "${e}"`:`No live issue found for uid "${e}"`),this.uid=e,this.asPrefix=n,this.code="E_VALIDATION",this.retryable=!1}}class gn extends C{constructor(e,n){super(`Claim already held by "${e}" since ${n}`),this.heldBy=e,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class La extends C{constructor(e,n){super(`Issue "${e}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=e,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class jo extends C{constructor(e){const n=e.side==="source"?`"${e.rel}" already has a single target (${e.conflictingUid}) for source "${e.cappedUid}"`:`"${e.rel}" already has a single source (${e.conflictingUid}) for target "${e.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=e.side,this.cappedUid=e.cappedUid,this.rel=e.rel,this.conflictingUid=e.conflictingUid}}class Ua extends C{constructor(e,n){const i=n.length===0?"the project root":n.map(Ir).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots",r=Ia().map(Ir).join(", ");super(`Citation target "${e}" could not be verified and this project requires a real sha — accepted only under: ${i} (${o}). Tool-owned roots are always accepted: ${r}`),this.target=e,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class Rp extends C{constructor(e){super(`Citation target "${e}" is a directory, not a file — a citation must name a file inside it (use the citation's \`lines\` field for a range) so its content can be hashed`),this.target=e,this.code="E_VALIDATION",this.retryable=!1}}function jp(t,e){return(t==null?void 0:t.code)==="EISDIR"?new Rp(e):(Ro(t,"citation_sha",!0),new Ca(t))}class Da extends C{constructor(e){super(`A note is required to transition issue "${e}" (project_policy.transition_requires_note)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Ma extends C{constructor(e){super(`At least one citation is required to close issue "${e}" (project_policy.citation_required)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class _e extends C{constructor(e,n){super(n?`Invalid "${e}": ${n}`:`Invalid "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class Ue extends C{constructor(e,n){super(n?`Invalid anchor locator "${e}": ${n}`:`Invalid anchor locator "${e}"`),this.locator=e,this.code="E_VALIDATION",this.retryable=!1}}class xa extends C{constructor(e){super(`No live attestation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class ve extends C{constructor(e){super(`Invalid predicate: ${e}`),this.detail=e,this.code="E_VALIDATION",this.retryable=!1}}class Fa extends C{constructor(e){super(`No live obligation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class To extends C{constructor(e,n){super(`spec revision conflict: base_revision "${e}" does not match the current revision "${n}" — re-read the ticket's spec_revision and retry`),this.expected=e,this.actual=n,this.code="E_VALIDATION",this.retryable=!1}}function Tp(t){const e=t instanceof Error?t.message:String(t);return Ne.isBusyError(t)||Ne.isConcurrentConflict(t)?{code:"E_CONTENTION",retryable:!0,message:e,cause:t}:Ne.isUniqueConstraintError(t)||Ne.isForeignKeyError(t)?{code:"E_CONSTRAINT",retryable:!1,message:e,cause:t}:Ne.isDatabaseError(t)?(Ro(t,"transaction",!0),{code:"E_IO",retryable:!0,message:e,cause:t}):(Ro(t,"transaction",!1),{code:"E_IO",retryable:!1,message:e,cause:t})}const Op=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function G(t,e){if(Op.has(e.trim().toLowerCase()))throw new T(t,`"${e}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}class gi extends C{constructor(e){const n=e.required_kind!==void 0?` (requires "${e.required_kind}")`:"";super(`Transition refused: ${e.code}${n} — ${e.message}`),this.refusal=e,this.code="E_VALIDATION",this.retryable=!1}}class Oo extends C{constructor(e,n){super(`Override not permitted: actor "${n}" may not override obligation "${e}" (the actor is not listed in override.actors, or no override reason was recorded — an override always requires a reason)`),this.obligationUid=e,this.actor=n,this.code="E_VALIDATION",this.retryable=!1}}class hi extends C{constructor(e){const n=e.subject!==void 0?` ${e.subject}`:"";super(`Claim refused: ${e.code}${n} — ${e.message??"a block-severity condition is live"}`),this.refusal=e,this.code="E_VALIDATION",this.retryable=!1}}class Ba extends C{constructor(e){super(`No live citation found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}const Ip=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function pe(t){return Ip.test(t)}const yi=8,Ka=/^[0-9a-f-]+$/i,$p=new Set([8,13,18,23]);function Dt(t){if(t.length<yi||t.length>=36||!Ka.test(t))return!1;for(let e=0;e<t.length;e+=1){const n=t[e];if($p.has(e)){if(n!=="-")return!1}else if(n==="-")return!1}return!0}function Rt(t){return pe(t)?"exact":Dt(t)?"prefix":t.length>0&&t.length<yi&&Ka.test(t)?"too-short":"not-uid"}async function qa(t,e){const n=e.toLowerCase(),{rows:i}=await t.executeAll("SELECT uid, kind, name, is_superseded FROM node WHERE uid >= ? AND uid < ? AND t_invalid IS NULL",[n,`${n}`]);return i.map(o=>({uid:o.uid,kind:o.kind,name:o.name,isSuperseded:o.is_superseded===1}))}function Ha(t,e){if(e.length===0)return null;if(e.length===1)return e[0];throw new mi(t,e.map(n=>({uid:n.uid,kind:n.kind,name:n.name??""})))}function ze(t,e,n){return t==="issue"?new mn(e,n):new V(t??"uid",e)}function Va(t){return new T("uid",`uid prefix "${t}" is too short — a uid prefix must be at least ${yi} characters (or pass the full uid)`)}function wi(t){if(t!=null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function Ga(t){return{rowid:t.rowid,uid:t.uid,kind:t.kind,name:t.name,content:t.content??"",metadata:wi(t.meta),tInvalid:t.t_invalid,isSuperseded:t.is_superseded===1}}function P(){return new Date().toISOString()}function He(t){return ke.createHash("sha256").update(t).digest("hex")}function vi(t){return JSON.stringify(Io(t))}function Io(t){if(Array.isArray(t))return t.map(Io);if(t!==null&&typeof t=="object"){const e=t,n={};for(const i of Object.keys(e).sort())e[i]!==void 0&&(n[i]=Io(e[i]));return n}return t}async function Be(t,e){const n=await t.executeGet("SELECT * FROM node WHERE uid = ?",[e]);return n?Ga(n):null}async function se(t,e,n){const i=n==null?void 0:n.expectedKind,o=await Be(t,e);if(o){if(o.tInvalid!==null||i!==void 0&&o.kind!==i)throw ze(i,e,!1);return o}const r=Rt(e);if(r==="too-short")throw Va(e);if(r!=="prefix")throw ze(i,e,!1);const s=await qa(t,e),a=i!==void 0?s.filter(l=>l.kind===i):s,c=Ha(e,a);if(!c)throw ze(i,e,!0);const d=await Be(t,c.uid);if(!d||d.tInvalid!==null)throw ze(i,e,!0);return d}async function ae(t,e){const n=await se(t,e,{expectedKind:"issue"});if(n.isSuperseded)throw new Ut(e);return n}async function Q(t,e){const n=await t.executeGet("SELECT * FROM node WHERE rowid = ?",[e]);return n?Ga(n):null}const Cp=["off","on"];function Pp(){const t=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(t===void 0)return"off";if(Cp.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${t}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function X(t,e){const n=e.at??P(),i=e.content??e.name??"",o=He(i.trim().toLowerCase());if(Pp()==="on"){const c=await t.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const r=ke.randomUUID(),s=e.metadata!==void 0?JSON.stringify(e.metadata):null,a=await t.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
|
|
12
12
|
confidence, content_hash, namespace, meta, agent_id, session_id, source,
|
|
13
13
|
project_path, t_occurred, t_expires, t_created, t_valid)
|
|
14
14
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
-
RETURNING rowid`,[
|
|
16
|
-
WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[
|
|
17
|
-
WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[
|
|
15
|
+
RETURNING rowid`,[r,e.kind,i,e.name??null,null,null,null,1,null,o,"global",s,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${e.kind}" name="${e.name??""}"`);return{rowid:a.rowid,uid:r}}async function Lp(t,e){const{multiplicity:n}=e.rule;if(n==="n:m")return;if(n==="n:1"){const o=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
|
|
16
|
+
WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[e.srcRowid,e.rel,e.dstRowid]);if(o)throw new jo({side:"source",cappedUid:e.srcUid,rel:e.rel,conflictingUid:o.uid});return}const i=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
|
|
17
|
+
WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[e.dstRowid,e.rel,e.srcRowid]);if(i)throw new jo({side:"target",cappedUid:e.dstUid,rel:e.rel,conflictingUid:i.uid})}async function K(t,e){const{rule:n}=e;if(n.sourceKind!=="*"&&n.sourceKind!==e.srcKind)throw new $r(e.rel,"source",n.sourceKind,e.srcKind);if(n.targetKind!==e.dstKind)throw new $r(e.rel,"target",n.targetKind,e.dstKind);await Lp(t,e),e.typePolicy.validateEdge?e.typePolicy.validateEdge(e.srcKind,e.rel,e.dstKind):e.typePolicy.validateRel(e.rel);const i=e.at??P(),o=e.metadata!==void 0?JSON.stringify(e.metadata):null;await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
|
|
18
18
|
VALUES (?, ?, ?, ?, 'user_asserted', ?, ?, ?)
|
|
19
19
|
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
20
20
|
meta = excluded.meta, weight = excluded.weight,
|
|
21
|
-
t_invalid = NULL, t_valid = excluded.t_valid`,[
|
|
21
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[e.srcRowid,e.dstRowid,e.rel,e.weight??1,o,i,i])}class $r extends C{constructor(e,n,i,o){super(`"${e}" requires a ${n} of kind "${i}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function ie(t,e){const n=await t.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e.srcRowid,e.dstRowid,e.rel]);if(!n)return;const i=e.at??P(),o={...wi(n.meta)??{},invalidatedAt:i,...e.reason!==void 0?{invalidatedReason:e.reason}:{}};await t.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[i,JSON.stringify(o),n.rowid])}async function $o(t,e,n,i){const o=await t.executeGet("SELECT rowid, meta FROM node WHERE uid = ?",[e]);if(!o)return null;const r=wi(o.meta)??{};if((typeof r.revision=="number"&&Number.isFinite(r.revision)?r.revision:0)!==i)return null;const a=i+1,c={...r,...n,revision:a};return(await t.executeRun(`UPDATE node SET meta = ?, t_updated = ?
|
|
22
|
+
WHERE uid = ? AND COALESCE(json_extract(meta, '$.revision'), 0) = ?`,[JSON.stringify(c),P(),e,i])).rowsAffected===1?a:null}const en=[250,500];function Up(t){return new Promise(e=>setTimeout(e,t))}const Dp=["immediate","deferred"];function Mp(){const t=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(t===void 0)return"immediate";if(Dp.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${t}" is not a recognized transaction mode (expected "immediate" or "deferred"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "immediate" so a mistyped negative control can never pass for the wrong reason.`)}async function M(t,e){let n=0;for(;;)try{return await t.adapter.transaction(e,{mode:Mp()})}catch(i){if(i instanceof C)throw i;const o=Tp(i);if(o.code==="E_CONTENTION"){if(n<en.length){const r=en[n];n+=1,await Up(r);continue}throw new $a(en[en.length-1],i)}throw o.code==="E_IO"&&o.retryable?new Ca(i):i}}function F(t){return t.normalize("NFKC").toLowerCase()}function xp(){return new Set([...xt].map(t=>F(t)))}function bi(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Fp(t,e=P()){const{rows:n}=await t.adapter.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind = 'status' AND t_invalid IS NULL ORDER BY rowid ASC"),i=[],o=xp();for(const r of n){const s=F(r.name??"");if(!o.has(s))continue;const a=bi(r.meta);(a==null?void 0:a.terminal)!==!0&&i.push(r.rowid)}return{setTerminalRowids:i,at:e}}async function Bp(t,e){return M(t,async n=>{const i=[];for(const o of e.setTerminalRowids){const r=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[o]);if(!r)continue;if(r.kind!=="status")throw new Error(`applyTerminalBackfill: planned rowid ${o} is not a status row (kind="${r.kind}") — plan/DB mismatch, refusing to rewrite it.`);const s=bi(r.meta)??{},a=s.terminal===!0;if(a)continue;const c={...s,terminal:!0},d=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(c),o]);if(d.rowsAffected!==1)throw new Error(`applyTerminalBackfill: UPDATE affected ${d.rowsAffected} rows for rowid=${o}, expected exactly 1.`);i.push({rowid:r.rowid,uid:r.uid,hadTerminal:a})}return{entries:i,at:P()}})}async function Kp(t,e){await M(t,async n=>{for(const i of e.entries){const o=await n.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE rowid = ? AND t_invalid IS NULL",[i.rowid]);if(!o)continue;if(o.kind!=="status")throw new Error(`reverseTerminalBackfill: journal rowid ${i.rowid} is not a status row (kind="${o.kind}") — refusing to rewrite it.`);const s={...bi(o.meta)??{},terminal:i.hadTerminal},a=await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(s),i.rowid]);if(a.rowsAffected!==1)throw new Error(`reverseTerminalBackfill: UPDATE affected ${a.rowsAffected} rows for rowid=${i.rowid}, expected exactly 1.`)}})}function Me(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Mt(t,e,n){const i=await se(t,n,{expectedKind:e}),{name:o}=i;if(o===null)throw new V(e,n);return{...i,name:o}}async function at(t,e){if(pe(e)){const o=await Mt(t,"project",e);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[e]);if(!n)throw new V("project",e);let i;if(n.meta!==null)try{i=JSON.parse(n.meta)}catch{i=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??e,metadata:i}}async function Ei(t,e){var i;if(pe(e.ref)){const o=await Mt(t,"component",e.ref);if(((i=o.metadata)==null?void 0:i.projectUid)!==e.projectUid)throw new V("component",e.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await t.executeGet(`SELECT rowid, uid, name FROM node
|
|
22
23
|
WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
|
|
23
24
|
AND json_extract(meta, '$.projectUid') = ?
|
|
24
|
-
LIMIT 1`,[
|
|
25
|
+
LIMIT 1`,[e.ref,e.projectUid]);if(!n)throw new V("component",e.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref}}async function Wa(t,e){const n=await t.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
|
|
25
26
|
FROM edge e JOIN node c ON c.rowid = e.dst
|
|
26
27
|
WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
|
|
27
28
|
AND c.name = '(root)' AND c.t_invalid IS NULL
|
|
28
|
-
LIMIT 1`,[
|
|
29
|
+
LIMIT 1`,[e.projectRowid]);if(!n)throw new V("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}const xt=new Set(["closed","DONE","FIXED","RESOLVED","INVALID","SUPERSEDED"]),qp=new Set([...xt].map(t=>F(t)));function Hp(t){return qp.has(F(t))}const Ja=new Set(["EPIC"]),za=new Map([["EPIC","FEAT"]]),Vp=new Set([...Ja].map(t=>F(t))),Gp=new Map([...za].map(([t,e])=>[F(t),e]));function Wp(t){return Vp.has(F(t))}function Jp(t){return Gp.get(F(t))}async function zp(t,e,n){const i=F(n),{rows:o}=await t.executeAll("SELECT uid, name FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[e]);for(const r of o)if(!(r.name===null||r.name===n)&&F(r.name)===i)return{uid:r.uid,name:r.name}}async function Yp(t,e,n){const i=F(n),{rows:o}=await t.executeAll("SELECT rowid, uid, name, meta FROM node WHERE kind = ? AND t_invalid IS NULL ORDER BY rowid ASC",[e]);for(const r of o)if(r.name!==null&&F(r.name)===i)return{rowid:r.rowid,uid:r.uid,name:r.name,metadata:Me(r.meta)}}function tn(t,e,n,i){if(t!=="kind"||i===!0||!((n==null?void 0:n.lifecycle)==="deprecated")&&!Wp(e))return;const r=(typeof(n==null?void 0:n.replacedBy)=="string"?n.replacedBy:void 0)??Jp(e);throw new T("kind",`"${e}" is a deprecated kind${r?` — use "${r}" instead`:""}. Pass allowDeprecated:true only for a reviewed repair that must still write it.`)}async function xe(t,e){if(pe(e.ref)){const r=await Mt(t,e.catalogKind,e.ref);return tn(e.catalogKind,r.name,r.metadata,e.allowDeprecated),{rowid:r.rowid,uid:r.uid,name:r.name}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[e.catalogKind,e.ref]);if(n){const r=n.name??e.ref;return tn(e.catalogKind,r,Me(n.meta),e.allowDeprecated),{rowid:n.rowid,uid:n.uid,name:r}}if(e.catalogKind==="kind"){const r=await Yp(t,e.catalogKind,e.ref);if(r)return tn(e.catalogKind,r.name,r.metadata,e.allowDeprecated),{rowid:r.rowid,uid:r.uid,name:r.name}}else{const r=await zp(t,e.catalogKind,e.ref);if(r)throw new Np(e.catalogKind,r.name,e.ref)}tn(e.catalogKind,e.ref,void 0,e.allowDeprecated);const i=e.mintMetadata?await e.mintMetadata(t):{},o=await X(t,{kind:e.catalogKind,name:e.ref,metadata:i,at:e.at});return{rowid:o.rowid,uid:o.uid,name:e.ref}}async function Ya(t,e){return xe(t,{catalogKind:"status",ref:e.ref,at:e.at,mintMetadata:async()=>({terminal:Hp(e.ref)})})}async function Xa(t){const e=await t.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(e==null?void 0:e.maxRank)??null;return n===null?0:n+1}const Qa=[{rel:"owns_project",sourceKind:"project",targetKind:"component",multiplicity:"1:n"},{rel:"owns_component",sourceKind:"component",targetKind:"issue",multiplicity:"1:n"},{rel:"has_kind",sourceKind:"issue",targetKind:"kind",multiplicity:"n:1"},{rel:"has_status",sourceKind:"issue",targetKind:"status",multiplicity:"n:1"},{rel:"has_priority",sourceKind:"issue",targetKind:"priority",multiplicity:"n:1"},{rel:"authored_by",sourceKind:"issue",targetKind:"agent",multiplicity:"n:1"},{rel:"has_note",sourceKind:"issue",targetKind:"note",multiplicity:"1:n"},{rel:"has_citation",sourceKind:"issue",targetKind:"citation",multiplicity:"1:n"},{rel:"has_transition",sourceKind:"issue",targetKind:"transition",multiplicity:"1:n"},{rel:"audits",sourceKind:"*",targetKind:"audit",multiplicity:"1:n"},{rel:"depends_on",sourceKind:"component",targetKind:"component",multiplicity:"n:m"},{rel:"has_location",sourceKind:"component",targetKind:"location",multiplicity:"1:n"},{rel:"relates_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"supersedes",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"blocks",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"duplicate_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"part_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"attests",sourceKind:"*",targetKind:"attestation",multiplicity:"1:n"},{rel:"has_obligation",sourceKind:"issue",targetKind:"obligation",multiplicity:"1:n"},{rel:"satisfies",sourceKind:"obligation",targetKind:"attestation",multiplicity:"n:m"},{rel:"similar_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"}],Cr=new Map(Qa.map(t=>[t.rel,t]));async function q(t,e){const n=await t.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[e]);if(n){const o=Me(n.meta)??{},r=typeof o.source_kind=="string"?o.source_kind:void 0,s=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(r&&s&&a)return{rel:e,sourceKind:r,targetKind:s,multiplicity:a};const c=Cr.get(e);if(!c)throw new V("edge_kind",e);return await t.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[P(),n.rowid]),await X(t,{kind:"edge_kind",name:e,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const i=Cr.get(e);if(!i)throw new V("edge_kind",e);return await X(t,{kind:"edge_kind",name:e,metadata:{source_kind:i.sourceKind,target_kind:i.targetKind,multiplicity:i.multiplicity}}),i}const ee=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,citationAllowedExternalRoots:Object.freeze([]),dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[],similarityScope:"same-project",similarityCrossProjectThreshold:.92,similarityCrossProjectMargin:.05,similarityCrossProjectTokenOverlap:.5});function de(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}function Se(t){var i;const e=(i=t.metadata)==null?void 0:i.policy;if(e===null||typeof e!="object")return{...ee,citationAllowedExternalRoots:Ao()};const n=e;return{transitionRequiresNote:n.transitionRequiresNote??ee.transitionRequiresNote,citationRequired:n.citationRequired??ee.citationRequired,citationRequiresSha:n.citationRequiresSha??ee.citationRequiresSha,citationAllowedExternalRoots:Xp(n),defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??ee.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??ee.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??ee.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??ee.allowedStatuses,allowedKinds:n.allowedKinds??ee.allowedKinds,requiredFields:n.requiredFields??ee.requiredFields,similarityScope:n.similarityScope??ee.similarityScope,similarityCrossProjectThreshold:n.similarityCrossProjectThreshold??ee.similarityCrossProjectThreshold,similarityCrossProjectMargin:n.similarityCrossProjectMargin??ee.similarityCrossProjectMargin,similarityCrossProjectTokenOverlap:n.similarityCrossProjectTokenOverlap??ee.similarityCrossProjectTokenOverlap}}function Xp(t){const e=t.citationAllowedExternalRoots;return e===void 0||!Array.isArray(e)||!e.every(n=>typeof n=="string")?Ao():e}function Za(t){var n;const e=(n=t.metadata)==null?void 0:n.path;return typeof e=="string"&&e.length>0}function kt(t,e){const n={...t};for(const[i,o]of Object.entries(e))o!==void 0&&(n[i]=o);return n}async function Qp(t,e){return de("name",e.name),de("by",e.by),G("by",e.by),M(t,n=>Zp(n,t,e))}async function Zp(t,e,n){const i=P(),o=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),r={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=kt(Me(o.meta)??{},r);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:i}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}if(n.repoUrl!==void 0&&n.repoUrl.trim().length>0){const{rows:l}=await t.executeAll("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND t_invalid IS NULL ORDER BY rowid ASC"),u=l.find(f=>{var m;return((m=Me(f.meta))==null?void 0:m.repoUrl)===n.repoUrl});if(u){const f=kt(Me(u.meta)??{},r);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(f),u.rowid]),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:u.rowid,subjectUid:u.uid,subjectKind:"project",actor:n.by,action:"updated",note:"repo-url-dedupe",at:i}),{uid:u.uid,created:!1,project:{uid:u.uid,name:u.name??n.name,path:f.path,repoUrl:f.repoUrl,monorepo:f.monorepo,description:f.description}}}}const s=kt({},r),a=await X(t,{kind:"project",name:n.name,metadata:s,at:i}),c=await X(t,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:i}),d=await q(t,"owns_project");return await K(t,{at:i,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:d,typePolicy:e.typePolicy}),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:i}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function em(t,e){return de("project",e.project),de("name",e.name),de("by",e.by),G("by",e.by),M(t,n=>tm(n,t,e))}async function tm(t,e,n){const i=P(),o=await at(t,n.project),r=await t.executeGet(`SELECT rowid, uid, name, meta FROM node
|
|
29
30
|
WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
|
|
30
31
|
AND json_extract(meta, '$.projectUid') = ?
|
|
31
|
-
LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(
|
|
32
|
+
LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(r)u=kt({...Me(r.meta)??{},projectUid:o.uid},s),await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(u),r.rowid]),a=r.rowid,c=r.uid,d=r.name??n.name,l=!1;else{u=kt({projectUid:o.uid},s);const m=await X(t,{kind:"component",name:n.name,metadata:u,at:i});a=m.rowid,c=m.uid,d=n.name,l=!0}const f=await q(t,"owns_project");return await K(t,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:e.typePolicy}),await U({tx:t,typePolicy:e.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:i}),{uid:c,created:l,component:{uid:c,name:d,projectUid:o.uid,path:u.path,description:u.description}}}const Co=["path","url","tool"];async function nm(t,e){if(de("component",e.component),de("value",e.value),de("by",e.by),G("by",e.by),!Co.includes(e.locType))throw new T("locType",`must be one of ${Co.join(", ")}`);return M(t,async n=>{const i=P();let o;if(pe(e.component)){const d=await Mt(n,"component",e.component);o={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(e.project===void 0||e.project.trim().length===0)throw new T("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await at(n,e.project);o=await Ei(n,{projectUid:d.uid,ref:e.component})}const r=await n.executeGet(`SELECT rowid, uid FROM node
|
|
32
33
|
WHERE kind = 'location' AND t_invalid IS NULL
|
|
33
34
|
AND json_extract(meta, '$.componentUid') = ?
|
|
34
35
|
AND json_extract(meta, '$.locType') = ?
|
|
35
36
|
AND json_extract(meta, '$.value') = ?
|
|
36
|
-
LIMIT 1`,[o.uid,
|
|
37
|
-
|
|
38
|
-
|
|
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}
|
|
37
|
+
LIMIT 1`,[o.uid,e.locType,e.value]);if(r)return{uid:r.uid,created:!1,location:{uid:r.uid,locType:e.locType,value:e.value,componentUid:o.uid}};const s={componentUid:o.uid,locType:e.locType,value:e.value},a=await X(n,{kind:"location",name:e.value,metadata:s,at:i}),c=await q(n,"has_location");return await K(n,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:t.typePolicy}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:e.by,action:"created",at:i}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:e.locType,value:e.value,componentUid:o.uid}}})}async function om(t,e){return de("uid",e.uid),de("by",e.by),G("by",e.by),M(t,async n=>{var c;const i=P(),o=await Mt(n,"location",e.uid),r={...o.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:i},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[i,JSON.stringify(r),o.rowid]);if(s.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${s.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const d=await Be(n,a);(d==null?void 0:d.tInvalid)===null&&await ie(n,{srcRowid:d.rowid,dstRowid:o.rowid,rel:"has_location",reason:e.reason,at:i})}return await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:e.by,action:"deleted",note:e.reason,at:i}),{uid:o.uid,invalidated:!0}})}async function U(t){const e=t.at??P(),n={actor:t.actor,action:t.action,target_uid:t.subjectUid,from:t.from??null,to:t.to??null,note:t.note??null,at:e},i=He(vi(n)),o={...n,sha:i},r=await X(t.tx,{at:e,kind:"audit",name:t.action,content:t.note??t.action,metadata:o}),s=await q(t.tx,"audits");return await K(t.tx,{at:e,srcRowid:t.subjectRowid,srcUid:t.subjectUid,srcKind:t.subjectKind,dstRowid:r.rowid,dstUid:r.uid,dstKind:"audit",rel:"audits",rule:s,typePolicy:t.typePolicy}),{rowid:r.rowid,uid:r.uid,sha:i}}const im="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function Si(t,e){return`${t}
|
|
38
|
+
${e}`.trim()}function hn(t,e){const n=t.embedding;if(!n)return Promise.resolve();const i=rm(t,n,e),o={subjectRowid:e.subjectRowid,subjectUid:e.subjectUid,actor:e.actor,action:e.action,settled:i,outcome:"pending"},r=ja(t.adapter).register(o);return i.then(s=>{o.outcome=s,s!=="unrecorded"&&r()},()=>{o.outcome="unrecorded"}),i.then(()=>{})}async function rm(t,e,n){let i,o;try{if(n.action==="upsert"){const r=await e.embedDocument(n.content);await e.upsertVector(n.subjectRowid,r),i="embedding_upserted"}else await e.deleteVector(n.subjectRowid),i="embedding_deleted"}catch(r){i="embedding_failed",o=r instanceof Error?r.message:String(r),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,r)}try{await M(t,async r=>{await U({tx:r,typePolicy:t.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:i,note:o})})}catch(r){return console.error(`scheduleIssueEmbedding: failed to persist "${i}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,r),"unrecorded"}switch(i){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function sm(t,e){const n=[],i=[];for(const o of e)try{await M(t,async r=>{await U({tx:r,typePolicy:t.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:im})}),o.outcome="failed",n.push(o)}catch(r){o.outcome="unrecorded",i.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,r)}return{recorded:n,unrecorded:i}}async function yn(t,e=5e3){if(t!==":memory:"&&j.mkdirSync(_.dirname(t),{recursive:!0}),!Number.isInteger(e)||e<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${e}`);const n=await Ne.createStoreAdapter({dbPath:t});await n.pragmaSet("busy_timeout",e);const i=kl.createGraphBackend(n,{typePolicy:Tr});await vp(()=>i.applySchema());try{await pi(n)}catch(r){throw await n.close().catch(()=>{}),r}return{adapter:n,graph:i,typePolicy:Tr,flushEmbeds:r=>ja(n).drain(r)}}async function ec(t,e){const n=await t.flushEmbeds(e);let i=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const r=await sm(t,n.stillPending);i=r.recorded.length,o=[...o,...r.unrecorded]}}finally{await t.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:i,unrecorded:o}}async function Po(t){if(!t)return;let e;try{e=await ec(t)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}e.unrecorded.length>0?(console.error(`backlog: ${e.unrecorded.length} scheduled embed(s) died UNRECORDED — the store closed before they settled and the embedding_failed audit row could not be written. The subject write(s) are durable; the vector(s) are missing. Re-run the embedding backfill.`),process.exitCode||(process.exitCode=1)):e.stillPending.length>0&&console.error(`backlog: ${e.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Lo=["SIGINT","SIGTERM"];function tc(t,e=n=>process.exit(n)){let n=!1;const i=r=>{n||(n=!0,t().catch(s=>{console.error(`backlog: signal cleanup failed (${r}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{o(),e(128+te.constants.signals[r])}))},o=()=>{for(const r of Lo)process.removeListener(r,i)};for(const r of Lo)process.on(r,i);return{dispose:o}}function am(){return Lo.some(t=>process.listenerCount(t)>0)}const cm=[".git",".adhd","adhd.environment.yaml"];function Zn(t){let e=_.resolve(t);const{root:n}=_.parse(e);for(;;){for(const o of cm)if(j.existsSync(`${e}/${o}`))return e;if(e===n)return;const i=_.dirname(e);if(i===e)return;e=i}}const dm=new Set(["system","global","project"]);function lm(t,e){const n=t.cwd??process.cwd();if(t.scope)return t.scope==="project"?{scope:"project",projectRoot:Zn(n)??n}:{scope:t.scope};const i=e.ADHD_ENV_SCOPE;if(i!==void 0&&dm.has(i)){const r=i;return r==="project"?{scope:"project",projectRoot:Zn(n)??n}:{scope:r}}const o=Zn(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Pr(t){return`.${t}`}function um(t){const e=te.homedir();if(process.platform==="darwin")return _.join(e,"Library","Application Support",t);if(process.platform==="win32"){const i=process.env.APPDATA??_.join(e,"AppData","Roaming");return _.join(i,t)}const n=process.env.XDG_DATA_HOME??_.join(e,".local","share");return _.join(n,t)}function fm(t){const e=t.orgNamespace,n=t.adhdRoot??_.join(te.homedir(),Pr(e)),i=t.adhdRoot??um(e),o={system:_.join(i,t.project,t.namespace),global:_.join(n,t.project,t.namespace)};return t.projectRoot&&(o.project=_.join(t.projectRoot,Pr(e),t.project,t.namespace)),o}function nc(t,e){return e==="project"?t.project??t.global:t[e]}const pm="1.0.0-redesign.1",mm="adhd",gm="default",hm="adhd-environment.json",Ze="config.yaml",oc="config.local.yaml",ym={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Lr extends Error{constructor(e,n){super(`contentHash: lone surrogate in ${e} (not well-formed Unicode)`),this.location=e,this.offending=n,this.name="LoneSurrogateError"}}function Ur(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const i=e+1<t.length?t.charCodeAt(e+1):0;if(i<56320||i>57343)return!0;e++}else if(n>=56320&&n<=57343)return!0}return!1}function ic(t,e){const n=Array.from(t),i=Array.from(e),o=Math.min(n.length,i.length);for(let r=0;r<o;r++){const s=n[r].codePointAt(0)??0,a=i[r].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===i.length?0:n.length<i.length?-1:1}function Dr(t){return new TextEncoder().encode(t).length}function wm(t){const e=Object.keys(t).sort(ic);let n="";for(const o of e){const r=t[o];if(Ur(o))throw new Lr("key",o);if(Ur(r))throw new Lr("value",r);n+=`${Dr(o)}:${o}=${Dr(r)}:${r}
|
|
39
|
+
`}return`sha256-${rc(n)}`}function vm(t){const n=[...t].sort((i,o)=>ic(i.name,o.name)).map(i=>`${i.name}:${i.kind}:${i.scope}`).join(`
|
|
40
|
+
`);return`sha256-${rc(n)}`}function bm(t){return`ADHD_${t.toUpperCase().replace(/[.-]/g,"_")}`}function Em(t,e){return`${t}_${e.toUpperCase().replace(/[.-]/g,"_")}`}function Sm(t){const e={type:"object",properties:{}},n=t;for(const i of Object.keys(n)){const o=n[i],r=i.split(".");let s=e;r.forEach((a,c)=>{if(c===r.length-1){s.properties[a]=km(o);return}const l=s.properties[a];if(l===void 0){const u={type:"object",properties:{}};s.properties[a]=u,s=u}else s=l})}return e}function km(t){const e={type:t.type};return t.default!==void 0&&t.secret!==!0&&(e.default=t.default),t.description!==void 0&&(e.description=t.description),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.enum!==void 0&&(e.enum=t.enum),t.pattern!==void 0&&(e.pattern=t.pattern),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.items!==void 0&&(e.items=t.items),e}const _m="adhd-env-ref:";function Am(t){return`${_m}${t}`}const Nm=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Rm=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function ce(t,e){return(t>>>e|t<<32-e)>>>0}function jm(t){const e=Uint32Array.from(Rm),n=t.length*8;let i=t.length+1;for(;i%64!==56;)i++;i+=8;const o=new Uint8Array(i);o.set(t),o[t.length]=128;const r=Math.floor(n/4294967296),s=n>>>0,a=new DataView(o.buffer);a.setUint32(i-8,r,!1),a.setUint32(i-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<i;u+=64){for(let h=0;h<16;h++)c[h]=a.getUint32(u+h*4,!1);for(let h=16;h<64;h++){const S=c[h-15],E=c[h-2],N=ce(S,7)^ce(S,18)^S>>>3,k=ce(E,17)^ce(E,19)^E>>>10;c[h]=c[h-16]+N+c[h-7]+k>>>0}let f=e[0],m=e[1],p=e[2],g=e[3],y=e[4],w=e[5],v=e[6],b=e[7];for(let h=0;h<64;h++){const S=ce(y,6)^ce(y,11)^ce(y,25),E=y&w^~y&v,N=b+S+E+Nm[h]+c[h]>>>0,k=ce(f,2)^ce(f,13)^ce(f,22),R=f&m^f&p^m&p,A=k+R>>>0;b=v,v=w,w=y,y=g+N>>>0,g=p,p=m,m=f,f=N+A>>>0}e[0]=e[0]+f>>>0,e[1]=e[1]+m>>>0,e[2]=e[2]+p>>>0,e[3]=e[3]+g>>>0,e[4]=e[4]+y>>>0,e[5]=e[5]+w>>>0,e[6]=e[6]+v>>>0,e[7]=e[7]+b>>>0}const d=new Uint8Array(32),l=new DataView(d.buffer);for(let u=0;u<8;u++)l.setUint32(u*4,e[u],!1);return d}function Tm(t){let e="";for(const n of t)e+=n.toString(16).padStart(2,"0");return e}function rc(t){const e=new TextEncoder().encode(t);return Tm(jm(e))}const{parse:Om}=Ol;function sc(t,e=""){const n={};if(t===null||typeof t!="object"||Array.isArray(t))return e&&(n[e]=t),n;for(const[i,o]of Object.entries(t)){const r=e?`${e}.${i}`:i;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,sc(o,r)):n[r]=o}return n}function bt(t){if(j.existsSync(t))try{const e=j.readFileSync(t,"utf8"),n=Om(e);return n===null||typeof n!="object"||Array.isArray(n)?void 0:sc(n)}catch{return}}function Im(t){return{system:bt(_.join(t.system,Ze)),global:bt(_.join(t.global,Ze)),project:t.project?bt(_.join(t.project,Ze)):void 0,local:t.project?bt(_.join(t.project,oc)):void 0}}function Mr(t){const e={source:t.source,scope:t.scope};return t.source==="env"&&t.env!==void 0&&(e.env=t.env),e}function Uo(t,e){if(t===void 0)return t;switch(e){case"integer":{if(typeof t=="number")return t;const n=parseInt(String(t),10);return Number.isNaN(n)?t:n}case"number":{if(typeof t=="number")return t;const n=parseFloat(String(t));return Number.isNaN(n)?t:n}case"boolean":{if(typeof t=="boolean")return t;const n=String(t).toLowerCase();return n==="true"?!0:n==="false"?!1:t}case"array":return Array.isArray(t)?t:typeof t=="string"?t.length===0?[]:t.split(",").map(n=>n.trim()):t;case"string":return typeof t=="string"?t:String(t);default:return t}}function ac(t){const e={};for(const n of Object.keys(t)){const i=n.split(".");let o=e;i.forEach((r,s)=>{if(s===i.length-1){o[r]=t[n];return}const a=o[r];(typeof a!="object"||a===null||Array.isArray(a))&&(o[r]={}),o=o[r]})}return e}const $m=[["system","system"],["global","global"],["project","project"],["local","local"]];function Cm(t,e,n,i){const o={},r={},s={},a={};for(const c of Object.keys(t)){const d=t[c],l=d.env&&d.env!==""?d.env:Em(i.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??i.activeScope;let m=d.default,p="default";for(const[b,h]of $m){const S=e[b];S&&Object.prototype.hasOwnProperty.call(S,c)&&(m=Uo(S[c],d.type),p=h)}const g=n[l];let y,w,v;g!==void 0?(y=Uo(g,d.type),w="env",v=l):(y=m,w=p),o[c]=u?Am(l):y,r[c]=y,s[c]=Mr(u?{source:"env",scope:f,env:l}:{source:w,scope:f,env:v}),a[c]={...d,env:l,live:u,fallbackValue:m}}return{raw:o,nested:ac(o),typedRaw:r,provenance:s,fields:a}}function Pm(t,e){return t.replace(/\$\{HOME\}/g,te.homedir()).replace(/\$HOME\b/g,te.homedir()).replace(/\$\{PROJECT_ROOT\}/g,e.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,e.namespace)}function Lm(t,e){const n={};for(const[i,o]of Object.entries(t??{})){const r=o.scope??e.activeScope,s=o.share??ym[o.kind],a=o.path?Pm(o.path,e):_.join(nc(e.roots,r),i),c=s==="per-instance"?_.join(a,e.instanceId):a;n[i]={name:i,kind:o.kind,path:c,scope:r,share:s}}return n}function Um(t,e){const n={};for(const[i,o]of Object.entries(t??{})){const r=e[o.in];if(!r)throw new Error(`files.${i}.in references unknown dirs key "${o.in}"`);n[i]={name:i,in:o.in,path:_.join(r.path,o.name),share:o.share??"shared"}}return n}class cc extends Error{constructor(e){super(e.length>0?`Config validation failed: ${e.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=e,this.name="ValidationError"}}function Dm(t,e){if(!e)return;const n=e,i=n.properties;if(i!==void 0&&Object.keys(i).length===0)return;const r=new qs({allErrors:!0,strict:!1}).compile(n);if(!r(t))throw new cc(Mm(r.errors??[]))}function Mm(t){return t.map(e=>({field:xm(e),message:e.message??"is invalid",keyword:e.keyword}))}function xm(t){var i;const e=(t.instancePath??"").replace(/^\//,"").replace(/\//g,".");return e||(((i=t.params)==null?void 0:i.missingProperty)??"(root)")}function Fm(t,e){return _.join(nc(t,e),hm)}const Bm=384,Km=448;function qm(t,e,n={}){const i=n.mode??Bm,o=n.dirMode??Km,r=_.dirname(t);j.mkdirSync(r,{recursive:!0,mode:o}),j.chmodSync(r,o);const s=`${t}.tmp`,a=typeof e=="string"?e:JSON.stringify(e,null,2);try{j.writeFileSync(s,a,{encoding:"utf8",mode:i}),j.chmodSync(s,i),j.renameSync(s,t),j.chmodSync(t,i)}catch(c){try{j.existsSync(s)&&j.unlinkSync(s)}catch{}throw c}}const Hm="0.1.0";function xr(t,e){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(t)}`)}function Vm(){return`${process.pid}-${ke.randomBytes(3).toString("hex")}`}function ki(t,e,n={}){if(!t)throw new Error("Environment requires a non-empty 'project' name");xr(t,"project");const i=e.orgNamespace??mm,o=e.envPrefixOverride??bm(t),r=e.namespaces&&e.namespaces.length>0?e.namespaces:[gm],s=n.namespace??r[0];if(!r.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${t}" (declared: ${r.join(", ")})`);xr(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=lm({scope:n.scope,cwd:n.cwd},a),l=fm({project:t,namespace:s,orgNamespace:i,projectRoot:d,adhdRoot:n.adhdRoot});return{project:t,namespace:s,orgNamespace:i,envPrefix:o,scope:c,projectRoot:d,roots:l}}function Gm(t,e,n={}){const{namespace:i,orgNamespace:o,envPrefix:r,scope:s,projectRoot:a,roots:c}=ki(t,e,n),d=n.processEnv??process.env,l=Im(c),u=n.instanceId??Vm(),{raw:f,nested:m,typedRaw:p,provenance:g,fields:y}=Cm(e.config,l,d,{prefix:r,activeScope:s}),w={};for(const E of Object.keys(y)){const N=y[E];N.live&&(w[E]={env:N.env,type:N.type,fallback:N.secret===!0?void 0:N.fallbackValue})}const v=Sm(e.config);Dm(ac(p),v);const b=Lm(e.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:i}),h=Um(e.files,b);return{version:pm,libraryVersion:Hm,generatedAt:new Date().toISOString(),project:t,namespace:i,orgNamespace:o,envPrefix:r,scope:s,instanceId:u,config:m,raw:f,liveFields:w,fieldSchema:v,configHash:wm(Object.fromEntries(Object.entries(p).map(([E,N])=>[E,String(N)]))),structureHash:vm(Object.values(b).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(b),files:Object.values(h),provenance:g}}class jt extends Error{constructor(e){super(e),this.name="EnvironmentError"}}class Wm extends jt{constructor(e){super(`adhd-environment snapshot not found: ${e}`),this.snapshotPath=e,this.name="SnapshotNotFoundError"}}class Jm extends jt{constructor(e,n){super(`lock "${e}" is already held (${n})`),this.lockName=e,this.lockPath=n,this.name="LockHeldError"}}function zm(t,e){let n=t;for(const i of e.split("."))if(n!==null&&typeof n=="object"&&i in n)n=n[i];else return;return n}function Do(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Do(n));const e={};for(const[n,i]of Object.entries(t))e[n]=Do(i);return e}function Ym(t,e){const n=Do(t);for(const i of Object.keys(e)){const o=e[i],r=i.split(".");let s=n;for(let c=0;c<r.length-1;c++){const d=r[c],l=s[d];(typeof l!="object"||l===null||Array.isArray(l))&&(s[d]={}),s=s[d]}const a=r[r.length-1];Object.defineProperty(s,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?Uo(c,o.type):o.fallback}})}return n}function Xm(t){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new jt(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(t)}`)}class Cn{constructor(e,n,i={}){let o,r;try{o=Gm(e,n,i);const s=ki(e,n,i);r=Fm(s.roots,o.scope)}catch(s){throw s instanceof cc||s instanceof jt?s:new jt(s instanceof Error?s.message:String(s))}return Fr(this,o,r)}static fromSnapshot(e){if(!j.existsSync(e))throw new Wm(e);const n=JSON.parse(j.readFileSync(e,"utf8")),i=Object.create(Cn.prototype);return Fr(i,n,e)}get(e){const n=e.indexOf(".");if(n===-1)return;const i=e.slice(0,n),o=e.slice(n+1);switch(i){case"config":return zm(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(e){return e.startsWith(this.prefix)}resolveEnvName(e){if(this.isEnvNameAllowed(e))return process.env[e]}lock(e="singleton"){Xm(e);const n=this.paths.run??this._runDirFallback();j.mkdirSync(n,{recursive:!0});const i=_.join(n,`${e}.lock`);let o;try{o=j.openSync(i,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new Jm(e,i):s}j.writeSync(o,`${process.pid}
|
|
41
41
|
${this.instanceId}
|
|
42
|
-
`),
|
|
43
|
-
`)}]}}function
|
|
42
|
+
`),j.closeSync(o);let r=!1;return()=>{if(!r){r=!0;try{j.unlinkSync(i)}catch{}}}}_runDirFallback(){return _.join(_.dirname(this.snapshotPath),"run")}ensureDirs(){for(const e of Object.values(this.paths))j.mkdirSync(e,{recursive:!0})}write(){return qm(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Fr(t,e,n){const i={};for(const s of e.dirs)i[s.name]=s.path;const o={};for(const s of e.files)o[s.name]=s.path;const r=Ym(e.config,e.liveFields??{});return Object.defineProperties(t,{project:{value:e.project,enumerable:!0},namespace:{value:e.namespace,enumerable:!0},orgNamespace:{value:e.orgNamespace,enumerable:!0},scope:{value:e.scope,enumerable:!0},prefix:{value:e.envPrefix,enumerable:!0},instanceId:{value:e.instanceId,enumerable:!0},hash:{value:e.configHash,enumerable:!0},version:{value:{configHash:e.configHash,structureHash:e.structureHash,generatedAt:e.generatedAt,libraryVersion:e.libraryVersion},enumerable:!0},provenance:{value:e.provenance,enumerable:!0},dirs:{value:e.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:r,enumerable:!0},paths:{value:i,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:e,enumerable:!1}}),new Proxy(t,{get(s,a,c){return typeof a=="string"&&!(a in s)?s.get(a):Reflect.get(s,a,c)}})}const Ie={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production","test","sandbox"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"Backlog graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"The store adapter's `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"embedding.enabled":{type:"boolean",env:"ADHD_BACKLOG_EMBEDDING_ENABLED",default:!1,description:'RAG-SPEC.md §1.6 — opt IN to the semantic/RAG stack. Default FALSE: semantic inputs (filter.semantic, filter.anchor, view:"similar", sort:"relevance", fields:["_vector"]) answer RagNotConfiguredError (§5a) until this is set. Requires the optionalDependencies @adhd/sox-embedding-provider + @adhd/sox-vector-store to be installed, and a store whose adapter reports capabilities.nativeVectors (turso). Enabling it with any of those missing logs a typed reason and leaves RAG unconfigured — it never crashes startup.'},"embedding.provider":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_PROVIDER",default:"fastembed",description:"Embedding provider type, forwarded verbatim to @adhd/sox-embedding-provider's createEmbeddingProvider ('fastembed' | 'remote')."},"embedding.model":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_MODEL",default:"bge-base-en-v1.5",description:"Embedding model id (768-dim bge-base-en-v1.5 by default). RAG-SPEC.md §2.5: the dimensional contract is STRUCTURAL — changing this after items are embedded orphans existing vectors under the old model id rather than silently truncating; re-embed via admin(embedding_backfill)."},"service.transport":{type:"string",env:"ADHD_BACKLOG_SERVICE_TRANSPORT",default:"mcp",enum:["mcp","http","both"],description:"Transport(s) `serve` mounts: mcp | http | both."},"service.port":{type:"integer",env:"ADHD_BACKLOG_SERVICE_PORT",default:3300,description:"HTTP listen port (ignored for mcp-only)."},"service.host":{type:"string",env:"ADHD_BACKLOG_SERVICE_HOST",default:"127.0.0.1",description:"HTTP listen host (ignored for mcp-only)."},"service.serverCommand":{type:"string",env:"ADHD_BACKLOG_SERVICE_SERVER_COMMAND",default:"",description:"Absolute path (or PATH-resolvable bin) of the server artifact to verify at load time. Unset ⇒ no drift check (backlog serving itself)."},"service.connectGraceMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_CONNECT_GRACE_MS",default:2e4,description:"Pre-connect deadline extension applied to the FIRST attempt — the cold-start grace window (the fix for host-deadline < cold-start)."},"service.connectBudgetMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_CONNECT_BUDGET_MS",default:6e4,description:"Total wall-clock budget across all connect/handshake attempts (bounded)."},"service.readinessTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_SERVICE_READINESS_TIMEOUT_MS",default:3e4,description:"Timeout for ONE serving-path readiness probe."}}};function Pn(t){if(t)return t;const e=process.env.ADHD_BACKLOG_SCOPE;if(e)return e;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function et(t={}){const e={namespace:t.namespace??"production",scope:Pn(t.scope)};return t.adhdRoot!==void 0&&(e.adhdRoot=t.adhdRoot),t.cwd!==void 0&&(e.cwd=t.cwd),t.instanceId!==void 0&&(e.instanceId=t.instanceId),new Cn("backlog",Ie,e)}function tt(t){return t.config.db.path??t.files.db}function Qm(t,e){return`${t}:${e}`}function Zm(t={}){const e=process.env.APIGEN_IR_CACHE_FILE;if(e)return e;const n={namespace:"production",scope:"global"};t.adhdRoot!==void 0&&(n.adhdRoot=t.adhdRoot),t.instanceId!==void 0&&(n.instanceId=t.instanceId);const i=new Cn("backlog",Ie,n);return _.join(i.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function Br(t){return{raw:t,words:Nt(t)}}function dc(t,e,n,i){for(const o of i??[]){const r=o.path[o.path.length-1];if(o.namespace.raw===t&&(r==null?void 0:r.raw)===e)return o}return{id:`${Nt(t).join("-")}/${Nt(e).join("-")}`,host:"ts",namespace:Br(t),path:[Br(e)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function eg(t){var o;const e=((o=t.input)==null?void 0:o.properties)??{},n=t["x-apigen-envelope"],i={};for(const r of Object.keys(e)){if(r==="data")continue;const s=(n==null?void 0:n[r])??"adhd";i[r]=ga(s,r)}return i}function tg(t){const e=Of(t.options.port),n=t.options.routePrefix??"",i=t.options.projection??{},o=jf(t.packages.map(s=>s.id)),r=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const[s,a]of t.packages.entries()){const c=o[s];r.push(`import * as ${c}_ns from ${ye(a.importPath)}`),r.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}r.push(""),r.push(`const schemas: Record<string, unknown> = ${wa(JSON.stringify(Object.fromEntries(t.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,{schema:c,pkgId:s.id}]))),null,2))}`),r.push(""),r.push("const app = Fastify()"),r.push("");for(const[s,a]of t.packages.entries()){const c=o[s];for(const[d,l]of Object.entries(a.schemas)){const u=dc(a.id,d,l,t.operations),f=Oe({op:u,schema:l,transport:"http",projection:i}),m=n+f.http.route,p=f.http.verb,g=eg(l),y=Object.entries(g),w=ye(`${a.id}:${d}`),v=ye(d);if(p==="GET"){if(r.push(`app.get(${ye(m)}, async (req) => {`),r.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas[${w}]['schema'] as any)`),y.length>0){const b=y.map(([h,S])=>`${ye(h)}: (req.headers as Record<string, unknown>)[${ye(S)}]`).join(", ");r.push(` const envelope: Record<string, unknown> = { ${b} }`)}else r.push(" const envelope: Record<string, unknown> = {}");r.push(` return dispatch(${c}_fns as any, undefined, schemas[${w}]['schema'] as any, ${v}, envelope, query as any)`),r.push("})")}else{if(r.push(`app.post(${ye(m)}, async (req) => {`),r.push(" const { data = {} } = req.body as Record<string, unknown>"),y.length>0){const b=y.map(([h,S])=>`${ye(h)}: (req.headers as Record<string, unknown>)[${ye(S)}]`).join(", ");r.push(` const envelope: Record<string, unknown> = { ${b} }`)}else r.push(" const envelope: Record<string, unknown> = {}");r.push(` return dispatch(${c}_fns as any, undefined, schemas[${w}]['schema'] as any, ${v}, envelope, data as any)`),r.push("})")}}}return r.push(""),r.push("app.setErrorHandler((err, _req, reply) => {"),r.push(" reply.status(500).send({"),r.push(" code: 'internal',"),r.push(" message: err instanceof Error ? err.message : 'Internal error',"),r.push(" })"),r.push("})"),r.push(""),r.push("async function main(): Promise<void> {"),r.push(" try {"),r.push(` await app.listen({ port: ${e} })`),r.push(" } catch (err) {"),r.push(" app.log.error(err)"),r.push(" process.exit(1)"),r.push(" }"),r.push("}"),r.push(""),r.push("main()"),{files:[{path:"routes.ts",content:r.join(`
|
|
43
|
+
`)}]}}function ng(t){return`data: ${t}
|
|
44
44
|
|
|
45
|
-
`}function
|
|
46
|
-
data: ${
|
|
45
|
+
`}function og(t){return`event: error
|
|
46
|
+
data: ${t}
|
|
47
47
|
|
|
48
|
-
`}async function
|
|
48
|
+
`}async function ig(t,e,n){const i=new AbortController;e.raw.once("close",()=>i.abort());const o=n.raw;let r=!1;try{for await(const s of t){if(i.signal.aborted)break;r||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),r=!0),o.write(ng(JSON.stringify(s)))}r||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(s){const a=fe(s)?s:new z("internal",s instanceof Error?s.message:String(s));if(r)o.write(og(JSON.stringify(a.toJSON()))),o.end();else{const c=sg(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const rg={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function sg(t){return rg[t]??500}function lc(t){return fe(t)?rf[t.code]??500:500}function uc(t){return fe(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:"Internal error"}}function ag(t,e){if(t)for(const n of e){const i={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(i.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),t.info(n,o)}}class cg{constructor(e,n,i){this.app=e,this.routePrefix=n,this.signal=i,this.schemasByOpId=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}routeFor(e){return e.isMount?`${this.routePrefix}/${e.op.id}`:this.routePrefix+e.http.route}registerRoute(e,n){const i=this.routeFor(e),o=async(r,s)=>{const a={req:r,reply:s};try{const c=await this.readCall(a,e),d=await n(c);await this.writeResult(a,d,e)}catch(c){await this.writeError(a,c,e)}};e.http.verb==="GET"?this.app.get(i,o):this.app.post(i,o)}readCall(e,n){const{req:i}=e,o=i.headers,r={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(r[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?i.query??{}:i.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=i.query??{};s=a?nf(c,a):c}else{const{data:c={}}=i.body??{};s=c}}return{envelope:r,domainArgs:s,signal:this.signal}}async writeResult(e,n,i){const{req:o,reply:r}=e;if($n(n)){await ig(n,o,r);return}r.type("application/json"),r.send(JSON.stringify(n===void 0?null:n))}writeError(e,n,i){const{reply:o}=e;o.status(lc(n)).send(uc(n))}}function dg(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("http")||r.push(u)}return r}async function lg(t){var w,v;const e=t.options.port??3e3,n=t.options.host??"127.0.0.1",i=t.options.routePrefix??"",o=t.options.projection??{},r=di(t.options),s=li(t.options),a=t.logger??ai(),c=_l({logger:a});c.setErrorHandler((b,h,S)=>{S.status(lc(b)).send(uc(b))});const d=new cg(c,i,t.signal),l=[],u={},f={};for(const b of t.packages){if(!b.fns)throw new Error(`Package "${b.id}" is missing fns`);const h=b.fns,S=Object.entries(b.schemas).map(([A,O])=>({fnName:A,fnSchema:O,op:dc(b.id,A,O,t.operations)})),E={},N={};for(const{fnName:A,fnSchema:O,op:I}of S)E[I.id]=O,N[I.id]=h[A],u[I.id]=O,f[I.id]=h[A];const k=Ee(E,r),R={fns:N,createClient:b.createClient,schemas:E};for(const{fnSchema:A,op:O}of S){const I=Oe({op:O,schema:A,transport:"http",projection:o});d.bindSchema(O.id,A),d.registerRoute(I,Y=>st(I,k,Y,R));const{params:L,text:$}=ua(A);l.push({method:I.http.verb,route:i+I.http.route,text:$,params:L})}}const m=((w=t.packages[0])==null?void 0:w.id)??"ts",p=Ee(u,r),g={invoke:(b,h,S)=>p(b,{operation:{id:b},ctx:new Pt,domainArgs:h.domainArgs,envelope:h.envelope,signal:h.signal},S),invokeOptions:{fns:f,schemas:u,createClient:(v=t.packages[0])==null?void 0:v.createClient}},y=dg(r,s,m,t.operations??[],g);if(y.length>0){const b=Ee({},r),h={fns:{},schemas:{}};for(const S of y){const E=Oe({op:S,transport:"http",projection:o});d.registerRoute(E,N=>st(E,b,N,h)),l.push({method:E.http.verb,route:`${i}/${S.id}`,text:"",params:[]})}}return await c.listen({port:e,host:n}),a.info({host:n,port:e},`listening on http://${n}:${e}`),ag(a,l),new Promise(b=>{t.signal&&t.signal.addEventListener("abort",async()=>{await c.close(),b()})})}const ug={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(t){return tg(t)},run(t){return lg(t)}};function fg(t,e={}){const n=e.title??"API",i=e.version??"0.0.0",o={};for(const r of t){const s=qe(r),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:r.id,summary:r.id,responses:{200:pg(r.output)}};if(a==="GET")l.parameters=mg(r.input);else{const u=r.input;typeof u=="object"&&u!==null&&Object.keys(u).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:u}}})}o[c]===void 0&&(o[c]={}),o[c][d]=l}return{openapi:"3.1.0",info:{title:n,version:i},paths:o}}function pg(t){return typeof t=="object"&&t!==null&&Object.keys(t).length>0?{description:"Success",content:{"application/json":{schema:t}}}:{description:"Success"}}function mg(t){if(typeof t!="object"||t===null||typeof t.properties!="object"||t.properties===null)return[];const e=Array.isArray(t.required)?t.required:[],n=t.properties;return Object.entries(n).map(([i,o])=>({name:i,in:"query",required:e.includes(i),schema:o}))}function gg(t,e={}){return[{...Qs("_meta/openapi",t,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>fg(t.operations,{title:e.title,version:e.version})}]}const hg={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(t,e){return gg(t,e)}}}};function yg(){return`// Auto-generated by @adhd/apigen-cli — do not edit
|
|
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,10 +119,10 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
119
119
|
|
|
120
120
|
const transport = new StdioServerTransport()
|
|
121
121
|
server.connect(transport)
|
|
122
|
-
`}function
|
|
122
|
+
`}function wg(t,e){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
|
+
${t==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
|
|
126
126
|
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
127
127
|
import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
|
|
128
128
|
import { toolMetas, groupFns, groupCreateClient } from './index.js'
|
|
@@ -192,34 +192,71 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
|
192
192
|
}
|
|
193
193
|
})
|
|
194
194
|
|
|
195
|
-
const mcpTransport = new ${
|
|
195
|
+
const mcpTransport = new ${t==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
|
|
196
196
|
const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
|
|
197
|
-
httpServer.listen(${
|
|
198
|
-
`}function
|
|
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
|
|
201
|
-
|
|
202
|
-
|
|
197
|
+
httpServer.listen(${e}, () => console.error('MCP ${t} server on port ${e}'))
|
|
198
|
+
`}function Mo(t){return{raw:t,words:Nt(t)}}function vg(t){return Mo(Rf(ao.basename(t)))}function fc(t,e,n){if(n){const o=n.find(r=>{var s;return r.kind==="action"&&r.namespace.raw===t.id&&((s=r.path[r.path.length-1])==null?void 0:s.raw)===e});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${t.id}" fn "${e}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const i=Mo(e);return{id:`${t.id}/${e}`,host:"ts",namespace:Mo(t.id),path:t.dropFileSegment?[i]:[vg(t.importPath),i],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function bg(t,e,n){const i=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of t)i.push(`import * as ${o.id}_ns from '${o.importPath}'`),i.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);i.push(""),i.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of t)for(const[r,s]of Object.entries(o.schemas)){const a=fc({id:o.id,importPath:o.importPath},r,n),d=Oe({op:a,schema:s,transport:"mcp"}).mcp.name,l=So(d,s,e[d]??e[r]);i.push(` ${JSON.stringify(d)}: { group: '${o.id}', fnName: ${JSON.stringify(r)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}i.push("}"),i.push(""),i.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of t)i.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);i.push("}"),i.push(""),i.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of t)i.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return i.push("}"),i.join(`
|
|
199
|
+
`)}function Eg(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,i=t.options.toolDescriptions??{},o=t.operations,r=bg(t.packages,i,o),s=e==="stdio"?yg():wg(e,n);return{files:[{path:"index.ts",content:r},{path:"server.ts",content:s}]}}async function Sg(t){const e=await fa(t);if(e.ok){const o=e.chunks.map(r=>({type:"text",text:JSON.stringify(r)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=e;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const i={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(i)}],isError:!0}}const kg=Object.freeze({type:"object",properties:{}});class _g{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}bindToolMeta(e,n){this.cachedList=void 0,this.toolMeta.set(e,n)}registerRoute(e,n){this.cachedList=void 0,this.plans.set(e.mcp.name,e),this.dispatchers.set(e.mcp.name,n)}getPlan(e){return this.plans.get(e)}getDispatch(e){return this.dispatchers.get(e)}listTools(){if(this.cachedList)return this.cachedList;const e=[...this.plans.keys()].map(n=>{const i=this.toolMeta.get(n);return Object.freeze({name:n,description:(i==null?void 0:i.description)??n,inputSchema:(i==null?void 0:i.inputSchema)??kg,...i!=null&&i.outputSchema?{outputSchema:i.outputSchema}:{}})});return this.cachedList=Object.freeze(e),this.cachedList}readCall(e,n){const i={};for(const r of n.envelope){const s=e.meta[r.mcpMetaKey];s!==void 0&&(i[r.field]=s)}const o=n.isMount?e.args:e.args.data??{};return{envelope:i,domainArgs:o}}async writeResult(e,n,i){if($n(n)){e.output=await Sg(n);return}const o=this.schemasByOpId.get(i.op.id),{wrapped:r}=ma(o==null?void 0:o.output),s=bf(r,n);e.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(e,n,i){throw fe(n)&&n.code,n}}function Ag(t){if(t&&typeof t=="object"&&t.type==="object")return t;const e=t==null?void 0:t.oneOf;if(Array.isArray(e)&&e.length>0){const n={};let i=null;for(const o of e){if(!o||typeof o!="object")continue;const r=o,s=r.properties;if(s&&typeof s=="object")for(const[c,d]of Object.entries(s))c in n||(n[c]=d);const a=Array.isArray(r.required)?r.required:[];i=i===null?[...a]:i.filter(c=>a.includes(c))}return{...t,type:"object",properties:n,...i&&i.length>0?{required:i}:{}}}return{type:"object",properties:{}}}function Ng(t,e,n,i,o){var a;const r=[],s={host:n,operations:i};for(const c of t){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,e[c.id],o);for(const u of l)u.transports&&!u.transports.includes("mcp")||r.push(u)}return r}function Rg(t,e){var f,m;const n=t.options.projection??{},i=t.options.toolDescriptions??{},o=di(t.options),r=li(t.options),s={},a={};for(const p of t.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const g=p.fns,y=Object.entries(p.schemas).map(([S,E])=>({fnName:S,fnSchema:E,op:fc({id:p.id,importPath:p.importPath},S,t.operations)})),w={},v={};for(const{fnName:S,fnSchema:E,op:N}of y)w[N.id]=E,v[N.id]=g[S],s[N.id]=E,a[N.id]=g[S];const b=Ee(w,o),h={fns:v,createClient:p.createClient,schemas:w};for(const{fnName:S,fnSchema:E,op:N}of y){const k=Oe({op:N,schema:E,transport:"mcp",projection:n});e.bindSchema(N.id,E);const{outputSchema:R}=ma(E.output),A=So(k.mcp.name,E,i[k.mcp.name]??i[S]);e.bindToolMeta(k.mcp.name,{description:A,inputSchema:E.input,outputSchema:R}),e.registerRoute(k,O=>st(k,b,O,h))}}const c=((f=t.packages[0])==null?void 0:f.id)??"ts",d=Ee(s,o),l={invoke:(p,g,y)=>d(p,{operation:{id:p},ctx:new Pt,domainArgs:g.domainArgs,envelope:g.envelope,signal:g.signal},y),invokeOptions:{fns:a,schemas:s,createClient:(m=t.packages[0])==null?void 0:m.createClient}},u=Ng(o,r,c,t.operations??[],l);if(u.length>0){const p=Ee({},o),g={fns:{},schemas:{}};for(const y of u){const w=Oe({op:y,transport:"mcp",projection:n}),v=Ag(y.input),b=So(w.mcp.name,{input:v},i[w.mcp.name]);e.bindToolMeta(w.mcp.name,{description:b,inputSchema:v}),e.registerRoute(w,h=>st(w,p,h,g))}}}function jg(t){const e=t.packages[0];return{name:(e==null?void 0:e.id)??"apigen-mcp",version:(e==null?void 0:e.version)??"1.0.0"}}function eo(t,e,n){const i=new Al.Server(n,{capabilities:{tools:{}}});return i.setRequestHandler(Yi.ListToolsRequestSchema,async()=>({tools:t.listTools()})),i.setRequestHandler(Yi.CallToolRequestSchema,async o=>{const{name:r,arguments:s={}}=o.params,a=t.getPlan(r),c=t.getDispatch(r);if(!a||!c)throw new Error(`Unknown tool: ${r}`);const d=s,l=d._meta??{},u={args:d,meta:l},f=Date.now();try{const m=await t.readCall(u,a),p=await c(m);return await t.writeResult(u,p,a),e.info({tool:r,ms:Date.now()-f},`→ ${r}`),u.output}catch(m){throw fe(m)&&m.code!=="internal"?e.error({tool:r,ms:Date.now()-f,code:m.code,message:m.message},`✗ ${r}`):e.error({tool:r,ms:Date.now()-f,err:m},`✗ ${r}`),t.writeError(u,m,a),m}}),i}function Kr(t,e){return async(n,i)=>{try{await e(n,i)}catch(o){t.error({err:o},"mcp http transport handler error"),i.headersSent||i.writeHead(500),i.writableEnded||i.end("Internal Server Error")}}}function qr(t,e){const n=t.signal;if(!n)throw new z("invalid_argument",`apigen mcp transport "${e}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function Hr(t,e,n,i,o,r){return new Promise((s,a)=>{const c=d=>{a(new z("internal",`failed to bind mcp ${i} server on ${n}:${e}: ${d.message}`,{cause:d}))};t.once("error",c),t.listen(e,n,()=>{t.removeListener("error",c),t.on("error",l=>o.error({err:l},"mcp http server error")),o.info({host:n,port:e},`listening on http://${n}:${e}`);const d=()=>{o.info("mcp server shutting down"),t.close(()=>s()),t.closeAllConnections()};if(r.aborted){d();return}r.addEventListener("abort",d,{once:!0})})})}function Tg(t,e,n,i=process.stdin){return new Promise(o=>{let r=!1;function s(l){r||(r=!0,i.off("end",a),i.off("close",a),n==null||n.removeEventListener("abort",c),e.info(l),o())}function a(){s("stdio transport closed (stdin EOF)")}function c(){s("mcp server shutting down")}const d=t.onclose;if(t.onclose=()=>{d==null||d(),s("stdio transport closed")},i.once("end",a),i.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function Og(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,i=t.options.host??"127.0.0.1",o=t.logger??ai();o.info(`mcp server starting (${e})`);const r=new _g;Rg(t,r);const a=r.listTools().map(u=>u.name);o.info({tools:a},`${a.length} tools available`);for(const u of a){const f=r.getPlan(u),m=(f==null?void 0:f.params)??[],p=m.map(g=>`${g.name}${g.required?"":"?"}: ${g.type}`).join(", ");o.info({tool:u,args:{data:m}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}const c=jg(t);if(o.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),e==="stdio"){const u=eo(r,o,c),f=new Nl.StdioServerTransport;return await u.connect(f),o.info("stdio transport ready"),Tg(f,o,t.signal)}if(e==="sse"){const u=qr(t,e),f=new Map,m=zi.createServer(Kr(o,async(p,g)=>{const y=p.url??"";if(p.method==="GET"&&y==="/sse"){const w=eo(r,o,c),v=new Rl.SSEServerTransport("/messages",g);f.set(v.sessionId,v),v.onclose=()=>f.delete(v.sessionId),await w.connect(v)}else if(p.method==="POST"&&y.startsWith("/messages")){const w=new URLSearchParams(y.split("?")[1]??"").get("sessionId"),v=w?f.get(w):void 0;if(!v){g.writeHead(404),g.end("Session not found");return}await v.handlePostMessage(p,g)}else g.writeHead(404),g.end("Not found")}));return Hr(m,n,i,e,o,u)}const d=qr(t,e),l=zi.createServer(Kr(o,async(u,f)=>{const m=eo(r,o,c),p=new jl.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await m.connect(p),await p.handleRequest(u,f)}));return Hr(l,n,i,e,o,d)}const Ig={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(t){return Eg(t)},run(t){return Og(t)}},_i=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Ai=["body","citations","notes","auditTrail","blockers","related","_score","_vector","blocksOut","dependents","partOf","obligations","verdict","spec","similar"],$g=new Set([..._i,...Ai]);function Cg(t){return $g.has(t)}const Ft=["uid","kind","title","status","priority"],le=1e3,Ln=50;function Pg(t,e,n){return{target:t.file,target_type:"path",sha:e,line:t.lines??null,at:n,symbol:t.symbol??null,blastRadius:t.blastRadius??null,revision:t.revision??null}}function Lg(t){const e=t.metadata??{};return{uid:t.uid,file:typeof e.target=="string"?e.target:t.name??"",lines:typeof e.line=="string"?e.line:void 0,context:t.content||void 0,symbol:typeof e.symbol=="string"?e.symbol:void 0,blastRadius:e.blastRadius??void 0,revision:typeof e.revision=="string"?e.revision:void 0,sha:typeof e.sha=="string"?e.sha:"unverified",at:typeof e.at=="string"?e.at:t.tCreated,targetType:typeof e.target_type=="string"?e.target_type:void 0}}function Vr(t){return`${t.file}\0${t.lines??""}\0${t.revision??""}`}function Ug(t){const e=t??{},n=typeof e.target=="string"?e.target:"",i=typeof e.line=="string"?e.line:"",o=typeof e.revision=="string"?e.revision:"";return`${n}\0${i}\0${o}`}function $e(t){const e=t==null?void 0:t.revision;return typeof e=="number"&&Number.isFinite(e)?e:0}function re(t){return $e(t)+1}const Gr="redirectTo";async function pc(t,e){var r,s;const n=(r=e.metadata)==null?void 0:r[Gr];if(typeof n!="string"||n.length===0)return null;const i=await t.getNodeByUid(n);if(!i||i.tInvalid!==void 0)throw new T("redirectTo",`node "${e.uid}" redirects to "${n}", which is not a live node`);const o=(s=i.metadata)==null?void 0:s[Gr];if(typeof o=="string"&&o.length>0)throw new T("redirectTo",`redirect chain longer than one hop: "${e.uid}" -> "${n}" -> "${o}"`);return i}async function mc(t,e,n){const i=await t.getNodeByUid(e);if(i)return i.tInvalid!==void 0||n!==void 0&&i.kind!==n?null:i;if(Rt(e)!=="prefix")return null;const o=await t.transaction(c=>qa(c,e)),r=n!==void 0?o.filter(c=>c.kind===n):o,s=Ha(e,r);if(!s)return null;const a=await t.getNodeByUid(s.uid);return a&&a.tInvalid===void 0?a:null}async function Un(t,e,n){if(Rt(e)==="too-short")throw Va(e);const i=await mc(t,e,n==null?void 0:n.expectedKind);if(!i)throw ze(n==null?void 0:n.expectedKind,e,Rt(e)==="prefix");return i}async function Dg(t,e,n){return Rt(e)==="too-short"?null:mc(t,e,n==null?void 0:n.expectedKind)}async function Dn(t,e){const n=await Un(t,e,{expectedKind:"issue"});if(n.isSuperseded)throw new Ut(e,await hc(t,n));return n}async function gc(t,e){const n=await Un(t,e),o=await pc(t,n)??n;if(!o.isSuperseded)return o;const r=await hc(t,o);if(r===void 0)return o;const s=await t.getNodeByUid(r);return s&&s.tInvalid===void 0?s:o}async function hc(t,e){const n=new Set([e.id]);let i,o=e;for(;;){const s=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return i==null?void 0:i.uid;n.add(s.src);const a=(await t.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return i==null?void 0:i.uid;if(i=a,!a.isSuperseded)return a.uid;o=a}}async function x(t,e,n){if(pe(n)||Dt(n)){const r=await Dg(t,n,{expectedKind:e});if(r)return{id:r.id,uid:r.uid,name:r.name??n,record:r};if(pe(n))return null}const o=(await t.queryNodes({kind:e,name:n,liveOnly:!0,limit:1}))[0];if(o)return{id:o.id,uid:o.uid,name:o.name??n,record:o};if(e==="project"||e==="component"){const r=await t.queryNodes({kind:e,name:n,liveOnly:!1,metadata:{redirectTo:{exists:!0}},limit:5});for(const s of r){const a=await pc(t,s);if(a)return{id:a.id,uid:a.uid,name:a.name??n,record:a}}}return null}async function Ve(t,e,n){var r;if(pe(n)||Dt(n)){const s=await x(t,"component",n);return!s||((r=s.record.metadata)==null?void 0:r.projectUid)!==e?null:s}const o=(await t.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:e}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function me(t,e){return t.getEdges({src:e})}function yc(t,e){return t.getEdges({dst:e})}async function Ge(t,e){var c,d;const i=(c=(await t.getEdges({dst:e,rel:"owns_component"}))[0])==null?void 0:c.src;if(i===void 0)return{};const[o]=await t.getNodesByIds([i]);if(!o)return{};const s=(d=(await t.getEdges({dst:i,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:o};const[a]=await t.getNodesByIds([s]);return{component:o,project:a}}async function wc(t,e){const n=e.expectedKind==="component"&&e.projectUid!==void 0?await Ve(t,e.projectUid,e.ref):await x(t,e.expectedKind,e.ref);if(!n)return;if(await Mg(t,e.rel,e.expectedKind)){const o=await t.getEdges({src:n.id,rel:e.rel});return new Set(o.map(r=>r.dst))}const i=await t.getEdges({dst:n.id,rel:e.rel});return new Set(i.map(o=>o.src))}async function Mg(t,e,n){var r;const o=(r=(await t.queryNodes({kind:"edge_kind",name:e,liveOnly:!0,limit:1}))[0])==null?void 0:r.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function xg(t,e){return(await t.queryNodes({kind:e,liveOnly:!0})).map(i=>i.name).filter(i=>typeof i=="string")}function Fg(t,e){const n=t.length+1,i=e.length+1,o=Array.from({length:n},()=>new Array(i).fill(0));for(let r=0;r<n;r+=1)o[r][0]=r;for(let r=0;r<i;r+=1)o[0][r]=r;for(let r=1;r<n;r+=1)for(let s=1;s<i;s+=1)o[r][s]=t[r-1]===e[s-1]?o[r-1][s-1]:1+Math.min(o[r-1][s],o[r][s-1],o[r-1][s-1]);return o[t.length][e.length]}function Ni(t,e,n=3){const i=Math.max(2,Math.ceil(t.length/2));return e.map(o=>({candidate:o,distance:Fg(t.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=i).sort((o,r)=>o.distance-r.distance).slice(0,n).map(o=>o.candidate)}async function nt(t,e){const n=await xg(t,e.catalogKind),i=new Set,o=[];for(const r of e.refs){const s=await x(t,e.catalogKind,r);if(!s){o.push(r);continue}const a=await t.getEdges({dst:s.id,rel:e.rel});for(const c of a)i.add(c.src)}if(o.length>0){const r=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=o.map(a=>{const c=Ni(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new _e(e.field,`unknown ${e.catalogKind} value(s): ${s} — no live "${e.catalogKind}" catalog row matches (existing ${e.catalogKind} values: ${r})`)}return i}function Bg(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const i=new Set;for(const o of e)n.has(o)&&i.add(o);e=i}return e}const Wr=["evidence","blockers_terminal","relation","all_of","any_of","not"];function gt(t,e,n){for(const i of Object.keys(t))if(!e.includes(i))throw new ve(`${n} predicate has unexpected key "${i}" (allowed: ${e.join(", ")})`)}function Jr(t,e){if(typeof t!="string"||t.trim().length===0)throw new ve(`${e} must be a non-empty string`)}function wn(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new ve('a predicate must be an object with an "op" discriminator');const e=t,n=e.op;if(typeof n!="string")throw new ve('a predicate is missing its "op" discriminator');if(!Wr.includes(n))throw new ve(`unknown op "${n}" — the core is closed to ${Wr.map(i=>`"${i}"`).join(", ")}`);switch(n){case"evidence":{gt(e,["op","kind","min"],n),Jr(e.kind,"evidence.kind");const i=e.min;if(i!==void 0&&(typeof i!="number"||!Number.isInteger(i)||i<1))throw new ve("evidence.min must be an integer >= 1 when present");return}case"blockers_terminal":{gt(e,["op"],n);return}case"relation":{gt(e,["op","type","direction"],n),Jr(e.type,"relation.type");const i=e.direction;if(i!=="in"&&i!=="out")throw new ve('relation.direction must be "in" or "out"');return}case"all_of":case"any_of":{gt(e,["op","of"],n);const i=e.of;if(!Array.isArray(i))throw new ve(`${n}.of must be an array of predicates`);for(const o of i)wn(o);return}case"not":{gt(e,["op","of"],n),wn(e.of);return}}}async function ue(t,e){switch(t.op){case"evidence":return await e.countVerifiedAttestations(t.kind)>=(t.min??1);case"blockers_terminal":return e.blockersAllTerminal();case"relation":return e.relationExists(t.type,t.direction);case"all_of":{if(t.of.length===0)return!0;for(const n of t.of)if(!await ue(n,e))return!1;return!0}case"any_of":{if(t.of.length===0)return!1;for(const n of t.of)if(await ue(n,e))return!0;return!1}case"not":return!await ue(t.of,e)}}function vn(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}function Kg(t){if(t==null||typeof t!="object"||Array.isArray(t))throw new T("applies_to","is required");const e=t,n=e.to;if(typeof n!="string"||n.trim().length===0)throw new T("applies_to.to",'is required — a concrete status name or "*" for any terminal transition; omitting it is a validation error, not a silent default');const i=e.from;if(i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new T("applies_to.from","must be a non-empty string when present");return i===void 0?{to:n}:{to:n,from:i}}function qg(t){if(t===void 0)return;const e=t==null?void 0:t.actors;if(!Array.isArray(e)||e.length===0||!e.every(n=>typeof n=="string"&&n.trim().length>0))throw new T("override.actors","must be a non-empty array of non-blank identities when an override is present");return{actors:[...e]}}async function Hg(t,e){try{const n=await se(t,e,{expectedKind:"obligation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new Fa(e):n}}async function Vg(t,e){vn("uid",e.uid),vn("by",e.by),G("by",e.by);const n=Kg(e.applies_to);if(e.on_fail!=="block"&&e.on_fail!=="warn")throw new T("on_fail",'must be "block" or "warn"');const i=qg(e.override);wn(e.requirement);const o=P(),r=e.requirement;return M(t,async s=>{const a=await ae(s,e.uid),c={applies_to:n,requirement:r,on_fail:e.on_fail,...i!==void 0?{override:i}:{}},d=await X(s,{at:o,kind:"obligation",name:e.requirement.op,content:vi(r),metadata:c}),l=await q(s,"has_obligation");return await K(s,{at:o,srcRowid:a.rowid,srcUid:a.uid,srcKind:"issue",dstRowid:d.rowid,dstUid:d.uid,dstKind:"obligation",rel:"has_obligation",rule:l,typePolicy:t.typePolicy}),await U({tx:s,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"issue",actor:e.by,action:"obligated",to:d.uid,note:e.requirement.op,at:o}),{uid:a.uid,obligationUid:d.uid}})}async function Gg(t,e){return vn("obligationUid",e.obligationUid),vn("by",e.by),G("by",e.by),M(t,async n=>{const i=await Hg(n,e.obligationUid),o=P(),r=await n.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_obligation' AND t_invalid IS NULL",[i.rowid]),s={...i.metadata??{},invalidatedReason:"unobligated",invalidatedAt:o},a=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[o,JSON.stringify(s),i.rowid]);if(a.rowsAffected!==1)throw new Error(`unobligate: invalidate UPDATE affected ${a.rowsAffected} rows for uid="${e.obligationUid}", expected exactly 1.`);return r&&await ie(n,{srcRowid:r.src,dstRowid:i.rowid,rel:"has_obligation",reason:"unobligated",at:o}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"obligation",actor:e.by,action:"unobligated",at:o}),{obligationUid:i.uid,invalidated:!0}})}const to=["path","url","query","registry","commit","revision"];function Mn(t){if(typeof t!="string"||t.trim().length===0)throw new Ue(t,"locator is required");const e=t.indexOf(":");if(e<1)throw new Ue(t,`expected one of ${to.map(o=>`"${o}:"`).join(", ")}`);const n=t.slice(0,e),i=t.slice(e+1);if(!to.includes(n))throw new Ue(t,`unknown scheme "${n}" — expected one of ${to.map(o=>`"${o}:"`).join(", ")}`);if(i.trim().length===0)throw new Ue(t,`"${n}:" anchor has an empty body`);if(n==="path"){const o=/^(.*?)(?::(\d+))?$/.exec(i),r=(o==null?void 0:o[1])??i;if(r.trim().length===0)throw new Ue(t,"path anchor names no file");const s=(o==null?void 0:o[2])===void 0?void 0:Number(o[2]);return s===void 0?{scheme:"path",target:r}:{scheme:"path",target:r,line:s}}return{scheme:n,target:i}}function Ke(t,e){var n,i;try{return{status:0,stdout:Hs.execFileSync("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),stderr:""}}catch(o){const r=o;return{status:typeof r.status=="number"?r.status:-1,stdout:((n=r.stdout)==null?void 0:n.toString())??"",stderr:((i=r.stderr)==null?void 0:i.toString())??""}}}function bn(t){const e=Ke(t,["rev-parse","--is-inside-work-tree"]);return e.status===0&&e.stdout.trim()==="true"}function vc(t,e){return Ke(t,["cat-file","-e",`HEAD:${e}`]).status===0}function Wg(t,e,n){const i=Ke(t,["log","--oneline",`--since=${n}`,"--",e]);return i.status===0&&i.stdout.trim().length>0}function Jg(t,e){const n=Ke(t,["cat-file","-p",`HEAD:${e}`]);if(n.status===0)return ke.createHash("sha256").update(n.stdout).digest("hex")}const xo="default_branch_ancestor";function zg(t,e){const n=Ke(t,["symbolic-ref","-q","--short","refs/remotes/origin/HEAD"]);if(n.status===0){const r=n.stdout.trim();if(r.length>0)return r.replace(/^origin\//,"")}const i=Ke(t,["rev-parse","--abbrev-ref","HEAD"]),o=i.status===0?i.stdout.trim():"";if(o.length>0&&o!=="HEAD")return o}function bc(t,e,n){const i=xo;if(typeof e!="string"||e.trim().length===0||typeof t!="string"||t.trim().length===0)return{onDefaultBranch:!1,performed:i};if(!bn(t))return{onDefaultBranch:!1,performed:i};const o=zg(t);return o===void 0?{onDefaultBranch:!1,performed:i}:{onDefaultBranch:Ke(t,["merge-base","--is-ancestor",e.trim(),o]).status===0,performed:i}}async function Yg(t,e,n){return bc(t,e)}function Xg(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e),o=_.relative(n,i);if(!(o===""||o===".."||o.startsWith(`..${_.sep}`)||_.isAbsolute(o)))return o}function Ri(t,e){const n={checked_at:e.now,checked_by:e.by},i=Mn(t.locator);if(i.scheme==="commit"){const s=e.root;if(!s)return{state:"unknown",method:"none",...n,reason:"no project root could be resolved for the subject"};if(!bn(s))return{state:"unknown",method:"none",...n,reason:`no git work tree at "${s}"`};const a=bc(s,i.target);return a.onDefaultBranch?{state:"verified",method:a.performed,...n}:{state:"stale",method:a.performed,...n,reason:`commit "${i.target}" is not an ancestor of the default branch`}}if(i.scheme!=="path")return{state:"unverified",method:"none",...n,reason:`no mechanical checker is wired for "${i.scheme}:" anchors yet`};const o=e.root;if(!o)return{state:"unknown",method:"none",...n,reason:"no project root could be resolved for the subject"};if(!bn(o))return{state:"unknown",method:"none",...n,reason:`no git work tree at "${o}"`};const r=Xg(o,i.target);if(r===void 0)return{state:"unknown",method:"none",...n,reason:`anchor path "${i.target}" lies outside the project root`};if(!vc(o,r))return{state:"stale",method:"exists_at_head",...n,reason:`"${r}" is not present at HEAD`};if(e.sinceISO!==void 0&&Wg(o,r,e.sinceISO)){if(e.full!==!0)return{state:"stale",method:"changed_since",...n,reason:`"${r}" changed since ${e.sinceISO}`};const s=Jg(o,r);return s!==void 0&&s===t.digest.toLowerCase()?{state:"verified",method:"full_resolve",...n}:{state:"stale",method:"full_resolve",...n,reason:`"${r}" content no longer matches the anchor digest`}}return{state:"verified",method:"changed_since",...n}}function xn(t){const e=t??{};return{claimedBy:typeof e.claimedBy=="string"?e.claimedBy:void 0,claimedAt:typeof e.claimedAt=="string"?e.claimedAt:void 0}}function Ec(t,e){return t!==void 0?(Date.parse(e)-Date.parse(t))/6e4:Number.POSITIVE_INFINITY}function Fn(t,e,n){return Ec(t,e)>=n}function Sc(t){let e=!1;for(const n of t)if(n.severity==="block"){if(n.status==="True")return!1;n.status==="Unknown"&&(e=!0)}return e?"unknown":!0}function kc(t){const e=n=>n.severity==="block"?0:1;return[...t].sort((n,i)=>{const o=e(n)-e(i);if(o!==0)return o;const r=n.code.localeCompare(i.code);return r!==0?r:(n.subject??"").localeCompare(i.subject??"")})}const Qg=30;function Zg(t,e){return{type:"Budget",status:"Unknown",severity:"block",code:"Unknown",message:e}}function Fo(t,e=[]){switch(t.op){case"evidence":return e.includes(t.kind)||e.push(t.kind),e;case"all_of":case"any_of":for(const n of t.of)Fo(n,e);return e;case"not":return Fo(t.of,e),e;default:return e}}async function _c(t,e){switch(t.op){case"evidence":case"blockers_terminal":case"relation":return t.op;case"all_of":case"any_of":{for(const n of t.of)if(!await ue(n,e))return _c(n,e);return t.op}case"not":return t.op}}function eh(t){switch(t){case"evidence":return{code:"EvidenceUnverified",type:"Evidence"};case"blockers_terminal":return{code:"BlockedBy",type:"Blocked"};case"relation":return{code:"ReferenceUnresolved",type:"Reference"};default:return{code:"Unknown",type:"Obligation"}}}function th(t,e,n){return{async countVerifiedAttestations(i){const o=await t.getEdges({src:e.id,rel:"attests"});if(o.length===0)return 0;const r=await t.getNodesByIds(o.map(a=>a.dst));let s=0;for(const a of r){const c=a.metadata,d=c==null?void 0:c.claim,l=c==null?void 0:c.check,u=d!==null&&typeof d=="object"?d.kind:void 0,f=l!==null&&typeof l=="object"?l.state:void 0;u===i&&f==="verified"&&(s+=1)}return s},async blockersAllTerminal(){return n.length===0},async relationExists(i,o){return(o==="in"?await t.getEdges({dst:e.id,rel:i}):await t.getEdges({src:e.id,rel:i})).length>0}}}async function nh(t){const e=await t.queryNodes({kind:"status",liveOnly:!0}),n=new Set,i=new Set;for(const o of e)typeof o.name=="string"&&(n.add(o.name),Ae(o)&&i.add(o.name));return{all:n,terminal:i}}function oh(t){var i;const e=(i=t.applies_to)==null?void 0:i.to,n=t.on_fail;return t.requirement===void 0||typeof e!="string"||e.trim().length===0||n!=="block"&&n!=="warn"}async function ih(t,e){var o;const{project:n}=await Ge(t,e),i=(o=n==null?void 0:n.metadata)==null?void 0:o.path;return typeof i=="string"&&i.length>0?i:void 0}async function rh(t,e,n){const i=await t.getEdges({src:e,rel:"attests"});if(i.length===0)return;const o=await t.getNodesByIds(i.map(r=>r.dst));for(const r of o){const s=r.metadata,a=s==null?void 0:s.claim,c=s==null?void 0:s.check,d=s==null?void 0:s.anchor,l=a!==null&&typeof a=="object"?a.kind:void 0,u=c!==null&&typeof c=="object"?c.state:void 0;if(l!==n||u!=="verified")continue;const f={uid:r.uid};if(d!==null&&typeof d=="object"){const p=d.locator,g=d.digest;typeof p=="string"&&typeof g=="string"&&(f.anchor={locator:p,digest:g})}const m=a!==null&&typeof a=="object"?a.asserted_at:void 0;return typeof m=="string"&&(f.assertedAt=m),f}}function sh(t){try{return Mn(t)}catch{return}}async function ah(t,e,n,i,o){var s,a,c;const r=[];for(const d of i){const l=await rh(t,e,d);if((l==null?void 0:l.anchor)===void 0){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:`no stored-verified "${d}" attestation with a readable anchor`});continue}const u=sh(l.anchor.locator);if((u==null?void 0:u.scheme)!=="path"&&(u==null?void 0:u.scheme)!=="commit"){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:`no mechanical checker is wired for "${(u==null?void 0:u.scheme)??"unknown"}:" anchors yet`});continue}const f=await ih(t,e);if(f===void 0){r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"no project root could be resolved for the subject"});continue}(s=o.onRung)==null||s.call(o,3),o.maxRung>=4&&u.scheme==="path"&&((a=o.onRung)==null||a.call(o,4)),o.maxRung>=5&&((c=o.onRung)==null||c.call(o,5));const m=Ri(l.anchor,{root:f,...o.maxRung>=4&&l.assertedAt!==void 0?{sinceISO:l.assertedAt}:{},...o.maxRung>=5?{full:!0}:{},now:o.at,by:"verdict"});if(m.state==="stale"){r.push({type:"Evidence",status:"True",severity:n.on_fail,code:"EvidenceStale",subject:l.uid,message:`the "${d}" anchor is stale (${m.reason??m.method})`});continue}m.state==="verified"&&o.maxRung>=4||r.push({type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:m.state==="unknown"||m.state==="unverified"?`the "${d}" anchor could not be mechanically resolved (${m.reason??m.method})`:`the "${d}" anchor presence was confirmed but freshness was not re-resolved at this rung`})}return r}async function ch(t,e,n,i,o){let r;try{r=await ue(n.requirement,i)}catch{return[{type:"Obligation",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"the obligation predicate could not be evaluated"}]}if(!r){const a=eh(await _c(n.requirement,i));return[{type:a.type,status:"True",severity:n.on_fail,code:a.code,subject:n.uid,message:`obligation unsatisfied: ${a.code}`}]}const s=Fo(n.requirement);return s.length===0?[]:o.maxRung<3?[{type:"Evidence",status:"Unknown",severity:n.on_fail,code:"Unknown",subject:n.uid,message:"evidence anchor not re-resolved at this rung — actionability is genuinely unknown"}]:ah(t,e.id,n,s,o)}async function dh(t,e,n={}){var d,l;const i=n.maxRung??2,o=n.at??P(),r=n.claimStaleAfterMin??Qg,s=[];(d=n.onRung)==null||d.call(n,1);const a=await $c(t,e.id);for(const u of a)s.push({type:"Blocked",status:"True",severity:"block",code:"BlockedBy",subject:u.uid,message:`blocked by ${u.uid}`});if(i<2)s.push(Zg(void 0,"obligations were not evaluated at this rung"));else{(l=n.onRung)==null||l.call(n,2);const u=await Pc(t,e.id);u.length===0&&s.push({type:"Obligation",status:"True",severity:"warn",code:"MissingObligation",message:"no obligations are declared on this item"});const f=th(t,e,a),m=await nh(t),p={maxRung:i,at:o,...n.onRung?{onRung:n.onRung}:{}};for(const w of u){if(oh(w)){s.push({type:"Obligation",status:"True",severity:w.on_fail==="warn"?"warn":"block",code:"MissingObligation",subject:w.uid,message:"the obligation is malformed and cannot be evaluated"});continue}const v=w.applies_to.to;v==="*"||m.terminal.has(v)||!m.all.has(v)||s.push(...await ch(t,e,w,f,p))}const{claimedBy:g,claimedAt:y}=xn(e.metadata);g!==void 0&&Fn(y,o,r)&&s.push({type:"Claim",status:"True",severity:"warn",code:"ClaimStale",subject:g,message:`claim by "${g}" is stale (threshold ${r}min)`})}const c=kc(s);return{actionable:Sc(c),evaluated_at:o,revision:$e(e.metadata),conditions:c}}const lh="sha256:";function uh(t){return`${lh}${He(t)}`}function fh(t,e){const n=t==null?void 0:t[e];return typeof n=="string"&&n.length>0?n:void 0}function ph(t,e){const n=t==null?void 0:t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}const zr=["normal","force","snapshot"];function mh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_APPEND;if(t===void 0)return"normal";if(zr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_APPEND="${t}" is not a recognized mode (expected ${zr.join(", ")}). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting.`)}const Yr=["normal","raw-kind-only"];function gh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_DISCOVERY;if(t===void 0)return"normal";if(Yr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_DISCOVERY="${t}" is not a recognized mode (expected ${Yr.join(", ")}). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting.`)}function Ac(){return gh()==="raw-kind-only"}async function hh(t,e){const n=await se(t,e,{expectedKind:"issue"}),i=new Set([n.uid]),o=new Set([n.rowid]);let r=n;for(;;){const s=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL LIMIT 1",[r.rowid,"SUPERSEDES"]);if(!s)break;const a=await Q(t,s.src);if(a===null||a.tInvalid!==null||o.has(a.rowid))break;o.add(a.rowid),i.add(a.uid),r=a}return{head:r,chainUids:i}}async function Nc(t){return wc(t,{rel:"has_kind",expectedKind:"kind",ref:"SPEC"})}async function Rc(t){const e=new Map;for(const i of await t.queryNodes({kind:"SPEC",liveOnly:!0}))e.set(i.uid,i);const n=await Nc(t);if(n!==void 0&&n.size>0){const i=await t.getNodesByIds([...n],{liveOnly:!0});for(const o of i)e.set(o.uid,o)}return[...e.values()]}async function yh(t,e,n){const i=[...e];if(i.length===0)return;const o=i.map(()=>"?").join(", "),r=[];let s="kind = 'SPEC'";const a=n===void 0?[]:[...n];a.length>0&&(s=`(kind = 'SPEC' OR rowid IN (${a.map(()=>"?").join(", ")}))`,r.push(...a));const c=await t.executeGet(`SELECT uid FROM node
|
|
200
|
+
WHERE ${s} AND t_invalid IS NULL
|
|
201
|
+
AND json_extract(meta, '$.spec_of') IN (${o})
|
|
202
|
+
ORDER BY json_extract(meta, '$.revision_seq') DESC
|
|
203
|
+
LIMIT 1`,[...r,...i]);return c?await Be(t,c.uid)??void 0:void 0}async function wh(t,e){const n=[],i=new Set;let o=e;for(;o&&!i.has(o.uid);){i.add(o.uid),n.push(o.content);const r=fh(o.metadata,"prev_revision");o=r?await Be(t,r)??void 0:void 0}return n.reverse().join("")}async function vh(t,e){if(typeof e.uid!="string"||e.uid.trim().length===0)throw new T("uid","is required");if(typeof e.fragment!="string")throw new T("fragment","must be a string");if(typeof e.base_revision!="string")throw new T("base_revision","is required");if(typeof e.by!="string"||e.by.trim().length===0)throw new T("by","is required");G("by",e.by);const n=mh(),i=Ac()?void 0:await Nc(t.graph);return M(t,async o=>{const{head:r,chainUids:s}=await hh(o,e.uid),a=P(),c=await yh(o,s,i),d=(c==null?void 0:c.uid)??"",l=c?ph(c.metadata,"revision_seq")??0:0;if(n!=="force"&&e.base_revision!==d)throw new To(e.base_revision,d);const u=l+1,f=(c==null?void 0:c.uid)??null,m=c?await wh(o,c):"",p=n==="snapshot"?`${m}${e.fragment}`:e.fragment,g=`${m}${e.fragment}`,y=uh(g),w=e.anchor??{locator:"",digest:""},v={spec_of:r.uid,revision_seq:u,revision_token:y,prev_revision:f,anchor:w,appended_by:e.by,appended_at:a},b=await X(o,{at:a,kind:"SPEC",content:p,metadata:v});if(await $o(o,r.uid,{spec_revision:b.uid,spec_revision_token:y,spec_revision_seq:u},$e(r.metadata))===null)throw new To(e.base_revision,d);return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"spec-appended",to:b.uid,note:`seq ${u}`,at:a}),{uid:r.uid,spec_revision:b.uid,spec_revision_token:y,revision_seq:u}})}async function jc(t,e){let n;try{n=await gc(t,e)}catch{return}const i=new Set([e,n.uid]);let o=n;const r=new Set([n.id]);for(;;){const a=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(d=>!r.has(d.src));if(!a)break;r.add(a.src);const[c]=await t.getNodesByIds([a.src]);if(!c||c.tInvalid)break;i.add(c.uid),o=c}return{uid:n.uid,chainUids:i}}async function Tc(t,e){var s,a;const n=await jc(t,e);if(!n)return;const o=(Ac()?await t.queryNodes({kind:"SPEC",liveOnly:!0}):await Rc(t)).filter(c=>{var l;const d=(l=c.metadata)==null?void 0:l.spec_of;return typeof d=="string"&&n.chainUids.has(d)});if(o.length===0)return;o.sort((c,d)=>{var l,u;return(typeof((l=d.metadata)==null?void 0:l.revision_seq)=="number"?d.metadata.revision_seq:0)-(typeof((u=c.metadata)==null?void 0:u.revision_seq)=="number"?c.metadata.revision_seq:0)});const r=o[0];return{revision_uid:r.uid,revision_token:typeof((s=r.metadata)==null?void 0:s.revision_token)=="string"?r.metadata.revision_token:"",revision_seq:typeof((a=r.metadata)==null?void 0:a.revision_seq)=="number"?r.metadata.revision_seq:0}}async function Oc(t,e){var r,s,a;const n=await jc(t,e);if(!n)return;const i=await t.getNodeByUid(n.uid);if(!i)return;const o=typeof((r=i.metadata)==null?void 0:r.spec_revision)=="string"?i.metadata.spec_revision:void 0;if(o)return{revision_uid:o,revision_token:typeof((s=i.metadata)==null?void 0:s.spec_revision_token)=="string"?i.metadata.spec_revision_token:"",revision_seq:typeof((a=i.metadata)==null?void 0:a.spec_revision_seq)=="number"?i.metadata.spec_revision_seq:0}}async function bh(t,e){return await Oc(t,e)??await Tc(t,e)}const Xr=["normal","default-fresh"];function Eh(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_STALENESS;if(t===void 0)return"normal";if(Xr.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_STALENESS="${t}" is not a recognized mode (expected ${Xr.join(", ")}). This variable exists solely for negative-control test runs and must never be set in normal operation.`)}function Qr(t){return t.startsWith("sha256:")?t.slice(7):t}async function Ic(t,e){const n=Eh(),i=await Oc(t,e.uid),o=await Tc(t,e.uid);if(i!==void 0&&o!==void 0&&i.revision_uid!==o.revision_uid)return{current_revision:o.revision_uid,current_token:o.revision_token,state:"stale",method:"none",reason:"revision-drift"};const r=i??o;return r===void 0?{current_revision:"",current_token:"",state:"unknown",method:"none",reason:"no-revision"}:e.token===void 0||e.token===""?n==="default-fresh"?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"token"}:{current_revision:r.revision_uid,current_token:r.revision_token,state:"stale",method:"none",reason:"no-token-supplied"}:e.token===r.revision_token?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"token"}:Qr(e.token)===Qr(r.revision_token)?{current_revision:r.revision_uid,current_token:r.revision_token,state:"fresh",method:"content_hash"}:{current_revision:r.revision_uid,current_token:r.revision_token,state:"stale",method:"token",reason:"older-token"}}function ji(t){if(t){for(const e of t)if(!Cg(e))throw new _e("fields",`unknown field "${e}" — known fields: ${[..._i,...Ai].join(", ")}`)}}function Ae(t){var e;return((e=t==null?void 0:t.metadata)==null?void 0:e.terminal)===!0}async function Sh(t,e,n){const i=n.find(l=>l.rel==="has_kind"&&l.src===e),o=n.find(l=>l.rel==="has_status"&&l.src===e),r=n.find(l=>l.rel==="has_priority"&&l.src===e),s=n.find(l=>l.rel==="authored_by"&&l.src===e),a=[i==null?void 0:i.dst,o==null?void 0:o.dst,r==null?void 0:r.dst,s==null?void 0:s.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await t.getNodesByIds(a),d=new Map(c.map(l=>[l.id,l]));return{kind:i?d.get(i.dst):void 0,status:o?d.get(o.dst):void 0,priority:r?d.get(r.dst):void 0,author:s?d.get(s.dst):void 0}}async function kh(t,e,n){const i=n.filter(r=>r.rel==="has_citation"&&r.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(r=>r.dst))).map(r=>Lg({uid:r.uid,name:r.name,content:r.content,metadata:r.metadata,tCreated:r.tCreated}))}async function _h(t,e,n){const i=n.filter(r=>r.rel==="has_note"&&r.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(r=>r.dst))).map(r=>{var s,a,c;return{uid:r.uid,author:typeof((s=r.metadata)==null?void 0:s.author)=="string"?r.metadata.author:"",text:typeof((a=r.metadata)==null?void 0:a.text)=="string"?r.metadata.text:r.content,at:typeof((c=r.metadata)==null?void 0:c.at)=="string"?r.metadata.at:r.tCreated}})}async function Ah(t,e,n){const i=(n??await me(t,e)).filter(s=>s.rel==="audits"&&s.src===e);return i.length===0?[]:(await t.getNodesByIds(i.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,m;return{uid:s.uid,actor:typeof((a=s.metadata)==null?void 0:a.actor)=="string"?s.metadata.actor:"",action:typeof((c=s.metadata)==null?void 0:c.action)=="string"?s.metadata.action:s.name??"",from:typeof((d=s.metadata)==null?void 0:d.from)=="string"?s.metadata.from:void 0,to:typeof((l=s.metadata)==null?void 0:l.to)=="string"?s.metadata.to:void 0,note:typeof((u=s.metadata)==null?void 0:u.note)=="string"?s.metadata.note:void 0,sha:typeof((f=s.metadata)==null?void 0:f.sha)=="string"?s.metadata.sha:"",at:typeof((m=s.metadata)==null?void 0:m.at)=="string"?s.metadata.at:s.tCreated}}).sort((s,a)=>s.at.localeCompare(a.at))}async function $c(t,e){const n=await t.getEdges({dst:e,rel:"blocks"});if(n.length===0)return[];const i=n.map(s=>s.src),o=await t.getNodesByIds(i),r=await Bt(t,o);return o.filter(s=>!Ae(r.get(s.id))).map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=r.get(s.id))==null?void 0:a.name)??""}})}async function Nh(t,e,n){const i=n??await me(t,e),o=await yc(t,e),r=new Map,s=(d,l)=>{r.has(d)||r.set(d,l)};for(const d of i)d.rel==="relates_to"?s(d.dst,"relates_to"):d.rel==="part_of"?s(d.dst,"part_of"):d.rel==="blocks"&&s(d.dst,"blocks");for(const d of o)d.rel==="relates_to"?s(d.src,"relates_to"):d.rel==="part_of"?s(d.src,"part_of"):d.rel==="blocks"&&s(d.src,"blocked_by");if(r.size===0)return[];const a=await t.getNodesByIds([...r.keys()]),c=await Bt(t,a);return a.map(d=>{var l;return{uid:d.uid,title:d.name??"",status:((l=c.get(d.id))==null?void 0:l.name)??"",rel:r.get(d.id)}})}async function Rh(t,e,n){const i=n??await me(t,e),o=await yc(t,e),r=i.filter(p=>p.rel==="similar_to"&&p.src===e),s=o.filter(p=>p.rel==="similar_to"&&p.dst===e),a=[...new Set([...r.map(p=>p.dst),...s.map(p=>p.src)])];if(a.length===0)return{similarTo:[],similarFrom:[]};const c=await t.getNodesByIds(a),d=new Map(c.map(p=>[p.id,p])),l=await Bt(t,c),u=async p=>{var v,b;const g=d.get(p);if(!g)return;const{project:y}=await Ge(t,g.id),w={uid:g.uid,title:g.name??"",status:((v=l.get(g.id))==null?void 0:v.name)??""};return y&&(w.projectUid=y.uid,typeof((b=y.metadata)==null?void 0:b.repoUrl)=="string"&&(w.repoUrl=y.metadata.repoUrl)),w},f=[];for(const p of r){const g=await u(p.dst);g&&f.push(g)}const m=[];for(const p of s){const g=await u(p.src);g&&m.push(g)}return{similarTo:f,similarFrom:m}}async function jh(t,e,n){const i=(n??await me(t,e)).filter(s=>s.rel==="blocks"&&s.src===e);if(i.length===0)return[];const o=await t.getNodesByIds(i.map(s=>s.dst));if(o.length===0)return[];const r=await Bt(t,o);return o.map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=r.get(s.id))==null?void 0:a.name)??"",rel:"blocks"}})}async function Cc(t,e,n){const i=new Set,o=[e];for(;o.length>0;){const r=o.shift(),s=await t.getEdges({src:r,rel:"blocks"});for(const a of s)a.dst===e||i.has(a.dst)||n&&!n.has(a.dst)||(i.add(a.dst),o.push(a.dst))}return i.size}async function Th(t,e,n){var s;const i=(n??await me(t,e)).find(a=>a.rel==="part_of"&&a.src===e);if(!i)return null;const[o]=await t.getNodesByIds([i.dst]);if(!o)return null;const r=await Bt(t,[o]);return{uid:o.uid,title:o.name??"",status:((s=r.get(o.id))==null?void 0:s.name)??"",rel:"part_of"}}async function Pc(t,e,n){const i=(n??await me(t,e)).filter(a=>a.rel==="has_obligation"&&a.src===e);if(i.length===0)return[];const o=await t.getNodesByIds(i.map(a=>a.dst)),r=new Map(o.map(a=>[a.id,a])),s=[];for(const a of i){const c=r.get(a.dst);if(!c)continue;const d=c.metadata,l=d==null?void 0:d.applies_to,u=d==null?void 0:d.requirement,f=d==null?void 0:d.on_fail;if(l===void 0||u===void 0||f===void 0)continue;const m={uid:c.uid,applies_to:l,requirement:u,on_fail:f},p=d==null?void 0:d.override;p!==void 0&&(m.override=p),s.push(m)}return s}async function Bt(t,e){if(e.length===0)return new Map;const n=new Set(e.map(d=>d.id)),i=await t.getEdges({rel:"has_status"}),o=new Map;for(const d of i)n.has(d.src)&&!o.has(d.src)&&o.set(d.src,d.dst);const r=[...new Set(o.values())];if(r.length===0)return new Map;const s=await t.getNodesByIds(r),a=new Map(s.map(d=>[d.id,d])),c=new Map;for(const[d,l]of o){const u=a.get(l);u&&c.set(d,u)}return c}function nn(t,e){if(!e)return t;let n=t;if(e.after!==void 0){const i=n.findIndex(o=>o.uid===e.after);i>=0&&(n=n.slice(i+1))}return e.lastN!==void 0&&(n=n.slice(-e.lastN)),n}async function Lc(t,e,n,i={}){var S,E,N;const o={uid:e.uid},r=k=>n.includes(k),s=r("kind")||r("status")||r("priority")||r("author"),a=r("project")||r("component"),c=r("citations"),d=r("notes"),l=r("auditTrail"),u=r("blockers"),f=r("related"),m=r("blocksOut"),p=r("dependents"),g=r("partOf"),y=r("obligations"),w=r("verdict"),v=r("spec"),b=r("similar"),h=i.outgoingEdges??(s||c||d||l||f||m||g||y||b?await me(t,e.id):void 0);if(r("title")&&(o.title=e.name??""),r("createdAt")&&(o.createdAt=e.tCreated),r("updatedAt")&&(o.updatedAt=e.tValid),r("assignee")){const k=(S=e.metadata)==null?void 0:S.assignee;typeof k=="string"&&(o.assignee=k)}if(r("gitContext")){const k=(E=e.metadata)==null?void 0:E.gitContext;typeof k=="string"&&k.length>0&&(o.gitContext=k)}if(r("closedAt")){const k=(N=e.metadata)==null?void 0:N.closedAt;typeof k=="string"&&(o.closedAt=k)}if(r("body")&&(o.body=e.content),s&&h){const k=await Sh(t,e.id,h);r("kind")&&k.kind&&(o.kind=k.kind.name??""),r("status")&&k.status&&(o.status=k.status.name??""),r("priority")&&k.priority&&(o.priority=k.priority.name??""),r("author")&&k.author&&(o.author=k.author.name??"")}if(a){const{project:k,component:R}=await Ge(t,e.id);r("project")&&k&&(o.project=k.uid),r("component")&&R&&(o.component=R.uid)}if(c&&h&&(o.citations=nn(await kh(t,e.id,h),i.bounds)),d&&h&&(o.notes=await _h(t,e.id,h)),l&&h&&(o.auditTrail=nn(await Ah(t,e.id,h),i.bounds)),u&&(o.blockers=nn(await $c(t,e.id),i.bounds)),f&&h&&(o.related=nn(await Nh(t,e.id,h),i.bounds)),m&&h&&(o.blocksOut=await jh(t,e.id,h)),p&&(o.dependents=await Cc(t,e.id,i.scope)),g&&h&&(o.partOf=await Th(t,e.id,h)),y&&h&&(o.obligations=await Pc(t,e.id,h)),w)try{o.verdict=await dh(t,e,{...i.verdictRung!==void 0?{maxRung:i.verdictRung}:{},...i.onVerdictRung!==void 0?{onRung:i.onVerdictRung}:{}})}catch(k){const R=P();o.verdict={actionable:"unknown",evaluated_at:R,revision:$e(e.metadata),conditions:[{type:"Budget",status:"Unknown",severity:"block",code:"Unknown",message:`verdict derivation failed: ${k instanceof Error?k.message:String(k)}`}]}}if(v){const k=await bh(t,e.uid);k&&(o.spec={spec_revision:k.revision_uid,spec_revision_token:k.revision_token,revision_seq:k.revision_seq},i.specToken!==void 0&&(o.spec.freshness=(await Ic(t,{uid:e.uid,token:i.specToken})).state))}return b&&h&&(o.similar=await Rh(t,e.id,h)),r("_score")&&i.score!==void 0&&(o._score=i.score,i.scoreKind!==void 0&&(o._score_kind=i.scoreKind)),o}async function Tt(t,e,n,i,o,r){const s=new Set(e.map(a=>a.id));return Promise.all(e.map(a=>Lc(t,a,n,{score:i==null?void 0:i.get(a.uid),scoreKind:o==null?void 0:o.get(a.uid),scope:s,...(r==null?void 0:r.rung)!==void 0?{verdictRung:r.rung}:{},...(r==null?void 0:r.onRung)!==void 0?{onVerdictRung:r.onRung}:{}})))}const Oh=.0050125;function Ih(t){if(t===void 0)return Ln;if(!Number.isInteger(t)||t<=0||t>le)throw new _e("limit",`must be a positive integer ≤ ${le}, got ${t}`);return t}async function $h(t,e){const n=new Set;for(const i of e.refs){const o=await wc(t,{rel:e.rel,expectedKind:e.expectedKind,ref:i});if(o)for(const r of o)n.add(r)}return n}async function Ch(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function Ph(t,e){if(e.project===void 0&&e.component===void 0)return;let n,i;if(e.project!==void 0){const c=await x(t,"project",e.project);if(!c)return new Set;n=c.uid;const d=await t.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const u of d){const f=await t.getEdges({src:u.dst,rel:"owns_component"});for(const m of f)l.add(m.dst)}i=l}if(e.component===void 0)return i;const o=n!==void 0?await Ve(t,n,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"}),s=new Set(r.map(c=>c.dst));if(!i)return s;const a=new Set;for(const c of s)i.has(c)&&a.add(c);return a}function Lh(t){var i,o,r,s;const e={};t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until}));const n={};return Object.keys(e).length>0&&(n.metadata=e),(i=t.createdAt)!=null&&i.since&&(n.tCreatedAfter=t.createdAt.since),(o=t.createdAt)!=null&&o.until&&(n.tCreatedBefore=t.createdAt.until),(r=t.updatedAt)!=null&&r.since&&(n.tUpdatedAfter=t.updatedAt.since),(s=t.updatedAt)!=null&&s.until&&(n.tUpdatedBefore=t.updatedAt.until),Object.keys(n).length>0?n:void 0}async function Bn(t,e){if(!e)return;const n=[],i=await Ph(t,e);if(i!==void 0&&n.push(i),e.kind!==void 0){const c=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await nt(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await Ch(t,e.status));else{const c=Array.isArray(e.status)?e.status:[e.status];n.push(await nt(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(e.priority!==void 0){const c=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await nt(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}if(e.author!==void 0&&n.push(await $h(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.similarTo!==void 0){const c=await x(t,"issue",e.similarTo);if(!c)return new Set;const d=await t.getEdges({dst:c.id,rel:"similar_to"});n.push(new Set(d.map(l=>l.src)))}if(e.hasSimilar===!0){const c=await t.getEdges({rel:"similar_to"});n.push(new Set(c.map(d=>d.dst)))}const o=Lh(e);if(n.length===0&&!o)return;let r;if(n.length>0){let[c]=n;for(const d of n.slice(1)){const l=new Set;for(const u of c)d.has(u)&&l.add(u);c=l}if(r=c,r.size===0)return new Set}const s={kind:"issue",liveOnly:!0,isSuperseded:!1,...r?{ids:[...r]}:{},...o},a=await t.queryNodes(s);return new Set(a.map(c=>c.id))}const Uh=4;async function Dh(t,e){if(e.length===0)return[];const n=e.map(s=>s.id),i={ids:n,isSuperseded:!1,limit:n.length},o=await t.queryNodes(i),r=new Set(o.map(s=>s.id));return e.filter(s=>r.has(s.id))}async function Mh(t,e){var s;if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(((s=e.candidateIds)==null?void 0:s.size)===0)return[];const n=e.candidateIds?{ids:[...e.candidateIds]}:{kind:"issue"},i={text:e.text,vec:e.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:e.decayPerHour??Oh}],filters:n},o=[];let r=e.limit;for(let a=0;a<Uh;a++){const c=await t.search.backend.searchRanked(i,r);if(o.length=0,o.push(...await Dh(t.graph,c)),o.length>=e.limit||c.length<r)break;r*=2}return o.slice(0,e.limit)}async function xh(t,e){var h,S;const{graph:n}=t;if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");ji(e.fields);const i=e.fields??Ft,o=Ih(e.limit);let r,s;if(((h=e.filter)==null?void 0:h.anchor)!==void 0)s=await Dn(n,e.filter.anchor),r=`${s.name??""}
|
|
204
|
+
${s.content}`.trim();else if(((S=e.filter)==null?void 0:S.semantic)!==void 0)r=e.filter.semantic;else throw new T("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await Bn(n,e.filter);if(a&&s&&a.delete(s.id),(a==null?void 0:a.size)===0)return{items:[],hasMore:!1,limit:o};const c=await t.search.embedQuery(r),d=s?o+2:o+1,l=await Mh(t,{text:r,vec:c,candidateIds:a,limit:d}),u=s?l.filter(E=>E.id!==s.id):l,f=u.length>o,m=u.slice(0,o);if(m.length===0)return{items:[],hasMore:!1,limit:o};const p=await n.getNodesByIds(m.map(E=>E.id)),g=new Map(p.map(E=>[E.id,E])),y=m.map(E=>g.get(E.id)).filter(E=>E!==void 0),w=new Map(m.map(E=>{var N;return[(N=g.get(E.id))==null?void 0:N.uid,E.score]}).filter(E=>E[0]!==void 0)),v=new Map([...w.keys()].map(E=>[E,"rrf"]));return{items:await Tt(n,y,i,w,v),hasMore:f,limit:o}}const Fh=new Set(["a","an","and","are","as","at","be","but","by","for","from","has","have","in","is","it","its","of","on","or","that","the","this","to","was","were","will","with"]);function En(t){return t.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0&&!Fh.has(e))}function Bh(t,e){const n=new Set(En(t)),i=new Set(En(e));if(n.size===0||i.size===0)return 0;let o=0;for(const s of n)i.has(s)&&(o+=1);const r=n.size+i.size-o;return r===0?0:o/r}function Zr(t){if(t===void 0)return;const e=t.trim().replace(/\\/g,"/").toLowerCase();if(e.length!==0)return e.endsWith("/")?e.slice(0,-1):e}function Kh(t,e){const n=new Set((t.citationTokens??[]).flatMap(s=>En(s))),i=new Set((e.citationTokens??[]).flatMap(s=>En(s)));for(const s of n)if(i.has(s))return!0;const o=Zr(t.componentPath),r=Zr(e.componentPath);return!!(o&&r&&(o===r||o.startsWith(`${r}/`)||r.startsWith(`${o}/`)))}const qh=5;async function Hh(t,e){return e===void 0?void 0:Bn(t,{project:e})}async function Vh(t,e){var c,d,l,u;if(e===void 0)return;const n=await x(t,"project",e);if(!n)return;const i=typeof((c=n.record.metadata)==null?void 0:c.repoUrl)=="string"&&n.record.metadata.repoUrl.length>0?n.record.metadata.repoUrl:void 0,o=new Set;for(const f of await t.getEdges({src:n.id,rel:"owns_project"})){const[m]=await t.getNodesByIds([f.dst]),p=(d=m==null?void 0:m.metadata)==null?void 0:d.path;typeof p=="string"&&p.length>0&&o.add(p)}const r=[],s=await t.queryNodes({kind:"project",liveOnly:!0});for(const f of s){if(f.uid===n.uid)continue;const m=(l=f.metadata)==null?void 0:l.repoUrl;if(i!==void 0&&typeof m=="string"&&m===i){r.push(f.uid);continue}if(o.size!==0)for(const p of await t.getEdges({src:f.id,rel:"owns_project"})){const[g]=await t.getNodesByIds([p.dst]),y=(u=g==null?void 0:g.metadata)==null?void 0:u.path;if(typeof y=="string"&&y.length>0&&o.has(y)){r.push(f.uid);break}}}if(r.length===0)return;const a=new Set;for(const f of[n.uid,...r]){const m=await Bn(t,{project:f});if(m)for(const p of m)a.add(p)}return a}async function Gh(t,e,n){if(e!=="store-wide")return e==="multi-project"?Vh(t,n):Hh(t,n)}async function Uc(t,e){var s,a;const n=[],i=await t.getEdges({src:e,rel:"has_citation"});if(i.length>0){const c=await t.getNodesByIds(i.map(d=>d.dst));for(const d of c)for(const l of["target","symbol","errorText","blastRadius"]){const u=(s=d.metadata)==null?void 0:s[l];typeof u=="string"&&n.push(u)}}const{component:o}=await Ge(t,e),r=typeof((a=o==null?void 0:o.metadata)==null?void 0:a.path)=="string"?o.metadata.path:void 0;return{citationTokens:n,componentPath:r}}function Wh(t,e){var n;if(t)return{projectUid:t.uid,projectName:t.name??"",...e?{componentUid:e.uid}:{},...typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?{repoUrl:t.metadata.repoUrl}:{}}}async function Dc(t,e){var w,v;const{search:n,graph:i}=t;if(!i)return{candidates:[],degraded:!0,degradedReason:"no-search-backend"};const o=await Gh(i,e.scope,e.projectUid);if((o==null?void 0:o.size)===0)return{candidates:[],degraded:!1};if(o&&e.excludeIds){for(const b of e.excludeIds)o.delete(b);if(o.size===0)return{candidates:[],degraded:!1}}if(!n)return{candidates:[],degraded:!0,degradedReason:"no-search-backend"};if(typeof n.embedQuery!="function")return{candidates:[],degraded:!0,degradedReason:"no-embed-query"};const r=Si(e.title,e.body),s=await n.embedQuery(r),c={text:r,vec:s,signals:[{kind:"text"},{kind:"vec"}],filters:o?{ids:[...o]}:{kind:"issue"}},d=e.limit??qh,l=d*4,u=await n.backend.search(c,l);if(u.length===0)return{candidates:[],degraded:!0,degradedReason:"no-vector-scores"};const f=await i.getNodesByIds(u.map(b=>b.id)),m=new Map(f.map(b=>[b.id,b])),p=[];let g=!1;for(const b of u){const h=m.get(b.id);if(!h||h.tInvalid!==void 0||h.isSuperseded||(w=e.excludeIds)!=null&&w.has(b.id)||o&&!o.has(b.id))continue;const S=b.vecScore;S!==void 0&&(g=!0,p.push({node:h,score:S}))}if(!g)return{candidates:[],degraded:!0,degradedReason:"no-vector-scores"};p.sort((b,h)=>h.score-b.score);const y=[];for(let b=0;b<p.length;b+=1){const{node:h,score:S}=p[b],E=await Ge(i,h.id),N=(v=E.project)==null?void 0:v.uid,k=e.projectUid!==void 0&&N===e.projectUid,R=Wh(E.project,E.component);if(k){if(S<e.sameProjectThreshold)continue;y.push({uid:h.uid,title:h.name??"",score:S,scope:"same-project",provenance:R});continue}if(S<e.crossProjectThreshold)continue;const A=await Uc(i,h.id),O=Bh(e.title,h.name??""),I=Kh({title:e.title,citationTokens:e.citationTokens,componentPath:e.componentPath},{title:h.name??"",citationTokens:A.citationTokens,componentPath:A.componentPath});if(!(O>=e.tokenOverlapMin||I))continue;const L=p[b+1];if(L&&S-L.score<e.margin)continue;const $=["cosine"];O>=e.tokenOverlapMin&&$.push("title-tokens"),I&&$.push("structural"),y.push({uid:h.uid,title:h.name??"",score:S,scope:"cross-project",provenance:R,signals:$})}return y.sort((b,h)=>h.score-b.score),{candidates:y.slice(0,d),degraded:!1}}async function Jh(t,e){return(await Dc(t,e)).candidates}async function zh(t,e){const n=await t.getNodeByUid(e);if(!n||n.tInvalid!==void 0)return;const i=Se({uid:n.uid,rowid:n.id,name:n.name??"",metadata:n.metadata});return{projectUid:n.uid,policy:i}}async function es(t,e,n){var o;if(e.length===0)return[];const i=[];for(const r of e){const s=await t.getNodeByUid(r);if(!s||s.tInvalid!==void 0)continue;const{project:a,component:c}=await Ge(t,s.id),d=n.get(r)??{};i.push({uid:s.uid,title:s.name??"",projectUid:(a==null?void 0:a.uid)??"",projectName:(a==null?void 0:a.name)??"",...c?{componentUid:c.uid}:{},...a&&typeof((o=a.metadata)==null?void 0:o.repoUrl)=="string"?{repoUrl:a.metadata.repoUrl}:{},...d.score!==void 0?{score:d.score}:{},...d.signals!==void 0?{signals:d.signals}:{},...d.linkedTo!==void 0?{linkedTo:d.linkedTo}:{}})}return i}function ts(t){const e=new Map,n=r=>{let s=r;for(;e.get(s)!==s;)s=e.get(s);let a=r;for(;e.get(a)!==s;){const c=e.get(a);e.set(a,s),a=c}return s},i=r=>{e.has(r)||e.set(r,r)};for(const{a:r,b:s}of t){i(r),i(s);const a=n(r),c=n(s);a!==c&&e.set(a,c)}const o=new Map;for(const r of e.keys()){const s=n(r),a=o.get(s);a?a.push(r):o.set(s,[r])}return o}async function Yh(t,e){var y,w;const{graph:n}=t;if(!n)return;const i=e.filter;if(!i||i.project===void 0&&i.component===void 0)return;const o=new Date().toISOString(),r=e.limit??Ln,s=await Bn(n,i),a=new Set;let c=[];if(s&&s.size>0){c=await n.getNodesByIds([...s]);for(const v of c)a.add(v.uid)}let d;if(i.project!==void 0)d=(y=await x(n,"project",i.project))==null?void 0:y.uid;else if(i.component!==void 0){const v=await x(n,"component",i.component),b=(w=v==null?void 0:v.record.metadata)==null?void 0:w.projectUid;typeof b=="string"&&(d=b)}const l=d!==void 0?await zh(n,d):void 0,u=[];let f=0;if(t.search)for(const v of c.slice(0,r)){const b=await Uc(n,v.id),h=await Jh(t,{title:v.name??"",body:v.content??"",scope:"same-project",projectUid:d,sameProjectThreshold:(l==null?void 0:l.policy.dedupeThreshold)??.8,crossProjectThreshold:(l==null?void 0:l.policy.similarityCrossProjectThreshold)??.92,margin:(l==null?void 0:l.policy.similarityCrossProjectMargin)??.05,tokenOverlapMin:(l==null?void 0:l.policy.similarityCrossProjectTokenOverlap)??.5,citationTokens:b.citationTokens,componentPath:b.componentPath,limit:r,excludeIds:new Set([v.id])});f+=1;for(const S of h)u.push({a:v.uid,b:S.uid,score:S.score,...S.signals!==void 0?{signals:S.signals}:{}})}const m=[];if(u.length>0){const v=new Map,b=new Map,h=new Map;for(const E of u)v.set(E.a,Math.max(v.get(E.a)??0,E.score)),v.set(E.b,Math.max(v.get(E.b)??0,E.score)),E.signals!==void 0&&b.set(E.b,E.signals),h.set(E.b,E.a);const S=ts(u);for(const E of S.values()){if(E.length<2)continue;let N=E[0],k=-1;for(const A of E){const O=v.get(A)??0;O>k&&(k=O,N=A)}const R=await es(n,[N,...E.filter(A=>A!==N)],new Map(E.map(A=>[A,{score:v.get(A),signals:b.get(A),linkedTo:h.get(A)}])));m.push({seedUid:N,members:R,linked:!1})}}const p=[];for(const v of await n.getEdges({rel:"similar_to"})){const[b]=await n.getNodesByIds([v.src]),[h]=await n.getNodesByIds([v.dst]);!b||!h||a.size>0&&!a.has(b.uid)&&!a.has(h.uid)||p.push({a:b.uid,b:h.uid})}const g=[];if(p.length>0){const v=new Map;for(const h of p)v.set(h.a,h.b);const b=ts(p);for(const h of b.values()){if(h.length<2)continue;const S=await es(n,h,new Map(h.map(E=>[E,{linkedTo:v.get(E)}])));g.push({seedUid:h[0],members:S,linked:!0})}}return{candidate:m,linked:g,scanned:f,computedAt:o}}function Xh(t){return t.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function Qh(t){const e=typeof t.gitContext=="string"&&t.gitContext.length>0?t.gitContext:void 0,n=t.citations??[];if(e===void 0&&n.length===0)return[];const i=["",e!==void 0?`Citations: [${Xh(e)}]`:"Citations:"];for(const o of n){const r=o.lines?`${o.file}:${o.lines}`:o.file;i.push(`- [${r} sha:${o.sha}]`)}return i}function Zh(t){const e=[];return t.kind!==void 0&&e.push(`kind: ${t.kind}`),t.status!==void 0&&e.push(`status: ${t.status}`),t.priority!==void 0&&e.push(`priority: ${t.priority}`),t.assignee!==void 0&&e.push(`assignee: ${t.assignee}`),t.project!==void 0&&e.push(`project: ${t.project}`),t.component!==void 0&&e.push(`component: ${t.component}`),e.length>0?e.join(" · "):void 0}function ey(t){const e=[`## ${t.title??"(untitled)"}`],n=Zh(t);return n!==void 0&&e.push(n),t.body!==void 0&&t.body.length>0&&e.push("",t.body),e.push(...Qh(t)),e.join(`
|
|
205
|
+
`)}function ty(t){return t.length===0?`_No matching issues._
|
|
206
|
+
`:`${t.map(ey).join(`
|
|
203
207
|
|
|
204
208
|
`)}
|
|
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}
|
|
209
|
+
`}const Ti=["not_found","item_not_found","ambiguous_reference","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],ny=new Set(Ti);function Mc(t){return typeof t=="string"&&ny.has(t)}const Oi={not_found:4,item_not_found:1,ambiguous_reference:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function oy(t){return t.ok===!0}function iy(t){return t.ok===!1&&typeof t.error=="object"&&t.error!==null&&Mc(t.error.code)}function Ii(t,e){const n={ok:!0,data:t};return e!=null&&e.warnings&&e.warnings.length>0&&(n.warnings=e.warnings),e!=null&&e.meta&&(n.meta=e.meta),n}function ne(t,e,n){const i={code:t,message:e},o={...n??{}};return t==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(i.details=o),{ok:!1,error:i}}function je(t){return t.ok?0:Oi[t.error.code]}function xc(t){if(t===null||typeof t!="object")return!1;const e=t;if(typeof e.ok!="boolean")return!1;if(e.ok)return!0;const n=e.error;if(n===null||typeof n!="object")return!1;const i=n.code;return typeof i=="string"&&i in Oi}class Fc extends Error{constructor(e,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${e}" needs an embedded vector space and this store has none — a backend is configured, but zero items have been embedded, so nearest-neighbour ranking has nothing to rank. Run an embedding backfill to populate it. `:`backlog: "${e}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}const Bc=["get","query","priority-matrix","part-of-rollup","open-curve","report","lookup","create","update","add-citation","remove-citation","transition","attest","recheck","obligate","unobligate","spec-append","spec-check","claim","relate","move","upsert-project","upsert-component","upsert-location","rm-location","delete","embedding-status","merge-project","rm-project"],no=["kind","status","priority","relation","field","error_code","location_type","verb"],ry=[{catalog:"kind",rel:"has_kind"},{catalog:"status",rel:"has_status"},{catalog:"priority",rel:"has_priority"}],sy=new Set([...Ja].map(t=>F(t))),ay=new Map([...za].map(([t,e])=>[F(t),e]));function cy(t){const e=F(t);if(!sy.has(e))return{lifecycle:"active"};const n=ay.get(e);return{lifecycle:"deprecated",...n?{replacedBy:n}:{}}}function dy(t,e){const n=e.metadata??{},i=n.lifecycle==="deprecated"?"deprecated":"active",o=typeof n.replacedBy=="string"?n.replacedBy:void 0;return i==="deprecated"?{lifecycle:i,...o?{replacedBy:o}:{}}:t==="kind"?cy(e.name??""):{lifecycle:"active"}}async function ly(t,e){const n=await t.getEdges({rel:e}),i=new Map;for(const o of n)i.set(o.dst,(i.get(o.dst)??0)+1);return i}async function uy(t,e,n){const i=await t.queryNodes({kind:e,liveOnly:!0}),o=await ly(t,n);return i.map(r=>{const{lifecycle:s,replacedBy:a}=dy(e,r);return{name:r.name??"",uid:r.uid,catalog:e,source:"store",lifecycle:s,...a?{replacedBy:a}:{},usageCount:o.get(r.id)??0}})}function fy(t){const e=[];for(const n of xt)t.has(F(n))||e.push({name:n,catalog:"status",source:"reserved_terminal_status_names",lifecycle:"active"});return e}function ht(t,e,n){return n.map(i=>({name:i,catalog:t,source:e,lifecycle:"active"}))}function py(t){const e=new Map;for(const n of t){const i=e.get(n.catalog)??new Set,o=F(n.name);if(i.has(o))return!0;i.add(o),e.set(n.catalog,i)}return!1}async function Bo(t){const e=[],n=new Set;for(const{catalog:i,rel:o}of ry){const r=await uy(t,i,o);if(i==="status")for(const s of r)n.add(F(s.name));e.push(...r)}return e.push(...fy(n)),e.push(...ht("relation","edge_kind_table",Qa.map(i=>i.rel))),e.push(...ht("field","issue_field_union",[..._i,...Ai])),e.push(...ht("error_code","error_code_union",Ti)),e.push(...ht("location_type","valid_location_types",Co)),e.push(...ht("verb","mounted_verb_surface",Bc)),e.sort((i,o)=>{const r=no.indexOf(i.catalog)-no.indexOf(o.catalog);if(r!==0)return r;const s=i.name.localeCompare(o.name);return s!==0?s:(i.uid??"").localeCompare(o.uid??"")}),{catalogs:[...no],terms:e,hasCaseCollisions:py(e)}}async function my(t,e){return(await Bo(t)).terms.filter(i=>i.catalog===e)}function Ot(t){var e,n,i,o;return{uid:t.uid,name:t.name??"",path:typeof((e=t.metadata)==null?void 0:e.path)=="string"?t.metadata.path:void 0,repoUrl:typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?t.metadata.repoUrl:void 0,monorepo:typeof((i=t.metadata)==null?void 0:i.monorepo)=="boolean"?t.metadata.monorepo:void 0,description:typeof((o=t.metadata)==null?void 0:o.description)=="string"?t.metadata.description:void 0}}function Sn(t){var e,n,i;return{uid:t.uid,name:t.name??"",projectUid:typeof((e=t.metadata)==null?void 0:e.projectUid)=="string"?t.metadata.projectUid:"",path:typeof((n=t.metadata)==null?void 0:n.path)=="string"?t.metadata.path:void 0,description:typeof((i=t.metadata)==null?void 0:i.description)=="string"?t.metadata.description:void 0}}function Ko(t){var e,n,i;return{uid:t.uid,locType:typeof((e=t.metadata)==null?void 0:e.locType)=="string"?t.metadata.locType:"path",value:typeof((n=t.metadata)==null?void 0:n.value)=="string"?t.metadata.value:t.name??"",componentUid:typeof((i=t.metadata)==null?void 0:i.componentUid)=="string"?t.metadata.componentUid:""}}async function gy(t,e){if((e==null?void 0:e.project)!==void 0){const i=await x(t,"project",e.project);return i?[Ot(i.record)]:[]}return(await t.queryNodes({kind:"project",liveOnly:!0})).map(Ot)}async function hy(t,e){if((e==null?void 0:e.project)!==void 0){const i=await x(t,"project",e.project);return i?(await t.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:i.uid}}})).map(Sn):[]}return(await t.queryNodes({kind:"component",liveOnly:!0})).map(Sn)}async function yy(t,e){if((e==null?void 0:e.component)!==void 0){const i=e.project!==void 0?await(async()=>{const r=await x(t,"project",e.project);return r?Ve(t,r.uid,e.component):null})():await x(t,"component",e.component);return i?(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:i.uid}}})).map(Ko):[]}return(await t.queryNodes({kind:"location",liveOnly:!0})).map(Ko)}async function oo(t,e){var d,l,u,f,m,p,g,y,w;if(e.registry==="project"){const v=await x(t,"project",e.name);if(!v)throw new V("project",e.name);const b=await t.getEdges({src:v.id,rel:"owns_project"}),h=b.length>0?await t.getNodesByIds(b.map(k=>k.dst),{liveOnly:!0}):[],E=(await Promise.all(h.map(k=>t.getEdges({src:k.id,rel:"has_location"})))).flatMap(k=>k.map(R=>R.dst)),N=E.length>0?await t.getNodesByIds(E,{liveOnly:!0}):[];return{...Ot(v.record),components:h.map(k=>{var R;return{name:k.name??"",path:typeof((R=k.metadata)==null?void 0:R.path)=="string"?k.metadata.path:void 0}}),locations:N.map(k=>{var R,A;return{locType:typeof((R=k.metadata)==null?void 0:R.locType)=="string"?k.metadata.locType:"path",value:typeof((A=k.metadata)==null?void 0:A.value)=="string"?k.metadata.value:k.name??""}})}}if(e.registry==="component"){const v=(d=e.filter)==null?void 0:d.project,b=v!==void 0?await(async()=>{const R=await x(t,"project",v);if(!R)throw new V("project",v);return Ve(t,R.uid,e.name)})():await x(t,"component",e.name);if(!b)throw new V("component",e.name);const h=typeof((l=b.record.metadata)==null?void 0:l.projectUid)=="string"?b.record.metadata.projectUid:void 0,S=h?await t.getNodeByUid(h):null,E=S&&!S.tInvalid?S:null,N=await t.getEdges({src:b.id,rel:"has_location"}),k=N.length>0?await t.getNodesByIds(N.map(R=>R.dst),{liveOnly:!0}):[];return{...Sn(b.record),project:{name:(E==null?void 0:E.name)??"",path:typeof((u=E==null?void 0:E.metadata)==null?void 0:u.path)=="string"?E.metadata.path:void 0,repoUrl:typeof((f=E==null?void 0:E.metadata)==null?void 0:f.repoUrl)=="string"?E.metadata.repoUrl:void 0},locations:k.map(R=>{var A,O;return{locType:typeof((A=R.metadata)==null?void 0:A.locType)=="string"?R.metadata.locType:"path",value:typeof((O=R.metadata)==null?void 0:O.value)=="string"?R.metadata.value:R.name??""}})}}if(!pe(e.name)&&!Dt(e.name))throw new T("name","a location has no name — pass its uid");const n=await Un(t,e.name,{expectedKind:"location"}),i=typeof((m=n.metadata)==null?void 0:m.componentUid)=="string"?n.metadata.componentUid:void 0,o=i?await t.getNodeByUid(i):null,r=o&&!o.tInvalid?o:null,s=typeof((p=r==null?void 0:r.metadata)==null?void 0:p.projectUid)=="string"?r.metadata.projectUid:void 0,a=s?await t.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;return{...Ko(n),component:{name:(r==null?void 0:r.name)??"",path:typeof((g=r==null?void 0:r.metadata)==null?void 0:g.path)=="string"?r.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((y=c==null?void 0:c.metadata)==null?void 0:y.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((w=c==null?void 0:c.metadata)==null?void 0:w.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function wy(t){try{return new URL(t),!0}catch{return!1}}function vy(t){return wy(t)?"url":t.includes("/")||t.includes(".")||t.startsWith("~")?"path":"tool"}async function by(t,e){var f,m,p,g,y,w;const n=vy(e);let i=(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:e}},limit:1}))[0],o,r=!1;if(!i&&n==="path"){const v=await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:le+1});r=v.length>le;const h=(r?v.slice(0,le):v).find(S=>{var N;const E=typeof((N=S.metadata)==null?void 0:N.value)=="string"?S.metadata.value:"";return E.endsWith(e)||e.endsWith(E)});h&&(i=h,o="matched by path suffix/prefix fallback, not an exact value match")}if(!i)return{ok:!1,truncated:r};const s=typeof((f=i.metadata)==null?void 0:f.componentUid)=="string"?i.metadata.componentUid:void 0,a=s?await t.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new V("component",s??"(unresolved)");const d=typeof((m=c.metadata)==null?void 0:m.projectUid)=="string"?c.metadata.projectUid:void 0,l=d?await t.getNodeByUid(d):null,u=l&&!l.tInvalid?l:null;return u?{ok:!0,result:{project:{uid:u.uid,name:u.name??"",path:typeof((p=u.metadata)==null?void 0:p.path)=="string"?u.metadata.path:void 0,repoUrl:typeof((g=u.metadata)==null?void 0:g.repoUrl)=="string"?u.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((y=c.metadata)==null?void 0:y.path)=="string"?c.metadata.path:void 0},location:{uid:i.uid,locType:n,value:typeof((w=i.metadata)==null?void 0:w.value)=="string"?i.metadata.value:e},hint:o}}:{ok:!0,result:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:i.uid,locType:n,value:e},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}}async function Ey(t,e){var d;const n=typeof e=="string"?e:e.q,i=typeof e=="string"?void 0:e.kind,o=i===void 0||i==="issue",r=i===void 0||i==="location",s=i===void 0||i==="project",a=i===void 0||i==="component";if(pe(n)||Dt(n)){const l=await Un(t,n);return{project:{uid:"",name:""},redirect:{verb:"get",uid:l.uid}}}if(o){const l=n.toLowerCase().split(/\s+/).filter(f=>f.length>0),u=(await t.searchNodes(n,{filter:{kind:"issue",liveOnly:!0,isSuperseded:!1},limit:20})).filter(f=>l.some(m=>(f.name??"").toLowerCase().includes(m)));if(u.length===1)return{project:{uid:"",name:""},redirect:{verb:"get",uid:u[0].uid}};if(u.length>1)throw new mi(n,u.map(f=>({uid:f.uid,kind:f.kind,name:f.name??""})))}let c=!1;if(r){const l=await by(t,n);if(l.ok)return l.result;c=l.truncated}if(s){const u=(await t.queryNodes({kind:"project",name:n,liveOnly:!0,limit:1}))[0]??(await t.queryNodes({kind:"project",liveOnly:!0,metadata:{repoUrl:{eq:n}},limit:1}))[0];if(u)return{project:Ot(u),hint:"matched a project by name/repoUrl — no component or location was requested"}}if(a&&i==="component"){const l=await x(t,"component",n);if(l){const u=typeof((d=l.record.metadata)==null?void 0:d.projectUid)=="string"?l.record.metadata.projectUid:void 0,f=u?await t.getNodeByUid(u):null;return{project:f&&!f.tInvalid?Ot(f):{uid:"",name:""},component:Sn(l.record),hint:"matched a component by name/uid"}}}throw new V("location",c?`${n} (path suffix/prefix fallback scanned only the first ${le} live path locations; a match may exist beyond this cap)`:n)}function Kt(t){if(t===void 0)return Ln;if(!Number.isInteger(t)||t<=0||t>le)throw new _e("limit",`must be a positive integer ≤ ${le}, got ${t}`);return t}function Sy(t){var e,n;if(t.after!==void 0){if(t.sort!==void 0)throw new T("sort","sort is incompatible with keyset pagination (after) — request the first page unsorted, or page by offset if a non-insertion order is required");if(((e=t.filter)==null?void 0:e.grep)!==void 0||((n=t.filter)==null?void 0:n.semantic)!==void 0)throw new T("after","after (keyset) is incompatible with grep/semantic search — these route through the ranked search primitives, which have no rowid-ordered keyset contract; page a searched result set by sort + offset (rule 6) instead")}}async function ky(t,e){const n=new Set;for(const i of e.refs){const o=await x(t,e.expectedKind,i);if(!o)continue;const r=await t.getEdges({dst:o.id,rel:e.rel});for(const s of r)n.add(s.src)}return n}async function Kc(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function qt(t,e){if(!e)return;const n=[];let i;if(e.project!==void 0){const o=await x(t,"project",e.project);if(!o)return new Set;i=o.uid;const r=await t.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of r){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(e.component!==void 0){const o=i!==void 0?await Ve(t,i,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(r.map(s=>s.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await nt(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await Kc(t,e.status));else{const o=Array.isArray(e.status)?e.status:[e.status];n.push(await nt(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(e.priority!==void 0){const o=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await nt(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(e.author!==void 0&&n.push(await ky(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.similarTo!==void 0){const o=await x(t,"issue",e.similarTo);if(!o)return new Set;const r=await t.getEdges({dst:o.id,rel:"similar_to"});n.push(new Set(r.map(s=>s.src)))}if(e.hasSimilar===!0){const o=await t.getEdges({rel:"similar_to"});n.push(new Set(o.map(r=>r.dst)))}if(e.plan!==void 0){const o=await x(t,"issue",e.plan);if(!o)return new Set;const r=await t.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(r.map(s=>s.src)))}if(e.projectPath!==void 0){const o=await t.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:e.projectPath}}});if(o.length===0)return new Set;const r=new Set;for(const s of o){const a=await t.getEdges({src:s.id,rel:"owns_component"});for(const c of a)r.add(c.dst)}n.push(r)}return Bg(n)}function _y(t){if(!t)return;const e={};return t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until})),Object.keys(e).length>0?e:void 0}function Ay(t){if(t==="created")return"tCreated";if(t==="updated")return"tValid"}async function qc(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_priority"}))),i=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=i.length>0?await t.getNodesByIds(i):[],r=new Map(o.map(a=>{var c;return[a.id,typeof((c=a.metadata)==null?void 0:c.rank)=="number"?a.metadata.rank:Number.MAX_SAFE_INTEGER]})),s=new Map;return e.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;s.set(a.id,d!==void 0?r.get(d)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)}),s}async function Ny(t,e,n){const i=await qc(t,e),o=[...e].sort((r,s)=>i.get(r.id)-i.get(s.id));return n==="desc"?o.reverse():o}function It(t,e,n){return{total:n?t+1:t,total_relation:n?"gte":"eq",returned:t,limit:e,has_more:n}}async function Ry(t,e){var b,h,S,E,N,k,R,A,O,I,L,$;const{graph:n}=t;Sy(e),ji(e.fields);const i=Kt(e.limit),o=e.fields??Ft;if((e.sort==="relevance"||e.sort==="textMatch")&&((b=e.filter)==null?void 0:b.grep)===void 0&&((h=e.filter)==null?void 0:h.semantic)===void 0)throw new _e("sort",`"${e.sort}" requires filter.grep or filter.semantic`);const r=await qt(n,e.filter);if((r==null?void 0:r.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:i}};const s=_y(e.filter),a=(S=e.filter)==null?void 0:S.grep,c=(E=e.filter)==null?void 0:E.semantic,d={kind:"issue",isSuperseded:!1,...r?{ids:[...r]}:{},...s?{metadata:s}:{},...(k=(N=e.filter)==null?void 0:N.createdAt)!=null&&k.since?{tCreatedAfter:e.filter.createdAt.since}:{},...(A=(R=e.filter)==null?void 0:R.createdAt)!=null&&A.until?{tCreatedBefore:e.filter.createdAt.until}:{},...(I=(O=e.filter)==null?void 0:O.updatedAt)!=null&&I.since?{tUpdatedAfter:e.filter.updatedAt.since}:{},...($=(L=e.filter)==null?void 0:L.updatedAt)!=null&&$.until?{tUpdatedBefore:e.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let Y,H;const ge=e.offset??0,lt=ge+i;if(a!==void 0){const J=await n.searchNodes(a,{limit:lt,filter:d});H=new Set(J.map(he=>he.id))}if(c!==void 0){if(!t.search)throw new T("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const he={vec:await t.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Ji=await t.search.backend.searchRanked(he,lt);Y=H?Ji.filter(El=>H.has(El.id)):Ji}else H&&(Y=(await n.searchNodes(a,{limit:lt,filter:d})).map(he=>({id:he.id,score:he.score,fields:{}})));const Z=(Y??[]).map(J=>J.id).slice(ge,ge+i),ut=Z.length>0?await n.getNodesByIds(Z):[],ft=new Map(ut.map(J=>[J.id,J])),pt=Z.map(J=>ft.get(J)).filter(J=>J!==void 0),Vt=new Map((Y??[]).map(J=>{var he;return[(he=ft.get(J.id))==null?void 0:he.uid,J.score]}).filter(J=>J[0]!==void 0)),vl=c!==void 0?"rrf":"bm25",bl=new Map([...Vt.keys()].map(J=>[J,vl])),Vi=await Tt(n,pt,o,Vt,bl,{rung:2,onRung:t.onVerdictRung}),Gn=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Wn=Vi.length,Gi=Wn<Math.min(Gn-ge,i),Wi=ge+Wn<Gn;return{page:{items:Vi,hasMore:Wi},meta:{total:Gn,returned:Wn,limit:i,...e.offset!==void 0?{offset:e.offset}:{},...Gi?{truncated:!0}:{},has_more:Wi,total_relation:Gi?"gte":"eq"}}}const l=Ay(e.sort),u={...d,limit:i+1,...e.after!==void 0?{after:Number(e.after)}:{},...l&&e.after===void 0?{orderBy:l,orderDir:e.direction??"desc"}:{},...e.after===void 0&&e.offset!==void 0?{offset:e.offset}:{}};let f=await n.queryNodes(u);e.sort==="priority"&&e.after===void 0&&(f=await Ny(n,f,e.direction??"asc"));const m=f.length>i,p=m?f.slice(0,i):f,g=m?String(p[p.length-1].id):void 0,y=await Tt(n,p,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung}),w=await n.countNodes(d),v=e.after===void 0?e.offset:void 0;return{page:{items:y,nextCursor:g,hasMore:m},meta:{total:w,returned:y.length,limit:i,...v!==void 0?{offset:v}:{}}}}async function jy(t,e){var S;const{graph:n}=t,i=Kt(e.limit),o=e.fields??Ft,r=await Kc(n,"open"),s=await qt(n,e.filter),a=s?[...r].filter(E=>s.has(E)):[...r];if(a.length===0)return{items:[],meta:It(0,i,!1)};const c=await n.getNodesByIds(a),d=await n.getEdges({rel:"blocks"}),l=new Map;for(const E of d){const N=l.get(E.dst);N?N.push(E.src):l.set(E.dst,[E.src])}const u=[...new Set(d.map(E=>E.src))],f=new Set((u.length>0?await n.getNodesByIds(u):[]).map(E=>E.id)),m=await n.getEdges({rel:"has_status"}),p=new Map;for(const E of m)p.has(E.src)||p.set(E.src,E.dst);const g=[...new Set(p.values())],y=new Map((g.length>0?await n.getNodesByIds(g):[]).map(E=>[E.id,E])),w=[];for(const E of c){if(w.length>=i+1)break;if(typeof((S=E.metadata)==null?void 0:S.claimedBy)=="string")continue;const N=(l.get(E.id)??[]).filter(R=>f.has(R));if(N.length===0){w.push(E);continue}N.every(R=>{const A=p.get(R);return A!==void 0&&Ae(y.get(A))})&&w.push(E)}const v=w.length>i,b=v?w.slice(0,i):w,h=await Tt(n,b,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung});return{items:h,meta:It(h.length,i,v)}}async function Ty(t,e){const{graph:n}=t,i=Kt(e.limit),o=e.fields??Ft,r=e.staleAfterMin??30,s=new Date(Date.now()-r*6e4).toISOString(),a=await qt(n,e.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:i+1},d=await n.queryNodes(c),l=d.length>i,u=l?d.slice(0,i):d,f=await Tt(n,u,o,void 0,void 0,{rung:2,onRung:t.onVerdictRung});return{items:f,meta:It(f.length,i,l)}}const Oy=["blocks","relates_to","part_of"];function Iy(t){return Oy.includes(t)}async function $y(t,e){var u;const{graph:n}=t,i=Kt(e.limit??le),o=await qt(n,e.filter),r={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:i},s=await n.queryNodes(r),a=new Set(s.map(f=>f.id)),c=await Cy(n,s),d=s.map(f=>{var m;return{uid:f.uid,title:f.name??"",status:((m=c.get(f.id))==null?void 0:m.name)??""}}),l=[];for(const f of s){const m=await me(n,f.id);for(const p of m)if(Iy(p.rel)&&a.has(p.dst)){const g=(u=(await n.getNodesByIds([p.dst]))[0])==null?void 0:u.uid;g&&l.push({from:f.uid,to:g,rel:p.rel})}}return{nodes:d,edges:l}}async function Cy(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_status"}))),i=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=i.length>0?await t.getNodesByIds(i):[],r=new Map(o.map(a=>[a.id,a])),s=new Map;return e.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=r.get(d);u&&s.set(a.id,u)}}),s}async function Py(t,e){var h,S,E,N;const{graph:n}=t,i=Kt(e.limit??le),o=await qt(n,e.filter),r=((h=e.filter)==null?void 0:h.plan)!==void 0||((S=e.filter)==null?void 0:S.project)!==void 0||((E=e.filter)==null?void 0:E.component)!==void 0||((N=e.filter)==null?void 0:N.kind)!==void 0;if((o==null?void 0:o.size)===0)return{ok:!0,order:[]};const s={...r?{}:{kind:"issue"},isSuperseded:!1,...o?{ids:[...o]}:{},limit:i},a=await n.queryNodes(s),c=new Set(a.map(k=>k.id)),d=new Map(a.map(k=>[k.id,k.uid])),l=new Map,u=new Map;for(const k of a)l.set(k.id,0),u.set(k.id,[]);for(const k of a){const R=await n.getEdges({src:k.id,rel:"blocks"});for(const A of R)c.has(A.dst)&&(u.get(k.id).push(A.dst),l.set(A.dst,(l.get(A.dst)??0)+1))}const f=new Map;for(const k of a)f.set(k.id,await Cc(n,k.id,c));const m=await qc(n,a),p=(k,R)=>{const A=f.get(k)??0,O=f.get(R)??0;if(A!==O)return O-A;const I=m.get(k)??Number.MAX_SAFE_INTEGER,L=m.get(R)??Number.MAX_SAFE_INTEGER;if(I!==L)return I-L;const $=d.get(k),Y=d.get(R);return $<Y?-1:$>Y?1:0},g=[],y=k=>{g.push(k);let R=g.length-1;for(;R>0;){const A=R-1>>1;if(p(g[R],g[A])<0)[g[R],g[A]]=[g[A],g[R]],R=A;else break}},w=()=>{const k=g[0],R=g.pop();if(g.length>0){g[0]=R;let A=0;for(;;){const O=2*A+1,I=O+1;let L=A;if(O<g.length&&p(g[O],g[L])<0&&(L=O),I<g.length&&p(g[I],g[L])<0&&(L=I),L===A)break;[g[A],g[L]]=[g[L],g[A]],A=L}}return k};for(const k of a)(l.get(k.id)??0)===0&&y(k.id);const v=[],b=new Map(l);for(;g.length>0;){const k=w();v.push(k);for(const R of u.get(k)??[]){const A=(b.get(R)??0)-1;b.set(R,A),A===0&&y(R)}}return v.length!==a.length?{ok:!1,cycle:a.filter(R=>!v.includes(R.id)).map(R=>d.get(R.id))}:{ok:!0,order:v.map(k=>d.get(k))}}async function Ly(t,e){var s;const{graph:n}=t,i=e.overlapAxis,o=e.overlapUids;if(!i)throw new T("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new T("overlapUids","requires at least 2 uids to detect an overlap");const r=new Map;for(const a of o){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(i==="file"){const m=(await me(n,c.id)).filter(g=>g.rel==="has_citation"),p=m.length>0?await n.getNodesByIds(m.map(g=>g.dst)):[];for(const g of p){const y=typeof((s=g.metadata)==null?void 0:s.target)=="string"?g.metadata.target:void 0;y&&(r.has(y)||r.set(y,new Set),r.get(y).add(a))}continue}if(i==="author"){const m=(await me(n,c.id)).find(g=>g.rel==="authored_by");if(!m)continue;const[p]=await n.getNodesByIds([m.dst]);if(!p)continue;r.has(p.uid)||r.set(p.uid,new Set),r.get(p.uid).add(a);continue}const{project:d,component:l}=await Ge(n,c.id),u=i==="project"?d:l;u&&(r.has(u.uid)||r.set(u.uid,new Set),r.get(u.uid).add(a))}return[...r.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function Uy(t,e){return gy(t.graph,e.filter)}async function Dy(t,e){return hy(t.graph,e.filter)}async function My(t,e){return yy(t.graph,e.filter)}function xy(t){var e,n;return t.text!==void 0||((e=t.filter)==null?void 0:e.semantic)!==void 0||((n=t.filter)==null?void 0:n.anchor)!==void 0||t.view==="similar"||t.sort==="relevance"||(t.fields??[]).includes("_vector")}function Fy(t,e){var r,s;if(e.text===void 0)return e;if(((r=e.filter)==null?void 0:r.semantic)!==void 0||((s=e.filter)==null?void 0:s.grep)!==void 0)throw new T("text","text is mutually exclusive with filter.semantic/filter.grep — pick one: the free-text positional (text), or an explicit filter.semantic/filter.grep");if(e.text.trim().length===0)throw new T("text","must not be blank");const n=t.search!==void 0&&t.spacePopulated===!0,{text:i,...o}=e;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:i}:{grep:i}}}}async function By(t,e){var i,o,r,s;const n=e.view??"list";switch(n){case"list":{const{page:a,meta:c}=await Ry(t,e);return{result:{view:"list",...a},meta:c}}case"ready":{const{items:a,meta:c}=await jy(t,e);return{result:{view:"ready",items:a},meta:c}}case"graph":return{result:{view:"graph",graph:await $y(t,e)}};case"order":return{result:{view:"order",order:await Py(t,e)}};case"stale":{const{items:a,meta:c}=await Ty(t,e);return{result:{view:"stale",items:a},meta:c}}case"similar":{const a=((i=e.filter)==null?void 0:i.project)!==void 0||((o=e.filter)==null?void 0:o.component)!==void 0,c=((r=e.filter)==null?void 0:r.anchor)!==void 0||((s=e.filter)==null?void 0:s.semantic)!==void 0,d=a?await Yh(t,e):void 0;if(a&&!c){const m=e.limit??Ln;return{result:{view:"similar",items:[],...d?{clusters:d}:{}},meta:It(0,m,!1)}}const{items:l,hasMore:u,limit:f}=await xh(t,e);return{result:{view:"similar",items:l,...d?{clusters:d}:{}},meta:It(l.length,f,u)}}case"overlap":return{result:{view:"overlap",groups:await Ly(t,e)}};case"projects":return{result:{view:"projects",items:await Uy(t,e)}};case"components":return{result:{view:"components",items:await Dy(t,e)}};case"locations":return{result:{view:"locations",items:await My(t,e)}};case"kinds":return{result:{view:"kinds",catalogs:await Bo(t.graph)}};case"catalogs":return{result:{view:"catalogs",terms:e.catalog!==void 0?await my(t.graph,e.catalog):(await Bo(t.graph)).terms}};default:{const a=n;throw new _e("view",`unknown view "${a}"`)}}}const Ky=["list","ready","stale","similar"];async function qy(t,e={}){var a;await((a=t.assertVocabulary)==null?void 0:a.call(t));const n=Fy(t,e),i=await By(t,n);if(n.format!=="markdown")return i;const{result:o}=i,{view:r}=o;if(r!=="list"&&r!=="ready"&&r!=="stale"&&r!=="similar")throw new T("format",`"markdown" is only supported for view:${Ky.map(c=>`"${c}"`).join("/")} — view:"${r}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=o.items;return{result:{view:r,format:"markdown",markdown:ty(s)},meta:i.meta}}class Hy extends Error{constructor(e,n,i,o){super(`backlog embedding: ${e} produced a ${o}-dimensional vector but space "${n}" is ${i}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=e,this.modelId=n,this.expected=i,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let ns=!1,os=!1,is=!1;const kn=new WeakMap;async function Vy(t,e){const n=t;return typeof n.hasVectors!="function"?(ns||(ns=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${e}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(e)}async function rs(t){try{return{mod:await import(t)}}catch(e){return{err:e}}}const on=t=>t instanceof Error?t.message:String(t),Et=new WeakMap;async function Gy(t,e,n,i=r=>console.error(r),o){const r=Et.get(t);if(r)return r;const s=zy(t,e,n,i,o);Et.set(t,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?Et.delete(t):kn.set(t,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw Et.delete(t),kn.delete(t),a}}function Wy(t){const e=kn.get(t);if(e)return{present:!0,embedding:e.embedding,search:e.search}}function Jy(t){Et.delete(t),kn.delete(t)}function ss(t){return t&&t.length>0?t.join(", "):"(no config layer files found on disk)"}async function zy(t,e,n,i,o){var p;if(!(n!=null&&n.enabled))return(o==null?void 0:o.configuredEnabled)===!0?is||(is=!0,i(`backlog: embedding.enabled is TRUE in the on-disk config but this process is still running with it DISABLED (startup configHash ${o.startupHash??"unknown"}, on-disk configHash ${o.configuredHash??"unknown"}). The next semantic verb adopts it without a restart; if it does not, restart the process. Resolved config layers: ${ss(o.configPaths)}.`)):os||(os=!0,i(`backlog: embedding is DISABLED (the default) — semantic/RAG features are OFF for this process. Set embedding.enabled: true in a resolved config layer to opt in (adopted without a restart). Resolved config layers: ${ss(o==null?void 0:o.configPaths)}.`)),{};const r=(p=t.capabilities)==null?void 0:p.nativeVectors;if(r!==!0)return i(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(r)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,a]=await Promise.all([rs("@adhd/sox-vector-store"),rs("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const g=[..."err"in s?[`@adhd/sox-vector-store (${on(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${on(a.err)})`]:[]];return i(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${g.join("; ")}. Continuing WITHOUT semantic search.`),{}}let c;try{c=await a.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(g){return i(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${on(g)}. Continuing WITHOUT semantic search.`),{}}const d={modelId:c.metadata.modelId,dim:c.metadata.dimensions};let l;try{l=await s.mod.openTursoVectorStore(t,{dim:d.dim,modelId:d.modelId}),await l.ensureSpace(d)}catch(g){return i(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${on(g)}. Continuing WITHOUT semantic search.`),{}}const u=(g,y)=>{if(g.length!==d.dim)throw new Hy(y,d.modelId,d.dim,g.length);return g},f={modelId:d.modelId,async embedDocument(g){return u(await c.embedSingle(g,"document"),"embedDocument")},async upsertVector(g,y){await l.upsert(g,u(y,"upsertVector"),d)},async deleteVector(g){await l.delete(g,d.modelId)}};return{search:{backend:new Tl.StoreSearchBackend(l,e),async embedQuery(g){return u(await c.embedSingle(g,"query"),"embedQuery")},async spacePopulated(){return Vy(l,d.modelId)}},embedding:f}}const as=["status","priority","kind"],Yy="run the terminal-flag repair — `write/catalog-repair.ts`'s `planTerminalBackfill` + `applyTerminalBackfill` — which sets `metadata.terminal = true` on each named status row.",Xy="run the case-fragment repair — `write/catalog-merge.ts`'s `planCaseFragmentMerge` + `applyCaseFragmentMerge` — which collapses each folded group to one live row, re-points its edges, and records the merged-away spelling as an alias.";function Qy(t){const e=t.filter(o=>o.kind==="unflagged-terminal"),n=t.filter(o=>o.kind==="case-fragment-duplicate"),i=["backlog: status/priority/kind catalog invariant violated (ADR-0002: correct the source, never work around it)."];if(i.push(" This is a NAMED check: it reports the rows below and the repair. It never gates reads or unrelated writes — a drifted catalog is a bounded data problem, never an availability outage — and neither condition may be papered over with a read-time fallback."),e.length>0){i.push(` unflagged-terminal (${e.length}): a live status row whose name is a reserved terminal name but whose metadata.terminal is not true reads as NON-terminal, so closed items are returned under an open filter.`);for(const o of e)i.push(` - status "${o.name}" (uid ${o.uid})`);i.push(` remediation: ${Yy}`)}if(n.length>0){i.push(` case-fragment-duplicate (${n.length}): two or more live rows of the SAME catalog kind share a case-folded name, so a name-keyed reader splits one value across two rows.`);for(const o of n){const r=o.names.map((s,a)=>`"${s}" (uid ${o.uids[a]})`).join(", ");i.push(` - fold "${o.fold}": ${r}`)}i.push(` remediation: ${Xy}`)}return i.join(`
|
|
210
|
+
`)}class Hc extends Error{constructor(e){super(Qy(e)),this.violations=e,this.name="CatalogInvariantError"}}const Zy=new Set([...xt].map(t=>F(t)));function ew(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function tw(t){var i;const{rows:e}=await t.executeAll("SELECT rowid, uid, kind, name, meta FROM node WHERE kind IN (?, ?, ?) AND t_invalid IS NULL ORDER BY kind ASC, rowid ASC",[...as]),n=[];for(const o of e){if(o.kind!=="status")continue;const r=F(o.name??"");Zy.has(r)&&((i=ew(o.meta))==null?void 0:i.terminal)!==!0&&n.push({kind:"unflagged-terminal",name:o.name??"",uid:o.uid})}for(const o of as){const r=new Map;for(const s of e){if(s.kind!==o)continue;const a=F(s.name??""),c=r.get(a);c?c.push(s):r.set(a,[s])}for(const[s,a]of r)a.length<2||n.push({kind:"case-fragment-duplicate",fold:s,names:a.map(c=>c.name??""),uids:a.map(c=>c.uid)})}return n}async function Vc(t){const e=await tw(t);if(e.length!==0)throw new Hc(e)}async function nw(t,e){if(ji(e.fields),e.lastN!==void 0&&(!Number.isInteger(e.lastN)||e.lastN<=0))throw new _e("lastN",`must be a positive integer, got ${e.lastN}`);const n=e.fields??Ft,i=await Dn(t,e.uid),o=e.lastN!==void 0||e.after!==void 0?{lastN:e.lastN,after:e.after}:void 0;return Lc(t,i,n,{bounds:o,verdictRung:e.deriveThrough??3})}function ow(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):[]}const iw=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function Gc(t,e,n){if(t){for(const i of iw)if(t[i]!==void 0&&!e.has(i))throw new T(`filter.${i}`,`not supported by ${n} — this view scopes by ${[...e].join("/")} only`)}}async function Wc(t,e){const n=new Set;for(const i of e.refs){const o=await x(t,e.expectedKind,i);if(!o)continue;const r=await t.getEdges({dst:o.id,rel:e.rel});for(const s of r)n.add(s.src)}return n}async function rw(t,e){const i=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(r=>Ae(r)===(e==="closed")),o=new Set;for(const r of i){const s=await t.getEdges({dst:r.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}function Jc(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const i=new Set;for(const o of e)n.has(o)&&i.add(o);e=i}return e}async function zc(t,e){if(!e)return;const n=[];let i;if(e.project!==void 0){const o=await x(t,"project",e.project);if(!o)return new Set;i=o.uid;const r=await t.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of r){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(e.component!==void 0){const o=i!==void 0?await Ve(t,i,e.component):await x(t,"component",e.component);if(!o)return new Set;const r=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(r.map(s=>s.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Wc(t,{rel:"has_kind",expectedKind:"kind",refs:o}))}return Jc(n)}const sw=new Set(["project","component","kind","status"]);async function aw(t,e){const n=e??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await rw(t,n),scope:n};const i=Array.isArray(n)?n:[n];return{candidates:await Wc(t,{rel:"has_status",expectedKind:"status",refs:i}),scope:n}}async function Yc(t,e){const n=await zc(t,e),{candidates:i,scope:o}=await aw(t,e==null?void 0:e.status),r=Jc([n,i].filter(a=>a!==void 0));return(n==null?void 0:n.size)===0||(i==null?void 0:i.size)===0||(r==null?void 0:r.size)===0?{nodes:[],statusScope:o}:{nodes:await t.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...r?{ids:[...r]}:{}}),statusScope:o}}async function Xc(t,e={}){var l;const{graph:n}=t;Gc(e.filter,sw,"priorityMatrix");const{nodes:i,statusScope:o}=await Yc(n,e.filter);if(i.length===0)return{rows:[],unassigned:0,statusScope:o};const r=new Set(i.map(u=>u.id)),s=await n.queryNodes({kind:"priority",liveOnly:!0}),a=new Set,c=[];for(const u of s){const f=await n.getEdges({dst:u.id,rel:"has_priority"});let m=0;for(const g of f)r.has(g.src)&&(m+=1,a.add(g.src));const p=typeof((l=u.metadata)==null?void 0:l.rank)=="number"?u.metadata.rank:void 0;c.push({priority:u.name??"",priorityUid:u.uid,rank:p,count:m})}c.sort((u,f)=>(u.rank??Number.MAX_SAFE_INTEGER)-(f.rank??Number.MAX_SAFE_INTEGER));let d=0;for(const u of r)a.has(u)||(d+=1);return{rows:c,unassigned:d,statusScope:o}}const cw=50,cs=1e3;async function dw(t,e){if(e.length===0)return new Map;const n=await Promise.all(e.map(c=>t.getEdges({src:c.id,rel:"has_status"}))),i=new Map;n.forEach((c,d)=>{const l=c[0];l&&i.set(e[d].id,l.dst)});const o=[...new Set(i.values())];if(o.length===0)return new Map;const r=await t.getNodesByIds(o),s=new Map(r.map(c=>[c.id,c])),a=new Map;for(const[c,d]of i){const l=s.get(d);l&&a.set(c,l)}return a}async function lw(t,e){const{graph:n}=t,i=await Dn(n,e.uid);if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<=0||e.limit>cs))throw new _e("limit",`must be a positive integer ≤ ${cs}, got ${e.limit}`);const o=e.limit??cw,s=(await n.getSubgraph(i.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(g=>g.id!==i.id&&g.kind==="issue"&&!g.tInvalid),a=await dw(n,s);let c=0,d=0;const l=[];for(const g of s)Ae(a.get(g.id))?d+=1:(c+=1,l.push(g.uid));const u={uid:i.uid,childrenTotal:s.length,childrenOpen:c,childrenClosed:d};if(e.countOnly)return u;let f=l;if(e.after!==void 0){const g=f.findIndex(y=>y===e.after);g>=0&&(f=f.slice(g+1))}const m=f.slice(0,o),p=f.length>o;return{...u,childrenOpenUids:m,hasMore:p,...p&&m.length>0?{nextCursor:m[m.length-1]}:{}}}const uw=new Set(["project","component","kind"]);function fw(t,e,n){var r;const i=t.filter(s=>s.to!==void 0);if(i.length===0)return n;let o;for(const s of i)if(s.at<=e)o=s;else break;return o?o.to:(r=i[0])==null?void 0:r.from}async function pw(t){var u;const e=await t.getEdges({rel:"has_status"}),n=new Map;for(const f of e)n.has(f.src)||n.set(f.src,f.dst);const i=[...new Set(n.values())],o=new Map((i.length>0?await t.getNodesByIds(i):[]).map(f=>[f.id,f])),r=new Map;for(const[f,m]of n)r.set(f,(u=o.get(m))==null?void 0:u.name);const s=await t.getEdges({rel:"audits"}),a=new Map;for(const f of s){const m=a.get(f.src);m?m.push(f.dst):a.set(f.src,[f.dst])}const c=[...new Set(s.map(f=>f.dst))],d=new Map((c.length>0?await t.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,m]of a){const p=m.map(g=>d.get(g)).filter(g=>g!==void 0).map(g=>{var y,w,v,b,h,S,E;return{uid:g.uid,actor:typeof((y=g.metadata)==null?void 0:y.actor)=="string"?g.metadata.actor:"",action:typeof((w=g.metadata)==null?void 0:w.action)=="string"?g.metadata.action:g.name??"",from:typeof((v=g.metadata)==null?void 0:v.from)=="string"?g.metadata.from:void 0,to:typeof((b=g.metadata)==null?void 0:b.to)=="string"?g.metadata.to:void 0,note:typeof((h=g.metadata)==null?void 0:h.note)=="string"?g.metadata.note:void 0,sha:typeof((S=g.metadata)==null?void 0:S.sha)=="string"?g.metadata.sha:"",at:typeof((E=g.metadata)==null?void 0:E.at)=="string"?g.metadata.at:g.tCreated}}).sort((g,y)=>g.at.localeCompare(y.at));l.set(f,p)}return{currentStatusNameByIssue:r,auditTrailByIssue:l}}async function mw(t,e){var u;const{graph:n}=t;if(Gc(e.filter,uw,"openCurve"),e.at.length===0)throw new T("at","requires at least one ISO-8601 instant to sample");const i=e.at.map(f=>{const m=new Date(f);if(Number.isNaN(m.getTime()))throw new T("at",`"${f}" is not a parsable ISO-8601 instant`);return m.toISOString()}),o=await zc(n,e.filter);if((o==null?void 0:o.size)===0)return{points:i.map(f=>({at:f,existed:0,open:0,closed:0}))};const r=await n.queryNodes({kind:"status",liveOnly:!0}),s=new Map;for(const f of r){const m=Ae(f);f.name&&s.set(f.name,m);for(const p of ow((u=f.metadata)==null?void 0:u.aliases))s.set(p,m)}const{currentStatusNameByIssue:a,auditTrailByIssue:c}=await pw(n),d=new Map;for(const f of await n.getEdges({rel:"SUPERSEDES"})){const m=d.get(f.dst);(m===void 0||f.tCreated<m)&&d.set(f.dst,f.tCreated)}const l=[];for(const f of i){const m={kind:"issue",validAt:f,liveOnly:!1,...o?{ids:[...o]}:{}},p=await n.queryNodes(m);let g=0,y=0;for(const w of p){const v=d.get(w.id);if(v!==void 0&&v<=f)continue;y+=1;const b=a.get(w.id),h=c.get(w.id)??[],S=fw(h,f,b);(S!==void 0?s.get(S)??!1:!1)||(g+=1)}l.push({at:f,existed:y,open:g,closed:y-g})}return{points:l}}async function gw(t,e){const n=new Map;if(e.length===0)return n;const i=new Set(e.map(a=>a.id)),o=new Map;for(const a of await t.getEdges({rel:"has_kind"}))i.has(a.src)&&!o.has(a.src)&&o.set(a.src,a.dst);const r=[...new Set(o.values())],s=new Map((r.length>0?await t.getNodesByIds(r):[]).map(a=>[a.id,a.name??""]));for(const[a,c]of o){const d=s.get(c);d!==void 0&&n.set(a,d)}return n}async function hw(t,e){const n=new Map;if(e.length===0)return n;const i=new Set(e.map(a=>a.id)),o=new Map;for(const a of await t.getEdges({rel:"has_status"}))i.has(a.src)&&!o.has(a.src)&&o.set(a.src,a.dst);const r=[...new Set(o.values())],s=new Map((r.length>0?await t.getNodesByIds(r):[]).map(a=>[a.id,{name:a.name??"",terminal:Ae(a)}]));for(const[a,c]of o){const d=s.get(c);d&&n.set(a,d)}return n}async function yw(t,e){const{graph:n}=t,i=new Date().toISOString(),{nodes:o,statusScope:r}=await Yc(n,e.filter),a=(await Xc(t,{filter:e.filter})).rows.map(v=>({priority:v.priority,...v.rank!==void 0?{rank:v.rank}:{},count:v.count})),c=await gw(n,o),d=await hw(n,o),l=new Map,u=new Map,f=Date.parse(i);let m=0,p=0;for(const v of o){const b=c.get(v.id)??v.kind;l.set(b,(l.get(b)??0)+1);const h=d.get(v.id),S=(h==null?void 0:h.name)??"",E=(h==null?void 0:h.terminal)??!1,N=u.get(S)??{terminal:E,count:0};if(N.count+=1,u.set(S,N),!E){m+=1;const k=Date.parse(v.tCreated);Number.isNaN(k)||(p+=f-k)}}const g=[...l.entries()].map(([v,b])=>({kind:v,count:b})).sort((v,b)=>v.kind.localeCompare(b.kind)),y=[...u.entries()].map(([v,b])=>({status:v,terminal:b.terminal,count:b.count})).sort((v,b)=>v.status.localeCompare(b.status)),w=m>0?p/m/864e5:0;return{byKind:g,byPriority:a,byStatus:y,avgAgeDays:w,statusScope:r,computedAt:i}}function _t(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function ww(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`citation: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`citation: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`citation: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}const vw=/^[A-Za-z0-9][A-Za-z0-9._/@{}~^-]*$/;function bw(t){return t.length>0&&t.length<=256&&vw.test(t)&&!t.includes("..")}function Ew(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e),o=_.relative(n,i);if(!(o===""||o===".."||o.startsWith(`..${_.sep}`)||_.isAbsolute(o)))return o.split(_.sep).join("/")}function Sw(t,e,n){if(bw(e))try{const i=Hs.execFileSync("git",["-C",t,"show",`${e}:${n}`],{stdio:["ignore","pipe","pipe"],maxBuffer:67108864});return He(i)}catch{return}}async function kw(t,e,n,i,o=[]){if(!Za(t))return"unverified";if(n!==void 0){const r=Ew(t.metadata.path,e);return r===void 0?"unverified":Sw(t.metadata.path,n,r)??"unverified"}try{const{accepted:r,candidate:s}=await _p(t.metadata.path,e,[...i,...Ia(),...o]);if(!r)return"unverified";const a=await zo.readFile(s);return He(a)}catch(r){if(Oa(r))return"unverified";throw jp(r,e)}}async function Qc(t,e,n,i=[]){const o=[];for(const r of e)o.push(await kw(t,r.file,r.revision,n,i));return o}function Zc(t,e,n,i,o){for(let r=0;r<n.length;r+=1)if(i[r]==="unverified"&&e.citationRequiresSha){if(Za(t))throw new Ua(n[r].file,e.citationAllowedExternalRoots);console.error(`${o}: citation_requires_sha waived for path-less project uid="${t.uid}" — cannot verify citation "${n[r].file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}}async function $i(t,e,n,i,o){const r=await Qc(t,n,e.citationAllowedExternalRoots,i);return Zc(t,e,n,r,o),r}async function Kn(t,e,n){const i=await X(t,{at:n.at,kind:"citation",name:n.citation.file,content:n.citation.context??n.citation.file,metadata:Pg(n.citation,n.sha,n.at)}),o=await q(t,"has_citation");return await K(t,{at:n.at,srcRowid:n.issueRowid,srcUid:n.issueUid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"citation",rel:"has_citation",rule:o,typePolicy:e.typePolicy}),i}async function _w(t,e){const{rows:n}=await t.executeAll("SELECT dst FROM edge WHERE src = ? AND rel = 'has_citation' AND t_invalid IS NULL",[e]),i=[];for(const o of n){const r=await Q(t,o.dst);r&&r.tInvalid===null&&i.push({rowid:r.rowid,uid:r.uid,key:Ug(r.metadata)})}return i}async function ed(t,e){const n=await Q(t,e.citationRowid);if(!n)throw new Error(`removeCitation: citation rowid=${e.citationRowid} vanished mid-transaction.`);const i={...n.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:e.at},o=await t.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[e.at,JSON.stringify(i),n.rowid]);if(o.rowsAffected!==1)throw new Error(`removeCitation: invalidate UPDATE affected ${o.rowsAffected} rows for uid="${e.citationUid}", expected exactly 1.`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_citation' AND t_invalid IS NULL",[n.rowid]);r&&await ie(t,{srcRowid:r.src,dstRowid:n.rowid,rel:"has_citation",reason:e.reason,at:e.at})}async function Aw(t,e){try{const n=await se(t,e,{expectedKind:"citation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new Ba(e):n}}async function Nw(t,e){var a;_t("uid",e.uid),_t("by",e.by),G("by",e.by),_t("citation.file",(a=e.citation)==null?void 0:a.file);const n=await ae(t.adapter,e.uid),i=await ww(t.adapter,n.rowid),o=Se(i),r=await Lt(t.adapter,i.uid),s=await $i(i,o,[e.citation],r,"addCitation");return M(t,async c=>{const d=P(),l=await ae(c,e.uid),u=await Kn(c,t,{issueRowid:l.rowid,issueUid:l.uid,citation:e.citation,sha:s[0],at:d});return await U({tx:c,typePolicy:t.typePolicy,subjectRowid:l.rowid,subjectUid:l.uid,subjectKind:"issue",actor:e.by,action:"citation-added",to:u.uid,note:e.citation.file,at:d}),{uid:u.uid,issueUid:l.uid,citation:{uid:u.uid,file:e.citation.file,lines:e.citation.lines,context:e.citation.context,symbol:e.citation.symbol,blastRadius:e.citation.blastRadius,revision:e.citation.revision,sha:s[0],at:d,targetType:"path"}}})}async function Rw(t,e){return _t("uid",e.uid),_t("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await Aw(n,e.uid),r=await n.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = 'has_citation' AND t_invalid IS NULL",[o.rowid]);let s=o.rowid,a=o.uid,c="citation";if(r){const d=await Q(n,r.src);(d==null?void 0:d.kind)==="issue"&&d.tInvalid===null&&(s=d.rowid,a=d.uid,c="issue")}return await ed(n,{citationRowid:o.rowid,citationUid:o.uid,at:i,reason:e.reason}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:s,subjectUid:a,subjectKind:c,actor:e.by,action:"citation-removed",from:o.uid,note:e.reason,at:i}),{uid:o.uid,invalidated:!0}})}const ds=["abort","force","comment"];function yt(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}const ls=512;function td(t){if(typeof t=="string"&&t.length>ls)throw new T("gitContext",`must be at most ${ls} characters, got ${t.length}`)}function us(t,e,n){if(t.length>0&&!t.includes(n))throw new T(e,`"${n}" is not in this project's allowed ${e} set`)}function jw(t,e){for(const n of t){const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Tw(t,e){var r;const n=await Dn(t,e),i=new Set([n.id]);let o=n;for(;;){const a=(r=(await t.getEdges({src:o.id,rel:"part_of"}))[0])==null?void 0:r.dst;if(a===void 0||i.has(a))break;const[c]=await t.getNodesByIds([a]);if(!c||c.tInvalid!==void 0)break;i.add(c.id),o=c}return i}async function Ow(t,e,n,i){var s,a;const o=[];for(const c of n)o.push(c.file),typeof c.symbol=="string"&&o.push(c.symbol),typeof c.blastRadius=="string"&&o.push(c.blastRadius);let r;if(i!==void 0){const c=await Ve(t,e.uid,i);r=(s=c==null?void 0:c.record.metadata)==null?void 0:s.path}else{const c=await t.getEdges({src:e.rowid,rel:"owns_project"}),l=(await t.getNodesByIds(c.map(u=>u.dst))).find(u=>u.tInvalid===void 0&&u.name==="(root)");r=(a=l==null?void 0:l.metadata)==null?void 0:a.path}return{citationTokens:o,...typeof r=="string"?{componentPath:r}:{}}}async function Iw(t,e,n,i,o,r,s,a){const c=a!==void 0&&t.graph!==void 0?await Tw(t.graph,a):void 0;if(!n.dedupeScanEnabled)return{candidates:[],similarCandidates:[],degraded:!1};const d=t.graph!==void 0?await Ow(t.graph,e,r,s):void 0,l=await Dc(t,{title:i,body:o,scope:n.similarityScope,projectUid:e.uid,sameProjectThreshold:n.dedupeThreshold,crossProjectThreshold:n.similarityCrossProjectThreshold,margin:n.similarityCrossProjectMargin,tokenOverlapMin:n.similarityCrossProjectTokenOverlap,citationTokens:d==null?void 0:d.citationTokens,componentPath:d==null?void 0:d.componentPath,excludeIds:c}),u=l.candidates.filter(m=>m.scope==="same-project").map(m=>({uid:m.uid,title:m.title,score:m.score})),f=l.candidates.filter(m=>m.scope==="cross-project");return{candidates:u,similarCandidates:f,degraded:l.degraded,...l.degradedReason!==void 0?{degradedReason:l.degradedReason}:{}}}async function $w(t,e){var g;yt("title",e.title),yt("body",e.body),yt("project",e.project),yt("by",e.by),G("by",e.by),td(e.gitContext);const n=e.citations??[];n.forEach((y,w)=>yt(`citations[${w}].file`,y.file));const i=typeof e.gitContext=="string"&&e.gitContext.trim().length>0?e.gitContext:void 0,o=e.duplicateAction??"abort";if(e.duplicateAction!==void 0&&!ds.includes(e.duplicateAction))throw new T("duplicateAction",`must be one of ${ds.map(y=>`'${y}'`).join("|")}, got "${e.duplicateAction}"`);const r=await at(t.adapter,e.project),s=Se(r),a=await Lt(t.adapter,r.uid),c=await $i(r,s,n,a,"createIssue"),d=await Iw(t,r,s,e.title,e.body,n,e.component,e.dedupeExcludeUid),{candidates:l}=d,u=d.similarCandidates??[];if(o==="comment"){const y=l[0],w=u[0];if(w&&(!y||w.score>y.score))throw new T("duplicateAction",`"comment" cannot target a cross-project candidate (top cross-project match uid="${w.uid}", project "${((g=w.provenance)==null?void 0:g.projectUid)??"?"}") — a reviewed similar_to link is written with relate; comment may only attach to a same-project duplicate`)}if(d.degraded&&d.degradedReason==="no-embed-query"&&o==="abort")return{created:!1,reason:"duplicate-scan-degraded",duplicateScanDegraded:!0,...d.degradedReason!==void 0?{duplicateScanDegradedReason:d.degradedReason}:{}};if(l.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:l,...u.length>0?{similarCandidates:u}:{}};const f=d.degraded?{duplicateScanDegraded:!0,...d.degradedReason!==void 0?{duplicateScanDegradedReason:d.degradedReason}:{}}:{};let m;const p=await M(t,async y=>{const w=P();if(l.length>0&&o==="comment"){const[Z]=l,ut=await ae(y,Z.uid),ft=`${e.title}
|
|
206
211
|
|
|
207
|
-
${
|
|
212
|
+
${e.body}`,pt=await X(y,{kind:"note",content:ft,metadata:{author:e.by,text:ft,at:w},at:w}),Vt=await q(y,"has_note");return await K(y,{at:w,srcRowid:ut.rowid,srcUid:ut.uid,srcKind:"issue",dstRowid:pt.rowid,dstUid:pt.uid,dstKind:"note",rel:"has_note",rule:Vt,typePolicy:t.typePolicy}),{created:!1,commentedOn:{uid:ut.uid,noteId:pt.uid},duplicateCandidates:l,...u.length>0?{similarCandidates:u}:{},...f}}const v=await at(y,e.project),b=Se(v),h=e.component!==void 0?await Ei(y,{projectUid:v.uid,ref:e.component}):await Wa(y,{projectRowid:v.rowid}),S=e.component!==void 0?"explicit":"default-root",E=e.kind??b.defaultKind??"issue",N=await xe(y,{catalogKind:"kind",ref:E,at:w});us(b.allowedKinds,"kind",N.name);const k=e.status??b.defaultStatus??"open",R=await Ya(y,{ref:k,at:w});us(b.allowedStatuses,"status",R.name);let A;e.priority!==void 0&&(A=await xe(y,{catalogKind:"priority",ref:e.priority,at:w,mintMetadata:async Z=>({rank:await Xa(Z)})}));const O=e.author??e.by,I=await xe(y,{catalogKind:"agent",ref:O,at:w});jw(b.requiredFields,{...e,component:h.name,kind:N.name,status:R.name,priority:A==null?void 0:A.name});const L={revision:0};e.assignee!==void 0&&(L.assignee=e.assignee),i!==void 0&&(L.gitContext=i);const $=await X(y,{kind:"issue",name:e.title,content:e.body,metadata:L,at:w});m={rowid:$.rowid,uid:$.uid};const Y=await q(y,"owns_component");await K(y,{at:w,srcRowid:h.rowid,srcUid:h.uid,srcKind:"component",dstRowid:$.rowid,dstUid:$.uid,dstKind:"issue",rel:"owns_component",rule:Y,typePolicy:t.typePolicy});const H=await q(y,"has_kind");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:N.rowid,dstUid:N.uid,dstKind:"kind",rel:"has_kind",rule:H,typePolicy:t.typePolicy});const ge=await q(y,"has_status");if(await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:R.rowid,dstUid:R.uid,dstKind:"status",rel:"has_status",rule:ge,typePolicy:t.typePolicy}),A){const Z=await q(y,"has_priority");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:A.rowid,dstUid:A.uid,dstKind:"priority",rel:"has_priority",rule:Z,typePolicy:t.typePolicy})}const lt=await q(y,"authored_by");await K(y,{at:w,srcRowid:$.rowid,srcUid:$.uid,srcKind:"issue",dstRowid:I.rowid,dstUid:I.uid,dstKind:"agent",rel:"authored_by",rule:lt,typePolicy:t.typePolicy});for(let Z=0;Z<n.length;Z+=1)await Kn(y,t,{issueRowid:$.rowid,issueUid:$.uid,citation:n[Z],sha:c[Z],at:w});return await U({tx:y,typePolicy:t.typePolicy,subjectRowid:$.rowid,subjectUid:$.uid,subjectKind:"issue",actor:e.by,action:"created",at:w}),{created:!0,uid:$.uid,item:{uid:$.uid,title:e.title,kind:N.name,status:R.name,priority:A==null?void 0:A.name,project:v.uid,component:h.uid,createdAt:w,assignee:e.assignee,author:I.name,...i!==void 0?{gitContext:i}:{}},...l.length>0?{duplicateCandidates:l}:{},...u.length>0?{similarCandidates:u}:{},...f,placementResolved:S}});if(m){const y=hn(t,{action:"upsert",subjectRowid:m.rowid,subjectUid:m.uid,actor:e.by,content:Si(e.title,e.body)});e.awaitEmbed?await y:y.catch(()=>{})}return p}function wt(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}async function fs(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Cw(t,e){if(t.length>0&&!t.includes(e))throw new T("kind",`"${e}" is not in this project's allowed kind set`)}function Pw(t,e){for(const n of t){if(!(n in e))continue;const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function ps(t,e,n,i){const o=[],r=[];n.name!==void 0&&(o.push("name = ?"),r.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),r.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),r.push(i);const s=await t.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...r,e]);if(s.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${s.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function rn(t,e,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let r=n.override;if(!r&&o){const a=await Q(t,o.dst);(a==null?void 0:a.tInvalid)===null&&(r={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!r){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await ie(t,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await q(t,n.rel);await K(t,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:r.rowid,dstUid:r.uid,dstKind:r.kind,rel:n.rel,rule:s,typePolicy:e.typePolicy})}async function Lw(t,e,n){if(n.oldIssueRowid===n.newIssueRowid)return;const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!i)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await Q(t,i.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${i.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await ie(t,{srcRowid:i.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const r=await q(t,"owns_component");await K(t,{at:n.at,srcRowid:i.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:r,typePolicy:e.typePolicy})}const ms=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Uw(t,e){if(e.oldIssueRowid===e.newIssueRowid)return;const n=ms.map(()=>"?").join(", ");for(const i of["outgoing","incoming"]){const o=i==="outgoing"?"src":"dst",r=i==="outgoing"?"dst":"src",{rows:s}=await t.executeAll(`SELECT ${r} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[e.oldIssueRowid,...ms]);for(const a of s){const c=i==="outgoing"?e.oldIssueRowid:a.other,d=i==="outgoing"?a.other:e.oldIssueRowid,l=i==="outgoing"?e.newIssueRowid:a.other,u=i==="outgoing"?a.other:e.newIssueRowid;await ie(t,{srcRowid:c,dstRowid:d,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:e.at}),await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
|
|
208
213
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
209
214
|
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
210
215
|
weight = excluded.weight, confidence = excluded.confidence,
|
|
211
216
|
origin = excluded.origin, meta = excluded.meta,
|
|
212
|
-
t_invalid = NULL, t_valid = excluded.t_valid`,[l,u,a.rel,a.weight,a.confidence,a.origin,a.meta,
|
|
217
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[l,u,a.rel,a.weight,a.confidence,a.origin,a.meta,e.at,e.at])}}}function Dw(t){const e=[];return t.title!==void 0&&e.push("title"),t.body!==void 0&&e.push("body"),t.kind!==void 0&&e.push("kind"),t.priority!==void 0&&e.push("priority"),t.assignee!==void 0&&e.push("assignee"),t.author!==void 0&&e.push("author"),t.citations!==void 0&&e.push("citations"),e}function Mw(t,e){const n=["title","body","kind","priority","assignee","author","citations"];for(const i of n)if(t[i]!==void 0&&!e.includes(i))throw new Error(`update: patch key "${i}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function xw(t,e){if(wt("uid",e.uid),wt("by",e.by),G("by",e.by),e.status!==void 0)throw new _e("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");e.title!==void 0&&wt("title",e.title),e.body!==void 0&&wt("body",e.body);const i=Dw(e);if(i.length===0)throw new T("patch","update requires at least one of title/body/kind/priority/assignee/author/citations");Mw(e,i),e.citations!==void 0&&e.citations.forEach((a,c)=>wt(`citations[${c}].file`,a.file));let o=[];if(e.citations!==void 0&&e.citations.length>0){const a=await se(t.adapter,e.uid,{expectedKind:"issue"}),c=await fs(t.adapter,a.rowid),d=Se(c),l=await Lt(t.adapter,c.uid);o=await Qc(c,e.citations,d.citationAllowedExternalRoots,l)}let r;const s=await M(t,async a=>{const c=P(),d=await ae(a,e.uid),l=await fs(a,d.rowid),u=Se(l);let f;if(e.kind!==void 0){const b=await xe(a,{catalogKind:"kind",ref:e.kind,at:c});Cw(u.allowedKinds,b.name),f={rowid:b.rowid,uid:b.uid,kind:"kind",name:b.name}}let m;if(e.priority!==void 0){const b=await xe(a,{catalogKind:"priority",ref:e.priority,at:c,mintMetadata:async h=>({rank:await Xa(h)})});m={rowid:b.rowid,uid:b.uid,kind:"priority",name:b.name}}let p;if(e.author!==void 0){const b=await xe(a,{catalogKind:"agent",ref:e.author,at:c});p={rowid:b.rowid,uid:b.uid,kind:"agent",name:b.name}}const g={...e};f&&(g.kind=f.name),m&&(g.priority=m.name),p&&(g.author=p.name),Pw(u.requiredFields,g);let y=d.rowid,w=d.uid,v=!1;if(e.body!==void 0){if((await a.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[d.rowid])).rowsAffected!==1)throw new Ut(e.uid);const h=e.title??d.name??void 0,S={...d.metadata??{},revision:re(d.metadata)};e.assignee!==void 0&&(S.assignee=e.assignee);const E=await X(a,{kind:"issue",name:h,content:e.body,metadata:S,at:c});await a.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
|
|
213
218
|
VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
|
|
214
219
|
ON CONFLICT(src, dst, rel) DO UPDATE SET
|
|
215
220
|
meta = excluded.meta, weight = excluded.weight,
|
|
216
|
-
t_invalid = NULL, t_valid = excluded.t_valid`,[S.rowid,c.rowid,a,a]),await 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
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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]
|
|
221
|
+
t_invalid = NULL, t_valid = excluded.t_valid`,[E.rowid,d.rowid,c,c]),await ps(a,E.rowid,{},c),r={oldRowid:d.rowid,oldUid:d.uid,newRowid:E.rowid,newUid:E.uid,newTitle:h??"",newBody:e.body},y=E.rowid,w=E.uid,v=!0}else{const b={...d.metadata??{},...e.assignee!==void 0?{assignee:e.assignee}:{},revision:re(d.metadata)};await ps(a,d.rowid,{name:e.title,metadata:b},c)}if(await Lw(a,t,{oldIssueRowid:d.rowid,newIssueRowid:y,newIssueUid:w,at:c}),await rn(a,t,{rel:"has_status",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,reason:"superseded — status carried forward to the new node (update never changes status)",at:c,required:!0}),await rn(a,t,{rel:"has_kind",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:f,reason:"kind changed via update",at:c}),await rn(a,t,{rel:"has_priority",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:m,reason:"priority changed via update",at:c}),await rn(a,t,{rel:"authored_by",oldSrcRowid:d.rowid,newSrcRowid:y,newSrcUid:w,override:p,reason:"author changed via update",at:c}),await Uw(a,{oldIssueRowid:d.rowid,newIssueRowid:y,at:c}),e.citations!==void 0){const b=e.citations,h=await _w(a,y),S=new Set(h.map(k=>k.key)),E=[];for(let k=0;k<b.length;k+=1)S.has(Vr(b[k]))||E.push({citation:b[k],sha:o[k]});Zc(l,u,E.map(k=>k.citation),E.map(k=>k.sha),"update");const N=new Set(b.map(k=>Vr(k)));for(const k of h)N.has(k.key)||await ed(a,{citationRowid:k.rowid,citationUid:k.uid,at:c,reason:"removed via update citations diff"});for(const k of E)await Kn(a,t,{issueRowid:y,issueUid:w,citation:k.citation,sha:k.sha,at:c})}return await U({tx:a,typePolicy:t.typePolicy,subjectRowid:y,subjectUid:w,subjectKind:"issue",actor:e.by,action:"updated",from:v?d.uid:void 0,to:v?w:void 0,note:`fields changed: ${i.join(", ")}`,at:c}),{uid:w,changed:i}});if(r){const{oldRowid:a,oldUid:c,newRowid:d,newUid:l,newTitle:u,newBody:f}=r,m=Promise.all([hn(t,{action:"delete",subjectRowid:a,subjectUid:c,actor:e.by}),hn(t,{action:"upsert",subjectRowid:d,subjectUid:l,actor:e.by,content:Si(u,f)})]);e.awaitEmbed?await m:m.catch(()=>{})}return s}async function nd(t,e,n){const i=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[e,"has_status"]);if(!i)throw new Error(`${n}: issue rowid=${e} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await Q(t,i.dst);if((o==null?void 0:o.kind)!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${i.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function dt(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function od(t,e){return{async countVerifiedAttestations(n){const i=await t.executeGet(`SELECT COUNT(DISTINCT n.uid) AS n
|
|
222
|
+
FROM edge e JOIN node n ON n.rowid = e.dst
|
|
223
|
+
WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
|
|
224
|
+
AND n.kind = 'attestation' AND n.t_invalid IS NULL
|
|
225
|
+
AND json_extract(n.meta,'$.claim.kind') = ?
|
|
226
|
+
AND json_extract(n.meta,'$.check.state') = 'verified'`,[e,n]);return(i==null?void 0:i.n)??0},async blockersAllTerminal(){const n=await t.executeAll("SELECT src FROM edge WHERE dst = ? AND rel = 'blocks' AND t_invalid IS NULL",[e]);for(const{src:i}of n.rows){const o=await t.executeGet(`SELECT s.meta AS meta FROM edge se JOIN node s ON s.rowid = se.dst
|
|
227
|
+
WHERE se.src = ? AND se.rel = 'has_status' AND se.t_invalid IS NULL
|
|
228
|
+
ORDER BY se.rowid LIMIT 1`,[i]);if(!o||(dt(o.meta)??{}).terminal!==!0)return!1}return!0},async relationExists(n,i){const o=i==="in"?"SELECT 1 AS x FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL LIMIT 1":"SELECT 1 AS x FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL LIMIT 1",r=await t.executeGet(o,[e,n]);return r!=null}}}async function id(t,e){const n=await t.executeAll(`SELECT o.rowid AS rowid, o.uid AS uid, o.meta AS meta
|
|
229
|
+
FROM edge e JOIN node o ON o.rowid = e.dst
|
|
230
|
+
WHERE e.src = ? AND e.rel = 'has_obligation' AND e.t_invalid IS NULL
|
|
231
|
+
AND o.kind = 'obligation' AND o.t_invalid IS NULL
|
|
232
|
+
ORDER BY o.rowid`,[e]),i=[];for(const o of n.rows){const r=dt(o.meta),s=r==null?void 0:r.applies_to,a=r==null?void 0:r.requirement,c=r==null?void 0:r.on_fail,d=r==null?void 0:r.override,l=s!==null&&typeof s=="object"?s:void 0,u=l==null?void 0:l.to,f=l==null?void 0:l.from;if(a===void 0||typeof u!="string"||u.trim().length===0||c!=="block"&&c!=="warn"){i.push({rowid:o.rowid,uid:o.uid,appliesTo:{to:typeof u=="string"?u:""},requirement:a,onFail:c==="warn"?"warn":"block",malformed:!0});continue}const m=d!==null&&typeof d=="object"&&Array.isArray(d.actors)?{actors:d.actors.filter(p=>typeof p=="string")}:void 0;i.push({rowid:o.rowid,uid:o.uid,appliesTo:typeof f=="string"&&f.trim().length>0?{to:u,from:f}:{to:u},requirement:a,onFail:c,...m!==void 0?{override:m}:{}})}return i}function qo(t,e=[]){switch(t.op){case"evidence":return e.includes(t.kind)||e.push(t.kind),e;case"all_of":case"any_of":for(const n of t.of)qo(n,e);return e;case"not":return qo(t.of,e),e;default:return e}}async function Fw(t,e,n){const i=await t.executeGet(`SELECT n.uid AS uid
|
|
233
|
+
FROM edge e JOIN node n ON n.rowid = e.dst
|
|
234
|
+
WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
|
|
235
|
+
AND n.kind = 'attestation' AND n.t_invalid IS NULL
|
|
236
|
+
AND json_extract(n.meta,'$.claim.kind') = ?
|
|
237
|
+
AND json_extract(n.meta,'$.check.state') = 'verified'
|
|
238
|
+
ORDER BY n.rowid LIMIT 1`,[e,n]);return i==null?void 0:i.uid}async function Bw(t,e){return(await t.executeAll(`SELECT n.uid AS uid, n.meta AS meta
|
|
239
|
+
FROM edge e JOIN node n ON n.rowid = e.dst
|
|
240
|
+
WHERE e.src = ? AND e.rel = 'attests' AND e.t_invalid IS NULL
|
|
241
|
+
AND n.kind = 'attestation' AND n.t_invalid IS NULL
|
|
242
|
+
ORDER BY n.rowid`,[e])).rows.map(i=>{const o=dt(i.meta),r=o==null?void 0:o.claim,s=o==null?void 0:o.anchor,a=o==null?void 0:o.check,c=r!==null&&typeof r=="object"?r.kind:void 0,d=s!==null&&typeof s=="object"?s.locator:void 0,l=a!==null&&typeof a=="object"?a.state:void 0;return{uid:i.uid,claimKind:typeof c=="string"?c:"attestation",...typeof d=="string"?{anchorLocator:d}:{},...typeof l=="string"?{checkState:l}:{}}})}async function Kw(t,e){var s;const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)return;const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)return;const o=await t.executeGet("SELECT kind, t_invalid, meta FROM node WHERE rowid = ?",[i.src]);if((o==null?void 0:o.kind)!=="project"||o.t_invalid!==null)return;const r=(s=dt(o.meta))==null?void 0:s.path;return typeof r=="string"&&r.length>0?r:void 0}async function Ho(t,e){switch(t.op){case"evidence":case"blockers_terminal":case"relation":return t;case"all_of":{for(const n of t.of)if(!await ue(n,e))return Ho(n,e);return t}case"any_of":{for(const n of t.of)if(!await ue(n,e))return Ho(n,e);return t}case"not":return t;default:return t}}async function ln(t,e,n,i,o){var s,a,c;let r;try{r=await Ho(i,o)}catch{return{code:"Unknown",message:"the obligation predicate could not be evaluated",obligationUid:n}}if((r==null?void 0:r.op)==="evidence"){const d=r.kind,l=await Bw(t,e),u=l.filter(g=>g.claimKind===d),f=(s=l.find(g=>{var y;return(y=g.anchorLocator)==null?void 0:y.startsWith("commit:")}))==null?void 0:s.anchorLocator,m=(a=l.find(g=>{var y;return(y=g.anchorLocator)==null?void 0:y.startsWith("commit:")}))==null?void 0:a.uid,p={code:"EvidenceUnverified",obligationUid:n,required_kind:d,message:`no verified attestation of kind "${d}" satisfies this obligation`};if(f!==void 0){p.performed_check=xo;const g=await Kw(t,e),y=f.slice(7);m!==void 0&&(p.subject=m),((c=l.find(v=>v.uid===m))==null?void 0:c.checkState)==="stale"&&(p.code="EvidenceStale"),g!==void 0&&y.length>0&&((await Yg(g,y)).onDefaultBranch||(p.message=`commit "${y}" is asserted as evidence of kind "${d}" but is not an ancestor of the default branch (${xo}); a bare commit ref never satisfies a published-artifact obligation`))}else if(u.length>0){const g=u[0];g!==void 0&&(p.subject=g.uid),u.some(y=>y.checkState==="stale")&&(p.code="EvidenceStale",p.message=`the attestation of kind "${d}" is stale`)}return p}return(r==null?void 0:r.op)==="blockers_terminal"?{code:"BlockedBy",obligationUid:n,message:"a blocker is not terminal"}:(r==null?void 0:r.op)==="relation"?{code:"ReferenceUnresolved",obligationUid:n,message:`the required relation "${r.type}" (${r.direction}) is absent`}:{code:"Unknown",obligationUid:n,message:"the obligation is unsatisfied for a reason this gate does not name"}}function qw(t,e,n){const i=t.to==="*"||t.to===n,o=t.from===void 0||t.from===e;return i&&o}async function Hw(t,e){var a;const n=od(t,e.issueRowid),i=[],o=[],r=[],s=await id(t,e.issueRowid);for(const c of s){if(c.malformed){const u={code:"MissingObligation",obligationUid:c.uid,message:"the obligation is malformed and cannot be evaluated"};c.onFail==="warn"?o.push(u):i.push(u);continue}if(!qw(c.appliesTo,e.fromStatus,e.toStatus))continue;let d;try{d=await ue(c.requirement,n)}catch{const u={code:"Unknown",obligationUid:c.uid,message:"the obligation predicate could not be evaluated"};c.onFail==="warn"?o.push(u):i.push(u);continue}if(d){for(const u of qo(c.requirement)){const f=await Fw(t,e.issueRowid,u);f!==void 0&&r.push({obligationUid:c.uid,attestationUid:f})}continue}if(c.onFail==="warn"){o.push(await ln(t,e.issueRowid,c.uid,c.requirement,n));continue}if(((a=c.override)==null?void 0:a.actors.includes(e.effectiveActor))??!1){if(e.override===void 0){i.push(await ln(t,e.issueRowid,c.uid,c.requirement,n));continue}const u=e.override.reason;if(typeof u=="string"&&u.trim().length>0)continue;throw new Oo(c.uid,e.effectiveActor)}if(e.override!==void 0)throw new Oo(c.uid,e.effectiveActor);i.push(await ln(t,e.issueRowid,c.uid,c.requirement,n))}return{satisfied:i.length===0,refusals:i,satisfiedBy:r,warnings:o}}async function Vw(t,e){return(await t.executeAll(`SELECT n.uid AS uid, s.meta AS status_meta
|
|
243
|
+
FROM edge e
|
|
244
|
+
JOIN node n ON n.rowid = e.src
|
|
245
|
+
LEFT JOIN edge se
|
|
246
|
+
ON se.src = n.rowid AND se.rel = 'has_status' AND se.t_invalid IS NULL
|
|
247
|
+
LEFT JOIN node s ON s.rowid = se.dst
|
|
248
|
+
WHERE e.dst = ? AND e.rel = 'blocks' AND e.t_invalid IS NULL
|
|
249
|
+
AND n.t_invalid IS NULL`,[e])).rows.map(i=>{const o=dt(i.status_meta)??{},r=i.status_meta!==null?o.terminal===!0:!1;return{uid:i.uid,terminal:r}})}async function Gw(t){const e=await t.executeAll("SELECT name, meta FROM node WHERE kind = 'status' AND t_invalid IS NULL"),n=new Set,i=new Set;for(const o of e.rows){if(typeof o.name!="string")continue;n.add(o.name),(dt(o.meta)??{}).terminal===!0&&i.add(o.name)}return{all:n,terminal:i}}function Ww(t){switch(t){case"BlockedBy":return"Blocked";case"EvidenceUnverified":case"EvidenceStale":return"Evidence";case"ReferenceUnresolved":return"Reference";case"ClaimStale":return"Claim";default:return"Obligation"}}async function Jw(t,e,n){const i=[],o=await Vw(t,e.rowid);for(const u of o)u.terminal||i.push({type:"Blocked",status:"True",severity:"block",code:"BlockedBy",subject:u.uid,message:`blocked by ${u.uid}`});const r=od(t,e.rowid),s=await Gw(t),a=await id(t,e.rowid);a.length===0&&i.push({type:"Obligation",status:"True",severity:"warn",code:"MissingObligation",message:"no obligations are declared on this item"});for(const u of a){if(u.malformed){i.push({type:"Obligation",status:"True",severity:u.onFail,code:"MissingObligation",subject:u.uid,message:"the obligation is malformed and cannot be evaluated"});continue}const f=u.appliesTo.to;if(f==="*"||s.terminal.has(f)||!s.all.has(f))continue;let p;try{p=await ue(u.requirement,r)}catch{i.push({type:"Obligation",status:"Unknown",severity:u.onFail,code:"Unknown",subject:u.uid,message:"the obligation predicate could not be evaluated"});continue}if(p)continue;const g=await ln(t,e.rowid,u.uid,u.requirement,r);i.push({type:Ww(g.code),status:"True",severity:u.onFail,code:g.code,subject:g.subject??u.uid,message:g.message})}const{claimedBy:c,claimedAt:d}=xn(e.metadata);c!==void 0&&Fn(d,n.at,n.claimStaleAfterMin)&&i.push({type:"Claim",status:"True",severity:"warn",code:"ClaimStale",subject:c,message:`claim by "${c}" is stale (threshold ${n.claimStaleAfterMin}min)`});const l=kc(i);return{actionable:Sc(l),evaluated_at:n.at,revision:$e(e.metadata),conditions:l}}function sn(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}async function gs(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function zw(t,e){if(t.length>0&&!t.includes(e))throw new T("toStatus",`"${e}" is not in this project's allowed status set`)}function Yw(t,e){for(const n of t){if(!(n in e))continue;const i=e[n];if(i==null||typeof i=="string"&&i.trim().length===0)throw new T(n,"is required by this project's field policy")}}async function Xw(t,e){sn("uid",e.uid),sn("by",e.by),G("by",e.by),sn("toStatus",e.toStatus),td(e.gitContext);const n=e.citations??[];n.forEach((o,r)=>sn(`citations[${r}].file`,o.file));let i=[];if(n.length>0){const o=await se(t.adapter,e.uid,{expectedKind:"issue"}),r=await gs(t.adapter,o.rowid),s=Se(r),a=await Lt(t.adapter,r.uid);i=await $i(r,s,n,a,"transition")}return M(t,async o=>{var O;const r=P(),s=await ae(o,e.uid),a=await gs(o,s.rowid),c=Se(a),{claimedBy:d,claimedAt:l}=xn(s.metadata);if(d!==void 0&&d!==e.by&&!Fn(l,r,c.claimStaleAfterMin))throw new gn(d,l??r);const u=await nd(o,s.rowid,"transition"),f=u.name??"",m=await Ya(o,{ref:e.toStatus,at:r});zw(c.allowedStatuses,m.name),Yw(c.requiredFields,{status:m.name,note:e.note});const p=await Q(o,m.rowid),g=((O=p==null?void 0:p.metadata)==null?void 0:O.terminal)===!0;if(!(typeof e.note=="string"&&e.note.trim().length>0)&&c.transitionRequiresNote)throw new Da(s.uid);if(g&&c.citationRequired&&n.length===0)throw new Ma(s.uid);let w;if(g&&(w=await Hw(o,{issueRowid:s.rowid,fromStatus:f,toStatus:m.name,effectiveActor:e.by,...e.override!==void 0?{override:e.override}:{}}),!w.satisfied))throw new gi(w.refusals[0]);const v={target_uid:s.uid,from:f,to:m.name,agent:e.by,note:e.note??null,at:r},b=He(vi(v)),h=await X(o,{kind:"transition",content:e.note??"",metadata:{from_status:f,to_status:m.name,agent:e.by,note:e.note??null,sha:b,at:r,...w!==void 0&&w.satisfiedBy.length>0?{satisfied_by:w.satisfiedBy}:{}},at:r}),S=await q(o,"has_transition");await K(o,{at:r,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"transition",rel:"has_transition",rule:S,typePolicy:t.typePolicy}),await ie(o,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${m.name}"`,at:r});const E=await q(o,"has_status");await K(o,{at:r,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:m.rowid,dstUid:m.uid,dstKind:"status",rel:"has_status",rule:E,typePolicy:t.typePolicy});for(let I=0;I<n.length;I+=1)await Kn(o,t,{issueRowid:s.rowid,issueUid:s.uid,citation:n[I],sha:i[I],at:r});if(w!==void 0&&w.satisfiedBy.length>0){const I=await q(o,"satisfies");for(const{obligationUid:L,attestationUid:$}of w.satisfiedBy){const Y=await se(o,L,{expectedKind:"obligation"}),H=await se(o,$,{expectedKind:"attestation"});await K(o,{at:r,srcRowid:Y.rowid,srcUid:Y.uid,srcKind:"obligation",dstRowid:H.rowid,dstUid:H.uid,dstKind:"attestation",rel:"satisfies",rule:I,typePolicy:t.typePolicy})}}const N={...s.metadata??{}};N.revision=re(s.metadata),g?N.closedAt=r:delete N.closedAt,typeof e.gitContext=="string"&&e.gitContext.trim().length>0&&(N.gitContext=e.gitContext),w!==void 0&&w.satisfiedBy.length>0&&(N.satisfied_by=w.satisfiedBy);const k=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(N),r,s.rowid]);if(k.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${k.rowsAffected} rows for rowid=${s.rowid}, expected exactly 1.`);const R=e.override!==void 0&&typeof e.override.reason=="string"&&e.override.reason.trim().length>0?`override: ${e.override.reason}`:void 0,A=R===void 0?e.note:[e.note,R].filter(I=>typeof I=="string"&&I.length>0).join(" — ");return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"transitioned",from:f,to:m.name,note:A,at:r}),{uid:s.uid,fromStatus:f,toStatus:m.name,closedAt:g?r:void 0,transitionUid:h.uid}})}function hs(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function ys(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await Q(t,i.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const r={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Se(r)}async function vt(t,e,n,i){const o=await t.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),i,e]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function Qw(t,e){if(hs("uid",e.uid),hs("by",e.by),G("by",e.by),e.action!=="claim"&&e.action!=="release"&&e.action!=="renew")throw new T("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(e.action)})`);const n=e.force===!0;return M(t,async i=>{var d;const o=P(),r=await ae(i,e.uid),s={...r.metadata??{}},{claimedBy:a,claimedAt:c}=xn(s);if(e.action==="claim"){const l=await nd(i,r.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new La(r.uid,l.name??"");const u=await ys(i,r.rowid),p=(await Jw(i,r,{at:o,claimStaleAfterMin:u.claimStaleAfterMin})).conditions.filter(S=>S.severity==="block"&&S.status==="True")[0];if(p!==void 0&&!n)throw new hi(p);const g=p!==void 0?`force-claimed despite ${p.code}${p.subject!==void 0?` ${p.subject}`:""}`:void 0;if(a===void 0){const S={...s,claimedBy:e.by,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,S,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"claimed",to:e.by,note:g,at:o}),{uid:r.uid,status:"claimed",claimedBy:e.by,claimedAt:o}}if(a===e.by){const S={...s,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,S,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"claimed",from:e.by,to:e.by,note:g===void 0?"re-affirmed (held)":`${g} — re-affirmed (held)`,at:o}),{uid:r.uid,status:"held",heldBy:e.by,claimedBy:e.by,claimedAt:o}}const y=await ys(i,r.rowid),w=Ec(c,o),v=Fn(c,o,y.claimStaleAfterMin);if(!v&&!n)throw new gn(a,c??o);const b={...s,claimedBy:e.by,claimedAt:o,previousClaimant:a,revision:re(s)};await vt(i,r.rowid,b,o);const h=v?`stale claim reclaimed after ~${Math.floor(w)}min (threshold ${y.claimStaleAfterMin}min)`:"force override of a non-stale claim";return await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"reclaimed-stale",from:a,to:e.by,note:g===void 0?h:`${g} — ${h}`,at:o}),{uid:r.uid,status:"reclaimed-stale",claimedBy:e.by,claimedAt:o,previousClaimant:a}}if(e.action==="release"){if(a===e.by){const l={...s,revision:re(s)};return delete l.claimedBy,delete l.claimedAt,await vt(i,r.rowid,l,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"released",from:e.by,at:o}),{uid:r.uid,status:"released"}}return{uid:r.uid,status:"release-noop",wasClaimedBy:a}}if(a===e.by){const l={...s,claimedAt:o,revision:re(s)};return await vt(i,r.rowid,l,o),await U({tx:i,typePolicy:t.typePolicy,subjectRowid:r.rowid,subjectUid:r.uid,subjectKind:"issue",actor:e.by,action:"renewed",from:e.by,to:e.by,at:o}),{uid:r.uid,status:"renewed",claimedBy:e.by,claimedAt:o}}throw new gn(a??"",c??"")})}const ws=["relates_to","supersedes","blocks","duplicate_of","part_of","similar_to"];function io(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function Zw(t,e,n,i){const o=await t.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e,n,i]);return o?o.rowid:null}async function ev(t,e){if(io("sourceUid",e.sourceUid),io("targetUid",e.targetUid),io("by",e.by),G("by",e.by),!ws.includes(e.rel))throw new T("rel",`must be one of ${ws.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.rel)})`);if(e.action!=="add"&&e.action!=="remove")throw new T("action",`must be "add" or "remove" (got ${JSON.stringify(e.action)})`);if(e.sourceUid===e.targetUid)throw new T("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return M(t,async n=>{const i=P(),o=await ae(n,e.sourceUid),r=await ae(n,e.targetUid),s=await Zw(n,o.rowid,r.rowid,e.rel);if(e.action==="add"){if(s!==null)return{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"add",noop:!0};const a=await q(n,e.rel);return await K(n,{at:i,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:r.rowid,dstUid:r.uid,dstKind:"issue",rel:e.rel,rule:a,typePolicy:t.typePolicy}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"related",to:r.uid,note:e.rel,at:i}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"add",noop:!1}}return s===null?{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"remove",noop:!0}:(await ie(n,{srcRowid:o.rowid,dstRowid:r.rowid,rel:e.rel,reason:`relate: removed by "${e.by}"`,at:i}),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"unrelated",to:r.uid,note:e.rel,at:i}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),{sourceUid:o.uid,targetUid:r.uid,rel:e.rel,action:"remove",noop:!1})})}function vs(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function tv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await Q(t,n.src);if((i==null?void 0:i.kind)!=="component"||i.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:i.rowid,uid:i.uid,name:i.name??""}}async function nv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_project"]);if(!n)throw new Error(`move: component rowid=${e} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const i=await Q(t,n.src);if((i==null?void 0:i.kind)!=="project"||i.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:i.rowid,uid:i.uid,name:i.name??""}}async function ov(t,e){return vs("uid",e.uid),vs("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await ae(n,e.uid),r=await tv(n,o.rowid),s=await nv(n,r.rowid);let a;if(e.toProject!==void 0){const l=await at(n,e.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=s;let c;if(e.toComponent!==void 0?c=await Ei(n,{projectUid:a.uid,ref:e.toComponent}):c=await Wa(n,{projectRowid:a.rowid}),c.rowid===r.rowid)return{uid:o.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:r.uid,toComponent:c.uid};await ie(n,{srcRowid:r.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:i});const d=await q(n,"owns_component");return await K(n,{at:i,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:t.typePolicy}),await n.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify({...o.metadata??{},revision:re(o.metadata)}),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"moved",from:r.uid,to:c.uid,at:i}),{uid:o.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:r.uid,toComponent:c.uid}})}function ro(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}async function iv(t,e){ro("uid",e.uid),ro("by",e.by),G("by",e.by),ro("reason",e.reason);let n;const i=await M(t,async o=>{const r=P(),s=await ae(o,e.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:e.reason,invalidatedAt:r},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(a),s.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);return await U({tx:o,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"deleted",note:e.reason,at:r}),{uid:s.uid,invalidated:!0}});if(n){const o=hn(t,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:e.by});e.awaitEmbed?await o:o.catch(()=>{})}return i}async function bs(t,e){let n;try{n=await se(t,e)}catch(i){throw i instanceof V?new mn(e):i}if(n.kind!=="issue"&&n.kind!=="SPEC")throw new mn(e);if(n.kind==="issue"&&n.isSuperseded)throw new Ut(e);return{rowid:n.rowid,uid:n.uid,kind:n.kind,metadata:n.metadata}}function Xe(t,e){if(typeof e!="string"||e.trim().length===0)throw new T(t,"is required")}function rv(t){if(typeof t=="number"){if(Number.isFinite(t))return;throw new T("subject.revision","must be a finite number or a non-empty string")}if(!(typeof t=="string"&&t.trim().length>0))throw new T("subject.revision","must be a finite number or a non-empty string")}async function rd(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`attestation: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const i=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!i)throw new Error(`attestation: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await t.executeGet("SELECT uid, kind, t_invalid, meta FROM node WHERE rowid = ?",[i.src]);if((o==null?void 0:o.kind)!=="project"||o.t_invalid!==null)throw new Error(`attestation: resolved project rowid=${i.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const r=av(o.meta),s=r==null?void 0:r.path;return{uid:o.uid,path:typeof s=="string"&&s.length>0?s:void 0}}function sv(t,e){const n=_.resolve(t),i=_.isAbsolute(e)?_.resolve(e):_.resolve(n,e);if(!Ta(n,i))return;const o=_.relative(n,i);return o.length===0?void 0:o}async function sd(t,e,n,i){const o=Mn(e.locator);if(o.scheme!=="path")return n;const r=i===void 0?[]:await Lt(t,i),s=[...new Set([...n!==void 0?[n]:[],...r])];let a;for(const c of s){if(!bn(c))continue;const d=sv(c,o.target);if(d!==void 0){if(vc(c,d))return c;a===void 0&&(a=c)}}return a??n}function av(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function Es(t,e){try{const n=await se(t,e,{expectedKind:"attestation"});return{rowid:n.rowid,uid:n.uid,metadata:n.metadata}}catch(n){throw n instanceof V?new xa(e):n}}async function cv(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"attests"]);return n==null?void 0:n.src}function dv(t){const e=t==null?void 0:t.anchor;if(e===null||typeof e!="object")return;const n=e,i=n.locator,o=n.digest;if(!(typeof i!="string"||typeof o!="string"))return{locator:i,digest:o}}function Ss(t){const e=t==null?void 0:t.checks;return Array.isArray(e)?e:[]}function lv(t){const e=t==null?void 0:t.claim;if(e!==null&&typeof e=="object"){const n=e.kind;if(typeof n=="string")return n}return"attestation"}async function uv(t,e){var a,c,d,l;if(Xe("subject.id",(a=e.subject)==null?void 0:a.id),rv((c=e.subject)==null?void 0:c.revision),Xe("claim.kind",(d=e.claim)==null?void 0:d.kind),Xe("anchor.locator",(l=e.anchor)==null?void 0:l.locator),Xe("by",e.by),G("by",e.by),typeof e.anchor.digest!="string"||e.anchor.digest.trim().length===0)throw new Ue(e.anchor.locator,"a path anchor requires a content digest");Mn(e.anchor.locator);const n=await bs(t.adapter,e.subject.id),i=n.kind==="issue"?await rd(t.adapter,n.rowid):void 0,o=await sd(t.adapter,e.anchor,i==null?void 0:i.path,i==null?void 0:i.uid),r=P();let s=Ri(e.anchor,{...o!==void 0?{root:o}:{},sinceISO:r,full:!1,now:r,by:e.by});return M(t,async u=>{const f=await bs(u,e.subject.id);typeof e.subject.revision=="number"&&$e(f.metadata)!==e.subject.revision&&(s={...s,state:"unknown",reason:"revision-drift"});const m={subject:{id:f.uid,revision:e.subject.revision},claim:{kind:e.claim.kind,...e.claim.body!==void 0?{body:e.claim.body}:{},asserted_by:e.by,asserted_at:r},anchor:{locator:e.anchor.locator,digest:e.anchor.digest},check:s,checks:[s],lifecycle:{status:"active",supersedes:null,part_of:null}},p=await X(u,{at:r,kind:"attestation",name:e.claim.kind,content:e.claim.body??"",metadata:m}),g=await q(u,"attests");return await K(u,{at:r,srcRowid:f.rowid,srcUid:f.uid,srcKind:f.kind,dstRowid:p.rowid,dstUid:p.uid,dstKind:"attestation",rel:"attests",rule:g,typePolicy:t.typePolicy}),await U({tx:u,typePolicy:t.typePolicy,subjectRowid:f.rowid,subjectUid:f.uid,subjectKind:f.kind,actor:e.by,action:"attested",to:p.uid,note:e.claim.kind,at:r}),{attestationUid:p.uid,subject:{id:f.uid,revision:e.subject.revision},check:s}})}async function fv(t,e){Xe("attestationUid",e.attestationUid),Xe("by",e.by),G("by",e.by);const n=await Es(t.adapter,e.attestationUid),i=await cv(t.adapter,n.rowid),o=i===void 0?void 0:await rd(t.adapter,i),r=dv(n.metadata),s=Ss(n.metadata),a=s.length>0?s[s.length-1].checked_at:pv(n.metadata),c=P(),d=r?await sd(t.adapter,r,o==null?void 0:o.path,o==null?void 0:o.uid):void 0,l=r?Ri(r,{...d!==void 0?{root:d}:{},...a!==void 0?{sinceISO:a}:{},full:!0,now:c,by:e.by}):{state:"unknown",method:"none",checked_at:c,checked_by:e.by,reason:"attestation carries no readable anchor"};return M(t,async u=>{const f=await Es(u,e.attestationUid),m=f.metadata??{},p=[...Ss(m),l],g={...m,check:l,checks:p},y=await u.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(g),c,f.rowid]);if(y.rowsAffected!==1)throw new Error(`recheck: touch UPDATE affected ${y.rowsAffected} rows for rowid=${f.rowid}, expected exactly 1.`);return await U({tx:u,typePolicy:t.typePolicy,subjectRowid:f.rowid,subjectUid:f.uid,subjectKind:"attestation",actor:e.by,action:"rechecked",note:lv(m),at:c}),{attestationUid:f.uid,checks:p}})}function pv(t){const e=t==null?void 0:t.claim;if(e!==null&&typeof e=="object"){const n=e.asserted_at;if(typeof n=="string")return n}}function ot(t,e){if(e===void 0||e.trim().length===0)throw new T(t,"is required")}function mv(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}async function gv(t,e){return ot("fromUid",e.fromUid),ot("toUid",e.toUid),ot("by",e.by),G("by",e.by),M(t,async n=>{var l,u;const i=P(),o=await Be(n,e.fromUid);if((o==null?void 0:o.kind)!=="project")throw new V("project",e.fromUid);const r=await at(n,e.toUid);if(o.uid===r.uid)throw new T("toUid","must differ from fromUid");if(o.tInvalid!==null){const f=(l=o.metadata)==null?void 0:l.redirectTo;if(f===r.uid)return{survivorUid:r.uid,retiredUid:o.uid,movedIssues:0,retired:!0};throw new T("fromUid",`"${o.uid}" is already retired`+(typeof f=="string"?` (redirectTo "${f}")`:"")+" and cannot be re-merged onto a different survivor")}const s=await q(n,"owns_project"),{rows:a}=await n.executeAll(`SELECT c.rowid AS rowid, c.uid AS uid, c.meta AS meta
|
|
250
|
+
FROM edge e JOIN node c ON c.rowid = e.dst
|
|
251
|
+
WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
|
|
252
|
+
AND c.t_invalid IS NULL`,[o.rowid]);let c=0;for(const f of a){const{rows:m}=await n.executeAll("SELECT COUNT(*) AS n FROM edge WHERE src = ? AND rel = 'owns_component' AND t_invalid IS NULL",[f.rowid]);c+=((u=m[0])==null?void 0:u.n)??0,await ie(n,{srcRowid:o.rowid,dstRowid:f.rowid,rel:"owns_project",reason:"project-merge",at:i}),await K(n,{at:i,srcRowid:r.rowid,srcUid:r.uid,srcKind:"project",dstRowid:f.rowid,dstUid:f.uid,dstKind:"component",rel:"owns_project",rule:s,typePolicy:t.typePolicy});const p=mv(f.meta)??{};await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify({...p,projectUid:r.uid}),f.rowid])}const d={...o.metadata??{},redirectTo:r.uid,retiredAt:i,retiredReason:"project-merge"};return await n.executeRun("UPDATE node SET meta = ?, t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(d),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:e.by,action:"merged",to:r.uid,note:`merged into ${r.uid}`,at:i}),{survivorUid:r.uid,retiredUid:o.uid,movedIssues:c,retired:!0}})}async function hv(t,e){return ot("uid",e.uid),ot("reason",e.reason),ot("by",e.by),G("by",e.by),M(t,async n=>{const i=P(),o=await Be(n,e.uid);if((o==null?void 0:o.kind)!=="project")throw new V("project",e.uid);if(o.tInvalid!==null)return{uid:o.uid,retired:!0};const r={...o.metadata??{},retiredAt:i,retiredReason:e.reason};return await n.executeRun("UPDATE node SET meta = ?, t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(r),i,o.rowid]),await U({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:e.by,action:"removed",note:e.reason,at:i}),{uid:o.uid,retired:!0}})}function _n(t){var e;return(e=t.env.version)==null?void 0:e.configHash}async function ad(t){const e=t.embeddingConfig;e!=null&&e.refresh().changed&&Jy(t.store.adapter);const n=e?e.current():t.env.config.embedding;return Gy(t.store.adapter,t.store.graph,n,void 0,{configuredEnabled:e?e.configured().enabled:n==null?void 0:n.enabled,startupHash:_n(t),configuredHash:e?e.fingerprint().configHash:_n(t),configPaths:e?e.fingerprint().files.map(i=>i.path):void 0})}async function W(t,e){await pi(t.store.adapter);const{search:n,embedding:i}=e.needsSemantic?await ad(t):{};return{adapter:t.store.adapter,typePolicy:t.store.typePolicy,graph:t.store.graph,...n!==void 0?{search:n}:{},...i!==void 0?{embedding:i}:{}}}async function Ht(t,e){const{search:n}=e.needsSemantic?await ad(t):{},i=n!==void 0&&e.probeSpace?await n.spacePopulated():void 0;return{graph:t.store.graph,assertVocabulary:()=>pi(t.store.adapter),assertCatalogInvariants:()=>Vc(t.store.adapter),...n!==void 0?{search:n}:{},...i!==void 0?{spacePopulated:i}:{}}}const yv=[[mn,"item_not_found"],[xa,"item_not_found"],[Fa,"item_not_found"],[Ba,"item_not_found"],[mi,"ambiguous_reference"],[V,"not_found"],[T,"invalid_argument"],[Ue,"invalid_argument"],[ve,"invalid_argument"],[gn,"conflict"],[jo,"conflict"],[Ut,"conflict"],[La,"precondition_failed"],[Ma,"precondition_failed"],[Da,"precondition_failed"],[Ua,"precondition_failed"],[gi,"precondition_failed"],[Oo,"precondition_failed"],[hi,"precondition_failed"],[To,"precondition_failed"],[$a,"store_busy"],[Fc,"rag_not_configured"]],wv={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function cd(t){for(const[e,n]of yv)if(t instanceof e){const i=t instanceof C?{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}:void 0;return t instanceof gi?ne(n,t.message,{...i??{},refusal:t.refusal}):t instanceof hi?ne(n,t.message,{...i??{},refusal:t.refusal}):ne(n,t.message,i)}return t instanceof C?ne(wv[t.code]??"internal",t.message,{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}):ne("internal",t instanceof Error?t.message:String(t))}async function D(t){try{return Ii(await t())}catch(e){return cd(e)}}async function dd(t,e){return D(()=>"registry"in e?e.registry==="project"?oo(t.store.graph,{registry:"project",name:e.name}):e.registry==="component"?oo(t.store.graph,{registry:"component",name:e.name,filter:e.filter}):oo(t.store.graph,{registry:"location",name:e.name}):nw(t.store.graph,e))}async function ld(t,e){try{const{result:n,meta:i}=await qy(await Ht(t,{needsSemantic:xy(e),probeSpace:e.text!==void 0}),e);return Ii(n,i?{meta:i}:void 0)}catch(n){return cd(n)}}async function ud(t,e){return D(async()=>Xc(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function fd(t,e){return D(async()=>lw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function pd(t,e){return D(async()=>mw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function md(t,e){return D(async()=>yw(await Ht(t,{needsSemantic:!1,probeSpace:!1}),e))}async function gd(t){return D(async()=>{const e=t.embeddingConfig,n=e?e.configured():t.env.config.embedding,i=e?e.current():t.env.config.embedding,o=Wy(t.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(i==null?void 0:i.enabled)===!0,provider:(i==null?void 0:i.provider)??"",model:(i==null?void 0:i.model)??"",membersPresent:{embedding:(o==null?void 0:o.embedding)??!1,search:(o==null?void 0:o.search)??!1},divergent:(n==null?void 0:n.enabled)===!0!=((i==null?void 0:i.enabled)===!0),startupHash:_n(t)??"",currentHash:e?e.fingerprint().configHash:_n(t)??""}})}async function hd(t,e){return D(()=>Ey(t.store.graph,e))}async function yd(t,e){return D(async()=>$w(await W(t,{needsSemantic:!0}),e))}async function wd(t,e){return D(async()=>xw(await W(t,{needsSemantic:!0}),e))}async function vd(t,e){return D(async()=>Nw(await W(t,{needsSemantic:!1}),e))}async function bd(t,e){return D(async()=>Rw(await W(t,{needsSemantic:!1}),e))}async function Ed(t,e){return D(async()=>Xw(await W(t,{needsSemantic:!1}),e))}async function Sd(t,e){return D(async()=>uv(await W(t,{needsSemantic:!1}),e))}async function kd(t,e){return D(async()=>fv(await W(t,{needsSemantic:!1}),e))}async function _d(t,e){return D(async()=>Vg(await W(t,{needsSemantic:!1}),e))}async function Ad(t,e){return D(async()=>Gg(await W(t,{needsSemantic:!1}),e))}async function Nd(t,e){return D(async()=>vh(await W(t,{needsSemantic:!1}),e))}async function Rd(t,e){return D(()=>Ic(t.store.graph,e))}async function jd(t,e){return D(async()=>Qw(await W(t,{needsSemantic:!1}),e))}async function Td(t,e){return D(async()=>ev(await W(t,{needsSemantic:!1}),e))}async function Od(t,e){return D(async()=>ov(await W(t,{needsSemantic:!1}),e))}async function Id(t,e){return D(async()=>iv(await W(t,{needsSemantic:!1}),e))}async function $d(t,e){return D(async()=>Qp(await W(t,{needsSemantic:!1}),e))}async function Cd(t,e){return D(async()=>em(await W(t,{needsSemantic:!1}),e))}async function Pd(t,e){return D(async()=>nm(await W(t,{needsSemantic:!1}),e))}async function Ld(t,e){return D(async()=>om(await W(t,{needsSemantic:!1}),e))}async function Ud(t,e){return D(async()=>gv(await W(t,{needsSemantic:!1}),e))}async function Dd(t,e){return D(async()=>hv(await W(t,{needsSemantic:!1}),e))}const vv=Object.freeze(Object.defineProperty({__proto__:null,addCitation:vd,attest:Sd,claim:jd,create:yd,delete:Id,embeddingStatus:gd,get:dd,lookup:hd,mergeProject:Ud,move:Od,obligate:_d,openCurve:pd,partOfRollup:fd,priorityMatrix:ud,query:ld,recheck:kd,relate:Td,removeCitation:bd,report:md,rmLocation:Ld,rmProject:Dd,specAppend:Nd,specCheck:Rd,transition:Ed,unobligate:Ad,update:wd,upsertComponent:Cd,upsertLocation:Pd,upsertProject:$d},Symbol.toStringTag,{value:"Module"}));async function bv(t){let e;try{e=await Te.open(t,"r"),await e.sync()}catch{}finally{e&&await e.close().catch(()=>{})}}async function Md(t,e){const n=_.dirname(t);await Te.mkdir(n,{recursive:!0});const i=`${t}.${process.pid}.${ke.randomUUID()}.tmp`;let o;try{o=await Te.open(i,"w"),await o.writeFile(JSON.stringify(e),"utf8"),await o.sync(),await o.close(),o=void 0,await Te.rename(i,t),await bv(n)}catch(r){throw o&&await o.close().catch(()=>{}),await Te.unlink(i).catch(()=>{}),r}}function Ev(t){return{async get(){try{const e=await Te.readFile(t,"utf8");return JSON.parse(e)}catch{return}},async put(e,n){await Md(t,n)}}}const $t=1;function Sv(t){return ke.createHash("sha256").update(t).digest("hex")}async function ks(t){return Sv(await Te.readFile(t,"utf8"))}async function An(t){try{return(await Te.stat(t)).mtimeMs}catch{return}}async function _s(t,e){const n=await ks(t.source),i=ke.createHash("sha256");i.update(`formatVersion:${$t}
|
|
253
|
+
`),i.update(`extractorVersion:${e}
|
|
254
|
+
`),i.update(`host:${t.host}
|
|
255
|
+
`),i.update(`namespace:${t.namespace??""}
|
|
256
|
+
`),i.update(`source:${n}
|
|
257
|
+
`);for(const o of na(t.source))o!==t.source&&i.update(`dep:${o}:${await ks(o)}
|
|
258
|
+
`);return i.digest("hex")}async function As(t,e){const n=await An(t.source)??0,i=[];for(const o of na(t.source)){if(o===t.source)continue;const r=await An(o);r!==void 0&&i.push({path:o,mtimeMs:r})}return{contentKey:e,source:{path:t.source,mtimeMs:n},deps:i}}async function kv(t,e){if(e.source.path!==t.source)return!1;const n=await An(e.source.path);if(n===void 0||n!==e.source.mtimeMs)return!1;for(const i of e.deps){const o=await An(i.path);if(o===void 0||o!==i.mtimeMs)return!1}return!0}function _v(t){if(t.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const e=Ev(t.cache),n=t.extractorVersion;async function i(o,r,s){const a=s??await _s(o,n),c=await As(o,a);await e.put(t.cache,{formatVersion:$t,operations:r,extractorVersion:n,staleness:c})}return async(o,r)=>{const s=await e.get(t.cache);if((s==null?void 0:s.formatVersion)!==$t||s.extractorVersion!==n||!s.staleness){const d=await r();try{await i(o,d)}catch{}return d}if(await kv(o,s.staleness))return s.operations;const a=await _s(o,n);if(a===s.staleness.contentKey)return As(o,a).then(d=>e.put(t.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await r();try{await i(o,c,a)}catch{}return c}}Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href);const Av="api.ir.json",Nv=Yo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href),Ci=Nv("@adhd/apigen-core-client/package.json").version;function ct(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href));return j.existsSync(_.join(t,"api.d.ts"))?t:_.join(t,"..","dist")}function Rv(t){return _.join(t,Av)}function Pi(t){return ke.createHash("sha256").update(t).digest("hex")}function xd(t){const e=[],n=o=>{let r;try{r=j.readdirSync(o,{withFileTypes:!0})}catch{return}for(const s of r){const a=_.join(o,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&e.push(a)}};n(t),e.sort();const i={};for(const o of e)i[_.relative(t,o).split(_.sep).join("/")]=Pi(j.readFileSync(o));return i}function jv(t,e){const n=Object.keys(t).sort(),i=Object.keys(e).sort();if(n.length!==i.length)return!1;for(let o=0;o<n.length;o++){const r=n[o];if(r!==i[o]||t[r]!==e[r])return!1}return!0}function Fd(t){try{const e=Rv(t);if(!j.existsSync(e))return;const n=JSON.parse(j.readFileSync(e,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==$t||n.extractorVersion!==Ci)return;const i=n.artifactSource;if(!i||typeof i.sha256!="string"||typeof i.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const o=_.join(t,"api.d.ts");if(!j.existsSync(o))return;const r=j.readFileSync(o);if(r.byteLength!==i.bytes||Pi(r)!==i.sha256)return;const s=i.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return jv(s,xd(t))?n.operations:void 0}catch{return}}async function Tv(t){const e=j.readFileSync(t.apiDts),n=_.dirname(t.apiDts),i={formatVersion:$t,operations:t.operations,extractorVersion:t.extractorVersion,artifactSource:{path:_.relative(n,t.apiDts).split(_.sep).join("/"),sha256:Pi(e),bytes:e.byteLength,deps:xd(n)}};await Md(t.outFile,i)}function Bd(t={}){const e=ki("backlog",Ie,{namespace:t.namespace??"production",scope:Pn(t.scope),...t.adhdRoot!==void 0?{adhdRoot:t.adhdRoot}:{},...t.cwd!==void 0?{cwd:t.cwd}:{}}),n=[_.join(e.roots.system,Ze),_.join(e.roots.global,Ze)];return e.roots.project&&(n.push(_.join(e.roots.project,Ze)),n.push(_.join(e.roots.project,oc))),[...new Set(n)]}const Ov=t=>t instanceof Error?t.message:String(t),Ns=t=>({enabled:t.enabled===!0,provider:t.provider,model:t.model}),Iv=(t,e)=>t.enabled===e.enabled&&t.provider===e.provider&&t.model===e.model;function $v(t){const e=()=>t.layerFiles().map(a=>{try{const c=j.statSync(a);return{path:a,stamp:`${c.mtimeMs}:${c.size}`}}catch{return{path:a,stamp:"absent"}}}),n=(a,c)=>a.length===c.length&&a.every((d,l)=>d.path===c[l].path&&d.stamp===c[l].stamp);let i=Ns(t.baseline.config.embedding),o=i,r={configHash:t.baseline.version.configHash,files:e()};const s=()=>{const a=e();if(n(a,r.files))return!1;let c;try{c=t.rebuild()}catch(d){return t.log("warn",`backlog: could not re-read the embedding config layers (${Ov(d)}) — continuing with the last known effective embedding settings`),!1}return r={configHash:c.version.configHash,files:a},o=Ns(c.config.embedding),!0};return{current:()=>i,configured:()=>(s(),o),divergent:()=>(s(),o.enabled&&!i.enabled),refresh:()=>{const a=i;return s(),Iv(o,i)?{changed:!1,from:a,to:i}:(i=o,t.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${i.enabled}, provider ${i.provider}, model ${i.model}); adopting without restart`),{changed:!0,from:a,to:i})},fingerprint:()=>r}}function Cv(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),e=_.join(t,"package.json");return j.existsSync(e)?e:_.join(t,"..","package.json")}function Li(){const t=Cv(),e=JSON.parse(j.readFileSync(t,"utf8"));return{name:e.name,version:e.version}}function Kd(t={}){const e=t.now??(()=>Date.now()),n=()=>new Date(e()).toISOString();let i="starting",o=n(),r,s;const a=new Promise(d=>{s=d}),c=d=>{i!==d&&(i=d,o=n())};return{state:()=>i,report:()=>{const d={state:i,since:o,degraded:r!==void 0};return r!==void 0&&(d.failure={...r}),d},markLive:()=>c("live"),markReady:()=>{c("ready"),s==null||s()},fail:d=>(r={...d},{action:d.kind==="liveness"?"restart":"report"}),whenReady:()=>a}}const Pv={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Lv=/embedding[_-]?status$/i;function Uv(t){return t.replace(/-([a-z])/g,(e,n)=>n.toUpperCase())}function Dv(t){return async()=>{const e=t.pkg.fns,n=t.operations.find(a=>Lv.test(a.id)),i=(n==null?void 0:n.id.split("/").pop())??"embedding-status",o=[i,Uv(i),"embeddingStatus"].find(a=>typeof e[a]=="function")??"embeddingStatus",r=e[o];if(typeof r!="function")throw new Error(`readiness: no embedding-status operation is mounted (looked for ${o})`);const s=await t.pkg.createClient();return r(s)}}function Mv(t){var e,n;if(t!==null&&typeof t=="object"&&"ok"in t){const i=t;return i.ok===!0?{ready:!0}:{ready:!1,failure:{kind:"readiness",code:((e=i.error)==null?void 0:e.code)??"probe_failed",message:((n=i.error)==null?void 0:n.message)??"serving-path probe returned ok:false (transport answered, op did not)"}}}return{ready:!0}}async function qd(t,e){const n=e.timer??Pv,i=e.invoke??Dv(t);let o;const r=new Promise(c=>{o=n.setTimeout(()=>c({ready:!1,failure:{kind:"readiness",code:"probe_timeout",message:`serving-path probe did not answer within ${e.timeoutMs}ms`}}),e.timeoutMs)}),s=i().then(c=>Mv(c),c=>({ready:!1,failure:{kind:"readiness",code:"probe_error",message:c instanceof Error?c.message:String(c)}})),a=await Promise.race([s,r]);return n.clearTimeout(o),a}class Hd extends C{constructor(e,n){super(`Unknown config key "service.${e}" in ${n}. An unknown key is a hard error (a host would otherwise silently ignore it). Known keys are the service.* contract — see SERVICE_CONFIG_KEYS / the backlog docs.`),this.code="E_VALIDATION",this.retryable=!1,this.key=e,this.file=n}}class qn extends C{constructor(e,n){super(`Config field "${e}" must be an absolute path (or a PATH-resolvable bin such as "npx"/"node"), got "${n}". A relative path resolves against an unpredictable cwd and is refused.`),this.code="E_VALIDATION",this.retryable=!1,this.field=e,this.value=n}}class Vo extends C{constructor(e,n,i){super(`Unknown MCP config key "${n}" in ${e}`+(i?` (did you mean "${i}"?)`:"")+'. Allowed keys are type/command/args/env/url. An unknown key is a HARD ERROR: a host silently ignores it, so a server "configured" with it looks configured and is absent.'),this.code="E_VALIDATION",this.retryable=!1,this.entry=e,this.key=n,i!==void 0&&(this.suggestion=i)}}class Ye extends C{constructor(e,n,i){super(`Server artifact drift at ${i}: expected ${e}, got ${n}. Refusing to start — a config pointing at a missing or changed artifact must fail loudly, not launch a phantom.`),this.code="E_VALIDATION",this.retryable=!1,this.expected=e,this.actual=n,this.resolvedPath=i}}class Qe extends C{constructor(e,n){super(`Service not ready (state=${e})`+(n?`: ${n}`:"")+". The connect/handshake did not succeed inside its bounded budget."),this.code="E_VALIDATION",this.retryable=!0,this.state=e,n!==void 0&&(this.failure=n)}}const Go=Object.freeze(["service.transport","service.port","service.host","service.serverCommand","service.connectGraceMs","service.connectBudgetMs","service.readinessTimeoutMs"]),Rs="service.",xv={"service.transport":"mcp","service.port":3300,"service.host":"127.0.0.1","service.serverCommand":"","service.connectGraceMs":2e4,"service.connectBudgetMs":6e4,"service.readinessTimeoutMs":3e4};function Vd(t){const e=process.env.PATH;if(!e)return!1;for(const n of e.split(_.delimiter))if(n!=="")try{return j.accessSync(_.join(n,t),j.constants.X_OK),!0}catch{}return!1}function Nn(t,e){if(!(e===""||e===":memory:")&&!_.isAbsolute(e)&&!Vd(e))throw new qn(t,e)}function js(t,e){const n=Ie.config[t],i=n==null?void 0:n.type;if(e!==void 0){if(i==="integer"||i==="number"){const o=typeof e=="number"?e:Number(e);return Number.isFinite(o)?o:void 0}return i==="boolean"?typeof e=="boolean"?e:e==="true"||e==="1":e}}function Gd(t,e){var a;const n={scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace},i={...xv};for(const c of Bd(n)){const d=bt(c);if(d)for(const[l,u]of Object.entries(d)){if(!l.startsWith(Rs))continue;if(!Go.includes(l))throw new Hd(l.slice(Rs.length),c);const f=js(l,u);f!==void 0&&(i[l]=f)}}for(const c of Go){const d=(a=Ie.config[c])==null?void 0:a.env;if(!d)continue;const l=process.env[d];if(l===void 0)continue;const u=js(c,l);u!==void 0&&(i[c]=u)}t.transport!==void 0&&(i["service.transport"]=t.transport),t.port!==void 0&&(i["service.port"]=t.port),t.host!==void 0&&(i["service.host"]=t.host);const o=tt(e);Nn("service.dbPath",o);const r=String(i["service.serverCommand"]??"");Nn("server.command",r);const s=i["service.transport"];if(s!=="mcp"&&s!=="http"&&s!=="both")throw new qn("service.transport",String(i["service.transport"]));return{transport:s,port:Number(i["service.port"]),host:String(i["service.host"]),scope:Pn(t.scope),dbPath:o,busyTimeoutMs:e.config.db.busyTimeoutMs,server:{command:r,identity:{kind:"path"}},readiness:{timeoutMs:Number(i["service.readinessTimeoutMs"])},connect:{graceMs:Number(i["service.connectGraceMs"]),budgetMs:Number(i["service.connectBudgetMs"]),maxAttempts:4,baseMs:250,maxMs:5e3,breakerFailureThreshold:3,breakerResetMs:3e4}}}const Ts=["type","command","args","env","url"];function Ui(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Vo(e,"<non-object entry>");const n=t;for(const o of Object.keys(n)){if(Ts.includes(o))continue;const r=Ni(o,[...Ts]);throw new Vo(e,o,r[0])}const i=n.command;if(typeof i=="string")Nn("server.command",i);else if(Array.isArray(i)&&typeof i[0]=="string")Nn("server.command",i[0]);else if(i!==void 0)throw new qn("server.command",JSON.stringify(i))}function Fv(t){const e=process.env.PATH;if(e)for(const n of e.split(_.delimiter)){if(n==="")continue;const i=_.join(n,t);try{return j.accessSync(i,j.constants.X_OK),i}catch{}}}function Bv(t){return ke.createHash("sha256").update(j.readFileSync(t)).digest("hex")}function Kv(t,e){let n=_.dirname(t);for(let i=0;i<8;i++){const o=_.join(n,"node_modules",e,"package.json");if(j.existsSync(o))try{return JSON.parse(j.readFileSync(o,"utf8")).version}catch{return}const r=_.dirname(n);if(r===n)break;n=r}}function Wd(t){const{command:e,identity:n}=t;if(e==="")return;const i=_.isAbsolute(e)?e:Fv(e)??e,o=n.kind==="package"?`package ${n.name??""}@${n.version??""}`:`sha256 ${n.sha256??"(unspecified)"}`;if(!j.existsSync(i))throw new Ye(o,"missing",i);try{j.accessSync(i,j.constants.X_OK)}catch{throw new Ye(o,"not executable",i)}if(!_.isAbsolute(i))throw new Ye(o,"not found on PATH",i);if(n.kind==="path"&&n.sha256){const r=Bv(i);if(r!==n.sha256)throw new Ye(`sha256:${n.sha256}`,`sha256:${r}`,i)}else if(n.kind==="package"&&n.name&&n.version){const r=Kv(i,n.name)??"(unknown)";if(r!==n.version)throw new Ye(`version ${n.version}`,`version ${r}`,i)}}function Jd(t,e,n){const i=Math.min(e.maxMs,e.baseMs*2**t);return Math.floor(n()*i)}class zd{constructor(e){this.failures=0,this.probing=!1,this.failureThreshold=e.failureThreshold,this.resetMs=e.resetMs,this.now=e.now??(()=>Date.now())}state(){return this.openedAt===void 0?"closed":this.now()-this.openedAt>=this.resetMs?"half-open":"open"}tryPass(){const e=this.state();return e==="open"?!1:(e==="half-open"&&(this.probing=!0),!0)}onSuccess(){this.failures=0,this.openedAt=void 0,this.probing=!1}onFailure(){this.failures+=1,(this.probing||this.failures>=this.failureThreshold)&&(this.openedAt=this.now()),this.probing=!1}}async function Yd(t,e,n,i){const o=i.now();let r;for(let s=0;s<e.maxAttempts;s++){if(!n.tryPass())throw new Qe(n.state(),"circuit breaker open — refusing the attempt");if(i.now()-o>=e.budgetMs)throw new Qe("starting",`wall-clock budget ${e.budgetMs}ms exhausted after ${s} attempt(s)`);const a=s===0?Math.min(i.graceMs,e.budgetMs):e.maxMs;try{const c=await t(s,a);return n.onSuccess(),c}catch(c){if(r=c,n.onFailure(),s===e.maxAttempts-1)break;const d=Jd(s,e,i.rand);if(i.now()-o+d>e.budgetMs)break;await i.sleep(d)}}throw r instanceof Qe?r:new Qe(n.state(),r instanceof Error?r.message:String(r))}function Wo(t){if(!t.run)throw new Error(`@adhd/backlog: apigen plugin "${t.id}" declares no run() — cannot mount live`);return t.run}function Xd(){if(!process.env.VITEST)return;const t=()=>{},e={info:t,error:t,debug:t,fatal:t,warn:t,trace:t};return e.child=()=>e,e}const Os=["install","install-skill","serve"];function Hn(t){return t.filter(e=>e.kind==="action").map(e=>{const n=qe(e);return{id:e.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((e,n)=>e.id.localeCompare(n.id))}function qv(t){const e=t.filter(n=>{const i=n.cliPath[n.cliPath.length-1]??"";return Os.includes(i)||Os.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(e.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${e.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function Hv(t,e=[pn]){const n=Hn(t),i=new Set(n.map(r=>r.mcpTool)),o={host:"backlog",operations:t};for(const r of e){const s=r.capabilities.mount;if(s)for(const a of s.operations(o,void 0,void 0))i.add(qe(a).mcp.name)}return[...i].sort()}function Vv(t){return{id:`backlog/${t}`,host:"ts",namespace:{raw:"backlog",words:["backlog"]},path:[{raw:t,words:t.split("-")}],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function Qd(){return Bc.map(Vv).flatMap(t=>Hn([t])).sort((t,e)=>t.id.localeCompare(e.id))}function Gv(){const t=Fd(ct());if(!t)throw new Error(`@adhd/backlog: assertSurfaceIsReal cannot verify the surface — no valid baked IR artifact at ${ct()} (run "nx build backlog" first). Refusing to pass an unverifiable surface.`);const e=Hn(t),n=Qd(),i=new Set(e.map(c=>c.id)),o=new Set(n.map(c=>c.id)),r=[...o].filter(c=>!i.has(c)).sort(),s=[...i].filter(c=>!o.has(c)).sort();if(r.length===0&&s.length===0)return;const a=["@adhd/backlog: mounted-surface self-check failed — an advertised verb is not the surface the built package mounts."];throw r.length>0&&a.push(` advertised but absent from the built package (the \`enrich\` class): ${r.join(", ")}`),s.length>0&&a.push(` mounted but not in the pinned BACKLOG_VERBS list (split brain): ${s.join(", ")}`),new Error(a.join(`
|
|
259
|
+
`))}function Is(t){if(!t||typeof t!="object")return t;const e={},n=o=>{if(Array.isArray(o)){for(const s of o)n(s);return}if(!o||typeof o!="object")return;const r=o;for(const s of["definitions","$defs"]){const a=r[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,d]of Object.entries(a))c in e||(e[c]=d)}for(const[s,a]of Object.entries(r))s==="definitions"||s==="$defs"||n(a)};if(n(t),n(e),Object.keys(e).length===0)return t;const i=(o,r)=>{if(Array.isArray(o))return o.map(d=>i(d,r));if(!o||typeof o!="object")return o;const s=o,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return r.has(d)||!(d in e)?{}:i(e[d],new Set([...r,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=i(l,r));return c};return i(t,new Set)}async function Wv(t={}){const e=ct(),n=_.join(e,"api.d.ts");if(!j.existsSync(n))throw new Error(`@adhd/backlog: cannot mount — ${n} does not exist. Run "nx build backlog" first (the mounted surface is derived from the built .d.ts).`);const i=Fd(e);return i||(await Promise.resolve().then(()=>wl)).extractApiOperationsLive(t)}async function Di(t,e={}){const n=typeof t=="function"?t:()=>t,i=await Wv(e),o={schemas:Object.fromEntries(i.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:Is(c.input),output:Is(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},r=nu(o,[]),s=Hn(i);qv(s);const{version:a}=Li();return{pkg:{id:"backlog",version:a,schemas:r,importPath:_.join(ct(),"api.js"),fns:vv,createClient:async()=>n()},operations:i,surface:s}}async function Rn(t){const e=et({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace});e.ensureDirs();const n=Gd(t,e);Wd(n.server);const i=Kd(),o=()=>{var f;return(f=t.onStateChange)==null?void 0:f.call(t,i.report())},r=new AbortController;t.signal.aborted?r.abort():t.signal.addEventListener("abort",()=>r.abort(),{once:!0});let s,a;const c=tt(e),d=()=>(s||(s=Po(a)),s),l=am()?void 0:tc(d);try{a=await yn(c,e.config.db.busyTimeoutMs)}catch(f){throw l==null||l.dispose(),f}const u={store:a,env:e,embeddingConfig:$v({baseline:e,rebuild:()=>et({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace}),layerFiles:()=>Bd({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace}),log:(f,m)=>console.error(m)})};try{const{pkg:f,operations:m}=await Di(u,{adhdRoot:t.adhdRoot}),p=Xd(),g=[];!t.probeOnly&&(n.transport==="http"||n.transport==="both")&&g.push(Wo(ug)({packages:[f],outputDir:"",options:{port:n.port,host:n.host,usePlugins:[hg,pn]},signal:r.signal,operations:m,logger:p})),!t.probeOnly&&(n.transport==="mcp"||n.transport==="both")&&g.push(Wo(Ig)({packages:[f],outputDir:"",options:{transport:"stdio",usePlugins:[pn]},signal:r.signal,operations:m,logger:p})),i.markLive(),o();const y={maxAttempts:n.connect.maxAttempts,baseMs:n.connect.baseMs,maxMs:n.connect.maxMs,budgetMs:n.connect.budgetMs,breakerFailureThreshold:n.connect.breakerFailureThreshold,breakerResetMs:n.connect.breakerResetMs},w=new zd({failureThreshold:n.connect.breakerFailureThreshold,resetMs:n.connect.breakerResetMs}),v={pkg:f,operations:m,store:a};let b;try{b=await Yd(async(N,k)=>{var A;const R=await qd(v,{timeoutMs:Math.min(k,n.readiness.timeoutMs)});if(!R.ready)throw new Qe("starting",((A=R.failure)==null?void 0:A.message)??"serving-path probe not ready");return R},y,w,{graceMs:n.connect.graceMs,rand:Math.random,now:Date.now,sleep:N=>new Promise(k=>setTimeout(k,N))})}catch(N){b={ready:!1,failure:{kind:"readiness",code:"probe_unavailable",message:N instanceof Error?N.message:String(N)}}}b.ready?i.markReady():b.failure&&i.fail(b.failure),o();const h=Promise.all(g);let S;const E=()=>(S||(r.abort(),S=(async()=>{try{await h}catch{}l==null||l.dispose(),await d()})()),S);return{report:()=>i.report(),whenReady:()=>i.whenReady(),whenClosed:async()=>{try{await h}finally{await E()}},close:E}}catch(f){throw r.abort(),l==null||l.dispose(),await d(),f}}async function Jv(t){await(await Rn(t)).whenClosed()}const it=["claude","codex","opencode"],zv={claude:".claude",codex:".codex",opencode:".opencode"};function Zd(t,e){return e?_.join(t,".codex"):process.env.CODEX_HOME??_.join(t,".codex")}function Yv(t,e,n,i){if(e==="project")return _.join(n,zv[t],"skills");const o=i??te.homedir();return t==="claude"?_.join(o,".claude","skills"):t==="codex"?_.join(Zd(o,i),"skills"):_.join(o,".config","opencode","skills")}function Xv(){const t=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),e=_.join(t,"skill","SKILL.md");return j.existsSync(e)?e:_.join(t,"..","skill","SKILL.md")}class oe extends Error{constructor(e){super(e),this.name="BacklogUsageError"}}function Mi(t,e){console.error(JSON.stringify({code:"invalid_argument",message:t.message})),console.error(""),console.error(e),process.exitCode=2}const $s=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
|
|
223
260
|
|
|
224
261
|
Copies the packaged backlog SKILL.md into an agent host's skills directory.
|
|
225
262
|
(\`backlog install\` is the richer successor — it also registers the MCP server.)
|
|
@@ -233,16 +270,16 @@ Examples:
|
|
|
233
270
|
backlog install-skill
|
|
234
271
|
backlog install-skill --host opencode --scope user
|
|
235
272
|
backlog install-skill --host claude --scope project
|
|
236
|
-
`;function
|
|
237
|
-
`,"utf8"),l.push({host:u,scope:
|
|
238
|
-
`,"utf8")}function
|
|
239
|
-
`):[],
|
|
273
|
+
`;function Qv(t){let e="all",n="user";for(let o=0;o<t.length;o++){const r=t[o];if(r==="--host")e=t[++o]??"all";else if(r==="--scope")n=t[++o]??"user";else throw new oe(`backlog install-skill: unknown argument "${r}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new oe(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const i=e==="all"?[...it]:[e];for(const o of i)if(!it.includes(o))throw new oe(`backlog install-skill: --host must be one of ${it.join("|")}|all, got "${e}"`);return{hosts:i,scope:n}}function el(t,e=process.cwd(),n){const{hosts:i,scope:o}=Qv(t);return tl(i,o,e,n)}function tl(t,e,n,i){const o=Xv();if(!j.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const r=j.readFileSync(o,"utf8"),s=_.dirname(Ct.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)),a=_.join(s,"package.json"),c=j.existsSync(a)?a:_.join(s,"..","package.json"),d=JSON.parse(j.readFileSync(c,"utf8")),l=[];for(const u of t){const f=_.join(Yv(u,e,n,i),"backlog");j.mkdirSync(f,{recursive:!0});const m=_.join(f,"SKILL.md");j.writeFileSync(m,r,"utf8"),j.writeFileSync(_.join(f,"extension.json"),JSON.stringify({name:d.name,version:d.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
|
|
274
|
+
`,"utf8"),l.push({host:u,scope:e,path:m})}return l}async function nl(t){if(t.includes("--help")||t.includes("-h")){console.log($s);return}let e;try{e=el(t)}catch(n){if(n instanceof oe)return Mi(n,$s);throw n}console.log(JSON.stringify({installed:e}))}const xi=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Zv(t){if(!j.existsSync(t))return{};const e=j.readFileSync(t,"utf8").trim();if(e==="")return{};const n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${t} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function ol(t,e,n,i){const o=Zv(t),r=o[e],s=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{};s[n]=i,o[e]=s,j.mkdirSync(_.dirname(t),{recursive:!0}),j.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
275
|
+
`,"utf8")}function eb(t,e,n){if(t==="project")return _.join(e,".mcp.json");const i=te.homedir();return _.join(i,".claude.json")}function tb(t,e,n){if(t==="project")return _.join(e,"opencode.json");const i=te.homedir();return _.join(i,".config","opencode","opencode.json")}function nb(t,e,n){if(t==="project")return _.join(e,".codex","config.toml");const i=te.homedir();return _.join(Zd(i,n),"config.toml")}function ob(t,e,n){var d,l;const i=`[${e}]`,o=t.length>0?t.split(`
|
|
276
|
+
`):[],r=o.findIndex(u=>u.trim()===i),s=[i,...n];if(r===-1){if(o.length===0||o.every(u=>u.trim()===""))return s.join(`
|
|
240
277
|
`)+`
|
|
241
278
|
`;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
|
|
242
279
|
`)+`
|
|
243
|
-
`}let a=
|
|
280
|
+
`}let a=r+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,r),...s,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
|
|
244
281
|
`)+`
|
|
245
|
-
`}function
|
|
282
|
+
`}function ib(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}function rb(t,e,n){const i=eb(t,e),o={type:"stdio",command:"npx",args:[...xi]};return Ui(o,i),ol(i,"mcpServers","backlog",o),{host:"claude",scope:t,configPath:i,status:"written"}}function sb(t,e,n){const i=tb(t,e),o={type:"local",command:["npx",...xi]};return Ui(o,i),ol(i,"mcp","backlog",o),{host:"opencode",scope:t,configPath:i,status:"written"}}function ab(t,e,n){const i=nb(t,e,n),o=j.existsSync(i)?j.readFileSync(i,"utf8"):"",r=ob(o,"mcp_servers.backlog",['command = "npx"',`args = ${ib(xi)}`]);return j.mkdirSync(_.dirname(i),{recursive:!0}),j.writeFileSync(i,r,"utf8"),{host:"codex",scope:t,configPath:i,status:"written"}}function cb(t,e,n,i){return t==="claude"?rb(e,n):t==="opencode"?sb(e,n):ab(e,n,i)}function db(t,e){let n="all",i="user",o=!1,r=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--host")n=t[++a]??"all";else if(c==="--scope")i=t[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")r=!0;else throw new oe(`backlog ${e}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&r)throw new oe(`backlog ${e}: --skill-only and --mcp-only are mutually exclusive`);if(i!=="user"&&i!=="project"){const a=i==="global"?' — the machine-wide scope is spelled "user"':"";throw new oe(`backlog ${e}: --scope must be "user" or "project", got "${i}"${a}`)}const s=n==="all"?[...it]:[n];for(const a of s)if(!it.includes(a))throw new oe(`backlog ${e}: --host must be one of ${it.join("|")}|all, got "${n}"`);return{hosts:s,scope:i,skillOnly:o,mcpOnly:r}}const Cs=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
|
|
246
283
|
|
|
247
284
|
Installs the backlog skill AND registers the backlog MCP server into an agent
|
|
248
285
|
host's config, in one step.
|
|
@@ -259,26 +296,37 @@ Examples:
|
|
|
259
296
|
|
|
260
297
|
Back-compat: \`backlog install-skill\` remains available and behaves exactly
|
|
261
298
|
like \`backlog install --skill-only\` (original --host/--scope grammar only).
|
|
262
|
-
`;function
|
|
299
|
+
`;function lb(t,e=process.cwd(),n){const{hosts:i,scope:o,skillOnly:r,mcpOnly:s}=db(t,"install"),a=s?[]:tl(i,o,e,n),c=r?[]:i.map(d=>cb(d,o,e,n));return{skill:a,mcp:c}}async function ub(t){if(t.includes("--help")||t.includes("-h")){console.log(Cs);return}let e;try{e=lb(t)}catch(n){if(n instanceof oe)return Mi(n,Cs);throw n}for(const n of e.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of e.mcp){const i=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${i}`)}console.log(JSON.stringify(e))}const Ps=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
|
|
263
300
|
|
|
264
301
|
Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
|
|
265
302
|
process's own configured transports to the way an agent host or a script
|
|
266
303
|
expects to reach it.
|
|
267
304
|
|
|
268
|
-
--transport <name> mcp | http | both (default:
|
|
269
|
-
|
|
270
|
-
--
|
|
305
|
+
--transport <name> mcp | http | both (default: from ADHD_BACKLOG_SERVICE_TRANSPORT
|
|
306
|
+
/ the service.* config, else mcp)
|
|
307
|
+
--port <N> HTTP listen port (default: from ADHD_BACKLOG_SERVICE_PORT
|
|
308
|
+
/ the service.* config, else 3300; ignored for mcp-only)
|
|
309
|
+
--host <name> HTTP listen host (default: from ADHD_BACKLOG_SERVICE_HOST
|
|
310
|
+
/ the service.* config, else 127.0.0.1; ignored for mcp-only)
|
|
311
|
+
--ready-file <path> Write the service report to <path> once the server is
|
|
312
|
+
READY (the serving path answered), atomically, and
|
|
313
|
+
again on every state change.
|
|
314
|
+
--probe Run the serving-path readiness probe once, print the
|
|
315
|
+
report as JSON, and exit 0 (ready) / 1 (not ready).
|
|
271
316
|
|
|
272
317
|
Examples:
|
|
273
318
|
backlog serve
|
|
274
319
|
backlog serve --transport http --port 3300
|
|
275
320
|
backlog serve --transport both --host 0.0.0.0
|
|
276
|
-
|
|
277
|
-
|
|
321
|
+
backlog serve --transport mcp --ready-file /run/backlog/ready.json
|
|
322
|
+
backlog serve --probe
|
|
323
|
+
`;function fb(t){let e,n,i,o,r=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--transport")e=t[++a];else if(c==="--port")n=Number(t[++a]);else if(c==="--host")i=t[++a];else if(c==="--ready-file")o=t[++a];else if(c==="--probe")r=!0;else throw new oe(`backlog serve: unknown argument "${c}" (expected --transport/--port/--host/--ready-file/--probe)`)}if(e!==void 0&&e!=="mcp"&&e!=="http"&&e!=="both")throw new oe(`backlog serve: --transport must be mcp|http|both, got "${e}"`);const s={probe:r};return e!==void 0&&(s.transport=e),n!==void 0&&(s.port=n),i!==void 0&&(s.host=i),o!==void 0&&(s.readyFile=o),s}function pb(t,e){j.mkdirSync(_.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;j.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
324
|
+
`,"utf8"),j.renameSync(n,e)}async function il(t,e={}){if(t.includes("--help")||t.includes("-h")){console.log(Ps);return}let n;try{n=fb(t)}catch(d){if(d instanceof oe)return Mi(d,Ps);throw d}const i=new AbortController;process.on("SIGTERM",()=>i.abort()),process.on("SIGINT",()=>i.abort());const o={...n.transport!==void 0?{transport:n.transport}:{},...n.port!==void 0?{port:n.port}:{},...n.host!==void 0?{host:n.host}:{},...e,signal:i.signal};if(n.probe){const d=await Rn({...o,probeOnly:!0}),l=d.report();console.log(JSON.stringify(l)),await d.close(),l.state!=="ready"&&(process.exitCode=1);return}const r=n.readyFile,s=Rn({...o,...r!==void 0?{onStateChange:d=>{try{pb(d,r)}catch(l){console.error(`[backlog] WARNING: failed to write --ready-file ${r}: ${l instanceof Error?l.message:String(l)}`)}}}:{}}),a=e.namespace==="sandbox"?j.mkdtempSync(_.join(te.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Jo.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...a!==void 0?{logDir:a}:{}})}catch(d){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${d instanceof Error?d.message:String(d)}); telemetry records will be silently dropped this process`)}const c=await s;try{await c.whenClosed()}finally{await c.close()}}const mb=["input","data"];function gb(t){let e;for(let n=0;n<t.length;n++){const i=t[n];if(i!==void 0)if(i==="--input"){const o=t[n+1];o!==void 0&&(e=o)}else i.startsWith("--input=")&&(e=i.slice(8))}return e}function hb(t){let e;try{e=JSON.parse(t)}catch{return}if(!(e===null||typeof e!="object"||Array.isArray(e)))return e}function yb(t,e){let n=0;for(;n<t.length&&t[n]!==void 0&&!t[n].startsWith("-");)n++;for(let i=n;i>=1;i--){const o=t.slice(0,i).join(" ");for(const r of e){const s=qe(r).cli.path;if(s.join(" ")===o)return{op:r,path:s}}}}function wb(t,e){var a,c,d;const n=(a=t.path[t.path.length-1])==null?void 0:a.raw;if(!n)return;const i=e[n];if(!i)return;const o=i.input,r=(c=o.properties)==null?void 0:c.data,s=(d=r==null?void 0:r.properties)==null?void 0:d.input;if(s)return{schema:s,root:o}}function vb(t,e,n){if(t.includes("--help")||t.includes("-h"))return;const i=gb(t);if(i===void 0)return;const o=hb(i);if(!o)return;const r=yb(t,e);if(!r)return;const s=wb(r.op,n),a=(s==null?void 0:s.schema.properties)??{},c=mb.filter(d=>Object.prototype.hasOwnProperty.call(o,d)&&!Object.prototype.hasOwnProperty.call(a,d));if(c.length!==0)return{wrapperKeys:[...c],commandLabel:r.path.join(" "),exampleJson:s?JSON.stringify(rt(s.schema,s.root)):void 0}}function bb(t){const e=t.wrapperKeys.map(i=>`"${i}"`).join(" and "),n=t.exampleJson??"{ …the params… }";return`--input expects the CLI's bare params object, but was given the MCP envelope shape (a top-level ${e} wrapper). The CLI never wraps params in an "input"/"data" object — that envelope is the MCP calling convention (mcp__backlog__*) and does not apply here. Pass the params directly, e.g. ${t.commandLabel} --input '${n}'`}const Fi=["limit","offset","sort","direction"],rl=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],Bi=["status","priority"],Vn=["fields"],Eb={"claimed-by":"claimedBy","project-path":"projectPath"},sl=[...Fi,...Vn,...rl,...Bi].map(t=>`--${t}`).sort(),Sb=new Set([...Fi,...Vn]),kb=new Set([...Bi,...Vn]),_b=new Set([...Fi,...Vn,...rl,...Bi]),Ab=new Set(["limit","offset"]),al=['backlog search "<natural-language query>" [flags]',"",'Shorthand for `backlog query --input \'{"text": "<query>", ...}\'` — the same',"command, the same JSON envelope, the same exit codes. The query text is","matched semantically when the embedding space is populated, and by keyword","(FTS) when it is not.","","Paging / ranking:"," --limit <n> max items to return"," --offset <n> skip the first n"," --sort <s> override the derived default (relevance / textMatch)"," --direction <d> asc | desc"," --fields <a,b,c> projection; add _score to see ranking scores","","Filters (all compose with the query text):"," --status <s> open | closed | OPEN,IN_PROGRESS | …"," --priority <p> CRITICAL | HIGH | MEDIUM | LOW (comma-separated for several)"," --kind <k> BUG | DEBT | FEAT | …"," --project-path <p> component's repo-relative path (component.meta.path)"," --plan <uid|title> the parent plan issue this item is filed under (part_of)"," --assignee <a> durable owner"," --claimed-by <c> ephemeral claim holder"," --grep <q> extra keyword predicate. Composes with the query text ONLY"," once the embedding space is populated — without it the query"," text IS the keyword query and the two collide (§2.1b step 1).","","More-like-this:",' --anchor <ID> nearest neighbours of an EXISTING item (view:"similar").'," Replaces the positional query rather than refining it."].join(`
|
|
325
|
+
`);function Ls(t,e,n,i){if(!i){t[e]=n;return}const o=t[e]??[];t[e]=[...o,...n.split(",").map(r=>r.trim()).filter(r=>r.length>0)]}function cl(t){if(t.includes("--help")||t.includes("-h"))return{kind:"help",text:al};const e={},n={};let i,o=0;for(;o<t.length;){const a=t[o];if(!a.startsWith("--")){if(i!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};i=a,o+=1;continue}let c=a.slice(2),d;const l=c.indexOf("=");if(l!==-1&&(d=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!_b.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${sl.join(", ")}`};o+=1;let u;if(d!==void 0)u=d;else{if(o>=t.length)return{kind:"error",message:`Missing value for --${c}`};u=t[o],o+=1}const f=kb.has(c);Sb.has(c)?Ls(e,c,u,f):Ls(n,Eb[c]??c,u,f)}for(const a of["status","priority"]){const c=n[a];(c==null?void 0:c.length)===1&&(n[a]=c[0])}for(const a of Ab){const c=e[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(e[a]=Number(c))}const r=n.anchor;if(r!==void 0&&i!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(r===void 0&&i===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const s={...e};return r!==void 0?s.view="similar":s.text=i,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function dl(t){const e=t.find(n=>n.kind==="action");if(!e)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return qe(e).cli.path.slice(0,-1)}const Us=[pn];function Nb(t,e,n){const i={host:n,operations:e},o=new Set;for(const r of t){const s=r.capabilities.mount;if(!s)continue;const a=s.operations(i,void 0,void 0);for(const c of a){const[d]=qe(c).cli.path;d!==void 0&&o.add(d)}}return o}function ll(t,e,n){var o;return t.length===0?[...t]:(o=t[0])!=null&&o.startsWith("-")?[...t]:t[0]!==void 0&&n.has(t[0])?[...t]:e.length>0&&e.every((r,s)=>t[s]===r)?[...t]:[...e,...t]}function Ki(t){const e=[],n=[];let i=!1;for(let r=0;r<t.length;r++){const s=t[r];if(s!==void 0){if(s.startsWith("--namespace=")){const a=s.slice(12);a===""?i=!0:e.push(a);continue}if(s==="--namespace"){const a=t[r+1];a===void 0||a.startsWith("-")?i=!0:(e.push(a),r++);continue}n.push(s)}}const o=new Set(e);return{argv:n,namespace:e[e.length-1],missingValue:i,conflicting:o.size>1}}async function Rb(t){let e;for(let s=0;s<t.length;s++){const a=t[s];if(a!==void 0){if(a==="--out"||a==="-o"){const c=t[s+1];c!==void 0&&!c.startsWith("-")&&(e=c,s++)}else if(a.startsWith("--out=")){const c=a.slice(6);c!==""&&(e=c)}}}if(!e){const s=ne("invalid_argument","ir-artifact: --out <path> is required");console.error(JSON.stringify(s)),process.exitCode=je(s);return}const n=_.join(ct(),"api.d.ts");if(!j.existsSync(n)){const s=ne("internal",`ir-artifact: ${n} does not exist — run "nx build backlog" first`);console.error(JSON.stringify(s)),process.exitCode=je(s);return}const i=_.resolve(e),{buildBakedOperations:o}=await Promise.resolve().then(()=>wl),r=await o(n);await Tv({apiDts:n,outFile:i,extractorVersion:Ci,operations:r}),console.log(JSON.stringify({ok:!0,out:i,operations:r.length}))}async function ul(t,e={}){var y;const{argv:n,namespace:i,missingValue:o,conflicting:r}=Ki(t??process.argv.slice(2)),s={...e};if(o){const w=ne("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(w)),process.exitCode=je(w);return}if(r){const w=t??process.argv.slice(2),v=new Set;for(let h=0;h<w.length;h++){const S=w[h];S!==void 0&&(S.startsWith("--namespace=")?v.add(S.slice(12)):S==="--namespace"&&w[h+1]!==void 0&&v.add(w[h+1]))}const b=ne("invalid_argument",`Invalid argument "namespace": conflicting values ${[...v].map(h=>`"${h}"`).join(", ")}`);console.log(JSON.stringify(b)),process.exitCode=je(b);return}if(i!==void 0&&!((y=Ie.namespaces)!=null&&y.includes(i))){const w=Ie.namespaces??[],v=Ni(i,w),b=`must be one of ${w.map(S=>`"${S}"`).join(", ")}`+(v.length>0?` (did you mean ${v.map(S=>`"${S}"`).join(" or ")}?)`:""),h=ne("invalid_argument",`Invalid argument "namespace": ${b}`);console.log(JSON.stringify(h)),process.exitCode=je(h);return}i!==void 0&&(s.namespace=i);const a=s.namespace??"production";s.adhdRoot===void 0&&process.env.ADHD_ROOT&&(s.adhdRoot=process.env.ADHD_ROOT);const c=w=>w.includes(`${_.sep}backlog-sandbox-`);if(a==="sandbox"){s.adhdRoot!==void 0&&!c(s.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${s.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),s.adhdRoot=void 0),s.adhdRoot===void 0&&(s.adhdRoot=j.mkdtempSync(_.join(te.tmpdir(),"backlog-sandbox-")),console.error(`[backlog] --namespace sandbox: isolated store at ${s.adhdRoot} (not auto-deleted — pass ADHD_ROOT=${s.adhdRoot} to reuse it, or remove it yourself when done)`)),s.namespace="sandbox";const w=_.join(s.adhdRoot,"backlog","sandbox");j.mkdirSync(w,{recursive:!0}),j.writeFileSync(_.join(w,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
|
|
278
326
|
# an absence-of-file default. embedding.enabled is off so a sandboxed
|
|
279
327
|
# run never pays a real model-load cost or opens a real vector store.
|
|
280
328
|
embedding:
|
|
281
329
|
enabled: false
|
|
282
|
-
`)}if(s.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=
|
|
330
|
+
`)}if(s.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=_.join(s.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:tt(w),embeddingEnabled:w.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await Rb(n.slice(1));return}if(n[0]==="store-check"){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});w.ensureDirs();const v=tt(w);let b;try{b=await yn(v,w.config.db.busyTimeoutMs),await Vc(b.adapter);const{total:h,observed:S}=await Ra(b.adapter);console.log(JSON.stringify({ok:!0,dbPath:v,total:h,kinds:S,expectedKinds:[...fi]}));return}catch(h){if(h instanceof Na){console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"store_vocabulary_mismatch",message:h.message},observed:h.observed,expectedKinds:h.recognized})),process.exitCode=1;return}if(h instanceof Hc){console.error(h.message),console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"catalog_invariant_violation",message:h.message},violations:h.violations})),process.exitCode=1;return}throw h}finally{b&&await Po(b)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present, and assert the status/priority catalog invariants; non-zero on a mismatch or a catalog violation"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await nl(n.slice(1));return}if(n[0]==="install"){await ub(n.slice(1));return}if(n[0]==="serve"){await il(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(Li()));return}let l;if(n[0]==="search"){const w=cl(n.slice(1));if(w.kind==="help"){console.log(w.text);return}if(w.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:w.message})),process.exitCode=2;return}l=w.argv}let u;const f=async()=>{if(!u){const w=et({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});w.ensureDirs();const v=await yn(tt(w),w.config.db.busyTimeoutMs);u={store:v,ctx:{store:v,env:w}}}return u.ctx};let m;const p=()=>(m||(m=Po(u==null?void 0:u.store)),m),g=tc(p);try{const{pkg:w,operations:v}=await Di(f,{adhdRoot:s.adhdRoot}),b=l??n,h=dl(v),S=Nb(Us,v,w.id),E=ll(b,h,S),N=vb(E,v,w.schemas);if(N){const R=ne("invalid_argument",bb(N));console.error(JSON.stringify(R)),process.exitCode=je(R);return}await Wo(lp)({packages:[w],operations:v,outputDir:"",options:{argv:E,usePlugins:[...Us],exitCode:R=>xc(R)?je(R):void 0},signal:s.signal??new AbortController().signal,logger:Xd()});const k=b.length>1&&b[0]!=="batch"&&(b.includes("--help")||b.includes("-h"));k&&console.log("See also: `adhd-backlog batch action` — run this SAME operation over many items in one call instead of N one-at-a-time invocations (skill/SKILL.md §5)."),k&&b[0]==="query"&&console.log(`Notes:
|
|
283
331
|
- view:"similar" additionally requires filter.anchor (uid of the reference issue) OR filter.semantic (free text) — neither given throws invalid_argument.
|
|
284
|
-
- view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{g.dispose(),await p()}}function 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;
|
|
332
|
+
- view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{g.dispose(),await p()}}const fl="spec_of_seq",jb=`CREATE INDEX IF NOT EXISTS ${fl} ON node (json_extract(meta,'$.spec_of'), json_extract(meta,'$.revision_seq'))`,Tb="sha256:";function Ds(t){if(t)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}const Ms=["normal","raw-kind-only"];function Ob(){const t=process.env.ADHD_BACKLOG_UNSAFE_SPEC_RECONCILE;if(t===void 0)return"normal";if(Ms.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_SPEC_RECONCILE="${t}" is not a recognized mode (expected ${Ms.join(", ")}). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting.`)}async function Ib(t,e){return e==="raw-kind-only"?t.graph.queryNodes({kind:"SPEC",liveOnly:!0}):Rc(t.graph)}async function pl(t){var c;const e=await Ib(t,Ob()),n=new Map,i=[];for(const d of e){const u=(c=(await t.graph.getEdges({src:d.id,rel:"part_of"}))[0])==null?void 0:c.dst,[f]=u===void 0?[]:await t.graph.getNodesByIds([u]);if(!f||f.tInvalid){i.push(d.uid);continue}const m=n.get(f.uid)??{parent:f,specs:[]};m.specs.push(d),n.set(f.uid,m)}const o=[],r=[];let s=0;for(const{parent:d,specs:l}of n.values()){const u=await gc(t.graph,d.uid),f=[...l].sort((g,y)=>g.tCreated.localeCompare(y.tCreated));let m="",p=null;f.forEach((g,y)=>{var h,S,E,N,k;const w=y+1;m=`${m}${g.content}`;const v=`${Tb}${He(m)}`,b=!(((h=g.metadata)==null?void 0:h.spec_of)===u.uid&&((S=g.metadata)==null?void 0:S.revision_seq)===w&&((E=g.metadata)==null?void 0:E.revision_token)===v);if(b||(s+=1),o.push({revisionUid:g.uid,specOf:u.uid,revisionSeq:w,prevRevision:p,revisionToken:v,needsStamp:b}),p=g.uid,y===f.length-1){const R=((N=d.metadata)==null?void 0:N.spec_revision)===g.uid&&((k=d.metadata)==null?void 0:k.spec_revision_token)===v;r.push({ticketUid:u.uid,revisionUid:g.uid,revisionToken:v,revisionSeq:w,needsPointer:!R})}})}let a=!1;try{const{rows:d}=await t.adapter.executeAll("PRAGMA index_list('node')");a=d.some(l=>String(l.name)===fl)}catch{a=!1}return{scanned:e.length,stamps:o,heads:r,alreadyStamped:s,orphaned:i,indexCreated:a}}async function $b(t){const e=await pl(t);return await M(t,async n=>{await n.executeRun(jb);const i=P();for(const o of e.stamps){if(!o.needsStamp)continue;const r=await n.executeGet("SELECT meta FROM node WHERE uid = ?",[o.revisionUid]);await $o(n,o.revisionUid,{spec_of:o.specOf,revision_seq:o.revisionSeq,prev_revision:o.prevRevision,revision_token:o.revisionToken,anchor:{locator:"",digest:o.revisionToken},appended_by:"spec-revision.reconcile",appended_at:i},$e(Ds((r==null?void 0:r.meta)??null)))}for(const o of e.heads){if(!o.needsPointer)continue;const r=await n.executeGet("SELECT meta FROM node WHERE uid = ?",[o.ticketUid]);await $o(n,o.ticketUid,{spec_revision:o.revisionUid,spec_revision_token:o.revisionToken,spec_revision_seq:o.revisionSeq},$e(Ds((r==null?void 0:r.meta)??null)))}}),{...e,indexCreated:!0}}function ml(t){switch(t){case"status":return"has_status";case"priority":return"has_priority";case"kind":return"has_kind"}}function gl(t){return new RegExp("\\p{L}","u").test(t)&&t===t.toUpperCase()}function Cb(t){return t===t.toLowerCase()}function hl(t,e){return t==="priority"?gl(e):Cb(e)}function xs(t){if(t===null)return{};try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:{}}catch{return{}}}function Fs(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):[]}async function Bs(t,e){return await t.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ? AND t_invalid IS NULL",[e])??null}async function so(t,e){return await t.executeGet("SELECT rowid, uid, kind, name, meta FROM node WHERE uid = ?",[e])??null}function Pb(t,e,n=[]){const i=[],o=[],r=[["kind",n],["status",t],["priority",e]];for(const[s,a]of r){const c=new Map;for(const d of a){const l=F(d.name??""),u=c.get(l);u?u.push(d):c.set(l,[d])}for(const d of c.values()){if(d.length<2)continue;const l=[...d].sort((p,g)=>p.id-g.id),u=l.find(p=>hl(s,p.name??""));if(u===void 0&&(s==="status"||s==="kind")){o.push({kind:s,names:l.map(p=>p.name??"")});continue}const f=u??l[0],m=l.filter(p=>p.uid!==f.uid).map(p=>p.uid);m.length!==0&&i.push({canonicalUid:f.uid,fragmentUids:m})}}return{groups:i,unmergeable:o,at:P()}}function yl(t,e){if(t!=="status"&&t!=="priority"&&t!=="kind")throw new Error(`applyCaseFragmentMerge: uid ${e} is kind "${t}" — only "status"/"priority"/"kind" catalog rows are mergeable.`)}async function Lb(t,e){return M(t,async n=>{const i=[];for(const o of e.groups){const r=await Bs(n,o.canonicalUid);if(!r)continue;yl(r.kind,r.uid);const s=ml(r.kind),a=await q(n,s),c=F(r.name??""),d=xs(r.meta),l=r.name??"";if((r.kind==="status"||r.kind==="kind")&&!hl(r.kind,l))throw new Error(`applyCaseFragmentMerge: refusing to merge into ${r.kind} uid ${r.uid} named "${l}" — a ${r.kind} canonical must carry the canonical lowercase spelling.`);const u=[];for(const h of o.fragmentUids){const S=await Bs(n,h);if(S&&S.rowid!==r.rowid){if(S.kind!==r.kind)throw new Error(`applyCaseFragmentMerge: refusing to merge uid ${S.uid} (kind "${S.kind}") into uid ${r.uid} (kind "${r.kind}") — kinds must match.`);if(F(S.name??"")!==c)throw new Error(`applyCaseFragmentMerge: refusing to merge "${S.name??""}" into "${r.name??""}" — not a case-variant of the same token (they do not fold together).`);u.push(S)}}if(u.length===0)continue;let f;const m=[];let p=d;if(r.kind==="priority"&&!gl(l)){const h=l.toUpperCase();h!==l&&(await n.executeRun("UPDATE node SET name = ? WHERE rowid = ? AND t_invalid IS NULL",[h,r.rowid]),f={uid:r.uid,from:l,to:h},l.length>0&&m.push(l))}for(const h of u){const S=xs(h.meta),E=typeof S.rank=="number"?S.rank:void 0,{rows:N}=await n.executeAll("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[h.rowid,s]),k=[];for(const A of N){await ie(n,{srcRowid:A.src,dstRowid:h.rowid,rel:s,reason:"catalog-case-fragment-merge",at:e.at});const O=await Q(n,A.src);O&&(await K(n,{at:e.at,srcRowid:A.src,srcUid:O.uid,srcKind:O.kind,dstRowid:r.rowid,dstUid:r.uid,dstKind:r.kind,rel:s,rule:a,typePolicy:t.typePolicy}),k.push({srcRowid:A.src,rel:s,fragmentDstRowid:h.rowid}))}(typeof p.rank=="number"?p.rank:void 0)===void 0&&E!==void 0&&(p={...p,rank:E});for(const A of[h.name??"",...Fs(S.aliases)])A.length>0&&m.push(A);await n.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[e.at,h.rowid]),i.push({fragmentUid:h.uid,canonicalUid:r.uid,fragmentMeta:S,repointedEdges:k,...E!==void 0?{retainedRank:E}:{},...f!==void 0?{renamed:f}:{},canonicalMetaBefore:d})}const g=f?f.to:l,w=[...Fs(p.aliases)];let v=!1;for(const h of m)h!==g&&(w.includes(h)||(w.push(h),v=!0));v&&(p={...p,aliases:w}),(v||p!==d)&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ? AND t_invalid IS NULL",[JSON.stringify(p),r.rowid])}return{entries:i,at:e.at}})}async function Ub(t,e){await M(t,async n=>{const i=P(),o=new Map;for(const r of e.entries)r.canonicalMetaBefore!==void 0&&!o.has(r.canonicalUid)&&o.set(r.canonicalUid,r.canonicalMetaBefore);for(const r of e.entries){const s=await so(n,r.fragmentUid),a=await so(n,r.canonicalUid);if(!s||!a)continue;yl(s.kind,s.uid);const c=ml(s.kind),d=await q(n,c);for(const l of r.repointedEdges){await ie(n,{srcRowid:l.srcRowid,dstRowid:a.rowid,rel:l.rel,reason:"catalog-case-fragment-merge-reverse",at:i});const u=await Q(n,l.srcRowid);u&&await K(n,{at:i,srcRowid:l.srcRowid,srcUid:u.uid,srcKind:u.kind,dstRowid:s.rowid,dstUid:s.uid,dstKind:s.kind,rel:l.rel,rule:d,typePolicy:t.typePolicy})}await n.executeRun("UPDATE node SET meta = ?, t_invalid = NULL WHERE rowid = ?",[JSON.stringify(r.fragmentMeta??{}),s.rowid])}for(const[r,s]of o){const a=await so(n,r);a&&await n.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(s??{}),a.rowid])}for(const r of e.entries)r.renamed&&await n.executeRun("UPDATE node SET name = ? WHERE uid = ?",[r.renamed.from,r.renamed.uid])})}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:B&&B.tagName.toUpperCase()==="SCRIPT"&&B.src||new URL("index.js",document.baseURI).href)===Ct.pathToFileURL(j.realpathSync(process.argv[1])).href){const{namespace:t,argv:e}=Ki(process.argv.slice(2)),n=e[0]==="ir-artifact",i=t==="sandbox"?j.mkdtempSync(_.join(te.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{Jo.initTelemetry({service:"backlog",role:"cli",logSink:"file",...i!==void 0?{logDir:i}:{}})}catch(o){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${o instanceof Error?o.message:String(o)}); telemetry records will be silently dropped this process`)}ul().catch(o=>{console.error(o instanceof Error?o.stack??o.message:String(o)),process.exitCode=1})}const Db=Ci,qi="backlog";function Hi(t,e){return{sourceFile:t,namespace:qi,tsconfig:e,dropFileSegment:!0}}function Mb(t={}){return Zm(t)}function xb(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function Fb(t={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:_v({cache:Mb(t),extractorVersion:Db})}}}}let Ks;function Bb(t={}){return Ks??(Ks=Vu(xb()?[Fb(t)]:[],e=>{var n;return da(Hi(e.source,typeof((n=e.extractorOptions)==null?void 0:n.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0))})),Ks}async function Kb(t){return da(Hi(t))}async function qb(t={}){const e=_.join(ct(),"api.d.ts");return Bb(t)({source:e,host:"ts",namespace:qi,extractorOptions:{}})}const wl=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:qi,buildBacklogExtractOptions:Hi,buildBakedOperations:Kb,extractApiOperationsLive:qb},Symbol.toStringTag,{value:"Module"}));exports.ArtifactDriftError=Ye;exports.BACKLOG_ERROR_CODES=Ti;exports.BACKLOG_EXIT_CODE=Oi;exports.CircuitBreaker=zd;exports.NonAbsolutePathError=qn;exports.RESERVED_TERMINAL_STATUS_NAMES=xt;exports.RagNotConfiguredError=Fc;exports.SEARCH_FLAGS=sl;exports.SEARCH_HELP=al;exports.SERVICE_CONFIG_KEYS=Go;exports.ServiceNotReadyError=Qe;exports.UnknownConfigKeyError=Hd;exports.UnknownMcpConfigKeyError=Vo;exports.addCitation=vd;exports.applyCaseFragmentMerge=Lb;exports.applySpecRevisionReconcile=$b;exports.applyTerminalBackfill=Bp;exports.assertMcpEntryValid=Ui;exports.assertServerArtifact=Wd;exports.assertSurfaceIsReal=Gv;exports.assertValidPredicate=wn;exports.attest=Sd;exports.backlogEnvironmentSpec=Ie;exports.buildBacklogApigenPackage=Di;exports.buildBacklogEnv=et;exports.buildSearchArgv=cl;exports.catalogNameFold=F;exports.claim=jd;exports.closeGraphBacklogStore=ec;exports.create=yd;exports.createBacklogServer=Rn;exports.createLifecycle=Kd;exports.delete=Id;exports.describeBacklogSurface=Qd;exports.embeddingStatus=gd;exports.errorEnvelope=ne;exports.evaluatePredicate=ue;exports.exitCodeForEnvelope=je;exports.fullJitterDelay=Jd;exports.get=dd;exports.installSkill=el;exports.isBacklogErrorCode=Mc;exports.isOutcomeEnvelope=xc;exports.isOutcomeError=iy;exports.isOutcomeOk=oy;exports.isPathResolvableBin=Vd;exports.lookup=hd;exports.mergeProject=Ud;exports.move=Od;exports.obligate=_d;exports.okEnvelope=Ii;exports.openCurve=pd;exports.openGraphBacklogStore=yn;exports.partOfRollup=fd;exports.planCaseFragmentMerge=Pb;exports.planSpecRevisionReconcile=pl;exports.planTerminalBackfill=Fp;exports.prefixCommand=ll;exports.priorityMatrix=ud;exports.probeReadiness=qd;exports.query=ld;exports.readBacklogVersionInfo=Li;exports.recheck=kd;exports.relate=Td;exports.removeCitation=bd;exports.report=md;exports.resolveBacklogDbPath=tt;exports.resolveBacklogScope=Pn;exports.resolveCommandPrefix=dl;exports.resolveExpectedMcpToolNames=Hv;exports.resolveServiceConfig=Gd;exports.reverseCaseFragmentMerge=Ub;exports.reverseTerminalBackfill=Kp;exports.rmLocation=Ld;exports.rmProject=Dd;exports.runBacklogCli=ul;exports.runInstallSkillCommand=nl;exports.runServeCommand=il;exports.specAppend=Nd;exports.specCheck=Rd;exports.startBacklogServer=Jv;exports.stripNamespaceFlag=Ki;exports.suggestClaimantIdentity=Qm;exports.transition=Ed;exports.unobligate=Ad;exports.update=wd;exports.upsertComponent=Cd;exports.upsertLocation=Pd;exports.upsertProject=$d;exports.withResilience=Yd;
|