@maind-dev/mcp-bridge 0.89.0 → 0.90.0

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/build/index.js CHANGED
@@ -1,45 +1,45 @@
1
1
  #!/usr/bin/env node
2
- var hp=Object.defineProperty;var o=(e,t)=>hp(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var n in t)hp(e,n,{get:t[n],enumerable:!0})};import{existsSync as qx,mkdirSync as Yx,readdirSync as Jx,readFileSync as Xx,renameSync as Zx,statSync as Qx,unlinkSync as eS,writeFileSync as tS}from"node:fs";import{homedir as nS}from"node:os";import{join as Xi}from"node:path";function Zi(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=Yi(r.id),s=Yi(r.key),a=Yi(r.title),c=Yi(r.status);if(!(!i||!s||!a||!c)&&(t.push({id:i,key:s,title:a,status:c}),t.length>=rS))break}return t}function Qi(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`).join(", "),n=e.length===1;return`Assigned to your user in this repository and not taken yet: ${t}. Their own agents may take ${n?"it":"these"} (take_work_object). Mention ${n?"it":"them"} to your user and offer to take ${n?"it":"one"} \u2014 do not start unasked.`}function gp(e=nS()){return Xi(e,".maind","assigned-told")}function yp(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function _p(e){try{let t=JSON.parse(Xx(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],checked_at:typeof t.checked_at=="number"?t.checked_at:0}}catch{return{ids:[],checked_at:0}}}function oS(e,t,n){Yx(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;tS(r,JSON.stringify(n),{mode:384}),Zx(r,t)}function bp(e,t,n=gp()){let r=Xi(n,`${yp(e)}.json`);return qx(r)?t-_p(r).checked_at<sS:!1}function Aa(e,t,n,r=gp()){try{let i=Xi(r,`${yp(e)}.json`),s=_p(i),a=t.filter(c=>!s.ids.includes(c.id));return oS(r,i,{ids:[...s.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),aS(r,n,i),a}catch{return[]}}function aS(e,t,n){try{for(let r of Jx(e)){let i=Xi(e,r);i!==n&&t-Qx(i).mtimeMs>iS&&eS(i)}}catch{}}function wp(e){return e==="claude-code"}var rS,iS,sS,Yi,Ji,jr=_(()=>{"use strict";rS=5,iS=7*24*60*60*1e3,sS=6e4,Yi=o(e=>typeof e=="string"&&e.length>0?e:null,"str");o(Zi,"parseAssignedList");o(Qi,"assignedNoticeText");o(gp,"assignedToldDir");o(yp,"safeName");o(_p,"readTold");o(oS,"writeTold");o(bp,"checkedRecently");o(Aa,"takeUntold");o(aS,"pruneTold");Ji=class{static{o(this,"AssignedInbox")}current=[];told=new Set;update(t){if(!t||typeof t!="object")return;let n=t;n.ok===!0&&(this.current=Zi(n.assigned_to_you))}takeNote(){let t=this.current.filter(n=>!this.told.has(n.id));for(let n of t)this.told.add(n.id);return Qi(t)}};o(wp,"clientHasHooks")});function kp(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Hn(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function Ca(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function Ia(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Na(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var Oa=_(()=>{"use strict";o(kp,"parseFrame");o(Hn,"denyResult");o(Ca,"toolEvent");o(Ia,"policyEvent");o(Na,"shaEvent")});import{execFileSync as Ep}from"node:child_process";function Tp(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=fS}function mS(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let s of dS){let a=r[s];typeof a=="string"&&xp.test(a)&&i.push({field:s,sha:a})}for(let[s,a]of uS){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&xp.test(l)&&i.push({field:`${s}.${a}`,sha:l})}return i}function hS(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,Sp);for(let i=Sp;i>=pS;i--){let s=r.slice(0,i),a=t(s);if(a!==null&&a.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Bn(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Ap(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete e[t];return e}function es(e=process.cwd()){try{let n=Ep("git",["rev-parse","--show-toplevel"],{cwd:e,env:Ap(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function gS(e){return t=>{try{let r=Ep("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Ap(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function ts(e,t){if(t===null)return[];let n=mS(e);if(n.length===0)return[];let r=gS(t),i=[];for(let{field:s,sha:a}of n){let c=hS(a,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var dS,uS,xp,pS,Sp,fS,Da=_(()=>{"use strict";dS=["commit_sha","base_sha","head_sha"],uS=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],xp=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,pS=7,Sp=12,fS=10;o(Tp,"isDenyGrade");o(mS,"extractShaArgs");o(hS,"classifySha");o(Bn,"shaFindingText");o(Ap,"cleanGitEnv");o(es,"resolveRepoRootForSha");o(gS,"gitShaResolver");o(ts,"inspectLineForShas")});var Cp=_(()=>{"use strict"});var L,Ma,R,Be,Ur=_(()=>{(function(e){e.assertEqual=i=>{};function t(i){}o(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ma||(Ma={}));R=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Be=o(e=>{switch(typeof e){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(e)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(e)?R.array:e===null?R.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?R.promise:typeof Map<"u"&&e instanceof Map?R.map:typeof Set<"u"&&e instanceof Set?R.set:typeof Date<"u"&&e instanceof Date?R.date:R.object;default:return R.unknown}},"getParsedType")});var E,yS,fe,ns=_(()=>{Ur();E=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),yS=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),fe=class e extends Error{static{o(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=o(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};fe.create=e=>new fe(e)});var _S,tt,$a=_(()=>{ns();Ur();_S=o((e,t)=>{let n;switch(e.code){case E.invalid_type:e.received===R.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case E.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case E.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},"errorMap"),tt=_S});function bS(e){Ip=e}function Gn(){return Ip}var Ip,rs=_(()=>{$a();Ip=tt;o(bS,"setErrorMap");o(Gn,"getErrorMap")});function A(e,t){let n=Gn(),r=Hr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===tt?void 0:tt].filter(i=>!!i)});e.common.issues.push(r)}var Hr,wS,te,D,Vt,ce,is,ss,_t,Wn,La=_(()=>{rs();$a();Hr=o(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),wS=[];o(A,"addIssueToContext");te=class e{static{o(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return D;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,a=await i.value;r.push({key:s,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return D;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),Vt=o(e=>({status:"dirty",value:e}),"DIRTY"),ce=o(e=>({status:"valid",value:e}),"OK"),is=o(e=>e.status==="aborted","isAborted"),ss=o(e=>e.status==="dirty","isDirty"),_t=o(e=>e.status==="valid","isValid"),Wn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Np=_(()=>{});var I,Op=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}))});function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:o((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function $p(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function LS(e){return new RegExp(`^${$p(e)}$`)}function Lp(e){let t=`${Mp}T${$p(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function FS(e,t){return!!((t==="v4"||!t)&&IS.test(e)||(t==="v6"||!t)&&OS.test(e))}function jS(e,t){if(!TS.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function US(e,t){return!!((t==="v4"||!t)&&NS.test(e)||(t==="v6"||!t)&&DS.test(e))}function HS(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function Kn(e){if(e instanceof me){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=we.create(Kn(r))}return new me({...e._def,shape:o(()=>t,"shape")})}else return e instanceof it?new it({...e._def,type:Kn(e.element)}):e instanceof we?we.create(Kn(e.unwrap())):e instanceof We?We.create(Kn(e.unwrap())):e instanceof Ge?Ge.create(e.items.map(t=>Kn(t))):e}function ja(e,t){let n=Be(e),r=Be(t);if(e===t)return{valid:!0,data:e};if(n===R.object&&r===R.object){let i=L.objectKeys(t),s=L.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of s){let l=ja(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===R.array&&r===R.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let a=e[s],c=t[s],l=ja(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===R.date&&r===R.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Fp(e,t){return new rn({values:e,typeName:P.ZodEnum,...M(t)})}function Pp(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function jp(e,t={},n){return e?wt.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){let c=Pp(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let a=Pp(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):wt.create()}var ve,Dp,$,vS,kS,xS,SS,ES,TS,AS,RS,CS,Fa,IS,NS,OS,DS,PS,MS,Mp,$S,bt,zt,qt,Yt,Jt,Vn,Xt,Zt,wt,rt,Oe,zn,it,me,Qt,nt,os,en,Ge,as,qn,Yn,cs,tn,nn,rn,sn,vt,ke,we,We,on,an,Jn,BS,Br,Gr,cn,GS,P,WS,Up,Hp,KS,VS,Bp,zS,qS,YS,JS,XS,ZS,QS,eE,tE,nE,rE,iE,sE,oE,aE,cE,lE,dE,uE,pE,fE,mE,hE,gE,yE,_E,bE,wE,vE,kE,xE,SE,EE,TE,Gp=_(()=>{ns();rs();Op();La();Ur();ve=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dp=o((e,t)=>{if(_t(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new fe(e.common.issues);return this._error=n,this._error}}},"handleResult");o(M,"processCreateParams");$=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return Be(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Be(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new te,ctx:{common:t.parent.common,data:t.data,parsedType:Be(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Wn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Be(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Dp(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Be(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return _t(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>_t(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Be(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(Wn(i)?i:Promise.resolve(i));return Dp(r,s)}refine(t,n){let r=o(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let a=t(i),c=o(()=>s.addIssue({code:E.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new ke({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:o(n=>this["~validate"](n),"validate")}}optional(){return we.create(this,this._def)}nullable(){return We.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return vt.create(this,this._def)}or(t){return Qt.create([this,t],this._def)}and(t){return en.create(this,t,this._def)}transform(t){return new ke({...M(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new on({...M(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new Br({typeName:P.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new an({...M(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Gr.create(this,t)}readonly(){return cn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vS=/^c[^\s-]{8,}$/i,kS=/^[0-9a-z]+$/,xS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,SS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ES=/^[a-z0-9_-]{21}$/i,TS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,AS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,RS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,CS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",IS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,NS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,OS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,DS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,PS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mp="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$S=new RegExp(`^${Mp}$`);o($p,"timeRegexSource");o(LS,"timeRegex");o(Lp,"datetimeRegex");o(FS,"isValidIP");o(jS,"isValidJWT");o(US,"isValidCidr");bt=class e extends ${static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==R.string){let s=this._getOrReturnCtx(t);return A(s,{code:E.invalid_type,expected:R.string,received:s.parsedType}),D}let r=new te,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?A(i,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&A(i,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")RS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Fa||(Fa=new RegExp(CS,"u")),Fa.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")SS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")ES.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")vS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")kS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")xS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),A(i,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Lp(s).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?$S.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?LS(s).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?AS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?FS(t.data,s.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?jS(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?US(t.data,s.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?PS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?MS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};bt.create=e=>new bt({checks:[],typeName:P.ZodString,coerce:e?.coerce??!1,...M(e)});o(HS,"floatSafeRemainder");zt=class e extends ${static{o(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==R.number){let s=this._getOrReturnCtx(t);return A(s,{code:E.invalid_type,expected:R.number,received:s.parsedType}),D}let r,i=new te;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?HS(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:E.not_finite,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};zt.create=e=>new zt({checks:[],typeName:P.ZodNumber,coerce:e?.coerce||!1,...M(e)});qt=class e extends ${static{o(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==R.bigint)return this._getInvalidInput(t);let r,i=new te;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):L.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:E.invalid_type,expected:R.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};qt.create=e=>new qt({checks:[],typeName:P.ZodBigInt,coerce:e?.coerce??!1,...M(e)});Yt=class extends ${static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==R.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.boolean,received:r.parsedType}),D}return ce(t.data)}};Yt.create=e=>new Yt({typeName:P.ZodBoolean,coerce:e?.coerce||!1,...M(e)});Jt=class e extends ${static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==R.date){let s=this._getOrReturnCtx(t);return A(s,{code:E.invalid_type,expected:R.date,received:s.parsedType}),D}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return A(s,{code:E.invalid_date}),D}let r=new te,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Jt.create=e=>new Jt({checks:[],coerce:e?.coerce||!1,typeName:P.ZodDate,...M(e)});Vn=class extends ${static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==R.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.symbol,received:r.parsedType}),D}return ce(t.data)}};Vn.create=e=>new Vn({typeName:P.ZodSymbol,...M(e)});Xt=class extends ${static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.undefined,received:r.parsedType}),D}return ce(t.data)}};Xt.create=e=>new Xt({typeName:P.ZodUndefined,...M(e)});Zt=class extends ${static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==R.null){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.null,received:r.parsedType}),D}return ce(t.data)}};Zt.create=e=>new Zt({typeName:P.ZodNull,...M(e)});wt=class extends ${static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ce(t.data)}};wt.create=e=>new wt({typeName:P.ZodAny,...M(e)});rt=class extends ${static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ce(t.data)}};rt.create=e=>new rt({typeName:P.ZodUnknown,...M(e)});Oe=class extends ${static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:E.invalid_type,expected:R.never,received:n.parsedType}),D}};Oe.create=e=>new Oe({typeName:P.ZodNever,...M(e)});zn=class extends ${static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.void,received:r.parsedType}),D}return ce(t.data)}};zn.create=e=>new zn({typeName:P.ZodVoid,...M(e)});it=class e extends ${static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==R.array)return A(n,{code:E.invalid_type,expected:R.array,received:n.parsedType}),D;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(A(n,{code:a?E.too_big:E.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(A(n,{code:E.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(A(n,{code:E.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new ve(n,a,n.path,c)))).then(a=>te.mergeArray(r,a));let s=[...n.data].map((a,c)=>i.type._parseSync(new ve(n,a,n.path,c)));return te.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};it.create=(e,t)=>new it({type:e,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...M(t)});o(Kn,"deepPartialify");me=class e extends ${static{o(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==R.object){let d=this._getOrReturnCtx(t);return A(d,{code:E.invalid_type,expected:R.object,received:d.parsedType}),D}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Oe&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=s[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ve(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Oe){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(A(i,{code:E.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ve(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,f=await u.value;d.push({key:p,value:f,alwaysSet:u.alwaysSet})}return d}).then(d=>te.mergeObjectSync(r,d)):te.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:o((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:o(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:o(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:P.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}deepPartial(){return Kn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:o(()=>n,"shape")})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof we;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return Fp(L.objectKeys(this.shape))}};me.create=(e,t)=>new me({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:Oe.create(),typeName:P.ZodObject,...M(t)});me.strictCreate=(e,t)=>new me({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:Oe.create(),typeName:P.ZodObject,...M(t)});me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:Oe.create(),typeName:P.ZodObject,...M(t)});Qt=class extends ${static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new fe(c.ctx.common.issues));return A(n,{code:E.invalid_union,unionErrors:a}),D}if(o(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=a.map(l=>new fe(l));return A(n,{code:E.invalid_union,unionErrors:c}),D}}get options(){return this._def.options}};Qt.create=(e,t)=>new Qt({options:e,typeName:P.ZodUnion,...M(t)});nt=o(e=>e instanceof tn?nt(e.schema):e instanceof ke?nt(e.innerType()):e instanceof nn?[e.value]:e instanceof rn?e.options:e instanceof sn?L.objectValues(e.enum):e instanceof on?nt(e._def.innerType):e instanceof Xt?[void 0]:e instanceof Zt?[null]:e instanceof we?[void 0,...nt(e.unwrap())]:e instanceof We?[null,...nt(e.unwrap())]:e instanceof Br||e instanceof cn?nt(e.unwrap()):e instanceof an?nt(e._def.innerType):[],"getDiscriminator"),os=class e extends ${static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.object)return A(n,{code:E.invalid_type,expected:R.object,received:n.parsedType}),D;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let s of n){let a=nt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:P.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...M(r)})}};o(ja,"mergeValues");en=class extends ${static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=o((s,a)=>{if(is(s)||is(a))return D;let c=ja(s.value,a.value);return c.valid?((ss(s)||ss(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:E.invalid_intersection_types}),D)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};en.create=(e,t,n)=>new en({left:e,right:t,typeName:P.ZodIntersection,...M(n)});Ge=class e extends ${static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.array)return A(r,{code:E.invalid_type,expected:R.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return A(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ve(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>te.mergeArray(n,a)):te.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ge({items:e,typeName:P.ZodTuple,rest:null,...M(t)})};as=class e extends ${static{o(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.object)return A(r,{code:E.invalid_type,expected:R.object,received:r.parsedType}),D;let i=[],s=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ve(r,c,r.path,c)),value:a._parse(new ve(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?te.mergeObjectAsync(n,i):te.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof $?new e({keyType:t,valueType:n,typeName:P.ZodRecord,...M(r)}):new e({keyType:bt.create(),valueType:t,typeName:P.ZodRecord,...M(n)})}},qn=class extends ${static{o(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.map)return A(r,{code:E.invalid_type,expected:R.map,received:r.parsedType}),D;let i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ve(r,c,r.path,[d,"key"])),value:s._parse(new ve(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return D;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return D;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};qn.create=(e,t,n)=>new qn({valueType:t,keyType:e,typeName:P.ZodMap,...M(n)});Yn=class e extends ${static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.set)return A(r,{code:E.invalid_type,expected:R.set,received:r.parsedType}),D;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(A(r,{code:E.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(A(r,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}o(a,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new ve(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Yn.create=(e,t)=>new Yn({valueType:e,minSize:null,maxSize:null,typeName:P.ZodSet,...M(t)});cs=class e extends ${static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.function)return A(n,{code:E.invalid_type,expected:R.function,received:n.parsedType}),D;function r(c,l){return Hr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gn(),tt].filter(d=>!!d),issueData:{code:E.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function i(c,l){return Hr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gn(),tt].filter(d=>!!d),issueData:{code:E.invalid_return_type,returnTypeError:l}})}o(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof vt){let c=this;return ce(async function(...l){let d=new fe([]),u=await c._def.args.parseAsync(l,s).catch(h=>{throw d.addIssue(r(l,h)),d}),p=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(p,s).catch(h=>{throw d.addIssue(i(p,h)),d})})}else{let c=this;return ce(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new fe([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),p=c._def.returns.safeParse(u,s);if(!p.success)throw new fe([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ge.create(t).rest(rt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ge.create([]).rest(rt.create()),returns:n||rt.create(),typeName:P.ZodFunction,...M(r)})}},tn=class extends ${static{o(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};tn.create=(e,t)=>new tn({getter:e,typeName:P.ZodLazy,...M(t)});nn=class extends ${static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};nn.create=(e,t)=>new nn({value:e,typeName:P.ZodLiteral,...M(t)});o(Fp,"createZodEnum");rn=class e extends ${static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:L.joinValues(r),received:n.parsedType,code:E.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:E.invalid_enum_value,options:r}),D}return ce(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};rn.create=Fp;sn=class extends ${static{o(this,"ZodNativeEnum")}_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==R.string&&r.parsedType!==R.number){let i=L.objectValues(n);return A(r,{expected:L.joinValues(i),received:r.parsedType,code:E.invalid_type}),D}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=L.objectValues(n);return A(r,{received:r.data,code:E.invalid_enum_value,options:i}),D}return ce(t.data)}get enum(){return this._def.values}};sn.create=(e,t)=>new sn({values:e,typeName:P.ZodNativeEnum,...M(t)});vt=class extends ${static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.promise&&n.common.async===!1)return A(n,{code:E.invalid_type,expected:R.promise,received:n.parsedType}),D;let r=n.parsedType===R.promise?n.data:Promise.resolve(n.data);return ce(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};vt.create=(e,t)=>new vt({type:e,typeName:P.ZodPromise,...M(t)});ke=class extends ${static{o(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return D;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?D:l.status==="dirty"?Vt(l.value):n.value==="dirty"?Vt(l.value):l});{if(n.value==="aborted")return D;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?D:c.status==="dirty"?Vt(c.value):n.value==="dirty"?Vt(c.value):c}}if(i.type==="refinement"){let a=o(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?D:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?D:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_t(a))return D;let c=i.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>_t(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):D);L.assertNever(i)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:P.ZodEffects,effect:t,...M(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:P.ZodEffects,...M(n)});we=class extends ${static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===R.undefined?ce(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};we.create=(e,t)=>new we({innerType:e,typeName:P.ZodOptional,...M(t)});We=class extends ${static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===R.null?ce(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};We.create=(e,t)=>new We({innerType:e,typeName:P.ZodNullable,...M(t)});on=class extends ${static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===R.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:P.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});an=class extends ${static{o(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Wn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new fe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};an.create=(e,t)=>new an({innerType:e,typeName:P.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});Jn=class extends ${static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==R.nan){let r=this._getOrReturnCtx(t);return A(r,{code:E.invalid_type,expected:R.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};Jn.create=e=>new Jn({typeName:P.ZodNaN,...M(e)});BS=Symbol("zod_brand"),Br=class extends ${static{o(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Gr=class e extends ${static{o(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return o(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?D:s.status==="dirty"?(n.dirty(),Vt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?D:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:P.ZodPipeline})}},cn=class extends ${static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(i=>(_t(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Wn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};cn.create=(e,t)=>new cn({innerType:e,typeName:P.ZodReadonly,...M(t)});o(Pp,"cleanParams");o(jp,"custom");GS={object:me.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(P||(P={}));WS=o((e,t={message:`Input not instance of ${e.name}`})=>jp(n=>n instanceof e,t),"instanceOfType"),Up=bt.create,Hp=zt.create,KS=Jn.create,VS=qt.create,Bp=Yt.create,zS=Jt.create,qS=Vn.create,YS=Xt.create,JS=Zt.create,XS=wt.create,ZS=rt.create,QS=Oe.create,eE=zn.create,tE=it.create,nE=me.create,rE=me.strictCreate,iE=Qt.create,sE=os.create,oE=en.create,aE=Ge.create,cE=as.create,lE=qn.create,dE=Yn.create,uE=cs.create,pE=tn.create,fE=nn.create,mE=rn.create,hE=sn.create,gE=vt.create,yE=ke.create,_E=we.create,bE=We.create,wE=ke.createWithPreprocess,vE=Gr.create,kE=o(()=>Up().optional(),"ostring"),xE=o(()=>Hp().optional(),"onumber"),SE=o(()=>Bp().optional(),"oboolean"),EE={string:o(e=>bt.create({...e,coerce:!0}),"string"),number:o(e=>zt.create({...e,coerce:!0}),"number"),boolean:o(e=>Yt.create({...e,coerce:!0}),"boolean"),bigint:o(e=>qt.create({...e,coerce:!0}),"bigint"),date:o(e=>Jt.create({...e,coerce:!0}),"date")},TE=D});var m={};Q(m,{BRAND:()=>BS,DIRTY:()=>Vt,EMPTY_PATH:()=>wS,INVALID:()=>D,NEVER:()=>TE,OK:()=>ce,ParseStatus:()=>te,Schema:()=>$,ZodAny:()=>wt,ZodArray:()=>it,ZodBigInt:()=>qt,ZodBoolean:()=>Yt,ZodBranded:()=>Br,ZodCatch:()=>an,ZodDate:()=>Jt,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>os,ZodEffects:()=>ke,ZodEnum:()=>rn,ZodError:()=>fe,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>cs,ZodIntersection:()=>en,ZodIssueCode:()=>E,ZodLazy:()=>tn,ZodLiteral:()=>nn,ZodMap:()=>qn,ZodNaN:()=>Jn,ZodNativeEnum:()=>sn,ZodNever:()=>Oe,ZodNull:()=>Zt,ZodNullable:()=>We,ZodNumber:()=>zt,ZodObject:()=>me,ZodOptional:()=>we,ZodParsedType:()=>R,ZodPipeline:()=>Gr,ZodPromise:()=>vt,ZodReadonly:()=>cn,ZodRecord:()=>as,ZodSchema:()=>$,ZodSet:()=>Yn,ZodString:()=>bt,ZodSymbol:()=>Vn,ZodTransformer:()=>ke,ZodTuple:()=>Ge,ZodType:()=>$,ZodUndefined:()=>Xt,ZodUnion:()=>Qt,ZodUnknown:()=>rt,ZodVoid:()=>zn,addIssueToContext:()=>A,any:()=>XS,array:()=>tE,bigint:()=>VS,boolean:()=>Bp,coerce:()=>EE,custom:()=>jp,date:()=>zS,datetimeRegex:()=>Lp,defaultErrorMap:()=>tt,discriminatedUnion:()=>sE,effect:()=>yE,enum:()=>mE,function:()=>uE,getErrorMap:()=>Gn,getParsedType:()=>Be,instanceof:()=>WS,intersection:()=>oE,isAborted:()=>is,isAsync:()=>Wn,isDirty:()=>ss,isValid:()=>_t,late:()=>GS,lazy:()=>pE,literal:()=>fE,makeIssue:()=>Hr,map:()=>lE,nan:()=>KS,nativeEnum:()=>hE,never:()=>QS,null:()=>JS,nullable:()=>bE,number:()=>Hp,object:()=>nE,objectUtil:()=>Ma,oboolean:()=>SE,onumber:()=>xE,optional:()=>_E,ostring:()=>kE,pipeline:()=>vE,preprocess:()=>wE,promise:()=>gE,quotelessJson:()=>yS,record:()=>cE,set:()=>dE,setErrorMap:()=>bS,strictObject:()=>rE,string:()=>Up,symbol:()=>qS,transformer:()=>yE,tuple:()=>aE,undefined:()=>YS,union:()=>iE,unknown:()=>ZS,util:()=>L,void:()=>eE});var Ua=_(()=>{rs();La();Np();Ur();Gp();ns()});var le=_(()=>{Ua();Ua()});var Ha,Ba=_(()=>{"use strict";le();Ha=m.object({id:m.string().min(1),title:m.string().min(1).max(200),type:m.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:m.enum(["community","curated"]),lesson_class:m.enum(["general","architecture"]).default("general"),quality_tier:m.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:m.object({source:m.enum(["memory","vault","claude-md"]),source_id:m.string().min(1),migrated_at:m.string(),migrated_from_workspace:m.string().optional()}).optional(),context:m.object({tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tags:m.array(m.string()).default([])}),summary:m.string().min(1).max(500),problem:m.string().optional(),solution:m.string().optional(),gotchas:m.array(m.string()).default([]),template_body:m.string().min(1).optional(),target_file:m.string().min(1).optional(),submitted_by:m.string().optional(),evidence:m.string().optional(),last_validated_at:m.string().optional(),tool_versions:m.record(m.string(),m.string()).optional(),upvotes:m.number().int().nonnegative().default(0),version:m.number().int().min(1).default(1),changed_at:m.string().optional(),changelog:m.string().max(500).optional(),revision_of:m.string().optional(),org_id:m.string().uuid().optional(),org_name:m.string().optional(),scope:m.literal("private").optional(),body:m.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:m.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:m.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var AE,Wp=_(()=>{"use strict";le();Ba();AE=Ha.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:m.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:m.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:m.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:m.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var Kp,Vp,zp,qp,Ga,Yp,Jp,Xp,RE,Zp=_(()=>{"use strict";le();Kp=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Vp=m.enum(Kp),zp=["new_to_ai_agents","new_to_this_client","experienced"],qp=m.enum(zp),Ga=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],Yp=Ga.map(e=>e.header),Jp=m.object({experience_level:m.array(qp).default([]),stack_filters:m.array(m.string()).default([])}).default({experience_level:[],stack_filters:[]}),Xp=m.object({id:m.string().min(1),client:Vp,title:m.string().min(1),last_updated:m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:Jp,version:m.number().int().min(1).default(1),changelog:m.string().max(500).optional()}),RE=Xp.extend({body:m.string().min(1)})});var ef,ls,tf,ds,CE,IE,nf,rf,sf,of,us,NE,OE,Qp,DE,af,PE,cf=_(()=>{"use strict";le();ef=["operating_procedure","code_review","communication_style"],ls=m.enum(ef),tf=["info","recommended","required"],ds=m.enum(tf),CE=["optional","default_on","mandatory"],IE=m.enum(CE),nf=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],rf=m.enum(nf),sf=["verify","contribute","mixed"],of=m.enum(sf),us=m.object({clients:m.array(rf).default([]),stacks:m.array(m.string()).default([]),intents:m.array(of).default([])}).default({clients:[],stacks:[],intents:[]}),NE=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,OE=64,Qp=200,DE=m.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),af=m.object({id:m.string().min(5).max(OE).regex(NE,"id must match conv_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),scope:ls,version:m.number().int().min(1),changed_at:DE,changelog:m.string().max(500).optional(),applies_to:us,severity:ds.default("recommended"),disableability:IE.default("default_on"),summary:m.string().min(1).max(Qp,`summary must be \u2264 ${Qp} chars (rendered as one line in init-push)`),review_gate:m.object({enabled:m.boolean(),min_matched_symbols:m.number().int().min(1).max(8).default(2),hard:m.boolean().default(!1)}).optional(),gateway_gate:m.object({enabled:m.boolean(),deny_tools:m.array(m.string().min(1).max(128)).min(1).max(16),servers:m.array(m.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),PE=af.extend({body:m.string().min(1)})});var kt=_(()=>{"use strict";Ba();Wp();Zp();cf()});var Wa,ps,Ka,lf,df,uf,ME,pf=_(()=>{"use strict";le();Wa=m.object({type:m.literal("text"),md:m.string().min(1).max(2e4)}),ps=m.number().min(0).max(1).optional(),Ka=m.object({type:m.literal("media"),kind:m.enum(["image","video"]),url:m.string().url().max(2048),alt:m.string().max(500).optional(),caption:m.string().max(500).optional(),fog:m.object({top:ps,right:ps,bottom:ps,left:ps}).optional()}),lf=m.object({label:m.string().min(1).max(40),color:m.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),df=m.object({type:m.literal("accordion"),title:m.string().min(1).max(200),subtag:lf.optional(),blocks:m.array(m.discriminatedUnion("type",[Wa,Ka])).max(50)}),uf=m.discriminatedUnion("type",[Wa,Ka,df]),ME=m.array(uf).max(100)});var ff,$E,mf,hf,LE,FE,jE,gf=_(()=>{"use strict";le();ff=["free","solo_pro","team","enterprise"],$E=m.enum(ff),mf=["solo_pro","team","enterprise"],hf=m.enum(mf),LE=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),FE=m.object({user_id:m.string().uuid(),tier:hf,reason:m.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:LE.nullable().optional(),auto_revoke_on_stripe:m.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),jE=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var yf=_(()=>{"use strict"});var UE,HE,BE,_f=_(()=>{"use strict";le();UE=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),HE=m.object({org_id:m.string().uuid(),seats:m.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:m.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:UE.nullable().optional(),auto_revoke_on_stripe:m.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),BE=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var bf,GE,wf,vf,kf,xf,WE,Sf=_(()=>{"use strict";le();bf=m.enum(["info","important","critical"]),GE=m.enum(["pass","warn","fail"]),wf=m.object({type:m.enum(["template","lesson"]),id:m.string().min(1)}),vf=m.object({languages:m.array(m.string()).optional(),tools:m.array(m.string()).optional()}).optional(),kf=m.discriminatedUnion("kind",[m.object({kind:m.literal("file-exists"),path:m.string().min(1)}),m.object({kind:m.literal("any-file-exists"),paths:m.array(m.string().min(1)).min(1)}),m.object({kind:m.literal("any-agent-config")}),m.object({kind:m.literal("file-size-budget"),field:m.enum(["claude_md","readme"]),max_chars:m.number().int().positive()}),m.object({kind:m.literal("readme-section-present"),headers:m.array(m.string().min(1)).min(1)}),m.object({kind:m.literal("adr-dir-present")}),m.object({kind:m.literal("git-present")}),m.object({kind:m.literal("quality-gates-configured"),pass_if_at_least:m.number().int().min(1).max(4).optional(),warn_if_at_least:m.number().int().min(0).max(4).optional()}),m.object({kind:m.literal("storage-risk-safe"),allow_unknown:m.boolean().optional()}),m.object({kind:m.literal("doc-path-discoverability")})]),xf=m.object({id:m.string().min(1),title:m.string().min(1),severity:bf,weight:m.number().int().positive().max(100),applies_when:vf,check:kf,fail_message:m.string().min(1),warn_message:m.string().optional(),remediation:wf.optional()}),WE=m.object({version:m.literal(1),checks:m.array(xf).min(1)})});function VE(e){if(!KE.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function fs(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}function zE(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var KE,ms,Ef,Tf,Ke,Va,Af,qE,Rf=_(()=>{"use strict";le();KE=/^\d{4}-\d{2}-\d{2}$/;o(VE,"isRealDate");ms=m.string().refine(VE,{message:"expected a real calendar date as YYYY-MM-DD"}),Ef=["exact","prefix"],Tf=m.enum(Ef),Ke=m.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Va=[2e5,272e3],Af=m.object({model_pattern:m.string().min(1).max(100),match_kind:Tf,valid_from:ms,valid_to:ms.nullable().optional(),input:Ke,output:Ke,cache_read:Ke,cache_write_5m:Ke,cache_write_1h:Ke,long_context:m.enum(["same_price","tiered"]).optional(),input_above_200k:Ke.optional(),output_above_200k:Ke.optional(),cache_read_above_200k:Ke.optional(),cache_write_5m_above_200k:Ke.optional(),cache_write_1h_above_200k:Ke.optional(),context_threshold_tokens:m.number().int().positive().nullable().optional(),source_url:m.string().url().max(500).nullable().optional(),note:m.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>fs(e)===0||fs(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||fs(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>fs(e)===0||e.context_threshold_tokens==null||Va.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Va.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});o(fs,"aboveRateCount");o(zE,"rowKey");qE=m.object({changelog:m.string().min(1).max(500),as_of:ms,source_url:m.string().url().max(500),rows:m.array(Af).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let a=zE(i),c=n.get(a);c!==void 0?t.addIssue({code:m.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,s)});let r=new Map;e.rows.forEach((i,s)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:s,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,a)=>s.r.valid_from.localeCompare(a.r.valid_from));for(let s=0;s<i.length-1;s++){let a=i[s],c=i[s+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:m.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Xn=_(()=>{"use strict"});var Wr=_(()=>{"use strict"});var Of=_(()=>{"use strict";Wr();Xn()});var Df=_(()=>{"use strict";Xn()});var Pf=_(()=>{"use strict";kt();Wr();Xn()});var Mf=_(()=>{"use strict";Wr();Xn()});var $f=_(()=>{"use strict";Xn();Of();Df();Pf();Mf();Wr()});var f0,m0,Lf,h0,Ff,za,jf,Uf,Hf,Bf,g0,qa=_(()=>{"use strict";le();kt();f0=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,m0=64,Lf=200,h0=1e3,Ff=m.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),za=m.enum(["low","medium","high"]),jf=m.object({owner:m.string().min(1).max(160).optional(),risk_level:za.optional(),reviewed_at:Ff.optional()}).default({}),Uf=m.object({tags:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),limit:m.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Hf=m.object({lesson_query:Uf,lesson_pins:m.array(m.string()).default([]),lesson_excludes:m.array(m.string()).default([]),convention_ids:m.array(m.string()).default([]),template_ids:m.array(m.string()).default([]),setup_guide_ids:m.array(m.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Bf=m.object({id:m.string().min(6).max(m0).regex(f0,"id must match skill_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),version:m.number().int().min(1),changed_at:Ff,tier:m.enum(["community","curated"]).default("curated"),summary:m.string().min(1).max(Lf,`summary must be \u2264 ${Lf} chars (rendered as one line in skill_index)`),description:m.string().max(h0).optional(),applies_to:us,membership:Hf,governance:jf}),g0=Bf.extend({body:m.string().default(""),org_id:m.string().uuid().optional(),org_name:m.string().optional()})});var Gf,Wf,Kf,Vf,zf,qf,y0,Yf,_0,b0,Jf=_(()=>{"use strict";le();qa();Gf=m.enum(["maind","agent-skill"]),Wf=m.enum(["ready","needs_attention","blocked"]),Kf=m.enum(["info","important","critical"]),Vf=m.enum(["pass","warn","fail"]),zf=m.enum(["structure","governance","scope","membership","package","references"]),qf=m.object({id:m.string().min(1),title:m.string().min(1),status:Vf,severity:Kf,category:zf,field:m.string().nullable().optional(),message:m.string().min(1),hint:m.string().optional()}),y0=m.object({lesson_ids:m.array(m.string()).optional(),convention_ids:m.array(m.string()).optional(),template_ids:m.array(m.string()).optional(),setup_guide_ids:m.array(m.string()).optional()}).default({}),Yf=m.object({name:m.string().min(1).max(64),description:m.string().min(1).max(1024),license:m.string().optional(),compatibility:m.union([m.string(),m.array(m.string())]).optional(),metadata:m.record(m.string()).default({}),"allowed-tools":m.union([m.string(),m.array(m.string())]).optional()}).passthrough(),_0=m.object({directory_name:m.string().min(1).max(120).optional(),frontmatter:Yf,body:m.string().default(""),file_listing:m.array(m.string()).optional()}),b0=m.object({format:Gf,subject:m.string().min(1),status:Wf,summary:m.string().min(1),counts:m.object({pass:m.number().int().min(0),warn:m.number().int().min(0),fail:m.number().int().min(0)}),checks:m.array(qf),next_steps:m.array(m.string()),trust_note:m.string().min(1)})});var Ya=_(()=>{"use strict"});var Xf,v0,Zf,Qf,em,Zn,k0,tm,nm,rm,im,sm,om,am,cm,x0,lm,dm,um,xt,Ja,pm,fm,S0,mm=_(()=>{"use strict";le();kt();Ya();Xf=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],v0=m.enum(Xf),Zf=["verdict","advisory"],Qf=m.enum(Zf),em=["block","warn","note"],Zn=m.enum(em),k0=m.object({convention_id:m.string().min(1).max(64),convention_version:m.number().int().min(1),severity:ds,scope:ls,grade:Qf,matched_symbols:m.array(m.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:m.array(m.string().min(1).max(512)).max(64).default([]),summary:m.string().max(2e3),hard:m.boolean().optional()}),tm=["open","warn","info"],nm=m.enum(tm),rm=["introduced","pre_existing"],im=m.enum(rm),sm=["full","partial","none"],om=m.enum(sm),am=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),rule_id:m.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:nm,baseline:im,evidence_hash:m.string().regex(/^[a-f0-9]{64}$/),count:m.number().int().min(1).max(1e5)}),cm=m.object({version:m.literal(1).default(1),actions:m.object({required:Zn.default("block"),recommended:Zn.default("warn"),info:Zn.default("note")}).default({}),overrides:m.array(m.object({convention_id:m.string().min(1).max(64),action:Zn})).max(64).default([]),risk_flag_action:m.enum(["warn","note","ignore"]).default("warn"),detector_overrides:m.array(m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Zn,reason:m.string().min(1).max(200)})).max(32).optional()}),x0=cm.parse({}),lm=["ran","not_applicable","unavailable","ungraded"],dm=m.enum(lm),um=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),state:dm}),xt=1e3,Ja=m.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),pm=m.object({name:m.string().min(1).max(200),qualified_name:m.string().min(1).max(512).optional(),kind:m.string().min(1).max(64).optional(),language:m.string().min(1).max(32).optional(),change:m.enum(["added","modified","co_located"]).optional(),changed_line_count:m.number().int().min(0).max(1e4).optional()}),fm=m.object({base_kind:m.enum(["uncommitted","ref"]),changed_file_count:m.number().int().min(0),stale_file_count:m.number().int().min(0),unindexed_file_count:m.number().int().min(0).optional(),truncated:m.boolean(),hunk_coverage:m.enum(["full","partial","none"]),detector_coverage:om}),S0=m.object({changed_symbols:m.array(pm).max(xt),risk_flags:m.array(m.string().max(64)).max(16),detector_findings:m.array(am).max(64),detector_runs:m.array(um).min(1).max(32),diff_stats:fm,commit_sha:Ja.optional(),base_sha:Ja.optional(),merge_base_sha:Ja.optional(),dirty:m.boolean().optional(),code_index_version:m.string().min(1).max(32).optional()})});var hm,gm,ym,_m,bm,Xa,E0,T0,wm,vm,km,xm,Sm,A0,R0,Em,Tm,Am,C0,Rm=_(()=>{"use strict";le();hm=14,gm=14,ym=14,_m=1,bm=365,Xa=m.number().int().min(_m).max(bm),E0=["propose","direct"],T0="propose",wm=["propose","direct"],vm="propose",km=["propose","direct"],xm="propose",Sm=["off","propose","direct"],A0=["member","admin","owner"],R0="member",Em="off",Tm="en",Am=m.object({version:m.literal(1).default(1),at_risk_days:Xa.default(hm),stagnation_days:Xa.default(gm),agent_date_mode:m.enum(E0).default(T0),health_manual_ttl_days:Xa.default(ym),agent_event_mode:m.enum(wm).default(vm),agent_update_mode:m.enum(km).default(xm),agent_pull_mode:m.enum(Sm).default(Em),org_wide_authoring_min_role:m.enum(A0).default(R0),planning_language:m.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Tm)}),C0=Am.parse({})});var Cm,I0,Im=_(()=>{"use strict";le();Cm=m.object({version:m.literal(1).default(1),org_visibility:m.boolean().default(!1),session_span_visibility:m.boolean().default(!0)}),I0=Cm.parse({})});var Nm,Om,N0,O0,Dm=_(()=>{"use strict";le();Nm=m.object({tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tags:m.array(m.string()).default([])}),Om=m.object({id:m.string().uuid(),user_id:m.string().uuid(),project:m.string().max(200).nullable().optional(),title:m.string().min(1).max(200),body:m.string().min(1).max(2e4),context:Nm.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:m.string(),updated_at:m.string(),last_recalled_at:m.string().nullable().optional(),recall_count:m.number().int().nonnegative().default(0),graduated_draft_id:m.string().uuid().nullable().optional(),deleted_at:m.string().nullable().optional()}),N0=Om.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:m.number()}),O0=m.object({id:m.string().uuid(),title:m.string(),summary:m.string(),tags:m.array(m.string()).default([])})});var Pm=_(()=>{"use strict"});function hs(e){let t=[],n=null;return e.split(`
3
- `).forEach((r,i)=>{let s=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(s===""||a>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=P0.exec(r);if(!c)return;let l=c[3]??"";if(D0.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var D0,P0,Mm=_(()=>{"use strict";D0=new Set(["|",">","|-",">-","|+",">+"]),P0=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(hs,"plainScalarViolations")});function Vr(e,t){let n=o(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(p=>{let f=Number(p);return Number.isFinite(f)?f:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,i]=n(e),[s,a]=n(t);for(let c=0;c<Math.max(r.length,s.length);c+=1){let l=(r[c]??0)-(s[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&a.length===0)return 0;if(i.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(i.length,a.length);c+=1){let l=i[c],d=a[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),p=/^\d+$/.test(d);if(u&&p){let f=Number(l)-Number(d);if(f!==0)return f<0?-1:1}else{if(u!==p)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var $m=_(()=>{"use strict";o(Vr,"compareSemver")});var zr=_(()=>{"use strict";kt();pf();kt();kt();gf();yf();_f();Sf();Rf();$f();kt();qa();Jf();mm();Rm();Im();Dm();Pm();Ya();Mm();$m()});function Lm(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
- `).slice(0,1e3)}var Fm=_(()=>{"use strict";o(Lm,"nodeEmbedText")});var Za,Qa=_(()=>{"use strict";Za=["function","method","class","interface","enum","type_alias"]});function jm(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var Um=_(()=>{"use strict";o(jm,"cosineSimilarity")});import{execFileSync as M0}from"node:child_process";import{createHash as $0}from"node:crypto";import{readFileSync as L0}from"node:fs";import{posix as De}from"node:path";function Hm(e){let t=$0("sha256"),n=[];try{n=M0("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(l=>F0.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=o(l=>{if(r.has(l))return r.get(l);try{let d=L0(De.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),s=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=Bm(l,i,0),u=De.dirname(l)==="."?"":De.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&s.push({dir:d.pathsDir??u,baseUrl:d.baseUrl,paths:d.paths})}let c=[];for(let l of n.filter(d=>d.endsWith("package.json"))){let d=Gm(i(l));if(!d||typeof d.name!="string")continue;let u=De.dirname(l)==="."?"":De.dirname(l),p=a.get(u);c.push({name:d.name,dir:u,exports:d.exports,main:typeof d.main=="string"?d.main:void 0,module:typeof d.module=="string"?d.module:void 0,types:typeof d.types=="string"?d.types:void 0,outDir:p?.outDir,rootDir:p?.rootDir})}for(let l of[...r.keys()].sort())t.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:s},fingerprint:t.digest("hex")}}function Bm(e,t,n){let r=Gm(t(e));if(!r)return{};let i=De.dirname(e)==="."?"":De.dirname(e),s={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=De.normalize(De.join(i,a.endsWith(".json")?a:a+".json"));s=Bm(d,t,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=De.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=De.normalize(c.rootDir)),c.paths&&typeof c.paths=="object"&&(l.paths=c.paths,l.pathsDir=i,l.baseUrl=typeof c.baseUrl=="string"?c.baseUrl:void 0),l}function Gm(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"')n=!0,t+=i;else if(i==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
2
+ var Ef=Object.defineProperty;var o=(e,t)=>Ef(e,"name",{value:t,configurable:!0});var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>{for(var n in t)Ef(e,n,{get:t[n],enumerable:!0})};import{existsSync as uS,mkdirSync as fS,readdirSync as pS,readFileSync as mS,renameSync as hS,statSync as gS,unlinkSync as yS,writeFileSync as _S}from"node:fs";import{homedir as bS}from"node:os";import{join as ns}from"node:path";function rs(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n,i=es(r.id),s=es(r.key),a=es(r.title),c=es(r.status);if(!(!i||!s||!a||!c)&&(t.push({id:i,key:s,title:a,status:c}),t.length>=wS))break}return t}function is(e){if(e.length===0)return null;let t=e.map(r=>`${r.key} "${r.title}"${r.status==="warn"?" (blocked)":""}`).join(", "),n=e.length===1;return`Assigned to your user in this repository and not taken yet: ${t}. Their own agents may take ${n?"it":"these"} (take_work_object). Mention ${n?"it":"them"} to your user and offer to take ${n?"it":"one"} \u2014 do not start unasked.`}function Tf(e=bS()){return ns(e,".maind","assigned-told")}function Af(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function Rf(e){try{let t=JSON.parse(mS(e,"utf8"));return{ids:Array.isArray(t.ids)?t.ids.filter(n=>typeof n=="string"):[],checked_at:typeof t.checked_at=="number"?t.checked_at:0}}catch{return{ids:[],checked_at:0}}}function xS(e,t,n){fS(e,{recursive:!0,mode:448});let r=`${t}.tmp-${process.pid}`;_S(r,JSON.stringify(n),{mode:384}),hS(r,t)}function Cf(e,t,n=Tf()){let r=ns(n,`${Af(e)}.json`);return uS(r)?t-Rf(r).checked_at<kS:!1}function Pa(e,t,n,r=Tf()){try{let i=ns(r,`${Af(e)}.json`),s=Rf(i),a=t.filter(c=>!s.ids.includes(c.id));return xS(r,i,{ids:[...s.ids,...a.map(c=>c.id)].slice(-200),checked_at:n}),SS(r,n,i),a}catch{return[]}}function SS(e,t,n){try{for(let r of pS(e)){let i=ns(e,r);i!==n&&t-gS(i).mtimeMs>vS&&yS(i)}}catch{}}function If(e){return e==="claude-code"}var wS,vS,kS,es,ts,Ur=_(()=>{"use strict";wS=5,vS=7*24*60*60*1e3,kS=6e4,es=o(e=>typeof e=="string"&&e.length>0?e:null,"str");o(rs,"parseAssignedList");o(is,"assignedNoticeText");o(Tf,"assignedToldDir");o(Af,"safeName");o(Rf,"readTold");o(xS,"writeTold");o(Cf,"checkedRecently");o(Pa,"takeUntold");o(SS,"pruneTold");ts=class{static{o(this,"AssignedInbox")}current=[];told=new Set;update(t){if(!t||typeof t!="object")return;let n=t;n.ok===!0&&(this.current=rs(n.assigned_to_you))}takeNote(){let t=this.current.filter(n=>!this.told.has(n.id));for(let n of t)this.told.add(n.id);return is(t)}};o(If,"clientHasHooks")});function Of(e){let t;try{t=JSON.parse(e)}catch{return{kind:"opaque"}}if(typeof t!="object"||t===null||Array.isArray(t))return{kind:"opaque"};let n=t;if(n.jsonrpc!=="2.0")return{kind:"opaque"};let r=typeof n.id=="number"||typeof n.id=="string"?n.id:void 0,i=typeof n.method=="string"?n.method:void 0;if(i!==void 0){let s={kind:r!==void 0?"request":"notification",method:i,id:r};if(i==="tools/call"){let a=n.params;if(typeof a=="object"&&a!==null){let c=a.name;typeof c=="string"&&(s.toolName=c)}}return s}return r!==void 0&&("result"in n||"error"in n)?{kind:"response",id:r}:{kind:"opaque"}}function Bn(e,t,n){return JSON.stringify({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:n??`maind gateway: tool '${t}' is denied by local gateway policy. The call was not forwarded to the server. Remove the --deny-tool flag (or adjust the gateway policy) to allow it.`}],isError:!0}})}function $a(e,t,n,r){return{at:r,event:e,server:t,tool:n}}function La(e,t,n,r,i,s){return{at:r,event:e,server:t,tool:n,convention_id:i,convention_version:s}}function Fa(e,t,n,r){return{at:r,event:e,server:t,tool:n}}var ja=_(()=>{"use strict";o(Of,"parseFrame");o(Bn,"denyResult");o($a,"toolEvent");o(La,"policyEvent");o(Fa,"shaEvent")});import{execFileSync as Mf}from"node:child_process";function $f(e){return e.verdict==="fabricated"&&(e.matchedPrefixLen??0)>=IS}function NS(e){let t;try{t=JSON.parse(e)}catch{return[]}if(typeof t!="object"||t===null)return[];let n=t.params;if(typeof n!="object"||n===null)return[];let r=n.arguments;if(typeof r!="object"||r===null)return[];let i=[];for(let s of AS){let a=r[s];typeof a=="string"&&Df.test(a)&&i.push({field:s,sha:a})}for(let[s,a]of RS){let c=r[s];if(typeof c!="object"||c===null)continue;let l=c[a];typeof l=="string"&&Df.test(l)&&i.push({field:`${s}.${a}`,sha:l})}return i}function OS(e,t){let n=t(e);if(n===e)return{field:"",sha:e,verdict:"proven"};if(n!==null)return{field:"",sha:e,verdict:"unknown"};let r=e.slice(0,Pf);for(let i=Pf;i>=CS;i--){let s=r.slice(0,i),a=t(s);if(a!==null&&a.startsWith(s))return{field:"",sha:e,verdict:"fabricated",matchedPrefixOf:a,matchedPrefixLen:i}}return{field:"",sha:e,verdict:"unknown"}}function Gn(e,t){return e.verdict==="fabricated"?[`${t?"DENIED":"WARNING"}: the ${e.field} you passed (${e.sha}) does not exist in this repository,`,`but its prefix resolves to a real commit (${e.matchedPrefixOf}).`,"That combination cannot come from an unfetched object \u2014 it comes from completing an abbreviated hash.","Read the full hash instead of reconstructing it: `git rev-parse HEAD`, `git rev-parse <ref>`,","or `gh pr view <n> --json mergeCommit --jq .mergeCommit.oid`.",t?"The call was not forwarded.":"The call was forwarded \u2014 the record will carry an unverifiable hash."].join(" "):[`NOTE: the ${e.field} you passed (${e.sha}) could not be resolved in this repository.`,"That is often harmless \u2014 a fresh squash-merge commit, an unfetched branch, or a different repo in this workspace.","If you reconstructed it from an abbreviated hash, read the full one instead (`git rev-parse`, `gh --json`).","The call was forwarded."].join(" ")}function Lf(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete e[t];return e}function ss(e=process.cwd()){try{let n=Mf("git",["rev-parse","--show-toplevel"],{cwd:e,env:Lf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return n.length>0?n:null}catch{return null}}function DS(e){return t=>{try{let r=Mf("git",["rev-parse","--verify","--quiet",`${t}^{commit}`],{cwd:e,env:Lf(),encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return r.length>0?r:null}catch{return null}}}function os(e,t){if(t===null)return[];let n=NS(e);if(n.length===0)return[];let r=DS(t),i=[];for(let{field:s,sha:a}of n){let c=OS(a,r);c.verdict!=="proven"&&i.push({...c,field:s})}return i}var AS,RS,Df,CS,Pf,IS,Ua=_(()=>{"use strict";AS=["commit_sha","base_sha","head_sha"],RS=[["diff_stats","head_sha"],["diff_stats","base_sha"],["attest","commit_sha"],["attest","base_sha"],["attest","merge_base_sha"]],Df=/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,CS=7,Pf=12,IS=10;o($f,"isDenyGrade");o(NS,"extractShaArgs");o(OS,"classifySha");o(Gn,"shaFindingText");o(Lf,"cleanGitEnv");o(ss,"resolveRepoRootForSha");o(DS,"gitShaResolver");o(os,"inspectLineForShas")});var jf=_(()=>{"use strict"});var j,Ba,R,We,Hr=_(()=>{(function(e){e.assertEqual=i=>{};function t(i){}o(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}o(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=i=>{let s=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of s)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}o(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(j||(j={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ba||(Ba={}));R=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),We=o(e=>{switch(typeof e){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(e)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(e)?R.array:e===null?R.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?R.promise:typeof Map<"u"&&e instanceof Map?R.map:typeof Set<"u"&&e instanceof Set?R.set:typeof Date<"u"&&e instanceof Date?R.date:R.object;default:return R.unknown}},"getParsedType")});var T,PS,pe,as=_(()=>{Hr();T=j.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),PS=o(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),pe=class e extends Error{static{o(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},i=o(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};pe.create=e=>new pe(e)});var MS,nt,Ga=_(()=>{as();Hr();MS=o((e,t)=>{let n;switch(e.code){case T.invalid_type:e.received===R.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case T.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case T.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=t.defaultError,j.assertNever(e)}return{message:n}},"errorMap"),nt=MS});function $S(e){Uf=e}function Wn(){return Uf}var Uf,cs=_(()=>{Ga();Uf=nt;o($S,"setErrorMap");o(Wn,"getErrorMap")});function A(e,t){let n=Wn(),r=Br({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===nt?void 0:nt].filter(i=>!!i)});e.common.issues.push(r)}var Br,LS,ne,O,Vt,ce,ls,ds,_t,Kn,Wa=_(()=>{cs();Ga();Br=o(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let c="",l=r.filter(d=>!!d).slice().reverse();for(let d of l)c=d(a,{data:t,defaultError:c}).message;return{...i,path:s,message:c}},"makeIssue"),LS=[];o(A,"addIssueToContext");ne=class e{static{o(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return O;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let s=await i.key,a=await i.value;r.push({key:s,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return O;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}},O=Object.freeze({status:"aborted"}),Vt=o(e=>({status:"dirty",value:e}),"DIRTY"),ce=o(e=>({status:"valid",value:e}),"OK"),ls=o(e=>e.status==="aborted","isAborted"),ds=o(e=>e.status==="dirty","isDirty"),_t=o(e=>e.status==="valid","isValid"),Kn=o(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync")});var Hf=_(()=>{});var I,Bf=_(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(I||(I={}))});function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:o((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}function Vf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function eE(e){return new RegExp(`^${Vf(e)}$`)}function zf(e){let t=`${Kf}T${Vf(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function tE(e,t){return!!((t==="v4"||!t)&&zS.test(e)||(t==="v6"||!t)&&YS.test(e))}function nE(e,t){if(!GS.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function rE(e,t){return!!((t==="v4"||!t)&&qS.test(e)||(t==="v6"||!t)&&JS.test(e))}function iE(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}function Vn(e){if(e instanceof me){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=we.create(Vn(r))}return new me({...e._def,shape:o(()=>t,"shape")})}else return e instanceof st?new st({...e._def,type:Vn(e.element)}):e instanceof we?we.create(Vn(e.unwrap())):e instanceof Ve?Ve.create(Vn(e.unwrap())):e instanceof Ke?Ke.create(e.items.map(t=>Vn(t))):e}function Va(e,t){let n=We(e),r=We(t);if(e===t)return{valid:!0,data:e};if(n===R.object&&r===R.object){let i=j.objectKeys(t),s=j.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of s){let l=Va(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===R.array&&r===R.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let a=e[s],c=t[s],l=Va(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===R.date&&r===R.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function qf(e,t){return new rn({values:e,typeName:D.ZodEnum,...M(t)})}function Wf(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Yf(e,t={},n){return e?wt.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then(a=>{if(!a){let c=Wf(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!s){let a=Wf(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):wt.create()}var ve,Gf,$,FS,jS,US,HS,BS,GS,WS,KS,VS,Ka,zS,qS,YS,JS,XS,ZS,Kf,QS,bt,zt,qt,Yt,Jt,zn,Xt,Zt,wt,it,De,qn,st,me,Qt,rt,us,en,Ke,fs,Yn,Jn,ps,tn,nn,rn,sn,vt,ke,we,Ve,on,an,Xn,sE,Gr,Wr,cn,oE,D,aE,Jf,Xf,cE,lE,Zf,dE,uE,fE,pE,mE,hE,gE,yE,_E,bE,wE,vE,kE,xE,SE,EE,TE,AE,RE,CE,IE,NE,OE,DE,PE,ME,$E,LE,FE,jE,UE,HE,BE,GE,Qf=_(()=>{as();cs();Bf();Wa();Hr();ve=class{static{o(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Gf=o((e,t)=>{if(_t(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new pe(e.common.issues);return this._error=n,this._error}}},"handleResult");o(M,"processCreateParams");$=class{static{o(this,"ZodType")}get description(){return this._def.description}_getType(t){return We(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:We(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ne,ctx:{common:t.parent.common,data:t.data,parsedType:We(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Kn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:We(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Gf(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:We(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return _t(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>_t(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:We(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(Kn(i)?i:Promise.resolve(i));return Gf(r,s)}refine(t,n){let r=o(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,s)=>{let a=t(i),c=o(()=>s.addIssue({code:T.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new ke({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:o(n=>this["~validate"](n),"validate")}}optional(){return we.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return st.create(this)}promise(){return vt.create(this,this._def)}or(t){return Qt.create([this,t],this._def)}and(t){return en.create(this,t,this._def)}transform(t){return new ke({...M(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new on({...M(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new Gr({typeName:D.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new an({...M(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Wr.create(this,t)}readonly(){return cn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},FS=/^c[^\s-]{8,}$/i,jS=/^[0-9a-z]+$/,US=/^[0-9A-HJKMNP-TV-Z]{26}$/i,HS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,BS=/^[a-z0-9_-]{21}$/i,GS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,WS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,KS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,VS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",zS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,YS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,JS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,XS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ZS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",QS=new RegExp(`^${Kf}$`);o(Vf,"timeRegexSource");o(eE,"timeRegex");o(zf,"datetimeRegex");o(tE,"isValidIP");o(nE,"isValidJWT");o(rE,"isValidCidr");bt=class e extends ${static{o(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==R.string){let s=this._getOrReturnCtx(t);return A(s,{code:T.invalid_type,expected:R.string,received:s.parsedType}),O}let r=new ne,i;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=t.data.length>s.value,c=t.data.length<s.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?A(i,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):c&&A(i,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")KS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"email",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ka||(Ka=new RegExp(VS,"u")),Ka.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"emoji",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")HS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"uuid",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")BS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"nanoid",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")FS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")jS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid2",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")US.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ulid",code:T.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),A(i,{validation:"url",code:T.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"regex",code:T.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?zf(s).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?QS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?eE(s).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:T.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?WS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"duration",code:T.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?tE(t.data,s.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ip",code:T.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?nE(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"jwt",code:T.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?rE(t.data,s.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cidr",code:T.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?XS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64",code:T.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?ZS.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64url",code:T.invalid_string,message:s.message}),r.dirty()):j.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:T.invalid_string,...I.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...I.errToObj(t)})}url(t){return this._addCheck({kind:"url",...I.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...I.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...I.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...I.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...I.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...I.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...I.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...I.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...I.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...I.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...I.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...I.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...I.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...I.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...I.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...I.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...I.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...I.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...I.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...I.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...I.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...I.errToObj(n)})}nonempty(t){return this.min(1,I.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};bt.create=e=>new bt({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...M(e)});o(iE,"floatSafeRemainder");zt=class e extends ${static{o(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==R.number){let s=this._getOrReturnCtx(t);return A(s,{code:T.invalid_type,expected:R.number,received:s.parsedType}),O}let r,i=new ne;for(let s of this._def.checks)s.kind==="int"?j.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:T.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?iE(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:T.not_finite,message:s.message}),i.dirty()):j.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:I.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:I.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&j.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};zt.create=e=>new zt({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...M(e)});qt=class e extends ${static{o(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==R.bigint)return this._getInvalidInput(t);let r,i=new ne;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):j.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:T.invalid_type,expected:R.bigint,received:n.parsedType}),O}gte(t,n){return this.setLimit("min",t,!0,I.toString(n))}gt(t,n){return this.setLimit("min",t,!1,I.toString(n))}lte(t,n){return this.setLimit("max",t,!0,I.toString(n))}lt(t,n){return this.setLimit("max",t,!1,I.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:I.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:I.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};qt.create=e=>new qt({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...M(e)});Yt=class extends ${static{o(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==R.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.boolean,received:r.parsedType}),O}return ce(t.data)}};Yt.create=e=>new Yt({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...M(e)});Jt=class e extends ${static{o(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==R.date){let s=this._getOrReturnCtx(t);return A(s,{code:T.invalid_type,expected:R.date,received:s.parsedType}),O}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return A(s,{code:T.invalid_date}),O}let r=new ne,i;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:T.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:T.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):j.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:I.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:I.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Jt.create=e=>new Jt({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...M(e)});zn=class extends ${static{o(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==R.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.symbol,received:r.parsedType}),O}return ce(t.data)}};zn.create=e=>new zn({typeName:D.ZodSymbol,...M(e)});Xt=class extends ${static{o(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.undefined,received:r.parsedType}),O}return ce(t.data)}};Xt.create=e=>new Xt({typeName:D.ZodUndefined,...M(e)});Zt=class extends ${static{o(this,"ZodNull")}_parse(t){if(this._getType(t)!==R.null){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.null,received:r.parsedType}),O}return ce(t.data)}};Zt.create=e=>new Zt({typeName:D.ZodNull,...M(e)});wt=class extends ${static{o(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ce(t.data)}};wt.create=e=>new wt({typeName:D.ZodAny,...M(e)});it=class extends ${static{o(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ce(t.data)}};it.create=e=>new it({typeName:D.ZodUnknown,...M(e)});De=class extends ${static{o(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:T.invalid_type,expected:R.never,received:n.parsedType}),O}};De.create=e=>new De({typeName:D.ZodNever,...M(e)});qn=class extends ${static{o(this,"ZodVoid")}_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.void,received:r.parsedType}),O}return ce(t.data)}};qn.create=e=>new qn({typeName:D.ZodVoid,...M(e)});st=class e extends ${static{o(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),O;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(A(n,{code:a?T.too_big:T.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(A(n,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(A(n,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new ve(n,a,n.path,c)))).then(a=>ne.mergeArray(r,a));let s=[...n.data].map((a,c)=>i.type._parseSync(new ve(n,a,n.path,c)));return ne.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:I.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:I.toString(n)}})}nonempty(t){return this.min(1,t)}};st.create=(e,t)=>new st({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...M(t)});o(Vn,"deepPartialify");me=class e extends ${static{o(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=j.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==R.object){let d=this._getOrReturnCtx(t);return A(d,{code:T.invalid_type,expected:R.object,received:d.parsedType}),O}let{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||c.push(d);let l=[];for(let d of a){let u=s[d],f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new ve(i,f,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof De){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(A(i,{code:T.unrecognized_keys,keys:c}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let f=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new ve(i,f,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>ne.mergeObjectSync(r,d)):ne.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return I.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:o((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:o(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:o(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:D.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of j.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}omit(t){let n={};for(let r of j.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:o(()=>n,"shape")})}deepPartial(){return Vn(this)}partial(t){let n={};for(let r of j.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:o(()=>n,"shape")})}required(t){let n={};for(let r of j.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof we;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:o(()=>n,"shape")})}keyof(){return qf(j.objectKeys(this.shape))}};me.create=(e,t)=>new me({shape:o(()=>e,"shape"),unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...M(t)});me.strictCreate=(e,t)=>new me({shape:o(()=>e,"shape"),unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...M(t)});me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...M(t)});Qt=class extends ${static{o(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(let c of s)if(c.result.status==="valid")return c.result;for(let c of s)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=s.map(c=>new pe(c.ctx.common.issues));return A(n,{code:T.invalid_union,unionErrors:a}),O}if(o(i,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let l of r){let d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let c=a.map(l=>new pe(l));return A(n,{code:T.invalid_union,unionErrors:c}),O}}get options(){return this._def.options}};Qt.create=(e,t)=>new Qt({options:e,typeName:D.ZodUnion,...M(t)});rt=o(e=>e instanceof tn?rt(e.schema):e instanceof ke?rt(e.innerType()):e instanceof nn?[e.value]:e instanceof rn?e.options:e instanceof sn?j.objectValues(e.enum):e instanceof on?rt(e._def.innerType):e instanceof Xt?[void 0]:e instanceof Zt?[null]:e instanceof we?[void 0,...rt(e.unwrap())]:e instanceof Ve?[null,...rt(e.unwrap())]:e instanceof Gr||e instanceof cn?rt(e.unwrap()):e instanceof an?rt(e._def.innerType):[],"getDiscriminator"),us=class e extends ${static{o(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),O;let r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let s of n){let a=rt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,s)}}return new e({typeName:D.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...M(r)})}};o(Va,"mergeValues");en=class extends ${static{o(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=o((s,a)=>{if(ls(s)||ls(a))return O;let c=Va(s.value,a.value);return c.valid?((ds(s)||ds(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:T.invalid_intersection_types}),O)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};en.create=(e,t,n)=>new en({left:e,right:t,typeName:D.ZodIntersection,...M(n)});Ke=class e extends ${static{o(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.array)return A(r,{code:T.invalid_type,expected:R.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return A(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new ve(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>ne.mergeArray(n,a)):ne.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ke.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ke({items:e,typeName:D.ZodTuple,rest:null,...M(t)})};fs=class e extends ${static{o(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.object)return A(r,{code:T.invalid_type,expected:R.object,received:r.parsedType}),O;let i=[],s=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:s._parse(new ve(r,c,r.path,c)),value:a._parse(new ve(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ne.mergeObjectAsync(n,i):ne.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof $?new e({keyType:t,valueType:n,typeName:D.ZodRecord,...M(r)}):new e({keyType:bt.create(),valueType:t,typeName:D.ZodRecord,...M(n)})}},Yn=class extends ${static{o(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.map)return A(r,{code:T.invalid_type,expected:R.map,received:r.parsedType}),O;let i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:i._parse(new ve(r,c,r.path,[d,"key"])),value:s._parse(new ve(r,l,r.path,[d,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return O;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return O;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}};Yn.create=(e,t,n)=>new Yn({valueType:t,keyType:e,typeName:D.ZodMap,...M(n)});Jn=class e extends ${static{o(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.set)return A(r,{code:T.invalid_type,expected:R.set,received:r.parsedType}),O;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(A(r,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(A(r,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let s=this._def.valueType;function a(l){let d=new Set;for(let u of l){if(u.status==="aborted")return O;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}o(a,"finalizeSet");let c=[...r.data.values()].map((l,d)=>s._parse(new ve(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:I.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:I.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Jn.create=(e,t)=>new Jn({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...M(t)});ps=class e extends ${static{o(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.function)return A(n,{code:T.invalid_type,expected:R.function,received:n.parsedType}),O;function r(c,l){return Br({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Wn(),nt].filter(d=>!!d),issueData:{code:T.invalid_arguments,argumentsError:l}})}o(r,"makeArgsIssue");function i(c,l){return Br({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Wn(),nt].filter(d=>!!d),issueData:{code:T.invalid_return_type,returnTypeError:l}})}o(i,"makeReturnsIssue");let s={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof vt){let c=this;return ce(async function(...l){let d=new pe([]),u=await c._def.args.parseAsync(l,s).catch(h=>{throw d.addIssue(r(l,h)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,s).catch(h=>{throw d.addIssue(i(f,h)),d})})}else{let c=this;return ce(function(...l){let d=c._def.args.safeParse(l,s);if(!d.success)throw new pe([r(l,d.error)]);let u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,s);if(!f.success)throw new pe([i(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ke.create(t).rest(it.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ke.create([]).rest(it.create()),returns:n||it.create(),typeName:D.ZodFunction,...M(r)})}},tn=class extends ${static{o(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};tn.create=(e,t)=>new tn({getter:e,typeName:D.ZodLazy,...M(t)});nn=class extends ${static{o(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:t.data}}get value(){return this._def.value}};nn.create=(e,t)=>new nn({value:e,typeName:D.ZodLiteral,...M(t)});o(qf,"createZodEnum");rn=class e extends ${static{o(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:j.joinValues(r),received:n.parsedType,code:T.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:T.invalid_enum_value,options:r}),O}return ce(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};rn.create=qf;sn=class extends ${static{o(this,"ZodNativeEnum")}_parse(t){let n=j.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==R.string&&r.parsedType!==R.number){let i=j.objectValues(n);return A(r,{expected:j.joinValues(i),received:r.parsedType,code:T.invalid_type}),O}if(this._cache||(this._cache=new Set(j.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=j.objectValues(n);return A(r,{received:r.data,code:T.invalid_enum_value,options:i}),O}return ce(t.data)}get enum(){return this._def.values}};sn.create=(e,t)=>new sn({values:e,typeName:D.ZodNativeEnum,...M(t)});vt=class extends ${static{o(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.promise&&n.common.async===!1)return A(n,{code:T.invalid_type,expected:R.promise,received:n.parsedType}),O;let r=n.parsedType===R.promise?n.data:Promise.resolve(n.data);return ce(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};vt.create=(e,t)=>new vt({type:e,typeName:D.ZodPromise,...M(t)});ke=class extends ${static{o(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return O;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?O:l.status==="dirty"?Vt(l.value):n.value==="dirty"?Vt(l.value):l});{if(n.value==="aborted")return O;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?O:c.status==="dirty"?Vt(c.value):n.value==="dirty"?Vt(c.value):c}}if(i.type==="refinement"){let a=o(c=>{let l=i.refinement(c,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?O:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?O:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_t(a))return O;let c=i.transform(a.value,s);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>_t(a)?Promise.resolve(i.transform(a.value,s)).then(c=>({status:n.value,value:c})):O);j.assertNever(i)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:D.ZodEffects,effect:t,...M(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...M(n)});we=class extends ${static{o(this,"ZodOptional")}_parse(t){return this._getType(t)===R.undefined?ce(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};we.create=(e,t)=>new we({innerType:e,typeName:D.ZodOptional,...M(t)});Ve=class extends ${static{o(this,"ZodNullable")}_parse(t){return this._getType(t)===R.null?ce(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ve.create=(e,t)=>new Ve({innerType:e,typeName:D.ZodNullable,...M(t)});on=class extends ${static{o(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===R.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:D.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});an=class extends ${static{o(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Kn(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};an.create=(e,t)=>new an({innerType:e,typeName:D.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});Xn=class extends ${static{o(this,"ZodNaN")}_parse(t){if(this._getType(t)!==R.nan){let r=this._getOrReturnCtx(t);return A(r,{code:T.invalid_type,expected:R.nan,received:r.parsedType}),O}return{status:"valid",value:t.data}}};Xn.create=e=>new Xn({typeName:D.ZodNaN,...M(e)});sE=Symbol("zod_brand"),Gr=class extends ${static{o(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Wr=class e extends ${static{o(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return o(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?O:s.status==="dirty"?(n.dirty(),Vt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?O:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:D.ZodPipeline})}},cn=class extends ${static{o(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=o(i=>(_t(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Kn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};cn.create=(e,t)=>new cn({innerType:e,typeName:D.ZodReadonly,...M(t)});o(Wf,"cleanParams");o(Yf,"custom");oE={object:me.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(D||(D={}));aE=o((e,t={message:`Input not instance of ${e.name}`})=>Yf(n=>n instanceof e,t),"instanceOfType"),Jf=bt.create,Xf=zt.create,cE=Xn.create,lE=qt.create,Zf=Yt.create,dE=Jt.create,uE=zn.create,fE=Xt.create,pE=Zt.create,mE=wt.create,hE=it.create,gE=De.create,yE=qn.create,_E=st.create,bE=me.create,wE=me.strictCreate,vE=Qt.create,kE=us.create,xE=en.create,SE=Ke.create,EE=fs.create,TE=Yn.create,AE=Jn.create,RE=ps.create,CE=tn.create,IE=nn.create,NE=rn.create,OE=sn.create,DE=vt.create,PE=ke.create,ME=we.create,$E=Ve.create,LE=ke.createWithPreprocess,FE=Wr.create,jE=o(()=>Jf().optional(),"ostring"),UE=o(()=>Xf().optional(),"onumber"),HE=o(()=>Zf().optional(),"oboolean"),BE={string:o(e=>bt.create({...e,coerce:!0}),"string"),number:o(e=>zt.create({...e,coerce:!0}),"number"),boolean:o(e=>Yt.create({...e,coerce:!0}),"boolean"),bigint:o(e=>qt.create({...e,coerce:!0}),"bigint"),date:o(e=>Jt.create({...e,coerce:!0}),"date")},GE=O});var m={};ee(m,{BRAND:()=>sE,DIRTY:()=>Vt,EMPTY_PATH:()=>LS,INVALID:()=>O,NEVER:()=>GE,OK:()=>ce,ParseStatus:()=>ne,Schema:()=>$,ZodAny:()=>wt,ZodArray:()=>st,ZodBigInt:()=>qt,ZodBoolean:()=>Yt,ZodBranded:()=>Gr,ZodCatch:()=>an,ZodDate:()=>Jt,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>us,ZodEffects:()=>ke,ZodEnum:()=>rn,ZodError:()=>pe,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ps,ZodIntersection:()=>en,ZodIssueCode:()=>T,ZodLazy:()=>tn,ZodLiteral:()=>nn,ZodMap:()=>Yn,ZodNaN:()=>Xn,ZodNativeEnum:()=>sn,ZodNever:()=>De,ZodNull:()=>Zt,ZodNullable:()=>Ve,ZodNumber:()=>zt,ZodObject:()=>me,ZodOptional:()=>we,ZodParsedType:()=>R,ZodPipeline:()=>Wr,ZodPromise:()=>vt,ZodReadonly:()=>cn,ZodRecord:()=>fs,ZodSchema:()=>$,ZodSet:()=>Jn,ZodString:()=>bt,ZodSymbol:()=>zn,ZodTransformer:()=>ke,ZodTuple:()=>Ke,ZodType:()=>$,ZodUndefined:()=>Xt,ZodUnion:()=>Qt,ZodUnknown:()=>it,ZodVoid:()=>qn,addIssueToContext:()=>A,any:()=>mE,array:()=>_E,bigint:()=>lE,boolean:()=>Zf,coerce:()=>BE,custom:()=>Yf,date:()=>dE,datetimeRegex:()=>zf,defaultErrorMap:()=>nt,discriminatedUnion:()=>kE,effect:()=>PE,enum:()=>NE,function:()=>RE,getErrorMap:()=>Wn,getParsedType:()=>We,instanceof:()=>aE,intersection:()=>xE,isAborted:()=>ls,isAsync:()=>Kn,isDirty:()=>ds,isValid:()=>_t,late:()=>oE,lazy:()=>CE,literal:()=>IE,makeIssue:()=>Br,map:()=>TE,nan:()=>cE,nativeEnum:()=>OE,never:()=>gE,null:()=>pE,nullable:()=>$E,number:()=>Xf,object:()=>bE,objectUtil:()=>Ba,oboolean:()=>HE,onumber:()=>UE,optional:()=>ME,ostring:()=>jE,pipeline:()=>FE,preprocess:()=>LE,promise:()=>DE,quotelessJson:()=>PS,record:()=>EE,set:()=>AE,setErrorMap:()=>$S,strictObject:()=>wE,string:()=>Jf,symbol:()=>uE,transformer:()=>PE,tuple:()=>SE,undefined:()=>fE,union:()=>vE,unknown:()=>hE,util:()=>j,void:()=>yE});var za=_(()=>{cs();Wa();Hf();Hr();Qf();as()});var le=_(()=>{za();za()});var qa,Ya=_(()=>{"use strict";le();qa=m.object({id:m.string().min(1),title:m.string().min(1).max(200),type:m.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:m.enum(["community","curated"]),lesson_class:m.enum(["general","architecture"]).default("general"),quality_tier:m.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:m.object({source:m.enum(["memory","vault","claude-md"]),source_id:m.string().min(1),migrated_at:m.string(),migrated_from_workspace:m.string().optional()}).optional(),context:m.object({tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tags:m.array(m.string()).default([])}),summary:m.string().min(1).max(500),problem:m.string().optional(),solution:m.string().optional(),gotchas:m.array(m.string()).default([]),template_body:m.string().min(1).optional(),target_file:m.string().min(1).optional(),submitted_by:m.string().optional(),evidence:m.string().optional(),last_validated_at:m.string().optional(),tool_versions:m.record(m.string(),m.string()).optional(),upvotes:m.number().int().nonnegative().default(0),version:m.number().int().min(1).default(1),changed_at:m.string().optional(),changelog:m.string().max(500).optional(),revision_of:m.string().optional(),org_id:m.string().uuid().optional(),org_name:m.string().optional(),scope:m.literal("private").optional(),body:m.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:m.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:m.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))})});var WE,ep=_(()=>{"use strict";le();Ya();WE=qa.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:m.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:m.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:m.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:m.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})})});var tp,np,rp,ip,Ja,sp,op,ap,KE,cp=_(()=>{"use strict";le();tp=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],np=m.enum(tp),rp=["new_to_ai_agents","new_to_this_client","experienced"],ip=m.enum(rp),Ja=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],sp=Ja.map(e=>e.header),op=m.object({experience_level:m.array(ip).default([]),stack_filters:m.array(m.string()).default([])}).default({experience_level:[],stack_filters:[]}),ap=m.object({id:m.string().min(1),client:np,title:m.string().min(1),last_updated:m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:op,version:m.number().int().min(1).default(1),changelog:m.string().max(500).optional()}),KE=ap.extend({body:m.string().min(1)})});var dp,ms,up,hs,VE,zE,fp,pp,mp,hp,gs,qE,YE,lp,JE,gp,XE,yp=_(()=>{"use strict";le();dp=["operating_procedure","code_review","communication_style"],ms=m.enum(dp),up=["info","recommended","required"],hs=m.enum(up),VE=["optional","default_on","mandatory"],zE=m.enum(VE),fp=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],pp=m.enum(fp),mp=["verify","contribute","mixed"],hp=m.enum(mp),gs=m.object({clients:m.array(pp).default([]),stacks:m.array(m.string()).default([]),intents:m.array(hp).default([])}).default({clients:[],stacks:[],intents:[]}),qE=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,YE=64,lp=200,JE=m.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),gp=m.object({id:m.string().min(5).max(YE).regex(qE,"id must match conv_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),scope:ms,version:m.number().int().min(1),changed_at:JE,changelog:m.string().max(500).optional(),applies_to:gs,severity:hs.default("recommended"),disableability:zE.default("default_on"),summary:m.string().min(1).max(lp,`summary must be \u2264 ${lp} chars (rendered as one line in init-push)`),review_gate:m.object({enabled:m.boolean(),min_matched_symbols:m.number().int().min(1).max(8).default(2),hard:m.boolean().default(!1)}).optional(),gateway_gate:m.object({enabled:m.boolean(),deny_tools:m.array(m.string().min(1).max(128)).min(1).max(16),servers:m.array(m.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),XE=gp.extend({body:m.string().min(1)})});var kt=_(()=>{"use strict";Ya();ep();cp();yp()});var Xa,ys,Za,_p,bp,wp,ZE,vp=_(()=>{"use strict";le();Xa=m.object({type:m.literal("text"),md:m.string().min(1).max(2e4)}),ys=m.number().min(0).max(1).optional(),Za=m.object({type:m.literal("media"),kind:m.enum(["image","video"]),url:m.string().url().max(2048),alt:m.string().max(500).optional(),caption:m.string().max(500).optional(),fog:m.object({top:ys,right:ys,bottom:ys,left:ys}).optional()}),_p=m.object({label:m.string().min(1).max(40),color:m.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),bp=m.object({type:m.literal("accordion"),title:m.string().min(1).max(200),subtag:_p.optional(),blocks:m.array(m.discriminatedUnion("type",[Xa,Za])).max(50)}),wp=m.discriminatedUnion("type",[Xa,Za,bp]),ZE=m.array(wp).max(100)});var kp,QE,xp,Sp,e0,t0,n0,Ep=_(()=>{"use strict";le();kp=["free","solo_pro","team","enterprise"],QE=m.enum(kp),xp=["solo_pro","team","enterprise"],Sp=m.enum(xp),e0=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),t0=m.object({user_id:m.string().uuid(),tier:Sp,reason:m.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:e0.nullable().optional(),auto_revoke_on_stripe:m.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),n0=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Tp=_(()=>{"use strict"});var r0,i0,s0,Ap=_(()=>{"use strict";le();r0=m.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),i0=m.object({org_id:m.string().uuid(),seats:m.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:m.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:r0.nullable().optional(),auto_revoke_on_stripe:m.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),s0=m.object({override_id:m.string().uuid(),reason:m.string().min(3).max(200).optional()})});var Rp,o0,Cp,Ip,Np,Op,a0,Dp=_(()=>{"use strict";le();Rp=m.enum(["info","important","critical"]),o0=m.enum(["pass","warn","fail"]),Cp=m.object({type:m.enum(["template","lesson"]),id:m.string().min(1)}),Ip=m.object({languages:m.array(m.string()).optional(),tools:m.array(m.string()).optional()}).optional(),Np=m.discriminatedUnion("kind",[m.object({kind:m.literal("file-exists"),path:m.string().min(1)}),m.object({kind:m.literal("any-file-exists"),paths:m.array(m.string().min(1)).min(1)}),m.object({kind:m.literal("any-agent-config")}),m.object({kind:m.literal("file-size-budget"),field:m.enum(["claude_md","readme"]),max_chars:m.number().int().positive()}),m.object({kind:m.literal("readme-section-present"),headers:m.array(m.string().min(1)).min(1)}),m.object({kind:m.literal("adr-dir-present")}),m.object({kind:m.literal("git-present")}),m.object({kind:m.literal("quality-gates-configured"),pass_if_at_least:m.number().int().min(1).max(4).optional(),warn_if_at_least:m.number().int().min(0).max(4).optional()}),m.object({kind:m.literal("storage-risk-safe"),allow_unknown:m.boolean().optional()}),m.object({kind:m.literal("doc-path-discoverability")})]),Op=m.object({id:m.string().min(1),title:m.string().min(1),severity:Rp,weight:m.number().int().positive().max(100),applies_when:Ip,check:Np,fail_message:m.string().min(1),warn_message:m.string().optional(),remediation:Cp.optional()}),a0=m.object({version:m.literal(1),checks:m.array(Op).min(1)})});function l0(e){if(!c0.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}function _s(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}function d0(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}var c0,bs,Pp,Mp,ze,Qa,$p,u0,Lp=_(()=>{"use strict";le();c0=/^\d{4}-\d{2}-\d{2}$/;o(l0,"isRealDate");bs=m.string().refine(l0,{message:"expected a real calendar date as YYYY-MM-DD"}),Pp=["exact","prefix"],Mp=m.enum(Pp),ze=m.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),Qa=[2e5,272e3],$p=m.object({model_pattern:m.string().min(1).max(100),match_kind:Mp,valid_from:bs,valid_to:bs.nullable().optional(),input:ze,output:ze,cache_read:ze,cache_write_5m:ze,cache_write_1h:ze,long_context:m.enum(["same_price","tiered"]).optional(),input_above_200k:ze.optional(),output_above_200k:ze.optional(),cache_read_above_200k:ze.optional(),cache_write_5m_above_200k:ze.optional(),cache_write_1h_above_200k:ze.optional(),context_threshold_tokens:m.number().int().positive().nullable().optional(),source_url:m.string().url().max(500).nullable().optional(),note:m.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>_s(e)===0||_s(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||_s(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>_s(e)===0||e.context_threshold_tokens==null||Qa.includes(e.context_threshold_tokens),{message:`above-rates are only supported at a context_threshold_tokens the analyzer cuts at (${Qa.join(", ")}) \u2014 it cannot see another boundary`,path:["context_threshold_tokens"]});o(_s,"aboveRateCount");o(d0,"rowKey");u0=m.object({changelog:m.string().min(1).max(500),as_of:bs,source_url:m.string().url().max(500),rows:m.array($p).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,s)=>{let a=d0(i),c=n.get(a);c!==void 0?t.addIssue({code:m.ZodIssueCode.custom,path:["rows",s],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,s)});let r=new Map;e.rows.forEach((i,s)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:s,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((s,a)=>s.r.valid_from.localeCompare(a.r.valid_from));for(let s=0;s<i.length-1;s++){let a=i[s],c=i[s+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:m.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}})});var Zn=_(()=>{"use strict"});var Kr=_(()=>{"use strict"});var Hp=_(()=>{"use strict";Kr();Zn()});var Bp=_(()=>{"use strict";Zn()});var Gp=_(()=>{"use strict";kt();Kr();Zn()});var Wp=_(()=>{"use strict";Kr();Zn()});var Kp=_(()=>{"use strict";Zn();Hp();Bp();Gp();Wp();Kr()});var I0,N0,Vp,O0,zp,ec,qp,Yp,Jp,Xp,D0,tc=_(()=>{"use strict";le();kt();I0=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,N0=64,Vp=200,O0=1e3,zp=m.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,m.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),ec=m.enum(["low","medium","high"]),qp=m.object({owner:m.string().min(1).max(160).optional(),risk_level:ec.optional(),reviewed_at:zp.optional()}).default({}),Yp=m.object({tags:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),limit:m.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),Jp=m.object({lesson_query:Yp,lesson_pins:m.array(m.string()).default([]),lesson_excludes:m.array(m.string()).default([]),convention_ids:m.array(m.string()).default([]),template_ids:m.array(m.string()).default([]),setup_guide_ids:m.array(m.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),Xp=m.object({id:m.string().min(6).max(N0).regex(I0,"id must match skill_<lowercase_alphanum_underscore>"),title:m.string().min(1).max(200),version:m.number().int().min(1),changed_at:zp,tier:m.enum(["community","curated"]).default("curated"),summary:m.string().min(1).max(Vp,`summary must be \u2264 ${Vp} chars (rendered as one line in skill_index)`),description:m.string().max(O0).optional(),applies_to:gs,membership:Jp,governance:qp}),D0=Xp.extend({body:m.string().default(""),org_id:m.string().uuid().optional(),org_name:m.string().optional()})});var Zp,Qp,em,tm,nm,rm,P0,im,M0,$0,sm=_(()=>{"use strict";le();tc();Zp=m.enum(["maind","agent-skill"]),Qp=m.enum(["ready","needs_attention","blocked"]),em=m.enum(["info","important","critical"]),tm=m.enum(["pass","warn","fail"]),nm=m.enum(["structure","governance","scope","membership","package","references"]),rm=m.object({id:m.string().min(1),title:m.string().min(1),status:tm,severity:em,category:nm,field:m.string().nullable().optional(),message:m.string().min(1),hint:m.string().optional()}),P0=m.object({lesson_ids:m.array(m.string()).optional(),convention_ids:m.array(m.string()).optional(),template_ids:m.array(m.string()).optional(),setup_guide_ids:m.array(m.string()).optional()}).default({}),im=m.object({name:m.string().min(1).max(64),description:m.string().min(1).max(1024),license:m.string().optional(),compatibility:m.union([m.string(),m.array(m.string())]).optional(),metadata:m.record(m.string()).default({}),"allowed-tools":m.union([m.string(),m.array(m.string())]).optional()}).passthrough(),M0=m.object({directory_name:m.string().min(1).max(120).optional(),frontmatter:im,body:m.string().default(""),file_listing:m.array(m.string()).optional()}),$0=m.object({format:Zp,subject:m.string().min(1),status:Qp,summary:m.string().min(1),counts:m.object({pass:m.number().int().min(0),warn:m.number().int().min(0),fail:m.number().int().min(0)}),checks:m.array(rm),next_steps:m.array(m.string()),trust_note:m.string().min(1)})});var nc=_(()=>{"use strict"});var om,F0,am,cm,lm,Qn,j0,dm,um,fm,pm,mm,hm,gm,ym,U0,_m,bm,wm,xt,rc,vm,km,H0,xm=_(()=>{"use strict";le();kt();nc();om=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],F0=m.enum(om),am=["verdict","advisory"],cm=m.enum(am),lm=["block","warn","note"],Qn=m.enum(lm),j0=m.object({convention_id:m.string().min(1).max(64),convention_version:m.number().int().min(1),severity:hs,scope:ms,grade:cm,matched_symbols:m.array(m.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:m.array(m.string().min(1).max(512)).max(64).default([]),summary:m.string().max(2e3),hard:m.boolean().optional()}),dm=["open","warn","info"],um=m.enum(dm),fm=["introduced","pre_existing"],pm=m.enum(fm),mm=["full","partial","none"],hm=m.enum(mm),gm=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),rule_id:m.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:um,baseline:pm,evidence_hash:m.string().regex(/^[a-f0-9]{64}$/),count:m.number().int().min(1).max(1e5)}),ym=m.object({version:m.literal(1).default(1),actions:m.object({required:Qn.default("block"),recommended:Qn.default("warn"),info:Qn.default("note")}).default({}),overrides:m.array(m.object({convention_id:m.string().min(1).max(64),action:Qn})).max(64).default([]),risk_flag_action:m.enum(["warn","note","ignore"]).default("warn"),detector_overrides:m.array(m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Qn,reason:m.string().min(1).max(200)})).max(32).optional()}),U0=ym.parse({}),_m=["ran","not_applicable","unavailable","ungraded"],bm=m.enum(_m),wm=m.object({detector_id:m.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:m.string().regex(/^\d+\.\d+\.\d+$/),state:bm}),xt=1e3,rc=m.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),vm=m.object({name:m.string().min(1).max(200),qualified_name:m.string().min(1).max(512).optional(),kind:m.string().min(1).max(64).optional(),language:m.string().min(1).max(32).optional(),change:m.enum(["added","modified","co_located"]).optional(),changed_line_count:m.number().int().min(0).max(1e4).optional()}),km=m.object({base_kind:m.enum(["uncommitted","ref"]),changed_file_count:m.number().int().min(0),stale_file_count:m.number().int().min(0),unindexed_file_count:m.number().int().min(0).optional(),truncated:m.boolean(),hunk_coverage:m.enum(["full","partial","none"]),detector_coverage:hm}),H0=m.object({changed_symbols:m.array(vm).max(xt),risk_flags:m.array(m.string().max(64)).max(16),detector_findings:m.array(gm).max(64),detector_runs:m.array(wm).min(1).max(32),diff_stats:km,commit_sha:rc.optional(),base_sha:rc.optional(),merge_base_sha:rc.optional(),dirty:m.boolean().optional(),code_index_version:m.string().min(1).max(32).optional()})});var Sm,Em,Tm,Am,Rm,ic,B0,G0,Cm,Im,Nm,Om,Dm,W0,K0,Pm,Mm,$m,V0,Lm=_(()=>{"use strict";le();Sm=14,Em=14,Tm=14,Am=1,Rm=365,ic=m.number().int().min(Am).max(Rm),B0=["propose","direct"],G0="propose",Cm=["propose","direct"],Im="propose",Nm=["propose","direct"],Om="propose",Dm=["off","propose","direct"],W0=["member","admin","owner"],K0="member",Pm="off",Mm="en",$m=m.object({version:m.literal(1).default(1),at_risk_days:ic.default(Sm),stagnation_days:ic.default(Em),agent_date_mode:m.enum(B0).default(G0),health_manual_ttl_days:ic.default(Tm),agent_event_mode:m.enum(Cm).default(Im),agent_update_mode:m.enum(Nm).default(Om),agent_pull_mode:m.enum(Dm).default(Pm),org_wide_authoring_min_role:m.enum(W0).default(K0),planning_language:m.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Mm)}),V0=$m.parse({})});var Fm,z0,jm=_(()=>{"use strict";le();Fm=m.object({version:m.literal(1).default(1),org_visibility:m.boolean().default(!1),session_span_visibility:m.boolean().default(!0)}),z0=Fm.parse({})});var Um,Hm,q0,Y0,Bm=_(()=>{"use strict";le();Um=m.object({tools:m.array(m.string()).default([]),languages:m.array(m.string()).default([]),platforms:m.array(m.string()).default([]),tags:m.array(m.string()).default([])}),Hm=m.object({id:m.string().uuid(),user_id:m.string().uuid(),project:m.string().max(200).nullable().optional(),title:m.string().min(1).max(200),body:m.string().min(1).max(2e4),context:Um.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:m.string(),updated_at:m.string(),last_recalled_at:m.string().nullable().optional(),recall_count:m.number().int().nonnegative().default(0),graduated_draft_id:m.string().uuid().nullable().optional(),deleted_at:m.string().nullable().optional()}),q0=Hm.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:m.number()}),Y0=m.object({id:m.string().uuid(),title:m.string(),summary:m.string(),tags:m.array(m.string()).default([])})});var Gm=_(()=>{"use strict"});function ws(e){let t=[],n=null;return e.split(`
3
+ `).forEach((r,i)=>{let s=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(s===""||a>n)return;n=null}if(s===""||s.startsWith("#"))return;let c=X0.exec(r);if(!c)return;let l=c[3]??"";if(J0.has(l.trim())){n=a;return}let d=l.split(/\s+#/)[0].trim();d===""||`'"[{&*`.includes(d[0])||d.includes(": ")&&t.push({line:i+1,value:d})}),t}var J0,X0,Wm=_(()=>{"use strict";J0=new Set(["|",">","|-",">-","|+",">+"]),X0=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;o(ws,"plainScalarViolations")});function zr(e,t){let n=o(c=>{let[l,d=""]=c.split("-",2),u=l.split(".").map(f=>{let p=Number(f);return Number.isFinite(p)?p:0});for(;u.length<3;)u.push(0);return[u,d.length>0?d.split("."):[]]},"split"),[r,i]=n(e),[s,a]=n(t);for(let c=0;c<Math.max(r.length,s.length);c+=1){let l=(r[c]??0)-(s[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&a.length===0)return 0;if(i.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(i.length,a.length);c+=1){let l=i[c],d=a[c];if(l===void 0)return-1;if(d===void 0)return 1;let u=/^\d+$/.test(l),f=/^\d+$/.test(d);if(u&&f){let p=Number(l)-Number(d);if(p!==0)return p<0?-1:1}else{if(u!==f)return u?-1:1;if(l!==d)return l<d?-1:1}}return 0}var Km=_(()=>{"use strict";o(zr,"compareSemver")});var qr=_(()=>{"use strict";kt();vp();kt();kt();Ep();Tp();Ap();Dp();Lp();Kp();kt();tc();sm();xm();Lm();jm();Bm();Gm();nc();Wm();Km()});function Vm(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
4
+ `).slice(0,1e3)}var zm=_(()=>{"use strict";o(Vm,"nodeEmbedText")});var sc,oc=_(()=>{"use strict";sc=["function","method","class","interface","enum","type_alias"]});function qm(e,t){let n=Math.min(e.length,t.length),r=0,i=0,s=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,s+=l*l}return i===0||s===0?0:r/(Math.sqrt(i)*Math.sqrt(s))}var Ym=_(()=>{"use strict";o(qm,"cosineSimilarity")});import{execFileSync as Z0}from"node:child_process";import{createHash as Q0}from"node:crypto";import{readFileSync as eT}from"node:fs";import{posix as Pe}from"node:path";function Jm(e){let t=Q0("sha256"),n=[];try{n=Z0("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
5
+ `).filter(l=>tT.test(l)).sort()}catch{return{config:{packages:[],tsconfigs:[]},fingerprint:t.digest("hex")}}let r=new Map,i=o(l=>{if(r.has(l))return r.get(l);try{let d=eT(Pe.join(e,l),"utf8");return r.set(l,d),d}catch{return null}},"read"),s=[],a=new Map;for(let l of n.filter(d=>!d.endsWith("package.json"))){let d=Xm(l,i,0),u=Pe.dirname(l)==="."?"":Pe.dirname(l);l.endsWith("tsconfig.json")&&a.set(u,d),d.paths&&s.push({dir:d.pathsDir??u,baseUrl:d.baseUrl,paths:d.paths})}let c=[];for(let l of n.filter(d=>d.endsWith("package.json"))){let d=Zm(i(l));if(!d||typeof d.name!="string")continue;let u=Pe.dirname(l)==="."?"":Pe.dirname(l),f=a.get(u);c.push({name:d.name,dir:u,exports:d.exports,main:typeof d.main=="string"?d.main:void 0,module:typeof d.module=="string"?d.module:void 0,types:typeof d.types=="string"?d.types:void 0,outDir:f?.outDir,rootDir:f?.rootDir})}for(let l of[...r.keys()].sort())t.update(l).update("\0").update(r.get(l)).update("\0");return{config:{packages:c,tsconfigs:s},fingerprint:t.digest("hex")}}function Xm(e,t,n){let r=Zm(t(e));if(!r)return{};let i=Pe.dirname(e)==="."?"":Pe.dirname(e),s={},a=r.extends;if(typeof a=="string"&&a.startsWith(".")&&n<4){let d=Pe.normalize(Pe.join(i,a.endsWith(".json")?a:a+".json"));s=Xm(d,t,n+1)}let c=r.compilerOptions??{},l={...s};return typeof c.outDir=="string"&&(l.outDir=Pe.normalize(c.outDir)),typeof c.rootDir=="string"&&(l.rootDir=Pe.normalize(c.rootDir)),c.paths&&typeof c.paths=="object"&&(l.paths=c.paths,l.pathsDir=i,l.baseUrl=typeof c.baseUrl=="string"?c.baseUrl:void 0),l}function Zm(e){if(e===null)return null;let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"')n=!0,t+=i;else if(i==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
6
6
  `;)r++;t+=`
7
- `}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(j0(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function j0(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="}"||e[s]==="]")continue}t+=i}return t}var F0,Wm=_(()=>{"use strict";F0=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;o(Hm,"loadModuleConfig");o(Bm,"compilerFacts");o(Gm,"parseJsonc");o(j0,"dropTrailingCommas")});import{posix as Pe}from"node:path";function qr(e,t){let n=Pe.normalize(e).replace(/^\.\//,""),r=[],i=gs.some(c=>n.endsWith(c));i&&r.push(n);let s=/\.d\.(m|c)?ts$/.exec(n);s&&r.push(n.slice(0,-s[0].length)+".ts",n.slice(0,-s[0].length)+".tsx");let a=/\.(js|jsx|mjs|cjs)$/.exec(n);if(a){let c=n.slice(0,-a[0].length);for(let l of gs)r.push(c+l)}if(!i&&!s){for(let c of gs)r.push(n+c);for(let c of gs)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function Vm(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let s=Vm(i,t);if(s)return s}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return Yr(n[t]);for(let i of r){let s=i.indexOf("*");if(s<0)continue;let a=i.slice(0,s),c=i.slice(s+1);if(t.startsWith(a)&&t.endsWith(c)){let l=Yr(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Yr(e):null}function Yr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Yr(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of U0)if(n in t){let r=Yr(t[n]);if(r)return r}}return null}function H0(e,t){let n=Pe.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=Pe.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=Pe.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(Pe.join(s,n.slice(i.length+1)))}return r}var gs,U0,ec,Km,Qn,tc=_(()=>{"use strict";gs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],U0=["import","default","node","require","types"],ec={kind:"unresolved"},Km={kind:"external"};o(qr,"resolvePathCandidates");Qn=class{static{o(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(t,n){let r=`${Pe.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let s=qr(Pe.join(Pe.dirname(t),n),this.files);return s?{kind:"file",path:s}:ec}if(n.startsWith("node:"))return Km;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(s=>n===s.name||n.startsWith(s.name+"/"));if(i){let s=n===i.name?".":"./"+n.slice(i.name.length+1),a=this.viaPackage(i,s);return a?{kind:"file",path:a}:ec}return Km}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=Pe.join(r.dir,r.baseUrl??".");for(let[s,a]of Object.entries(r.paths)){let c=s.indexOf("*"),l=null;if(c<0)s===n&&(l="");else{let d=s.slice(0,c),u=s.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of a){let u=qr(Pe.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return ec}}return null}viaPackage(t,n){let r=[],i=Vm(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let s of[t.module,t.main,t.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let a of H0(t,s)){let c=qr(Pe.join(t.dir,a),this.files);if(c)return c}return null}};o(Vm,"exportTarget");o(Yr,"conditionTarget");o(H0,"toSource")});function Ve(e){return`${e}#<module>`}function ze(e,t,n){return`${e}#${t}:${n}`}var ln=_(()=>{"use strict";o(Ve,"moduleKey");o(ze,"symbolKey")});import{posix as zm}from"node:path";function Ym(e){let t=new Map,n=new Set,r=new Map,i=new Map,s=new Set,a=o((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),s.add(c.nodeKey),B0.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===ze(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),a(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:s}}function Jm(e,t,n=new Qn({packages:[],tsconfigs:[]},t.files)){let r=V0(),i=new nc(e,t,n);for(let s of e)s.language==="python"?z0(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function K0(e,t,n){return t.startsWith(".")?qr(zm.join(zm.dirname(e),t),n):null}function V0(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;e.has(s)||(e.add(s),t.push({srcKey:n,dstKey:r,kind:i}))}}}function z0(e,t,n,r,i){for(let s of t){let a=r.nameToKeys.get(s.targetName);!a||a.length!==1||i(s.fromKey,a[0],s.kind)}for(let s of n){let a=K0(e,s.specifier,r.files);a&&i(s.fromModuleKey,Ve(a),"imports")}}function q0(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return ze(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var B0,qm,G0,W0,nc,Xm=_(()=>{"use strict";ln();tc();B0=new Set(["function","method","class","interface","enum","type_alias"]),qm=["function","class","variable","enum","interface","type_alias"],G0=8,W0=new Set(["globalThis","JSON","Math","Object","Array","Promise","Reflect","Number","String","Boolean","Symbol","BigInt","Date","RegExp","Intl","Atomics","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","console","process","Buffer","require","module","window","document","navigator","location","history","localStorage","sessionStorage","performance","crypto","URL","URLSearchParams","Deno","Bun"]);o(Ym,"buildResolutionIndex");o(Jm,"resolveCrossFileEdges");o(K0,"resolveImportTarget");o(V0,"edgeCollector");o(z0,"legacyFacts");o(q0,"classKeyOfMethod");nc=class{static{o(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let s=new Map;for(let a of i.imports)a.localName&&a.importedName&&s.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(i.filePath,s);for(let a of i.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:i.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:i.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let i=this.resolveRef(t.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of t.imports){let i=this.modules.resolve(t.filePath,r.specifier);i.kind==="file"&&n(Ve(t.filePath),Ve(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let a=this.resolveLocal(t,n.targetName,0);return a?.kind==="symbol"?a.key:null}if(r==="this")return n.kind==="calls"?this.ownMethod(n.fromKey,n.targetName):null;if(n.receiverType&&n.kind==="calls")return this.typedMethod(t,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let a=r.endsWith(".*"),c=a?r.slice(0,-2):r;if(W0.has(c)&&!this.bindings.get(t)?.has(c))return null;let l=this.bindings.get(t)?.get(c);if(l&&this.modules.resolve(t,l.specifier).kind!=="file")return null;if(!a){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),s=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=q0(a);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return s.length===1?s[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);s=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(s?.kind!=="symbol")return null;let a=s.key.endsWith(":class")?[s.key]:[...this.implementers(s.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=ze(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(t)){if(!s.endsWith(":class"))continue;let a=s.indexOf("#"),c=ze(s.slice(0,a),`${s.slice(a+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let a of this.supertypes(s))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let s=t.slice(0,r),a=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=ze(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>G0)return null;this.memo.set(i,null);let s=this.computeExport(t,n,r);return this.memo.set(i,s),s}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let s=this.topLevel(t,n);if(s)return s;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(t,l.specifier);if(d.kind!=="file")continue;let u=this.resolveExport(d.path,n,r+1);u&&c.set(u.kind==="symbol"?u.key:`ns:${u.file}`,u)}return c.size===1?[...c.values()][0]:null}topLevel(t,n){let r=this.index.topLevel.get(t)?.get(n);if(!r||r.length===0)return null;if(r.length===1)return{kind:"symbol",key:r[0]};let i=o(s=>{let a=qm.indexOf(s.slice(s.lastIndexOf(":")+1));return a<0?qm.length:a},"rank");return{kind:"symbol",key:[...r].sort((s,a)=>i(s)-i(a))[0]}}}});function er(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function Jr(e){return e.toLowerCase().endsWith(".d.ts")}var ys=_(()=>{"use strict";o(er,"languageForPath");o(Jr,"isSkippablePath")});import{appendFileSync as Y0,existsSync as Zm,mkdirSync as J0,readFileSync as X0}from"node:fs";import{join as Z0}from"node:path";function Xr(e,t={}){try{if(!Zm(e)){if(!t.create)return"skipped";J0(e,{recursive:!0})}let n=Z0(e,".gitignore"),r=Zm(n)?X0(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=_s.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let a=r===null?[...Q0,...s]:s,c=r&&!r.endsWith(`
7
+ `}else if(i==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r++}else t+=i}try{let r=JSON.parse(nT(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function nT(e){let t="",n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){t+=i,i==="\\"?t+=e[++r]??"":i==='"'&&(n=!1);continue}if(i==='"'&&(n=!0),i===","){let s=r+1;for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="}"||e[s]==="]")continue}t+=i}return t}var tT,Qm=_(()=>{"use strict";tT=/(^|\/)(package\.json|tsconfig\.json|jsconfig\.json)$/;o(Jm,"loadModuleConfig");o(Xm,"compilerFacts");o(Zm,"parseJsonc");o(nT,"dropTrailingCommas")});import{posix as Me}from"node:path";function Yr(e,t){let n=Me.normalize(e).replace(/^\.\//,""),r=[],i=vs.some(c=>n.endsWith(c));i&&r.push(n);let s=/\.d\.(m|c)?ts$/.exec(n);s&&r.push(n.slice(0,-s[0].length)+".ts",n.slice(0,-s[0].length)+".tsx");let a=/\.(js|jsx|mjs|cjs)$/.exec(n);if(a){let c=n.slice(0,-a[0].length);for(let l of vs)r.push(c+l)}if(!i&&!s){for(let c of vs)r.push(n+c);for(let c of vs)r.push(`${n}/index${c}`)}for(let c of r)if(t.has(c))return c;return null}function th(e,t){if(e==null)return null;if(typeof e=="string")return t==="."?e:null;if(Array.isArray(e)){for(let i of e){let s=th(i,t);if(s)return s}return null}if(typeof e!="object")return null;let n=e,r=Object.keys(n);if(r.length>0&&r.every(i=>i.startsWith("."))){if(t in n)return Jr(n[t]);for(let i of r){let s=i.indexOf("*");if(s<0)continue;let a=i.slice(0,s),c=i.slice(s+1);if(t.startsWith(a)&&t.endsWith(c)){let l=Jr(n[i]);if(l)return l.replace("*",t.slice(a.length,t.length-c.length))}}return null}return t==="."?Jr(e):null}function Jr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Jr(t);if(n)return n}return null}if(e&&typeof e=="object"){let t=e;for(let n of rT)if(n in t){let r=Jr(t[n]);if(r)return r}}return null}function iT(e,t){let n=Me.normalize(t).replace(/^\.\//,""),r=[n];if(e.outDir){let i=Me.normalize(e.outDir).replace(/^\.\//,"").replace(/\/$/,""),s=Me.normalize(e.rootDir??"src").replace(/^\.\//,"").replace(/\/$/,"");(n===i||n.startsWith(i+"/"))&&r.unshift(Me.join(s,n.slice(i.length+1)))}return r}var vs,rT,ac,eh,er,cc=_(()=>{"use strict";vs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"],rT=["import","default","node","require","types"],ac={kind:"unresolved"},eh={kind:"external"};o(Yr,"resolvePathCandidates");er=class{static{o(this,"ModuleResolver")}files;packages;tsconfigs;cache=new Map;constructor(t,n){this.files=n,this.packages=[...t.packages].sort((r,i)=>i.name.length-r.name.length),this.tsconfigs=t.tsconfigs.filter(r=>r.paths&&Object.keys(r.paths).length>0).sort((r,i)=>i.dir.length-r.dir.length)}resolve(t,n){let r=`${Me.dirname(t)}\0${n}`,i=this.cache.get(r);return i||(i=this.compute(t,n),this.cache.set(r,i)),i}compute(t,n){if(n.startsWith(".")){let s=Yr(Me.join(Me.dirname(t),n),this.files);return s?{kind:"file",path:s}:ac}if(n.startsWith("node:"))return eh;let r=this.viaTsconfigPaths(t,n);if(r)return r;let i=this.packages.find(s=>n===s.name||n.startsWith(s.name+"/"));if(i){let s=n===i.name?".":"./"+n.slice(i.name.length+1),a=this.viaPackage(i,s);return a?{kind:"file",path:a}:ac}return eh}viaTsconfigPaths(t,n){let r=this.tsconfigs.find(s=>s.dir===""||t.startsWith(s.dir+"/"));if(!r?.paths)return null;let i=Me.join(r.dir,r.baseUrl??".");for(let[s,a]of Object.entries(r.paths)){let c=s.indexOf("*"),l=null;if(c<0)s===n&&(l="");else{let d=s.slice(0,c),u=s.slice(c+1);n.startsWith(d)&&n.endsWith(u)&&n.length>=d.length+u.length&&(l=n.slice(d.length,n.length-u.length))}if(l!==null){for(let d of a){let u=Yr(Me.join(i,d.replace("*",l)),this.files);if(u)return{kind:"file",path:u}}return ac}}return null}viaPackage(t,n){let r=[],i=th(t.exports,n);if(i)r.push(i);else if(t.exports===void 0)if(n==="."){for(let s of[t.module,t.main,t.types])s&&r.push(s);r.push("index")}else r.push(n);for(let s of r)for(let a of iT(t,s)){let c=Yr(Me.join(t.dir,a),this.files);if(c)return c}return null}};o(th,"exportTarget");o(Jr,"conditionTarget");o(iT,"toSource")});function qe(e){return`${e}#<module>`}function Ye(e,t,n){return`${e}#${t}:${n}`}var ln=_(()=>{"use strict";o(qe,"moduleKey");o(Ye,"symbolKey")});import{posix as nh}from"node:path";function ih(e){let t=new Map,n=new Set,r=new Map,i=new Map,s=new Set,a=o((c,l,d)=>{let u=c.get(l);u?u.push(d):c.set(l,[d])},"push");for(let c of e)if(n.add(c.filePath),s.add(c.nodeKey),sT.has(c.kind)&&a(t,c.name,c.nodeKey),c.kind==="method"&&a(i,c.name,c.nodeKey),c.kind!=="module"&&c.nodeKey===Ye(c.filePath,c.name,c.kind)){let l=r.get(c.filePath);l||r.set(c.filePath,l=new Map),a(l,c.name,c.nodeKey)}return{nameToKeys:t,files:n,topLevel:r,methodsByName:i,keys:s}}function sh(e,t,n=new er({packages:[],tsconfigs:[]},t.files)){let r=lT(),i=new lc(e,t,n);for(let s of e)s.language==="python"?dT(s.filePath,s.refs,s.imports,t,r.push):i.resolveFile(s,r.push);return r.edges}function cT(e,t,n){return t.startsWith(".")?Yr(nh.join(nh.dirname(e),t),n):null}function lT(){let e=new Set,t=[];return{edges:t,push(n,r,i){if(n===r)return;let s=`${n} ${r} ${i}`;e.has(s)||(e.add(s),t.push({srcKey:n,dstKey:r,kind:i}))}}}function dT(e,t,n,r,i){for(let s of t){let a=r.nameToKeys.get(s.targetName);!a||a.length!==1||i(s.fromKey,a[0],s.kind)}for(let s of n){let a=cT(e,s.specifier,r.files);a&&i(s.fromModuleKey,qe(a),"imports")}}function uT(e){let t=e.indexOf("#"),n=e.slice(t+1,e.lastIndexOf(":"));return Ye(e.slice(0,t),n.slice(0,n.lastIndexOf(".")),"class")}var sT,rh,oT,aT,lc,oh=_(()=>{"use strict";ln();cc();sT=new Set(["function","method","class","interface","enum","type_alias"]),rh=["function","class","variable","enum","interface","type_alias"],oT=8,aT=new Set(["globalThis","JSON","Math","Object","Array","Promise","Reflect","Number","String","Boolean","Symbol","BigInt","Date","RegExp","Intl","Atomics","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","console","process","Buffer","require","module","window","document","navigator","location","history","localStorage","sessionStorage","performance","crypto","URL","URLSearchParams","Deno","Bun"]);o(ih,"buildResolutionIndex");o(sh,"resolveCrossFileEdges");o(cT,"resolveImportTarget");o(lT,"edgeCollector");o(dT,"legacyFacts");o(uT,"classKeyOfMethod");lc=class{static{o(this,"SymbolResolver")}index;modules;bindings=new Map;exports=new Map;memo=new Map;languages=new Map;heritage=new Map;supertypesMemo=new Map;nameableMemo=new Map;implementersOf=null;constructor(t,n,r){this.index=n,this.modules=r;for(let i of t){this.languages.set(i.filePath,i.language),this.exports.set(i.filePath,i.exports??[]);let s=new Map;for(let a of i.imports)a.localName&&a.importedName&&s.set(a.localName,{specifier:a.specifier,importedName:a.importedName});this.bindings.set(i.filePath,s);for(let a of i.refs){if(a.kind==="calls")continue;let c=this.heritage.get(a.fromKey);c?c.push({file:i.filePath,ref:a}):this.heritage.set(a.fromKey,[{file:i.filePath,ref:a}])}}}resolveFile(t,n){for(let r of t.refs){let i=this.resolveRef(t.filePath,r);i&&n(r.fromKey,i,r.kind)}for(let r of t.imports){let i=this.modules.resolve(t.filePath,r.specifier);i.kind==="file"&&n(qe(t.filePath),qe(i.path),"imports")}}resolveRef(t,n){let r=n.receiver??null;if(r===null){let a=this.resolveLocal(t,n.targetName,0);return a?.kind==="symbol"?a.key:null}if(r==="this")return n.kind==="calls"?this.ownMethod(n.fromKey,n.targetName):null;if(n.receiverType&&n.kind==="calls")return this.typedMethod(t,n.receiverType,n.targetName);if(r!=="?"&&r!=="this.*"&&!r.startsWith("this.")){let a=r.endsWith(".*"),c=a?r.slice(0,-2):r;if(aT.has(c)&&!this.bindings.get(t)?.has(c))return null;let l=this.bindings.get(t)?.get(c);if(l&&this.modules.resolve(t,l.specifier).kind!=="file")return null;if(!a){let d=this.resolveLocal(t,r,0);if(d?.kind==="namespace"){let u=this.resolveExport(d.file,n.targetName,1);return u?.kind==="symbol"?u.key:null}}}if(n.kind!=="calls"||r==="?"||r.endsWith(".*"))return null;let i=this.nameableKeys(t),s=(this.index.methodsByName.get(n.targetName)??[]).filter(a=>{let c=uT(a);if(i.has(c))return!0;for(let l of this.supertypes(c))if(i.has(l)&&this.implementers(l).size===1)return!0;return!1});return s.length===1?s[0]:null}typedMethod(t,n,r){if(n==="#")return null;let i=n.indexOf("."),s;if(i<0)s=this.resolveLocal(t,n,0);else{let c=this.resolveLocal(t,n.slice(0,i),0);s=c?.kind==="namespace"?this.resolveExport(c.file,n.slice(i+1),1):null}if(s?.kind!=="symbol")return null;let a=s.key.endsWith(":class")?[s.key]:[...this.implementers(s.key)];return a.length!==1?null:this.methodOf(a[0],r)}methodOf(t,n){let r=t.indexOf("#"),i=Ye(t.slice(0,r),`${t.slice(r+1,t.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(i))return i;for(let s of this.supertypes(t)){if(!s.endsWith(":class"))continue;let a=s.indexOf("#"),c=Ye(s.slice(0,a),`${s.slice(a+1,s.lastIndexOf(":"))}.${n}`,"method");if(this.index.keys.has(c))return c}return null}implementers(t){if(!this.implementersOf){this.implementersOf=new Map;for(let n of this.heritage.keys())for(let r of this.supertypes(n)){let i=this.implementersOf.get(r);i||this.implementersOf.set(r,i=new Set),i.add(n)}}return this.implementersOf.get(t)??new Set}nameableKeys(t){let n=this.nameableMemo.get(t);if(n)return n;n=new Set;for(let r of this.bindings.get(t)?.keys()??[]){let i=this.resolveLocal(t,r,0);i?.kind==="symbol"&&n.add(i.key)}for(let r of this.index.topLevel.get(t)?.values()??[])for(let i of r)n.add(i);return this.nameableMemo.set(t,n),n}supertypes(t){let n=this.supertypesMemo.get(t);if(n)return n;n=new Set,this.supertypesMemo.set(t,n);for(let{file:r,ref:i}of this.heritage.get(t)??[]){let s=this.resolveRef(r,i);if(s){n.add(s);for(let a of this.supertypes(s))n.add(a)}}return n}ownMethod(t,n){let r=t.indexOf("#"),i=t.lastIndexOf(":");if(r<0||i<r)return null;let s=t.slice(0,r),a=t.slice(r+1,i),c=t.slice(i+1),l=c==="method"?a.slice(0,a.lastIndexOf(".")):c==="class"?a:null;if(!l)return null;let d=Ye(s,`${l}.${n}`,"method");return this.index.keys.has(d)?d:null}resolveLocal(t,n,r){let i=this.bindings.get(t)?.get(n);return i?this.resolveBinding(t,i,r):this.topLevel(t,n)}resolveBinding(t,n,r){let i=this.modules.resolve(t,n.specifier);return i.kind!=="file"?null:n.importedName==="*"?{kind:"namespace",file:i.path}:this.resolveExport(i.path,n.importedName,r+1)}resolveExport(t,n,r){let i=`${t}\0${n}`;if(this.memo.has(i))return this.memo.get(i);if(r>oT)return null;this.memo.set(i,null);let s=this.computeExport(t,n,r);return this.memo.set(i,s),s}computeExport(t,n,r){let i=this.exports.get(t)??[];for(let l of i)if(l.exportedName===n){if(l.specifier){let d=this.modules.resolve(t,l.specifier);return d.kind!=="file"?null:l.importedName==="*"?{kind:"namespace",file:d.path}:this.resolveExport(d.path,l.importedName??n,r+1)}if(l.localName)return this.resolveLocal(t,l.localName,r+1)}let s=this.topLevel(t,n);if(s)return s;let a=this.bindings.get(t)?.get(n);if(a)return this.resolveBinding(t,a,r);let c=new Map;for(let l of i){if(l.exportedName!=="*"||!l.specifier)continue;let d=this.modules.resolve(t,l.specifier);if(d.kind!=="file")continue;let u=this.resolveExport(d.path,n,r+1);u&&c.set(u.kind==="symbol"?u.key:`ns:${u.file}`,u)}return c.size===1?[...c.values()][0]:null}topLevel(t,n){let r=this.index.topLevel.get(t)?.get(n);if(!r||r.length===0)return null;if(r.length===1)return{kind:"symbol",key:r[0]};let i=o(s=>{let a=rh.indexOf(s.slice(s.lastIndexOf(":")+1));return a<0?rh.length:a},"rank");return{kind:"symbol",key:[...r].sort((s,a)=>i(s)-i(a))[0]}}}});function tr(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}function Xr(e){return e.toLowerCase().endsWith(".d.ts")}var ks=_(()=>{"use strict";o(tr,"languageForPath");o(Xr,"isSkippablePath")});import{appendFileSync as fT,existsSync as ah,mkdirSync as pT,readFileSync as mT}from"node:fs";import{join as hT}from"node:path";function Zr(e,t={}){try{if(!ah(e)){if(!t.create)return"skipped";pT(e,{recursive:!0})}let n=hT(e,".gitignore"),r=ah(n)?mT(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),s=xs.filter(l=>!i.has(l));if(s.length===0)return"unchanged";let a=r===null?[...gT,...s]:s,c=r&&!r.endsWith(`
8
8
  `)?`
9
- `:"";return Y0(n,c+a.join(`
9
+ `:"";return fT(n,c+a.join(`
10
10
  `)+`
11
- `),r===null?"created":"appended"}catch{return"skipped"}}var _s,rc,Q0,bs=_(()=>{"use strict";_s=["code-index.sqlite","code-index.sqlite-wal","code-index.sqlite-shm","index-refresh.lock","conventions-cache.json","conventions-cache.json.*.tmp","context.md","manifest.json","git-context.md","review.md","review.json","review-comment.md","run-review.md","pr-body.md","HANDOFF-*.md"],rc=["# Written by the maind tools: machine-local files that must not be committed.","# Missing lines are appended, nothing is removed \u2014 your own lines stay.",'# Never "*": this directory also holds files that ARE committed (feature.json, gates.json \u2026).'],Q0=rc;o(Xr,"ensureMaindLocalIgnore")});import{execFileSync as eT}from"node:child_process";import{createHash as tT}from"node:crypto";import{readFileSync as nT,readdirSync as rT,statSync as iT}from"node:fs";import{posix as sc,sep as Qm}from"node:path";function C(e,t){try{return eT("git",[...sT,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function oT(e){return Qm==="/"?e:e.split(Qm).join("/")}function ws(e){let t=[];for(let n of e){let r=oT(n).trim();if(!r||Jr(r))continue;let i=er(r);i&&t.push({path:r,language:i})}return t}function th(e){return ws(e)}function nh(e){let t=St(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return ws(t.split(`
12
- `));let n=[];return rh(e,"",n),ws(n)}function rh(e,t,n){let r;try{r=rT(sc.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&eh.has(i.name)||eh.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?rh(e,s,n):i.isFile()&&n.push(s)}}function oc(e,t){return ac(e,t)??t}function ac(e,t){let n=C(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function vs(e,t={}){if(Zr(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?oc(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=St(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of s.split(`
13
- `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=ic((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?a.set(u,"added"):d==="R"?a.set(u,"renamed"):a.set(u,"modified"))}if(n){let c=St(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
14
- `)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let p=l.slice(3),f=p.indexOf(" -> ");f>=0&&(p=p.slice(f+4)),p=ic(p),!(!p||a.has(p))&&(d==="?"||d==="A"||u==="A"?a.set(p,"added"):d==="R"?a.set(p,"renamed"):a.set(p,"modified"))}}return a}function ic(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function cc(e,t={}){let n=vs(e,t);return n===null?null:ws(n.keys())}function ih(e,t){try{let n=iT(sc.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function ks(e){return tT("sha256").update(e).digest("hex")}function Zr(e){return St(e,["rev-parse","HEAD"])?.trim()??null}function xs(e,t){return St(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function lc(e){let t=St(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
- `).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=aT(e);return n.some(i=>r===null||!cT(e,i,r))}function aT(e){let t=St(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function cT(e,t,n){let r=t[0],i=t[1];if(ic(t.slice(3))!==n)return!1;let s;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))s="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let p=St(e,["show",`HEAD:${n}`]);if(p===null)return!1;s=p}else return!1;let a;try{a=nT(sc.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=o(p=>p.replace(/\r\n/g,`
16
- `),"norm"),l=c(s),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([..._s,...rc]);return d.slice(l.length).split(`
17
- `).map(p=>p.trim()).every(p=>p.length===0||u.has(p))}var eh,sT,St,pe=_(()=>{"use strict";ys();bs();eh=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),sT=["-c","diff.renames=true","-c","core.quotePath=false","-c","diff.algorithm=myers","-c","diff.indentHeuristic=true","-c","diff.interHunkContext=0","-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","diff.relative=false","-c","diff.renameLimit=1000"];o(C,"runGit");St=C;o(oT,"toPosix");o(ws,"classify");o(th,"classifyPaths");o(nh,"discoverSourceFiles");o(rh,"walk");o(oc,"resolveDiffBase");o(ac,"resolveMergeBase");o(vs,"enumerateChangedPaths");o(ic,"unquote");o(cc,"changedSourceFiles");o(ih,"statFile");o(ks,"hashContent");o(Zr,"headCommit");o(xs,"resolveCommitSha");o(lc,"isWorktreeDirty");o(aT,"toolIgnoreRepoPath");o(cT,"isToolOnlyIgnoreChange")});function oh(e,t={}){if(C(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?oc(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=C(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(s,"utf8")>lT?c="none":fT(s,a,()=>{c="partial"}),n){let l=C(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
18
- `)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||a.has(u))&&a.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function fT(e,t,n){let r=null,i=0,s=!1,a=!1,c=o(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
19
- `)){if(l.startsWith("diff --git ")){c(),s=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:a?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=pT.exec(l);if(d){if(i++,i>dT){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let u=Number(d[1]),p=d[2]===void 0?1:Number(d[2]);p>0?r.addedRanges.push({start:u,end:u+p-1}):r.deletionPoints.push(u);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<uT&&r.addedLines.push(l.slice(1))}c()}var lT,dT,uT,sh,pT,ah=_(()=>{"use strict";pe();lT=16*1024*1024,dT=500,uT=4e3,sh=256*1024,pT=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;o(oh,"changedHunks");o(fT,"parseUnifiedDiff")});function uc(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=ph&&r++,c>i&&(i=c);for(let d of a.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=a.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>s&&(s=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}function gT(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function lh(e){return e.split(mT).filter(t=>t.trim().length>0)}function dh(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(hT);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function yT(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function fh(e,t,n={}){let r=gT(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,uh),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,dc),l=[];for(let u of c){let p=C(e,["log","-n",String(s),ch,"--",u]),f=p===null?[]:lh(p).map(dh).filter(h=>h!==null);l.push({path:u,lastCommits:f.slice(0,r),ownership:i?{topAuthors:yT(f),commitsInWindow:f.length}:null})}let d=null;if(n.since){let u=xs(e,n.since),p=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],f=C(e,["log",...p,"-n",String(Ss+1),ch,"--name-only","--",...c]),h=[];if(f!==null)for(let g of lh(f)){let y=g.split(`
20
- `),b=dh(y[0]??"");if(!b)continue;let w=y.slice(1).filter(x=>x.trim().length>0).length;h.push({sha:b.sha,dateIso:b.dateIso,authorName:b.authorName,subject:b.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Ss),truncated:h.length>Ss}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:a.length>dc}}var mT,hT,uh,dc,Ss,ch,ph,pc=_(()=>{"use strict";pe();mT="",hT="\0",uh=200,dc=50,Ss=100,ch="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",ph=10;o(uc,"aggregateHistoryContext");o(gT,"clamp");o(lh,"splitRecords");o(dh,"parseHistoryRecord");o(yT,"aggregateOwnership");o(fh,"readFileHistory")});import{execFileSync as _T}from"node:child_process";import{readdirSync as bT,statSync as mh}from"node:fs";import{isAbsolute as wT,join as fc,relative as vT,resolve as kT}from"node:path";function ST(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function ET(e,t){try{let n=_T("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}function TT(e){let t;try{t=bT(e)}catch{return null}for(let n of t.filter(ST))try{let r=mh(fc(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function AT(e){try{return mh(e).isDirectory()}catch{return!1}}function RT(e,t){let n=vT(e,t);return!n||n.startsWith("..")?t:n}function mc(e){let t=xT.filter(c=>AT(fc(e,c))),n=ET(e,"core.hooksPath"),r=n?wT(n)?n:kT(e,n):fc(e,".git","hooks"),i=RT(e,r),s=TT(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function hc(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}var xT,gc=_(()=>{"use strict";xT=[".githooks",".husky"];o(ST,"isRealHook");o(ET,"gitConfig");o(TT,"hasExecutableHook");o(AT,"isDir");o(RT,"displayPath");o(mc,"resolveHookState");o(hc,"describeHookState")});import{posix as hh}from"node:path";function tr(e){let t=CT.exec(e);return t?t[1]:null}function st(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function dn(e,t){let n=C(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(s=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let a=hh.basename(s),c=tr(a);if(c===null)continue;let l=hh.dirname(s),d=i.get(l)??[];d.push({path:s,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([s,a])=>({dir:s,files:a.sort((c,l)=>st(c.version,l.version))})).sort((s,a)=>s.dir.localeCompare(a.dir))}function Qr(e){let t=C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var CT,ei=_(()=>{"use strict";pe();CT=/^(\d+)_.+\.sql$/;o(tr,"parseMigrationVersion");o(st,"compareVersions");o(dn,"discoverSupabaseProjects");o(Qr,"resolveDefaultBranch")});import{execFileSync as IT}from"node:child_process";import{existsSync as de,readFileSync as Et,readdirSync as Es,statSync as _c}from"node:fs";import{posix as F}from"node:path";function PT(e,t){let n=(()=>{let i=C(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=F.dirname(e);for(let i=0;i<8&&r&&r!==F.dirname(r);i++){if(de(F.join(r,".git"))){let s=(()=>{let c=C(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&wc(n,s))){let c=MT(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=F.dirname(r)}return null}function MT(e,t){let n=[];for(let r of OT){let i;try{i=Es(F.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let a=`${r}/${s}`,c=F.join(e,a),l=F.join(t,a);try{let d=_c(c),u=_c(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>DT)continue;Et(c).equals(Et(l))||n.push(a)}catch{continue}}}return n.sort()}function kh(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let s=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(s){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!s&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${vc}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:c.map(l=>`${l.install} (in ${F.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${c} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=o(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=c.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:c.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let a=$T(e.hooks);return a&&t.push(a),LT(t)}function $T(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:hc(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}function LT(e){return[...e].sort((t,n)=>gh[t.status]-gh[n.status]||t.id.localeCompare(n.id))}function xh(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function ot(e){let t=e?.trim();return t||null}function FT(e){let t=ot(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function jT(e){let t=ot(C(e,["rev-parse","--git-dir"]));if(!t)return null;let n=F.isAbsolute(t)?t:F.join(e,t);return de(F.join(n,"rebase-merge"))||de(F.join(n,"rebase-apply"))?"rebase":de(F.join(n,"MERGE_HEAD"))?"merge":de(F.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function UT(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
21
- `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function HT(e){let t=F.join(e,vc);if(!de(t))return[];try{return Et(t,"utf8").split(`
22
- `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function BT(e){try{return dn(e).map(t=>F.join(F.dirname(t.dir),"config.toml"))}catch{return[]}}function GT(e){let t=C(e,["ls-files","-z","--",...NT]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=vh[F.basename(r)];if(i===void 0)continue;let s=F.dirname(r);if(!WT(e,s))continue;let a=s==="."?"node_modules":F.join(s,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function WT(e,t){return t==="."?!0:bc(e,t)}function bc(e,t){if(de(F.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Et(F.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Sh(e,t={}){if(ot(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=ot(C(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,a=FT(e),c=ot(C(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let j=ot(C(e,["rev-parse","HEAD"])),H=ot(C(e,["rev-parse","@{u}"]));l=j!=null&&H!=null?j===H:null,d=C(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,p=null;if(a){let j=ot(C(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(j){let[H,N]=j.split(/\s+/).map(U=>Number.parseInt(U,10));Number.isFinite(H)&&(p=H),Number.isFinite(N)&&(u=N)}}let h=(C(e,["status","--porcelain"])??"").split(`
23
- `).filter(j=>j.trim().length>0).length,g=jT(e),y=ot(C(e,["rev-parse","--show-toplevel"]))??e,b=UT(C(e,["worktree","list","--porcelain"])??""),w=b[0]?.path??null,x=w!=null&&wc(w,y),S=Math.max(0,b.length-1),k=null;if(w&&!wc(w,y)){let j=o(N=>de(F.join(w,N))&&!de(F.join(y,N)),"here"),H=[...wh,...BT(y),...HT(y),...t.probePaths??[]];k={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(H.filter(j))],missingDeps:GT(y).filter(N=>j(N.dir))}}let v=PT(y,e),T=t.includeRelease===!1?null:XT(e,s),O=[];return a&&(O=(C(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
- `).map(H=>H.trim()).filter(H=>H.length>0)),{isRepo:!0,branch:s,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:p,uncommitted:h,detachedHead:i,inProgressOp:g,isSharedMainTree:x,otherWorktrees:S,worktreeParity:k,toolCopyDrift:v,stalePackageBuilds:Eh(y),release:T,unmergedMigrations:O,hooks:mc(e)}}function wc(e,t){let n=o(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function zT(e){let t=new Set;bc(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<_h;){let i=n.pop();if(i===void 0)break;if(i.depth>=VT)continue;let s;try{s=Es(F.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of s){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:F.join(i.rel,a.name);if(r+=1,r>=_h)break;bc(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function qT(e){let t=[];try{let n=F.join(e,"pnpm-workspace.yaml");if(de(n)){let r=!1;for(let i of Et(n,"utf8").split(`
25
- `)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);a?t.push(a[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=F.join(e,"package.json");if(de(r)){let i=JSON.parse(Et(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function YT(e){let t=[];for(let n of zT(e)){let r=n==="."?e:F.join(e,n),i=o(s=>n==="."?s:F.join(n,s),"prefix");for(let s of qT(r)){if(t.length>=yc)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let a=s.slice(0,-2),c=F.join(r,a);if(!de(c))continue;for(let l of Es(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(F.join(a,l.name))),t.length>=yc)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,yc)}function bh(e){let t=null,n=0,r=[e];for(;r.length>0&&n<yh;){let i=r.pop();if(i===void 0)break;let s;try{s=Es(i,{withFileTypes:!0})}catch{continue}for(let a of s){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=F.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=_c(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=yh)break}}}return t}function JT(e,t){let n=new Set;for(let r of t)try{let i=F.join(e,r,"package.json");if(!de(i))continue;let s=JSON.parse(Et(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=s[a];if(!(c===null||typeof c!="object"))for(let[l,d]of Object.entries(c))typeof d=="string"&&d.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Eh(e){let t=[],n=YT(e),r=JT(e,n);for(let i of n)try{let s=F.join(e,i,"package.json");if(!de(s))continue;let a=JSON.parse(Et(s,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=o(w=>{if(typeof w!="string")return null;let x=w.replace(/^\.\//,"").split("/")[0];return x==="build"||x==="dist"?x:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let p=l!==null&&d!==null?"both":l!==null?"types":"runtime",f=F.join(e,i,"src"),h=F.join(e,i,u);if(!de(f)||!de(h))continue;let g=bh(f),y=bh(h);if(g===null||y===null)continue;let b=g-y;b>KT&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(b),impact:p})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function XT(e,t){if(!t)return null;let n=ZT(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function ZT(e,t){try{return IT("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function ti(e,t={}){let n=await Sh(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=kh(n),i=xh(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var wh,vc,vh,NT,OT,DT,gh,KT,yc,yh,VT,_h,kc=_(()=>{"use strict";gc();pe();ei();wh=["supabase/config.toml","supabase/.temp",".env"],vc=".maind/worktree-requirements",vh={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},NT=Object.keys(vh).flatMap(e=>[e,"*/"+e]),OT=["scripts"],DT=512*1024;o(PT,"gatherToolCopyDrift");o(MT,"compareToolDirs");o(kh,"computeDivergence");o($T,"computeHookFinding");gh={open:0,warn:1,info:2,passed:3};o(LT,"sortFindings");o(xh,"isHealthy");o(ot,"trimOrNull");o(FT,"resolveDefaultBranch");o(jT,"detectInProgressOp");o(UT,"parseWorktrees");o(HT,"readWorktreeRequirements");o(BT,"discoverSupabaseConfigProbes");o(GT,"discoverDependencyDirs");o(WT,"isWorkspaceRoot");o(bc,"hasWorkspaceMarkers");o(Sh,"gatherRepoHealthFacts");o(wc,"samePath");KT=2e3,yc=64,yh=4e3,VT=3,_h=400;o(zT,"findWorkspaceRoots");o(qT,"workspacePatternsAt");o(YT,"listWorkspacePackageDirs");o(bh,"newestMtimeUnder");o(JT,"consumedWorkspaceNames");o(Eh,"gatherStalePackageBuilds");o(XT,"gatherReleaseFact");o(ZT,"runGh");o(ti,"checkDivergence")});import{existsSync as xc,readdirSync as Th}from"node:fs";import{posix as qe}from"node:path";function Ec(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Sc)}function Rh(e,t={}){let n=t.minFiles??Tc;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??Ah)}function rr(e){return`${e.dir}#${e.prefix}`}function ni(e){let t=QT.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Ch(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=rr(i),a=e.sightingsByNamespace.get(s);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let p=u.find(g=>n.has(g)),f=u.filter(g=>g!==p),h=`${i.prefix}${l}`;t.push(p?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${h} is already taken`,detail:`This branch adds ${p}, but ${h} already exists as ${f.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:p,sightings:d.filter(g=>g.path!==p),suggestion:`${i.prefix}${Ac(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function Ih(e){return!e.some(t=>t.status==="open")}function Ac(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Rc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Nh(e,t){let n=Rc(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=ni(qe.basename(n));if(!i)return r;let s=`${qe.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>rr(u)===s)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:i.number,taken:d.length>0,sightings:d,suggestion:Ac(c.keys(),i.number)}}function Ts(e){let t=e?.trim();return t||null}function nr(e){return e?e.split(`
26
- `).filter(Boolean):[]}function eA(e){let t=Ts(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Oh(e,t={}){let n=t.minFiles??Tc,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=C(e,r);if(i===null)return[];let s=new Map;for(let a of i.split("\0").filter(Boolean)){let c=qe.dirname(a),l=ni(qe.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=s.get(d);u?u.numbers.push(l.number):s.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(a=>Rh(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>rr(a).localeCompare(rr(c)))}async function Cc(e,t={}){let n=[];if(Ts(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Oh(e,t),s=new Map(i.map(h=>[rr(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=o((h,g,y)=>{let b=qe.dirname(h),w=ni(qe.basename(h));if(!w)return;let x=`${b}#${w.prefix}`;if(!s.has(x))return;let S=c.get(x)??new Map,k=S.get(w.number)??[];k.push({kind:g,where:y,path:h}),S.set(w.number,k),c.set(x,S)},"record"),d=o((h,g,y)=>{if(a.length===0)return;let b=C(e,["ls-tree","-r","--name-only",h,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let w of nr(b))l(w,g,y)},"scanTree");for(let h of a){let g=qe.join(e,h);if(xc(g))try{for(let y of Th(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let u=eA(e),p=t.baseRef??(u?`origin/${u}`:null);if(p?d(p,"default_branch",p):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let h=Ts(C(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of nr(C(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==h&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let h=Ts(C(e,["rev-parse","--show-toplevel"]));for(let g of nr(C(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!xc(y)))for(let b of a){let w=qe.join(y,b);if(xc(w))try{for(let x of Th(w))l(`${b}/${x}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let f=[];if(p&&a.length>0){let h=C(e,["diff","--name-only","--diff-filter=A",`${p}...HEAD`,"--",...a]);h===null?n.push(Sc):f=nr(h);let g=C(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(f=[...f,...nr(g)]);let y=C(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(f=[...f,...nr(y)])}return{isRepo:!0,defaultBranch:u,baseRef:p,namespaces:i,sightingsByNamespace:c,addedPaths:f,skipped:n}}async function un(e,t={}){let n=await Cc(e,t),r=Ch(n);return{ok:Ih(r),findings:r,facts:n}}async function pn(e,t,n={}){let r=Rc(t);if(!ni(qe.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Cc(e,{...n,dirs:n.dirs??[qe.dirname(r)]});return Nh(i,r)}var Sc,QT,Tc,Ah,ri=_(()=>{"use strict";pe();Sc="could not diff against the base ref \u2014 everything reported as info";o(Ec,"isNumberCollisionsGraded");QT=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Tc=3,Ah=.8;o(Rh,"isCounterNamespace");o(rr,"namespaceKey");o(ni,"parseNumbered");o(Ch,"computeNumberCollisions");o(Ih,"isCollisionFree");o(Ac,"suggestNextNumber");o(Rc,"normaliseRepoPath");o(Nh,"checkProposedNumber");o(Ts,"trimOrNull");o(nr,"lines");o(eA,"resolveDefaultBranch");o(Oh,"detectNamespaces");o(Cc,"gatherNumberCollisionFacts");o(un,"checkNumberCollisions");o(pn,"checkNumberForPath")});import{execFileSync as tA}from"node:child_process";import{createHash as nA}from"node:crypto";function Ic(e){return nA("sha256").update(e).digest("hex")}function rA(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function iA(e){let t=rA(e);return t?Ic(t):null}function oA(e){return typeof e=="string"&&sA.test(e)}function Dh(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(oA(t))return t;let n;try{n=tA("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?iA(n):null}var sA,Nc=_(()=>{"use strict";o(Ic,"sha256Hex");o(rA,"normalizeRemoteUrl");o(iA,"projectKeyFromRemote");sA=/^[a-f0-9]{64}$/;o(oA,"isProjectKey");o(Dh,"computeProjectKey")});function Mc(e){return`spec.${e}`}function ir(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function aA(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let a=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Ph(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(aA)}function si(e){return Ic(JSON.stringify(Ph(e)))}var ii,Oc,Dc,Pc,$c=_(()=>{"use strict";Nc();ii={det_number_collisions:{version:"1.2.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.1.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.1.0",rules:["release.phantom","release.unpublished","release.mislabelled"]},det_agent_doc_prose:{version:"1.1.0",rules:["agentdoc.added_prose"]}},Oc="number.collision",Dc="theme.dead_class",Pc="acl.missing_revoke";o(Mc,"specDriftRuleId");o(ir,"gradeEngineStatus");o(aA,"codePointCompare");o(Ph,"normalizeEvidenceForHash");o(si,"hashDetectorEvidence")});import{existsSync as cA,readFileSync as Mh}from"node:fs";import{posix as lA}from"node:path";function Cs(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Is(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
27
- `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function oi(e){return e==='"'||e==="'"||e==="`"}function Ns(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function As(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(oi(s)){i=Cs(e,i);continue}if(Ns(e,i)){i=Is(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function dA(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Ns(e,t)){t=Is(e,t);continue}break}return e.slice(t)}function sr(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(oi(s)){i=Cs(e,i);continue}if(Ns(e,i)){i=Is(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>dA(s).trim()).filter(s=>s.length>0)}function jh(e){let t=Cs(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
28
- `:i==="r"?"\r":i==="t"?" ":i)}function uA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fc(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${uA(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let a=e[i];if(oi(a)){i=Cs(e,i);continue}if(Ns(e,i)){i=Is(e,i);continue}if(!s){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(a===";")return null;i++;continue}if(a==="[")return As(e,i);if(a===";")return null;i++}return null}function jc(e){let t={};if(!e.startsWith("{"))return t;for(let n of sr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();oi(s[0]??"")&&(t[i]=jh(s))}return t}function pA(e,t){if(!e.startsWith("{"))return null;for(let n of sr(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function Uh(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Hh(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Bh(e,t){let n=Fc(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Hh(),i=[],s=0;for(let a of sr(n.slice(1,-1))){if(!a.startsWith("{")){s++;continue}let c=jc(a),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Uh(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Gh(e,t){let n=Fc(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Hh(),i=[],s=0,a=o((c,l,d)=>{let u=t.levels[l],p=l===t.levels.length-1;for(let f of sr(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!f.startsWith("{")){s++;continue}let y=jc(f);for(let[b,w]of Object.entries(u.fields??{}))h[b]=y[String(w)]??"";if(!p&&typeof u.children=="string"){let b=pA(f,u.children);g=b&&b.startsWith("[")?As(b,0):null}}else{if(!f.startsWith("[")){s++;continue}let y=sr(f.slice(1,-1));for(let[b,w]of Object.entries(u.fields??{})){let x=y[Number(w)];h[b]=x!==void 0&&oi(x[0]??"")?jh(x):""}if(!p&&typeof u.children=="number"){let b=y[u.children];g=b!==void 0&&b.startsWith("[")?As(b,0):null}}if(p){let y=h[t.key_field];if(!y){s++;continue}let b=(t.partition_by??[]).map(w=>h[w]??"");i.push({key:y,fields:Uh(h,t.fields),orderPath:b,ordinal:r(b)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function $h(e,t){return t.extractor==="object-array"?Bh(e,t):Gh(e,t)}function Wh(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function Kh(e,t,n){return`spec.drift:${e}#${t}:${n}`}function fA(e){return e.orderPath.join(" / ")||"(flat)"}function Vh(e,t,n,r){let i=[],s=o((d,u,p,f,h,g)=>{i.push({id:Kh(e.id,d,p),contract:e.id,dimension:d,status:u,key:p,title:f,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){s("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${fA(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let p of e.compare_fields??[]){let f=d.fields[p]??"",h=u.fields[p]??"";f!==h&&s("fields","open",`${d.key}.${p}`,`${d.key}: ${p} is "${h||"\u2014"}", the specification says "${f||"\u2014"}"`,`Field \`${p}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),p=l.get(u);p?p.push(d):l.set(u,[d])}for(let[d,u]of l){let p=u.filter(y=>a.has(y.key)).map(y=>y.key),f=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(f),g=p.filter(y=>h.has(y));if(f.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${f.join(" \u2192 ")}
29
- specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if(Wh(d,e.grounding,r))continue;let u=a.has(d);s("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function mA(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let a=s.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Lh(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}function zh(e,t={}){let n=o(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=o(u=>{let p=[],f=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let S=g==null?h.spec.path:h.impl.path;p.push(Lh(h.id,`Declared file could not be read: ${S}`)),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=$h(g,h.spec),w=$h(y,h.impl);if(b.error||w.error){p.push(Lh(h.id,b.error??w.error??"unknown")),f.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let x=b.dropped>0||w.dropped>0;f.push({id:h.id,measured:!0,specRecords:b.records.length,implRecords:w.records.length,partial:x}),x&&p.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${b.dropped} specification and ${w.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),p.push(...Vh(h,b.records,w.records,e.files)),p.push(...mA(h,{spec:b.records.length,impl:w.records.length},u))}return{findings:p,contracts:f}},"runOnce"),s=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let p of u.exceptions??[])c.set(Kh(u.id,p.dimension,p.key),p);let l=s.findings.map(u=>{let p=c.get(u.id);return p?{...u,status:"info",exceptionReason:p.reason}:a.has(u.id)?{...u,status:"info",detail:`${u.detail}
30
- Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,p)=>Fh[u.status]-Fh[p.status]||u.id.localeCompare(p.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:s.contracts}}function Lc(e){let t=e?.trim();return t||null}function Os(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=o(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=o(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=o(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return s(`${u}: not an object`);if(!d)return s(`${u}: \`id\` is missing`);if(!r(l.reason))return s(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let p of["spec","impl"]){let f=n(l[p]);if(!f)return s(`${u}: \`${p}\` is missing`);let h=r(f.extractor);if(!h)return s(`${u}: \`${p}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return s(`${u}: unknown \`${p}.extractor\` "${h}"`);if(!r(f.path)||!r(f.symbol)||!r(f.key_field))return s(`${u}: \`${p}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(f.levels))return s(`${u}: \`${p}\` is a nested-literal-list and needs \`levels\``)}for(let p of Array.isArray(l.exceptions)?l.exceptions:[]){let f=n(p);if(!f||!r(f.reason))return s(`${u}: exception for "${r(f?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function hA(e){let t=Lc(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function gA(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}async function qh(e,t={}){let n=o((g,y)=>lA.join(g,y),"join"),r=t.manifestPath??Rs,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Lc(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let a=n(e,r);if(!cA(a))return{...s,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Os(Mh(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let d=new Map;for(let g of gA(c))try{d.set(g,Mh(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,p=C(e,["ls-files","-z"]);if(p===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let g of p.split("\0"))g&&u.add(g);let f=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:hA(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(f=Lc(C(e,["merge-base",y,"HEAD"])),!f)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let b of d.keys())h.set(b,C(e,["show",`${f}:${b}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:f,files:u,skipped:i}}async function fn(e,t={}){let n=await qh(e,t);return{...zh(n,t),facts:n}}function Uc(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Rs,Fh,ai=_(()=>{"use strict";pe();Rs=".maind/spec-contracts.json";o(Cs,"endOfString");o(Is,"skipComment");o(oi,"isQuote");o(Ns,"isCommentStart");o(As,"sliceBalanced");o(dA,"stripLeadingTrivia");o(sr,"splitTopLevel");o(jh,"readStringLiteral");o(uA,"escapeRe");o(Fc,"findSymbolArray");o(jc,"parseObjectFields");o(pA,"objectFieldRaw");o(Uh,"pickFields");o(Hh,"makeOrdinals");o(Bh,"extractObjectArray");o(Gh,"extractNestedList");o($h,"extractRecords");o(Wh,"isGrounded");o(Kh,"findingId");o(fA,"partitionOf");o(Vh,"compareContract");o(mA,"checkAssertions");o(Lh,"unreadable");Fh={open:0,warn:1,info:2,passed:3};o(zh,"computeSpecDrift");o(Lc,"trimOrNull");o(Os,"parseManifest");o(hA,"resolveDefaultBranch");o(gA,"declaredPaths");o(qh,"gatherSpecDriftFacts");o(fn,"checkSpecDrift");o(Uc,"isSpecDriftGraded")});import{execFileSync as yA}from"node:child_process";import{existsSync as _A,readFileSync as bA}from"node:fs";import{join as wA}from"node:path";function ci(e){let t=[],n=e.split(`
31
- `);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":vA.test(i)?"never-published":"released"})}return t}function Jh(e){let t=new Map;for(let n of ci(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(i=>i.line),shapes:r.map(i=>i.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function Xh(e,t){let n=Jh(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of ci(t))r.set(a.version,(r.get(a.version)??0)+1);let i=[],s=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?i:s).push({...a,countBefore:c})}return{introduced:i,preExisting:s,baseResolved:!0}}function Zh(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let i=Xh(r.head,e.baseRef===null?null:r.base);for(let s of i.introduced)t.push({path:r.path,version:s.version,level:"open",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} has ${s.count} headings (was ${s.countBefore})`});for(let s of i.preExisting)t.push({path:r.path,version:s.version,level:"info",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} already had ${s.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function Yh(e,t){try{return yA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function kA(e,t={}){let n=Yh(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null,s=r.map(a=>{let c=wA(e,a);return{path:a,head:_A(c)?bA(c,"utf8"):null,base:i===null?null:Yh(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function Hc(e,t={}){return Zh(kA(e,t))}var vA,Ds=_(()=>{"use strict";vA=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(ci,"parseVersionHeadings");o(Jh,"findDuplicateHeadings");o(Xh,"classifyIntroduced");o(Zh,"computeChangelogDuplicates");o(Yh,"git");o(kA,"gatherChangelogFacts");o(Hc,"checkChangelogDuplicates")});import{execFileSync as xA}from"node:child_process";import{existsSync as SA,readFileSync as Qh}from"node:fs";import{dirname as eg,join as tg}from"node:path";function rg(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(Vr);for(let a of s){if(r.has(a)||Vr(a,n.version)>=0)continue;let c=!i.has(a);t.push({package:n.name,version:a,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${a} is newly documented as released but the registry never served it`:`${n.name}@${a} is documented as released but the registry never served it`})}for(let a of[...n.neverPublished??[]].sort(Vr))r.has(a)&&t.push({package:n.name,version:a,level:"info",rule:"release.mislabelled",title:`${n.name}@${a} is marked never published but the registry serves it`});r.has(n.version)||t.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"mismatch",reason:null,findings:t,facts:e}}function ng(e){let t=ci(e),n=[...new Set(t.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(t.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function Bc(e,t){try{return xA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function ig(e,t=null){let n=Bc(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(Qh(tg(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let a=eg(i)==="."?"":eg(i),c=tg(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=SA(c)?ng(Qh(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,p=t===null?null:Bc(["show",`${t}:${u}`],e),f=t===null?null:p===null?[]:ng(p).documented;r.push({dir:a,name:s.name,version:s.version,documented:l,documentedBase:f,neverPublished:d})}return r}async function EA(e){let t=`https://registry.npmjs.org/${e.replace("/","%2F")}`,n=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(n.status===404)return[];if(!n.ok)throw new Error(`HTTP ${n.status}`);let r=await n.json();return Object.keys(r.versions??{})}async function sg(e,t={}){if(Bc(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=ig(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??EA,i={};for(let s of n)try{i[s.name]=await r(s.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${s.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function Gc(e,t={}){return rg(await sg(e,t))}var Wc=_(()=>{"use strict";zr();Ds();o(rg,"computeReleaseClaims");o(ng,"claimsOf");o(Bc,"git");o(ig,"discoverPackages");o(EA,"packument");o(sg,"gatherReleaseClaimsFacts");o(Gc,"checkReleaseClaims")});import{execFileSync as TA}from"node:child_process";import{existsSync as AA,readFileSync as RA}from"node:fs";import{join as CA}from"node:path";function Vc(e){let t=[],n=!1;for(let r of e.split(`
32
- `)){let i=r.trim();if(n){i===lg&&(n=!1);continue}if(i===cg){n=!0;continue}t.push(r)}return t.join(`
33
- `)}function og(e){return e.split(`
34
- `).map(t=>t.trim()).filter(t=>t.length>0)}function dg(e,t){let n=new Map;for(let s of og(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of og(e)){let a=n.get(s)??0;a>0?n.set(s,a-1):r.push(s)}let i=0;for(let s of n.values())i+=s;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function ug(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.baseRef===null)return{ok:!1,verdict:"no_opinion",reason:"no base to measure growth against",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no agent instruction file tracked",findings:[],facts:e};let t=[];for(let n of e.files){if(n.head===null)continue;let r=dg(Vc(n.head),n.base===null?null:Vc(n.base));r.net!==0&&t.push({path:n.path,level:"open",netLines:r.net,addedLines:r.added.length,removedLines:r.removed,sample:r.added.slice(0,5),newFile:n.base===null,title:n.base===null?`${n.path}: new agent instruction file with ${r.net} line(s) \u2014 every line loads into every session`:`${n.path}: +${r.net} line(s) of agent instructions \u2014 every line loads into every session; durable knowledge belongs in docs, a convention or a code comment`})}return{ok:t.length===0,verdict:t.length===0?"clean":"grown",reason:null,findings:t,facts:e}}function Kc(e,t){try{return TA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function pg(e,t={}){let n=Kc(["ls-files","-z","--",...ag],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Kc(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=CA(e,a);return{path:a,head:AA(c)?RA(c,"utf8"):null,base:r===null?null:Kc(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function zc(e,t={}){return ug(pg(e,t))}var ag,cg,lg,qc=_(()=>{"use strict";ag=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],cg="<!-- maind:conventions v1 begin -->",lg="<!-- maind:conventions v1 end -->";o(Vc,"stripManagedConventionsBlock");o(og,"contentLines");o(dg,"proseDelta");o(ug,"computeAgentDocProse");o(Kc,"git");o(pg,"gatherAgentDocProseFacts");o(zc,"checkAgentDocProse")});var fg,mg,Yc=_(()=>{"use strict";fg=[".github/workflows/*.yml",".github/workflows/*.yaml",".gitlab-ci.yml",".gitlab-ci.yaml",".gitlab/ci/*.yml",".gitlab/ci/*.yaml","bitbucket-pipelines.yml",".circleci/config.yml",".circleci/config.yaml","azure-pipelines.yml","azure-pipelines.yaml",".azure-pipelines/*.yml",".azure-pipelines/*.yaml",".gitea/workflows/*.yml",".gitea/workflows/*.yaml",".forgejo/workflows/*.yml",".forgejo/workflows/*.yaml",".woodpecker.yml",".woodpecker.yaml",".woodpecker/*.yml",".woodpecker/*.yaml",".drone.yml"],mg=new RegExp([String.raw`^\.github/workflows/.+\.ya?ml$`,String.raw`^\.gitlab-ci\.ya?ml$`,String.raw`^\.gitlab/ci/.+\.ya?ml$`,String.raw`^bitbucket-pipelines\.yml$`,String.raw`^\.circleci/config\.ya?ml$`,String.raw`^azure-pipelines\.ya?ml$`,String.raw`^\.azure-pipelines/.+\.ya?ml$`,String.raw`^\.(gitea|forgejo)/workflows/.+\.ya?ml$`,String.raw`^\.woodpecker\.ya?ml$`,String.raw`^\.woodpecker/.+\.ya?ml$`,String.raw`^\.drone\.yml$`,String.raw`^Jenkinsfile$`].join("|"))});import{execFileSync as IA}from"node:child_process";import{existsSync as NA,readFileSync as OA}from"node:fs";import{join as DA}from"node:path";function gg(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no YAML CI config (GitHub, GitLab, Bitbucket, CircleCI, Azure, Gitea/Forgejo, Woodpecker, Drone)",findings:[],facts:e};let t=[];for(let n of e.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:hs(n.base).map(i=>i.value));for(let i of hs(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,a=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:a?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${s}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function hg(e,t){try{return IA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function yg(e,t={}){let n=hg(["ls-files","-z","--",...fg],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let a=DA(e,s);return{path:s,content:NA(a)?OA(a,"utf8"):null,base:i===null?null:hg(["show",`${i}:${s}`],e)}})}}function Jc(e,t={}){return gg(yg(e,t))}var Xc=_(()=>{"use strict";zr();Yc();o(gg,"computeWorkflowYaml");o(hg,"git");o(yg,"gatherWorkflowYamlFacts");o(Jc,"checkWorkflowYaml")});import{readFileSync as PA}from"node:fs";import{join as MA,posix as $A}from"node:path";function _g(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
35
- `;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function Me(e){let t=[],n="",r=!1,i=!1,s=o(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function at(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function LA(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!at(a[1]).map(f=>Me(f)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!at(c[1]).map(p=>Me(p)?.name??"").filter(Boolean).includes("public"))return null;let d=at(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Me(p)?.name??"").filter(p=>p.length>0&&p!=="public");if(d.length===0)return null;let u=[];for(let p of at(i)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...li]};f[2]!=="("&&li.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function bg(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let a=i.trim();if(FA.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!at(l[1]).map(f=>Me(f)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let p=a.replace(/^TABLE\s+/i,""),f=at(p).map(h=>Me(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(f.length===0)return null;c=f}let d=at(s).map(p=>p.replace(/^GROUP\s+/i,"").trim()).map(p=>Me(p)?.name??"").filter(p=>p.length>0&&p!=="public"),u=[];for(let p of at(r)){let f=/^([A-Za-z]+)\s*(\()?/.exec(p.trim());if(!f)continue;let h=f[1].toUpperCase(),g=f[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...li]};!g&&li.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function Qc(e){let t=new Map,n=[...e].sort((i,s)=>st(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=_g(i.content);for(let a of s.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let p=LA(c);if(!p)continue;let f=p.roles.includes("anon"),h=p.roles.includes("authenticated");if(p.action==="revoke"){if(f&&(r.anonAddressed=!0),h)for(let g of p.writePrivs)r.authWritesRevoked.add(g)}else if(f&&(r.anonAddressed=!1),h)for(let g of p.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let p=Me(l[2]);if(!p||p.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(p.name))continue;t.set(p.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let p=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let f of at(p)){let h=Me(f);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let p=Me(u[1]),f=Me(u[2]);if(p&&f&&p.schema==="public"){let h=t.get(p.name);h&&(t.delete(p.name),t.set(f.name,h))}continue}if(/^REVOKE\b/i.test(c)){let p=bg(c);if(!p)continue;let f=p.tables==="all_in_public"?[...t.keys()]:p.tables,h=p.roles.includes("anon"),g=p.roles.includes("authenticated");if(!h&&!g)continue;for(let y of f){let b=t.get(y);if(b&&(h&&(b.anonAddressed=!0),g))for(let w of p.writePrivs)b.authWritesRevoked.add(w)}continue}}}return t}function Zc(e){let t=[];for(let[n,r]of Qc(e)){let i=[];r.anonAddressed||i.push("anon"),li.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function wg(e){let t=Zc(e.files),n=new Map;if(e.baseFiles!==null)for(let r of Zc(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function vg(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function tl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(Ps)||t.endsWith(el))}function UA(e,t){try{let n=PA(e,"utf8");return n.length>t?null:n}catch{return null}}function HA(e,t,n,r,i){let s=C(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${Ps}`),null;let a=new Set,c=[];for(let u of s.split(`
36
- `).filter(Boolean)){let[p,...f]=u.split(" ");p.startsWith("A")?a.add(f[0]):p.startsWith("R")?(c.push(f[0]),a.add(f[1])):(p.startsWith("M")||p.startsWith("D"))&&c.push(f[0])}let l=[],d=new Set(c);for(let{ref:u,content:p}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:p});for(let u of c){let p=$A.basename(u),f=tr(p);if(f===null)continue;let h=C(e,["show",`${r}:${u}`]);if(h===null)return i.push(`could not read ${u} at ${r} ${el}`),null;l.push({name:p,version:f,content:h})}return l}function mn(e,t={}){let n=t.maxFileBytes??jA,r=[],i=dn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,a=null;if(s)if(t.baseRef)a=t.baseRef;else{let f=Qr(e);a=f?`origin/${f}`:null,a===null&&r.push(`no default branch resolvable ${Ps}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let f of i){let h=[];for(let b of f.files){let w=UA(MA(e,b.path),n);if(w===null){r.push(`could not read ${b.path} \u2014 excluded from the fold`);continue}h.push({ref:b,content:w})}let g=h.map(({ref:b,content:w})=>({name:b.name,version:b.version,content:w})),y=a===null?null:HA(e,f.dir,h,a,r);c.push(...wg({dir:f.dir,files:g,baseFiles:y})),l.push({dir:f.dir,migrationCount:g.length,tableCount:Qc(g).size})}let d=l.reduce((f,h)=>f+h.migrationCount,0),u=vg(d,c.length),p={open:0,info:1};return c.sort((f,h)=>p[f.status]-p[h.status]||f.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(f=>f.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var li,FA,jA,Ps,el,Ms=_(()=>{"use strict";pe();ei();o(_g,"stripSql");o(Me,"normalizeQualifiedIdent");o(at,"splitTopLevel");li=["INSERT","UPDATE","DELETE"];o(LA,"parseDefaultAclTables");FA=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(bg,"parseTableRevoke");o(Qc,"foldTableAcl");o(Zc,"evaluateTableAcl");o(wg,"computeTableAclFindings");o(vg,"deriveTableAclVerdict");jA=5e6,Ps="\u2014 findings reported ungraded (open)",el="\u2014 baseline degraded";o(tl,"isTableAclGraded");o(UA,"safeRead");o(HA,"baseFilesFor");o(mn,"checkTableAclLint")});import{readFileSync as BA}from"node:fs";import{join as nl}from"node:path";function il(e){return e.verdict!=="no_opinion"&&e.graded}function sl(e){let t=new Set;for(let n of e.matchAll(GA))t.add(n[1]);return t}function ol(e){return new Set([...e].map(t=>t.split("-")[0]))}function Ag(e){return e.split(`
11
+ `),r===null?"created":"appended"}catch{return"skipped"}}var xs,dc,gT,Ss=_(()=>{"use strict";xs=["code-index.sqlite","code-index.sqlite-wal","code-index.sqlite-shm","index-refresh.lock","conventions-cache.json","conventions-cache.json.*.tmp","context.md","manifest.json","git-context.md","review.md","review.json","review-comment.md","run-review.md","pr-body.md","HANDOFF-*.md"],dc=["# Written by the maind tools: machine-local files that must not be committed.","# Missing lines are appended, nothing is removed \u2014 your own lines stay.",'# Never "*": this directory also holds files that ARE committed (feature.json, gates.json \u2026).'],gT=dc;o(Zr,"ensureMaindLocalIgnore")});import{execFileSync as yT}from"node:child_process";import{createHash as _T}from"node:crypto";import{readFileSync as bT,readdirSync as wT,statSync as vT}from"node:fs";import{posix as fc,sep as ch}from"node:path";function C(e,t){try{return yT("git",[...kT,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:15e3,maxBuffer:64*1024*1024})}catch{return null}}function xT(e){return ch==="/"?e:e.split(ch).join("/")}function Es(e){let t=[];for(let n of e){let r=xT(n).trim();if(!r||Xr(r))continue;let i=tr(r);i&&t.push({path:r,language:i})}return t}function dh(e){return Es(e)}function uh(e){let t=St(e,["ls-files","--cached","--others","--exclude-standard"]);if(t!==null)return Es(t.split(`
12
+ `));let n=[];return fh(e,"",n),Es(n)}function fh(e,t,n){let r;try{r=wT(fc.join(e,t),{withFileTypes:!0})}catch{return}for(let i of r){if(i.name.startsWith(".")&&i.name!=="."&&lh.has(i.name)||lh.has(i.name))continue;let s=t?`${t}/${i.name}`:i.name;i.isDirectory()?fh(e,s,n):i.isFile()&&n.push(s)}}function pc(e,t){return mc(e,t)??t}function mc(e,t){let n=C(e,["merge-base",t,"HEAD"])?.trim();return n&&n.length>0?n:null}function Ts(e,t={}){if(Qr(e)===null)return null;let n=t.includeUncommitted!==!1,r=t.since?pc(e,t.since):"HEAD",i=["diff","--name-status","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=St(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map;for(let c of s.split(`
13
+ `)){if(!c.trim())continue;let l=c.split(" ");if(l.length<2)continue;let d=l[0][0],u=uc((l.length>=3?l[l.length-1]:l[1]).trim());u&&(d==="A"||d==="C"?a.set(u,"added"):d==="R"?a.set(u,"renamed"):a.set(u,"modified"))}if(n){let c=St(e,["status","--porcelain","-uall"])??"";for(let l of c.split(`
14
+ `)){if(l.length<4)continue;let d=l[0],u=l[1];if(d==="D"||u==="D")continue;let f=l.slice(3),p=f.indexOf(" -> ");p>=0&&(f=f.slice(p+4)),f=uc(f),!(!f||a.has(f))&&(d==="?"||d==="A"||u==="A"?a.set(f,"added"):d==="R"?a.set(f,"renamed"):a.set(f,"modified"))}}return a}function uc(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function hc(e,t={}){let n=Ts(e,t);return n===null?null:Es(n.keys())}function ph(e,t){try{let n=vT(fc.join(e,t));return{mtimeMs:Math.floor(n.mtimeMs),size:n.size}}catch{return null}}function As(e){return _T("sha256").update(e).digest("hex")}function Qr(e){return St(e,["rev-parse","HEAD"])?.trim()??null}function Rs(e,t){return St(e,["rev-parse","--verify",`${t}^{commit}`])?.trim()??null}function gc(e){let t=St(e,["status","--porcelain","-uall"]);if(t===null)return!1;let n=t.split(`
15
+ `).filter(i=>i.trim().length>0);if(n.length===0)return!1;let r=ST(e);return n.some(i=>r===null||!ET(e,i,r))}function ST(e){let t=St(e,["rev-parse","--show-prefix"]);return t===null?null:`${t.trim()}.maind/.gitignore`}function ET(e,t,n){let r=t[0],i=t[1];if(uc(t.slice(3))!==n)return!1;let s;if(r==="?"&&i==="?"||r==="A"&&(i===" "||i==="M"))s="";else if((r===" "||r==="M")&&(i===" "||i==="M")){let f=St(e,["show",`HEAD:${n}`]);if(f===null)return!1;s=f}else return!1;let a;try{a=bT(fc.join(e,".maind",".gitignore"),"utf8")}catch{return!1}let c=o(f=>f.replace(/\r\n/g,`
16
+ `),"norm"),l=c(s),d=c(a);if(!d.startsWith(l))return!1;let u=new Set([...xs,...dc]);return d.slice(l.length).split(`
17
+ `).map(f=>f.trim()).every(f=>f.length===0||u.has(f))}var lh,kT,St,fe=_(()=>{"use strict";ks();Ss();lh=new Set([".git","node_modules","build","dist",".next","out","coverage",".turbo",".cache","__pycache__",".venv","venv"]),kT=["-c","diff.renames=true","-c","core.quotePath=false","-c","diff.algorithm=myers","-c","diff.indentHeuristic=true","-c","diff.interHunkContext=0","-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","diff.relative=false","-c","diff.renameLimit=1000"];o(C,"runGit");St=C;o(xT,"toPosix");o(Es,"classify");o(dh,"classifyPaths");o(uh,"discoverSourceFiles");o(fh,"walk");o(pc,"resolveDiffBase");o(mc,"resolveMergeBase");o(Ts,"enumerateChangedPaths");o(uc,"unquote");o(hc,"changedSourceFiles");o(ph,"statFile");o(As,"hashContent");o(Qr,"headCommit");o(Rs,"resolveCommitSha");o(gc,"isWorktreeDirty");o(ST,"toolIgnoreRepoPath");o(ET,"isToolOnlyIgnoreChange")});function hh(e,t={}){if(C(e,["rev-parse","HEAD"])===null)return null;let n=t.includeUncommitted!==!1,r=t.since?pc(e,t.since):"HEAD",i=["diff","--unified=0","--no-color","--no-ext-diff","--diff-filter=d",r];if(!n){if(!t.since)throw new Error("nothing to enumerate: include_uncommitted=false requires a `since` ref");i.push("HEAD")}let s=C(e,i);if(s===null)throw new Error(`git diff failed \u2014 is '${r}' a valid ref?`);let a=new Map,c="full";if(Buffer.byteLength(s,"utf8")>TT?c="none":IT(s,a,()=>{c="partial"}),n){let l=C(e,["status","--porcelain","-uall"])??"";for(let d of l.split(`
18
+ `)){if(d.length<4||d[0]!=="?")continue;let u=d.slice(3);u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),!(!u||a.has(u))&&a.set(u,{path:u,status:"added",binary:!1,wholeFile:!0,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]})}}return{files:a,coverage:c}}function IT(e,t,n){let r=null,i=0,s=!1,a=!1,c=o(()=>{r&&t.set(r.path,r),r=null,i=0},"commit");for(let l of e.split(`
19
+ `)){if(l.startsWith("diff --git ")){c(),s=!1,a=!1;continue}if(l.startsWith("new file mode")){a=!0;continue}if(l.startsWith("rename to ")){s=!0;continue}if(l.startsWith("Binary files ")||l.startsWith("GIT binary patch")){r&&(r.binary=!0);continue}if(l.startsWith("+++ ")){let u=l.slice(4).trim();if(u.startsWith('"')&&u.endsWith('"')&&(u=u.slice(1,-1)),u.startsWith("b/")&&(u=u.slice(2)),u==="/dev/null")continue;r={path:u,status:a?"added":s?"renamed":"modified",binary:!1,wholeFile:!1,degraded:!1,addedRanges:[],deletionPoints:[],addedLines:[]};continue}if(!r)continue;let d=CT.exec(l);if(d){if(i++,i>AT){r.degraded||(r.degraded=!0,r.addedRanges=[],r.deletionPoints=[],r.addedLines=[],n());continue}let u=Number(d[1]),f=d[2]===void 0?1:Number(d[2]);f>0?r.addedRanges.push({start:u,end:u+f-1}):r.deletionPoints.push(u);continue}l.startsWith("+")&&!l.startsWith("+++")&&!r.degraded&&r.addedLines.length<RT&&r.addedLines.push(l.slice(1))}c()}var TT,AT,RT,mh,CT,gh=_(()=>{"use strict";fe();TT=16*1024*1024,AT=500,RT=4e3,mh=256*1024,CT=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;o(hh,"changedHunks");o(IT,"parseUnifiedDiff")});function _c(e,t=Date.now()){if(e.history.length===0)return;let n=new Set,r=0,i=0,s=0;for(let a of e.history){let c=a.ownership?.commitsInWindow??a.lastCommits.length;c>=vh&&r++,c>i&&(i=c);for(let d of a.ownership?.topAuthors??[])n.add(d.email.toLowerCase()||d.name);let l=a.lastCommits[0]?.dateIso;if(l){let d=Date.parse(l);Number.isFinite(d)&&d>s&&(s=d)}}return{window_commits:e.ownershipWindowCommits,files_scanned:e.history.length,hot_files:r,max_recent_commits:i,distinct_authors:n.size,newest_change_age_days:s>0?Math.max(0,Math.floor((t-s)/864e5)):0}}function DT(e,t,n){return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(Math.floor(e),n)}function _h(e){return e.split(NT).filter(t=>t.trim().length>0)}function bh(e){let[t,n,r,i,s]=e.replace(/\n+$/,"").split(OT);return!t||!i?null:{sha:t,authorName:n??"",authorEmail:r??"",dateIso:i,subject:s??""}}function PT(e){let t=new Map;for(let n of e){let r=n.authorEmail.toLowerCase()||n.authorName,i=t.get(r);i?i.commits+=1:t.set(r,{name:n.authorName,email:n.authorEmail,commits:1,lastDateIso:n.dateIso})}return[...t.values()].sort((n,r)=>r.commits-n.commits||n.email.localeCompare(r.email)).slice(0,10)}function kh(e,t,n={}){let r=DT(n.limit,20,100),i=n.includeOwnership!==!1,s=Math.max(r,wh),a=t.map(u=>u.trim()).filter(u=>u.length>0&&!u.startsWith(":")),c=a.slice(0,yc),l=[];for(let u of c){let f=C(e,["log","-n",String(s),yh,"--",u]),p=f===null?[]:_h(f).map(bh).filter(h=>h!==null);l.push({path:u,lastCommits:p.slice(0,r),ownership:i?{topAuthors:PT(p),commitsInWindow:p.length}:null})}let d=null;if(n.since){let u=Rs(e,n.since),f=u!==null?[`${u}..HEAD`]:[`--since=${n.since}`],p=C(e,["log",...f,"-n",String(Cs+1),yh,"--name-only","--",...c]),h=[];if(p!==null)for(let g of _h(p)){let y=g.split(`
20
+ `),b=bh(y[0]??"");if(!b)continue;let w=y.slice(1).filter(k=>k.trim().length>0).length;h.push({sha:b.sha,dateIso:b.dateIso,authorName:b.authorName,subject:b.subject,filesTouched:w})}d={sinceInput:n.since,sinceResolved:u,commits:h.slice(0,Cs),truncated:h.length>Cs}}return{history:l,regression:d,ownershipWindowCommits:s,pathsTruncated:a.length>yc}}var NT,OT,wh,yc,Cs,yh,vh,bc=_(()=>{"use strict";fe();NT="",OT="\0",wh=200,yc=50,Cs=100,yh="--format=%x1e%H%x00%an%x00%ae%x00%aI%x00%s",vh=10;o(_c,"aggregateHistoryContext");o(DT,"clamp");o(_h,"splitRecords");o(bh,"parseHistoryRecord");o(PT,"aggregateOwnership");o(kh,"readFileHistory")});import{execFileSync as MT}from"node:child_process";import{readdirSync as $T,statSync as xh}from"node:fs";import{isAbsolute as LT,join as wc,relative as FT,resolve as jT}from"node:path";function HT(e){return!e.endsWith(".sample")&&!e.startsWith(".")}function BT(e,t){try{let n=MT("git",["-C",e,"config","--get",t],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();return n.length>0?n:null}catch{return null}}function GT(e){let t;try{t=$T(e)}catch{return null}for(let n of t.filter(HT))try{let r=xh(wc(e,n));if(r.isFile()&&r.mode&73)return!0}catch{}return!1}function WT(e){try{return xh(e).isDirectory()}catch{return!1}}function KT(e,t){let n=FT(e,t);return!n||n.startsWith("..")?t:n}function vc(e){let t=UT.filter(c=>WT(wc(e,c))),n=BT(e,"core.hooksPath"),r=n?LT(n)?n:jT(e,n):wc(e,".git","hooks"),i=KT(e,r),s=GT(r);if(s===!0)return{verdict:"wired",reason:n?"wired":"default_path",hookDirs:t,hooksPath:n,effectiveDir:i};let a=n?s===null?"path_missing":"path_empty":t.length>0?"path_unset":"no_hooks";return{verdict:t.length>0?"present_unwired":"absent",reason:a,hookDirs:t,hooksPath:n,effectiveDir:i}}function kc(e){switch(e.reason){case"wired":return`Git-Gates aktiv (core.hooksPath \u2192 ${e.effectiveDir}).`;case"default_path":return"Git-Gates aktiv (.git/hooks, nicht versioniert).";case"path_unset":return`${e.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;case"path_missing":return`core.hooksPath zeigt auf ${e.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;case"path_empty":return`core.hooksPath zeigt auf ${e.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;case"no_hooks":return"Keine Git-Hooks im Repo."}}var UT,xc=_(()=>{"use strict";UT=[".githooks",".husky"];o(HT,"isRealHook");o(BT,"gitConfig");o(GT,"hasExecutableHook");o(WT,"isDir");o(KT,"displayPath");o(vc,"resolveHookState");o(kc,"describeHookState")});import{posix as Sh}from"node:path";function nr(e){let t=VT.exec(e);return t?t[1]:null}function ot(e,t){return e.length!==t.length?e.length-t.length:e<t?-1:e>t?1:0}function dn(e,t){let n=C(e,["ls-files","-z","--","supabase/migrations/*.sql","*/supabase/migrations/*.sql"]);if(n===null)return[];let r=o(s=>!t||t.length===0?!0:t.some(a=>{let c=a.replace(/\/+$/,"");return c===""||s===c||s.startsWith(`${c}/`)}),"wanted"),i=new Map;for(let s of n.split("\0").filter(Boolean)){if(!r(s))continue;let a=Sh.basename(s),c=nr(a);if(c===null)continue;let l=Sh.dirname(s),d=i.get(l)??[];d.push({path:s,name:a,version:c}),i.set(l,d)}return[...i.entries()].map(([s,a])=>({dir:s,files:a.sort((c,l)=>ot(c.version,l.version))})).sort((s,a)=>s.dir.localeCompare(a.dir))}function ei(e){let t=C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim();if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}var VT,ti=_(()=>{"use strict";fe();VT=/^(\d+)_.+\.sql$/;o(nr,"parseMigrationVersion");o(ot,"compareVersions");o(dn,"discoverSupabaseProjects");o(ei,"resolveDefaultBranch")});import{execFileSync as zT}from"node:child_process";import{existsSync as de,readFileSync as Et,readdirSync as Is,statSync as Ec}from"node:fs";import{posix as U}from"node:path";function XT(e,t){let n=(()=>{let i=C(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return i?i.trim():null})(),r=U.dirname(e);for(let i=0;i<8&&r&&r!==U.dirname(r);i++){if(de(U.join(r,".git"))){let s=(()=>{let c=C(r,["rev-parse","--path-format=absolute","--git-common-dir"]);return c?c.trim():null})();if(!(n!=null&&s!=null&&Ac(n,s))){let c=ZT(e,r);return c.length>0?{outerRepoPath:r,diverging:c}:null}}r=U.dirname(r)}return null}function ZT(e,t){let n=[];for(let r of YT){let i;try{i=Is(U.join(e,r),{withFileTypes:!0}).filter(s=>s.isFile()).map(s=>s.name)}catch{continue}for(let s of i){let a=`${r}/${s}`,c=U.join(e,a),l=U.join(t,a);try{let d=Ec(c),u=Ec(l);if(!u.isFile())continue;if(d.size!==u.size){n.push(a);continue}if(d.size>JT)continue;Et(c).equals(Et(l))||n.push(a)}catch{continue}}}return n.sort()}function Nh(e){let t=[];if(!e.isRepo)return t;let n=e.branch!=null&&e.defaultBranch!=null&&e.branch!==e.defaultBranch&&!e.detachedHead;if(e.detachedHead&&t.push({id:"worktree.detached-head",status:"warn",scope:"worktree",title:"Detached HEAD",detail:"HEAD points at a commit, not a branch \u2014 commits here are easily lost.",hint:"git switch -c <branch> to keep this work, or checkout an existing branch."}),n)if(e.upstream==null)t.push({id:"branch.no-upstream",status:"open",scope:"branch",title:"No upstream set",detail:`'${e.branch}' tracks nothing \u2014 a plain 'git push' goes nowhere or to the wrong ref, with no error.`,hint:`git push -u origin ${e.branch}`});else{let c=e.upstream.split("/").slice(1).join("/");c&&c!==e.branch&&t.push({id:"branch.upstream-mismatch",status:"open",scope:"branch",title:"Upstream points at a different branch",detail:`'${e.branch}' tracks '${e.upstream}' \u2014 pushes land on the wrong remote branch silently.`,hint:`git branch --set-upstream-to=origin/${e.branch} (then push -u)`}),e.remoteTrackingExists===!1&&t.push({id:"branch.unpushed-missing-remote",status:"open",scope:"branch",title:"Branch not on remote",detail:`'${e.branch}' has an upstream configured but no matching remote-tracking ref \u2014 the branch was never pushed.`,hint:`git push -u origin ${e.branch}`})}let r=e.behind??0,i=e.ahead??0;r>0&&t.push({id:"branch.behind",status:"info",scope:"branch",title:"Behind base",detail:`${r} commit(s) behind origin/${e.defaultBranch}${i>0?` (and ${i} ahead)`:""} \u2014 rebase/merge base before merging to avoid a stale PR.`,hint:`git fetch && git rebase origin/${e.defaultBranch}`});let s=e.isSharedMainTree&&e.otherWorktrees>0&&!n&&!e.detachedHead&&(e.ahead??0)>0;if(s){let c=e.ahead??0;t.push({id:"worktree.commit-on-shared-base",status:"open",scope:"worktree",title:"Commit on the shared base tree",detail:`${c} commit(s) sit on the shared '${e.defaultBranch}' checkout and not on ${e.upstream??`origin/${e.defaultBranch}`} \u2014 in a workflow that reaches the base branch only through a pull request, a commit here is one that landed in the wrong place. A branch switch in a tree other sessions share can be undone by one of them between the switch and the commit, and nothing reports it.`,hint:`Move the commit onto its branch, then reset the base tree: git branch -f <branch> HEAD && git reset --hard ${e.upstream??`origin/${e.defaultBranch}`} (check for uncommitted work first). Do the work in its own worktree.`})}if(!s&&e.upstream!=null&&e.headMatchesUpstream===!1&&t.push({id:"branch.unpushed-commits",status:"warn",scope:"branch",title:"Unpushed commits",detail:`Local HEAD is ahead of ${e.upstream} \u2014 commits exist only on this machine.`,hint:"git push"}),e.unmergedMigrations.length>0){let c=e.unmergedMigrations.length;t.push({id:"branch.unmerged-migrations",status:"info",scope:"branch",title:"Migrations not yet on the base branch",detail:`${c} migration file(s) added on '${e.branch}' are not on origin/${e.defaultBranch} yet \u2014 a cloud DB push run from ${e.defaultBranch} will NOT include them until this branch is merged.`,hint:`Merge to ${e.defaultBranch} first (promote), then run 'supabase db push --linked' from ${e.defaultBranch}.`})}if(e.isSharedMainTree&&e.otherWorktrees>0&&e.uncommitted>0&&!n&&t.push({id:"worktree.direct-on-shared-base",status:"warn",scope:"worktree",title:"Uncommitted work on the shared base tree",detail:`You are editing the shared '${e.defaultBranch}' checkout while ${e.otherWorktrees} feature worktree(s) exist \u2014 the workflow reaches base only via PR merge.`,hint:"Move the work into a feature worktree (git worktree add ../<name> -b feat/<name>)."}),e.inProgressOp&&t.push({id:"worktree.in-progress-op",status:"warn",scope:"worktree",title:`${e.inProgressOp} in progress`,detail:`A ${e.inProgressOp} is mid-flight \u2014 git operations behave unexpectedly until it is finished or aborted.`,hint:`git ${e.inProgressOp} --continue | --abort`}),e.worktreeParity&&e.worktreeParity.missing.length>0){let c=e.worktreeParity.missing;t.push({id:"worktree.parity-missing",status:"open",scope:"worktree",title:"Tooling files missing vs main checkout",detail:`${c.join(", ")} exist in the main checkout but not here \u2014 tools (e.g. supabase) may silently target the wrong/no project and report success.`,hint:`Copy the missing file(s) from ${e.worktreeParity.mainWorktreePath}, or declare them in ${Rc}.`})}if(e.worktreeParity&&e.worktreeParity.missingDeps.length>0){let c=e.worktreeParity.missingDeps;t.push({id:"worktree.deps-missing",status:"warn",scope:"worktree",title:"Dependencies never installed in this worktree",detail:`${c.map(l=>l.dir).join(", ")} exist(s) in the main checkout but not here \u2014 a lockfile is versioned next to it, so this tree was never installed. Tools that resolve binaries from node_modules (linters, commit hooks, dev servers) fail in ways that read like your own change broke them.`,hint:c.map(l=>`${l.install} (in ${U.dirname(l.dir)})`).join(" | ")})}if(e.toolCopyDrift&&e.toolCopyDrift.diverging.length>0){let{outerRepoPath:c,diverging:l}=e.toolCopyDrift,d=l.slice(0,3).join(", "),u=l.length>3?` (+${l.length-3} more)`:"";t.push({id:"setup.tool-copy-drift",status:"warn",scope:"setup",title:"Divergent copy of a tooling script one repo up",detail:`${c} ships ${d}${u} too, with different content. Reached by absolute path \u2014 or from a shell sitting one level up \u2014 you run THAT copy instead of this repo's, and it fails silently: it does most of the job and omits whatever this repo's version added.`,hint:`Invoke it repo-locally (\`bash ${l[0]}\` from this repo root), not via a path into ${c}.`})}if(e.stalePackageBuilds.length>0){let c=e.stalePackageBuilds,l=o(u=>u.impact==="runtime"?`${u.packageDir} (runtime)`:u.packageDir,"label"),d=c.every(u=>u.impact==="runtime")?`the bundler/node loads stale code while the TYPECHECK stays green (types resolve from src) \u2014 "Export X doesn't exist in target module \u2026/build".`:c.some(u=>u.impact==="runtime")?'"has no exported member X" in code you did not touch \u2014 and, for the packages marked (runtime), a green typecheck over stale loaded code.':'"has no exported member X" in code you did not touch, while CI is green.';t.push({id:"worktree.stale-package-build",status:"warn",scope:"worktree",title:"Workspace package build older than its source",detail:`${c.map(l).join(", ")}: src/ is newer than the built ${[...new Set(c.map(u=>u.buildDir))].join("/")} artifacts their consumers resolve from. Typical cause: a rebase/pull brought package sources, and nothing rebuilt ('prepare' runs only on install). Symptom: ${d}`,hint:`Rebuild: pnpm --filter ./${c[0].packageDir} build (one per package) \u2014 or re-run the workspace install.`})}e.release?.allRed&&t.push({id:"release.all-checks-red",status:"warn",scope:"release",title:"All checks failing \u2014 suspect account/billing/quota",detail:`All ${e.release.totalChecks} check(s) on the current PR failed. When every check goes red at once, the hypothesis is account/billing/quota, not your code (e.g. Actions spending-limit blocks the whole repo, including publisher jobs).`,hint:"Check the CI provider's billing/spending status before debugging code."});let a=QT(e.hooks);return a&&t.push(a),eA(t)}function QT(e){return!e||e.verdict!=="present_unwired"?null:{id:"setup.hooks-unwired",status:"warn",scope:"setup",title:"Git-Hooks liegen im Repo, feuern aber nicht",detail:kc(e),hint:e.reason==="path_missing"?`core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${e.hookDirs[0]??".githooks"}`:`git config core.hooksPath ${e.hookDirs[0]??".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`}}function eA(e){return[...e].sort((t,n)=>Eh[t.status]-Eh[n.status]||t.id.localeCompare(n.id))}function Oh(e){return!e.some(t=>t.status==="open"||t.status==="warn")}function at(e){let t=e?.trim();return t||null}function tA(e){let t=at(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function nA(e){let t=at(C(e,["rev-parse","--git-dir"]));if(!t)return null;let n=U.isAbsolute(t)?t:U.join(e,t);return de(U.join(n,"rebase-merge"))||de(U.join(n,"rebase-apply"))?"rebase":de(U.join(n,"MERGE_HEAD"))?"merge":de(U.join(n,"CHERRY_PICK_HEAD"))?"cherry-pick":null}function rA(e){let t=[],n=null,r=o(()=>{n?.path&&t.push({path:n.path,branch:n.branch,detached:n.detached??!1})},"flush");for(let i of e.split(`
21
+ `))if(i.startsWith("worktree "))r(),n={path:i.slice(9).trim(),detached:!1};else if(n)i.startsWith("branch ")?n.branch=i.slice(7).trim().replace(/^refs\/heads\//,""):i.trim()==="detached"&&(n.detached=!0);else continue;return r(),t}function iA(e){let t=U.join(e,Rc);if(!de(t))return[];try{return Et(t,"utf8").split(`
22
+ `).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#"))}catch{return[]}}function sA(e){try{return dn(e).map(t=>U.join(U.dirname(t.dir),"config.toml"))}catch{return[]}}function oA(e){let t=C(e,["ls-files","-z","--",...qT]);if(t===null)return[];let n=new Map;for(let r of t.split("\0").filter(Boolean)){let i=Ih[U.basename(r)];if(i===void 0)continue;let s=U.dirname(r);if(!aA(e,s))continue;let a=s==="."?"node_modules":U.join(s,"node_modules");n.has(a)||n.set(a,{dir:a,install:i})}return[...n.values()]}function aA(e,t){return t==="."?!0:Tc(e,t)}function Tc(e,t){if(de(U.join(e,t,"pnpm-workspace.yaml")))return!0;try{let n=JSON.parse(Et(U.join(e,t,"package.json"),"utf8"));return typeof n=="object"&&n!==null&&n.workspaces!==void 0}catch{return!1}}async function Dh(e,t={}){if(at(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,branch:null,defaultBranch:null,upstream:null,headMatchesUpstream:null,remoteTrackingExists:null,ahead:null,behind:null,uncommitted:0,detachedHead:!1,inProgressOp:null,isSharedMainTree:!1,otherWorktrees:0,worktreeParity:null,toolCopyDrift:null,stalePackageBuilds:[],release:null,unmergedMigrations:[],hooks:null};let r=at(C(e,["rev-parse","--abbrev-ref","HEAD"])),i=r==="HEAD",s=i?null:r,a=tA(e),c=at(C(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])),l=null,d=null;if(c){let F=at(C(e,["rev-parse","HEAD"])),H=at(C(e,["rev-parse","@{u}"]));l=F!=null&&H!=null?F===H:null,d=C(e,["rev-parse","--verify","--quiet",`refs/remotes/${c}`])!==null}let u=null,f=null;if(a){let F=at(C(e,["rev-list","--left-right","--count",`origin/${a}...HEAD`]));if(F){let[H,P]=F.split(/\s+/).map(L=>Number.parseInt(L,10));Number.isFinite(H)&&(f=H),Number.isFinite(P)&&(u=P)}}let h=(C(e,["status","--porcelain"])??"").split(`
23
+ `).filter(F=>F.trim().length>0).length,g=nA(e),y=at(C(e,["rev-parse","--show-toplevel"]))??e,b=rA(C(e,["worktree","list","--porcelain"])??""),w=b[0]?.path??null,k=w!=null&&Ac(w,y),S=Math.max(0,b.length-1),x=null;if(w&&!Ac(w,y)){let F=o(P=>de(U.join(w,P))&&!de(U.join(y,P)),"here"),H=[...Ch,...sA(y),...iA(y),...t.probePaths??[]];x={mainWorktreePath:w,currentWorktreePath:y,missing:[...new Set(H.filter(F))],missingDeps:oA(y).filter(P=>F(P.dir))}}let v=XT(y,e),E=t.includeRelease===!1?null:mA(e,s),N=[];return a&&(N=(C(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
24
+ `).map(H=>H.trim()).filter(H=>H.length>0)),{isRepo:!0,branch:s,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:d,ahead:u,behind:f,uncommitted:h,detachedHead:i,inProgressOp:g,isSharedMainTree:k,otherWorktrees:S,worktreeParity:x,toolCopyDrift:v,stalePackageBuilds:Ph(y),release:E,unmergedMigrations:N,hooks:vc(e)}}function Ac(e,t){let n=o(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}function dA(e){let t=new Set;Tc(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Ah;){let i=n.pop();if(i===void 0)break;if(i.depth>=lA)continue;let s;try{s=Is(U.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of s){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:U.join(i.rel,a.name);if(r+=1,r>=Ah)break;Tc(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}function uA(e){let t=[];try{let n=U.join(e,"pnpm-workspace.yaml");if(de(n)){let r=!1;for(let i of Et(n,"utf8").split(`
25
+ `)){let s=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(s)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(s);a?t.push(a[1]):s.trim().length>0&&!/^\s/.test(s)&&(r=!1)}}}else{let r=U.join(e,"package.json");if(de(r)){let i=JSON.parse(Et(r,"utf8")),s=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(s)&&t.push(...s.filter(a=>typeof a=="string"))}}}catch{return[]}return t}function fA(e){let t=[];for(let n of dA(e)){let r=n==="."?e:U.join(e,n),i=o(s=>n==="."?s:U.join(n,s),"prefix");for(let s of uA(r)){if(t.length>=Sc)break;if(!(s.startsWith("!")||s.includes("**")))try{if(s.endsWith("/*")){let a=s.slice(0,-2),c=U.join(r,a);if(!de(c))continue;for(let l of Is(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(U.join(a,l.name))),t.length>=Sc)break}else s.includes("*")||t.push(i(s))}catch{}}}return t.slice(0,Sc)}function Rh(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Th;){let i=r.pop();if(i===void 0)break;let s;try{s=Is(i,{withFileTypes:!0})}catch{continue}for(let a of s){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=U.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=Ec(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Th)break}}}return t}function pA(e,t){let n=new Set;for(let r of t)try{let i=U.join(e,r,"package.json");if(!de(i))continue;let s=JSON.parse(Et(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=s[a];if(!(c===null||typeof c!="object"))for(let[l,d]of Object.entries(c))typeof d=="string"&&d.startsWith("workspace:")&&n.add(l)}}catch{}return n}function Ph(e){let t=[],n=fA(e),r=pA(e,n);for(let i of n)try{let s=U.join(e,i,"package.json");if(!de(s))continue;let a=JSON.parse(Et(s,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=o(w=>{if(typeof w!="string")return null;let k=w.replace(/^\.\//,"").split("/")[0];return k==="build"||k==="dist"?k:null},"builtSeg"),l=c(a.types??a.typings),d=c(a.main),u=l??d;if(u===null)continue;let f=l!==null&&d!==null?"both":l!==null?"types":"runtime",p=U.join(e,i,"src"),h=U.join(e,i,u);if(!de(p)||!de(h))continue;let g=Rh(p),y=Rh(h);if(g===null||y===null)continue;let b=g-y;b>cA&&t.push({packageDir:i,buildDir:u,srcNewerByMs:Math.round(b),impact:f})}catch{}return t.sort((i,s)=>i.packageDir.localeCompare(s.packageDir))}function mA(e,t){if(!t)return null;let n=hA(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(s=>s.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}function hA(e,t){try{return zT("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}async function ni(e,t={}){let n=await Dh(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Nh(n),i=Oh(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}var Ch,Rc,Ih,qT,YT,JT,Eh,cA,Sc,Th,lA,Ah,Cc=_(()=>{"use strict";xc();fe();ti();Ch=["supabase/config.toml","supabase/.temp",".env"],Rc=".maind/worktree-requirements",Ih={"pnpm-lock.yaml":"pnpm install","package-lock.json":"npm install","yarn.lock":"yarn install","bun.lockb":"bun install"},qT=Object.keys(Ih).flatMap(e=>[e,"*/"+e]),YT=["scripts"],JT=512*1024;o(XT,"gatherToolCopyDrift");o(ZT,"compareToolDirs");o(Nh,"computeDivergence");o(QT,"computeHookFinding");Eh={open:0,warn:1,info:2,passed:3};o(eA,"sortFindings");o(Oh,"isHealthy");o(at,"trimOrNull");o(tA,"resolveDefaultBranch");o(nA,"detectInProgressOp");o(rA,"parseWorktrees");o(iA,"readWorktreeRequirements");o(sA,"discoverSupabaseConfigProbes");o(oA,"discoverDependencyDirs");o(aA,"isWorkspaceRoot");o(Tc,"hasWorkspaceMarkers");o(Dh,"gatherRepoHealthFacts");o(Ac,"samePath");cA=2e3,Sc=64,Th=4e3,lA=3,Ah=400;o(dA,"findWorkspaceRoots");o(uA,"workspacePatternsAt");o(fA,"listWorkspacePackageDirs");o(Rh,"newestMtimeUnder");o(pA,"consumedWorkspaceNames");o(Ph,"gatherStalePackageBuilds");o(mA,"gatherReleaseFact");o(hA,"runGh");o(ni,"checkDivergence")});import{existsSync as Ic,readdirSync as Mh}from"node:fs";import{posix as Je}from"node:path";function Oc(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes(Nc)}function Lh(e,t={}){let n=t.minFiles??Dc;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??$h)}function ir(e){return`${e.dir}#${e.prefix}`}function ri(e){let t=gA.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}function Fh(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let s=ir(i),a=e.sightingsByNamespace.get(s);if(!a)continue;let c=new Set(a.keys());for(let[l,d]of a){let u=[...new Set(d.map(g=>g.path))];if(u.length<2)continue;let f=u.find(g=>n.has(g)),p=u.filter(g=>g!==f),h=`${i.prefix}${l}`;t.push(f?{id:`number.collision:${s}#${l}`,status:"open",namespace:i,number:l,title:`${h} is already taken`,detail:`This branch adds ${f}, but ${h} already exists as ${p.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${h} stop being unambiguous.`,ownPath:f,sightings:d.filter(g=>g.path!==f),suggestion:`${i.prefix}${Pc(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${s}#${l}`,status:"info",namespace:i,number:l,title:`${h} is used more than once (pre-existing)`,detail:`${h} is carried by ${u.length} files: ${u.join(", ")}.`,sightings:d,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,s)=>r[i.status]-r[s.status]||i.id.localeCompare(s.id))}function jh(e){return!e.some(t=>t.status==="open")}function Pc(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}function Mc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Uh(e,t){let n=Mc(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=ri(Je.basename(n));if(!i)return r;let s=`${Je.dirname(n)}#${i.prefix}`,a=e.namespaces.find(u=>ir(u)===s)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(s)??new Map,l=new Set,d=[];for(let u of c.get(i.number)??[])u.path===n||l.has(u.path)||(l.add(u.path),d.push(u));return{path:n,namespace:a,number:i.number,taken:d.length>0,sightings:d,suggestion:Pc(c.keys(),i.number)}}function Ns(e){let t=e?.trim();return t||null}function rr(e){return e?e.split(`
26
+ `).filter(Boolean):[]}function yA(e){let t=Ns(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function Hh(e,t={}){let n=t.minFiles??Dc,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=C(e,r);if(i===null)return[];let s=new Map;for(let a of i.split("\0").filter(Boolean)){let c=Je.dirname(a),l=ri(Je.basename(a));if(!l)continue;let d=`${c}#${l.prefix}`,u=s.get(d);u?u.numbers.push(l.number):s.set(d,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...s.values()].filter(a=>Lh(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>ir(a).localeCompare(ir(c)))}async function $c(e,t={}){let n=[];if(Ns(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Hh(e,t),s=new Map(i.map(h=>[ir(h),h])),a=[...new Set(i.map(h=>h.dir))],c=new Map,l=o((h,g,y)=>{let b=Je.dirname(h),w=ri(Je.basename(h));if(!w)return;let k=`${b}#${w.prefix}`;if(!s.has(k))return;let S=c.get(k)??new Map,x=S.get(w.number)??[];x.push({kind:g,where:y,path:h}),S.set(w.number,x),c.set(k,S)},"record"),d=o((h,g,y)=>{if(a.length===0)return;let b=C(e,["ls-tree","-r","--name-only",h,"--",...a]);if(b===null){n.push(`could not read ${y}`);return}for(let w of rr(b))l(w,g,y)},"scanTree");for(let h of a){let g=Je.join(e,h);if(Ic(g))try{for(let y of Mh(g))l(`${h}/${y}`,"self","this worktree")}catch{n.push(`could not read ${h}`)}}let u=yA(e),f=t.baseRef??(u?`origin/${u}`:null);if(f?d(f,"default_branch",f):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let h=Ns(C(e,["rev-parse","--abbrev-ref","HEAD"]));for(let g of rr(C(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))g!==h&&d(g,"branch",`Branch ${g}`)}if(t.includeWorktrees!==!1){let h=Ns(C(e,["rev-parse","--show-toplevel"]));for(let g of rr(C(e,["worktree","list","--porcelain"]))){if(!g.startsWith("worktree "))continue;let y=g.slice(9).trim();if(!(!y||y===h||!Ic(y)))for(let b of a){let w=Je.join(y,b);if(Ic(w))try{for(let k of Mh(w))l(`${b}/${k}`,"worktree",`Worktree ${y}`)}catch{n.push(`could not read ${b} in ${y}`)}}}}let p=[];if(f&&a.length>0){let h=C(e,["diff","--name-only","--diff-filter=A",`${f}...HEAD`,"--",...a]);h===null?n.push(Nc):p=rr(h);let g=C(e,["ls-files","--others","--exclude-standard","--",...a]);g!==null&&(p=[...p,...rr(g)]);let y=C(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);y!==null&&(p=[...p,...rr(y)])}return{isRepo:!0,defaultBranch:u,baseRef:f,namespaces:i,sightingsByNamespace:c,addedPaths:p,skipped:n}}async function un(e,t={}){let n=await $c(e,t),r=Fh(n);return{ok:jh(r),findings:r,facts:n}}async function fn(e,t,n={}){let r=Mc(t);if(!ri(Je.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await $c(e,{...n,dirs:n.dirs??[Je.dirname(r)]});return Uh(i,r)}var Nc,gA,Dc,$h,ii=_(()=>{"use strict";fe();Nc="could not diff against the base ref \u2014 everything reported as info";o(Oc,"isNumberCollisionsGraded");gA=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Dc=3,$h=.8;o(Lh,"isCounterNamespace");o(ir,"namespaceKey");o(ri,"parseNumbered");o(Fh,"computeNumberCollisions");o(jh,"isCollisionFree");o(Pc,"suggestNextNumber");o(Mc,"normaliseRepoPath");o(Uh,"checkProposedNumber");o(Ns,"trimOrNull");o(rr,"lines");o(yA,"resolveDefaultBranch");o(Hh,"detectNamespaces");o($c,"gatherNumberCollisionFacts");o(un,"checkNumberCollisions");o(fn,"checkNumberForPath")});import{execFileSync as _A}from"node:child_process";import{createHash as bA}from"node:crypto";function Lc(e){return bA("sha256").update(e).digest("hex")}function wA(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function vA(e){let t=wA(e);return t?Lc(t):null}function xA(e){return typeof e=="string"&&kA.test(e)}function Bh(e=process.cwd()){let t=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(xA(t))return t;let n;try{n=_A("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return n?vA(n):null}var kA,Fc=_(()=>{"use strict";o(Lc,"sha256Hex");o(wA,"normalizeRemoteUrl");o(vA,"projectKeyFromRemote");kA=/^[a-f0-9]{64}$/;o(xA,"isProjectKey");o(Bh,"computeProjectKey")});function Bc(e){return`spec.${e}`}function sr(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}function SA(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let s=0;s<i;s++){let a=(n[s].codePointAt(0)??0)-(r[s].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}function Gh(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(SA)}function oi(e){return Lc(JSON.stringify(Gh(e)))}var si,jc,Uc,Hc,Gc=_(()=>{"use strict";Fc();si={det_number_collisions:{version:"1.2.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.1.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.1.0",rules:["release.phantom","release.unpublished","release.mislabelled"]},det_agent_doc_prose:{version:"1.1.0",rules:["agentdoc.added_prose"]}},jc="number.collision",Uc="theme.dead_class",Hc="acl.missing_revoke";o(Bc,"specDriftRuleId");o(sr,"gradeEngineStatus");o(SA,"codePointCompare");o(Gh,"normalizeEvidenceForHash");o(oi,"hashDetectorEvidence")});import{existsSync as EA,readFileSync as Wh}from"node:fs";import{posix as TA}from"node:path";function Ps(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}function Ms(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
27
+ `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}function ai(e){return e==='"'||e==="'"||e==="`"}function $s(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}function Os(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let s=e[i];if(ai(s)){i=Ps(e,i);continue}if($s(e,i)){i=Ms(e,i);continue}if(s==="["||s==="{")r++;else if((s==="]"||s==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}function AA(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if($s(e,t)){t=Ms(e,t);continue}break}return e.slice(t)}function or(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let s=e[i];if(ai(s)){i=Ps(e,i);continue}if($s(e,i)){i=Ms(e,i);continue}s==="["||s==="{"||s==="("?n++:s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(s=>AA(s).trim()).filter(s=>s.length>0)}function qh(e){let t=Ps(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
28
+ `:i==="r"?"\r":i==="t"?" ":i)}function RA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kc(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${RA(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,s=!1;for(;i<e.length;){let a=e[i];if(ai(a)){i=Ps(e,i);continue}if($s(e,i)){i=Ms(e,i);continue}if(!s){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))s=!0;else if(a===";")return null;i++;continue}if(a==="[")return Os(e,i);if(a===";")return null;i++}return null}function Vc(e){let t={};if(!e.startsWith("{"))return t;for(let n of or(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],s=r[4].trim();ai(s[0]??"")&&(t[i]=qh(s))}return t}function CA(e,t){if(!e.startsWith("{"))return null;for(let n of or(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}function Yh(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}function Jh(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}function Xh(e,t){let n=Kc(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Jh(),i=[],s=0;for(let a of or(n.slice(1,-1))){if(!a.startsWith("{")){s++;continue}let c=Vc(a),l=c[t.key_field];if(!l){s++;continue}let d=(t.partition_by??[]).map(u=>c[u]??"");i.push({key:l,fields:Yh(c,t.fields),orderPath:d,ordinal:r(d)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Zh(e,t){let n=Kc(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Jh(),i=[],s=0,a=o((c,l,d)=>{let u=t.levels[l],f=l===t.levels.length-1;for(let p of or(c.slice(1,-1))){let h={...d},g=null;if(u.shape==="object"){if(!p.startsWith("{")){s++;continue}let y=Vc(p);for(let[b,w]of Object.entries(u.fields??{}))h[b]=y[String(w)]??"";if(!f&&typeof u.children=="string"){let b=CA(p,u.children);g=b&&b.startsWith("[")?Os(b,0):null}}else{if(!p.startsWith("[")){s++;continue}let y=or(p.slice(1,-1));for(let[b,w]of Object.entries(u.fields??{})){let k=y[Number(w)];h[b]=k!==void 0&&ai(k[0]??"")?qh(k):""}if(!f&&typeof u.children=="number"){let b=y[u.children];g=b!==void 0&&b.startsWith("[")?Os(b,0):null}}if(f){let y=h[t.key_field];if(!y){s++;continue}let b=(t.partition_by??[]).map(w=>h[w]??"");i.push({key:y,fields:Yh(h,t.fields),orderPath:b,ordinal:r(b)});continue}g!==null&&a(g,l+1,h)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:s}:{records:i,error:null,dropped:s}}function Kh(e,t){return t.extractor==="object-array"?Xh(e,t):Zh(e,t)}function Qh(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}function eg(e,t,n){return`spec.drift:${e}#${t}:${n}`}function IA(e){return e.orderPath.join(" / ")||"(flat)"}function tg(e,t,n,r){let i=[],s=o((d,u,f,p,h,g)=>{i.push({id:eg(e.id,d,f),contract:e.id,dimension:d,status:u,key:f,title:p,detail:h,hint:g})},"push"),a=new Map(n.map(d=>[d.key,d])),c=new Map(t.map(d=>[d.key,d]));for(let d of t){let u=a.get(d.key);if(!u){s("coverage","open",d.key,`${d.key} is declared by the specification but missing from the implementation`,`Partition ${IA(d)}, position ${d.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let f of e.compare_fields??[]){let p=d.fields[f]??"",h=u.fields[f]??"";p!==h&&s("fields","open",`${d.key}.${f}`,`${d.key}: ${f} is "${h||"\u2014"}", the specification says "${p||"\u2014"}"`,`Field \`${f}\` disagrees between the two sides.`)}}let l=new Map;for(let d of t){let u=d.orderPath.join("\0"),f=l.get(u);f?f.push(d):l.set(u,[d])}for(let[d,u]of l){let f=u.filter(y=>a.has(y.key)).map(y=>y.key),p=n.filter(y=>y.orderPath.join("\0")===d).filter(y=>c.has(y.key)).map(y=>y.key),h=new Set(p),g=f.filter(y=>h.has(y));if(p.join("|")!==g.join("|")){let y=d.split("\0").join(" / ")||"(flat)";s("order","open",y,`Partition ${y}: sequence differs from the specification`,`implementation: ${p.join(" \u2192 ")}
29
+ specification: ${g.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let d of n)c.has(d.key)||s("extra","warn",d.key,`${d.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let d of new Set([...a.keys(),...c.keys()])){if(Qh(d,e.grounding,r))continue;let u=a.has(d);s("unrealized",u?"open":"warn",d,u?`${d} is referenced by the implementation but has no artefact`:`${d} is declared by the specification but not built yet`,u?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}function NA(e,t,n){let r=[];for(let i of e.assertions??[]){let s=n.get(i.path);if(!s)continue;let a=s.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(s.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),d=t[i.counts];l!==d&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${d}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}function Vh(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}function ng(e,t={}){let n=o(u=>({ok:!1,verdict:"no_opinion",reason:u,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(u=>t.contracts.includes(u.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(u=>`"${u}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=o(u=>{let f=[],p=[];for(let h of r){let g=u.get(h.spec.path),y=u.get(h.impl.path);if(g==null||y==null){let S=g==null?h.spec.path:h.impl.path;f.push(Vh(h.id,`Declared file could not be read: ${S}`)),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=Kh(g,h.spec),w=Kh(y,h.impl);if(b.error||w.error){f.push(Vh(h.id,b.error??w.error??"unknown")),p.push({id:h.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let k=b.dropped>0||w.dropped>0;p.push({id:h.id,measured:!0,specRecords:b.records.length,implRecords:w.records.length,partial:k}),k&&f.push({id:`contract.partial:${h.id}`,contract:h.id,dimension:"contract",status:"warn",key:null,title:`Contract "${h.id}" was measured incompletely`,detail:`${b.dropped} specification and ${w.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),f.push(...tg(h,b.records,w.records,e.files)),f.push(...NA(h,{spec:b.records.length,impl:w.records.length},u))}return{findings:f,contracts:p}},"runOnce"),s=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let u of i(e.baselineSources).findings)u.id.startsWith("contract.unreadable:")||a.add(u.id);let c=new Map;for(let u of r)for(let f of u.exceptions??[])c.set(eg(u.id,f.dimension,f.key),f);let l=s.findings.map(u=>{let f=c.get(u.id);return f?{...u,status:"info",exceptionReason:f.reason}:a.has(u.id)?{...u,status:"info",detail:`${u.detail}
30
+ Pre-existing at ${e.baseRef} \u2014 inventory, not introduced by this branch.`}:u});l.sort((u,f)=>zh[u.status]-zh[f.status]||u.id.localeCompare(f.id));let d=l.some(u=>u.status==="open");return{ok:!d,verdict:d?"drifted":"aligned",reason:null,findings:l,contracts:s.contracts}}function Wc(e){let t=e?.trim();return t||null}function Ls(e){let t;try{t=JSON.parse(e)}catch(a){return{manifest:null,error:`manifest is not valid JSON: ${a.message}`}}let n=o(a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,"obj"),r=o(a=>typeof a=="string"?a:"","str"),i=n(t);if(!i||!Array.isArray(i.contracts))return{manifest:null,error:"manifest has no `contracts` array"};let s=o(a=>({manifest:null,error:a}),"bad");for(let[a,c]of i.contracts.entries()){let l=n(c),d=r(l?.id),u=d?`contract "${d}"`:`contract #${a+1}`;if(!l)return s(`${u}: not an object`);if(!d)return s(`${u}: \`id\` is missing`);if(!r(l.reason))return s(`${u}: \`reason\` is missing \u2014 it is mandatory, because it is what makes this file a record of knowledge rather than configuration`);for(let f of["spec","impl"]){let p=n(l[f]);if(!p)return s(`${u}: \`${f}\` is missing`);let h=r(p.extractor);if(!h)return s(`${u}: \`${f}.extractor\` is missing`);if(h!=="object-array"&&h!=="nested-literal-list")return s(`${u}: unknown \`${f}.extractor\` "${h}"`);if(!r(p.path)||!r(p.symbol)||!r(p.key_field))return s(`${u}: \`${f}\` needs \`path\`, \`symbol\` and \`key_field\``);if(h==="nested-literal-list"&&!Array.isArray(p.levels))return s(`${u}: \`${f}\` is a nested-literal-list and needs \`levels\``)}for(let f of Array.isArray(l.exceptions)?l.exceptions:[]){let p=n(f);if(!p||!r(p.reason))return s(`${u}: exception for "${r(p?.key)||"?"}" has no \`reason\` \u2014 an exception without one is a blank cheque nobody revokes`)}}return{manifest:i,error:null}}function OA(e){let t=Wc(C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(C(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}function DA(e){let t=new Set;for(let n of e.contracts){t.add(n.spec.path),t.add(n.impl.path);for(let r of n.assertions??[])t.add(r.path)}return[...t]}async function rg(e,t={}){let n=o((g,y)=>TA.join(g,y),"join"),r=t.manifestPath??Ds,i=[],s={isRepo:!1,manifestPath:r,manifest:null,manifestError:null,sources:new Map,baselineSources:new Map,baseRef:null,files:new Set,skipped:i};if(Wc(C(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{...s,manifestError:"not a git work tree"};let a=n(e,r);if(!EA(a))return{...s,isRepo:!0,manifestError:`no manifest at ${r} \u2014 nothing is declared, so nothing is asserted`};let c=null,l=null;try{({manifest:c,error:l}=Ls(Wh(a,"utf8")))}catch(g){l=`manifest at ${r} could not be read: ${g.message}`}if(!c)return{...s,isRepo:!0,manifestError:l};let d=new Map;for(let g of DA(c))try{d.set(g,Wh(n(e,g),"utf8"))}catch{d.set(g,null),i.push(`declared file unreadable in the working tree: ${g}`)}let u=new Set,f=C(e,["ls-files","-z"]);if(f===null)i.push("could not list tracked files \u2014 grounding is skipped");else for(let g of f.split("\0"))g&&u.add(g);let p=null,h=new Map;if(t.includeBaseline!==!1){let g=t.baseRef?null:OA(e),y=t.baseRef??(g?`origin/${g}`:null);if(!y)i.push("no default branch resolvable (offline clone?) \u2014 every finding reported as new");else if(p=Wc(C(e,["merge-base",y,"HEAD"])),!p)i.push(`no merge-base with ${y} \u2014 every finding reported as new`);else for(let b of d.keys())h.set(b,C(e,["show",`${p}:${b}`]))}return{isRepo:!0,manifestPath:r,manifest:c,manifestError:null,sources:d,baselineSources:h,baseRef:p,files:u,skipped:i}}async function pn(e,t={}){let n=await rg(e,t);return{...ng(n,t),facts:n}}function zc(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null}var Ds,zh,ci=_(()=>{"use strict";fe();Ds=".maind/spec-contracts.json";o(Ps,"endOfString");o(Ms,"skipComment");o(ai,"isQuote");o($s,"isCommentStart");o(Os,"sliceBalanced");o(AA,"stripLeadingTrivia");o(or,"splitTopLevel");o(qh,"readStringLiteral");o(RA,"escapeRe");o(Kc,"findSymbolArray");o(Vc,"parseObjectFields");o(CA,"objectFieldRaw");o(Yh,"pickFields");o(Jh,"makeOrdinals");o(Xh,"extractObjectArray");o(Zh,"extractNestedList");o(Kh,"extractRecords");o(Qh,"isGrounded");o(eg,"findingId");o(IA,"partitionOf");o(tg,"compareContract");o(NA,"checkAssertions");o(Vh,"unreadable");zh={open:0,warn:1,info:2,passed:3};o(ng,"computeSpecDrift");o(Wc,"trimOrNull");o(Ls,"parseManifest");o(OA,"resolveDefaultBranch");o(DA,"declaredPaths");o(rg,"gatherSpecDriftFacts");o(pn,"checkSpecDrift");o(zc,"isSpecDriftGraded")});import{execFileSync as PA}from"node:child_process";import{existsSync as MA,readFileSync as $A}from"node:fs";import{join as LA}from"node:path";function li(e){let t=[],n=e.split(`
31
+ `);for(let r=0;r<n.length;r+=1){let i=n[r]??"";if(!/^##(?!#)\s/.test(i))continue;let s=/(\d+\.\d+\.\d+)/.exec(i);s&&t.push({version:s[1],line:r+1,raw:i.trim(),shape:/^##\s+Unreleased\b/i.test(i)?"unreleased-labelled":FA.test(i)?"never-published":"released"})}return t}function sg(e){let t=new Map;for(let n of li(e)){let r=t.get(n.version);r?r.push(n):t.set(n.version,[n])}return[...t.entries()].filter(([,n])=>n.length>1).map(([n,r])=>({version:n,count:r.length,lines:r.map(i=>i.line),shapes:r.map(i=>i.shape)})).sort((n,r)=>(n.lines[0]??0)-(r.lines[0]??0))}function og(e,t){let n=sg(e);if(t===null)return{introduced:[],preExisting:n.map(a=>({...a,countBefore:a.count})),baseResolved:!1};let r=new Map;for(let a of li(t))r.set(a.version,(r.get(a.version)??0)+1);let i=[],s=[];for(let a of n){let c=r.get(a.version)??0;(a.count>c?i:s).push({...a,countBefore:c})}return{introduced:i,preExisting:s,baseResolved:!0}}function ag(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no CHANGELOG.md tracked",findings:[],facts:e};let t=[];for(let r of e.files){if(r.head===null)continue;let i=og(r.head,e.baseRef===null?null:r.base);for(let s of i.introduced)t.push({path:r.path,version:s.version,level:"open",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} has ${s.count} headings (was ${s.countBefore})`});for(let s of i.preExisting)t.push({path:r.path,version:s.version,level:"info",count:s.count,countBefore:s.countBefore,lines:s.lines,title:`${r.path}: version ${s.version} already had ${s.count} headings`})}return{ok:!t.some(r=>r.level==="open"),verdict:t.length===0?"clean":"duplicates",reason:null,findings:t,facts:e}}function ig(e,t){try{return PA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function jA(e,t={}){let n=ig(["ls-files","-z","--","*CHANGELOG.md","CHANGELOG.md"],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null,s=r.map(a=>{let c=LA(e,a);return{path:a,head:MA(c)?$A(c,"utf8"):null,base:i===null?null:ig(["show",`${i}:${a}`],e)}});return{isRepo:!0,baseRef:i,files:s}}function qc(e,t={}){return ag(jA(e,t))}var FA,Fs=_(()=>{"use strict";FA=/\((?:nie\s+ver(?:ö|oe)ffentlicht|never\s+published)\b[^)]*\)/i;o(li,"parseVersionHeadings");o(sg,"findDuplicateHeadings");o(og,"classifyIntroduced");o(ag,"computeChangelogDuplicates");o(ig,"git");o(jA,"gatherChangelogFacts");o(qc,"checkChangelogDuplicates")});import{execFileSync as UA}from"node:child_process";import{existsSync as HA,readFileSync as cg}from"node:fs";import{dirname as lg,join as dg}from"node:path";function fg(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.packages.length===0)return{ok:!1,verdict:"no_opinion",reason:"no publishable package.json tracked",findings:[],facts:e};if(!e.registryReachable)return{ok:!1,verdict:"no_opinion",reason:e.registryError??"registry unreachable",findings:[],facts:e};let t=[];for(let n of e.packages){let r=new Set(e.published[n.name]??[]),i=new Set(n.documentedBase??n.documented),s=[...n.documented].sort(zr);for(let a of s){if(r.has(a)||zr(a,n.version)>=0)continue;let c=!i.has(a);t.push({package:n.name,version:a,level:c?"open":"info",rule:"release.phantom",title:c?`${n.name}@${a} is newly documented as released but the registry never served it`:`${n.name}@${a} is documented as released but the registry never served it`})}for(let a of[...n.neverPublished??[]].sort(zr))r.has(a)&&t.push({package:n.name,version:a,level:"info",rule:"release.mislabelled",title:`${n.name}@${a} is marked never published but the registry serves it`});r.has(n.version)||t.push({package:n.name,version:n.version,level:"info",rule:"release.unpublished",title:`${n.name}@${n.version} is not published yet`})}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"mismatch",reason:null,findings:t,facts:e}}function ug(e){let t=li(e),n=[...new Set(t.filter(s=>s.shape!=="never-published").map(s=>s.version))],r=new Set(n),i=[...new Set(t.filter(s=>s.shape==="never-published"&&!r.has(s.version)).map(s=>s.version))];return{documented:n,neverPublished:i}}function Yc(e,t){try{return UA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:32*1024*1024})}catch{return null}}function pg(e,t=null){let n=Yc(["ls-files","-z","--","package.json","*/package.json"],e);if(n===null)return[];let r=[];for(let i of[...new Set(n.split("\0").filter(Boolean))].sort()){let s;try{s=JSON.parse(cg(dg(e,i),"utf8"))}catch{continue}if(s.private===!0||typeof s.name!="string"||typeof s.version!="string")continue;let a=lg(i)==="."?"":lg(i),c=dg(e,a,"CHANGELOG.md"),{documented:l,neverPublished:d}=HA(c)?ug(cg(c,"utf8")):{documented:[],neverPublished:[]},u=a===""?"CHANGELOG.md":`${a}/CHANGELOG.md`,f=t===null?null:Yc(["show",`${t}:${u}`],e),p=t===null?null:f===null?[]:ug(f).documented;r.push({dir:a,name:s.name,version:s.version,documented:l,documentedBase:p,neverPublished:d})}return r}async function BA(e){let t=`https://registry.npmjs.org/${e.replace("/","%2F")}`,n=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(n.status===404)return[];if(!n.ok)throw new Error(`HTTP ${n.status}`);let r=await n.json();return Object.keys(r.versions??{})}async function mg(e,t={}){if(Yc(["rev-parse","--is-inside-work-tree"],e)===null)return{isRepo:!1,packages:[],published:{},registryReachable:!1,registryError:null};let n=pg(e,t.baseRef??null);if(t.offline===!0)return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:"offline"};let r=t.fetchVersions??BA,i={};for(let s of n)try{i[s.name]=await r(s.name)}catch(a){return{isRepo:!0,packages:n,published:{},registryReachable:!1,registryError:`${s.name}: ${a.message}`}}return{isRepo:!0,packages:n,published:i,registryReachable:!0,registryError:null}}async function Jc(e,t={}){return fg(await mg(e,t))}var Xc=_(()=>{"use strict";qr();Fs();o(fg,"computeReleaseClaims");o(ug,"claimsOf");o(Yc,"git");o(pg,"discoverPackages");o(BA,"packument");o(mg,"gatherReleaseClaimsFacts");o(Jc,"checkReleaseClaims")});import{execFileSync as GA}from"node:child_process";import{existsSync as WA,readFileSync as KA}from"node:fs";import{join as VA}from"node:path";function Qc(e){let t=[],n=!1;for(let r of e.split(`
32
+ `)){let i=r.trim();if(n){i===_g&&(n=!1);continue}if(i===yg){n=!0;continue}t.push(r)}return t.join(`
33
+ `)}function hg(e){return e.split(`
34
+ `).map(t=>t.trim()).filter(t=>t.length>0)}function bg(e,t){let n=new Map;for(let s of hg(t??""))n.set(s,(n.get(s)??0)+1);let r=[];for(let s of hg(e)){let a=n.get(s)??0;a>0?n.set(s,a-1):r.push(s)}let i=0;for(let s of n.values())i+=s;return{added:r,removed:i,net:Math.max(0,r.length-i)}}function wg(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.baseRef===null)return{ok:!1,verdict:"no_opinion",reason:"no base to measure growth against",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no agent instruction file tracked",findings:[],facts:e};let t=[];for(let n of e.files){if(n.head===null)continue;let r=bg(Qc(n.head),n.base===null?null:Qc(n.base));r.net!==0&&t.push({path:n.path,level:"open",netLines:r.net,addedLines:r.added.length,removedLines:r.removed,sample:r.added.slice(0,5),newFile:n.base===null,title:n.base===null?`${n.path}: new agent instruction file with ${r.net} line(s) \u2014 every line loads into every session`:`${n.path}: +${r.net} line(s) of agent instructions \u2014 every line loads into every session; durable knowledge belongs in docs, a convention or a code comment`})}return{ok:t.length===0,verdict:t.length===0?"clean":"grown",reason:null,findings:t,facts:e}}function Zc(e,t){try{return GA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:64*1024*1024})}catch{return null}}function vg(e,t={}){let n=Zc(["ls-files","-z","--",...gg],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=t.baseRef&&Zc(["merge-base",t.baseRef,"HEAD"],e)?.trim()||null,s=[...new Set(n.split("\0").filter(Boolean))].sort().map(a=>{let c=VA(e,a);return{path:a,head:WA(c)?KA(c,"utf8"):null,base:r===null?null:Zc(["show",`${r}:${a}`],e)}});return{isRepo:!0,baseRef:r,files:s}}function el(e,t={}){return wg(vg(e,t))}var gg,yg,_g,tl=_(()=>{"use strict";gg=[":(glob)**/CLAUDE.md",":(glob)**/AGENTS.md",":(glob)**/GEMINI.md",":(glob)**/.cursorrules",":(glob)**/.windsurfrules",":(glob)**/.github/copilot-instructions.md"],yg="<!-- maind:conventions v1 begin -->",_g="<!-- maind:conventions v1 end -->";o(Qc,"stripManagedConventionsBlock");o(hg,"contentLines");o(bg,"proseDelta");o(wg,"computeAgentDocProse");o(Zc,"git");o(vg,"gatherAgentDocProseFacts");o(el,"checkAgentDocProse")});var kg,xg,nl=_(()=>{"use strict";kg=[".github/workflows/*.yml",".github/workflows/*.yaml",".gitlab-ci.yml",".gitlab-ci.yaml",".gitlab/ci/*.yml",".gitlab/ci/*.yaml","bitbucket-pipelines.yml",".circleci/config.yml",".circleci/config.yaml","azure-pipelines.yml","azure-pipelines.yaml",".azure-pipelines/*.yml",".azure-pipelines/*.yaml",".gitea/workflows/*.yml",".gitea/workflows/*.yaml",".forgejo/workflows/*.yml",".forgejo/workflows/*.yaml",".woodpecker.yml",".woodpecker.yaml",".woodpecker/*.yml",".woodpecker/*.yaml",".drone.yml"],xg=new RegExp([String.raw`^\.github/workflows/.+\.ya?ml$`,String.raw`^\.gitlab-ci\.ya?ml$`,String.raw`^\.gitlab/ci/.+\.ya?ml$`,String.raw`^bitbucket-pipelines\.yml$`,String.raw`^\.circleci/config\.ya?ml$`,String.raw`^azure-pipelines\.ya?ml$`,String.raw`^\.azure-pipelines/.+\.ya?ml$`,String.raw`^\.(gitea|forgejo)/workflows/.+\.ya?ml$`,String.raw`^\.woodpecker\.ya?ml$`,String.raw`^\.woodpecker/.+\.ya?ml$`,String.raw`^\.drone\.yml$`,String.raw`^Jenkinsfile$`].join("|"))});import{execFileSync as zA}from"node:child_process";import{existsSync as qA,readFileSync as YA}from"node:fs";import{join as JA}from"node:path";function Eg(e){if(!e.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not a repository",findings:[],facts:e};if(e.files.length===0)return{ok:!1,verdict:"no_opinion",reason:"no YAML CI config (GitHub, GitLab, Bitbucket, CircleCI, Azure, Gitea/Forgejo, Woodpecker, Drone)",findings:[],facts:e};let t=[];for(let n of e.files){if(n.content===null)continue;let r=new Set(n.base===null?[]:ws(n.base).map(i=>i.value));for(let i of ws(n.content)){let s=i.value.length>60?`${i.value.slice(0,57)}\u2026`:i.value,a=e.baseRef!==null&&!r.has(i.value);t.push({path:n.path,level:a?"open":"info",line:i.line,value:i.value,title:`${n.path}:${i.line}: unquoted plain scalar containing ": " \u2014 ${s}`})}}return{ok:!t.some(n=>n.level==="open"),verdict:t.length===0?"clean":"unparsable",reason:null,findings:t,facts:e}}function Sg(e,t){try{return zA("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4,maxBuffer:16*1024*1024})}catch{return null}}function Tg(e,t={}){let n=Sg(["ls-files","-z","--",...kg],e);if(n===null)return{isRepo:!1,baseRef:null,files:[]};let r=[...new Set(n.split("\0").filter(Boolean))].sort(),i=t.baseRef??null;return{isRepo:!0,baseRef:i,files:r.map(s=>{let a=JA(e,s);return{path:s,content:qA(a)?YA(a,"utf8"):null,base:i===null?null:Sg(["show",`${i}:${s}`],e)}})}}function rl(e,t={}){return Eg(Tg(e,t))}var il=_(()=>{"use strict";qr();nl();o(Eg,"computeWorkflowYaml");o(Sg,"git");o(Tg,"gatherWorkflowYamlFacts");o(rl,"checkWorkflowYaml")});import{readFileSync as XA}from"node:fs";import{join as ZA,posix as QA}from"node:path";function Ag(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
35
+ `;)n++;continue}if(i==="/"&&s==="*"){let c=1;for(n+=2;n<r&&c>0;)e[n]==="/"&&e[n+1]==="*"?(c++,n+=2):e[n]==="*"&&e[n+1]==="/"?(c--,n+=2):n++;t+=" ";continue}if(i==="$"){let c=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(e.slice(n));if(c){let l=c[0],d=e.indexOf(l,n+l.length);n=d===-1?r:d+l.length,t+=" ";continue}}let a=(i==="E"||i==="e")&&s==="'"&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]));if(i==="'"||a){let c=i!=="'";for(n+=c?2:1;n<r;){if(c&&e[n]==="\\"){n+=2;continue}if(e[n]==="'"){if(e[n+1]==="'"){n+=2;continue}n++;break}n++}t+=" ";continue}t+=i,n++}return t}function $e(e){let t=[],n="",r=!1,i=!1,s=o(()=>{t.push(i?n:n.toLowerCase()),n="",i=!1},"flush");for(let c=0;c<e.length;c++){let l=e[c];if(l==='"'){if(r&&e[c+1]==='"'){n+='"',c++;continue}r=!r,i=!0;continue}if(l==="."&&!r){s();continue}n+=l}s();let a=t.filter(c=>c.length>0);return a.length===0||a.length>2?null:a.length===2?{schema:a[0],name:a[1]}:{schema:"public",name:a[0]}}function ct(e){let t=[],n=0,r="";for(let i of e){if(i==="("&&n++,i===")"&&(n=Math.max(0,n-1)),i===","&&n===0){t.push(r.trim()),r="";continue}r+=i}return r.trim()&&t.push(r.trim()),t}function eR(e){let t=/^ALTER\s+DEFAULT\s+PRIVILEGES\s+([\s\S]*?)(REVOKE|GRANT)\s+(?:GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+TABLES\s+(?:FROM|TO)\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT|WITH\s+GRANT\s+OPTION))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(/REVOKE\s+GRANT\s+OPTION\s+FOR/i.test(e))return null;let a=/\bFOR\s+ROLE\s+([\s\S]+?)(?=\s+IN\s+SCHEMA\b|$)/i.exec(n);if(a&&!ct(a[1]).map(p=>$e(p)?.name??"").filter(Boolean).includes("postgres"))return null;let c=/\bIN\s+SCHEMA\s+([\s\S]+?)(?=\s+FOR\s+ROLE\b|$)/i.exec(n);if(!c||!ct(c[1]).map(f=>$e(f)?.name??"").filter(Boolean).includes("public"))return null;let d=ct(s).map(f=>f.replace(/^GROUP\s+/i,"").trim()).map(f=>$e(f)?.name??"").filter(f=>f.length>0&&f!=="public");if(d.length===0)return null;let u=[];for(let f of ct(i)){let p=/^([A-Za-z]+)\s*(\()?/.exec(f.trim());if(!p)continue;let h=p[1].toUpperCase();if(h==="ALL")return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:[...di]};p[2]!=="("&&di.includes(h)&&u.push(h)}return{action:r.toUpperCase()==="REVOKE"?"revoke":"grant",roles:d,writePrivs:u}}function Rg(e){let t=/^REVOKE\s+(GRANT\s+OPTION\s+FOR\s+)?([\s\S]+?)\s+ON\s+([\s\S]+?)\s+FROM\s+([\s\S]+?)(?:\s+(?:CASCADE|RESTRICT))?\s*$/i.exec(e.trim());if(!t)return null;let[,n,r,i,s]=t;if(n)return null;let a=i.trim();if(tR.test(a))return null;let c,l=/^ALL\s+TABLES\s+IN\s+SCHEMA\s+([\s\S]+)$/i.exec(a);if(l){if(!ct(l[1]).map(p=>$e(p)?.name??"").filter(Boolean).includes("public"))return null;c="all_in_public"}else{let f=a.replace(/^TABLE\s+/i,""),p=ct(f).map(h=>$e(h)).filter(h=>h!==null).filter(h=>h.schema==="public").map(h=>h.name);if(p.length===0)return null;c=p}let d=ct(s).map(f=>f.replace(/^GROUP\s+/i,"").trim()).map(f=>$e(f)?.name??"").filter(f=>f.length>0&&f!=="public"),u=[];for(let f of ct(r)){let p=/^([A-Za-z]+)\s*(\()?/.exec(f.trim());if(!p)continue;let h=p[1].toUpperCase(),g=p[2]==="(";if(h==="ALL")return{tables:c,roles:d,writePrivs:[...di]};!g&&di.includes(h)&&u.push(h)}return{tables:c,roles:d,writePrivs:u}}function ol(e){let t=new Map,n=[...e].sort((i,s)=>ot(i.version,s.version)),r={anonAddressed:!1,authWritesRevoked:new Set};for(let i of n){let s=Ag(i.content);for(let a of s.split(";")){let c=a.trim();if(!c)continue;if(/^ALTER\s+DEFAULT\s+PRIVILEGES\b/i.test(c)){let f=eR(c);if(!f)continue;let p=f.roles.includes("anon"),h=f.roles.includes("authenticated");if(f.action==="revoke"){if(p&&(r.anonAddressed=!0),h)for(let g of f.writePrivs)r.authWritesRevoked.add(g)}else if(p&&(r.anonAddressed=!1),h)for(let g of f.writePrivs)r.authWritesRevoked.delete(g);continue}let l=/^CREATE\s+((?:UNLOGGED\s+|TEMP(?:ORARY)?\s+|GLOBAL\s+|LOCAL\s+)*)TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:ONLY\s+)?([^\s(;]+)/i.exec(c);if(l){if(/\bTEMP(?:ORARY)?\b/i.test(l[1]??""))continue;let f=$e(l[2]);if(!f||f.schema!=="public"||/^CREATE\s+(?:\w+\s+)*TABLE\s+IF\s+NOT\s+EXISTS/i.test(c)&&t.has(f.name))continue;t.set(f.name,{createdIn:i.version,anonAddressed:r.anonAddressed,authWritesRevoked:new Set(r.authWritesRevoked)});continue}let d=/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]+)$/i.exec(c);if(d){let f=d[1].replace(/\s+(?:CASCADE|RESTRICT)\s*$/i,"");for(let p of ct(f)){let h=$e(p);h&&h.schema==="public"&&t.delete(h.name)}continue}let u=/^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([^\s;]+)\s+RENAME\s+TO\s+([^\s;]+)/i.exec(c);if(u){let f=$e(u[1]),p=$e(u[2]);if(f&&p&&f.schema==="public"){let h=t.get(f.name);h&&(t.delete(f.name),t.set(p.name,h))}continue}if(/^REVOKE\b/i.test(c)){let f=Rg(c);if(!f)continue;let p=f.tables==="all_in_public"?[...t.keys()]:f.tables,h=f.roles.includes("anon"),g=f.roles.includes("authenticated");if(!h&&!g)continue;for(let y of p){let b=t.get(y);if(b&&(h&&(b.anonAddressed=!0),g))for(let w of f.writePrivs)b.authWritesRevoked.add(w)}continue}}}return t}function sl(e){let t=[];for(let[n,r]of ol(e)){let i=[];r.anonAddressed||i.push("anon"),di.every(s=>r.authWritesRevoked.has(s))||i.push("authenticated_writes"),i.length>0&&t.push({table:n,createdIn:r.createdIn,missing:i})}return t.sort((n,r)=>n.table.localeCompare(r.table))}function Cg(e){let t=sl(e.files),n=new Map;if(e.baseFiles!==null)for(let r of sl(e.baseFiles))n.set(r.table,new Set(r.missing));return t.map(r=>{let i=e.baseFiles===null?null:n.get(r.table),a=i!=null&&r.missing.every(l=>i.has(l))?"info":"open",c=r.missing.map(l=>l==="anon"?"kein Tabellen-REVOKE nennt anon":"authenticated beh\xE4lt Schreibrechte (kumulierte REVOKEs decken INSERT/UPDATE/DELETE nicht)").join("; ");return{id:`table.acl:${e.dir}#${r.table}`,status:a,project:e.dir,table:r.table,createdIn:r.createdIn,missing:r.missing,title:`public.${r.table}: Default-Grants nie adressiert (${r.missing.join(", ")})`,detail:`\xDCber den gesamten Migrations-Bestand von ${e.dir}: ${c}. Supabase' ALTER DEFAULT PRIVILEGES grantet vollen CRUD an anon UND authenticated auf jede neue public-Tabelle; ohne Tabellen-REVOKE ist RLS die einzige Verteidigungslinie. Tabelle erzeugt in Migration ${r.createdIn}.`,hint:`REVOKE ALL ON public.${r.table} FROM PUBLIC, anon; REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.${r.table} FROM authenticated; \u2014 SELECT f\xFCr authenticated darf bewusst bleiben (RLS-gedecktes Lese-Muster). PUBLIC allein reicht NICHT (Default-Privileges sind direkte Rollen-Grants). Ein REVOKE in einer sp\xE4teren Migration z\xE4hlt ebenfalls; in DO-Bl\xF6cken z\xE4hlt es nicht (aufs Top-Level ziehen). Eine Tabelle, die NACH der Wurzelbehandlung entsteht (ALTER DEFAULT PRIVILEGES \u2026 IN SCHEMA public REVOKE ALL ON TABLES FROM anon, authenticated), kommt bereits geschlossen zur Welt und braucht kein eigenes REVOKE \u2014 diese Tabelle hier ist \xE4lter als die Wurzelbehandlung oder es gibt keine.`}})}function Ig(e,t){return e===0?"no_opinion":t===0?"clean":"exposed"}function cl(e){return e.verdict!=="no_opinion"&&e.facts.baseRef!==null&&!e.facts.skipped.some(t=>t.endsWith(js)||t.endsWith(al))}function rR(e,t){try{let n=XA(e,"utf8");return n.length>t?null:n}catch{return null}}function iR(e,t,n,r,i){let s=C(e,["diff","--name-status",`${r}...HEAD`,"--",t]);if(s===null)return i.push(`could not diff ${t} against ${r} ${js}`),null;let a=new Set,c=[];for(let u of s.split(`
36
+ `).filter(Boolean)){let[f,...p]=u.split(" ");f.startsWith("A")?a.add(p[0]):f.startsWith("R")?(c.push(p[0]),a.add(p[1])):(f.startsWith("M")||f.startsWith("D"))&&c.push(p[0])}let l=[],d=new Set(c);for(let{ref:u,content:f}of n)!a.has(u.path)&&!d.has(u.path)&&l.push({name:u.name,version:u.version,content:f});for(let u of c){let f=QA.basename(u),p=nr(f);if(p===null)continue;let h=C(e,["show",`${r}:${u}`]);if(h===null)return i.push(`could not read ${u} at ${r} ${al}`),null;l.push({name:f,version:p,content:h})}return l}function mn(e,t={}){let n=t.maxFileBytes??nR,r=[],i=dn(e,t.dirs);if(i.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],baseRef:null,skipped:r}};let s=t.includeBaseline!==!1,a=null;if(s)if(t.baseRef)a=t.baseRef;else{let p=ei(e);a=p?`origin/${p}`:null,a===null&&r.push(`no default branch resolvable ${js}`)}else r.push("baseline disabled \u2014 every finding reported as open");let c=[],l=[];for(let p of i){let h=[];for(let b of p.files){let w=rR(ZA(e,b.path),n);if(w===null){r.push(`could not read ${b.path} \u2014 excluded from the fold`);continue}h.push({ref:b,content:w})}let g=h.map(({ref:b,content:w})=>({name:b.name,version:b.version,content:w})),y=a===null?null:iR(e,p.dir,h,a,r);c.push(...Cg({dir:p.dir,files:g,baseFiles:y})),l.push({dir:p.dir,migrationCount:g.length,tableCount:ol(g).size})}let d=l.reduce((p,h)=>p+h.migrationCount,0),u=Ig(d,c.length),f={open:0,info:1};return c.sort((p,h)=>f[p.status]-f[h.status]||p.id.localeCompare(h.id)),{ok:u!=="no_opinion"&&!c.some(p=>p.status==="open"),verdict:u,findings:c,facts:{projects:l,baseRef:a,skipped:r}}}var di,tR,nR,js,al,Us=_(()=>{"use strict";fe();ti();o(Ag,"stripSql");o($e,"normalizeQualifiedIdent");o(ct,"splitTopLevel");di=["INSERT","UPDATE","DELETE"];o(eR,"parseDefaultAclTables");tR=/^(?:FUNCTION|PROCEDURE|ROUTINE|SEQUENCE|SCHEMA|DATABASE|DOMAIN|TYPE|LANGUAGE|FOREIGN\b|LARGE\b|TABLESPACE|PARAMETER|ALL\s+(?:FUNCTIONS|PROCEDURES|ROUTINES|SEQUENCES)\b)/i;o(Rg,"parseTableRevoke");o(ol,"foldTableAcl");o(sl,"evaluateTableAcl");o(Cg,"computeTableAclFindings");o(Ig,"deriveTableAclVerdict");nR=5e6,js="\u2014 findings reported ungraded (open)",al="\u2014 baseline degraded";o(cl,"isTableAclGraded");o(rR,"safeRead");o(iR,"baseFilesFor");o(mn,"checkTableAclLint")});import{readFileSync as sR}from"node:fs";import{join as ll}from"node:path";function ul(e){return e.verdict!=="no_opinion"&&e.graded}function fl(e){let t=new Set;for(let n of e.matchAll(oR))t.add(n[1]);return t}function pl(e){return new Set([...e].map(t=>t.split("-")[0]))}function $g(e){return e.split(`
37
37
  `).map(t=>{let n=t.trimStart();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")?"":t}).join(`
38
- `)}function al(e){let t=ol(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=Ag(i),a=new Set;for(let c of s.matchAll(WA)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;a.has(u)||(a.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function kg(e){return`${e.file} ${e.klass}`}function KA(e,t){let n=t===null?null:new Set(t.map(kg));return e.map(r=>({...r,status:n!==null&&n.has(kg(r))?"info":"open"}))}function Rg(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function cl(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Sg(e,t){let n=C(e,["ls-files","--",...t]);return n===null?[]:n.split(`
39
- `).filter(Boolean)}function hn(e,t={}){let n=t.maxFileBytes??VA,r=new Set;for(let u of Sg(e,["*.css"])){let p=rl(nl(e,u),n);if(p!==null)for(let f of sl(p))r.add(f)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>xg.map(p=>`${u.replace(/\/+$/,"")}/**/${p}`)):xg,s=[];for(let u of Sg(e,i)){if(!cl(u))continue;let p=rl(nl(e,u),n);p!==null&&s.push({path:u,content:p})}let a=al({tokens:r,sources:s}),c=t.includeBaseline===!1?null:zA(e,i,n,t.baseRef),l=KA(a,c?.findings??null),d=Rg(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:ol(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function zA(e,t,n,r){let i=r??YA(e);if(i===null)return null;let s=C(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let a=C(e,["diff","--name-only","--no-renames",s]);if(a===null)return null;let c=new Set(a.split(`
40
- `).filter(Boolean)),l=o(p=>c.has(p)?C(e,["show",`${s}:${p}`]):rl(nl(e,p),n),"atBase"),d=new Set;for(let p of Eg(e,s,["*.css"])){let f=l(p);if(f!==null)for(let h of sl(f))d.add(h)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let p of Eg(e,s,t)){if(!cl(p))continue;let f=l(p);f===null||f.length>n||u.push({path:p,content:f})}return{findings:al({tokens:d,sources:u}),mergeBase:s}}function Eg(e,t,n){let r=C(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
41
- `).filter(i=>i.length>0&&n.some(s=>qA(i,s)))}function qA(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function YA(e){let t=C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>C(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function rl(e,t){try{let n=BA(e,"utf8");return n.length>t?null:n}catch{return null}}var Tg,GA,WA,xg,VA,$s=_(()=>{"use strict";pe();o(il,"isThemeClassDriftGraded");Tg=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],GA=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,WA=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Tg.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(sl,"extractTokens");o(ol,"deriveNamespaces");o(Ag,"stripCommentLines");o(al,"evaluateThemeClasses");o(kg,"findingKey");o(KA,"gradeAgainstBaseline");o(Rg,"deriveThemeClassVerdict");xg=["*.ts","*.tsx","*.js","*.jsx"],VA=15e5;o(cl,"isScannableSource");o(Sg,"listTracked");o(hn,"checkThemeClassDrift");o(zA,"baselineFindings");o(Eg,"listTrackedAt");o(qA,"matchesSourcePattern");o(YA,"resolveBaseRef");o(rl,"safeRead")});function ll(e){return ii[e].version}function lt(e,t,n,r){return{detector_id:e,detector_version:ll(e),state:t,finding_count:n,...r?{reason:r}:{}}}function K(e,t,n){return{summary:lt(e,t,0,n),findings:[]}}function Pg(e){return e==="open"||e==="warn"||e==="info"}function JA(e){let t="det_number_collisions";if(!e.ok)return K(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return K(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return K(t,"not_applicable","no numbered namespaces");if(!Ec(n))return K(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!Pg(s.status))continue;let{level:a,baseline:c}=ir(s.status);i.push({detector_id:t,rule_id:Oc,level:a,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:lt(t,"ran",i.length),findings:i}}function XA(e){let t="det_spec_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return K(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"no opinion");if(!Uc(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Pg(i.status))continue;let{level:s,baseline:a}=ir(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Mc(i.dimension),level:s,baseline:a,evidence:[i.id],title:i.title})}return{summary:lt(t,"ran",r.length),findings:r}}function ZA(e){let t="det_theme_class_drift";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no theme tokens");if(!il(n))return K(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=ir(i.status);r.push({detector_id:t,rule_id:Dc,level:s,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:lt(t,"ran",r.length),findings:r}}function QA(e){let t="det_table_acl_lint";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable","no supabase migrations");if(!tl(n))return K(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=ir(i.status);r.push({detector_id:t,rule_id:Pc,level:s,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:lt(t,"ran",r.length),findings:r}}function eR(e){let t="det_changelog_duplicates";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return K(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:lt(t,"ran",r.length),findings:r}}function tR(e){let t="det_workflow_yaml";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return K(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return K(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:lt(t,"ran",r.length),findings:r}}function nR(e){let t="det_release_claims";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?K(t,"ungraded",n.reason??"registry unreachable"):K(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:lt(t,"ran",r.length),findings:r}}function rR(e){let t="det_agent_doc_prose";if(!e.ok)return K(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?K(t,"ungraded",n.reason??"no base ref to grade against"):K(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:lt(t,"ran",r.length),findings:r}}function dl(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Ls[e.level]-Ls[t.level]||Ig[e.baseline]-Ig[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Ng(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function iR(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=si(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:ll(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,a=n.get(s);a?(a.evidence.push(...i.evidence),a.count+=1,Ls[i.level]<Ls[a.level]&&(a.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:ll(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:si(i.evidence),count:i.count});return r.sort(dl)}function sR(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function xe(e){let t={det_number_collisions:JA(e.number),det_spec_drift:XA(e.spec),det_theme_class_drift:ZA(e.theme),det_table_acl_lint:QA(e.acl),det_changelog_duplicates:eR(e.changelog),det_workflow_yaml:tR(e.workflow),det_release_claims:nR(e.release),det_agent_doc_prose:rR(e.agentDoc)},n=Cg.map(l=>t[l].summary),r=Cg.flatMap(l=>t[l].findings),i=iR(r),s=[...i].sort((l,d)=>Ng(l)-Ng(d)||dl(l,d)).slice(0,Og).sort(dl),a=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:si(l.evidence),title:l.title}));return{findings:s,coverage:sR(n,a),engines:n,local:c,truncated:a}}function ct(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e},agentDoc:{ok:!1,error:e}}}function pl(e){return e instanceof Error?e.message:String(e)}async function Tt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:pl(t)}}}async function fl(e,t={}){let n={...Dg,...t.engines};try{if(!Mg(e))return xe(ct("not a git work tree"));let r=await $g(e,n,t.baseRef),i=await ul(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return xe({...r,number:i})}catch(r){return xe(ct(`detector adapter failed: ${pl(r)}`))}}async function ml(e,t={}){let n={...Dg,...t.engines};try{if(!Mg(e)){let a=xe(ct("not a git work tree"));return{commit:a,local:a}}let r=await $g(e,n,t.baseRef),i=await ul(e,n,t.baseRef,"commit"),s=await ul(e,n,t.baseRef,"local");return{commit:xe({...r,number:i}),local:xe({...r,number:s})}}catch(r){let i=xe(ct(`detector adapter failed: ${pl(r)}`));return{commit:i,local:i}}}function Mg(e){return C(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function $g(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Tt(()=>t.spec(e,r)),theme:await Tt(()=>t.theme(e,r)),acl:await Tt(()=>t.acl(e,r)),changelog:await Tt(()=>t.changelog(e,r)),workflow:await Tt(()=>t.workflow(e,r)),release:await Tt(()=>t.release(e,r)),agentDoc:await Tt(()=>t.agentDoc(e,r))}}function ul(e,t,n,r,i){let s=r==="local";return Tt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var Og,Dg,Cg,Ls,Ig,hl=_(()=>{"use strict";pe();$c();ri();ai();Wc();qc();Xc();Ds();Ms();$s();Og=64,Dg={number:o((e,t)=>un(e,t),"number"),spec:o((e,t)=>fn(e,t),"spec"),theme:o((e,t)=>hn(e,t),"theme"),acl:o((e,t)=>mn(e,t),"acl"),changelog:o((e,t)=>Hc(e,t),"changelog"),workflow:o((e,t)=>Jc(e,t),"workflow"),release:o((e,t)=>Gc(e,t),"release"),agentDoc:o((e,t)=>zc(e,t),"agentDoc")},Cg=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims","det_agent_doc_prose"];o(ll,"versionOf");o(lt,"summary");o(K,"noFindings");o(Pg,"isFindingStatus");o(JA,"adaptNumber");o(XA,"adaptSpec");o(ZA,"adaptTheme");o(QA,"adaptAcl");o(eR,"adaptChangelog");o(tR,"adaptWorkflow");o(nR,"adaptRelease");o(rR,"adaptAgentDoc");Ls={open:0,warn:1,info:2},Ig={introduced:0,pre_existing:1};o(dl,"compareWire");o(Ng,"capPriority");o(iR,"buildWire");o(sR,"deriveCoverage");o(xe,"adaptDetectorReports");o(ct,"unavailableDetectorReports");o(pl,"errorText");o(Tt,"attempt");o(fl,"runRepoHealthDetectors");o(ml,"runRepoHealthDetectorScopes");o(Mg,"insideWorkTree");o($g,"runSharedEngines");o(ul,"runNumberEngine")});var Lg,gl=_(()=>{"use strict";Yc();Lg=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:mg},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function Fg(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Lg){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=oR(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function oR(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
42
- `):t.readUntracked(e)}var jg=_(()=>{"use strict";gl();o(Fg,"scanRiskFlags");o(oR,"contentForPath")});var At,yl,Rt,or,di,ar,_l,Fs,js,Us,bl,Ug,cr=_(()=>{"use strict";At="3",yl=`
38
+ `)}function ml(e){let t=pl(e.tokens),n=[];for(let{path:r,content:i}of e.sources){let s=$g(i),a=new Set;for(let c of s.matchAll(aR)){let l=c[2],d=l.split("-")[0];if(!t.has(d)||e.tokens.has(l))continue;let u=`${c[1]}-${l}`;a.has(u)||(a.add(u),n.push({file:r,klass:u,token:l,namespace:d}))}}return n}function Ng(e){return`${e.file} ${e.klass}`}function cR(e,t){let n=t===null?null:new Set(t.map(Ng));return e.map(r=>({...r,status:n!==null&&n.has(Ng(r))?"info":"open"}))}function Lg(e,t){return e===0?"no_opinion":t===0?"clean":"drift"}function hl(e){return!(/\.(test|spec)\.[jt]sx?$/.test(e)||/(^|\/)__(tests|mocks)__\//.test(e))}function Dg(e,t){let n=C(e,["ls-files","--",...t]);return n===null?[]:n.split(`
39
+ `).filter(Boolean)}function hn(e,t={}){let n=t.maxFileBytes??lR,r=new Set;for(let u of Dg(e,["*.css"])){let f=dl(ll(e,u),n);if(f!==null)for(let p of fl(f))r.add(p)}if(r.size===0)return{ok:!1,verdict:"no_opinion",tokenCount:0,namespaceCount:0,findings:[],scannedFiles:0,graded:!1,baseRef:null};let i=t.dirs!==void 0&&t.dirs.length>0?t.dirs.flatMap(u=>Og.map(f=>`${u.replace(/\/+$/,"")}/**/${f}`)):Og,s=[];for(let u of Dg(e,i)){if(!hl(u))continue;let f=dl(ll(e,u),n);f!==null&&s.push({path:u,content:f})}let a=ml({tokens:r,sources:s}),c=t.includeBaseline===!1?null:dR(e,i,n,t.baseRef),l=cR(a,c?.findings??null),d=Lg(r.size,l.length);return{ok:d!=="no_opinion"&&!l.some(u=>u.status==="open"),verdict:d,tokenCount:r.size,namespaceCount:pl(r).size,findings:l,scannedFiles:s.length,graded:c!==null,baseRef:c?.mergeBase??null}}function dR(e,t,n,r){let i=r??fR(e);if(i===null)return null;let s=C(e,["merge-base",i,"HEAD"])?.trim();if(!s)return null;let a=C(e,["diff","--name-only","--no-renames",s]);if(a===null)return null;let c=new Set(a.split(`
40
+ `).filter(Boolean)),l=o(f=>c.has(f)?C(e,["show",`${s}:${f}`]):dl(ll(e,f),n),"atBase"),d=new Set;for(let f of Pg(e,s,["*.css"])){let p=l(f);if(p!==null)for(let h of fl(p))d.add(h)}if(d.size===0)return{findings:[],mergeBase:s};let u=[];for(let f of Pg(e,s,t)){if(!hl(f))continue;let p=l(f);p===null||p.length>n||u.push({path:f,content:p})}return{findings:ml({tokens:d,sources:u}),mergeBase:s}}function Pg(e,t,n){let r=C(e,["ls-tree","-r","--name-only",t]);return r===null?[]:r.split(`
41
+ `).filter(i=>i.length>0&&n.some(s=>uR(i,s)))}function uR(e,t){let n=t.lastIndexOf("/"),r=n<0?t:t.slice(n+1),i=n<0?"":t.slice(0,n).replace(/\/\*\*$/,"");if(i!==""&&!e.startsWith(i+"/"))return!1;let s=e.slice(e.lastIndexOf("/")+1);return r.startsWith("*")?s.endsWith(r.slice(1)):s===r}function fR(e){let t=C(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"])?.trim(),r=(t?/refs\/remotes\/origin\/(.+)$/.exec(t):null)?.[1]??["main","master"].find(i=>C(e,["rev-parse","--verify","--quiet",`origin/${i}`])!==null);return r?`origin/${r}`:null}function dl(e,t){try{let n=sR(e,"utf8");return n.length>t?null:n}catch{return null}}var Mg,oR,aR,Og,lR,Hs=_(()=>{"use strict";fe();o(ul,"isThemeClassDriftGraded");Mg=["bg","text","border","border-x","border-y","border-t","border-r","border-b","border-l","divide","outline","ring","ring-offset","fill","stroke","accent","caret","decoration","placeholder","shadow","from","via","to"],oR=/--(?:color|background-image)-([a-z0-9-]+)\s*:/g,aR=new RegExp(String.raw`(?:^|[\s"'\`:])!?(`+Mg.join("|")+String.raw`)-([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?!-)`,"g");o(fl,"extractTokens");o(pl,"deriveNamespaces");o($g,"stripCommentLines");o(ml,"evaluateThemeClasses");o(Ng,"findingKey");o(cR,"gradeAgainstBaseline");o(Lg,"deriveThemeClassVerdict");Og=["*.ts","*.tsx","*.js","*.jsx"],lR=15e5;o(hl,"isScannableSource");o(Dg,"listTracked");o(hn,"checkThemeClassDrift");o(dR,"baselineFindings");o(Pg,"listTrackedAt");o(uR,"matchesSourcePattern");o(fR,"resolveBaseRef");o(dl,"safeRead")});function gl(e){return si[e].version}function dt(e,t,n,r){return{detector_id:e,detector_version:gl(e),state:t,finding_count:n,...r?{reason:r}:{}}}function V(e,t,n){return{summary:dt(e,t,0,n),findings:[]}}function Gg(e){return e==="open"||e==="warn"||e==="info"}function pR(e){let t="det_number_collisions";if(!e.ok)return V(t,"unavailable",e.error);let{facts:n,findings:r}=e.report;if(!n.isRepo)return V(t,"unavailable",n.skipped.join("; ")||"not a git work tree");if(n.namespaces.length===0)return V(t,"not_applicable","no numbered namespaces");if(!Oc(n))return V(t,"ungraded",n.skipped.join("; ")||"no base ref to grade against");let i=[];for(let s of r){if(!Gg(s.status))continue;let{level:a,baseline:c}=sr(s.status);i.push({detector_id:t,rule_id:jc,level:a,baseline:c,evidence:[...s.ownPath?[s.ownPath]:[],...s.sightings.map(l=>l.path)],title:s.title})}return{summary:dt(t,"ran",i.length),findings:i}}function mR(e){let t="det_spec_drift";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(!n.facts.isRepo)return V(t,"unavailable",n.facts.manifestError??"not a git work tree");if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"no opinion");if(!zc(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no merge-base to grade against");let r=[];for(let i of n.findings){if(!Gg(i.status))continue;let{level:s,baseline:a}=sr(i.status,{excepted:i.exceptionReason!==void 0});r.push({detector_id:t,rule_id:Bc(i.dimension),level:s,baseline:a,evidence:[i.id],title:i.title})}return{summary:dt(t,"ran",r.length),findings:r}}function hR(e){let t="det_theme_class_drift";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable","no theme tokens");if(!ul(n))return V(t,"ungraded","no merge-base to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=sr(i.status);r.push({detector_id:t,rule_id:Uc,level:s,baseline:a,evidence:[i.file,i.klass,i.token],title:`${i.klass} in ${i.file} \u2014 token ${i.token} does not exist`})}return{summary:dt(t,"ran",r.length),findings:r}}function gR(e){let t="det_table_acl_lint";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable","no supabase migrations");if(!cl(n))return V(t,"ungraded",n.facts.skipped.join("; ")||"no base ref to grade against");let r=[];for(let i of n.findings){let{level:s,baseline:a}=sr(i.status);r.push({detector_id:t,rule_id:Hc,level:s,baseline:a,evidence:[i.project,i.table,...i.missing],title:i.title})}return{summary:dt(t,"ran",r.length),findings:r}}function yR(e){let t="det_changelog_duplicates";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return V(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"changelog.duplicate_heading",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,i.version],title:i.title}));return{summary:dt(t,"ran",r.length),findings:r}}function _R(e){let t="det_workflow_yaml";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return V(t,"not_applicable",n.reason??"nothing to check");if(n.facts.baseRef===null)return V(t,"ungraded","no base ref to grade against");let r=n.findings.map(i=>({detector_id:t,rule_id:"workflow.unparsable_yaml",level:i.level,baseline:i.level==="open"?"introduced":"pre_existing",evidence:[i.path,String(i.line)],title:i.title}));return{summary:dt(t,"ran",r.length),findings:r}}function bR(e){let t="det_release_claims";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.packages.length>0&&!n.facts.registryReachable?V(t,"ungraded",n.reason??"registry unreachable"):V(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:i.rule,level:i.level,baseline:"introduced",evidence:[i.package,i.version],title:i.title}));return{summary:dt(t,"ran",r.length),findings:r}}function wR(e){let t="det_agent_doc_prose";if(!e.ok)return V(t,"unavailable",e.error);let n=e.report;if(n.verdict==="no_opinion")return n.facts.isRepo&&n.facts.files.length>0&&n.facts.baseRef===null?V(t,"ungraded",n.reason??"no base ref to grade against"):V(t,"not_applicable",n.reason??"nothing to check");let r=n.findings.map(i=>({detector_id:t,rule_id:"agentdoc.added_prose",level:i.level,baseline:"introduced",evidence:[i.path,...i.sample,String(i.netLines)],title:i.title}));return{summary:dt(t,"ran",r.length),findings:r}}function yl(e,t){return e.detector_id.localeCompare(t.detector_id)||e.rule_id.localeCompare(t.rule_id)||Bs[e.level]-Bs[t.level]||jg[e.baseline]-jg[t.baseline]||(e.evidence_hash<t.evidence_hash?-1:e.evidence_hash>t.evidence_hash?1:0)}function Ug(e){return e.baseline==="pre_existing"?3:e.level==="open"?0:e.level==="warn"?1:2}function vR(e){let t=new Map,n=new Map;for(let i of e)if(i.baseline==="introduced"){let s=oi(i.evidence),a=`${i.detector_id}|${i.rule_id}|${i.level}|${s}`,c=t.get(a);c?c.count+=1:t.set(a,{detector_id:i.detector_id,detector_version:gl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"introduced",evidence_hash:s,count:1})}else{let s=`${i.detector_id}|${i.rule_id}`,a=n.get(s);a?(a.evidence.push(...i.evidence),a.count+=1,Bs[i.level]<Bs[a.level]&&(a.level=i.level)):n.set(s,{detector_id:i.detector_id,rule_id:i.rule_id,level:i.level,evidence:[...i.evidence],count:1})}let r=[...t.values()];for(let i of n.values())r.push({detector_id:i.detector_id,detector_version:gl(i.detector_id),rule_id:i.rule_id,level:i.level,baseline:"pre_existing",evidence_hash:oi(i.evidence),count:i.count});return r.sort(yl)}function kR(e,t){let n=e.filter(r=>r.state==="ran"||r.state==="not_applicable").length;return n===0?"none":n<e.length||t>0?"partial":"full"}function xe(e){let t={det_number_collisions:pR(e.number),det_spec_drift:mR(e.spec),det_theme_class_drift:hR(e.theme),det_table_acl_lint:gR(e.acl),det_changelog_duplicates:yR(e.changelog),det_workflow_yaml:_R(e.workflow),det_release_claims:bR(e.release),det_agent_doc_prose:wR(e.agentDoc)},n=Fg.map(l=>t[l].summary),r=Fg.flatMap(l=>t[l].findings),i=vR(r),s=[...i].sort((l,d)=>Ug(l)-Ug(d)||yl(l,d)).slice(0,Hg).sort(yl),a=i.length-s.length,c=r.map(l=>({detector_id:l.detector_id,rule_id:l.rule_id,level:l.level,baseline:l.baseline,evidence_hash:oi(l.evidence),title:l.title}));return{findings:s,coverage:kR(n,a),engines:n,local:c,truncated:a}}function lt(e){return{number:{ok:!1,error:e},spec:{ok:!1,error:e},theme:{ok:!1,error:e},acl:{ok:!1,error:e},changelog:{ok:!1,error:e},workflow:{ok:!1,error:e},release:{ok:!1,error:e},agentDoc:{ok:!1,error:e}}}function bl(e){return e instanceof Error?e.message:String(e)}async function Tt(e){try{return{ok:!0,report:await e()}}catch(t){return{ok:!1,error:bl(t)}}}async function wl(e,t={}){let n={...Bg,...t.engines};try{if(!Wg(e))return xe(lt("not a git work tree"));let r=await Kg(e,n,t.baseRef),i=await _l(e,n,t.baseRef,t.scope??"local",t.includeWorktrees);return xe({...r,number:i})}catch(r){return xe(lt(`detector adapter failed: ${bl(r)}`))}}async function vl(e,t={}){let n={...Bg,...t.engines};try{if(!Wg(e)){let a=xe(lt("not a git work tree"));return{commit:a,local:a}}let r=await Kg(e,n,t.baseRef),i=await _l(e,n,t.baseRef,"commit"),s=await _l(e,n,t.baseRef,"local");return{commit:xe({...r,number:i}),local:xe({...r,number:s})}}catch(r){let i=xe(lt(`detector adapter failed: ${bl(r)}`));return{commit:i,local:i}}}function Wg(e){return C(e,["rev-parse","--is-inside-work-tree"])?.trim()==="true"}async function Kg(e,t,n){let r=n?{baseRef:n}:{};return{spec:await Tt(()=>t.spec(e,r)),theme:await Tt(()=>t.theme(e,r)),acl:await Tt(()=>t.acl(e,r)),changelog:await Tt(()=>t.changelog(e,r)),workflow:await Tt(()=>t.workflow(e,r)),release:await Tt(()=>t.release(e,r)),agentDoc:await Tt(()=>t.agentDoc(e,r))}}function _l(e,t,n,r,i){let s=r==="local";return Tt(()=>t.number(e,{...n?{baseRef:n}:{},includeBranches:s,includeWorktrees:i??s}))}var Hg,Bg,Fg,Bs,jg,kl=_(()=>{"use strict";fe();Gc();ii();ci();Xc();tl();il();Fs();Us();Hs();Hg=64,Bg={number:o((e,t)=>un(e,t),"number"),spec:o((e,t)=>pn(e,t),"spec"),theme:o((e,t)=>hn(e,t),"theme"),acl:o((e,t)=>mn(e,t),"acl"),changelog:o((e,t)=>qc(e,t),"changelog"),workflow:o((e,t)=>rl(e,t),"workflow"),release:o((e,t)=>Jc(e,t),"release"),agentDoc:o((e,t)=>el(e,t),"agentDoc")},Fg=["det_number_collisions","det_spec_drift","det_theme_class_drift","det_table_acl_lint","det_changelog_duplicates","det_workflow_yaml","det_release_claims","det_agent_doc_prose"];o(gl,"versionOf");o(dt,"summary");o(V,"noFindings");o(Gg,"isFindingStatus");o(pR,"adaptNumber");o(mR,"adaptSpec");o(hR,"adaptTheme");o(gR,"adaptAcl");o(yR,"adaptChangelog");o(_R,"adaptWorkflow");o(bR,"adaptRelease");o(wR,"adaptAgentDoc");Bs={open:0,warn:1,info:2},jg={introduced:0,pre_existing:1};o(yl,"compareWire");o(Ug,"capPriority");o(vR,"buildWire");o(kR,"deriveCoverage");o(xe,"adaptDetectorReports");o(lt,"unavailableDetectorReports");o(bl,"errorText");o(Tt,"attempt");o(wl,"runRepoHealthDetectors");o(vl,"runRepoHealthDetectorScopes");o(Wg,"insideWorkTree");o(Kg,"runSharedEngines");o(_l,"runNumberEngine")});var Vg,xl=_(()=>{"use strict";nl();Vg=[{flag:"sql_migration_added",path:/(^|\/)migrations\/[^/]+\.sql$/i,onlyWhenAdded:!0},{flag:"security_definer_touched",path:/\.sql$/i,content:/\bSECURITY\s+DEFINER\b/i},{flag:"rls_policy_changed",path:/\.sql$/i,content:/\b(CREATE|ALTER|DROP)\s+POLICY\b|\bROW\s+LEVEL\s+SECURITY\b/i},{flag:"auth_config_changed",path:/(^|\/)supabase\/config\.toml$|(^|\/)(middleware|proxy)\.(ts|js)$/},{flag:"package_manifest_changed",path:/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|requirements\.txt|pyproject\.toml|Cargo\.toml|go\.mod)$/},{flag:"ci_workflow_changed",path:xg},{flag:"env_or_secrets_file",path:/(^|\/)\.env(\.[^/]+)?$|\.(pem|key)$/}]});function zg(e){let t=new Set;for(let[n,r]of e.paths)for(let i of Vg){if(t.has(i.flag)||!i.path.test(n)||i.onlyWhenAdded&&r!=="added")continue;if(!i.content){t.add(i.flag);continue}let s=xR(n,e);s!==null&&i.content.test(s)&&t.add(i.flag)}return[...t].sort()}function xR(e,t){let n=t.hunks.get(e);return n&&!n.wholeFile&&!n.degraded?n.addedLines.join(`
42
+ `):t.readUntracked(e)}var qg=_(()=>{"use strict";xl();o(zg,"scanRiskFlags");o(xR,"contentForPath")});var At,Sl,Rt,ar,ui,cr,El,Gs,Ws,Ks,Tl,Yg,lr=_(()=>{"use strict";At="3",Sl=`
43
43
  CREATE TABLE IF NOT EXISTS meta (
44
44
  key TEXT PRIMARY KEY,
45
45
  value TEXT NOT NULL
@@ -127,20 +127,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
127
127
  vec BLOB NOT NULL,
128
128
  content_hash TEXT NOT NULL
129
129
  );
130
- `,Rt="schema_version",or="last_index_commit",di="last_indexed_at",ar="edges_dirty",_l="resolve_config_fp",Fs="embed_recipe_version",js="embed_model",Us="embed_dim",bl="last_synced_at",Ug="last_synced_commit"});function wl(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}function Hg(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of wl(e.name))t.add(i);for(let i of wl(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Bg(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of wl(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var vl=_(()=>{"use strict";o(wl,"splitIdentifier");o(Hg,"buildSearchText");o(Bg,"toFtsMatchQuery")});import{readFileSync as Gg}from"node:fs";import{posix as Wg}from"node:path";function Kg(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function gn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function Vg(e){return e==="added"?0:e==="modified"?1:2}function aR(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var ui,kl=_(()=>{"use strict";zr();Fm();Qa();Um();Wm();tc();Xm();pe();ah();pc();kc();ri();hl();ai();jg();cr();vl();ui=class{static{o(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(Rt),i=await this.store.countFiles()>0;(t.full||i&&r!==At)&&await this.wipe();let s=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let w=cc(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(w===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=w}else a=nh(this.repoRoot);let c=new Set(a.map(w=>w.path)),l=new Map(s.map(w=>[w.path,w])),d=s.length>0&&!t.full,u={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},p=!1,f=o(async()=>{p||(p=!0,await this.store.setMeta(ar,"1"))},"markEdgesDirty");for(let w of s)c.has(w.path)||(await f(),await this.store.deleteFile(w.path),u.filesDeleted++);let h=0;for(let w of a){h++;let x=ih(this.repoRoot,w.path);if(!x){u.filesSkipped++;continue}let S=l.get(w.path);if(S&&S.mtimeMs===x.mtimeMs&&S.size===x.size){u.filesSkipped++;continue}let k=this.readRepoFile(w.path);if(k===null){u.filesSkipped++;continue}let v=ks(k);if(S&&S.contentHash===v){await this.store.upsertFile({...S,mtimeMs:x.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let T=await this.parser.parse(w.path,k,w.language),O=new Map;for(let H of T.nodes)O.set(H.nodeKey,Hg(H));let j={path:w.path,language:w.language,contentHash:v,mtimeMs:x.mtimeMs,size:x.size,indexedAt:n};await f(),await this.store.replaceFileNodes(j,T.nodes,O,{contains:T.edges,refs:T.refs,imports:T.imports,exports:T.exports}),u.filesParsed++,t.onProgress?.({path:w.path,done:h,total:a.length})}let g=Hm(this.repoRoot),y=await this.store.getMeta(_l)!==g.fingerprint;if(p||y||await this.store.getMeta(ar)==="1"){let w=Ym(await this.store.getNameIndex()),x=new Qn(g.config,w.files),S=Jm(await this.store.getAllFacts(),w,x);await this.store.replaceCrossFileEdges(S),await this.store.setMeta(_l,g.fingerprint),await this.store.setMeta(ar,"0")}if(this.embedder&&t.embed){let w=await this.store.getNodesByKinds([...Za]),x=await this.store.getEmbeddingContentHashes(),S=[];for(let v of w){let T=Lm(v),O=ks(`${this.embedder.recipeVersion}\0${T}`);x.get(v.nodeKey)!==O&&S.push({nodeKey:v.nodeKey,text:T,hash:O})}let k=64;for(let v=0;v<S.length;v+=k){let T=S.slice(v,v+k),O=await this.embedder.embedDocuments(T.map(H=>H.text));await this.store.upsertEmbeddings(T.map((H,N)=>({nodeKey:H.nodeKey,dim:this.embedder.dim,vec:O[N],contentHash:H.hash})));let j=Math.min(v+k,S.length);t.onProgress?.({path:"embedding symbols",done:j,total:S.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Fs,this.embedder.recipeVersion),await this.store.setMeta(js,this.embedder.model),await this.store.setMeta(Us,String(this.embedder.dim))}await this.store.setMeta(Rt,At),await this.store.setMeta(di,String(n));let b=Zr(this.repoRoot);return b&&await this.store.setMeta(or,b),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(di);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(or),schemaVersion:await this.store.getMeta(Rt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=gn(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&s.push({...Kg(c),score:a.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=gn(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:jm(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...Kg(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=gn(n.maxDepth,3,5),s=gn(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let p=0;p<i&&u.length>0;p++){let f=[];for(let h of u){let g=await this.store.neighbors(h,r,a,s);for(let y of g){let b=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(b))continue;if(l.add(b),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),f.push(w))}}u=f}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Gg(Wg.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let s={};for(let a of r)s[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(gn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=cc(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=gn(t.limit,64,200),i=[],s=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&s++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=vs(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Zr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return fh(this.repoRoot,n,t)}async checkDivergence(t={}){return ti(this.repoRoot,t)}async checkNumberCollisions(t={}){return un(this.repoRoot,t)}async checkNumberForPath(t,n={}){return pn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return fn(this.repoRoot,t)}async reviewDetectors(t={}){return fl(this.repoRoot,t)}async reviewDetectorScopes(t={}){return ml(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=vs(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=oh(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",a=Fg({paths:n,hunks:i,readUntracked:o(f=>this.readRepoFileHead(f,sh),"readUntracked")}),c=th(n.keys()),l=gn(t.limit,64,t.attest?xt:200),d=[],u=0,p=0;for(let f of c){let h=await this.store.getNodesByFile(f.path);if(h.length===0)continue;u++;let g=await this.store.getFile(f.path),y=this.readRepoFile(f.path),b=g!==null&&y!==null&&ks(y)!==g.contentHash;b&&(p++,s==="full"&&(s="partial"));let w=n.get(f.path)??"modified",x=i.get(f.path);for(let S of h)d.push(aR(S,w,x,b))}return d.sort((f,h)=>Vg(f.change)-Vg(h.change)||(f.filePath<h.filePath?-1:f.filePath>h.filePath?1:0)||f.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:p,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:Zr(this.repoRoot),dirty:lc(this.repoRoot),baseSha:t.since?xs(this.repoRoot,t.since):null,mergeBaseSha:t.since?ac(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return Gg(Wg.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};o(Kg,"toHit");o(gn,"clampLimit");o(Vg,"changeRank");o(aR,"classifyReviewSymbol")});var zg=_(()=>{"use strict";pe()});var cR,QG,qg=_(()=>{"use strict";pe();cR=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],QG=new RegExp(cR.join("|"),"g")});import{existsSync as xl,readdirSync as lR,readFileSync as dR}from"node:fs";import{spawnSync as uR}from"node:child_process";import{dirname as pR,join as Hs,posix as Sl}from"node:path";function Jg(e){let t=[],n={host:"127.0.0.1",port:e.config.source==="missing"?null:e.config.port,configSource:e.config.source,reachable:null,ledgerCount:null};if(e.config.source==="missing")return t.push({id:`db.config_missing:${e.dir}`,status:"open",project:e.dir,title:"supabase/config.toml nirgends auffindbar \u2014 DB-Ziel unbekannt",detail:`Weder dieser Tree noch der Haupt-Worktree tragen eine config.toml f\xFCr ${e.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${El} ausweichen \u2014 dorthin schreibt ein Werkzeug ohne Fehlermeldung, ggf. in die Datenbank eines FREMDEN Projekts (real passiert 2026-08-26: 'INSERT 0 1' in den falschen Ledger). Dieses Tool r\xE4t deshalb NIE einen Port und hat keine Verbindung versucht.`,hint:"config.toml aus dem Haupt-Checkout kopieren (sie ist bewusst gitignored \u2014 Ports/Keys sind lokal), dann erneut pr\xFCfen. `.maind/worktree-requirements` deklariert die Datei bereits f\xFCr check_divergence."}),{dir:e.dir,verdict:"blind",findings:t,db:n};e.config.source==="main_worktree"&&t.push({id:`db.config_missing_here:${e.dir}`,status:"open",project:e.dir,title:`config.toml fehlt in DIESEM Tree \u2014 Vergleich lief \xFCber den Haupt-Worktree (Port ${e.config.port})`,detail:`Der Ledger-Vergleich nutzt die config.toml des Haupt-Worktrees und ist damit aussagekr\xE4ftig. Aber jedes Supabase-CLI-Kommando, das HIER l\xE4uft, sieht keine config.toml und weicht still auf Port ${El} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let p=r===null?"unreachable":r.reason,f=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${f?`: ${f}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[p];return t.push({id:`db.${p}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(e.fileVersions),a=e.fileVersions.filter(p=>!i.has(p)).sort(st);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(p=>!s.has(p)).sort(st),l=new Map,d=[];for(let p of c){let f=e.siblingVersions.get(p);if(f){let h=l.get(f)??[];h.push(p),l.set(f,h)}else d.push(p)}for(let[p,f]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${p}`,status:"info",project:e.dir,title:`${f.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${p}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${f.join(", ")}. Die Dateien liegen in ${p} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:f});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let p=new Set(e.remote.versions),f=e.fileVersions.filter(g=>!p.has(g)).sort(st),h=e.remote.versions.filter(g=>!s.has(g)).sort(st);f.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${f.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${f.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:f}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(p=>p.status==="open"||p.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function Xg(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function Qg(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
131
- `).filter(Boolean).slice(-1)[0]}}function Yg(e,t,n){let r=e(t,fR,n);return r.ok===!1?Qg(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
132
- `).map(i=>i.trim()).filter(Boolean)}}function ey(e){for(let t of e.split(/^\[/m)){if(!/^db\]/.test(t))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(t.slice(t.indexOf("]")+1));if(n)return Number(n[1])}return null}function mR(e){let t=C(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=pR(t);return n===e?null:n}function hR(e,t,n){let r=Sl.dirname(t),s=[{path:Hs(e,r,"config.toml"),source:"worktree"}],a=mR(e);a&&s.push({path:Hs(a,r,"config.toml"),source:"main_worktree"});for(let c of s)if(xl(c.path))try{let l=ey(dR(c.path,"utf8"));if(l===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:l}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function gR(e,t){let n=new Map,r=C(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=C(e,["rev-parse","--show-toplevel"])?.trim();for(let s of r.split(`
133
- `)){if(!s.startsWith("worktree "))continue;let a=s.slice(9).trim();if(!a||a===i||!xl(a))continue;let c=Hs(a,t);if(xl(c))try{for(let l of lR(c)){let d=tr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function Tl(e,t={}){let n=t.runPsql??Zg,r=t.timeoutMs??15e3,i=[],s=dn(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let p of s){let f=hR(e,p.dir,i),h=f.source==="missing"?null:Yg(n,`postgresql://postgres:postgres@127.0.0.1:${f.port}/postgres`,r),g=t.remoteDbUrl!==void 0?Yg(n,t.remoteDbUrl,r):null,y=Jg({dir:p.dir,projectRoot:Hs(e,Sl.dirname(Sl.dirname(p.dir))),fileVersions:p.files.map(b=>b.version),config:f,ledger:h,siblingVersions:gR(e,p.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:p.dir,migrationCount:p.files.length,verdict:y.verdict,db:y.db})}let d=Xg(l),u={open:0,warn:1,info:2};return a.sort((p,f)=>u[p.status]-u[f.status]||p.id.localeCompare(f.id)),{ok:d==="in_sync",verdict:d,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var El,Zg,fR,ty=_(()=>{"use strict";pe();ei();El=54322;o(Jg,"evaluateLedgerProject");o(Xg,"deriveLedgerVerdict");Zg=o((e,t,n)=>{let r=uR("psql",[e,"-tAc",t],{encoding:"utf8",timeout:n,env:{...process.env,PGCONNECT_TIMEOUT:"5"}});return r.error&&r.error.code==="ENOENT"?{ok:!1,code:"enoent",stderr:""}:r.status!==0?{ok:!1,code:"error",stderr:(r.stderr??"").trim()}:{ok:!0,stdout:r.stdout??""}},"defaultRunPsql"),fR="select version from supabase_migrations.schema_migrations order by version";o(Qg,"classifyLedgerError");o(Yg,"readLedger");o(ey,"parseDbPort");o(mR,"mainWorktreeRoot");o(hR,"resolveConfig");o(gR,"gatherSiblingVersions");o(Tl,"checkMigrationLedgerDrift")});function Se(e){return typeof e=="string"?e:String(e??"")}function pi(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function Al(e){return{nodeKey:Se(e.node_key),kind:Se(e.kind),name:Se(e.name),qualifiedName:Se(e.qualified_name),filePath:Se(e.file_path),startLine:pi(e.start_line),endLine:pi(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function iy(e){return{path:Se(e.path),language:Se(e.language),contentHash:Se(e.content_hash),mtimeMs:pi(e.mtime_ms),size:pi(e.size),indexedAt:pi(e.indexed_at)}}function Rl(e){let t=new Map,n=o(i=>{let s=t.get(i);return s===void 0&&(s=e.prepare(i),t.set(i,s)),s},"stmt"),r=o(i=>{let s=n(Ct.meta).get(i);return s===void 0?null:Se(s.value)},"metaValue");return{meta(){let i=r(Rt),s=r(di);return{schemaVersion:i,schemaCurrent:i===At,edgesDirty:r(ar)==="1",lastIndexedAt:s===null?null:Number(s)}},file(i){let s=n(Ct.file).get(i);return s===void 0?null:iy(s)},files(i){let s=new Map;for(let a of new Set(i)){let c=n(Ct.file).get(a);c!==void 0&&s.set(a,iy(c))}return s},symbolsInFile(i,s=yR){return n(Ct.symbolsInFile).all(i,s).map(Al)},symbolsNamed(i,s=_R){let a=new Map;for(let c of new Set(i)){let l=n(Ct.symbolsNamed).all(c,s);l.length>0&&a.set(c,l.map(Al))}return a},callersOfFile(i,s=bR){return n(Ct.callersOfFile).all(i,i,s).map(c=>({calleeKey:Se(c.callee_key),kind:Se(c.edge_kind),caller:Al(c)}))},importersOf(i,s=wR){let a=n(Ct.importersOf).all(Ve(i),s),c=[];for(let l of a){let d=Se(l.src_key),u=d.endsWith(ry)?d.slice(0,-ry.length):d;u!==i&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function fi(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var ny,Ct,yR,_R,bR,wR,ry,Cl=_(()=>{"use strict";ln();cr();ny="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Ct={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${ny} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${ny} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"},yR=400,_R=8,bR=600,wR=200,ry="#<module>";o(Se,"str");o(pi,"num");o(Al,"toSymbol");o(iy,"toFileRow");o(Rl,"createIndexReader");o(fi,"isFileCurrent")});var Il,Nl=_(()=>{"use strict";Il="0.2.0"});function Ol(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:xt,attest:!0}}function Dl(e,t){let n=0,r=[];for(let s of e.symbols){let a=s.qualifiedName?s.qualifiedName:void 0;if(s.name.length===0||s.name.length>Bs||a!==void 0&&a.length>Gs){n+=1;continue}r.push({name:s.name,...a!==void 0?{qualified_name:a}:{},...s.kind&&s.kind.length<=oy?{kind:s.kind}:{},...s.language&&s.language.length<=ay?{language:s.language}:{},change:s.change,changed_line_count:Math.min(Math.max(0,s.changedLineCount),cy)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(s=>({detector_id:s.detector_id,detector_version:s.detector_version,state:s.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Il},dropped:n}}function Pl(e,t,n){return e?{persist:!1,skipped:"no_report"}:n.headSha?t?n.baseKind==="ref"&&typeof n.mergeBaseSha!="string"?{persist:!1,skipped:"no_merge_base"}:{persist:!0,skipped:null}:{persist:!1,skipped:"no_project_key"}:{persist:!1,skipped:"no_head"}}function Ml(e,t,n){let r=t,i=[];r===0?i.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):i.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&i.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&i.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let s=e.changedFiles-e.indexedFiles;return s>0&&i.push(`${s} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&i.push(`Symbol list truncated at ${xt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&i.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),i.join(" ")}function $l(e){let t=/^MCP error (-?\d+):\s*([\s\S]*)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]??"";return n===sy&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===sy?{kind:"invalid_params",code:n,detail:r,issues:vR(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function vR(e){let t=e.indexOf("[");if(t===-1)return[];try{let n=JSON.parse(e.slice(t));return Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null):[]}catch{return[]}}function Ll(e){if(e.kind!=="invalid_params"||e.issues.length!==1)return!1;let t=e.issues[0],n=t.path??[];return n.length===1&&n[0]==="findings"&&t.code==="invalid_type"&&(t.received===void 0||t.received==="undefined")}var Bs,Gs,oy,ay,cy,sy,kR,ly=_(()=>{"use strict";zr();Nl();Bs=200,Gs=512,oy=64,ay=32,cy=1e4;o(Ol,"attestReviewOptions");o(Dl,"buildAttestPayload");o(Pl,"attestPersistDecision");o(Ml,"attestCoverageNote");sy=-32602;o($l,"classifyMcpErrorText");o(vR,"parseIssues");o(Ll,"isLegacyAttestRejection");kR=`MCP error -32602: Input validation error: Invalid arguments for tool review_verdict: ${JSON.stringify([{code:"invalid_type",expected:"array",received:"undefined",path:["findings"],message:"Required"}],null,2)}`});var It=_(()=>{"use strict";Cp();kl();pc();gl();pe();Ds();Xc();Wc();qc();kc();zg();qg();gc();ri();$s();ai();ei();Ms();ty();$c();hl();ri();ai();$s();Ms();ys();Qa();cr();Cl();bs();Nl();ly()});import{execFileSync as xR}from"node:child_process";import{createHash as SR}from"node:crypto";import{mkdirSync as ER,readFileSync as TR,renameSync as AR,writeFileSync as RR}from"node:fs";import{dirname as dy,join as uy}from"node:path";function dt(e=process.cwd()){try{let t=xR("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function lr(e){return SR("sha256").update(e).digest("hex").slice(0,16)}function Ws(e){return uy(e,CR)}function py(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function fy(e,t,n,r=new Date().toISOString()){try{if(!py(n))return;let i={version:Fl,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=Ws(e);ER(dy(s),{recursive:!0}),Xr(dy(s));let a=`${s}.${process.pid}.tmp`;RR(a,JSON.stringify(i,null,2),"utf8"),AR(a,s)}catch{}}function Ks(e,t){try{let n=TR(Ws(e),"utf8"),r=JSON.parse(n);return r.version!==Fl||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!py(r.result)?null:{version:Fl,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function my(e,t,n=new Date){let r=IR(t.cached_at,n),i=t.result.instructions??"",s={...t.result,instructions:`${r}
134
-
135
- ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function IR(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${NR(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function NR(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let s=Math.floor(i/60);if(s<24)return`${s} hour${s===1?"":"s"} ago`;let a=Math.floor(s/24);return`${a} day${a===1?"":"s"} ago`}var Fl,CR,Nt=_(()=>{"use strict";It();Fl=1,CR=uy(".maind","conventions-cache.json");o(dt,"resolveRepoRoot");o(lr,"keyFingerprint");o(Ws,"cachePath");o(py,"hasInstructions");o(fy,"writeConventionsCache");o(Ks,"readConventionsCache");o(my,"buildCachedInitializeResponse");o(IR,"fallbackMarker");o(NR,"relativeAge")});import{existsSync as Ys,mkdirSync as BR,readFileSync as yy,writeFileSync as Gl,chmodSync as _y}from"node:fs";import{homedir as GR,hostname as WR,platform as Bl,release as KR}from"node:os";import{randomUUID as VR}from"node:crypto";import{join as yn}from"node:path";function $e(){let e=GR(),t=process.env;if(Bl()==="darwin")return yn(e,"Library","Application Support","maind");if(Bl()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:yn(e,"AppData","Roaming");return yn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:yn(e,".config");return yn(n,"maind")}function by(e){Ys(e)||BR(e,{recursive:!0,mode:448})}function ne(){let e=$e();by(e);let t=yn(e,zR);if(Ys(t)){let r=yy(t,"utf8").trim();if(JR(r))return r}let n=VR();Gl(t,n+`
136
- `,{encoding:"utf8",mode:384});try{_y(t,384)}catch{}return n}function JR(e){return YR.test(e)}function Wl(){return yn($e(),qR)}function _n(e){let t=$e();by(t);let n=Wl();Gl(n,e+`
137
- `,{encoding:"utf8",mode:384});try{_y(n,384)}catch{}}function q(){let e=Wl();if(!Ys(e))return null;let t=yy(e,"utf8").trim();return t.length>0?t:null}function gi(){let e=Wl();Ys(e)&&Gl(e,"",{encoding:"utf8",mode:384})}function wy(){try{return`mcp-bridge-${WR()}`}catch{return"mcp-bridge"}}function Js(e){return{os:`${Bl()} ${KR()}`,ide:"mcp-bridge",ext_version:e,device_id:ne()}}var zR,qR,YR,ue=_(()=>{"use strict";o($e,"configDir");o(by,"ensureDir");zR="device-id",qR="api-key";o(ne,"ensureDeviceId");YR=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(JR,"isUuid");o(Wl,"apiKeyPath");o(_n,"writeApiKey");o(q,"readApiKey");o(gi,"clearApiKey");o(wy,"bridgeLabel");o(Js,"clientMeta")});function yi(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:XR}function dr(e){return`${yi()}/${e.replace(/^\/+/,"")}`}var XR,ur=_(()=>{"use strict";XR="https://fn.maind.dev/functions/v1";o(yi,"functionsOrigin");o(dr,"functionsUrl")});import{mkdirSync as iC,readFileSync as sC,renameSync as oC,writeFileSync as aC}from"node:fs";import{join as cC}from"node:path";function ky(e=$e()){return cC(e,dC)}function pC(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,uC)}function bn(e,t,n){try{let r=n.dir??$e();iC(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:pC(t),bridge_version:n.version},s=ky(r),a=`${s}.${process.pid}.tmp`;aC(a,JSON.stringify(i)+`
138
- `,{encoding:"utf8",mode:384}),oC(a,s)}catch{}}function xy(e=$e()){try{let t=JSON.parse(sC(ky(e),"utf8"));return t.v!==1||typeof t.at!="string"||!lC.includes(t.outcome)?null:{v:1,at:t.at,outcome:t.outcome,detail:typeof t.detail=="string"?t.detail:null,bridge_version:typeof t.bridge_version=="string"?t.bridge_version:"?"}}catch{return null}}var lC,dC,uC,Kl=_(()=>{"use strict";ue();lC=["ok","paired","auth_failed","not_paired"],dC="connection-state.json",uC=200;o(ky,"connectionStatePath");o(pC,"redactDetail");o(bn,"writeConnectionState");o(xy,"readConnectionState")});var B,Le=_(()=>{"use strict";B="0.89.0"});import{execFileSync as Sy}from"node:child_process";import{createHash as fC}from"node:crypto";function mC(e){return fC("sha256").update(e).digest("hex")}function hC(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function Xs(e){let t=hC(e);return t?mC(t):null}function Y(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&gC.test(e))return e;let t;try{t=Sy("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Xs(t):null}function Zs(e){let t;try{t=Sy("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?Xs(t):null}var gC,Fe=_(()=>{"use strict";o(mC,"sha256Hex");o(hC,"normalizeRemoteUrl");o(Xs,"projectKeyFromRemote");gC=/^[a-f0-9]{64}$/;o(Y,"computeProjectKey");o(Zs,"projectKeyForRepo")});import yC from"node:path";import{fileURLToPath as _C}from"node:url";function bC(e,t=yC.sep){return e.split(t).includes("_npx")}function Ee(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",Ty,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):bC(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function Te(){try{let e=_C(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ot(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Ey(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Ey(n)).join(" ")}function Qs(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(Ty)}function eo(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Ey(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Ty,wn=_(()=>{"use strict";Ty="@maind-dev/mcp-bridge";o(bC,"isEphemeralEntry");o(Ee,"resolveBridgeLaunch");o(Te,"currentBridgeEntry");o(Ot,"launchToShellCommand");o(Qs,"isNpxForm");o(eo,"isLegacyHookForm");o(Ey,"shellQuote")});import*as W from"node:path";function Ay(e){let t=e.launch??Ee({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}function vC(e){switch(e.platform){case"darwin":return W.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??W.join(e.homeDir,"AppData","Roaming");return W.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??W.join(e.homeDir,".config");return W.join(t,"Claude","claude_desktop_config.json")}}}function zl(e,t){switch(e.platform){case"darwin":return W.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??W.join(e.homeDir,"AppData","Roaming");return W.join(n,t)}default:{let n=e.xdgConfigHome??W.join(e.homeDir,".config");return W.join(n,t)}}}function kC(e){return W.join(zl(e,"Code"),"User")}function ql(e,t){return{kind:"foreign-entries",dir:zl(e,t),ours:["User"]}}function Ry(e){return{evidence:[ql(e,"Cursor"),{kind:"foreign-entries",dir:W.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function xC(e){return{evidence:[ql(e,"Windsurf"),{kind:"foreign-entries",dir:W.join(e.homeDir,".codeium","windsurf"),ours:["mcp_config.json"]}],skipDetail:"Windsurf not found (no Windsurf app data, nothing of Windsurf's in ~/.codeium/windsurf)"}}function Cy(e){return e.clineDataDir?e.clineDataDir:W.join(e.clineDir??W.join(e.homeDir,".cline"),"data")}function EC(e){return e.clineMcpSettingsPath??W.join(Cy(e),"settings","cline_mcp_settings.json")}function TC(e){return{evidence:[{kind:"foreign-entries",dir:Cy(e),ours:["settings"]},...SC.map(t=>({kind:"dir",path:W.join(zl(e,t),"User","globalStorage","saoudrizwan.claude-dev")}))],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline storage in any editor)"}}function Iy(e){return e.continueGlobalDir??W.join(e.homeDir,".continue")}function AC(e){return W.join(Iy(e),"mcpServers","maind.json")}function RC(e){return{evidence:[{kind:"foreign-entries",dir:Iy(e),ours:["mcpServers"]}],skipDetail:"Continue not found (nothing of Continue's in ~/.continue)"}}function CC(e){return W.join(kC(e),"mcp.json")}function _i(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:W.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:W.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:vC(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:W.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Ry(e)},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:W.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json",presence:xC(e)},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:CC(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[ql(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:EC(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:TC(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:AC(e),kind:"json",presence:RC(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:W.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function Ny(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Oy(e){return e.jsonShape??wC}function no(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Vl(e.env.XDG_CONFIG_HOME),appData:Vl(e.env.APPDATA),clineDir:to(e.env.CLINE_DIR),clineDataDir:to(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:to(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:to(e.env.CONTINUE_GLOBAL_DIR)}}function Vl(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function to(e){let t=Vl(e);return t!==null&&W.isAbsolute(t)?t:null}var wC,SC,bi,fr=_(()=>{"use strict";wn();wC={serversKey:"mcpServers"};o(Ay,"buildMaindServerEntry");o(vC,"claudeDesktopConfigPath");o(zl,"editorAppDataDir");o(kC,"vsCodeUserDir");o(ql,"editorRan");o(Ry,"cursorPresence");o(xC,"windsurfPresence");SC=["Code","Code - Insiders","Cursor","VSCodium","Windsurf","AgentComposer"];o(Cy,"clineDataDir");o(EC,"clineMcpSettingsPath");o(TC,"clinePresence");o(Iy,"continueGlobalDir");o(AC,"continueMcpConfigPath");o(RC,"continuePresence");o(CC,"vsCodeUserMcpPath");o(_i,"getClientTargets");o(Ny,"filterTargetsByFamily");o(Oy,"jsonShapeOf");bi=[...new Set(_i({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];o(no,"makeDefaultContext");o(Vl,"nonEmpty");o(to,"absoluteOrNull")});import*as My from"node:fs/promises";import*as Dt from"node:path";import*as $y from"node:readline";async function Ly(e){let t=Dt.resolve(e),n=t;for(;;){if(await Fy(n))return n;let r=Dt.dirname(n);if(r===n)return t;n=r}}async function ro(e){let n=Dt.resolve(e),r=[];for(;;){await Fy(n)&&r.push(n);let i=Dt.dirname(n);if(i===n)break;n=i}return r}async function Fy(e){for(let t of NC)try{return await My.access(Dt.join(e,t)),!0}catch{}return!1}async function jy(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
130
+ `,Rt="schema_version",ar="last_index_commit",ui="last_indexed_at",cr="edges_dirty",El="resolve_config_fp",Gs="embed_recipe_version",Ws="embed_model",Ks="embed_dim",Tl="last_synced_at",Yg="last_synced_commit"});function Al(e){return e.replace(/[_\-./]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>0)}function Jg(e){let t=new Set;t.add(e.name.toLowerCase()),t.add(e.qualifiedName.toLowerCase());for(let i of Al(e.name))t.add(i);for(let i of Al(e.qualifiedName))t.add(i);let n=[e.doc??"",e.signature??""].join(" ").trim(),r=[...t].join(" ");return n?`${r} ${n}`:r}function Xg(e){let t=new Set;for(let n of e.split(/\s+/)){let r=n.replace(/[^A-Za-z0-9]+/g,"");if(r.length!==0){t.add(r.toLowerCase());for(let i of Al(r))t.add(i)}}return t.size===0?null:[...t].map(n=>`${n}*`).join(" OR ")}var Rl=_(()=>{"use strict";o(Al,"splitIdentifier");o(Jg,"buildSearchText");o(Xg,"toFtsMatchQuery")});import{readFileSync as Zg}from"node:fs";import{posix as Qg}from"node:path";function ey(e){return{nodeKey:e.nodeKey,kind:e.kind,name:e.name,qualifiedName:e.qualifiedName,filePath:e.filePath,language:e.language,startLine:e.startLine,endLine:e.endLine}}function gn(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(1,Math.min(n,Math.floor(e)))}function ty(e){return e==="added"?0:e==="modified"?1:2}function SR(e,t,n,r){if(r)return{...e,change:"co_located",changedLineCount:0,staleIndex:!0};if(t==="added"||n?.wholeFile)return{...e,change:"added",changedLineCount:e.endLine-e.startLine+1,staleIndex:!1};if(!n||n.degraded||n.binary)return{...e,change:"co_located",changedLineCount:0,staleIndex:!1};let i=0;for(let a of n.addedRanges){let c=Math.max(a.start,e.startLine),l=Math.min(a.end,e.endLine);l>=c&&(i+=l-c+1)}let s=n.deletionPoints.some(a=>a>=e.startLine-1&&a<=e.endLine);return i>0||s?{...e,change:"modified",changedLineCount:i,staleIndex:!1}:{...e,change:"co_located",changedLineCount:0,staleIndex:!1}}var fi,Cl=_(()=>{"use strict";qr();zm();oc();Ym();Qm();cc();oh();fe();gh();bc();Cc();ii();kl();ci();qg();lr();Rl();fi=class{static{o(this,"CodeIndexEngine")}store;parser;repoRoot;embedder;constructor(t){this.store=t.store,this.parser=t.parser,this.repoRoot=t.repoRoot,this.embedder=t.embedder??null}async indexRepository(t={}){let n=t.now??Date.now();await this.store.init(),await this.parser.init();let r=await this.store.getMeta(Rt),i=await this.store.countFiles()>0;(t.full||i&&r!==At)&&await this.wipe();let s=await this.store.getAllFiles(),a;if(t.onlyChangedSince!==void 0){if(s.length>0)throw new Error("onlyChangedSince builds a throwaway index and needs an empty store \u2014 on a filled one the deletion pass would drop every file outside the diff");let w=hc(this.repoRoot,{since:t.onlyChangedSince,includeUncommitted:!1});if(w===null)throw new Error("onlyChangedSince requires a git repository with a HEAD commit");a=w}else a=uh(this.repoRoot);let c=new Set(a.map(w=>w.path)),l=new Map(s.map(w=>[w.path,w])),d=s.length>0&&!t.full,u={filesScanned:a.length,filesParsed:0,filesSkipped:0,filesDeleted:0,nodeCount:0,edgeCount:0,durationMs:0,incremental:d},f=!1,p=o(async()=>{f||(f=!0,await this.store.setMeta(cr,"1"))},"markEdgesDirty");for(let w of s)c.has(w.path)||(await p(),await this.store.deleteFile(w.path),u.filesDeleted++);let h=0;for(let w of a){h++;let k=ph(this.repoRoot,w.path);if(!k){u.filesSkipped++;continue}let S=l.get(w.path);if(S&&S.mtimeMs===k.mtimeMs&&S.size===k.size){u.filesSkipped++;continue}let x=this.readRepoFile(w.path);if(x===null){u.filesSkipped++;continue}let v=As(x);if(S&&S.contentHash===v){await this.store.upsertFile({...S,mtimeMs:k.mtimeMs,indexedAt:n}),u.filesSkipped++;continue}let E=await this.parser.parse(w.path,x,w.language),N=new Map;for(let H of E.nodes)N.set(H.nodeKey,Jg(H));let F={path:w.path,language:w.language,contentHash:v,mtimeMs:k.mtimeMs,size:k.size,indexedAt:n};await p(),await this.store.replaceFileNodes(F,E.nodes,N,{contains:E.edges,refs:E.refs,imports:E.imports,exports:E.exports}),u.filesParsed++,t.onProgress?.({path:w.path,done:h,total:a.length})}let g=Jm(this.repoRoot),y=await this.store.getMeta(El)!==g.fingerprint;if(f||y||await this.store.getMeta(cr)==="1"){let w=ih(await this.store.getNameIndex()),k=new er(g.config,w.files),S=sh(await this.store.getAllFacts(),w,k);await this.store.replaceCrossFileEdges(S),await this.store.setMeta(El,g.fingerprint),await this.store.setMeta(cr,"0")}if(this.embedder&&t.embed){let w=await this.store.getNodesByKinds([...sc]),k=await this.store.getEmbeddingContentHashes(),S=[];for(let v of w){let E=Vm(v),N=As(`${this.embedder.recipeVersion}\0${E}`);k.get(v.nodeKey)!==N&&S.push({nodeKey:v.nodeKey,text:E,hash:N})}let x=64;for(let v=0;v<S.length;v+=x){let E=S.slice(v,v+x),N=await this.embedder.embedDocuments(E.map(H=>H.text));await this.store.upsertEmbeddings(E.map((H,P)=>({nodeKey:H.nodeKey,dim:this.embedder.dim,vec:N[P],contentHash:H.hash})));let F=Math.min(v+x,S.length);t.onProgress?.({path:"embedding symbols",done:F,total:S.length})}await this.store.pruneOrphanEmbeddings(),await this.store.setMeta(Gs,this.embedder.recipeVersion),await this.store.setMeta(Ws,this.embedder.model),await this.store.setMeta(Ks,String(this.embedder.dim))}await this.store.setMeta(Rt,At),await this.store.setMeta(ui,String(n));let b=Qr(this.repoRoot);return b&&await this.store.setMeta(ar,b),u.nodeCount=await this.store.countNodes(),u.edgeCount=await this.store.countEdges(),u.durationMs=(t.now??Date.now())-n,u}async status(){await this.store.init();let t=await this.store.countFiles(),n=await this.store.languageDistribution(),r={};for(let s of n)r[s.language]=s.count;let i=await this.store.getMeta(ui);return{indexed:t>0,fileCount:t,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),lastIndexedAt:i?Number(i):null,lastIndexCommit:await this.store.getMeta(ar),schemaVersion:await this.store.getMeta(Rt),languages:r}}async searchGraph(t,n={}){await this.store.init();let r=gn(n.limit,20,100),i=await this.store.searchFts(t,n.kind??null,r),s=[];for(let a of i){let c=await this.store.getNode(a.nodeKey);c&&s.push({...ey(c),score:a.score})}return s}async semanticQuery(t,n={}){if(await this.store.init(),!this.embedder)return[];let r=gn(n.limit,20,100),i=await this.embedder.embedQuery(t),a=(await this.store.allEmbeddings()).map(l=>({nodeKey:l.nodeKey,score:qm(i,l.vec)})).sort((l,d)=>d.score-l.score).slice(0,r),c=[];for(let l of a){let d=await this.store.getNode(l.nodeKey);d&&c.push({...ey(d),score:l.score})}return c}async tracePath(t,n={}){await this.store.init();let r=n.direction??"out",i=gn(n.maxDepth,3,5),s=gn(n.limit,100,1e3),a=n.kinds??null,c=[],l=new Set,d=new Set([t]),u=[t];for(let f=0;f<i&&u.length>0;f++){let p=[];for(let h of u){let g=await this.store.neighbors(h,r,a,s);for(let y of g){let b=`${y.srcKey} ${y.dstKey} ${y.kind}`;if(l.has(b))continue;if(l.add(b),c.push({srcKey:y.srcKey,dstKey:y.dstKey,kind:y.kind}),c.length>=s)return c;let w=r==="out"?y.dstKey:y.srcKey;d.has(w)||(d.add(w),p.push(w))}}u=p}return c}async getCodeSnippet(t){await this.store.init();let n=await this.store.getNode(t);if(!n)return null;let r="";try{r=Zg(Qg.join(this.repoRoot,n.filePath),"utf8").slice(n.startByte,n.endByte)}catch{return null}return{nodeKey:n.nodeKey,filePath:n.filePath,startLine:n.startLine,endLine:n.endLine,source:r}}async getArchitecture(t={}){await this.store.init();let n=await this.store.kindDistribution(),r=await this.store.languageDistribution(),i={};for(let a of n)i[a.kind]=a.count;let s={};for(let a of r)s[a.language]=a.count;return{fileCount:await this.store.countFiles(),nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),kindDistribution:i,languageDistribution:s,topModules:await this.store.topModulesByFanIn(gn(t.topN,10,50))}}async changedSymbols(t={}){await this.store.init();let n=hc(this.repoRoot,t);if(n===null)throw new Error("changedSymbols requires a git repository (change detection is git-based)");let r=gn(t.limit,64,200),i=[],s=0;for(let a of n){let c=await this.store.getNodesByFile(a.path);c.length>0&&s++,i.push(...c)}return i.sort((a,c)=>a.filePath.localeCompare(c.filePath)||a.startLine-c.startLine),{changedFiles:n.length,indexedFiles:s,symbols:i.slice(0,r),truncated:i.length>r}}async fileHistory(t={}){let n=t.paths??[];if(n.length===0){let r=Ts(this.repoRoot,{since:t.since});if(r===null)throw new Error("fileHistory requires a git repository (history is git-based)");n=[...r.keys()]}else if(Qr(this.repoRoot)===null)throw new Error("fileHistory requires a git repository (history is git-based)");return kh(this.repoRoot,n,t)}async checkDivergence(t={}){return ni(this.repoRoot,t)}async checkNumberCollisions(t={}){return un(this.repoRoot,t)}async checkNumberForPath(t,n={}){return fn(this.repoRoot,t,n)}async checkSpecDrift(t={}){return pn(this.repoRoot,t)}async reviewDetectors(t={}){return wl(this.repoRoot,t)}async reviewDetectorScopes(t={}){return vl(this.repoRoot,t)}async reviewChanges(t={}){await this.store.init();let n=Ts(this.repoRoot,t);if(n===null)throw new Error("reviewChanges requires a git repository (change detection is git-based)");let r=hh(this.repoRoot,t),i=r?.files??new Map,s=r?.coverage??"none",a=zg({paths:n,hunks:i,readUntracked:o(p=>this.readRepoFileHead(p,mh),"readUntracked")}),c=dh(n.keys()),l=gn(t.limit,64,t.attest?xt:200),d=[],u=0,f=0;for(let p of c){let h=await this.store.getNodesByFile(p.path);if(h.length===0)continue;u++;let g=await this.store.getFile(p.path),y=this.readRepoFile(p.path),b=g!==null&&y!==null&&As(y)!==g.contentHash;b&&(f++,s==="full"&&(s="partial"));let w=n.get(p.path)??"modified",k=i.get(p.path);for(let S of h)d.push(SR(S,w,k,b))}return d.sort((p,h)=>ty(p.change)-ty(h.change)||(p.filePath<h.filePath?-1:p.filePath>h.filePath?1:0)||p.startLine-h.startLine),{changedFiles:c.length,indexedFiles:u,staleFiles:f,symbols:d.slice(0,l),truncated:d.length>l,riskFlags:a,hunkCoverage:s,baseKind:t.since?"ref":"uncommitted",headSha:Qr(this.repoRoot),dirty:gc(this.repoRoot),baseSha:t.since?Rs(this.repoRoot,t.since):null,mergeBaseSha:t.since?mc(this.repoRoot,t.since):null}}async close(){await this.store.close()}readRepoFileHead(t,n){let r=this.readRepoFile(t);return r===null?null:r.slice(0,n)}readRepoFile(t){try{return Zg(Qg.join(this.repoRoot,t),"utf8")}catch{return null}}async wipe(){for(let t of await this.store.getAllFiles())await this.store.deleteFile(t.path)}};o(ey,"toHit");o(gn,"clampLimit");o(ty,"changeRank");o(SR,"classifyReviewSymbol")});var ny=_(()=>{"use strict";fe()});var ER,$W,ry=_(()=>{"use strict";fe();ER=["Accepted","Proposed","Superseded","Rejected","Deprecated","Angenommen","Akzeptiert","Vorschlag","Abgel\xF6st","Draft"],$W=new RegExp(ER.join("|"),"g")});import{existsSync as Il,readdirSync as TR,readFileSync as AR}from"node:fs";import{spawnSync as RR}from"node:child_process";import{dirname as CR,join as Vs,posix as Nl}from"node:path";function sy(e){let t=[],n={host:"127.0.0.1",port:e.config.source==="missing"?null:e.config.port,configSource:e.config.source,reachable:null,ledgerCount:null};if(e.config.source==="missing")return t.push({id:`db.config_missing:${e.dir}`,status:"open",project:e.dir,title:"supabase/config.toml nirgends auffindbar \u2014 DB-Ziel unbekannt",detail:`Weder dieser Tree noch der Haupt-Worktree tragen eine config.toml f\xFCr ${e.dir}. Die Supabase-CLI w\xFCrde hier still auf ihren Default-Port ${Ol} ausweichen \u2014 dorthin schreibt ein Werkzeug ohne Fehlermeldung, ggf. in die Datenbank eines FREMDEN Projekts (real passiert 2026-08-26: 'INSERT 0 1' in den falschen Ledger). Dieses Tool r\xE4t deshalb NIE einen Port und hat keine Verbindung versucht.`,hint:"config.toml aus dem Haupt-Checkout kopieren (sie ist bewusst gitignored \u2014 Ports/Keys sind lokal), dann erneut pr\xFCfen. `.maind/worktree-requirements` deklariert die Datei bereits f\xFCr check_divergence."}),{dir:e.dir,verdict:"blind",findings:t,db:n};e.config.source==="main_worktree"&&t.push({id:`db.config_missing_here:${e.dir}`,status:"open",project:e.dir,title:`config.toml fehlt in DIESEM Tree \u2014 Vergleich lief \xFCber den Haupt-Worktree (Port ${e.config.port})`,detail:`Der Ledger-Vergleich nutzt die config.toml des Haupt-Worktrees und ist damit aussagekr\xE4ftig. Aber jedes Supabase-CLI-Kommando, das HIER l\xE4uft, sieht keine config.toml und weicht still auf Port ${Ol} aus \u2014 die Silent-Redirect-Falle vom 2026-08-26.`,hint:"config.toml aus dem Haupt-Checkout in diesen Worktree kopieren, bevor irgendein `supabase \u2026`-Kommando l\xE4uft."});let r=e.ledger;if(r===null||r.ok===!1){n.reachable=r===null?null:!1;let f=r===null?"unreachable":r.reason,p=r!==null&&r.ok===!1?r.detail:void 0,g={psql_missing:{title:"psql nicht im PATH \u2014 Ledger nicht lesbar",detailText:"Ohne psql kann der lokale Ledger nicht gelesen werden. Kein Urteil \xFCber Drift m\xF6glich.",hint:"psql installieren (z. B. `brew install libpq` + PATH) oder den lokalen Stack-Client nachr\xFCsten."},unreachable:{title:`lokale Datenbank auf 127.0.0.1:${e.config.port} nicht erreichbar`,detailText:"Der Port aus config.toml antwortet nicht \u2014 der Stack schl\xE4ft vermutlich. Scheitert wenigstens laut (anders als die Default-Port-Falle); ein Urteil \xFCber Drift ist trotzdem nicht m\xF6glich.",hint:"`npx supabase start` im Projekt, dann erneut pr\xFCfen."},no_ledger:{title:`Port ${e.config.port} antwortet, tr\xE4gt aber KEINEN Supabase-Ledger`,detailText:"supabase_migrations.schema_migrations existiert dort nicht. Mutma\xDFlich lauscht auf diesem Port eine FREMDE Datenbank \u2014 dieselbe Verwechslungsklasse wie die 54322-Panne, nur von der anderen Seite gesehen.",hint:"Pr\xFCfen, wer auf dem Port lauscht (`lsof -nP -iTCP:<port> -sTCP:LISTEN`), und die config.toml gegen das Projekt halten."},query_failed:{title:"Ledger-Abfrage fehlgeschlagen",detailText:`Die SELECT-Abfrage gegen supabase_migrations.schema_migrations scheiterte${p?`: ${p}`:"."}`,hint:"psql-Fehlertext pr\xFCfen; das Tool liest ausschlie\xDFlich (SELECT) und r\xE4t nie einen anderen Port."}}[f];return t.push({id:`db.${f}:${e.dir}`,status:"warn",project:e.dir,title:g.title,detail:g.detailText,hint:g.hint}),{dir:e.dir,verdict:"blind",findings:t,db:n}}n.reachable=!0,n.ledgerCount=r.versions.length;let i=new Set(r.versions),s=new Set(e.fileVersions),a=e.fileVersions.filter(f=>!i.has(f)).sort(ot);a.length>0&&t.push({id:`ledger.behind:${e.dir}`,status:"open",project:e.dir,title:`lokales Schema hinter dem Repo \u2014 ${a.length} Migration(en) nicht angewandt`,detail:`Die verbundene Datenbank (127.0.0.1:${e.config.port}) kennt diese Repo-Migrationen nicht: ${a.join(", ")}. Jeder Lauf gegen dieses Schema pr\xFCft die Garantien von gestern; genau so wurde der SQL-Assertion-Gate zweimal still \xFCbersprungen (2026-08-26).`,hint:(e.projectRoot?`cd ${e.projectRoot} && npx supabase migration up`:"`npx supabase migration up` im Projektverzeichnis")+" (bzw. `--include-all` bei \xE4lteren Slots), dann erneut pr\xFCfen. Meldet der Lauf nichts Angewendetes, war es das falsche Verzeichnis ODER die Migration lief bereits \u2014 diese Pruefung sagt, was davon.",versions:a});let c=r.versions.filter(f=>!s.has(f)).sort(ot),l=new Map,d=[];for(let f of c){let p=e.siblingVersions.get(f);if(p){let h=l.get(p)??[];h.push(f),l.set(p,h)}else d.push(f)}for(let[f,p]of l)t.push({id:`ledger.sibling_wip:${e.dir}#${f}`,status:"info",project:e.dir,title:`${p.length} Ledger-Zeile(n) geh\xF6ren dem Geschwister-Worktree ${f}`,detail:`Angewandt, aber ohne Datei in DIESEM Tree: ${p.join(", ")}. Die Dateien liegen in ${f} \u2014 dessen WIP auf der geteilten lokalen Datenbank. Auf einer Maschine mit Feature-Branches ist das der erwartete Dauerzustand (local \u2287 trunk), kein Defekt und nichts zu reparieren.`,hint:"Nichts tun. Insbesondere KEIN `migration repair --status reverted` \u2014 das w\xFCrde die Arbeit der Parallel-Session un-verbuchen.",versions:p});if(d.length>0&&t.push({id:`ledger.phantom:${e.dir}`,status:"warn",project:e.dir,title:`${d.length} Ledger-Zeile(n) ohne Datei \u2014 nirgends, auch in keinem Worktree`,detail:`Angewandt laut Ledger, aber die Datei existiert weder hier noch in einem Geschwister-Worktree: ${d.join(", ")}. Entweder wurde eine angewandte Migration gel\xF6scht/umbenannt, oder der Ledger geh\xF6rt einem anderen Stand.`,hint:"Herkunft kl\xE4ren, bevor irgendetwas repariert wird \u2014 ein Repair auf Verdacht war die teurere H\xE4lfte der 2026-08-26-Panne.",versions:d}),e.remote!==null)if(e.remote.ok===!1)t.push({id:`remote.unreadable:${e.dir}`,status:"warn",project:e.dir,title:"Remote-Ledger nicht lesbar",detail:`Die \xFCbergebene Remote-Quelle war nicht abfragbar (${e.remote.reason}). NICHT als "kein Drift" werten.`,hint:"Connection-String/Netz pr\xFCfen; ohne Remote-Quelle bleibt der Remote-Vergleich aus (bewusst)."});else{let f=new Set(e.remote.versions),p=e.fileVersions.filter(g=>!f.has(g)).sort(ot),h=e.remote.versions.filter(g=>!s.has(g)).sort(ot);p.length>0&&t.push({id:`remote.behind:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger hinter dem Repo \u2014 ${p.length} Migration(en) nicht gepusht`,detail:`Im Repo, aber nicht im Remote-Ledger: ${p.join(", ")}.`,hint:"Push \xFCber den Push-Wrapper dieses Repos fahren (er protokolliert den Absender), nie roh.",versions:p}),h.length>0&&t.push({id:`remote.ahead:${e.dir}`,status:"warn",project:e.dir,title:`Remote-Ledger tr\xE4gt ${h.length} Version(en) ohne Datei im Repo`,detail:`Im Remote-Ledger, aber nicht im Repo: ${h.join(", ")}. Herkunft kl\xE4ren (Push an master vorbei?).`,hint:"Herkunft kl\xE4ren: wer hat diesen Stand in die Remote-DB gebracht? Ein Push-Log (falls vorhanden) nennt den Absender.",versions:h})}let u=t.some(f=>f.status==="open"||f.status==="warn")?"drift":"in_sync";return{dir:e.dir,verdict:u,findings:t,db:n}}function oy(e){return e.length===0?"no_opinion":e.includes("blind")?"blind":e.includes("drift")?"drift":"in_sync"}function cy(e,t){if(t==="enoent")return{ok:!1,reason:"psql_missing"};let n=e.toLowerCase();return n.includes("does not exist")&&n.includes("schema_migrations")?{ok:!1,reason:"no_ledger"}:n.includes("connection refused")||n.includes("could not connect")||n.includes("timeout expired")||n.includes("server closed the connection")||n.includes("connection timed out")?{ok:!1,reason:"unreachable"}:{ok:!1,reason:"query_failed",detail:e.split(`
131
+ `).filter(Boolean).slice(-1)[0]}}function iy(e,t,n){let r=e(t,IR,n);return r.ok===!1?cy(r.stderr,r.code):{ok:!0,versions:r.stdout.split(`
132
+ `).map(i=>i.trim()).filter(Boolean)}}function ly(e){for(let t of e.split(/^\[/m)){if(!/^db\]/.test(t))continue;let n=/^\s*port\s*=\s*(\d+)/m.exec(t.slice(t.indexOf("]")+1));if(n)return Number(n[1])}return null}function NR(e){let t=C(e,["rev-parse","--path-format=absolute","--git-common-dir"])?.trim();if(!t)return null;let n=CR(t);return n===e?null:n}function OR(e,t,n){let r=Nl.dirname(t),s=[{path:Vs(e,r,"config.toml"),source:"worktree"}],a=NR(e);a&&s.push({path:Vs(a,r,"config.toml"),source:"main_worktree"});for(let c of s)if(Il(c.path))try{let l=ly(AR(c.path,"utf8"));if(l===null){n.push(`${c.path}: kein [db].port lesbar \u2014 Kandidat \xFCbersprungen`);continue}return{source:c.source,port:l}}catch{n.push(`${c.path}: nicht lesbar \u2014 Kandidat \xFCbersprungen`)}return{source:"missing"}}function DR(e,t){let n=new Map,r=C(e,["worktree","list","--porcelain"]);if(r===null)return n;let i=C(e,["rev-parse","--show-toplevel"])?.trim();for(let s of r.split(`
133
+ `)){if(!s.startsWith("worktree "))continue;let a=s.slice(9).trim();if(!a||a===i||!Il(a))continue;let c=Vs(a,t);if(Il(c))try{for(let l of TR(c)){let d=nr(l);d!==null&&!n.has(d)&&n.set(d,a)}}catch{}}return n}function Dl(e,t={}){let n=t.runPsql??ay,r=t.timeoutMs??15e3,i=[],s=dn(e,t.dirs);if(s.length===0)return{ok:!1,verdict:"no_opinion",findings:[],facts:{projects:[],remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}};let a=[],c=[],l=[];for(let f of s){let p=OR(e,f.dir,i),h=p.source==="missing"?null:iy(n,`postgresql://postgres:postgres@127.0.0.1:${p.port}/postgres`,r),g=t.remoteDbUrl!==void 0?iy(n,t.remoteDbUrl,r):null,y=sy({dir:f.dir,projectRoot:Vs(e,Nl.dirname(Nl.dirname(f.dir))),fileVersions:f.files.map(b=>b.version),config:p,ledger:h,siblingVersions:DR(e,f.dir),remote:g});a.push(...y.findings),l.push(y.verdict),c.push({dir:f.dir,migrationCount:f.files.length,verdict:y.verdict,db:y.db})}let d=oy(l),u={open:0,warn:1,info:2};return a.sort((f,p)=>u[f.status]-u[p.status]||f.id.localeCompare(p.id)),{ok:d==="in_sync",verdict:d,findings:a,facts:{projects:c,remoteConsulted:t.remoteDbUrl!==void 0,skipped:i}}}var Ol,ay,IR,dy=_(()=>{"use strict";fe();ti();Ol=54322;o(sy,"evaluateLedgerProject");o(oy,"deriveLedgerVerdict");ay=o((e,t,n)=>{let r=RR("psql",[e,"-tAc",t],{encoding:"utf8",timeout:n,env:{...process.env,PGCONNECT_TIMEOUT:"5"}});return r.error&&r.error.code==="ENOENT"?{ok:!1,code:"enoent",stderr:""}:r.status!==0?{ok:!1,code:"error",stderr:(r.stderr??"").trim()}:{ok:!0,stdout:r.stdout??""}},"defaultRunPsql"),IR="select version from supabase_migrations.schema_migrations order by version";o(cy,"classifyLedgerError");o(iy,"readLedger");o(ly,"parseDbPort");o(NR,"mainWorktreeRoot");o(OR,"resolveConfig");o(DR,"gatherSiblingVersions");o(Dl,"checkMigrationLedgerDrift")});function Se(e){return typeof e=="string"?e:String(e??"")}function pi(e){return typeof e=="number"?e:Number(typeof e=="bigint"?e:e??0)}function Pl(e){return{nodeKey:Se(e.node_key),kind:Se(e.kind),name:Se(e.name),qualifiedName:Se(e.qualified_name),filePath:Se(e.file_path),startLine:pi(e.start_line),endLine:pi(e.end_line),signature:typeof e.signature=="string"?e.signature:null}}function py(e){return{path:Se(e.path),language:Se(e.language),contentHash:Se(e.content_hash),mtimeMs:pi(e.mtime_ms),size:pi(e.size),indexedAt:pi(e.indexed_at)}}function Ml(e){let t=new Map,n=o(i=>{let s=t.get(i);return s===void 0&&(s=e.prepare(i),t.set(i,s)),s},"stmt"),r=o(i=>{let s=n(Ct.meta).get(i);return s===void 0?null:Se(s.value)},"metaValue");return{meta(){let i=r(Rt),s=r(ui);return{schemaVersion:i,schemaCurrent:i===At,edgesDirty:r(cr)==="1",lastIndexedAt:s===null?null:Number(s)}},file(i){let s=n(Ct.file).get(i);return s===void 0?null:py(s)},files(i){let s=new Map;for(let a of new Set(i)){let c=n(Ct.file).get(a);c!==void 0&&s.set(a,py(c))}return s},symbolsInFile(i,s=PR){return n(Ct.symbolsInFile).all(i,s).map(Pl)},symbolsNamed(i,s=MR){let a=new Map;for(let c of new Set(i)){let l=n(Ct.symbolsNamed).all(c,s);l.length>0&&a.set(c,l.map(Pl))}return a},callersOfFile(i,s=$R){return n(Ct.callersOfFile).all(i,i,s).map(c=>({calleeKey:Se(c.callee_key),kind:Se(c.edge_kind),caller:Pl(c)}))},importersOf(i,s=LR){let a=n(Ct.importersOf).all(qe(i),s),c=[];for(let l of a){let d=Se(l.src_key),u=d.endsWith(fy)?d.slice(0,-fy.length):d;u!==i&&!c.includes(u)&&c.push(u)}return c},close(){e.close()}}}function mi(e,t){return Math.floor(t.mtimeMs)===e.mtimeMs&&t.size===e.size}var uy,Ct,PR,MR,$R,LR,fy,$l=_(()=>{"use strict";ln();lr();uy="node_key, kind, name, qualified_name, file_path, start_line, end_line, signature",Ct={meta:"SELECT key, value FROM meta WHERE key = ?",file:"SELECT path, language, content_hash, mtime_ms, size, indexed_at FROM files WHERE path = ?",symbolsInFile:`SELECT ${uy} FROM nodes WHERE file_path = ? AND kind <> 'module' ORDER BY start_line LIMIT ?`,symbolsNamed:`SELECT ${uy} FROM nodes WHERE name = ? AND kind <> 'module' ORDER BY file_path, start_line LIMIT ?`,callersOfFile:"SELECT e.dst_key AS callee_key, e.kind AS edge_kind, c.node_key, c.kind, c.name, c.qualified_name, c.file_path, c.start_line, c.end_line, c.signature FROM nodes n JOIN edges e ON e.dst_key = n.node_key AND e.kind IN ('calls', 'extends', 'implements') JOIN nodes c ON c.node_key = e.src_key WHERE n.file_path = ? AND c.file_path <> ? LIMIT ?",importersOf:"SELECT src_key FROM edges WHERE dst_key = ? AND kind = 'imports' LIMIT ?"},PR=400,MR=8,$R=600,LR=200,fy="#<module>";o(Se,"str");o(pi,"num");o(Pl,"toSymbol");o(py,"toFileRow");o(Ml,"createIndexReader");o(mi,"isFileCurrent")});var Ll,Fl=_(()=>{"use strict";Ll="0.2.0"});function jl(e,t){return{since:e??void 0,includeUncommitted:e?t:!0,limit:xt,attest:!0}}function Ul(e,t){let n=0,r=[];for(let s of e.symbols){let a=s.qualifiedName?s.qualifiedName:void 0;if(s.name.length===0||s.name.length>zs||a!==void 0&&a.length>qs){n+=1;continue}r.push({name:s.name,...a!==void 0?{qualified_name:a}:{},...s.kind&&s.kind.length<=hy?{kind:s.kind}:{},...s.language&&s.language.length<=gy?{language:s.language}:{},change:s.change,changed_line_count:Math.min(Math.max(0,s.changedLineCount),yy)})}return{payload:{changed_symbols:r,risk_flags:[...e.riskFlags],detector_findings:t.findings,detector_runs:t.engines.map(s=>({detector_id:s.detector_id,detector_version:s.detector_version,state:s.state})),diff_stats:{base_kind:e.baseKind,changed_file_count:e.changedFiles,stale_file_count:e.staleFiles,unindexed_file_count:e.changedFiles-e.indexedFiles,truncated:e.truncated||n>0,hunk_coverage:e.hunkCoverage,detector_coverage:t.coverage},...e.headSha?{commit_sha:e.headSha}:{},...e.baseSha?{base_sha:e.baseSha}:{},...typeof e.mergeBaseSha=="string"?{merge_base_sha:e.mergeBaseSha}:{},dirty:e.dirty,code_index_version:Ll},dropped:n}}function Hl(e,t,n){return e?{persist:!1,skipped:"no_report"}:n.headSha?t?n.baseKind==="ref"&&typeof n.mergeBaseSha!="string"?{persist:!1,skipped:"no_merge_base"}:{persist:!0,skipped:null}:{persist:!1,skipped:"no_project_key"}:{persist:!1,skipped:"no_head"}}function Bl(e,t,n){let r=t,i=[];r===0?i.push("No code_review conventions are visible to you \u2014 nothing was checked at convention level. This is an abstention, not a clean bill."):i.push(`Matched by the server (attest mode) against its full visible code_review set${typeof r=="number"?` (${r} convention(s))`:""} \u2014 ${e.symbols.length-n} changed symbol(s), no session filter, no cap.`),e.hunkCoverage!=="full"&&i.push(`Hunk coverage ${e.hunkCoverage}: some symbols could not be line-graded and count as co_located.`),e.staleFiles>0&&i.push(`${e.staleFiles} changed file(s) had a stale index \u2014 their symbols degraded to co_located.`);let s=e.changedFiles-e.indexedFiles;return s>0&&i.push(`${s} changed file(s) have no index rows \u2014 invisible to symbol matching (risk flags still cover them).`),e.truncated&&i.push(`Symbol list truncated at ${xt} (co_located dropped first) \u2014 not attestation-grade.`),n>0&&i.push(`${n} symbol(s) with a name beyond the server schema were left out \u2014 not attestation-grade.`),i.join(" ")}function Gl(e){let t=/^MCP error (-?\d+):\s*([\s\S]*)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=t[2]??"";return n===my&&/\bTool \S+ not found\b/.test(r)?{kind:"unknown_tool",code:n,detail:r,issues:[]}:n===my?{kind:"invalid_params",code:n,detail:r,issues:FR(r)}:{kind:"tool_error",code:n,detail:r,issues:[]}}function FR(e){let t=e.indexOf("[");if(t===-1)return[];try{let n=JSON.parse(e.slice(t));return Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null):[]}catch{return[]}}function Wl(e){if(e.kind!=="invalid_params"||e.issues.length!==1)return!1;let t=e.issues[0],n=t.path??[];return n.length===1&&n[0]==="findings"&&t.code==="invalid_type"&&(t.received===void 0||t.received==="undefined")}var zs,qs,hy,gy,yy,my,jR,_y=_(()=>{"use strict";qr();Fl();zs=200,qs=512,hy=64,gy=32,yy=1e4;o(jl,"attestReviewOptions");o(Ul,"buildAttestPayload");o(Hl,"attestPersistDecision");o(Bl,"attestCoverageNote");my=-32602;o(Gl,"classifyMcpErrorText");o(FR,"parseIssues");o(Wl,"isLegacyAttestRejection");jR=`MCP error -32602: Input validation error: Invalid arguments for tool review_verdict: ${JSON.stringify([{code:"invalid_type",expected:"array",received:"undefined",path:["findings"],message:"Required"}],null,2)}`});var It=_(()=>{"use strict";jf();Cl();bc();xl();fe();Fs();il();Xc();tl();Cc();ny();ry();xc();ii();Hs();ci();ti();Us();dy();Gc();kl();ii();ci();Hs();Us();ks();oc();lr();$l();Ss();Fl();_y()});import{execFileSync as UR}from"node:child_process";import{createHash as HR}from"node:crypto";import{mkdirSync as BR,readFileSync as GR,renameSync as WR,writeFileSync as KR}from"node:fs";import{dirname as by,join as wy}from"node:path";function ut(e=process.cwd()){try{let t=UR("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function dr(e){return HR("sha256").update(e).digest("hex").slice(0,16)}function Ys(e){return wy(e,VR)}function vy(e){return!!e&&typeof e.instructions=="string"&&e.instructions.trim().length>0}function ky(e,t,n,r=new Date().toISOString()){try{if(!vy(n))return;let i={version:Kl,cached_at:r,mcp_url:t.mcpUrl,key_fp:t.keyFp,result:n},s=Ys(e);BR(by(s),{recursive:!0}),Zr(by(s));let a=`${s}.${process.pid}.tmp`;KR(a,JSON.stringify(i,null,2),"utf8"),WR(a,s)}catch{}}function Js(e,t){try{let n=GR(Ys(e),"utf8"),r=JSON.parse(n);return r.version!==Kl||r.mcp_url!==t.mcpUrl||r.key_fp!==t.keyFp||typeof r.cached_at!="string"||!vy(r.result)?null:{version:Kl,cached_at:r.cached_at,mcp_url:r.mcp_url,key_fp:r.key_fp,result:r.result}}catch{return null}}function xy(e,t,n=new Date){let r=zR(t.cached_at,n),i=t.result.instructions??"",s={...t.result,instructions:`${r}
134
+
135
+ ${i}`};return JSON.stringify({jsonrpc:"2.0",id:e,result:s})}function zR(e,t){return`NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${qR(e,t)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`}function qR(e,t){let n=Date.parse(e);if(Number.isNaN(n))return"at an unknown time";let r=t.getTime()-n,i=Math.floor(r/6e4);if(i<1)return"just now";if(i<60)return`${i} minute${i===1?"":"s"} ago`;let s=Math.floor(i/60);if(s<24)return`${s} hour${s===1?"":"s"} ago`;let a=Math.floor(s/24);return`${a} day${a===1?"":"s"} ago`}var Kl,VR,Nt=_(()=>{"use strict";It();Kl=1,VR=wy(".maind","conventions-cache.json");o(ut,"resolveRepoRoot");o(dr,"keyFingerprint");o(Ys,"cachePath");o(vy,"hasInstructions");o(ky,"writeConventionsCache");o(Js,"readConventionsCache");o(xy,"buildCachedInitializeResponse");o(zR,"fallbackMarker");o(qR,"relativeAge")});import{existsSync as eo,mkdirSync as sC,readFileSync as Ty,writeFileSync as Jl,chmodSync as Ay}from"node:fs";import{homedir as oC,hostname as aC,platform as Yl,release as cC}from"node:os";import{randomUUID as lC}from"node:crypto";import{join as yn}from"node:path";function Le(){let e=oC(),t=process.env;if(Yl()==="darwin")return yn(e,"Library","Application Support","maind");if(Yl()==="win32"){let r=t.APPDATA&&t.APPDATA.length>0?t.APPDATA:yn(e,"AppData","Roaming");return yn(r,"maind")}let n=t.XDG_CONFIG_HOME&&t.XDG_CONFIG_HOME.length>0?t.XDG_CONFIG_HOME:yn(e,".config");return yn(n,"maind")}function Ry(e){eo(e)||sC(e,{recursive:!0,mode:448})}function re(){let e=Le();Ry(e);let t=yn(e,dC);if(eo(t)){let r=Ty(t,"utf8").trim();if(pC(r))return r}let n=lC();Jl(t,n+`
136
+ `,{encoding:"utf8",mode:384});try{Ay(t,384)}catch{}return n}function pC(e){return fC.test(e)}function Xl(){return yn(Le(),uC)}function _n(e){let t=Le();Ry(t);let n=Xl();Jl(n,e+`
137
+ `,{encoding:"utf8",mode:384});try{Ay(n,384)}catch{}}function Y(){let e=Xl();if(!eo(e))return null;let t=Ty(e,"utf8").trim();return t.length>0?t:null}function yi(){let e=Xl();eo(e)&&Jl(e,"",{encoding:"utf8",mode:384})}function Cy(){try{return`mcp-bridge-${aC()}`}catch{return"mcp-bridge"}}function to(e){return{os:`${Yl()} ${cC()}`,ide:"mcp-bridge",ext_version:e,device_id:re()}}var dC,uC,fC,ue=_(()=>{"use strict";o(Le,"configDir");o(Ry,"ensureDir");dC="device-id",uC="api-key";o(re,"ensureDeviceId");fC=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;o(pC,"isUuid");o(Xl,"apiKeyPath");o(_n,"writeApiKey");o(Y,"readApiKey");o(yi,"clearApiKey");o(Cy,"bridgeLabel");o(to,"clientMeta")});function _i(){let e=(process.env.MAIND_FUNCTIONS_ORIGIN??"").trim().replace(/\/+$/,"");return e.length>0?e:mC}function ur(e){return`${_i()}/${e.replace(/^\/+/,"")}`}var mC,fr=_(()=>{"use strict";mC="https://fn.maind.dev/functions/v1";o(_i,"functionsOrigin");o(ur,"functionsUrl")});import{mkdirSync as vC,readFileSync as kC,renameSync as xC,writeFileSync as SC}from"node:fs";import{join as EC}from"node:path";function Ny(e=Le()){return EC(e,AC)}function CC(e){return e.replace(/mnd_[a-f0-9]{8}_[a-f0-9]{56}/gi,"mnd_\u2026").slice(0,RC)}function bn(e,t,n){try{let r=n.dir??Le();vC(r,{recursive:!0,mode:448});let i={v:1,at:(n.now??new Date).toISOString(),outcome:e,detail:t===null?null:CC(t),bridge_version:n.version},s=Ny(r),a=`${s}.${process.pid}.tmp`;SC(a,JSON.stringify(i)+`
138
+ `,{encoding:"utf8",mode:384}),xC(a,s)}catch{}}function Oy(e=Le()){try{let t=JSON.parse(kC(Ny(e),"utf8"));return t.v!==1||typeof t.at!="string"||!TC.includes(t.outcome)?null:{v:1,at:t.at,outcome:t.outcome,detail:typeof t.detail=="string"?t.detail:null,bridge_version:typeof t.bridge_version=="string"?t.bridge_version:"?"}}catch{return null}}var TC,AC,RC,Zl=_(()=>{"use strict";ue();TC=["ok","paired","auth_failed","not_paired"],AC="connection-state.json",RC=200;o(Ny,"connectionStatePath");o(CC,"redactDetail");o(bn,"writeConnectionState");o(Oy,"readConnectionState")});var B,Fe=_(()=>{"use strict";B="0.90.0"});import{execFileSync as Dy}from"node:child_process";import{createHash as IC}from"node:crypto";function NC(e){return IC("sha256").update(e).digest("hex")}function OC(e){let t=e.trim();if(!t)return null;let n=/^[a-z][a-z0-9+.-]*:\/\//i.exec(t);if(n)t=t.slice(n[0].length),t=t.replace(/^[^@/]+@/,""),t=t.replace(/^([^/:]+):\d+(?=\/)/,"$1");else{t=t.replace(/^[^@/]+@/,"");let r=t.indexOf(":");r>=0&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`)}return t=t.replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase(),t.length>0?t:null}function mr(e){let t=OC(e);return t?NC(t):null}function J(){let e=process.env.MAIND_PROJECT_KEY?.trim().toLowerCase();if(e&&DC.test(e))return e;let t;try{t=Dy("git",["config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?mr(t):null}function no(e){let t;try{t=Dy("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}return t?mr(t):null}var DC,Ee=_(()=>{"use strict";o(NC,"sha256Hex");o(OC,"normalizeRemoteUrl");o(mr,"projectKeyFromRemote");DC=/^[a-f0-9]{64}$/;o(J,"computeProjectKey");o(no,"projectKeyForRepo")});import PC from"node:path";import{fileURLToPath as MC}from"node:url";function $C(e,t=PC.sep){return e.split(t).includes("_npx")}function Te(e){let t=e.extraArgs??[],n=o(r=>({command:"npx",args:["-y",My,...t],env:{},fallbackReason:r}),"npx");return e.entryPath===null?n("bridge entry path could not be resolved"):$C(e.entryPath,e.sep)?n("bridge is running from the npx cache (install it globally to pin a path)"):e.nodePath?{command:e.nodePath,args:[e.entryPath,...t],env:e.isElectron?{ELECTRON_RUN_AS_NODE:"1"}:{},fallbackReason:null}:n("node executable path unavailable")}function Ae(){try{let e=MC(import.meta.url);return e.endsWith(".js")?e:null}catch{return null}}function Ot(e){let t=Object.entries(e.env).map(([n,r])=>`${n}=${Py(r)}`);return[...t,e.command,...e.args].map((n,r)=>r<t.length?n:Py(n)).join(" ")}function ro(e){return/(^|\s)npx(\s|$)/.test(e)&&e.includes(My)}function io(e){return/(^|[\s/])maind-hook(\s|$)/.test(e)?!0:/claude-code-hook[/\\]build[/\\]/.test(e)}function Py(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var My,wn=_(()=>{"use strict";My="@maind-dev/mcp-bridge";o($C,"isEphemeralEntry");o(Te,"resolveBridgeLaunch");o(Ae,"currentBridgeEntry");o(Ot,"launchToShellCommand");o(ro,"isNpxForm");o(io,"isLegacyHookForm");o(Py,"shellQuote")});import*as K from"node:path";function $y(e){let t=e.launch??Te({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{command:t.command,args:t.args,env:{...t.env,MAIND_CLIENT_FAMILY:e.clientFamily,MAIND_MCP_URL:e.mcpUrl}}}function FC(e){switch(e.platform){case"darwin":return K.join(e.homeDir,"Library","Application Support","Claude","claude_desktop_config.json");case"win32":{let t=e.appData??K.join(e.homeDir,"AppData","Roaming");return K.join(t,"Claude","claude_desktop_config.json")}default:{let t=e.xdgConfigHome??K.join(e.homeDir,".config");return K.join(t,"Claude","claude_desktop_config.json")}}}function ed(e,t){switch(e.platform){case"darwin":return K.join(e.homeDir,"Library","Application Support",t);case"win32":{let n=e.appData??K.join(e.homeDir,"AppData","Roaming");return K.join(n,t)}default:{let n=e.xdgConfigHome??K.join(e.homeDir,".config");return K.join(n,t)}}}function jC(e){return K.join(ed(e,"Code"),"User")}function td(e,t){return{kind:"foreign-entries",dir:ed(e,t),ours:["User"]}}function Ly(e){return{evidence:[td(e,"Cursor"),{kind:"foreign-entries",dir:K.join(e.homeDir,".cursor"),ours:["mcp.json","hooks.json"]}],skipDetail:"Cursor not found (no Cursor app data, nothing of Cursor's in ~/.cursor)"}}function UC(e){return{evidence:[td(e,"Windsurf"),{kind:"foreign-entries",dir:K.join(e.homeDir,".codeium","windsurf"),ours:["mcp_config.json"]}],skipDetail:"Windsurf not found (no Windsurf app data, nothing of Windsurf's in ~/.codeium/windsurf)"}}function Fy(e){return e.clineDataDir?e.clineDataDir:K.join(e.clineDir??K.join(e.homeDir,".cline"),"data")}function BC(e){return e.clineMcpSettingsPath??K.join(Fy(e),"settings","cline_mcp_settings.json")}function GC(e){return{evidence:[{kind:"foreign-entries",dir:Fy(e),ours:["settings"]},...HC.map(t=>({kind:"dir",path:K.join(ed(e,t),"User","globalStorage","saoudrizwan.claude-dev")}))],skipDetail:"Cline not found (no Cline data in ~/.cline, no Cline storage in any editor)"}}function jy(e){return e.continueGlobalDir??K.join(e.homeDir,".continue")}function WC(e){return K.join(jy(e),"mcpServers","maind.json")}function KC(e){return{evidence:[{kind:"foreign-entries",dir:jy(e),ours:["mcpServers"]}],skipDetail:"Continue not found (nothing of Continue's in ~/.continue)"}}function VC(e){return K.join(jC(e),"mcp.json")}function bi(e){return[{key:"claude-code-project",label:"Claude Code (project-scoped .mcp.json)",clientFamilyEnv:"claude-code",scope:"project",path:K.join(e.projectRoot,".mcp.json"),kind:"json"},{key:"claude-code-user",label:"Claude Code (user-scoped ~/.claude.json)",clientFamilyEnv:"claude-code",scope:"user",path:K.join(e.homeDir,".claude.json"),kind:"json"},{key:"claude-desktop",label:"Claude Desktop",clientFamilyEnv:"claude-desktop",scope:"user",path:FC(e),kind:"json"},{key:"cursor",label:"Cursor (~/.cursor/mcp.json)",clientFamilyEnv:"cursor",scope:"user",path:K.join(e.homeDir,".cursor","mcp.json"),kind:"json",presence:Ly(e)},{key:"windsurf",label:"Windsurf (~/.codeium/windsurf/mcp_config.json)",clientFamilyEnv:"windsurf",scope:"user",path:K.join(e.homeDir,".codeium","windsurf","mcp_config.json"),kind:"json",presence:UC(e)},{key:"vscode-copilot",label:"GitHub Copilot (VS Code user mcp.json)",clientFamilyEnv:"copilot",scope:"user",path:VC(e),kind:"json",jsonShape:{serversKey:"servers",entryType:"stdio"},presence:{evidence:[td(e,"Code")],skipDetail:"VS Code not found (no VS Code app data)"}},{key:"cline",label:"Cline (~/.cline/data/settings/cline_mcp_settings.json)",clientFamilyEnv:"cline",scope:"user",path:BC(e),kind:"json",jsonShape:{serversKey:"mcpServers",clientKeys:{defaults:{disabled:!1},drop:["transport","type","transportType","url","headers"]}},presence:GC(e)},{key:"continue",label:"Continue (~/.continue/mcpServers/maind.json)",clientFamilyEnv:"continue",scope:"user",path:WC(e),kind:"json",presence:KC(e)},{key:"codex-cli",label:"Codex CLI (~/.codex/config.toml)",clientFamilyEnv:"codex",scope:"user",path:K.join(e.homeDir,".codex","config.toml"),kind:"toml"}]}function Uy(e,t){return t===null?e:e.filter(n=>n.clientFamilyEnv===t)}function Hy(e){return e.jsonShape??LC}function oo(e){return{projectRoot:e.projectRoot,homeDir:e.homeDir,platform:e.platform,xdgConfigHome:Ql(e.env.XDG_CONFIG_HOME),appData:Ql(e.env.APPDATA),clineDir:so(e.env.CLINE_DIR),clineDataDir:so(e.env.CLINE_DATA_DIR),clineMcpSettingsPath:so(e.env.CLINE_MCP_SETTINGS_PATH),continueGlobalDir:so(e.env.CONTINUE_GLOBAL_DIR)}}function Ql(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function so(e){let t=Ql(e);return t!==null&&K.isAbsolute(t)?t:null}var LC,HC,wi,hr=_(()=>{"use strict";wn();LC={serversKey:"mcpServers"};o($y,"buildMaindServerEntry");o(FC,"claudeDesktopConfigPath");o(ed,"editorAppDataDir");o(jC,"vsCodeUserDir");o(td,"editorRan");o(Ly,"cursorPresence");o(UC,"windsurfPresence");HC=["Code","Code - Insiders","Cursor","VSCodium","Windsurf","AgentComposer"];o(Fy,"clineDataDir");o(BC,"clineMcpSettingsPath");o(GC,"clinePresence");o(jy,"continueGlobalDir");o(WC,"continueMcpConfigPath");o(KC,"continuePresence");o(VC,"vsCodeUserMcpPath");o(bi,"getClientTargets");o(Uy,"filterTargetsByFamily");o(Hy,"jsonShapeOf");wi=[...new Set(bi({projectRoot:"/",homeDir:"/",platform:"linux",xdgConfigHome:null,appData:null}).map(e=>e.clientFamilyEnv))];o(oo,"makeDefaultContext");o(Ql,"nonEmpty");o(so,"absoluteOrNull")});import*as Wy from"node:fs/promises";import*as Dt from"node:path";import*as Ky from"node:readline";async function Vy(e){let t=Dt.resolve(e),n=t;for(;;){if(await zy(n))return n;let r=Dt.dirname(n);if(r===n)return t;n=r}}async function ao(e){let n=Dt.resolve(e),r=[];for(;;){await zy(n)&&r.push(n);let i=Dt.dirname(n);if(i===n)break;n=i}return r}async function zy(e){for(let t of qC)try{return await Wy.access(Dt.join(e,t)),!0}catch{}return!1}async function qy(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;process.stdout.write(`
139
139
  Multiple project roots found between cwd and the filesystem root:
140
140
  `),e.forEach((s,a)=>{process.stdout.write(` [${a+1}] ${s}
141
141
  `)}),process.stdout.write(`
142
- Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=$y.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(s=>{n.question("",a=>s(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
143
- `),null):e[i-1]}var NC,Yl=_(()=>{"use strict";NC=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];o(Ly,"detectProjectRoot");o(ro,"findAllProjectRoots");o(Fy,"hasAnyMarker");o(jy,"disambiguateProjectRoot")});import{existsSync as OC,readdirSync as DC}from"node:fs";import*as re from"node:fs/promises";import*as io from"node:path";async function Z(e){try{return await re.readFile(e,"utf8")}catch(t){if(PC(t))return null;throw t}}async function Jl(e){await re.mkdir(e,{recursive:!0})}async function V(e,t,n){let r=io.dirname(e);await Jl(r);let i=io.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await re.writeFile(i,t,{encoding:"utf8",mode:n});try{await re.rename(i,e)}catch(s){if(MC(s))try{await re.copyFile(i,e),await re.unlink(i).catch(()=>{}),n!==void 0&&await re.chmod(e,n).catch(()=>{});return}catch(a){throw await re.unlink(i).catch(()=>{}),a}throw await re.unlink(i).catch(()=>{}),s}}async function Uy(e,t){let n=await Z(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function PC(e){return Hy(e)&&e.code==="ENOENT"}function MC(e){return!Hy(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Hy(e){return typeof e=="object"&&e!==null&&"code"in e}var so,_e=_(()=>{"use strict";so={exists:o(e=>OC(e),"exists"),readdir:o(e=>{try{return DC(e)}catch{return null}},"readdir")};o(Z,"readFileSafe");o(Jl,"ensureDir");o(V,"atomicWriteFile");o(Uy,"hasLinePrefix");o(PC,"isNoEnt");o(MC,"isWindowsRenameFailure");o(Hy,"isNodeError")});function $C(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function LC(e,t){if(e.kind==="dir")return t.exists(e.path);let n=t.readdir(e.dir);return n===null?!1:n.some(r=>!$C(r)&&!e.ours.includes(r))}function Xl(e,t){return e.evidence.some(n=>LC(n,t))}function By(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||Xl(t.presence,r))return null;let i=r.exists(t.path);return{target:t.key,action:"merge",status:"skipped",detail:i?`${t.presence.skipDetail}; leftover file: maind-mcp-bridge doctor --remove-phantoms`:t.presence.skipDetail}}var Zl=_(()=>{"use strict";fr();o($C,"isNoise");o(LC,"evidenceHolds");o(Xl,"clientPresent");o(By,"presenceSkipRow")});function ZC(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}function QC(e){return`I want to add the **maind MCP server** to my AI coding agent.
142
+ Which one should receive the MCP config and preamble files? [1-${e.length}, default 1]: `);let n=Ky.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),r=await new Promise(s=>{n.question("",a=>s(a.trim()))});if(n.close(),r==="")return e[0];let i=Number.parseInt(r,10);return Number.isNaN(i)||i<1||i>e.length?(process.stdout.write(`Invalid selection "${r}", aborting. Re-run with --project-root <path>.
143
+ `),null):e[i-1]}var qC,nd=_(()=>{"use strict";qC=["package.json",".git","pyproject.toml","Cargo.toml","go.mod",".hg"];o(Vy,"detectProjectRoot");o(ao,"findAllProjectRoots");o(zy,"hasAnyMarker");o(qy,"disambiguateProjectRoot")});import{existsSync as YC,readdirSync as JC}from"node:fs";import*as ie from"node:fs/promises";import*as co from"node:path";async function Q(e){try{return await ie.readFile(e,"utf8")}catch(t){if(XC(t))return null;throw t}}async function rd(e){await ie.mkdir(e,{recursive:!0})}async function z(e,t,n){let r=co.dirname(e);await rd(r);let i=co.join(r,`.maind-install-${process.pid}-${Date.now()}.tmp`);await ie.writeFile(i,t,{encoding:"utf8",mode:n});try{await ie.rename(i,e)}catch(s){if(ZC(s))try{await ie.copyFile(i,e),await ie.unlink(i).catch(()=>{}),n!==void 0&&await ie.chmod(e,n).catch(()=>{});return}catch(a){throw await ie.unlink(i).catch(()=>{}),a}throw await ie.unlink(i).catch(()=>{}),s}}async function Yy(e,t){let n=await Q(e);return n===null?!1:n.split(/\r?\n/).some(i=>i.startsWith(t))}function XC(e){return Jy(e)&&e.code==="ENOENT"}function ZC(e){return!Jy(e)||process.platform!=="win32"?!1:e.code==="EEXIST"||e.code==="EPERM"||e.code==="EACCES"}function Jy(e){return typeof e=="object"&&e!==null&&"code"in e}var lo,_e=_(()=>{"use strict";lo={exists:o(e=>YC(e),"exists"),readdir:o(e=>{try{return JC(e)}catch{return null}},"readdir")};o(Q,"readFileSafe");o(rd,"ensureDir");o(z,"atomicWriteFile");o(Yy,"hasLinePrefix");o(XC,"isNoEnt");o(ZC,"isWindowsRenameFailure");o(Jy,"isNodeError")});function QC(e){return e===".DS_Store"||e==="Thumbs.db"||e==="desktop.ini"||e.startsWith(".maind-install-")}function eI(e,t){if(e.kind==="dir")return t.exists(e.path);let n=t.readdir(e.dir);return n===null?!1:n.some(r=>!QC(r)&&!e.ours.includes(r))}function id(e,t){return e.evidence.some(n=>eI(n,t))}function Xy(e){let{target:t,explicitFamily:n,probe:r}=e;if(t.presence===void 0||n===t.clientFamilyEnv||id(t.presence,r))return null;let i=r.exists(t.path);return{target:t.key,action:"merge",status:"skipped",detail:i?`${t.presence.skipDetail}; leftover file: maind-mcp-bridge doctor --remove-phantoms`:t.presence.skipDetail}}var sd=_(()=>{"use strict";hr();o(QC,"isNoise");o(eI,"evidenceHolds");o(id,"clientPresent");o(Xy,"presenceSkipRow")});function hI(e,t){let n=new URLSearchParams;t.stack&&t.stack.length>0&&n.set("stack",t.stack.join(",")),t.intent&&n.set("intent",t.intent),t.project&&n.set("project",t.project),t.verbosity&&n.set("verbosity",t.verbosity);let r=n.toString();return r?e.includes("?")?`${e}&${r}`:`${e}?${r}`:e}function gI(e){return`I want to add the **maind MCP server** to my AI coding agent.
144
144
 
145
145
  - My stack: \`__STACK__\`
146
146
  - MCP endpoint: \`${e}\`
@@ -372,7 +372,7 @@ written config.
372
372
 
373
373
  --- Preamble block ---
374
374
 
375
- ${hr}`}function xn(e,t,n,r={serversKey:"mcpServers"},i={}){let s=n?`
375
+ ${yr}`}function xn(e,t,n,r={serversKey:"mcpServers"},i={}){let s=n?`
376
376
  MAIND_CLIENT_FAMILY="${n}"`:"",a=n?' "$CONFIG_FILE" "$MAIND_MCP_URL" "$MAIND_CLIENT_FAMILY"':' "$CONFIG_FILE" "$MAIND_MCP_URL"',c=n?"if (clientFamily) server.env.MAIND_CLIENT_FAMILY = clientFamily;":"",l=r.entryType?`
377
377
  type: "${r.entryType}",`:"",d=i.keepClientKeys?`const previous = config[serversKey].maind;
378
378
  if (previous && typeof previous === "object") {
@@ -421,7 +421,7 @@ ${d}`:""}
421
421
  config[serversKey].maind = server;
422
422
  fs.writeFileSync(file, JSON.stringify(config, null, 2) + "\\n");
423
423
  console.log("WROTE " + file);
424
- NODE`}function eI(e){return`#!/usr/bin/env bash
424
+ NODE`}function yI(e){return`#!/usr/bin/env bash
425
425
  set -euo pipefail
426
426
 
427
427
  CONFIG_FILE="$HOME/.codex/config.toml"
@@ -474,7 +474,7 @@ if (serverCount !== 1 || envCount !== 1) {
474
474
 
475
475
  fs.writeFileSync(file, next.endsWith("\\n") ? next : next + "\\n");
476
476
  console.log("WROTE " + file);
477
- NODE`}function tI(e=ed){let t=`${e}${XC}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Windsurf, Codex, Copilot, Claude Desktop), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, cursor, windsurf, copilot, codex, claude-desktop.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:QC(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
477
+ NODE`}function _I(e=ad){let t=`${e}${mI}`;return[{id:"bridge-installer",label:"Quick setup",description:"One-shot installer. Runs browser pairing, merges the MCP-server entry into every supported AI-client config it finds (Claude Code, Cursor, Windsurf, Codex, Copilot, Claude Desktop), and writes the maind preamble block into CLAUDE.md / AGENTS.md / .cursorrules / .windsurfrules / .github/copilot-instructions.md. Idempotent \u2014 re-running is safe. Run from your project root.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install",extraVariants:[{label:"Non-interactive (CI / scripts)",description:"Skip every TTY prompt. Includes the SessionStart-hook merge into ~/.claude/settings.json \u2014 pass --no-hook to opt out. Useful for Docker, CI, and Dashboard-One-Click flows.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --full"},{label:"Filter to one client",description:"Install for a single client family instead of all detected ones. Replace `<family>` with one of claude-code, cursor, windsurf, copilot, codex, claude-desktop.",lang:"bash",template:"npx -y @maind-dev/mcp-bridge install --client <family>"}]},{id:"ai-prompt",label:"AI agent prompt (Power-User / Air-gapped fallback)",description:"Pre-installer fallback: paste this prompt into your AI agent (Claude Code, Copilot, Cursor, Codex, \u2026) and let it orchestrate the install manually. Use this when `npx` is restricted (corporate, air-gapped), when your workspace has a custom layout the auto-detect can't resolve, or when you want to see every config block before it's written. The Quick Setup tab above is the recommended path for most users.",lang:"markdown",template:gI(t)},{id:"claude-code-cli",label:"Claude Code",description:"Browser-pairing project config. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls with a stable device id. Replace `__STACK__` with your stack slugs.",filename:".mcp.json",lang:"json",template:`{
478
478
  "mcpServers": {
479
479
  "maind": {
480
480
  "command": "npx",
@@ -502,7 +502,7 @@ args = ["-y", "@maind-dev/mcp-bridge"]
502
502
 
503
503
  [mcp_servers.maind.env]
504
504
  MAIND_CLIENT_FAMILY = "codex"
505
- MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:eI(t)}]},{id:"copilot",label:"GitHub Copilot",description:'Browser-pairing workspace config for Copilot agent mode: `.vscode/mcp.json` in VS Code\'s own shape \u2014 `servers` (not `mcpServers`) with `"type": "stdio"`; VS Code ignores an `mcpServers` key silently. Uses `npx`, so the file carries no machine paths and can be committed for the whole team. The installer (`npx -y @maind-dev/mcp-bridge install --client copilot`) instead writes your personal user-profile mcp.json with absolute paths \u2014 same shape, one machine. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.',filename:".vscode/mcp.json",lang:"json",template:`{
505
+ MAIND_MCP_URL = "${t}"`,extraVariants:[{key:"bash-pairing",label:"Bash pairing",description:"Idempotent installer for ~/.codex/config.toml. It replaces only the maind MCP sections and lets the bridge create a fresh device-bound key via browser pairing on first launch.",filename:"install-maind-codex.sh",lang:"bash",template:yI(t)}]},{id:"copilot",label:"GitHub Copilot",description:'Browser-pairing workspace config for Copilot agent mode: `.vscode/mcp.json` in VS Code\'s own shape \u2014 `servers` (not `mcpServers`) with `"type": "stdio"`; VS Code ignores an `mcpServers` key silently. Uses `npx`, so the file carries no machine paths and can be committed for the whole team. The installer (`npx -y @maind-dev/mcp-bridge install --client copilot`) instead writes your personal user-profile mcp.json with absolute paths \u2014 same shape, one machine. On first launch, @maind-dev/mcp-bridge opens browser pairing, creates a fresh device-bound key, and forwards all MCP calls as GitHub Copilot. Replace `__STACK__` with your stack slugs.',filename:".vscode/mcp.json",lang:"json",template:`{
506
506
  "servers": {
507
507
  "maind": {
508
508
  "type": "stdio",
@@ -531,7 +531,7 @@ set -e
531
531
 
532
532
  read -r -d '' MAIND_BLOCK <<'MAIND_PREAMBLE_EOF' || true
533
533
 
534
- ${hr}
534
+ ${yr}
535
535
  MAIND_PREAMBLE_EOF
536
536
 
537
537
  mkdir -p .github
@@ -635,7 +635,7 @@ const tools = await mcp.getTools();
635
635
  "env": {
636
636
  "MAIND_MCP_URL": "${t}"
637
637
  }
638
- }`}]}var YC,JC,ed,XC,E2,hr,T2,zy=_(()=>{"use strict";YC="__STACK__",JC="__INTENT__",ed="https://mcp.maind.dev/mcp",XC=`?stack=${YC}&intent=${JC}`;o(ZC,"buildStackAwareEndpoint");E2=ZC(ed,{stack:["nextjs","supabase"],intent:"mixed"}),hr=`## maind MCP integration \u2014 Mandatory consultation
638
+ }`}]}var fI,pI,ad,mI,cV,yr,lV,n_=_(()=>{"use strict";fI="__STACK__",pI="__INTENT__",ad="https://mcp.maind.dev/mcp",mI=`?stack=${fI}&intent=${pI}`;o(hI,"buildStackAwareEndpoint");cV=hI(ad,{stack:["nextjs","supabase"],intent:"mixed"}),yr=`## maind MCP integration \u2014 Mandatory consultation
639
639
 
640
640
  This project uses the maind MCP server (mcp.maind.dev/mcp) as
641
641
  authoritative source for vetted coding conventions and lessons. The
@@ -704,31 +704,31 @@ For non-trivial changes, resolve documentation path in this order:
704
704
  If no path is discoverable, provide a guided fallback:
705
705
  \`docs/README.md\` + \`docs/adr/\` + \`docs/code/\` + \`docs/sessions/\`.
706
706
 
707
- Full tool set + provenance via \`get_conventions\`.`;o(QC,"buildAiPromptBody");o(xn,"buildJsonConfigInstaller");o(eI,"buildCodexTomlInstaller");o(tI,"buildSnippetTemplates");T2=tI(ed)});function nI(e){return`Project conventions \u2014 always-on policies served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on Codex session start, do not edit by hand.`}function ao(e,t){let n=e.replace(/\r\n/g,`
708
- `).trim(),{text:r}=rI(n,6e3);return[qy,nI(t),r,Yy].join(`
709
- `)}function rI(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
707
+ Full tool set + provenance via \`get_conventions\`.`;o(gI,"buildAiPromptBody");o(xn,"buildJsonConfigInstaller");o(yI,"buildCodexTomlInstaller");o(_I,"buildSnippetTemplates");lV=_I(ad)});function bI(e){return`Project conventions \u2014 always-on policies served by maind; updated ${e.date} by mcp-bridge ${e.bridgeVersion}. Managed block: the bridge rewrites it on Codex session start, do not edit by hand.`}function fo(e,t){let n=e.replace(/\r\n/g,`
708
+ `).trim(),{text:r}=wI(n,6e3);return[r_,bI(t),r,i_].join(`
709
+ `)}function wI(e,t){if(e.length<=t)return{text:e,dropped:0};let n=e.split(`
710
710
  `),r=o(a=>{let c=n.slice(a),l=c.filter(d=>/^- /.test(d)).length;return`\u2026 (${l>0?l:c.length} more via get_conventions)`},"tailFor"),i=[],s=0;for(let a=0;a<n.length;a++){let c=(i.length===0?0:1)+n[a].length,l=a+1<n.length?1+r(a+1).length:0;if(s+c+l>t){if(i.length===0){let u=r(1);i.push(n[0].slice(0,Math.max(0,t-u.length-1)))}let d=r(i.length);return{text:[...i,d].join(`
711
711
  `),dropped:n.length-i.length}}i.push(n[a]),s+=c}return{text:i.join(`
712
- `),dropped:0}}function Jy(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function co(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function lo(e,t,n){let r=e.includes(`\r
712
+ `),dropped:0}}function s_(e){return e.split(/\r?\n/).filter(t=>/^- /.test(t)).length}function po(e,t){return e.split(/\r?\n/).some(n=>n.startsWith(t))}function mo(e,t,n){let r=e.includes(`\r
713
713
  `)?`\r
714
714
  `:`
715
715
  `,i=e.split(r),s=t.split(`
716
- `),a=i.findIndex(g=>g.trim()===qy);if(a>=0){let g=i.findIndex((w,x)=>x>a&&w.trim()===Yy);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(a,g+1);if(iI(y,s))return{next:e,changed:!1,outcome:"unchanged"};let b=[...i.slice(0,a),...s,...i.slice(g+1)].join(r);return{next:b,changed:b!==e,outcome:"replaced"}}let c=i.findIndex(g=>g.startsWith(n));if(c<0)return{next:e,changed:!1,outcome:"no-header"};let l=i.length,d=!1;for(let g=c+1;g<i.length;g++){if(/^\s{0,3}(```|~~~)/.test(i[g])){d=!d;continue}if(!d&&/^#{1,2}\s/.test(i[g])){l=g;break}}let u=l-1;for(;u>c&&i[u].trim()==="";)u--;let p=i.slice(0,u+1),f=i.slice(u+1),h=[...p,"",...s];return l===i.length?h.push(...f.length===0?[""]:f):((f.length===0||f[0].trim()!=="")&&h.push(""),h.push(...f)),{next:h.join(r),changed:!0,outcome:"inserted"}}function iI(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(n!==1&&e[n].replace(/\r$/,"")!==t[n])return!1;return!0}var qy,Yy,td=_(()=>{"use strict";qy="<!-- maind:conventions v1 begin -->",Yy="<!-- maind:conventions v1 end -->";o(nI,"renderConventionsLead");o(ao,"renderConventionsBlock");o(rI,"capAtLineBoundary");o(Jy,"countConventions");o(co,"hasMaindSection");o(lo,"upsertConventionsBlock");o(iI,"sameConventions")});import*as Ye from"node:path";function sI(e){return[{key:"preamble:CLAUDE.md",path:Ye.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Ye.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Ye.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Ye.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Ye.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Ye.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function Xy(e,t=!1){let n=sI(e),r=[];for(let i of n)r.push(await aI(i,t));return e.conventions!==void 0&&r.push(await oI(e,t)),r}async function oI(e,t){let n=Ye.join(e.projectRoot,"AGENTS.md"),r=o(i=>({target:uo,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let s=await Z(n)??(t?`${hr}
717
- `:null);if(s===null||!co(s,Sn))return r("skipped (no maind header in AGENTS.md)");let a=await e.conventions();if(a===null||a.trim().length===0)return r("skipped (no conventions yet)");let c=ao(a,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??B}),l=lo(s,c,Sn);switch(l.outcome){case"unchanged":return r("unchanged");case"no-header":return r("skipped (no maind header in AGENTS.md)");case"damaged":return r("skipped (begin marker without end marker \u2014 remove the <!-- maind:conventions --> lines)");case"inserted":case"replaced":{let d=l.outcome==="inserted"?"insert":"refresh";return t?{target:uo,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await V(n,l.next),{target:uo,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let s=i instanceof Error?i.message:String(i);return{target:uo,action:"upsert",status:"failed",detail:`conventions block: ${s}`}}}async function aI(e,t){try{if(e.mayNeedParentDir&&!t&&await Jl(Ye.dirname(e.path)),await Uy(e.path,Sn))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await Z(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${hr}
718
- `:cI(r)+`${hr}
719
- `;return await V(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}function cI(e){return e.endsWith(`
716
+ `),a=i.findIndex(g=>g.trim()===r_);if(a>=0){let g=i.findIndex((w,k)=>k>a&&w.trim()===i_);if(g<0)return{next:e,changed:!1,outcome:"damaged"};let y=i.slice(a,g+1);if(vI(y,s))return{next:e,changed:!1,outcome:"unchanged"};let b=[...i.slice(0,a),...s,...i.slice(g+1)].join(r);return{next:b,changed:b!==e,outcome:"replaced"}}let c=i.findIndex(g=>g.startsWith(n));if(c<0)return{next:e,changed:!1,outcome:"no-header"};let l=i.length,d=!1;for(let g=c+1;g<i.length;g++){if(/^\s{0,3}(```|~~~)/.test(i[g])){d=!d;continue}if(!d&&/^#{1,2}\s/.test(i[g])){l=g;break}}let u=l-1;for(;u>c&&i[u].trim()==="";)u--;let f=i.slice(0,u+1),p=i.slice(u+1),h=[...f,"",...s];return l===i.length?h.push(...p.length===0?[""]:p):((p.length===0||p[0].trim()!=="")&&h.push(""),h.push(...p)),{next:h.join(r),changed:!0,outcome:"inserted"}}function vI(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(n!==1&&e[n].replace(/\r$/,"")!==t[n])return!1;return!0}var r_,i_,cd=_(()=>{"use strict";r_="<!-- maind:conventions v1 begin -->",i_="<!-- maind:conventions v1 end -->";o(bI,"renderConventionsLead");o(fo,"renderConventionsBlock");o(wI,"capAtLineBoundary");o(s_,"countConventions");o(po,"hasMaindSection");o(mo,"upsertConventionsBlock");o(vI,"sameConventions")});import*as Xe from"node:path";function kI(e){return[{key:"preamble:CLAUDE.md",path:Xe.join(e.projectRoot,"CLAUDE.md"),mayNeedParentDir:!1},{key:"preamble:AGENTS.md",path:Xe.join(e.projectRoot,"AGENTS.md"),mayNeedParentDir:!1},{key:"preamble:.github/copilot-instructions.md",path:Xe.join(e.projectRoot,".github","copilot-instructions.md"),mayNeedParentDir:!0},{key:"preamble:.cursorrules",path:Xe.join(e.projectRoot,".cursorrules"),mayNeedParentDir:!1},{key:"preamble:.windsurfrules",path:Xe.join(e.projectRoot,".windsurfrules"),mayNeedParentDir:!1},{key:"preamble:~/.claude/maind-session-start-reminder.md",path:Xe.join(e.homeDir,".claude","maind-session-start-reminder.md"),mayNeedParentDir:!0}]}async function o_(e,t=!1){let n=kI(e),r=[];for(let i of n)r.push(await SI(i,t));return e.conventions!==void 0&&r.push(await xI(e,t)),r}async function xI(e,t){let n=Xe.join(e.projectRoot,"AGENTS.md"),r=o(i=>({target:ho,action:"upsert",status:"skipped",detail:`conventions block: ${i}`}),"skip");try{let s=await Q(n)??(t?`${yr}
717
+ `:null);if(s===null||!po(s,Sn))return r("skipped (no maind header in AGENTS.md)");let a=await e.conventions();if(a===null||a.trim().length===0)return r("skipped (no conventions yet)");let c=fo(a,{date:new Date().toISOString().slice(0,10),bridgeVersion:e.bridgeVersion??B}),l=mo(s,c,Sn);switch(l.outcome){case"unchanged":return r("unchanged");case"no-header":return r("skipped (no maind header in AGENTS.md)");case"damaged":return r("skipped (begin marker without end marker \u2014 remove the <!-- maind:conventions --> lines)");case"inserted":case"replaced":{let d=l.outcome==="inserted"?"insert":"refresh";return t?{target:ho,action:"upsert",status:"would-merge",detail:`conventions block: would ${d}`}:(await z(n,l.next),{target:ho,action:"upsert",status:"merged",detail:`conventions block: ${d==="insert"?"inserted":"refreshed"}`})}}}catch(i){let s=i instanceof Error?i.message:String(i);return{target:ho,action:"upsert",status:"failed",detail:`conventions block: ${s}`}}}async function SI(e,t){try{if(e.mayNeedParentDir&&!t&&await rd(Xe.dirname(e.path)),await Yy(e.path,Sn))return{target:e.key,action:"skip",status:"skipped",detail:"## maind MCP integration header already present"};let r=await Q(e.path);if(t)return{target:e.key,action:r===null?"write":"append",status:r===null?"would-create":"would-merge",detail:e.path};let i=r===null||r.length===0?`${yr}
718
+ `:EI(r)+`${yr}
719
+ `;return await z(e.path,i),{target:e.key,action:r===null?"write":"append",status:r===null?"created":"merged",detail:e.path}}catch(n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"append",status:"failed",detail:r}}}function EI(e){return e.endsWith(`
720
720
 
721
721
  `)?e:e.endsWith(`
722
722
  `)?e+`
723
723
  `:e+`
724
724
 
725
- `}var Sn,uo,nd=_(()=>{"use strict";zy();Le();td();_e();Sn="## maind MCP integration",uo="preamble:AGENTS.md#conventions";o(sI,"buildPreambleTargets");o(Xy,"writePreambleFiles");o(oI,"writeAgentsMdConventionsBlock");o(aI,"writeOnePreambleFile");o(cI,"ensureTrailingBlankLine")});import{existsSync as lI}from"node:fs";import*as Zy from"node:path";function Re(e,t={},n=Pt){let r=t.fileExists??lI,i=t.expectedCommand??dI,s={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);rd(a)&&(s=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=uI(s,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(a.subcommand)}`;if(eo(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(Qs(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=pI(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function id(e){return e.some(t=>t.status!=="ok")}function po(e){return e.some(t=>t.remedy==="run-install")}function dI(e){return Ot(Ee({entryPath:Te(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function uI(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!rd(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!rd(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function pI(e){for(let t of fI(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return Zy.isAbsolute(t)?t:null;return null}function fI(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Je,Pt,gr,Mt=_(()=>{"use strict";wn();Je="on-session-briefing",Pt=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"SessionStart",subcommand:Je,label:"SessionStart briefing hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-briefing' when a session starts (and again after a compaction) and adds your maind session briefing to the session context \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 kept under Claude Code's 10,000-character hook limit so it arrives whole. This is delivery, not enforcement: it never blocks anything, and it works with the guard pack off. UNLIKE the other core hooks it talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, project key and the client family 'claude-code' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call; it keeps a per-session marker and a one-line log entry under ~/.maind/guard/. When the guard pack's guard-inject is wired too, that one stays silent, so the briefing arrives once."},{event:"UserPromptSubmit",subcommand:"on-prompt-context",label:"UserPromptSubmit context hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-prompt-context' each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against two local sources: the project conventions MAIND already cached here (.maind/conventions-cache.json, or the session-briefing cache ~/.maind/guard/briefing-cache.json) and the symbol NAMES in this repository's local code index (.maind/code-index.sqlite \u2014 index rows only, never file contents). When something matches, it adds at most ~2,000 characters for the model: the matching conventions, and the file:line of symbols the prompt names. The prompt is never uploaded, stored or logged; nothing leaves the machine, and no network call is made. Each convention and symbol is mentioned at most once per session (an empty marker file per item under ~/.maind/context/). It never blocks or rewrites a prompt."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PreToolUse",subcommand:"on-read-context",label:"PreToolUse read-context hook",timeout:5,matcher:"Read",consentDescription:"It runs 'maind-mcp-bridge on-read-context' before the Read tool opens a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents \u2014 and looks it up in this repository's local code index (.maind/code-index.sqlite): symbol names, kinds, line spans, each symbol's stored first declaration line, and the import-resolved call graph. Only if the index still matches that file on disk does it add at most ~1,500 characters for the model: which symbols other files call and from where, which files import it, and \u2014 when the Read covers only part of the file \u2014 an outline of the rest. A file the index does not cover, or one changed since it was indexed, gets nothing. Runs entirely on this machine; no network call, nothing is uploaded; at most once per file per session (an empty marker file under ~/.maind/context/). It never blocks a Read."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],gr=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off, and while the core on-session-briefing hook is wired \u2014 that one delivers the same briefing, guard or no guard."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. With the guard-difficulty hook also installed (ADR-360), block mode may in addition deny edits during an open difficulty episode until a maind consultation happens \u2014 reading only that hook's local log. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."},{event:"PostToolUseFailure",subcommand:"guard-difficulty",label:"Guard difficulty hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-difficulty' after a tool call FAILS (ADR-360). For Bash and for MCP tools other than maind's own it reads the tool NAME and, for Bash, the PROGRAM and subcommand of the command line (e.g. `pnpm test`) \u2014 never paths, flags, values, the error text or any output \u2014 and appends one line (time, 'fail', that program name) to a local per-session log in ~/.maind/guard/triggers/. File tools, lookups such as grep or ls, interrupts you caused and subagent calls are not counted. When four failed attempts follow each other without a ten-minute pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key like guard-inject \u2014 never tool data \u2014 and, if conv_consult_on_difficulty is on for you, adds ONE hint for the model to consult maind before the next attempt. Only in block mode ('guard mode block') and only if that convention is required does the gate hook then deny edits until a consultation happens (override: 'guard skip --kind difficulty'). Off on this machine: 'guard difficulty off'; off everywhere: switch the convention off in your maind settings. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-outcome",label:"Guard outcome hook",timeout:10,matcher:"Bash|mcp__.*",consentDescription:"It runs 'maind-mcp-bridge guard-outcome' after a Bash or MCP tool call SUCCEEDS (ADR-360). Test and build runs often end with exit code 0 because their output is piped through `tail` or `grep`, so for Bash it reads the LAST 8 KB of stdout/stderr on this machine to recognise a failure summary (e.g. '2 failed', 'error TS2322', 'ELIFECYCLE') and then discards it \u2014 no output is stored or sent. It writes the same kind of line as guard-difficulty (time, fail or ok, a program name such as `pnpm test`), and an 'ok' only for a program that already failed in this session: that is how a fixed problem is recognised. The log stays in ~/.maind/guard/triggers/; nothing leaves the machine. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-capture",label:"Guard capture hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-capture' when a turn ends (ADR-360). Only after a hard-won fix recorded by the guard-difficulty and guard-outcome hooks \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it holds the end of the turn ONCE per episode with a reason asking the agent to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'; off everywhere: the convention switch. Inactive while guard mode is off."}];o(Re,"inspectHookWiring");o(id,"hasWiringDrift");o(po,"needsInstallRun");o(dI,"defaultExpectedCommand");o(uI,"findCommand");o(pI,"extractScriptPath");o(fI,"tokenize");o(rd,"isObject")});import{existsSync as mI,readFileSync as hI}from"node:fs";import{join as gI}from"node:path";function je(){return gI($e(),"config.json")}function Ce(){try{let e=je();if(!mI(e))return null;let t=JSON.parse(hI(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),typeof n.guard_difficulty=="boolean"&&(r.guard_difficulty=n.guard_difficulty),typeof n.guard_capture=="boolean"&&(r.guard_capture=n.guard_capture),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),Array.isArray(n.declined_hooks)&&(r.declined_hooks=n.declined_hooks.filter(i=>typeof i=="string")),r}catch{return null}}var $t=_(()=>{"use strict";ue();o(je,"bridgeConfigPath");o(Ce,"readBridgeConfig")});function yI(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===sd?r.add(a.subcommand):(l.status==="created"||l.status==="merged"||l.status==="skipped"&&l.detail!==void 0&&/already runs maind /.test(l.detail))&&r.delete(a.subcommand))});let i=[...r].sort();return i.length===e.length&&i.every(a=>e.includes(a))?null:i}async function od(e,t,n=je()){try{let r={},i=await Z(n);if(i!==null&&i.trim().length>0){let l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let s=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=yI(s,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await V(n,JSON.stringify(c,null,2)+`
726
- `,384)}catch{}}var sd,ad=_(()=>{"use strict";$t();_e();sd="user declined";o(yI,"nextDeclinedHooks");o(od,"recordHookDecisions")});import*as dd from"node:path";import*as e_ from"node:readline";async function t_(e,t){let n=dd.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await Z(n)}catch(f){return{target:r,action:"merge",status:"failed",detail:`read: ${cd(f)}`}}let s,a="create";if(i===null||i.trim().length===0)s={};else{a="merge";try{let f=JSON.parse(i);if(!ld(f))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};s=f}catch(f){return{target:r,action:"merge",status:"failed",detail:`parse: ${cd(f)}`}}}let c=bI(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await(e.prompt??wI)(e.out,`
725
+ `}var Sn,ho,ld=_(()=>{"use strict";n_();Fe();cd();_e();Sn="## maind MCP integration",ho="preamble:AGENTS.md#conventions";o(kI,"buildPreambleTargets");o(o_,"writePreambleFiles");o(xI,"writeAgentsMdConventionsBlock");o(SI,"writeOnePreambleFile");o(EI,"ensureTrailingBlankLine")});import{existsSync as TI}from"node:fs";import*as a_ from"node:path";function Ce(e,t={},n=Pt){let r=t.fileExists??TI,i=t.expectedCommand??AI,s={};if(e!==null&&e.trim().length>0)try{let a=JSON.parse(e);dd(a)&&(s=a)}catch{}return n.map(a=>{let c={event:a.event,subcommand:a.subcommand},l=RI(s,a.event,a.subcommand);if(l===null)return{...c,status:"missing",command:null,remedy:"run-install",detail:`${a.label} is not wired \u2014 this bridge can run '${a.subcommand}', but nothing calls it.`};let d=` Replace its command with: ${i(a.subcommand)}`;if(io(l))return{...c,status:"legacy",command:l,remedy:"edit-command",detail:`${a.label} still runs the retired @maind/claude-code-hook, which was folded into the bridge and is not published.`+d};if(ro(l))return{...c,status:"npx",command:l,remedy:"edit-command",detail:`${a.label} runs through 'npx' \u2014 PATH and npm's per-Node-version globals decide which bridge that is.`+d};let u=CI(l);return u!==null&&!r(u)?{...c,status:"broken",command:l,remedy:"edit-command",detail:`${a.label} points at ${u}, which does not exist \u2014 the hook fails silently on every run.`+d}:{...c,status:"ok",command:l,remedy:"none",detail:`${a.label} is wired.`}})}function ud(e){return e.some(t=>t.status!=="ok")}function go(e){return e.some(t=>t.remedy==="run-install")}function AI(e){return Ot(Te({entryPath:Ae(),nodePath:process.execPath,extraArgs:[e],isElectron:process.versions.electron!==void 0}))}function RI(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!dd(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!dd(a))continue;let c=a.command;if(typeof c=="string"&&c.includes(n))return c}}return null}function CI(e){for(let t of II(e))if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return a_.isAbsolute(t)?t:null;return null}function II(e){let t=[],n="",r=!1;for(let i of e){if(i==="'"){r=!r;continue}if(!r&&/\s/.test(i)){n.length>0&&t.push(n),n="";continue}n+=i}return n.length>0&&t.push(n),t}function dd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ze,Pt,_r,Mt=_(()=>{"use strict";wn();Ze="on-session-briefing",Pt=[{event:"SessionStart",subcommand:"on-session-start",label:"SessionStart hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."},{event:"SessionStart",subcommand:Ze,label:"SessionStart briefing hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-briefing' when a session starts (and again after a compaction) and adds your maind session briefing to the session context \u2014 the project conventions first, then your top lessons, skills and memory titles \u2014 kept under Claude Code's 10,000-character hook limit so it arrives whole. This is delivery, not enforcement: it never blocks anything, and it works with the guard pack off. UNLIKE the other core hooks it talks to the maind server: it fetches the briefing from mcp.maind.dev, sending your API key, device id, project key and the client family 'claude-code' \u2014 never file contents, never paths. Cache-first (~12h, ~/.maind/guard/briefing-cache.json), so most session starts add no network call; it keeps a per-session marker and a one-line log entry under ~/.maind/guard/. When the guard pack's guard-inject is wired too, that one stays silent, so the briefing arrives once."},{event:"UserPromptSubmit",subcommand:"on-prompt-context",label:"UserPromptSubmit context hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-prompt-context' each time you submit a prompt. It reads the PROMPT TEXT on this machine only and matches it against two local sources: the project conventions MAIND already cached here (.maind/conventions-cache.json, or the session-briefing cache ~/.maind/guard/briefing-cache.json) and the symbol NAMES in this repository's local code index (.maind/code-index.sqlite \u2014 index rows only, never file contents). When something matches, it adds at most ~2,000 characters for the model: the matching conventions, and the file:line of symbols the prompt names. The prompt is never uploaded, stored or logged; nothing leaves the machine, and no network call is made. Each convention and symbol is mentioned at most once per session (an empty marker file per item under ~/.maind/context/). It never blocks or rewrites a prompt."},{event:"PreToolUse",subcommand:"on-tool-use",label:"PreToolUse hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."},{event:"PreToolUse",subcommand:"on-file-write",label:"PreToolUse write-guard hook",timeout:5,matcher:"Write",consentDescription:"It runs 'maind-mcp-bridge on-file-write' before the Write tool creates a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents, never any other tool's arguments \u2014 to check whether a numbered filename (ADR-262-\u2026, 0001-\u2026, RFC-12-\u2026) would claim a number a sibling branch or worktree already holds, and blocks that one Write while naming the next free number (ADR-263). Runs entirely on this machine (git + fs); nothing is uploaded. This is a SEPARATE hook from on-tool-use precisely because it reads an argument, which that one promises not to."},{event:"PreToolUse",subcommand:"on-file-edit",label:"PreToolUse edit-guard hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-file-edit' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares it LOCALLY against the cached peer view from this machine's own presence announces (~/.maind/presence/): when another of your sessions holds a claim or works on the same directory, it INFORMS the agent with who/where/how-fresh. The path never leaves the machine; the hook never blocks a tool call (advisory only, ADR-277). This is a SEPARATE hook from on-file-write because that one's consent covers Write alone and may deny; this one covers Edit+Write and never does."},{event:"PreToolUse",subcommand:"on-repo-health",label:"PreToolUse repo-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-repo-health' before the Edit and Write tools, and before those only \u2014 at most ONCE per session and repository, not on every call. It reads the target file PATH (never the file's contents) to find which repository you are editing, then inspects THAT repository with git and the filesystem: is a machine-local tooling file present in the main checkout but missing in this worktree, were dependencies never installed here, is a build older than its source, are you mid-rebase, on a detached HEAD, editing the shared base tree, or are checked-in git hooks not actually wired? Everything stays on this machine; no network call, and no file contents are read or stored. It only ever adds a note for the model and NEVER blocks a tool call. Separately consented from the other Edit/Write hooks because it inspects the repository, not just the path."},{event:"PreToolUse",subcommand:"on-read-context",label:"PreToolUse read-context hook",timeout:5,matcher:"Read",consentDescription:"It runs 'maind-mcp-bridge on-read-context' before the Read tool opens a file, and before that tool only. It reads the target file PATH \u2014 never the file's contents \u2014 and looks it up in this repository's local code index (.maind/code-index.sqlite): symbol names, kinds, line spans, each symbol's stored first declaration line, and the import-resolved call graph. Only if the index still matches that file on disk does it add at most ~1,500 characters for the model: which symbols other files call and from where, which files import it, and \u2014 when the Read covers only part of the file \u2014 an outline of the rest. A file the index does not cover, or one changed since it was indexed, gets nothing. Runs entirely on this machine; no network call, nothing is uploaded; at most once per file per session (an empty marker file under ~/.maind/context/). It never blocks a Read."},{event:"PostToolUse",subcommand:"on-write-health",label:"PostToolUse write-health hook",timeout:10,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge on-write-health' AFTER the Edit and Write tools, and after those only. It reads the target file PATH to decide which checks that path makes relevant, and then \u2014 this is the wider promise, which is why it is consented separately \u2014 READS THE REPOSITORY'S TRACKED SOURCE FILES FROM DISK to run them: is a registry still consistent with the design artefact it implements (only if this repo declares such a contract in .maind/spec-contracts.json), does a Tailwind class point at a theme token that does not exist (only if this repo declares theme tokens), does a new Supabase migration leave default grants in place (only if this repo has migrations). A repository without those things stays silent. File contents are read, parsed and discarded; nothing is stored and nothing is uploaded. Each finding is reported to the model at most ONCE per session, only for findings THIS branch introduces, and the hook can never block or undo an edit \u2014 PostToolUse fires after the tool has already run."},{event:"Stop",subcommand:"on-session-end",label:"Stop hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."},{event:"Stop",subcommand:"on-index-refresh",label:"Stop index-refresh hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge on-index-refresh' at the end of a turn, and refreshes this repository's local code index so codebase search, trace, map, history and review answer from the current tree instead of a stale snapshot. This one READS YOUR SOURCE FILES \u2014 the ones git reports as changed \u2014 parses them, and writes symbol names and line spans to .maind/code-index.sqlite inside the repository. That is a wider promise than the other hooks make, which is why it is consented separately. Everything stays on this machine; nothing is uploaded, and no file contents are stored. It returns immediately (the work runs detached), holds one run per repository at a time, and only refreshes an index that already exists \u2014 the first build stays an explicit 'codebase_index' call."}],_r=[{event:"SessionStart",subcommand:"guard-inject",label:"Guard inject hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-inject' when a session starts (ADR-284 guard). UNLIKE every other hook, this one talks to the maind server: it fetches your session briefing from mcp.maind.dev \u2014 sending your API key, device id, project key, and the client family 'claude-code'; never file contents, never paths \u2014 and injects the result into the session context, so the briefing no longer depends on the model remembering to ask. Cache-first (~12h), so most session starts add no network call. Inactive (exit 0, no output) while guard mode is off, and while the core on-session-briefing hook is wired \u2014 that one delivers the same briefing, guard or no guard."},{event:"PreToolUse",subcommand:"guard-gate",label:"Guard gate hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-gate' before the Edit and Write tools, and before those only. It reads the tool NAME and the session id \u2014 never the tool's arguments, never file contents \u2014 and checks LOCALLY whether this session has been briefed (injection or a maind consultation call). Warn mode (default) adds one reminder line for the model and never blocks; block mode (explicit opt-in via 'guard mode block') may DENY an un-briefed edit, naming the reason and a logged override command. With the guard-difficulty hook also installed (ADR-360), block mode may in addition deny edits during an open difficulty episode until a maind consultation happens \u2014 reading only that hook's local log. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-stop",label:"Guard stop hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-stop' when the session tries to finish. Only with the strict stop-gate enabled ('guard_stop_gate': true \u2014 off by default) and edits made without a review_changes run, it blocks the FIRST stop attempt with a reason so the review can happen; it never blocks twice. Reads only local state; nothing leaves the machine. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-cross-observe",label:"Guard cross-session observe hook",timeout:5,matcher:"Read|Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-observe' after the Read, Edit and Write tools, and after those only. It reads the target file PATH \u2014 never the file's contents \u2014 stats its modification time, and records it as this session's baseline in ~/.maind/cross-session/ (local file, TTL-pruned). That baseline is what lets the check hook detect when a parallel session, an editor, or git changes a file under you. Nothing leaves the machine. Inactive while guard mode is off."},{event:"PreToolUse",subcommand:"guard-cross-check",label:"Guard cross-session check hook",timeout:5,matcher:"Edit|Write",consentDescription:"It runs 'maind-mcp-bridge guard-cross-check' before the Edit and Write tools, and before those only. It reads the target file PATH \u2014 never the file's contents \u2014 and compares the file's current modification time against the baseline this session last observed. If the file changed outside the session (parallel session, editor, git checkout/pull), warn mode adds one advisory telling the model to re-read and reconcile; block mode ('guard mode block') DENIES that one edit with the same instruction. Runs entirely on this machine. Inactive while guard mode is off."},{event:"PostToolUseFailure",subcommand:"guard-difficulty",label:"Guard difficulty hook",timeout:10,consentDescription:"It runs 'maind-mcp-bridge guard-difficulty' after a tool call FAILS (ADR-360). For Bash and for MCP tools other than maind's own it reads the tool NAME and, for Bash, the PROGRAM and subcommand of the command line (e.g. `pnpm test`) \u2014 never paths, flags, values, the error text or any output \u2014 and appends one line (time, 'fail', that program name) to a local per-session log in ~/.maind/guard/triggers/. File tools, lookups such as grep or ls, interrupts you caused and subagent calls are not counted. When four failed attempts follow each other without a ten-minute pause and without a maind consultation, it fetches the state of the trigger conventions ONCE (cached 12h) from mcp.maind.dev, sending your API key, device id and project key like guard-inject \u2014 never tool data \u2014 and, if conv_consult_on_difficulty is on for you, adds ONE hint for the model to consult maind before the next attempt. Only in block mode ('guard mode block') and only if that convention is required does the gate hook then deny edits until a consultation happens (override: 'guard skip --kind difficulty'). Off on this machine: 'guard difficulty off'; off everywhere: switch the convention off in your maind settings. Inactive while guard mode is off."},{event:"PostToolUse",subcommand:"guard-outcome",label:"Guard outcome hook",timeout:10,matcher:"Bash|mcp__.*",consentDescription:"It runs 'maind-mcp-bridge guard-outcome' after a Bash or MCP tool call SUCCEEDS (ADR-360). Test and build runs often end with exit code 0 because their output is piped through `tail` or `grep`, so for Bash it reads the LAST 8 KB of stdout/stderr on this machine to recognise a failure summary (e.g. '2 failed', 'error TS2322', 'ELIFECYCLE') and then discards it \u2014 no output is stored or sent. It writes the same kind of line as guard-difficulty (time, fail or ok, a program name such as `pnpm test`), and an 'ok' only for a program that already failed in this session: that is how a fixed problem is recognised. The log stays in ~/.maind/guard/triggers/; nothing leaves the machine. Inactive while guard mode is off."},{event:"Stop",subcommand:"guard-capture",label:"Guard capture hook",timeout:5,consentDescription:"It runs 'maind-mcp-bridge guard-capture' when a turn ends (ADR-360). Only after a hard-won fix recorded by the guard-difficulty and guard-outcome hooks \u2014 at least five failed attempts over at least five minutes, then the same program succeeded \u2014 and only while conv_learning_capture_offer is on for you, it holds the end of the turn ONCE per episode with a reason asking the agent to ask YOU whether the finding should be recorded (private memory, lesson draft, project documentation, or no). It never records anything itself. Reads only local state; nothing leaves the machine. Off on this machine: 'guard capture off'; off everywhere: the convention switch. Inactive while guard mode is off."}];o(Ce,"inspectHookWiring");o(ud,"hasWiringDrift");o(go,"needsInstallRun");o(AI,"defaultExpectedCommand");o(RI,"findCommand");o(CI,"extractScriptPath");o(II,"tokenize");o(dd,"isObject")});import{existsSync as NI,readFileSync as OI}from"node:fs";import{join as DI}from"node:path";function je(){return DI(Le(),"config.json")}function Ie(){try{let e=je();if(!NI(e))return null;let t=JSON.parse(OI(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r={};return typeof n.auto_announce=="boolean"&&(r.auto_announce=n.auto_announce),typeof n.machine_label=="string"&&(r.machine_label=n.machine_label),typeof n.auto_working_paths=="boolean"&&(r.auto_working_paths=n.auto_working_paths),(n.guard_mode==="off"||n.guard_mode==="warn"||n.guard_mode==="block")&&(r.guard_mode=n.guard_mode),typeof n.guard_stop_gate=="boolean"&&(r.guard_stop_gate=n.guard_stop_gate),typeof n.guard_difficulty=="boolean"&&(r.guard_difficulty=n.guard_difficulty),typeof n.guard_capture=="boolean"&&(r.guard_capture=n.guard_capture),(n.gateway_mode==="off"||n.gateway_mode==="warn"||n.gateway_mode==="enforce")&&(r.gateway_mode=n.gateway_mode),typeof n.gateway_attest=="boolean"&&(r.gateway_attest=n.gateway_attest),(n.gateway_sha_proof==="off"||n.gateway_sha_proof==="warn"||n.gateway_sha_proof==="enforce")&&(r.gateway_sha_proof=n.gateway_sha_proof),Array.isArray(n.declined_hooks)&&(r.declined_hooks=n.declined_hooks.filter(i=>typeof i=="string")),r}catch{return null}}var $t=_(()=>{"use strict";ue();o(je,"bridgeConfigPath");o(Ie,"readBridgeConfig")});function PI(e,t,n){let r=new Set(e);t.forEach((a,c)=>{let l=n[c];l!==void 0&&(l.detail===fd?r.add(a.subcommand):(l.status==="created"||l.status==="merged"||l.status==="skipped"&&l.detail!==void 0&&/already runs maind /.test(l.detail))&&r.delete(a.subcommand))});let i=[...r].sort();return i.length===e.length&&i.every(a=>e.includes(a))?null:i}async function pd(e,t,n=je()){try{let r={},i=await Q(n);if(i!==null&&i.trim().length>0){let l=JSON.parse(i);typeof l=="object"&&l!==null&&!Array.isArray(l)&&(r=l)}let s=Array.isArray(r.declined_hooks)?r.declined_hooks.filter(l=>typeof l=="string"):[],a=PI(s,e,t);if(a===null)return;let c={...r};a.length>0?c.declined_hooks=a:delete c.declined_hooks,await z(n,JSON.stringify(c,null,2)+`
726
+ `,384)}catch{}}var fd,md=_(()=>{"use strict";$t();_e();fd="user declined";o(PI,"nextDeclinedHooks");o(pd,"recordHookDecisions")});import*as yd from"node:path";import*as l_ from"node:readline";async function d_(e,t){let n=yd.join(e.homeDir,".claude","settings.json"),r=t.targetKey;if(e.skip)return{target:r,action:"skip",status:"skipped",detail:"--no-hook"};let i;try{i=await Q(n)}catch(p){return{target:r,action:"merge",status:"failed",detail:`read: ${hd(p)}`}}let s,a="create";if(i===null||i.trim().length===0)s={};else{a="merge";try{let p=JSON.parse(i);if(!gd(p))return{target:r,action:"merge",status:"failed",detail:"existing settings.json is not a JSON object"};s=p}catch(p){return{target:r,action:"merge",status:"failed",detail:`parse: ${hd(p)}`}}}let c=$I(s,t.event,t.matchPattern);if(c!==null)return{target:r,action:"skip",status:"skipped",detail:t.skipDetail(c)};if(!e.full){if(!e.isInteractive)return{target:r,action:"skip",status:"skipped",detail:"consent-required: pass --full to write the hook non-interactively"};if(e.dryRun)return{target:r,action:"merge",status:a==="create"?"would-create":"would-merge",detail:`${n} (would prompt for consent in real run)`};if(!await(e.prompt??LI)(e.out,`
727
727
  Merge a ${t.event} hook into ${n}?
728
728
  ${t.consentDescription}
729
- [Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:sd}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},p=JSON.stringify(u,null,2)+`
730
- `;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await V(n,p,384)}catch(f){return{target:r,action:"merge",status:"failed",detail:`write: ${cd(f)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function n_(e){let t=dd.join(e.homeDir,Qy);return t_(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:o(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${Qy} into every new Claude Code session.`})}function _I(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function ud(e,t){let n=e.launch??Ee({entryPath:Te(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Ot(n);return t_(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:_I(t),skipDetail:o(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return eo(i)?`${s}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:Qs(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function pd(e){let t=[];for(let n of Pt)t.push(await ud(e,n));return t}function bI(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!ld(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!ld(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function wI(e,t){e.write(t);let n=e_.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function ld(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cd(e){return e instanceof Error?e.message:String(e)}var Qy,fd=_(()=>{"use strict";_e();wn();Mt();ad();Qy=".claude/maind-session-start-reminder.md";o(t_,"mergeClaudeHook");o(n_,"mergeSessionStartHook");o(_I,"targetKeyFor");o(ud,"mergeSubcommandHook");o(pd,"mergeAllSubcommandHooks");o(bI,"findExistingHookCommand");o(wI,"promptYesNo");o(ld,"isObject");o(cd,"errMessage")});import{existsSync as xI}from"node:fs";import{dirname as SI,join as s_}from"node:path";function Ft(e,t=xI){let n=e;for(;;){if(t(s_(n,".git")))return n;let r=SI(n);if(r===n)return null;n=r}}var Lt,fo=_(()=>{"use strict";Lt=s_(".maind","code-index.sqlite");o(Ft,"findRepoRoot")});function mo(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function Ut(e){return e+1}function ho(e){return(e.text.split(`
731
- `,1)[0]??"").trim().slice(0,200)}function DI(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function PI(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=DI(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function md(e,t,n,r){for(let i of PI(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function vi(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:t,receiver:"this.*"}:i?.type==="identifier"?{name:t,receiver:`${i.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function jt(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return jt(t.childForFieldName("name"));case"parenthesized_type":return jt(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?jt(n[0]):"#"}default:return"#"}}function $I(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function hd(e){if(e?.type!=="new_expression")return null;let t=e.childForFieldName("constructor");return t?.type==="identifier"||t?.type==="member_expression"?t.text:null}function ki(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=jt(n.childForFieldName("type"))??hd(i)??($I(i)?"#":null);s&&t.set(r.text,s)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=jt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function Ht(e,t,n,r,i={locals:ki(n)}){let s=new Set,a=o(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(s.has(d))return;s.add(d);let u=l.receiver,p=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:p})},"add"),c=r?["call_expression","new_expression",...MI]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(vi(l.childForFieldName("function")));else if(l.type==="new_expression")a(vi(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(vi(d))}}var MI,go=_(()=>{"use strict";o(mo,"newResult");o(Ut,"line1");o(ho,"signatureOf");o(DI,"calleeName");o(PI,"collectCallTargets");o(md,"addCallRefs");o(vi,"calleeRef");MI=["jsx_opening_element","jsx_self_closing_element"];o(jt,"typeNameOf");o($I,"isMethodCallResult");o(hd,"newTypeOf");o(ki,"collectTypeHints");o(Ht,"addTsRefs")});function f_(e,t){let n=mo();for(let r of e.namedChildren)LI(r,t,n);return n}function m_(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function LI(e,t,n){let r=m_(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??jI(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=yo(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&md(n,s.nodeKey,a,p_);return}case"class_definition":FI(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let a=yo(r,t,s.text,s.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function FI(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=yo(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=m_(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,p=yo(l,t,d,u,"method");n.nodes.push(p),n.edges.push({srcKey:i.nodeKey,dstKey:p.nodeKey,kind:"contains"});let f=l.childForFieldName("body");f&&md(n,p.nodeKey,f,p_)}}function yo(e,t,n,r,i){return{nodeKey:ze(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Ut(e.startPosition.row),endLine:Ut(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:ho(e),doc:null}}function jI(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var p_,h_=_(()=>{"use strict";ln();go();p_="call";o(f_,"extractPython");o(m_,"unwrapDecorated");o(LI,"handleTopLevel");o(FI,"addClass");o(yo,"makeNode");o(jI,"firstDottedName")});function y_(e,t){let n=mo(),r=t.language!=="typescript";for(let i of e.namedChildren)HI(i,t,n,r);return WI(e,t,n),n}function UI(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function HI(e,t,n,r){if(e.type==="export_statement"&&BI(e,t,n,r))return;let i=UI(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":GI(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=g_(i,t,n,"function",r);s&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=VI(i,t,n,r);s&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":gd(i,t,n,"interface");return;case"type_alias_declaration":gd(i,t,n,"type_alias");return;case"enum_declaration":gd(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of i.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&Ht(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";g_(a,t,n,d?"function":"variable",r,c,l)}return}default:Ht(n,t.moduleKey,i,r);return}}function BI(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=_d(e.childForFieldName("source")),s=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),s)for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(s){for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):Ht(n,t.moduleKey,c,r),!0):!1}function GI(e,t,n){let r=_d(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),s=[],a=o((c,l)=>{s.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")a("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&a("*",l)}else if(c.type==="named_imports")for(let l of c.namedChildren.filter(d=>d.type==="import_specifier")){let d=l.childForFieldName("name")?.text;d&&a(d,l.childForFieldName("alias")?.text??d)}s.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...s)}function WI(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?_d(i):null;if(s===null)continue;let c=KI(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:s})}}function KI(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function g_(e,t,n,r,i,s,a){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=_o(e,t,l,l,r);if(n.nodes.push(d),n.edges.push({srcKey:t.moduleKey,dstKey:d.nodeKey,kind:"contains"}),r==="function"){let u=a??e.childForFieldName("body")??e;Ht(n,d.nodeKey,u,i,{locals:ki(e)})}else a&&Ht(n,d.nodeKey,a,i);return d}function gd(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=_o(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function VI(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=_o(e,t,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of a?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(p=>({kind:"implements",ref:yd(p)})):[{kind:"extends",ref:yd(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:p,ref:f}of u)f&&n.refs.push({fromKey:s.nodeKey,kind:p,targetName:f.name,receiver:f.receiver})}let c=e.childForFieldName("body");if(!c)return s;let l=zI(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Ht(n,s.nodeKey,g,r,{locals:ki(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let p=`${i}.${u}`,f=_o(d,t,u,p,"method");n.nodes.push(f),n.edges.push({srcKey:s.nodeKey,dstKey:f.nodeKey,kind:"contains"});let h=d.childForFieldName("body");h&&Ht(n,f.nodeKey,h,r,{locals:ki(d),thisFields:l})}return s}function zI(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=jt(n.childForFieldName("type"))??hd(n.childForFieldName("value"));r&&i&&t.set(r.text,i)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),s=jt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function _o(e,t,n,r,i){return{nodeKey:ze(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Ut(e.startPosition.row),endLine:Ut(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:ho(e),doc:null}}function yd(e){if(!e)return null;switch(e.type){case"generic_type":return yd(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return vi(e);default:return null}}function _d(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var __=_(()=>{"use strict";ln();go();o(y_,"extractTypescript");o(UI,"unwrapExport");o(HI,"handleTopLevel");o(BI,"handleExportForm");o(GI,"addImport");o(WI,"collectDynamicImports");o(KI,"enclosingDeclarator");o(g_,"addFunctionLike");o(gd,"addSimpleNamed");o(VI,"addClass");o(zI,"classFieldTypes");o(_o,"makeNode");o(yd,"heritageRef");o(_d,"stringValue")});import{createRequire as qI}from"node:module";import{join as YI}from"node:path";function v_(e,t){return t?YI(t,b_[e]):qI(import.meta.url).resolve(`tree-sitter-wasms/out/${b_[e]}`)}var b_,w_,k_=_(()=>{"use strict";b_={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},w_="tree-sitter.wasm";o(v_,"grammarPath")});import{join as JI}from"node:path";import bd from"web-tree-sitter";var XI,bo,x_=_(()=>{"use strict";ln();ys();h_();__();go();k_();XI=["typescript","tsx","javascript","python"],bo=class{static{o(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await bd.init(this.assetDir?{locateFile:o(t=>JI(this.assetDir,t||w_),"locateFile")}:void 0),this.parser=new bd,this.initialized=!0)}supports(t){return XI.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=s.rootNode,c=Ve(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Ut(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?f_(a,d):y_(a,d);return s.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await bd.Language.load(v_(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as ZI}from"node:module";function S_(){return wo("node:sqlite")}function yr(){if(xi)return xi;try{let{DatabaseSync:e}=S_(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),xi={ok:!0}}finally{t.close()}}catch(e){xi={ok:!1,reason:e instanceof Error?e.message:String(e)}}return xi}function QI(e){let{DatabaseSync:t}=S_(),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>n.exec(r),"exec"),close:o(()=>n.close(),"close"),transaction:o(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function eN(e){let t=wo("better-sqlite3"),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>{n.exec(r)},"exec"),close:o(()=>{n.close()},"close"),transaction:o(r=>n.transaction(r),"transaction")}}function E_(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function vo(e){let t=E_(),n=o(()=>{let{DatabaseSync:i}=wo("node:sqlite"),s=new i(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:o(a=>s.prepare(a),"prepare"),exec:o(a=>s.exec(a),"exec"),close:o(()=>s.close(),"close"),transaction:o(a=>a,"transaction")}}},"openBuiltinRo"),r=o(()=>{let i=wo("better-sqlite3"),s=new i(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:o(a=>s.prepare(a),"prepare"),exec:o(a=>{s.exec(a)},"exec"),close:o(()=>{s.close()},"close"),transaction:o(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(i){try{return r()}catch(s){let a=o(c=>c instanceof Error?c.message:String(c),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(i)}); better-sqlite3 (${a(s)})`)}}}function ko(e){let t=E_(),n=o(i=>{let s=i==="node:sqlite"?QI(e):eN(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=yr();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=yr();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}var wo,xi,xo=_(()=>{"use strict";wo=ZI(import.meta.url);o(S_,"loadBuiltin");xi=null;o(yr,"probeBuiltinSqlite");o(QI,"openBuiltin");o(eN,"openBetter");o(E_,"backendOverride");o(vo,"openSqliteReadOnly");o(ko,"openSqliteDatabase")});function D_(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function P_(e,t,n,r){let i=new Map;for(let a of e)i.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let s=o(a=>i.get(String(a.file_path)),"entry");for(let a of t)s(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Tn(a.receiver),receiverType:Tn(a.receiver_type)});for(let a of n){let c=s(a);if(!c)continue;let l={fromModuleKey:Ve(c.filePath),specifier:String(a.specifier),importedName:Tn(a.imported_name),localName:Tn(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:Tn(a.local_name),specifier:Tn(a.specifier),importedName:Tn(a.imported_name)};s(a)?.exports.push(c)}return[...i.values()]}var T_,A_,R_,C_,I_,N_,O_,Tn,M_=_(()=>{"use strict";ln();T_=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],A_="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",R_="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",C_="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",I_="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",N_="SELECT file_path, specifier, imported_name, local_name FROM file_imports",O_="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";o(D_,"factRows");Tn=o(e=>e==null?null:String(e),"str");o(P_,"assembleFacts")});function So(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var $_,Si,L_=_(()=>{"use strict";xo();cr();M_();vl();o(So,"toNodeRow");$_=400,Si=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=ko(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(yl)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)a.run(l.nodeKey,l.kind,l.name,l.qualifiedName,l.filePath,l.language,l.startLine,l.endLine,l.startByte,l.endByte,l.signature,l.doc),c.run(l.nodeKey,r.get(l.nodeKey)??l.name);if(i){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let h of i.contains)l.run(h.srcKey,h.dstKey,h.kind);let d=D_(t.path,i),u=this.db.prepare(A_);for(let h of d.refs)u.run(...h);let p=this.db.prepare(R_);for(let h of d.imports)p.run(...h);let f=this.db.prepare(C_);for(let h of d.exports)f.run(...h)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return P_(t,this.db.prepare(I_).all(),this.db.prepare(N_).all(),this.db.prepare(O_).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let i of t)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)s.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?So(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(So)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(So)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(So)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=Bg(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
729
+ [Y/n]: `))return{target:r,action:"skip",status:"skipped",detail:fd}}let l={...t.matcher===void 0?{}:{matcher:t.matcher},hooks:[{type:"command",command:t.command,timeout:t.timeout}]},d=s.hooks?.[t.event]??[],u={...s,hooks:{...s.hooks??{},[t.event]:[...d,l]}},f=JSON.stringify(u,null,2)+`
730
+ `;if(e.dryRun)return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"would-create":"would-merge",detail:n};try{await z(n,f,384)}catch(p){return{target:r,action:"merge",status:"failed",detail:`write: ${hd(p)}`}}return{target:r,action:a==="create"?"write":"merge",status:a==="create"?"created":"merged",detail:n}}async function u_(e){let t=yd.join(e.homeDir,c_);return d_(e,{event:"SessionStart",command:`cat ${t}`,timeout:5,matchPattern:/maind-session-start-reminder\.md/,targetKey:"hook:~/.claude/settings.json",skipDetail:o(()=>"SessionStart hook already references the reminder file","skipDetail"),consentDescription:`It 'cat's ${c_} into every new Claude Code session.`})}function MI(e){return`hook(${e.subcommand}):~/.claude/settings.json`}async function _d(e,t){let n=e.launch??Te({entryPath:Ae(),nodePath:process.execPath,extraArgs:[t.subcommand],isElectron:process.versions.electron!==void 0}),r=Ot(n);return d_(e,{event:t.event,command:r,timeout:t.timeout,matcher:t.matcher,matchPattern:new RegExp(t.subcommand),targetKey:MI(t),skipDetail:o(i=>{let s=`${t.label} already runs maind ${t.subcommand}`;return io(i)?`${s}, but via the retired @maind/claude-code-hook \u2014 the bridge now owns that subcommand and that package is not published. Replace its command with: ${r}`:ro(i)?`${s}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${r}`:s},"skipDetail"),consentDescription:t.consentDescription})}async function bd(e){let t=[];for(let n of Pt)t.push(await _d(e,n));return t}function $I(e,t,n){let r=e.hooks?.[t];if(!Array.isArray(r))return null;for(let i of r){if(!gd(i))continue;let s=i.hooks;if(Array.isArray(s))for(let a of s){if(!gd(a))continue;let c=a.command;if(typeof c=="string"&&n.test(c))return c}}return null}async function LI(e,t){e.write(t);let n=l_.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r===""||r==="y"||r==="yes"}function gd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hd(e){return e instanceof Error?e.message:String(e)}var c_,wd=_(()=>{"use strict";_e();wn();Mt();md();c_=".claude/maind-session-start-reminder.md";o(d_,"mergeClaudeHook");o(u_,"mergeSessionStartHook");o(MI,"targetKeyFor");o(_d,"mergeSubcommandHook");o(bd,"mergeAllSubcommandHooks");o($I,"findExistingHookCommand");o(LI,"promptYesNo");o(gd,"isObject");o(hd,"errMessage")});import{existsSync as UI}from"node:fs";import{dirname as HI,join as m_}from"node:path";function Ft(e,t=UI){let n=e;for(;;){if(t(m_(n,".git")))return n;let r=HI(n);if(r===n)return null;n=r}}var Lt,yo=_(()=>{"use strict";Lt=m_(".maind","code-index.sqlite");o(Ft,"findRepoRoot")});function _o(){return{nodes:[],edges:[],refs:[],imports:[],exports:[]}}function Ut(e){return e+1}function bo(e){return(e.text.split(`
731
+ `,1)[0]??"").trim().slice(0,200)}function JI(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}function XI(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=JI(r.childForFieldName("function"));i&&n.add(i)}return[...n]}function vd(e,t,n,r){for(let i of XI(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}function ki(e){if(!e)return null;switch(e.type){case"identifier":case"type_identifier":return{name:e.text,receiver:null};case"member_expression":{let t=e.childForFieldName("property")?.text;if(!t)return null;let n=e.childForFieldName("object");if(n?.type==="this")return{name:t,receiver:"this"};if(n?.type==="identifier")return{name:t,receiver:n.text};let r=n?.type==="member_expression"&&n.childForFieldName("object")?.type==="this"?n.childForFieldName("property")?.text:void 0;if(r)return{name:t,receiver:`this.${r}`};let i=n;for(;i?.type==="member_expression";)i=i.childForFieldName("object");return i?.type==="this"?{name:t,receiver:"this.*"}:i?.type==="identifier"?{name:t,receiver:`${i.text}.*`}:{name:t,receiver:"?"}}case"nested_identifier":{let t=e.text.split(".");return{name:t[t.length-1],receiver:t.length===2?t[0]:"?"}}default:return null}}function jt(e){if(!e)return null;let t=e.type==="type_annotation"?e.namedChildren[0]??null:e;if(!t)return null;switch(t.type){case"type_identifier":return t.text;case"nested_type_identifier":return t.text.replace(/\s+/g,"");case"generic_type":return jt(t.childForFieldName("name"));case"parenthesized_type":return jt(t.namedChildren[0]??null);case"union_type":{let n=t.namedChildren.filter(r=>!(r.type==="literal_type"&&/^(null|undefined)$/.test(r.text))&&!(r.type==="predefined_type"&&/^(null|undefined|void)$/.test(r.text)));return n.length===1?jt(n[0]):"#"}default:return"#"}}function QI(e){let t=e?.type==="await_expression"?e.namedChildren[0]??null:e;return t?.type==="call_expression"&&t.childForFieldName("function")?.type==="member_expression"}function kd(e){if(e?.type!=="new_expression")return null;let t=e.childForFieldName("constructor");return t?.type==="identifier"||t?.type==="member_expression"?t.text:null}function xi(e){let t=new Map;for(let n of e.descendantsOfType("variable_declarator")){let r=n.childForFieldName("name");if(r?.type!=="identifier")continue;let i=n.childForFieldName("value"),s=jt(n.childForFieldName("type"))??kd(i)??(QI(i)?"#":null);s&&t.set(r.text,s)}for(let n of e.descendantsOfType(["required_parameter","optional_parameter"])){let r=n.childForFieldName("pattern");if(r?.type!=="identifier")continue;let i=jt(n.childForFieldName("type"));i&&t.set(r.text,i)}return t}function Ht(e,t,n,r,i={locals:xi(n)}){let s=new Set,a=o(l=>{if(!l)return;let d=`${l.receiver??""}\0${l.name}`;if(s.has(d))return;s.add(d);let u=l.receiver,f=u===null||u==="this"||u==="?"||u.endsWith(".*")?null:u.startsWith("this.")?i.thisFields?.get(u.slice(5))??null:i.locals.get(u)??null;e.refs.push({fromKey:t,kind:"calls",targetName:l.name,receiver:u,receiverType:f})},"add"),c=r?["call_expression","new_expression",...ZI]:["call_expression","new_expression"];for(let l of n.descendantsOfType(c))if(l.type==="call_expression")a(ki(l.childForFieldName("function")));else if(l.type==="new_expression")a(ki(l.childForFieldName("constructor")));else{let d=l.childForFieldName("name");if(d?.type==="identifier"&&!/^[A-Z]/.test(d.text))continue;a(ki(d))}}var ZI,wo=_(()=>{"use strict";o(_o,"newResult");o(Ut,"line1");o(bo,"signatureOf");o(JI,"calleeName");o(XI,"collectCallTargets");o(vd,"addCallRefs");o(ki,"calleeRef");ZI=["jsx_opening_element","jsx_self_closing_element"];o(jt,"typeNameOf");o(QI,"isMethodCallResult");o(kd,"newTypeOf");o(xi,"collectTypeHints");o(Ht,"addTsRefs")});function k_(e,t){let n=_o();for(let r of e.namedChildren)eN(r,t,n);return n}function x_(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}function eN(e,t,n){let r=x_(e);switch(r.type){case"import_statement":case"import_from_statement":{let s=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??nN(r);s&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let s=vo(r,t,i,i,"function");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&vd(n,s.nodeKey,a,v_);return}case"class_definition":tN(r,t,n);return;case"expression_statement":{let s=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(s&&s.type==="identifier"){let a=vo(r,t,s.text,s.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}function tN(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=vo(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let s=e.childForFieldName("superclasses");if(s){for(let c of s.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=x_(c);if(l.type!=="function_definition")continue;let d=l.childForFieldName("name")?.text;if(!d)continue;let u=`${r}.${d}`,f=vo(l,t,d,u,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let p=l.childForFieldName("body");p&&vd(n,f.nodeKey,p,v_)}}function vo(e,t,n,r,i){return{nodeKey:Ye(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Ut(e.startPosition.row),endLine:Ut(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bo(e),doc:null}}function nN(e){return e.descendantsOfType("dotted_name")[0]?.text??null}var v_,S_=_(()=>{"use strict";ln();wo();v_="call";o(k_,"extractPython");o(x_,"unwrapDecorated");o(eN,"handleTopLevel");o(tN,"addClass");o(vo,"makeNode");o(nN,"firstDottedName")});function T_(e,t){let n=_o(),r=t.language!=="typescript";for(let i of e.namedChildren)iN(i,t,n,r);return aN(e,t,n),n}function rN(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}function iN(e,t,n,r){if(e.type==="export_statement"&&sN(e,t,n,r))return;let i=rN(e),s=e.type==="export_statement"&&/^export\s+default\b/.test(e.text);switch(i.type){case"import_statement":oN(i,t,n);return;case"function_declaration":case"generator_function_declaration":{let a=E_(i,t,n,"function",r);s&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"class_declaration":case"abstract_class_declaration":{let a=lN(i,t,n,r);s&&a&&n.exports.push({exportedName:"default",localName:a.name});return}case"interface_declaration":xd(i,t,n,"interface");return;case"type_alias_declaration":xd(i,t,n,"type_alias");return;case"enum_declaration":xd(i,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let a of i.namedChildren){if(a.type!=="variable_declarator")continue;let c=a.childForFieldName("name"),l=a.childForFieldName("value");if(!c||c.type!=="identifier"){l&&Ht(n,t.moduleKey,l,r);continue}let d=l?.type==="arrow_function"||l?.type==="function_expression"||l?.type==="function";E_(a,t,n,d?"function":"variable",r,c,l)}return}default:Ht(n,t.moduleKey,i,r);return}}function sN(e,t,n,r){if(e.childForFieldName("declaration"))return!1;let i=Ed(e.childForFieldName("source")),s=e.namedChildren.find(l=>l.type==="export_clause"),a=e.namedChildren.find(l=>l.type==="namespace_export");if(i!==null){if(n.imports.push({fromModuleKey:t.moduleKey,specifier:i}),s)for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;n.exports.push({exportedName:u,specifier:i,importedName:d})}else if(a){let l=a.namedChildren.find(d=>d.type==="identifier")?.text;l&&n.exports.push({exportedName:l,specifier:i,importedName:"*"})}else n.exports.push({exportedName:"*",specifier:i});return!0}if(s){for(let l of s.namedChildren.filter(d=>d.type==="export_specifier")){let d=l.childForFieldName("name")?.text;if(!d)continue;let u=l.childForFieldName("alias")?.text??d;u!==d&&n.exports.push({exportedName:u,localName:d})}return!0}let c=e.childForFieldName("value");return c?(c.type==="identifier"?n.exports.push({exportedName:"default",localName:c.text}):Ht(n,t.moduleKey,c,r),!0):!1}function oN(e,t,n){let r=Ed(e.childForFieldName("source"));if(r===null)return;let i=e.namedChildren.find(c=>c.type==="import_clause"),s=[],a=o((c,l)=>{s.push({fromModuleKey:t.moduleKey,specifier:r,importedName:c,localName:l})},"bind");for(let c of i?.namedChildren??[])if(c.type==="identifier")a("default",c.text);else if(c.type==="namespace_import"){let l=c.namedChildren.find(d=>d.type==="identifier")?.text;l&&a("*",l)}else if(c.type==="named_imports")for(let l of c.namedChildren.filter(d=>d.type==="import_specifier")){let d=l.childForFieldName("name")?.text;d&&a(d,l.childForFieldName("alias")?.text??d)}s.length===0?n.imports.push({fromModuleKey:t.moduleKey,specifier:r}):n.imports.push(...s)}function aN(e,t,n){for(let r of e.descendantsOfType("call_expression")){if(r.childForFieldName("function")?.type!=="import")continue;let i=r.childForFieldName("arguments")?.namedChildren[0]??null,s=i?.type==="string"?Ed(i):null;if(s===null)continue;let c=cN(r)?.childForFieldName("name");if(c?.type==="identifier")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:"*",localName:c.text});else if(c?.type==="object_pattern"){for(let l of c.namedChildren)if(l.type==="shorthand_property_identifier_pattern")n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:l.text,localName:l.text});else if(l.type==="pair_pattern"){let d=l.childForFieldName("key")?.text,u=l.childForFieldName("value");d&&u?.type==="identifier"&&n.imports.push({fromModuleKey:t.moduleKey,specifier:s,importedName:d,localName:u.text})}}else n.imports.push({fromModuleKey:t.moduleKey,specifier:s})}}function cN(e){let t=e.parent??null,n=t?.type==="await_expression"?t.parent??null:t;return n?.type==="variable_declarator"?n:null}function E_(e,t,n,r,i,s,a){let l=(s??e.childForFieldName("name"))?.text;if(!l)return null;let d=ko(e,t,l,l,r);if(n.nodes.push(d),n.edges.push({srcKey:t.moduleKey,dstKey:d.nodeKey,kind:"contains"}),r==="function"){let u=a??e.childForFieldName("body")??e;Ht(n,d.nodeKey,u,i,{locals:xi(e)})}else a&&Ht(n,d.nodeKey,a,i);return d}function xd(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let s=ko(e,t,i,i,r);n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"})}function lN(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return null;let s=ko(e,t,i,i,"class");n.nodes.push(s),n.edges.push({srcKey:t.moduleKey,dstKey:s.nodeKey,kind:"contains"});let a=e.namedChildren.find(d=>d.type==="class_heritage");for(let d of a?.namedChildren??[]){let u=d.type==="implements_clause"?d.namedChildren.map(f=>({kind:"implements",ref:Sd(f)})):[{kind:"extends",ref:Sd(d.type==="extends_clause"?d.childForFieldName("value"):d)}];for(let{kind:f,ref:p}of u)p&&n.refs.push({fromKey:s.nodeKey,kind:f,targetName:p.name,receiver:p.receiver})}let c=e.childForFieldName("body");if(!c)return s;let l=dN(c);for(let d of c.namedChildren){if(d.type==="public_field_definition"||d.type==="field_definition"){let g=d.childForFieldName("value");g&&Ht(n,s.nodeKey,g,r,{locals:xi(g),thisFields:l});continue}if(d.type!=="method_definition")continue;let u=d.childForFieldName("name")?.text;if(!u)continue;let f=`${i}.${u}`,p=ko(d,t,u,f,"method");n.nodes.push(p),n.edges.push({srcKey:s.nodeKey,dstKey:p.nodeKey,kind:"contains"});let h=d.childForFieldName("body");h&&Ht(n,p.nodeKey,h,r,{locals:xi(d),thisFields:l})}return s}function dN(e){let t=new Map;for(let n of e.namedChildren)if(n.type==="public_field_definition"||n.type==="field_definition"){let r=n.childForFieldName("name")??n.childForFieldName("property"),i=jt(n.childForFieldName("type"))??kd(n.childForFieldName("value"));r&&i&&t.set(r.text,i)}else if(n.type==="method_definition"&&n.childForFieldName("name")?.text==="constructor")for(let r of n.childForFieldName("parameters")?.namedChildren??[]){if(!r.namedChildren.some(a=>a.type==="accessibility_modifier"||a.type==="override_modifier")&&!/^\s*readonly\b/.test(r.text))continue;let i=r.childForFieldName("pattern"),s=jt(r.childForFieldName("type"));i?.type==="identifier"&&s&&t.set(i.text,s)}return t}function ko(e,t,n,r,i){return{nodeKey:Ye(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Ut(e.startPosition.row),endLine:Ut(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:bo(e),doc:null}}function Sd(e){if(!e)return null;switch(e.type){case"generic_type":return Sd(e.childForFieldName("name"));case"nested_type_identifier":{let t=e.childForFieldName("name")?.text,n=e.childForFieldName("module");return t?{name:t,receiver:n?.type==="identifier"?n.text:"?"}:null}case"identifier":case"type_identifier":case"member_expression":return ki(e);default:return null}}function Ed(e){return!e||e.type!=="string"?null:e.text.replace(/^["'`]|["'`]$/g,"")}var A_=_(()=>{"use strict";ln();wo();o(T_,"extractTypescript");o(rN,"unwrapExport");o(iN,"handleTopLevel");o(sN,"handleExportForm");o(oN,"addImport");o(aN,"collectDynamicImports");o(cN,"enclosingDeclarator");o(E_,"addFunctionLike");o(xd,"addSimpleNamed");o(lN,"addClass");o(dN,"classFieldTypes");o(ko,"makeNode");o(Sd,"heritageRef");o(Ed,"stringValue")});import{createRequire as uN}from"node:module";import{join as fN}from"node:path";function I_(e,t){return t?fN(t,R_[e]):uN(import.meta.url).resolve(`tree-sitter-wasms/out/${R_[e]}`)}var R_,C_,N_=_(()=>{"use strict";R_={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},C_="tree-sitter.wasm";o(I_,"grammarPath")});import{join as pN}from"node:path";import Td from"web-tree-sitter";var mN,xo,O_=_(()=>{"use strict";ln();ks();S_();A_();wo();N_();mN=["typescript","tsx","javascript","python"],xo=class{static{o(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await Td.init(this.assetDir?{locateFile:o(t=>pN(this.assetDir,t||C_),"locateFile")}:void 0),this.parser=new Td,this.initialized=!0)}supports(t){return mN.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let s=i.parse(n);if(!s)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[],exports:[]};let a=s.rootNode,c=qe(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Ut(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},d={filePath:t,language:r,source:n,moduleKey:c},u=r==="python"?k_(a,d):T_(a,d);return s.delete(),{filePath:t,language:r,nodes:[l,...u.nodes],edges:u.edges,refs:u.refs,imports:u.imports,exports:u.exports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await Td.Language.load(I_(t,this.assetDir)),this.grammars.set(t,n)),n}}});import{createRequire as hN}from"node:module";function D_(){return So("node:sqlite")}function br(){if(Si)return Si;try{let{DatabaseSync:e}=D_(),t=new e(":memory:");try{t.exec("CREATE VIRTUAL TABLE probe_fts USING fts5(t)"),t.exec("INSERT INTO probe_fts (t) VALUES ('probe')"),t.prepare("SELECT bm25(probe_fts) AS s FROM probe_fts WHERE probe_fts MATCH 'probe'").get(),Si={ok:!0}}finally{t.close()}}catch(e){Si={ok:!1,reason:e instanceof Error?e.message:String(e)}}return Si}function gN(e){let{DatabaseSync:t}=D_(),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>n.exec(r),"exec"),close:o(()=>n.close(),"close"),transaction:o(r=>()=>{n.exec("BEGIN");try{r(),n.exec("COMMIT")}catch(i){try{n.exec("ROLLBACK")}catch{}throw i}},"transaction")}}function yN(e){let t=So("better-sqlite3"),n=new t(e);return{prepare:o(r=>n.prepare(r),"prepare"),exec:o(r=>{n.exec(r)},"exec"),close:o(()=>{n.close()},"close"),transaction:o(r=>n.transaction(r),"transaction")}}function P_(){let e=(process.env.MAIND_SQLITE_BACKEND??"").trim().toLowerCase();return e==="builtin"||e==="better"?e:null}function Eo(e){let t=P_(),n=o(()=>{let{DatabaseSync:i}=So("node:sqlite"),s=new i(e,{readOnly:!0});return{backend:"node:sqlite",db:{prepare:o(a=>s.prepare(a),"prepare"),exec:o(a=>s.exec(a),"exec"),close:o(()=>s.close(),"close"),transaction:o(a=>a,"transaction")}}},"openBuiltinRo"),r=o(()=>{let i=So("better-sqlite3"),s=new i(e,{readonly:!0,fileMustExist:!0});return{backend:"better-sqlite3",db:{prepare:o(a=>s.prepare(a),"prepare"),exec:o(a=>{s.exec(a)},"exec"),close:o(()=>{s.close()},"close"),transaction:o(a=>a,"transaction")}}},"openBetterRo");if(t==="builtin")return n();if(t==="better")return r();try{return n()}catch(i){try{return r()}catch(s){let a=o(c=>c instanceof Error?c.message:String(c),"reason");throw new Error(`no usable SQLite backend for a read-only open: node:sqlite (${a(i)}); better-sqlite3 (${a(s)})`)}}}function To(e){let t=P_(),n=o(i=>{let s=i==="node:sqlite"?gN(e):yN(e);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA foreign_keys = ON"),{db:s,backend:i}},"openAs");if(t==="builtin"){let i=br();if(!i.ok)throw new Error(`MAIND_SQLITE_BACKEND=builtin, but node:sqlite is unusable: ${i.reason}`);return n("node:sqlite")}if(t==="better")return n("better-sqlite3");let r=br();if(r.ok)return n("node:sqlite");try{return n("better-sqlite3")}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`no usable SQLite backend: node:sqlite unavailable (${r.reason}); better-sqlite3 unavailable (${s})`)}}var So,Si,Ao=_(()=>{"use strict";So=hN(import.meta.url);o(D_,"loadBuiltin");Si=null;o(br,"probeBuiltinSqlite");o(gN,"openBuiltin");o(yN,"openBetter");o(P_,"backendOverride");o(Eo,"openSqliteReadOnly");o(To,"openSqliteDatabase")});function B_(e,t){return{refs:t.refs.map(n=>[e,n.fromKey,n.kind,n.targetName,n.receiver??null,n.receiverType??null]),imports:t.imports.map(n=>[e,n.specifier,n.importedName??null,n.localName??null]),exports:t.exports.map(n=>[e,n.exportedName,n.localName??null,n.specifier??null,n.importedName??null])}}function G_(e,t,n,r){let i=new Map;for(let a of e)i.set(a.path,{filePath:a.path,language:a.language,refs:[],imports:[],exports:[]});let s=o(a=>i.get(String(a.file_path)),"entry");for(let a of t)s(a)?.refs.push({fromKey:String(a.src_key),kind:String(a.kind),targetName:String(a.target_name),receiver:Tn(a.receiver),receiverType:Tn(a.receiver_type)});for(let a of n){let c=s(a);if(!c)continue;let l={fromModuleKey:qe(c.filePath),specifier:String(a.specifier),importedName:Tn(a.imported_name),localName:Tn(a.local_name)};c.imports.push(l)}for(let a of r){let c={exportedName:String(a.exported_name),localName:Tn(a.local_name),specifier:Tn(a.specifier),importedName:Tn(a.imported_name)};s(a)?.exports.push(c)}return[...i.values()]}var M_,$_,L_,F_,j_,U_,H_,Tn,W_=_(()=>{"use strict";ln();M_=["DELETE FROM file_refs WHERE file_path = ?","DELETE FROM file_imports WHERE file_path = ?","DELETE FROM file_exports WHERE file_path = ?"],$_="INSERT INTO file_refs(file_path, src_key, kind, target_name, receiver, receiver_type) VALUES(?, ?, ?, ?, ?, ?)",L_="INSERT INTO file_imports(file_path, specifier, imported_name, local_name) VALUES(?, ?, ?, ?)",F_="INSERT INTO file_exports(file_path, exported_name, local_name, specifier, imported_name) VALUES(?, ?, ?, ?, ?)",j_="SELECT file_path, src_key, kind, target_name, receiver, receiver_type FROM file_refs",U_="SELECT file_path, specifier, imported_name, local_name FROM file_imports",H_="SELECT file_path, exported_name, local_name, specifier, imported_name FROM file_exports";o(B_,"factRows");Tn=o(e=>e==null?null:String(e),"str");o(G_,"assembleFacts")});function Ro(e){return{nodeKey:e.node_key,kind:e.kind,name:e.name,qualifiedName:e.qualified_name,filePath:e.file_path,language:e.language,startLine:e.start_line,endLine:e.end_line,startByte:e.start_byte,endByte:e.end_byte,signature:e.signature,doc:e.doc}}var K_,Ei,V_=_(()=>{"use strict";Ao();lr();W_();Rl();o(Ro,"toNodeRow");K_=400,Ei=class{static{o(this,"NodeSqliteStore")}db;backend;constructor(t){let n=To(t);this.db=n.db,this.backend=n.backend}async init(){this.db.exec(Sl)}async close(){this.db.close()}async getMeta(t){return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}async setMeta(t,n){this.db.prepare("INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}async getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(n=>({path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}))}async getFile(t){let n=this.db.prepare("SELECT * FROM files WHERE path = ?").get(t);return n?{path:n.path,language:n.language,contentHash:n.content_hash,mtimeMs:n.mtime_ms,size:n.size,indexedAt:n.indexed_at}:null}async upsertFile(t){this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)}async replaceFileNodes(t,n,r,i){this.db.transaction(()=>{this.deleteFileGraph(t.path);let a=this.insertNodeStmt(),c=this.insertFtsStmt();for(let l of n)a.run(l.nodeKey,l.kind,l.name,l.qualifiedName,l.filePath,l.language,l.startLine,l.endLine,l.startByte,l.endByte,l.signature,l.doc),c.run(l.nodeKey,r.get(l.nodeKey)??l.name);if(i){let l=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let h of i.contains)l.run(h.srcKey,h.dstKey,h.kind);let d=B_(t.path,i),u=this.db.prepare($_);for(let h of d.refs)u.run(...h);let f=this.db.prepare(L_);for(let h of d.imports)f.run(...h);let p=this.db.prepare(F_);for(let h of d.exports)p.run(...h)}this.upsertFileStmt().run(t.path,t.language,t.contentHash,t.mtimeMs,t.size,t.indexedAt)})()}async deleteFile(t){this.db.transaction(()=>{this.deleteFileGraph(t),this.db.prepare("DELETE FROM files WHERE path = ?").run(t)})()}async getAllFacts(){let t=this.db.prepare("SELECT path, language FROM files").all();return G_(t,this.db.prepare(j_).all(),this.db.prepare(U_).all(),this.db.prepare(H_).all())}async replaceCrossFileEdges(t){this.db.transaction(()=>{this.db.prepare("DELETE FROM edges WHERE kind <> 'contains'").run();let r=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let i of t)r.run(i.srcKey,i.dstKey,i.kind)})()}async replaceOutgoingEdges(t,n){this.db.transaction(()=>{let i=this.db.prepare("DELETE FROM edges WHERE src_key = ?");for(let a of t)i.run(a);let s=this.db.prepare("INSERT OR IGNORE INTO edges(src_key, dst_key, kind) VALUES(?, ?, ?)");for(let a of n)s.run(a.srcKey,a.dstKey,a.kind)})()}async getNameIndex(){return this.db.prepare("SELECT node_key, name, kind, file_path FROM nodes").all().map(n=>({nodeKey:n.node_key,name:n.name,kind:n.kind,filePath:n.file_path}))}async getNode(t){let n=this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(t);return n?Ro(n):null}async getNodesByFile(t){return this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(t).map(Ro)}async getNodesByKinds(t){return t.length===0?[]:this.db.prepare(`SELECT * FROM nodes WHERE kind IN (${t.map(()=>"?").join(",")})`).all(...t).map(Ro)}async getAllNodes(){return this.db.prepare("SELECT * FROM nodes").all().map(Ro)}async getAllEdges(){return this.db.prepare("SELECT src_key, dst_key, kind FROM edges").all().map(n=>({srcKey:n.src_key,dstKey:n.dst_key,kind:n.kind}))}async upsertEmbeddings(t){let n=this.db.prepare("INSERT OR REPLACE INTO embeddings(node_key, dim, vec, content_hash) VALUES(?, ?, ?, ?)");this.db.transaction(()=>{for(let i of t){let s=Buffer.from(i.vec.buffer,i.vec.byteOffset,i.vec.byteLength);n.run(i.nodeKey,i.dim,s,i.contentHash)}})()}async getEmbeddingContentHashes(){let t=this.db.prepare("SELECT node_key, content_hash FROM embeddings").all();return new Map(t.map(n=>[n.node_key,n.content_hash]))}async allEmbeddings(){return this.db.prepare("SELECT node_key, vec FROM embeddings").all().map(n=>({nodeKey:n.node_key,vec:new Float32Array(n.vec.buffer,n.vec.byteOffset,n.vec.byteLength/4)}))}async pruneOrphanEmbeddings(){let t=this.db.prepare("DELETE FROM embeddings WHERE node_key NOT IN (SELECT node_key FROM nodes)").run();return Number(t.changes)}async countEmbeddings(){return this.db.prepare("SELECT COUNT(*) AS c FROM embeddings").get().c}async searchFts(t,n,r){let i=Xg(t);if(!i)return[];let s=n?`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
732
732
  FROM nodes_fts f JOIN nodes n ON n.node_key = f.node_key
733
733
  WHERE nodes_fts MATCH ? AND n.kind = ?
734
734
  ORDER BY score LIMIT ?`:`SELECT f.node_key AS node_key, bm25(nodes_fts) AS score
@@ -741,7 +741,7 @@ ${t.consentDescription}
741
741
  FROM nodes n
742
742
  WHERE n.kind = 'module'
743
743
  ORDER BY imports_in DESC, symbol_count DESC
744
- LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=$_)for(let a of n.slice(s,s+$_))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of T_)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
744
+ LIMIT ?`).all(t).map(r=>({filePath:r.file_path,language:r.language,symbolCount:r.symbol_count,importsOut:r.imports_out,importsIn:r.imports_in}))}deleteFileGraph(t){let n=this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(t).map(s=>s.node_key),r=this.db.prepare("DELETE FROM edges WHERE src_key = ?"),i=this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");for(let s=0;s<n.length;s+=K_)for(let a of n.slice(s,s+K_))r.run(a),i.run(a);this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t);for(let s of M_)this.db.prepare(s).run(t)}_insNode=null;insertNodeStmt(){return this._insNode||(this._insNode=this.db.prepare(`INSERT OR REPLACE INTO nodes(
745
745
  node_key, kind, name, qualified_name, file_path, language,
746
746
  start_line, end_line, start_byte, end_byte, signature, doc
747
747
  ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)),this._insNode}_insFts=null;insertFtsStmt(){return this._insFts||(this._insFts=this.db.prepare("INSERT INTO nodes_fts(node_key, search_text) VALUES(?, ?)")),this._insFts}_upsertFile=null;upsertFileStmt(){return this._upsertFile||(this._upsertFile=this.db.prepare(`INSERT INTO files(path, language, content_hash, mtime_ms, size, indexed_at)
@@ -751,46 +751,46 @@ ${t.consentDescription}
751
751
  content_hash = excluded.content_hash,
752
752
  mtime_ms = excluded.mtime_ms,
753
753
  size = excluded.size,
754
- indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as tN}from"node:crypto";function _r(e){return tN("sha256").update(e,"utf8").digest("hex")}function F_(e){return{node_key_hash:_r(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:_r(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?_r(e.signature):null}}function j_(e){return{src_key_hash:_r(e.srcKey),dst_key_hash:_r(e.dstKey),kind:e.kind}}function U_(e,t,n){return{node_key_hash:_r(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var H_=_(()=>{"use strict";o(_r,"sha256");o(F_,"toCloudNode");o(j_,"toCloudEdge");o(U_,"toCloudEmbedding")});import{randomUUID as nN}from"node:crypto";function wd(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function B_(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function G_(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var br,wr,rN,vd=_(()=>{"use strict";cr();H_();br=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},wr=class{static{o(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(or),lastSyncedAt:B_(await this.store.getMeta(bl))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(F_),n=(await this.store.getAllEdges()).map(j_),r=await this.store.getMeta(Rt)??At,i=await this.store.getMeta(or),s=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(b=>[b.language,b.count])),c=nN(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:a},d=0,u=wd(t,this.chunk),p=wd(n,this.chunk*2),f=Math.max(1,u.length+p.length);for(let b of u)await this.post("/api/codebase/push",{...l,nodes:b,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:f});for(let b of p)await this.post("/api/codebase/push",{...l,nodes:[],edges:b,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:f});u.length===0&&p.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let h=t.map(b=>b.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:f,total:f});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(bl,String(Date.now())),i&&await this.store.setMeta(Ug,i),{nodes:t.length,edges:n.length,pruned:G_(g.nodes_deleted),edgesPruned:G_(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>U_(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=wd(a,rN),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Fs),n=await this.store.getMeta(js),r=B_(await this.store.getMeta(Us));if(!t||!n||!r)throw new br("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new br(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},rN=250;o(wd,"chunkArray");o(B_,"numOrNull");o(G_,"numOr0")});var xd={};Q(xd,{CodeIndexSync:()=>wr,DEFAULT_DB_RELPATH:()=>kd,SyncError:()=>br,createCodeIndexSync:()=>sN,createNodeCodeIndex:()=>To,openIndexReader:()=>oN,openSqliteDatabase:()=>ko,openSqliteReadOnly:()=>vo,probeBuiltinSqlite:()=>yr});import{mkdirSync as iN}from"node:fs";import{posix as Eo}from"node:path";function To(e){let t=e.dbPath??Eo.join(e.repoRoot,kd);iN(Eo.dirname(t),{recursive:!0}),e.dbPath===void 0&&Xr(Eo.dirname(t));let n=new Si(t),r=new bo;return new ui({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function sN(e){let t=e.dbPath??Eo.join(e.repoRoot,kd),n=e.projectKey??Dh(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Si(t);return new wr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function oN(e){return Rl(vo(e).db)}var kd,Ao=_(()=>{"use strict";Nc();x_();kl();Cl();L_();xo();vd();bs();vd();xo();kd=".maind/code-index.sqlite";o(To,"createNodeCodeIndex");o(sN,"createCodeIndexSync");o(oN,"openIndexReader")});import{execFileSync as W_}from"node:child_process";import{existsSync as K_,realpathSync as V_}from"node:fs";import{createRequire as aN}from"node:module";import{basename as cN,dirname as lN,isAbsolute as z_,join as dN,relative as q_,resolve as Ro,sep as Y_}from"node:path";function Co(){let e=yr();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return aN(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function J_(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function he(e=process.cwd()){try{let t=W_("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function Z_(e,t=he(),n=process.cwd()){let r=z_(e)?[e]:[Ro(t,e),Ro(n,e)];for(let i of r){let s=lN(i);if(!K_(s))continue;let a;try{a=V_(s)}catch{continue}let c=Q_(a);if(c===null)continue;let l=q_(c,dN(a,cN(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(Y_).join("/")}}return null}function vr(e,t=he(),n=process.cwd()){let r=z_(e)?[e]:[Ro(t,e),Ro(n,e)];for(let i of r){if(!K_(i))continue;let s;try{s=V_(i)}catch{continue}let a=Q_(s);if(a===null)continue;let c=q_(a,s);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(Y_).join("/")}}return null}function Q_(e){try{let t=W_("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function eb(){return To({repoRoot:he()})}function tb(e){return To({repoRoot:e})}var X_,Bt=_(()=>{"use strict";Ao();o(Co,"probeNativeStore");o(J_,"isNativeStoreUnavailable");X_="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";o(he,"resolveRepoRoot");o(Z_,"resolveRepoRootForPath");o(vr,"resolveRepoRootForDir");o(Q_,"gitToplevelOf");o(eb,"defaultEngineFactory");o(tb,"engineForRoot")});async function Io(e){return ut("get_session_briefing",{tools:["claude-code"]},e)}async function ut(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Ei,i=new AbortController,s=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:uN,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id"),d=(c.headers.get("content-type")??"").startsWith("text/event-stream")?await nb(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let b=null;try{let w=JSON.parse(d);typeof w.result?.instructions=="string"&&(b=w.result.instructions)}catch{b=null}n.onInitialize(b)}if(!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(b=>b.text().catch(()=>"")).catch(()=>"");let p=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!p.ok)return null;let h=(p.headers.get("content-type")??"").startsWith("text/event-stream")?await nb(p):await p.text();if(h.trim().length===0)return null;let g=JSON.parse(h);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(b=>b.type==="text"&&typeof b.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function nb(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",a=o(()=>{if(i.length===0)return;let c=i.join(`
754
+ indexed_at = excluded.indexed_at`)),this._upsertFile}}});import{createHash as _N}from"node:crypto";function wr(e){return _N("sha256").update(e,"utf8").digest("hex")}function z_(e){return{node_key_hash:wr(e.nodeKey),name:e.name,qualified_name:e.qualifiedName,path_hash:wr(e.filePath),kind:e.kind,language:e.language,start_line:e.startLine,end_line:e.endLine,signature_hash:e.signature?wr(e.signature):null}}function q_(e){return{src_key_hash:wr(e.srcKey),dst_key_hash:wr(e.dstKey),kind:e.kind}}function Y_(e,t,n){return{node_key_hash:wr(e.nodeKey),embedding:Array.from(e.vec),recipe_version:n.recipeVersion,dim:n.dim,model:n.model,content_hash:t}}var J_=_(()=>{"use strict";o(wr,"sha256");o(z_,"toCloudNode");o(q_,"toCloudEdge");o(Y_,"toCloudEmbedding")});import{randomUUID as bN}from"node:crypto";function Ad(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function X_(e){if(e===null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Z_(e){return typeof e=="number"&&Number.isFinite(e)?e:0}var vr,kr,wN,Rd=_(()=>{"use strict";lr();J_();vr=class extends Error{static{o(this,"SyncError")}status;code;constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="SyncError"}},kr=class{static{o(this,"CodeIndexSync")}store;cfg;base;chunk;fetchImpl;constructor(t,n){this.store=t,this.cfg=n,this.base=n.endpoint.replace(/\/+$/,""),this.chunk=n.chunkSize&&n.chunkSize>0?n.chunkSize:1e3,this.fetchImpl=n.fetchImpl??fetch}async close(){await this.store.close()}async setConsent(t,n){await this.post("/api/codebase/consent",{enabled:t,policy_version:n??null})}async remoteStatus(){let t=new URLSearchParams({project_key:this.cfg.projectKey});return await this.get(`/api/codebase/status?${t.toString()}`)}async localStatus(){return await this.store.init(),{indexed:await this.store.countFiles()>0,nodeCount:await this.store.countNodes(),edgeCount:await this.store.countEdges(),embeddingCount:await this.store.countEmbeddings(),fileCount:await this.store.countFiles(),headCommit:await this.store.getMeta(ar),lastSyncedAt:X_(await this.store.getMeta(Tl))}}async push(){await this.store.init();let t=(await this.store.getAllNodes()).map(z_),n=(await this.store.getAllEdges()).map(q_),r=await this.store.getMeta(Rt)??At,i=await this.store.getMeta(ar),s=await this.store.countFiles(),a=Object.fromEntries((await this.store.languageDistribution()).map(b=>[b.language,b.count])),c=bN(),l={project_key:this.cfg.projectKey,head_commit:i,schema_version:r,file_count:s,lang_dist:a},d=0,u=Ad(t,this.chunk),f=Ad(n,this.chunk*2),p=Math.max(1,u.length+f.length);for(let b of u)await this.post("/api/codebase/push",{...l,nodes:b,edges:[]}),this.cfg.onProgress?.({phase:"nodes",done:++d,total:p});for(let b of f)await this.post("/api/codebase/push",{...l,nodes:[],edges:b,sync_gen:c}),this.cfg.onProgress?.({phase:"edges",done:++d,total:p});u.length===0&&f.length===0&&await this.post("/api/codebase/push",{...l,nodes:[],edges:[]});let h=t.map(b=>b.node_key_hash),g=await this.post("/api/codebase/prune",{project_key:this.cfg.projectKey,keep_node_key_hashes:h,edge_sync_gen:c});this.cfg.onProgress?.({phase:"prune",done:p,total:p});let y=await this.store.countEmbeddings()>0?await this.pushEmbeddings():0;return await this.store.setMeta(Tl,String(Date.now())),i&&await this.store.setMeta(Yg,i),{nodes:t.length,edges:n.length,pruned:Z_(g.nodes_deleted),edgesPruned:Z_(g.edges_deleted),embeddings:y,headCommit:i}}async pushEmbeddings(){await this.store.init();let t=await this.store.getEmbeddingContentHashes();if(t.size===0)return 0;let n=await this.embedMeta(),r=new URLSearchParams({project_key:this.cfg.projectKey}),s=(await this.get(`/api/codebase/embedding-hashes?${r.toString()}`)).hashes??{},a=(await this.store.allEmbeddings()).map(d=>Y_(d,t.get(d.nodeKey)??"",n)).filter(d=>d.content_hash!==""&&s[d.node_key_hash]!==d.content_hash);if(a.length===0)return 0;let c=Ad(a,wN),l=0;for(let d of c)await this.post("/api/codebase/push-embeddings",{project_key:this.cfg.projectKey,embeddings:d}),this.cfg.onProgress?.({phase:"embeddings",done:++l,total:c.length});return a.length}async embedMeta(){let t=await this.store.getMeta(Gs),n=await this.store.getMeta(Ws),r=X_(await this.store.getMeta(Ks));if(!t||!n||!r)throw new vr("local embeddings lack embedder metadata \u2014 re-run `maind index --embed` once to record it",0,"missing_embed_meta");return{recipeVersion:t,model:n,dim:r}}headers(){let t={"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`};return this.cfg.deviceId&&(t["x-maind-device-id"]=this.cfg.deviceId),t}async post(t,n){let r=await this.fetchImpl(`${this.base}${t}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)});return this.unwrap(r,t)}async get(t){let n=await this.fetchImpl(`${this.base}${t}`,{method:"GET",headers:this.headers()});return this.unwrap(n,t)}async unwrap(t,n){let r=await t.text().catch(()=>""),i=null;try{i=r?JSON.parse(r):null}catch{i=null}if(!t.ok||!i||i.ok!==!0){let s=i?.error;throw new vr(`${n} failed (HTTP ${t.status})${s?`: ${s}`:""}`,t.status,s)}return i}},wN=250;o(Ad,"chunkArray");o(X_,"numOrNull");o(Z_,"numOr0")});var Id={};ee(Id,{CodeIndexSync:()=>kr,DEFAULT_DB_RELPATH:()=>Cd,SyncError:()=>vr,createCodeIndexSync:()=>kN,createNodeCodeIndex:()=>Io,openIndexReader:()=>xN,openSqliteDatabase:()=>To,openSqliteReadOnly:()=>Eo,probeBuiltinSqlite:()=>br});import{mkdirSync as vN}from"node:fs";import{posix as Co}from"node:path";function Io(e){let t=e.dbPath??Co.join(e.repoRoot,Cd);vN(Co.dirname(t),{recursive:!0}),e.dbPath===void 0&&Zr(Co.dirname(t));let n=new Ei(t),r=new xo;return new fi({store:n,parser:r,repoRoot:e.repoRoot,embedder:e.embedder})}function kN(e){let t=e.dbPath??Co.join(e.repoRoot,Cd),n=e.projectKey??Bh(e.repoRoot)??void 0;if(!n)throw new Error("No project_key \u2014 the repo has no git remote. Cloud sync scopes by sha256(remote); commit a remote or pass an explicit key.");let r=new Ei(t);return new kr(r,{endpoint:e.endpoint,apiKey:e.apiKey,projectKey:n,deviceId:e.deviceId,chunkSize:e.chunkSize,onProgress:e.onProgress})}function xN(e){return Ml(Eo(e).db)}var Cd,No=_(()=>{"use strict";Fc();O_();Cl();$l();V_();Ao();Rd();Ss();Rd();Ao();Cd=".maind/code-index.sqlite";o(Io,"createNodeCodeIndex");o(kN,"createCodeIndexSync");o(xN,"openIndexReader")});import{execFileSync as Q_}from"node:child_process";import{existsSync as eb,realpathSync as tb}from"node:fs";import{createRequire as SN}from"node:module";import{basename as EN,dirname as TN,isAbsolute as nb,join as AN,relative as rb,resolve as Oo,sep as ib}from"node:path";function Do(){let e=br();if(e.ok)return{ok:!0,backend:"node:sqlite"};try{return SN(import.meta.url)("better-sqlite3"),{ok:!0,backend:"better-sqlite3"}}catch(t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`node:sqlite: ${e.reason}; better-sqlite3: ${n}`}}}function sb(e){let t=e?.code??"",n=e instanceof Error?e.message:String(e);return/better.sqlite3|better_sqlite3|bindings file|no usable SQLite backend/i.test(`${t} ${n}`)||t==="ERR_DLOPEN_FAILED"||/NODE_MODULE_VERSION/.test(n)}function he(e=process.cwd()){try{let t=Q_("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:e}catch{return e}}function ab(e,t=he(),n=process.cwd()){let r=nb(e)?[e]:[Oo(t,e),Oo(n,e)];for(let i of r){let s=TN(i);if(!eb(s))continue;let a;try{a=tb(s)}catch{continue}let c=cb(a);if(c===null)continue;let l=rb(c,AN(a,EN(i)));if(!l.startsWith(".."))return{repoRoot:c,repoRelPath:l.split(ib).join("/")}}return null}function xr(e,t=he(),n=process.cwd()){let r=nb(e)?[e]:[Oo(t,e),Oo(n,e)];for(let i of r){if(!eb(i))continue;let s;try{s=tb(i)}catch{continue}let a=cb(s);if(a===null)continue;let c=rb(a,s);if(!c.startsWith(".."))return{repoRoot:a,repoRelDir:c===""?"":c.split(ib).join("/")}}return null}function cb(e){try{let t=Q_("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function lb(){return Io({repoRoot:he()})}function db(e){return Io({repoRoot:e})}var ob,Bt=_(()=>{"use strict";No();o(Do,"probeNativeStore");o(sb,"isNativeStoreUnavailable");ob="codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";o(he,"resolveRepoRoot");o(ab,"resolveRepoRootForPath");o(xr,"resolveRepoRootForDir");o(cb,"gitToplevelOf");o(lb,"defaultEngineFactory");o(db,"engineForRoot")});async function Po(e){return ft("get_session_briefing",{tools:["claude-code"]},e)}async function ft(e,t,n){let r=n.mcpUrl??process.env.MAIND_MCP_URL??Ti,i=new AbortController,s=setTimeout(()=>i.abort(),n.timeoutMs??3e3);try{let a={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n.apiKey}`,"x-maind-client-family":n.clientFamily??"claude-code","x-maind-client-version":n.bridgeVersion,"x-maind-bridge-version":n.bridgeVersion};n.deviceId&&(a["x-maind-device-id"]=n.deviceId),n.projectKey&&(a["x-maind-project-key"]=n.projectKey);let c=await fetch(r,{method:"POST",headers:a,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-init",method:"initialize",params:{protocolVersion:RN,capabilities:{},clientInfo:{name:"maind-mcp-bridge-guard",version:n.bridgeVersion}}})}),l=c.headers.get("mcp-session-id"),d=(c.headers.get("content-type")??"").startsWith("text/event-stream")?await ub(c).catch(()=>""):await c.text().catch(()=>"");if(n.onInitialize){let b=null;try{let w=JSON.parse(d);typeof w.result?.instructions=="string"&&(b=w.result.instructions)}catch{b=null}n.onInitialize(b)}if(!c.ok||!l)return null;let u={...a,"mcp-session-id":l};await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})}).then(b=>b.text().catch(()=>"")).catch(()=>"");let f=await fetch(r,{method:"POST",headers:u,signal:i.signal,body:JSON.stringify({jsonrpc:"2.0",id:"guard-briefing",method:"tools/call",params:{name:e,arguments:t}})});if(!f.ok)return null;let h=(f.headers.get("content-type")??"").startsWith("text/event-stream")?await ub(f):await f.text();if(h.trim().length===0)return null;let g=JSON.parse(h);if(g.error||g.result?.isError)return null;let y=g.result?.content?.find(b=>b.type==="text"&&typeof b.text=="string")?.text;return typeof y=="string"&&y.trim().length>0?y:null}catch{return null}finally{clearTimeout(s)}}async function ub(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s="",a=o(()=>{if(i.length===0)return;let c=i.join(`
755
755
  `).trim();i=[],c.length>0&&(s=c)},"flush");for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
756
- `))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&i.push(p.slice(5).replace(/^\s/,""))}}return a(),s}var Ei,uN,An=_(()=>{"use strict";Ei="https://mcp.maind.dev/mcp",uN="2025-06-18";o(Io,"fetchSessionBriefing");o(ut,"fetchToolText");o(nb,"readSseMessage")});async function G(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=o(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function kr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Ie(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ge=_(()=>{"use strict";o(G,"readHookInput");o(kr,"transcriptPathOf");o(Ie,"toolFilePathOf")});import{existsSync as pN,readFileSync as fN}from"node:fs";import{join as Sd}from"node:path";function rb(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Ed(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function sb(e,t={}){return e.some(n=>Ed(Re(n,t,[ib])[0]))}function No(e,t){let n=Re(e,t,[ib])[0],r=Re(e,t,[mN])[0];return{channel:Ed(n)?"core":Ed(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function ob(e,t){let n=[Sd(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Sd(t,".claude","settings.json"),Sd(t,".claude","settings.local.json")),n.map(r=>{try{return pN(r)?fN(r,"utf8"):null}catch{return null}})}var ib,mN,Oo=_(()=>{"use strict";Mt();o(rb,"hookOf");ib=rb(Pt,Je),mN=rb(gr,"guard-inject");o(Ed,"isRunnable");o(sb,"coreBriefingWiredIn");o(No,"briefingChannel");o(ob,"claudeSettingsSources")});function ab(e){return e==="on"?!0:e==="off"?!1:null}function ie(e=process.env,t=Ce()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0,difficulty:ab(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:ab(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function Rn(e,t=je()){let n={};try{let i=await Z(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await V(t,JSON.stringify(r,null,2)+`
757
- `,384)}var Xe=_(()=>{"use strict";$t();_e();o(ab,"envSwitch");o(ie,"resolveGuardConfig");o(Rn,"writeGuardConfig")});function Po(e){if(!e)return null;let t=e.split(`
756
+ `))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let f=u.endsWith("\r")?u.slice(0,-1):u;if(f===""){a();continue}f.startsWith(":")||f.startsWith("data:")&&i.push(f.slice(5).replace(/^\s/,""))}}return a(),s}var Ti,RN,An=_(()=>{"use strict";Ti="https://mcp.maind.dev/mcp",RN="2025-06-18";o(Po,"fetchSessionBriefing");o(ft,"fetchToolText");o(ub,"readSseMessage")});async function W(){if(process.stdin.isTTY)return{};let e=[];return await new Promise(t=>{let n=!1,r=o(s=>{n||(n=!0,clearTimeout(i),t(s))},"settle"),i=setTimeout(()=>r({}),200);process.stdin.on("data",s=>e.push(s)),process.stdin.on("end",()=>{try{let s=Buffer.concat(e).toString("utf-8").trim();r(s?JSON.parse(s):{})}catch{r({})}}),process.stdin.on("error",()=>r({}))})}function Sr(e){return typeof e.transcript_path=="string"?e.transcript_path:""}function Ne(e){let t=e.tool_input;if(t===null||typeof t!="object")return"";let n=t.file_path;return typeof n=="string"?n:""}var ge=_(()=>{"use strict";o(W,"readHookInput");o(Sr,"transcriptPathOf");o(Ne,"toolFilePathOf")});import{existsSync as CN,readFileSync as IN}from"node:fs";import{join as Nd}from"node:path";function fb(e,t){let n=e.find(r=>r.subcommand===t);if(!n)throw new Error(`no hook for subcommand ${t}`);return n}function Od(e){return e.status==="ok"||e.status==="npx"||e.status==="legacy"}function mb(e,t={}){return e.some(n=>Od(Ce(n,t,[pb])[0]))}function Mo(e,t){let n=Ce(e,t,[pb])[0],r=Ce(e,t,[NN])[0];return{channel:Od(n)?"core":Od(r)&&t.guardMode!=="off"?"guard":"none",core:n,guard:r}}function hb(e,t){let n=[Nd(e,".claude","settings.json")];return t!==null&&t.length>0&&n.push(Nd(t,".claude","settings.json"),Nd(t,".claude","settings.local.json")),n.map(r=>{try{return CN(r)?IN(r,"utf8"):null}catch{return null}})}var pb,NN,$o=_(()=>{"use strict";Mt();o(fb,"hookOf");pb=fb(Pt,Ze),NN=fb(_r,"guard-inject");o(Od,"isRunnable");o(mb,"coreBriefingWiredIn");o(Mo,"briefingChannel");o(hb,"claudeSettingsSources")});function gb(e){return e==="on"?!0:e==="off"?!1:null}function se(e=process.env,t=Ie()){let n=e.MAIND_GUARD;return{mode:n==="off"||n==="warn"||n==="block"?n:t?.guard_mode??"off",stopGate:t?.guard_stop_gate===!0,difficulty:gb(e.MAIND_GUARD_DIFFICULTY)??t?.guard_difficulty!==!1,capture:gb(e.MAIND_GUARD_CAPTURE)??t?.guard_capture!==!1}}async function Rn(e,t=je()){let n={};try{let i=await Q(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await z(t,JSON.stringify(r,null,2)+`
757
+ `,384)}var Qe=_(()=>{"use strict";$t();_e();o(gb,"envSwitch");o(se,"resolveGuardConfig");o(Rn,"writeGuardConfig")});function Fo(e){if(!e)return null;let t=e.split(`
758
758
  `),n=t.findIndex(i=>i.startsWith("=== Project Conventions"));if(n<0)return null;let r=[];for(let i=n;i<t.length&&t[i].trim()!=="";i++)r.push(t[i]);return r.length>1?r.join(`
759
- `):null}function hN(e){let t=e.indexOf("{"),n=null;if(t>=0)try{n=JSON.parse(e.slice(t))}catch{n=null}if(n===null)return[{title:"Session briefing",lines:e.split(`
760
- `),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=o((s,a)=>(s??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function cb(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
761
- `);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...hN(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
762
-
763
- ${d.title}`;if(Do(c+u)>a){l=!1;break}c+=u;for(let p=0;p<d.lines.length;p++){let f=`
764
- ${d.lines[p]}`;if(Do(c+f)<=a){c+=f;continue}l=!1;let h=`
765
- (+${d.lines.length-p} more \u2014 via ${d.more})`;Do(c+h)<=r&&(c+=h);break}if(!l)break}if(!l){let d=`
766
- \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;Do(c+d)<=r&&(c+=d)}return{text:c+`
767
- `,complete:l}}var Do,Td=_(()=>{"use strict";Do=o(e=>Buffer.byteLength(e,"utf8"),"bytes");o(Po,"extractConventionsBlock");o(hN,"briefingSections");o(cb,"composeInjection")});import{mkdir as gN,readFile as yN,writeFile as _N,rename as bN}from"node:fs/promises";import{existsSync as db}from"node:fs";import{homedir as wN}from"node:os";import{join as ub}from"node:path";function lb(){return{config:null,sessions:{},pending_metrics:[]}}async function X(){if(!db(Mo))return lb();try{let e=await yN(Mo,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
768
- `),lb()}}async function Ze(e){db(pt)||await gN(pt,{recursive:!0,mode:448});let t=`${Mo}.tmp`;await _N(t,JSON.stringify(e,null,2),{mode:384}),await bN(t,Mo)}function Ad(e){return e.thresholds??e.config?.thresholds??vN}var pt,Mo,vN,Qe=_(()=>{"use strict";pt=ub(wN(),".maind"),Mo=ub(pt,"state.json"),vN={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};o(lb,"emptyState");o(X,"loadState");o(Ze,"saveState");o(Ad,"resolveThresholds")});import{existsSync as fb}from"node:fs";import{mkdir as kN,readFile as xN,readdir as SN,rename as EN,stat as TN,unlink as AN,writeFile as RN}from"node:fs/promises";import{join as Ti}from"node:path";function mb(e){return Ti(Rd,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function ft(e){try{let t=mb(e);if(!fb(t))return{};let n=JSON.parse(await xN(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function ye(e,t){await kN(Rd,{recursive:!0,mode:448});let n=mb(e),r=`${n}.tmp`;await RN(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await EN(r,n)}async function hb(e=7*24*60*60*1e3,t=Date.now()){await pb(Rd,".json",e,t),await pb(Cd,".jsonl",e,t)}async function pb(e,t,n,r){try{if(!fb(e))return;for(let i of await SN(e)){if(!i.endsWith(t))continue;let s=Ti(e,i);try{let a=await TN(s);r-a.mtimeMs>n&&await AN(s)}catch{}}}catch{}}var Ue,Rd,Cd,mt=_(()=>{"use strict";Qe();Ue=Ti(pt,"guard"),Rd=Ti(Ue,"sessions"),Cd=Ti(Ue,"triggers");o(mb,"sessionFile");o(ft,"loadGuardSession");o(ye,"saveGuardSession");o(hb,"sweepOldGuardSessions");o(pb,"sweepDir")});import{existsSync as CN}from"node:fs";import{appendFile as IN,mkdir as NN,open as ON}from"node:fs/promises";import{join as DN}from"node:path";async function J(e){try{await NN(Ue,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
769
- `;await IN(Cn,t,{mode:384})}catch{}}async function gb(e=256*1024){let t={inject_ok:0,inject_fail:0,warn:0,deny:0,override:0,stop_block:0,gate_override:0,cross_session_warn:0,cross_session_deny:0,difficulty_nudge:0,difficulty_deny:0,difficulty_resolved:0,capture_prompt:0,capture_taken:0};try{if(!CN(Cn))return t;let n=await ON(Cn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
770
- `);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Cn,ht=_(()=>{"use strict";mt();Cn=DN(Ue,"events.jsonl");o(J,"appendGuardEvent");o(gb,"readGuardEventCounts")});var vb={};Q(vb,{BRIEFING_CACHE_FILE:()=>xr,UNAVAILABLE_LINE:()=>bb,carriesBriefing:()=>_b,deliverSessionBriefing:()=>Lo,formatInjection:()=>wb,resolveBriefingInjection:()=>$o,runGuardInject:()=>WN,runsUnderCursor:()=>Ai});import{existsSync as PN}from"node:fs";import{mkdir as MN,readFile as $N,rename as LN,writeFile as FN}from"node:fs/promises";import{homedir as jN}from"node:os";import{dirname as UN,join as HN}from"node:path";async function $o(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??xr,s=n.fetcher??Io,a=await zN(i),c=a!==null&&a.format===yb&&r-Date.parse(a.fetched_at)<BN&&a.project_key===e,l=o(p=>p.conventions?{conventions:p.conventions}:{},"withConventions");if(c)return{text:a.text,via:"cache",...l(a)};let d=null,u=await s({onInitialize:o(p=>{d=Po(p)},"onInitialize"),apiKey:t,deviceId:YN(),projectKey:e,bridgeVersion:B,timeoutMs:GN});if(u!==null){let p=d;return await qN(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:yb,...p?{conventions:p}:{}}),{text:u,via:"fetch",...p?{conventions:p}:{}}}return a!==null?{text:a.text,via:"stale-cache",...l(a)}:{text:null,via:"none"}}async function WN(){try{if(ie().mode==="off")return 0;let t=await G();return sb(ob(jN(),VN(t)))?0:await Lo("guard",t)}catch{return 0}}function _b(e){return e==="resume"||e==="fork"}function Ai(e,t=process.env){let n=t.CURSOR_VERSION;return typeof n=="string"&&n.trim().length>0?!0:typeof e.cursor_version=="string"&&e.cursor_version.length>0}function KN(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Lo(e,t,n={}){let r=n.write??KN;if(Ai(t,n.env??process.env))return 0;let i=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(i===null)return 0;await hb();let s=typeof t.source=="string"?t.source:"startup";if(_b(s)){let h=await ft(i);return await ye(i,{...h,carryover:!0}),0}let a=(n.apiKey??q)();if(a===null)return 0;let c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=(n.projectKey??Y)(),d=await $o(l,a,n.inject),u=await ft(i);if(d.text===null)return await ye(i,{...u,inject_failed:!0}),await J({event:"inject_fail",session_id:i,cwd:c,project_key:l??void 0,...e==="core"?{detail:"core"}:{}}),await r(bb),0;let p=wb(d.text,d.via,d.conventions??null,e);await r(p.text),await ye(i,{...u,injected:!0});let f=p.complete?d.via:`${d.via}+budget`;return await J({event:"inject_ok",session_id:i,cwd:c,project_key:l??void 0,detail:e==="core"?`core:${f}`:f}),0}function VN(e){let t=process.env.CLAUDE_PROJECT_DIR;return typeof t=="string"&&t.trim().length>0?t.trim():typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:null}function wb(e,t,n=null,r="guard"){let i=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",s=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${s}, delivered by the bridge's session-start hook (ADR-359)${i} \u2014 `:`[maind guard] ${s}, injected deterministically (ADR-284)${i} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return cb(a,n,e)}async function zN(e){try{if(!PN(e))return null;let t=JSON.parse(await $N(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text,...typeof t.format=="number"?{format:t.format}:{},...typeof t.conventions=="string"&&t.conventions.length>0?{conventions:t.conventions}:{}}}catch{return null}}async function qN(e,t){try{await MN(UN(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await FN(n,JSON.stringify(t,null,2),{mode:384}),await LN(n,e)}catch{}}function YN(){try{return ne()}catch{return null}}var xr,BN,yb,GN,bb,Sr=_(()=>{"use strict";ue();ge();Oo();Fe();Le();Xe();Td();ht();mt();An();xr=HN(Ue,"briefing-cache.json"),BN=12*60*60*1e3,yb=2,GN=3e3;o($o,"resolveBriefingInjection");o(WN,"runGuardInject");o(_b,"carriesBriefing");o(Ai,"runsUnderCursor");o(KN,"writeStdout");o(Lo,"deliverSessionBriefing");bb=`[maind] Session briefing unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.
771
- `;o(VN,"projectDirOf");o(wb,"formatInjection");o(zN,"readCache");o(qN,"writeCache");o(YN,"safeDeviceId")});var Ib={};Q(Ib,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>Ab,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Eb,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Tb,AGENTS_MD_REFRESH_STATE_FILE:()=>Sb,gitToplevel:()=>Rb,loadConventionsForAgentsMd:()=>Fo,refreshAgentsMdConventions:()=>cO});import{execFileSync as JN}from"node:child_process";import{createHash as XN}from"node:crypto";import{mkdir as ZN,readFile as QN,realpath as eO,rename as tO,writeFile as nO}from"node:fs/promises";import{dirname as rO,isAbsolute as iO,join as xb,relative as sO,resolve as oO}from"node:path";async function Fo(e,t,n){if(e===null)return null;let r=await $o(t,e,{fetcher:n.allowFetch?i=>Io({...i,clientFamily:"codex"}):async()=>null});return r.text===null?null:r.conventions??null}async function cO(e,t){let n=t.err??(r=>process.stderr.write(`${r}
772
- `));try{if(e!=="codex")return{status:"skipped",reason:"family"};let r=t.env??process.env;if(dO(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),s=(t.gitToplevel??Rb)(i);if(s===null)return{status:"skipped",reason:"no-root"};let a=await kb(s),c=[];for(let k of await(t.findRoots??ro)(i)){let v=await kb(k);lO(v,a)&&!c.includes(v)&&c.push(v)}c.includes(a)||c.push(a);let l=null,d=null;for(let k of c){let v=xb(k,"AGENTS.md"),T=await Z(v);if(T!==null&&co(T,Sn)){l=v,d=T;break}}if(l===null||d===null)return uO(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${Sn}" header between the working directory and ${a} (the bridge never writes above the repository root)`),{status:"skipped",reason:"no-agents-md-in-repo"};let u=t.nowMs??Date.now(),p=t.stateFile??Sb,f=await fO(p),h=pO(l),g=f.roots[h]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Eb)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let b=await(t.loadConventions??((k,v)=>Fo(v,k,{allowFetch:!0})))(t.projectKey,t.apiKey);if(b===null||b.trim().length===0)return{status:"skipped",reason:"no-conventions"};let w=ao(b,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??B}),x=lo(d,w,Sn);if(x.outcome==="damaged")return n(`maind: AGENTS.md conventions block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and the bridge re-inserts the block`),{status:"skipped",reason:"damaged"};if(x.outcome==="no-header")return{status:"skipped",reason:"no-agents-md-in-repo"};if(x.changed&&await V(l,x.next),await mO(p,f,h,u),!x.changed)return{status:"unchanged",file:l};let S=Jy(w);return n(`maind: AGENTS.md conventions block refreshed (${S} conventions)`),{status:"refreshed",file:l,conventions:S,inserted:x.outcome==="inserted"}}catch(r){let i=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md conventions block not refreshed \u2014 ${i}`),{status:"failed",error:i}}}function Rb(e){try{let t=JN("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function lO(e,t){let n=sO(t,e);return n===""||!n.startsWith("..")&&!iO(n)}async function kb(e){try{return await eO(e)}catch{return oO(e)}}function dO(e){return Cb(e[Tb])}function uO(e){return Cb(e[Ab])}function Cb(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function pO(e){return XN("sha256").update(e).digest("hex")}async function fO(e){let t={version:1,roots:{}};try{let n=JSON.parse(await QN(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[i,s]of Object.entries(n.roots))s&&typeof s.checked_at=="string"&&(r[i]={checked_at:s.checked_at});return{version:1,roots:r}}catch{return t}}async function mO(e,t,n,r){let i={};for(let[a,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<aO&&(i[a]=c)}i[n]={checked_at:new Date(r).toISOString()},await ZN(rO(e),{recursive:!0,mode:448});let s=`${e}.${process.pid}.tmp`;await nO(s,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await tO(s,e)}var Sb,Eb,Tb,Ab,aO,Id=_(()=>{"use strict";An();Sr();mt();td();_e();nd();Yl();Le();Sb=xb(Ue,"agents-md-refresh.json"),Eb=12*60*60*1e3,Tb="MAIND_NO_AGENTS_MD_REFRESH",Ab="MAIND_DEBUG",aO=30*24*60*60*1e3;o(Fo,"loadConventionsForAgentsMd");o(cO,"refreshAgentsMdConventions");o(Rb,"gitToplevel");o(lO,"isWithin");o(kb,"realpathOrResolve");o(dO,"isOptedOut");o(uO,"isDebug");o(Cb,"isSet");o(pO,"fileKey");o(fO,"readState");o(mO,"writeState")});import{mkdirSync as Lb,rmdirSync as Fb,statSync as bO}from"node:fs";import{join as jb}from"node:path";import{setTimeout as wO}from"node:timers/promises";function Ub(e){return jb(e,".maind","index-refresh.lock")}function Ho(e,t=Date.now()){let n=Ub(e);try{if(t-bO(n).mtimeMs<vO)return!1;Fb(n)}catch{}try{return Lb(n,{recursive:!1}),!0}catch{return!1}}function Ri(e){try{Fb(Ub(e))}catch{}}async function Hb(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(a=>wO(a).then(()=>{})),s=r()+(n.waitMs??3e4);try{Lb(jb(e,".maind"),{recursive:!0})}catch{}for(;!Ho(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Ri(e)}}var vO,Nd=_(()=>{"use strict";vO=30*6e4;o(Ub,"lockPath");o(Ho,"acquireLock");o(Ri,"releaseLock");o(Hb,"withIndexLock")});import{execFile as rw}from"node:child_process";import{randomUUID as WO}from"node:crypto";function JO(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Ld.test(t)?t:WO()}function Fd(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function XO(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function ZO(e){return await new Promise(t=>{rw("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(QO(r))})})}function QO(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function eD(){return await new Promise(e=>{rw("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8"},(t,n)=>{if(t)return e(null);let r=n.trim();e(r.length>0&&r!=="HEAD"?r:null)})})}function tD(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function nD(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Ld.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(s=>{Ld.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var nw,iw,KO,VO,zO,qO,YO,Ld,Ko,jd=_(()=>{"use strict";$t();nw=45e3,iw=3e4,KO=5,VO=120,zO=3e4,qO=15*6e4,YO=1500,Ld=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(JO,"resolveClientSessionId");o(Fd,"autoAnnounceDisabled");o(XO,"autoWorkingPathsEnabled");Ko=class{static{o(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??Ce)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??eD,this.gitBranchObject=t.gitBranchObject??ZO,this.log=t.log??(i=>process.stderr.write(i+`
773
- `)),this.machineLabel=tD(r?.machine_label),this.enabled=this.projectKey!==null&&!Fd(n,r),this.workingPathsEnabled=XO(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??nD(n,JO(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<nw||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<nw||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<KO||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,YO).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(zO*2**(this.consecutiveFailures-1),qO);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let s=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${s} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:VO,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let a=await this.gitBranchObject(s);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};o(ZO,"defaultGitBranchObject");o(QO,"normalizeObjectId");o(eD,"defaultGitBranch");o(tD,"normalizeMachineLabel");o(nD,"staticIdentity")});import{mkdirSync as sw,readdirSync as lw,readFileSync as rD,renameSync as ow,statSync as iD,unlinkSync as Ud,writeFileSync as aw}from"node:fs";import{homedir as sD}from"node:os";import{join as Er}from"node:path";function dw(){return Er(sD(),".maind","presence")}function uw(e,t){return Er(e,t)}function pw(e){let t=e.baseDir??dw(),n=uw(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=o(d=>{if(c!==null&&c!==d)try{Ud(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let p=d;if(p.ok!==!0)return;let f={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:Array.isArray(p.peers)?p.peers:[],conflicts:Array.isArray(p.conflicts)?p.conflicts:[],...(()=>{let y=Zi(p.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};sw(n,{recursive:!0,mode:448});let h=Er(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;aw(g,JSON.stringify(f),{mode:384}),ow(g,h),l(h),cw(n,a(),h)}catch{}},endSession(){try{c&&Ud(c)}catch{}},markFailed(d,u){try{let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};sw(n,{recursive:!0,mode:448});let f=Er(n,`${u.sessionId}.json`),h=`${f}.tmp-${r}`;aw(h,JSON.stringify(p),{mode:384}),ow(h,f),l(f),cw(n,a(),f)}catch{}}}}function cw(e,t,n){try{for(let r of lw(e)){if(!r.endsWith(".json"))continue;let i=Er(e,r);if(i!==n)try{t-iD(i).mtimeMs>oD&&Ud(i)}catch{}}}catch{}}function On(e,t=dw()){try{let n=uw(t,e),r=[];for(let i of lw(n))if(i.endsWith(".json"))try{let s=JSON.parse(rD(Er(n,i),"utf8")),a=aD(s);a&&r.push(a)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function aD(e){if(typeof e!="object"||e===null)return null;let t=e;return t.v!==1||typeof t.written_at!="string"||typeof t.project_key!="string"||typeof t.own_session_id!="string"||typeof t.own_pid!="number"||typeof t.own_ppid!="number"||typeof t.cwd!="string"?null:{v:1,written_at:t.written_at,project_key:t.project_key,own_session_id:t.own_session_id,own_pid:t.own_pid,own_ppid:t.own_ppid,cwd:t.cwd,branch:typeof t.branch=="string"?t.branch:null,peers:Array.isArray(t.peers)?t.peers:[],conflicts:Array.isArray(t.conflicts)?t.conflicts:[],...typeof t.announce_error=="string"?{announce_error:t.announce_error}:{},...(()=>{let n=Zi(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var oD,Vo=_(()=>{"use strict";jr();oD=120*6e4;o(dw,"presenceSnapshotBaseDir");o(uw,"projectDir");o(pw,"createSnapshotStore");o(cw,"pruneStale");o(On,"readSnapshots");o(aD,"parseSnapshot")});import{execFileSync as cD}from"node:child_process";import{createHash as lD,randomUUID as dD}from"node:crypto";import{existsSync as uD,mkdirSync as pD,readdirSync as fD,readFileSync as mw,renameSync as mD,statSync as Hd,unlinkSync as hw,writeFileSync as hD}from"node:fs";import{homedir as gD}from"node:os";import{basename as yD,join as Gt}from"node:path";function Tr(e){return Gt(e??Gt(gD(),".maind","presence"),"identity")}function Ii(e,t){if(e){let n=yD(e).replace(/\.jsonl$/i,"");if(Ci.test(n))return n.toLowerCase()}return t&&Ci.test(t)?t.toLowerCase():null}function gw(e){let t=e.nowMs??Date.now();pD(e.dir,{recursive:!0,mode:448});let n=Gt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(mw(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...a?{model:a}:{}};hD(r,JSON.stringify(c,null,2)+`
774
- `,{mode:384}),mD(r,n),kD(e.dir,t)}function yw(e,t,n,r=Date.now()){try{let i=Hd(Gt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function _w(e,t){try{hw(Gt(e,`${t}.json`))}catch{}}function kD(e,t){try{for(let n of fD(e))if(n.endsWith(".json"))try{let r=Hd(Gt(e,n));t-r.mtimeMs>bD&&hw(Gt(e,n))}catch{}}catch{}}function xD(e){return bw(e)?.file??null}function bw(e){let t=Gt(e.dir,`${e.agentPid}.json`);try{if(!uD(t))return null;let n=Hd(t);if(n.mtimeMs<e.bridgeStartMs-wD)return null;let r=JSON.parse(mw(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Ci.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!SD(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function fw(e){return e.replace(/\/+$/,"")}function SD(e,t){let n=fw(e),r=fw(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function ED(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=lD("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function TD(e){if(process.platform==="win32")return null;try{let t=cD("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function AD(){try{return ne()}catch{return null}}var Ci,_D,bD,wD,vD,zo,qo=_(()=>{"use strict";ue();Ci=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_D=8,bD=48*60*6e4,wD=6e4,vD="9f3c72da-2f10-4b8f-9c31-ad291c0de291";o(Tr,"identityDirPath");o(Ii,"transcriptStemOf");o(gw,"writeAgentIdentityFile");o(yw,"identityFileStale");o(_w,"deleteAgentIdentityFile");o(kD,"pruneIdentityDir");o(xD,"readAgentIdentityFile");o(bw,"readAgentIdentityEntry");o(fw,"normDir");o(SD,"sameSessionTree");o(ED,"uuidV5");o(TD,"processStartTime");zo=class{static{o(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??Tr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Ci.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??AD)(),s=(t.ppidStart??TD)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=ED(`${i}|${this.agentPid}|${s}|${t.projectKey}`,vD),this.source="derived";return}this.id=dD(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){return this.resync()!=="unchanged"}resync(){let t=this.readStem();if(t===null)return"unchanged";if(this.source==="client_native")return t===this.stem?"unchanged":(this.id=t,this.stem=t,this.aliases=this.envId!==null&&this.envId!==t?[this.envId]:[],"switched");if(t===this.id)return"unchanged";let n=this.id;return this.id=t,this.stem=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),"upgraded"}adopt(t){let n=t.trim().toLowerCase();if(!Ci.test(n)||n===this.id)return;let r=this.id;this.id=n,!(this.source==="client_native"&&r===this.stem)&&this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>_D&&this.aliases.shift())}activityAtMs(){return bw({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return xD({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};o(AD,"defaultDeviceId")});function Bd(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Gd=_(()=>{"use strict";o(Bd,"newModeState")});import{createReadStream as RD,existsSync as CD}from"node:fs";import{stat as ID}from"node:fs/promises";import{createInterface as ND}from"node:readline";async function Wd(e){if(!e||!CD(e))return null;let t;try{t=await ID(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(a=>{let c=RD(e,{encoding:"utf-8"}),l=ND({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;try{let p=JSON.parse(u),f=p.message?.usage;if(!f)return;let h=typeof p.message?.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=h??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof f.input_tokens=="number"&&(r+=f.input_tokens),typeof f.output_tokens=="number"&&(i+=f.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var ww=_(()=>{"use strict";o(Wd,"summariseTranscript")});var vw=_(()=>{"use strict"});function Ni(e){if(!e)return null;let t=null;for(let n of e.matchAll(DD)){let r=n[1].toLowerCase();OD.has(r)&&(t=r)}return t}var OD,DD,Yo=_(()=>{"use strict";OD=new Set(["low","medium","high","xhigh","max"]),DD=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;o(Ni,"detectEffortLevel")});import{createReadStream as PD,existsSync as MD,readdirSync as $D}from"node:fs";import{basename as Sw,dirname as LD,join as kw}from"node:path";import{createInterface as FD}from"node:readline";function Ar(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function HD(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=UD[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function Jo(e){let t=Sw(e).replace(/\.jsonl$/,""),n=kw(LD(e),t,"subagents"),r;try{r=$D(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>kw(n,i))}async function xw(e,t,n,r,i){MD(e)&&await new Promise(s=>{let a=PD(e,{encoding:"utf-8"}),c=FD({input:a}),l=0;c.on("line",d=>{l++;let u=d.trim();if(!u)return;let p;try{p=JSON.parse(u)}catch{return}if(p.message?.role!=="assistant")return;let f=typeof p.message.id=="string"&&p.message.id?p.message.id:null,h=typeof p.requestId=="string"&&p.requestId?p.requestId:null,g=f??h??`${e}#${l}`,y=HD(p.message.content),b=r.get(g);if(b){for(let v of y)b.edited_paths.includes(v)||b.edited_paths.push(v);return}if(n.has(g))return;n.add(g);let w=p.message.usage??{},x=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,S=typeof p.message.model=="string"&&p.message.model?p.message.model:"",k={ts:Number.isFinite(x)?x:0,model:S||"<unknown>",synthetic:S===jD,input_tokens:Ar(w.input_tokens),output_tokens:Ar(w.output_tokens),cache_read_tokens:Ar(w.cache_read_input_tokens),cache_creation_tokens:Ar(w.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Ar(w.cache_creation?.ephemeral_1h_input_tokens),Ar(w.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:y,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(g,k),i.push(k)}),c.on("close",()=>s()),c.on("error",()=>s()),a.on("error",()=>s())})}function Kd(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function Oi(e){let t=new Set,n=new Map,r=[],i=e?Jo(e):[];if(!e)return{turns:r,subagent_files:i};let s=[];await xw(e,Dn,t,n,s),Kd(s),r.push(...s);for(let a of i){let c=[],l=Sw(a).replace(/\.jsonl$/,"");await xw(a,l,t,n,c),Kd(c);for(let d of c)d.sidechain=!0;r.push(...c)}return{turns:r,subagent_files:i}}var Dn,jD,UD,Xo=_(()=>{"use strict";Dn="main",jD="<synthetic>",UD={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};o(Ar,"num");o(HD,"editedPathsOf");o(Jo,"subagentFilesOf");o(xw,"readStream");o(Kd,"fillTimestamps");o(Oi,"collectTurns")});import{createReadStream as Ew,existsSync as BD}from"node:fs";import{createInterface as Tw}from"node:readline";function YD(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,a=e.get(s);if(!a){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function Zo(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function JD(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
775
- `)}function XD(e,t){let n=o(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)a.has(l)&&c++;return c/s.size>=.8}function ZD(e,t,n){return GD.test(e)?{polarity:-1,magnitude:Rr.rework,kind:"rework"}:n&&WD.test(e)?{polarity:-1,magnitude:Rr.correction,kind:"correction"}:KD.test(e)?{polarity:1,magnitude:Rr.acceptance,kind:"acceptance"}:t!==null&&XD(t,e)?{polarity:-1,magnitude:Rr.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function QD(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Aw,behaviour_measured:!0}}async function eP(e,t){for(let n of Jo(e))await new Promise(r=>{let i=Tw({input:Ew(n,{encoding:"utf-8"})});i.on("line",s=>{let a=s.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of Zo(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(Qo))continue;let d=l.name.slice(Qo.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Vd(e,t={}){let n=QD("");if(!e||!BD(e))return n;let r=t.turns??(await Oi(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let i=[],s=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=Ew(e,{encoding:"utf-8"}),y=Tw({input:g}),b=o(w=>{let x=w.trim();if(!x)return;let S;try{S=JSON.parse(x)}catch{return}if(n.lines_seen++,!n.session_id){let U=S.sessionId??S.session_id;typeof U=="string"&&U&&(n.session_id=U)}S.type==="ai-title"&&typeof S.aiTitle=="string"&&S.aiTitle&&(n.ai_title=S.aiTitle),typeof S.slug=="string"&&S.slug&&(n.session_slug=S.slug);let k=S.message?.role,v=S.isSidechain===!0;if(k==="assistant")for(let U of Zo(S.message?.content)){if(U.type!=="tool_use"||typeof U.name!="string"||!U.name.startsWith(Qo))continue;let ae=U.name.slice(Qo.length);ae&&(n.maind_tool_calls??={},n.maind_tool_calls[ae]=(n.maind_tool_calls[ae]??0)+1)}if(v)return;if(k==="assistant"){let U=Zo(S.message?.content),ae=!1;for(let yt of U)yt.type==="tool_use"&&(n.tool_calls++,ae=!0,yt.name==="AskUserQuestion"&&n.agent_questions++);c=ae;return}if(k!=="user")return;let T=Zo(S.message?.content),O=JD(T);if(O.includes(VD)){n.interrupts++,i.push({polarity:-1,magnitude:Rr.interrupt,kind:"interrupt"});return}if(T.some(U=>U.type==="tool_result"&&U.is_error===!0&&typeof U.content=="string"&&U.content.includes(zD))){n.tool_denials++,i.push({polarity:-1,magnitude:Rr.denial,kind:"denial"});return}if(T.some(U=>U.type==="tool_result")||!O.trim())return;n.user_turns++,n.user_chars+=O.length;let H=Ni(O);H&&(a=H);let N=ZD(O,l,c);l=O,N.kind==="correction"?n.corrections++:N.kind==="rework"?n.reworks++:N.kind==="repeat"?n.repeated_instructions++:N.kind==="acceptance"&&n.acceptances++,N.polarity!==0&&i.push(N),c=!1},"processLine");y.on("line",w=>{try{b(w)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await eP(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||YD(s,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...s.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,p=0,f=[];return i.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*qD+h.polarity*h.magnitude;let y=Number(u.toFixed(3));f.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),p+=y,g>0&&i[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=f,n.momentum_final=f.length?f[f.length-1].value:0,n.momentum_auc=Number(p.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var Qo,Aw,GD,WD,KD,VD,zD,qD,Rr,Rw=_(()=>{"use strict";Yo();Xo();Qo="mcp__maind__",Aw="2026-10-01",GD=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,WD=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,KD=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,VD="[Request interrupted by user",zD="The user doesn't want to proceed with this tool use",qD=.7,Rr={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(YD,"bumpModel");o(Zo,"asBlocks");o(JD,"textOf");o(XD,"isRepeat");o(ZD,"classifyGenuine");o(QD,"emptyAnalysis");o(eP,"tallySubagentMaindCalls");o(Vd,"analyzeSession")});function zd(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function qd(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function Yd(e,t,n,r="unknown",i){let s={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};return t&&t.started_at&&(s.session_span=n?{...t,...n}:t),s}var Cw=_(()=>{"use strict";o(zd,"parseIngestResponse");o(qd,"describeSliceVerdict");o(Yd,"ingestBody")});import{homedir as tP}from"node:os";import{join as nP}from"node:path";var rP,Jd=_(()=>{"use strict";rP=nP(tP(),".codex","sessions")});var Iw=_(()=>{"use strict";Jd()});import{isAbsolute as Qd,relative as sP,resolve as Nw,sep as eu}from"node:path";function Ow(e){return e>ta[1]?"above_272k":e>ta[0]?"band_200k_272k":"standard"}function Dw(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function ea(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function tu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=o(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let d=l,u=ea(d.from);typeof d.object_id!="string"||!Xd.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:ea(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=ea(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:ea(c.to)})}let s=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!Xd.test(c.object_id)||typeof c.path_prefix=="string"&&s.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&Xd.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:s}}function Pw(e,t){if(!Qd(e))return null;let n=sP(Nw(t),Nw(e));return!n||n==="."||n.startsWith("..")||Qd(n)?null:eu==="/"?n:n.split(eu).join("/")}function aP(e,t){return t===""||e===t||e.startsWith(t+"/")}function nu(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Mw(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function ru(e,t){for(let n of Mw(t))if(aP(e,n.path_prefix))return n.object_id;return null}function cP(e,t){for(let n of Mw(t))if(nu(e,n.path_prefix))return n.object_id;return null}function Zd(e,t){return e>=t.from&&(t.to===null||e<t.to)}function $w(e,t,n,r){let i=e.ts,s=r?.anchors??[],a=t.map(c=>ru(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>Zd(i,u));if(c.length)return c.sort((u,p)=>p.from-u.from||u.object_id.localeCompare(p.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>Zd(i,u));if(l.length)return{object_id:(l.find(p=>a.includes(p.object_id))??l.find(p=>n!==null&&p.object_id===n.object_id)??[...l].sort((p,f)=>p.object_id.localeCompare(f.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>Zd(i,u));if(d.length){let u=t[0]??n?.rel??null,p=(u===null?d:d.filter(f=>nu(f.path_prefix,u))).sort((f,h)=>h.path_prefix.length-f.path_prefix.length);for(let f of p){let h=cP(f.path_prefix,s);if(h)return{object_id:h,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function iu(e,t,n){let r=t?.anchors??[],i=o(g=>{if(!n.repoRoot)return[];let y=[];for(let b of g.edited_paths){let w=Pw(b,n.repoRoot);w!==null&&!y.includes(w)&&y.push(w)}return y},"relOf"),s=o(g=>{for(let y of g){let b=ru(y,r);if(b)return{object_id:b,rel:y}}return null},"firstAnchoredEdit"),a=new Map;for(let g of e){let y=a.get(g.stream)??[];y.push(g),a.set(g.stream,y)}let c=[...a.entries()].sort(([g],[y])=>g===Dn?-1:y===Dn?1:0),l=[],d=o(g=>{let y=null;for(let b of l){if(b.ts>g&&g>0)break;y=b.seg}return y},"mainSegmentAt"),u=new Map;for(let[g,y]of c){let b=y.map((x,S)=>({t:x,i:S,rels:i(x)})).sort((x,S)=>x.t.ts-S.t.ts||x.i-S.i),w=null;for(let x of b){let S=s(x.rels);if(S){w=S;break}}!w&&g!==Dn&&b.length&&(w=d(b[0].t.ts));for(let x of b){let S=s(x.rels);S&&(w=S),g===Dn&&l.push({ts:x.t.ts,seg:w});let k=x.t;if(k.input_tokens+k.output_tokens+k.cache_read_tokens+k.cache_creation_tokens===0)continue;let T=$w(k,x.rels,w,t),O=Ow(k.input_tokens+k.cache_read_tokens+k.cache_creation_tokens),j=Dw(k.model),H=`${T.object_id??""}|${T.source}|${j}|${O}`,N=u.get(H);N||(N={object_id:T.object_id,attribution_source:T.source,model:j,context_tier:O,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},u.set(H,N)),N.input_tokens+=k.input_tokens,N.output_tokens+=k.output_tokens,N.cache_read_tokens+=k.cache_read_tokens,N.cache_creation_tokens+=k.cache_creation_tokens,N.cache_creation_1h_tokens+=k.cache_creation_1h_tokens,N.turns+=1,k.ts>0&&((N.firstMs===0||k.ts<N.firstMs)&&(N.firstMs=k.ts),k.ts>N.lastMs&&(N.lastMs=k.ts))}}let p=n.nowMs??Date.now(),f=[];for(let g of u.values()){let{firstMs:y,lastMs:b,...w}=g;w.first_ts=new Date(y>0?y:p).toISOString(),w.last_ts=new Date(b>0?b:p).toISOString(),f.push(w)}let h={lease:0,binding:1,claim:2,path:3,none:4};return f.sort((g,y)=>h[g.attribution_source]-h[y.attribution_source]||(g.object_id??"").localeCompare(y.object_id??"")||g.model.localeCompare(y.model)||g.context_tier.localeCompare(y.context_tier)),f}function su(e,t){let n=new Map;for(let s of e){let a=new Set;for(let c of s.edited_paths){if(!Qd(c))continue;let l=t(lP(c));l&&a.add(l)}for(let c of a)n.set(c,(n.get(c)??0)+1)}let r=null,i=0;for(let[s,a]of n)(a>i||a===i&&r!==null&&s.length>r.length)&&(r=s,i=a);return r}function lP(e){let t=e.split(eu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}var ta,oP,Xd,Lw=_(()=>{"use strict";Xo();ta=[2e5,272e3];o(Ow,"contextTierOf");o(Dw,"normalizeModelId");oP=ta[0],Xd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(ea,"msOf");o(tu,"parseCostContext");o(Pw,"toRepoRelative");o(aP,"underPrefix");o(nu,"prefixesOverlap");o(Mw,"sortedAnchors");o(ru,"anchorFor");o(cP,"bestAnchorOverlapping");o(Zd,"inWindow");o($w,"assignTurn");o(iu,"sliceSession");o(su,"dominantCheckoutRoot");o(lP,"dirOf")});var Fw=_(()=>{"use strict"});import{createReadStream as dP,existsSync as uP}from"node:fs";import{createInterface as pP}from"node:readline";function jw(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function hP(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
776
- `)}function Bw(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function gP(e){let t=e.message?.role;if(t==="assistant")return{holder:jw(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=jw(e.message?.content),r=hP(n);return r.includes(fP)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(mP))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function ou(e){let t=Bw("");if(!e||!uP(e))return t;let n=null,r=0,i=0,s=null,a="human",c=[];return await new Promise(l=>{let d=dP(e,{encoding:"utf-8"}),u=pP({input:d}),p=o(f=>{let h=f.trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{return}if(!t.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(t.session_id=w)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||s!==null&&y<s)return;let b=gP(g);if(b!==null){if(t.event_count++,b.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;a==="agent"?i+=w:w>=Uw*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<Hw&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=y,a=b.holder}},"processLine");u.on("line",f=>{try{p(f)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var fP,mP,Uw,Hw,Gw=_(()=>{"use strict";fP="[Request interrupted by user",mP="The user doesn't want to proceed with this tool use",Uw=60,Hw=200;o(jw,"asBlocks");o(hP,"textOf");o(Bw,"emptySpan");o(gP,"classify");o(ou,"analyzeSpan")});import{createReadStream as yP,existsSync as _P}from"node:fs";import{createInterface as bP}from"node:readline";function vP(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function na(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function kP(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
777
- `)}return""}async function au(e,t={}){if(!e||!_P(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Bd(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:Bd(),a=t.start??0;return await new Promise(c=>{let l=yP(e,{encoding:"utf-8",start:t.start??0}),d=bP({input:l});d.on("line",p=>{a+=Buffer.byteLength(p,"utf-8")+1;let f=p.trim();if(!f)return;let h;try{h=JSON.parse(f)}catch{return}let g=h.sessionId??h.session_id??"",y=h.timestamp?Date.parse(h.timestamp):Date.now(),b=h.message?.role;if(h.type==="ai-title"&&typeof h.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:h.aiTitle});return}if(h.type==="attachment"&&h.attachment?.type){let w=wP[h.attachment.type];w&&(s[vP(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(b==="user"){let w=kP(h.message?.content),x=Ni(w);x&&(i=x);let S={session_id:g,ts:y,text:w,effort_directive:x};n.push({kind:"user",...S});return}if(b==="assistant"){let w=h.message?.usage,x=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,S=typeof h.requestId=="string"&&h.requestId?h.requestId:null,k=x??S,v=k!==null&&r.has(k);k!==null&&!v&&r.add(k);let T={session_id:g,ts:y,model:h.message?.model??null,input_tokens:v?0:na(w?.input_tokens),output_tokens:v?0:na(w?.output_tokens),cache_read_input_tokens:v?0:na(w?.cache_read_input_tokens),cache_creation_input_tokens:v?0:na(w?.cache_creation_input_tokens),effort:i,isSidechain:h.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...T})}});let u=o(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var wP,Ww=_(()=>{"use strict";Yo();Gd();wP={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};o(vP,"modeFlagKey");o(na,"num");o(kP,"extractUserText");o(au,"streamTranscript")});var Kw=_(()=>{"use strict"});import{homedir as xP}from"node:os";import{join as SP}from"node:path";function lu(e){return e.replace(/[/.]/g,"-")}var EP,cu,Vw=_(()=>{"use strict";EP=xP(),cu=SP(EP,".claude","projects");o(lu,"projectPathFromCwd")});var Cr=_(()=>{"use strict";Gd();ww();vw();Rw();Cw();Xo();Jd();Iw();Lw();Fw();Gw();Ww();Yo();Kw();Vw()});import{parse as PP}from"jsonc-parser";function du(e,t){let n=e.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0);for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function pu(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!a)return null;let c=/^\s*command\s*=\s*"([^"]*)"/m.exec(a[1]),l=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(a[1]);return c?{command:c[1],args:l?[...l[1].matchAll(/"([^"]*)"/g)].map(d=>d[1]):[]}:null}let t=[],n=PP(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,i=r.servers?.maind??r.mcpServers?.maind,s=i?.transport??i;return!s||typeof s.command!="string"?null:{command:s.command,args:Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[]}}function Ir(e,t){let n=`npm i -g ${Nr}@${e}`;return t?`nvm use ${t} && ${n}`:n}function ia(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(p=>p.bridgeVersion).filter(p=>p!==null)],r=e.latestVersion??n.sort(du).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(p=>p.bridgeVersion!==null);if(e.nodeTrees.length>0){let p=e.pathWinner?.node??null,f=e.nodeTrees.find(g=>g.node===p);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):f&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${f.node} tree (${f.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let g=e.nodeTrees.find(y=>y.node===e.nvmDefault);g&&g.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${g.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Ir(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>du(y.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${g.node} carries bridge ${g.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Ir(r,g.node)})}let s=!1,a=new Map,c=o((p,f)=>{let h=a.get(p)??{version:e.installVersionOf(p),clients:[]};h.clients.push(f),a.set(p,h)},"noteInstall");for(let p of e.clientConfigs){let f=pu(p);if(f===null)continue;if(p.present===!1){t.push({check:"client-config",level:"warn",message:`${p.label}: ${p.path} names maind, but the client is not installed \u2014 nothing reads this file (a leftover of an earlier install).`,fix:"maind-mcp-bridge doctor --remove-phantoms"});continue}if(s=!0,/(^|\/)npx(\.cmd)?$/.test(f.command)&&f.args.some(y=>y.includes(Nr))){t.push({check:"client-config",level:"warn",message:`${p.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${Ir(r)}, then set "command": "maind-mcp-bridge" (no args) in ${p.path}`});continue}let g=/(^|[\\/])node(\.exe)?$/.test(f.command);if(g&&f.args.length>0){let y=f.args[0];if(!e.fileExists(y)){t.push({check:"client-config",level:"error",message:`${p.label} runs ${y}, which does not exist.`,fix:`re-run \`npx -y ${Nr}@${r} install\` to rewrite the entry`});continue}c(y,p.label)}else if(f.command.includes("/")||f.command.includes("\\")){if(!e.fileExists(f.command)){t.push({check:"client-config",level:"error",message:`${p.label} points at ${f.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${p.path} (after ${Ir(r)})`});continue}}else if(f.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${p.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Ir(r,e.nvmDefault)});continue}g||(f.command.includes("/")||f.command.includes("\\")?c(f.command,p.label):f.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,p.label)),t.push({check:"client-config",level:"ok",message:`${p.label}: ${[f.command,...f.args].join(" ")}`})}if(s||t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${Nr} install`}),e.latestVersion!==null)for(let[p,f]of a){let h=f.clients.join(", ");if(f.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${p} is.`});else if(du(f.version,e.latestVersion)<0){let g=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(p)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${f.version} (${p}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:g?Ir(e.latestVersion,g):`npx -y ${Nr}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${f.version} (published: ${e.latestVersion}).`})}for(let{dir:p,maind:f}of e.npxStaleDirs)t.push({check:"npx-cache",level:f?"error":"info",message:f?`a half-built better-sqlite3 was left in ${p} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${p} (another tool's npx entry, not maind's).`,fix:`rm -rf '${p.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!Yw.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),l===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):MP.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&Yw.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;if(d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let p=Re(e.claudeSettings,{fileExists:o(h=>e.fileExists(h),"fileExists")}),f=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of p){if(h.status==="missing")continue;if(h.status!=="ok"){t.push({check:"hooks",level:h.status==="broken"?"error":"warn",message:h.detail});continue}let g=h.command?/(\S+\/build\/index\.js)/.exec(h.command)?.[1]??null:null,y=g?e.installVersionOf(g):null;y!==null&&f!==null&&y!==f&&t.push({check:"hooks",level:"warn",message:`${h.event}/${h.subcommand} runs bridge ${y}, the MCP server runs ${f} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}t.some(h=>h.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}if(e.claudeSettings!==null){let p=e.guardMode??"off",f=No(e.claudeSettings,{guardMode:p,fileExists:o(b=>e.fileExists(b),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Nr}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(Je);f.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${Je} hook).`}):f.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${Je} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):f.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${p}); without the core ${Je} hook it stops when the guard is switched off.`,fix:g}):y?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${Je} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:g}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${Je}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:g})}let u=e.context??null;if(u!==null&&e.claudeSettings!==null){let p=Re(e.claudeSettings,{fileExists:o(f=>e.fileExists(f),"fileExists")}).filter(f=>(f.subcommand==="on-prompt-context"||f.subcommand==="on-read-context")&&f.status!=="missing").map(f=>f.subcommand);if(p.length>0){let f=t.length;u.sqlite.ok?u.repoRoot!==null&&!u.indexPresent&&t.push({check:"context",level:"info",message:`${u.repoRoot} has no code index \u2014 on-read-context stays silent there, and on-prompt-context can only match conventions.`,fix:"ask your agent to run codebase_index once (or run `maind index` in the repo); the Stop hook keeps it fresh after that"}):t.push({check:"context",level:"warn",message:`${p.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${u.sqlite.reason}). They stay silent.`,fix:"update Node to >= 22.16 (builtin SQLite), or run `npm rebuild better-sqlite3` in the bridge's install prefix"}),p.includes("on-prompt-context")&&u.repoRoot!==null&&!u.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${u.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===f&&t.push({check:"context",level:"ok",message:`${p.join(" and ")}: code index and cached conventions present${u.repoRoot?` for ${u.repoRoot}`:""}.`})}}return t}function Jw(e){let t=e.filter(i=>i.level==="error"&&uu.includes(i.check)).sort((i,s)=>uu.indexOf(i.check)-uu.indexOf(s.check)),n=t[0];if(n===void 0)return $P(e);let r=t.length>1?` ${t.length-1} more finding(s).`:"";return`[maind] setup problem \u2014 ${n.message}`+(n.fix?` Fix: ${n.fix}.`:"")+r+" All findings with fixes: `maind-mcp-bridge doctor` (or `npx -y @maind-dev/mcp-bridge doctor`)."}function $P(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?null:`[maind] setup gap \u2014 ${t.message} Call get_session_briefing now to load them.`+(t.fix?` To add the hook, run in a terminal (append-only, asks consent per hook): ${t.fix}`:"")}function Xw(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),i=e.filter(a=>a.level==="error").length,s=e.filter(a=>a.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
759
+ `):null}function ON(e){let t=e.indexOf("{"),n=null;if(t>=0)try{n=JSON.parse(e.slice(t))}catch{n=null}if(n===null)return[{title:"Session briefing",lines:e.split(`
760
+ `),more:"get_session_briefing"}];let r=[];n.setup_advisory!==null&&n.setup_advisory!==void 0&&r.push({title:"Setup advisory (first session)",lines:[JSON.stringify(n.setup_advisory)],more:"get_agent_setup_guide"});let i=o((s,a)=>(s??[]).map(a).filter(c=>c!==null),"list");return r.push({title:"Top lessons for this session",lines:i(n.briefing,s=>s.title?`- ${s.title}${s.id?` (${s.id})`:""}${s.summary?` \u2014 ${s.summary}`:""}`:null),more:"get_lesson(id)"},{title:"Skills (activate_skill(id) when a task matches)",lines:i(n.skill_index,s=>s.id?`- ${s.id}${s.summary?`: ${s.summary}`:""}`:null),more:"suggest_skills"},{title:"Your private memories (recall_memory(query) loads a body)",lines:i(n.memory_index,s=>s.title?`- ${s.title}`:null),more:"recall_memory"},{title:"Lesson map \u2014 fetch with get_lesson(id) when a topic comes up",lines:i(n.convention_index,s=>s.id?`- ${s.id}${s.title?`: ${s.title}`:""}`:null),more:"search_lessons"}),r.filter(s=>s.lines.length>0)}function yb(e,t,n,r=9e3){let i=[];if(t){let[d,...u]=t.split(`
761
+ `);i.push({title:d,lines:u,more:"get_conventions"})}i.push(...ON(n));let a=Math.max(0,r-200),c=e,l=!0;for(let d of i){let u=`
762
+
763
+ ${d.title}`;if(Lo(c+u)>a){l=!1;break}c+=u;for(let f=0;f<d.lines.length;f++){let p=`
764
+ ${d.lines[f]}`;if(Lo(c+p)<=a){c+=p;continue}l=!1;let h=`
765
+ (+${d.lines.length-f} more \u2014 via ${d.more})`;Lo(c+h)<=r&&(c+=h);break}if(!l)break}if(!l){let d=`
766
+ \u2026 budget reached \u2014 the rest via get_session_briefing / get_conventions.`;Lo(c+d)<=r&&(c+=d)}return{text:c+`
767
+ `,complete:l}}var Lo,Dd=_(()=>{"use strict";Lo=o(e=>Buffer.byteLength(e,"utf8"),"bytes");o(Fo,"extractConventionsBlock");o(ON,"briefingSections");o(yb,"composeInjection")});import{mkdir as DN,readFile as PN,writeFile as MN,rename as $N}from"node:fs/promises";import{existsSync as bb}from"node:fs";import{homedir as LN}from"node:os";import{join as wb}from"node:path";function _b(){return{config:null,sessions:{},pending_metrics:[]}}async function Z(){if(!bb(jo))return _b();try{let e=await PN(jo,"utf-8"),t=JSON.parse(e);return{config:t.config??null,sessions:t.sessions??{},pending_metrics:Array.isArray(t.pending_metrics)?t.pending_metrics:[],thresholds:t.thresholds,thresholds_synced_at:t.thresholds_synced_at,guard_signals:t.guard_signals,repo_health_seen:t.repo_health_seen,write_health_seen:t.write_health_seen}}catch(e){return process.stderr.write(`[maind-mcp-bridge] state.json corrupt, resetting: ${e instanceof Error?e.message:String(e)}
768
+ `),_b()}}async function et(e){bb(Ue)||await DN(Ue,{recursive:!0,mode:448});let t=`${jo}.tmp`;await MN(t,JSON.stringify(e,null,2),{mode:384}),await $N(t,jo)}function Pd(e){return e.thresholds??e.config?.thresholds??FN}var Ue,jo,FN,He=_(()=>{"use strict";Ue=wb(LN(),".maind"),jo=wb(Ue,"state.json"),FN={warn_at_pct:60,handoff_at_pct:85,model_token_limit:2e5};o(_b,"emptyState");o(Z,"loadState");o(et,"saveState");o(Pd,"resolveThresholds")});import{existsSync as kb}from"node:fs";import{mkdir as jN,readFile as UN,readdir as HN,rename as BN,stat as GN,unlink as WN,writeFile as KN}from"node:fs/promises";import{join as Ai}from"node:path";function xb(e){return Ai(Md,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".json")}async function pt(e){try{let t=xb(e);if(!kb(t))return{};let n=JSON.parse(await UN(t,"utf8"));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function ye(e,t){await jN(Md,{recursive:!0,mode:448});let n=xb(e),r=`${n}.tmp`;await KN(r,JSON.stringify({...t,updated_at:new Date().toISOString()},null,2),{mode:384}),await BN(r,n)}async function Sb(e=7*24*60*60*1e3,t=Date.now()){await vb(Md,".json",e,t),await vb($d,".jsonl",e,t)}async function vb(e,t,n,r){try{if(!kb(e))return;for(let i of await HN(e)){if(!i.endsWith(t))continue;let s=Ai(e,i);try{let a=await GN(s);r-a.mtimeMs>n&&await WN(s)}catch{}}}catch{}}var Be,Md,$d,mt=_(()=>{"use strict";He();Be=Ai(Ue,"guard"),Md=Ai(Be,"sessions"),$d=Ai(Be,"triggers");o(xb,"sessionFile");o(pt,"loadGuardSession");o(ye,"saveGuardSession");o(Sb,"sweepOldGuardSessions");o(vb,"sweepDir")});import{existsSync as VN}from"node:fs";import{appendFile as zN,mkdir as qN,open as YN}from"node:fs/promises";import{join as JN}from"node:path";async function X(e){try{await qN(Be,{recursive:!0,mode:448});let t=JSON.stringify({ts:new Date().toISOString(),...e})+`
769
+ `;await zN(Cn,t,{mode:384})}catch{}}async function Eb(e=256*1024){let t={inject_ok:0,inject_fail:0,warn:0,deny:0,override:0,stop_block:0,gate_override:0,cross_session_warn:0,cross_session_deny:0,difficulty_nudge:0,difficulty_deny:0,difficulty_resolved:0,capture_prompt:0,capture_taken:0};try{if(!VN(Cn))return t;let n=await YN(Cn,"r");try{let r=(await n.stat()).size,i=Math.max(0,r-e),s=Buffer.alloc(r-i);await n.read(s,0,s.length,i);let c=s.toString("utf8").split(`
770
+ `);for(let l of i>0?c.slice(1):c)if(l.trim())try{let d=JSON.parse(l);typeof d.event=="string"&&d.event in t&&(t[d.event]+=1)}catch{}}finally{await n.close()}}catch{}return t}var Cn,ht=_(()=>{"use strict";mt();Cn=JN(Be,"events.jsonl");o(X,"appendGuardEvent");o(Eb,"readGuardEventCounts")});var Ib={};ee(Ib,{BRIEFING_CACHE_FILE:()=>Er,UNAVAILABLE_LINE:()=>Rb,carriesBriefing:()=>Ab,deliverSessionBriefing:()=>Ho,formatInjection:()=>Cb,resolveBriefingInjection:()=>Uo,runGuardInject:()=>aO,runsUnderCursor:()=>Ri});import{existsSync as XN}from"node:fs";import{mkdir as ZN,readFile as QN,rename as eO,writeFile as tO}from"node:fs/promises";import{homedir as nO}from"node:os";import{dirname as rO,join as iO}from"node:path";async function Uo(e,t,n={}){let r=n.nowMs??Date.now(),i=n.cacheFile??Er,s=n.fetcher??Po,a=await dO(i),c=a!==null&&a.format===Tb&&r-Date.parse(a.fetched_at)<sO&&a.project_key===e,l=o(f=>f.conventions?{conventions:f.conventions}:{},"withConventions");if(c)return{text:a.text,via:"cache",...l(a)};let d=null,u=await s({onInitialize:o(f=>{d=Fo(f)},"onInitialize"),apiKey:t,deviceId:fO(),projectKey:e,bridgeVersion:B,timeoutMs:oO});if(u!==null){let f=d;return await uO(i,{fetched_at:new Date(r).toISOString(),project_key:e,text:u,format:Tb,...f?{conventions:f}:{}}),{text:u,via:"fetch",...f?{conventions:f}:{}}}return a!==null?{text:a.text,via:"stale-cache",...l(a)}:{text:null,via:"none"}}async function aO(){try{if(se().mode==="off")return 0;let t=await W();return mb(hb(nO(),lO(t)))?0:await Ho("guard",t)}catch{return 0}}function Ab(e){return e==="resume"||e==="fork"}function Ri(e,t=process.env){let n=t.CURSOR_VERSION;return typeof n=="string"&&n.trim().length>0?!0:typeof e.cursor_version=="string"&&e.cursor_version.length>0}function cO(e){return new Promise(t=>{process.stdout.write(e,()=>t())})}async function Ho(e,t,n={}){let r=n.write??cO;if(Ri(t,n.env??process.env))return 0;let i=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(i===null)return 0;await Sb();let s=typeof t.source=="string"?t.source:"startup";if(Ab(s)){let h=await pt(i);return await ye(i,{...h,carryover:!0}),0}let a=(n.apiKey??Y)();if(a===null)return 0;let c=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),l=(n.projectKey??J)(),d=await Uo(l,a,n.inject),u=await pt(i);if(d.text===null)return await ye(i,{...u,inject_failed:!0}),await X({event:"inject_fail",session_id:i,cwd:c,project_key:l??void 0,...e==="core"?{detail:"core"}:{}}),await r(Rb),0;let f=Cb(d.text,d.via,d.conventions??null,e);await r(f.text),await ye(i,{...u,injected:!0});let p=f.complete?d.via:`${d.via}+budget`;return await X({event:"inject_ok",session_id:i,cwd:c,project_key:l??void 0,detail:e==="core"?`core:${p}`:p}),0}function lO(e){let t=process.env.CLAUDE_PROJECT_DIR;return typeof t=="string"&&t.trim().length>0?t.trim():typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:null}function Cb(e,t,n=null,r="guard"){let i=t==="stale-cache"?" \u2014 served from local cache, server unreachable":"",s=`Session briefing${n?" + project conventions":""}`,a=(r==="core"?`[maind] ${s}, delivered by the bridge's session-start hook (ADR-359)${i} \u2014 `:`[maind guard] ${s}, injected deterministically (ADR-284)${i} \u2014 `)+"the session-start get_session_briefing consultation is satisfied by this block:";return yb(a,n,e)}async function dO(e){try{if(!XN(e))return null;let t=JSON.parse(await QN(e,"utf8"));return typeof t.fetched_at!="string"||typeof t.text!="string"||Number.isNaN(Date.parse(t.fetched_at))?null:{fetched_at:t.fetched_at,project_key:typeof t.project_key=="string"?t.project_key:null,text:t.text,...typeof t.format=="number"?{format:t.format}:{},...typeof t.conventions=="string"&&t.conventions.length>0?{conventions:t.conventions}:{}}}catch{return null}}async function uO(e,t){try{await ZN(rO(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;await tO(n,JSON.stringify(t,null,2),{mode:384}),await eO(n,e)}catch{}}function fO(){try{return re()}catch{return null}}var Er,sO,Tb,oO,Rb,Tr=_(()=>{"use strict";ue();ge();$o();Ee();Fe();Qe();Dd();ht();mt();An();Er=iO(Be,"briefing-cache.json"),sO=12*60*60*1e3,Tb=2,oO=3e3;o(Uo,"resolveBriefingInjection");o(aO,"runGuardInject");o(Ab,"carriesBriefing");o(Ri,"runsUnderCursor");o(cO,"writeStdout");o(Ho,"deliverSessionBriefing");Rb=`[maind] Session briefing unavailable \u2014 the maind server could not be reached and there is no local copy yet. Call get_session_briefing once the maind tools respond.
771
+ `;o(lO,"projectDirOf");o(Cb,"formatInjection");o(dO,"readCache");o(uO,"writeCache");o(fO,"safeDeviceId")});var jb={};ee(jb,{AGENTS_MD_REFRESH_DEBUG_ENV:()=>$b,AGENTS_MD_REFRESH_INTERVAL_MS:()=>Pb,AGENTS_MD_REFRESH_OPT_OUT_ENV:()=>Mb,AGENTS_MD_REFRESH_STATE_FILE:()=>Db,gitToplevel:()=>Lb,loadConventionsForAgentsMd:()=>Bo,refreshAgentsMdConventions:()=>EO});import{execFileSync as pO}from"node:child_process";import{createHash as mO}from"node:crypto";import{mkdir as hO,readFile as gO,realpath as yO,rename as _O,writeFile as bO}from"node:fs/promises";import{dirname as wO,isAbsolute as vO,join as Ob,relative as kO,resolve as xO}from"node:path";async function Bo(e,t,n){if(e===null)return null;let r=await Uo(t,e,{fetcher:n.allowFetch?i=>Po({...i,clientFamily:"codex"}):async()=>null});return r.text===null?null:r.conventions??null}async function EO(e,t){let n=t.err??(r=>process.stderr.write(`${r}
772
+ `));try{if(e!=="codex")return{status:"skipped",reason:"family"};let r=t.env??process.env;if(AO(r))return{status:"skipped",reason:"opt-out"};let i=t.cwd??process.cwd(),s=(t.gitToplevel??Lb)(i);if(s===null)return{status:"skipped",reason:"no-root"};let a=await Nb(s),c=[];for(let x of await(t.findRoots??ao)(i)){let v=await Nb(x);TO(v,a)&&!c.includes(v)&&c.push(v)}c.includes(a)||c.push(a);let l=null,d=null;for(let x of c){let v=Ob(x,"AGENTS.md"),E=await Q(v);if(E!==null&&po(E,Sn)){l=v,d=E;break}}if(l===null||d===null)return RO(r)&&n(`maind: AGENTS.md conventions block skipped \u2014 no AGENTS.md with the "${Sn}" header between the working directory and ${a} (the bridge never writes above the repository root)`),{status:"skipped",reason:"no-agents-md-in-repo"};let u=t.nowMs??Date.now(),f=t.stateFile??Db,p=await IO(f),h=CO(l),g=p.roots[h]?.checked_at;if(typeof g=="string"&&!Number.isNaN(Date.parse(g))&&u-Date.parse(g)<Pb)return{status:"skipped",reason:"cadence"};if(t.apiKey===null)return{status:"skipped",reason:"no-api-key"};let b=await(t.loadConventions??((x,v)=>Bo(v,x,{allowFetch:!0})))(t.projectKey,t.apiKey);if(b===null||b.trim().length===0)return{status:"skipped",reason:"no-conventions"};let w=fo(b,{date:new Date(u).toISOString().slice(0,10),bridgeVersion:t.bridgeVersion??B}),k=mo(d,w,Sn);if(k.outcome==="damaged")return n(`maind: AGENTS.md conventions block not refreshed \u2014 begin marker without end marker in ${l}; remove the <!-- maind:conventions --> lines and the bridge re-inserts the block`),{status:"skipped",reason:"damaged"};if(k.outcome==="no-header")return{status:"skipped",reason:"no-agents-md-in-repo"};if(k.changed&&await z(l,k.next),await NO(f,p,h,u),!k.changed)return{status:"unchanged",file:l};let S=s_(w);return n(`maind: AGENTS.md conventions block refreshed (${S} conventions)`),{status:"refreshed",file:l,conventions:S,inserted:k.outcome==="inserted"}}catch(r){let i=r instanceof Error?r.message:String(r);return n(`maind: AGENTS.md conventions block not refreshed \u2014 ${i}`),{status:"failed",error:i}}}function Lb(e){try{let t=pO("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return t.length>0?t:null}catch{return null}}function TO(e,t){let n=kO(t,e);return n===""||!n.startsWith("..")&&!vO(n)}async function Nb(e){try{return await yO(e)}catch{return xO(e)}}function AO(e){return Fb(e[Mb])}function RO(e){return Fb(e[$b])}function Fb(e){let t=e?.trim().toLowerCase();return t!==void 0&&t.length>0&&t!=="0"&&t!=="false"}function CO(e){return mO("sha256").update(e).digest("hex")}async function IO(e){let t={version:1,roots:{}};try{let n=JSON.parse(await gO(e,"utf8"));if(!n||typeof n.roots!="object"||n.roots===null)return t;let r={};for(let[i,s]of Object.entries(n.roots))s&&typeof s.checked_at=="string"&&(r[i]={checked_at:s.checked_at});return{version:1,roots:r}}catch{return t}}async function NO(e,t,n,r){let i={};for(let[a,c]of Object.entries(t.roots)){let l=Date.parse(c.checked_at);!Number.isNaN(l)&&r-l<SO&&(i[a]=c)}i[n]={checked_at:new Date(r).toISOString()},await hO(wO(e),{recursive:!0,mode:448});let s=`${e}.${process.pid}.tmp`;await bO(s,JSON.stringify({version:1,roots:i},null,2),{mode:384}),await _O(s,e)}var Db,Pb,Mb,$b,SO,Ld=_(()=>{"use strict";An();Tr();mt();cd();_e();ld();nd();Fe();Db=Ob(Be,"agents-md-refresh.json"),Pb=12*60*60*1e3,Mb="MAIND_NO_AGENTS_MD_REFRESH",$b="MAIND_DEBUG",SO=30*24*60*60*1e3;o(Bo,"loadConventionsForAgentsMd");o(EO,"refreshAgentsMdConventions");o(Lb,"gitToplevel");o(TO,"isWithin");o(Nb,"realpathOrResolve");o(AO,"isOptedOut");o(RO,"isDebug");o(Fb,"isSet");o(CO,"fileKey");o(IO,"readState");o(NO,"writeState")});import{mkdirSync as Vb,rmdirSync as zb,statSync as $O}from"node:fs";import{join as qb}from"node:path";import{setTimeout as LO}from"node:timers/promises";function Yb(e){return qb(e,".maind","index-refresh.lock")}function Ko(e,t=Date.now()){let n=Yb(e);try{if(t-$O(n).mtimeMs<FO)return!1;zb(n)}catch{}try{return Vb(n,{recursive:!1}),!0}catch{return!1}}function Ci(e){try{zb(Yb(e))}catch{}}async function Jb(e,t,n={}){let r=n.now??Date.now,i=n.sleep??(a=>LO(a).then(()=>{})),s=r()+(n.waitMs??3e4);try{Vb(qb(e,".maind"),{recursive:!0})}catch{}for(;!Ko(e,r());){if(r()>=s)return{locked:!1};await i(n.pollMs??250)}try{return{locked:!0,value:await t()}}finally{Ci(e)}}var FO,Fd=_(()=>{"use strict";FO=30*6e4;o(Yb,"lockPath");o(Ko,"acquireLock");o(Ci,"releaseLock");o(Jb,"withIndexLock")});import{execFile as fw}from"node:child_process";import{randomUUID as aD}from"node:crypto";function pD(e){let t=(e.MAIND_SESSION_ID??"").trim().toLowerCase();return Wd.test(t)?t:aD()}function Kd(e,t){let n=(e.MAIND_AUTO_ANNOUNCE??"").trim().toLowerCase();return n==="off"||n==="0"||n==="false"?!0:t?.auto_announce===!1}function mD(e,t){let n=(e.MAIND_AUTO_WORKING_PATHS??"").trim().toLowerCase();return n==="on"||n==="1"||n==="true"?!0:n==="off"||n==="0"||n==="false"?!1:t?.auto_working_paths===!0}async function hD(e){return await new Promise(t=>{fw("git",["config","--get",`branch.${e}.maindObject`],{timeout:2e3,encoding:"utf8"},(n,r)=>{if(n)return t(null);t(gD(r))})})}function gD(e){let t=(e??"").trim().toLowerCase();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t)?t:null}async function yD(){return await new Promise(e=>{fw("git",["rev-parse","--abbrev-ref","HEAD"],{timeout:2e3,encoding:"utf8"},(t,n)=>{if(t)return e(null);let r=n.trim();e(r.length>0&&r!=="HEAD"?r:null)})})}function _D(e){if(typeof e!="string")return null;let t=e.trim().slice(0,100);return t.length>0?t:null}function bD(e,t){let n=t,r=(e.MAIND_SESSION_ID??"").trim().toLowerCase(),i=Wd.test(r)&&r===t?"env":"random";return{current:o(()=>({id:n,source:i,aliases:[]}),"current"),tryUpgrade:o(()=>!1,"tryUpgrade"),adopt:o(s=>{Wd.test(s)&&(n=s.trim().toLowerCase())},"adopt"),activityAtMs:o(()=>null,"activityAtMs")}}var uw,pw,cD,lD,dD,uD,fD,Wd,Yo,Vd=_(()=>{"use strict";$t();uw=45e3,pw=3e4,cD=5,lD=120,dD=3e4,uD=15*6e4,fD=1500,Wd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(pD,"resolveClientSessionId");o(Kd,"autoAnnounceDisabled");o(mD,"autoWorkingPathsEnabled");Yo=class{static{o(this,"PresenceAnnouncer")}projectKey;postToolCall;now;gitBranch;gitBranchObject;lastSentObjectId=null;log;machineLabel;enabled;workingPathsEnabled;deriveWorkingPaths;snapshot;identity;sessionMeta;lastBranch=null;lastAnnounceAt=0;lastActivityAt=0;missingSideChannelPolls=0;warnedMissingSideChannel=!1;inFlight=!1;consecutiveFailures=0;nextAttemptAt=0;ended=!1;constructor(t){let n=t.env??process.env,r=(t.readConfig??Ie)();this.projectKey=t.projectKey,this.postToolCall=t.postToolCall,this.now=t.now??Date.now,this.gitBranch=t.gitBranch??yD,this.gitBranchObject=t.gitBranchObject??hD,this.log=t.log??(i=>process.stderr.write(i+`
773
+ `)),this.machineLabel=_D(r?.machine_label),this.enabled=this.projectKey!==null&&!Kd(n,r),this.workingPathsEnabled=mD(n,r),this.deriveWorkingPaths=t.deriveWorkingPaths??null,this.snapshot=t.snapshot??null,this.identity=t.identity??bD(n,pD(n)),this.sessionMeta=t.sessionMeta??null}get sessionId(){return this.identity.current().id}get isEnabled(){return this.enabled}onSessionReady(){!this.enabled||this.ended||this.lastAnnounceAt>0||this.announce("active")}onActivity(){!this.enabled||this.ended||this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<uw||this.announce("active"))}pollActivity(){if(!this.enabled||this.ended)return;let t=this.identity.activityAtMs();if(t===null){this.noteMissingSideChannel();return}this.missingSideChannelPolls=0,!(t<=this.lastActivityAt)&&this.lastAnnounceAt!==0&&(this.now()-this.lastAnnounceAt<uw||(this.lastActivityAt=t,this.onActivity()))}noteMissingSideChannel(){this.warnedMissingSideChannel||++this.missingSideChannelPolls<cD||(this.warnedMissingSideChannel=!0,this.log("[maind-mcp-bridge] presence: no activity side channel for this session \u2014 presence now refreshes only on MAIND tool calls, so a session that is working can still appear stale. Re-run `maind-mcp-bridge install` to wire the hooks."))}async end(){if(!this.enabled||this.ended||(this.ended=!0,this.lastAnnounceAt===0))return;let t=new Promise(n=>setTimeout(n,fD).unref());await Promise.race([this.send("ended"),t])}async announce(t){if(!this.inFlight&&!(this.now()<this.nextAttemptAt)){this.inFlight=!0;try{await this.send(t),this.consecutiveFailures>0&&this.log("[maind-mcp-bridge] presence announce recovered."),this.consecutiveFailures=0,this.nextAttemptAt=0,this.lastAnnounceAt=this.now()}catch(n){this.consecutiveFailures+=1;let r=Math.min(dD*2**(this.consecutiveFailures-1),uD);this.nextAttemptAt=this.now()+r,this.consecutiveFailures===1&&this.log(`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${n instanceof Error?n.message:String(n)}`)}finally{this.inFlight=!1}}}async send(t){if(this.projectKey===null)return;try{if(t==="active"){let s=this.identity.current().id;(this.identity.resync?this.identity.resync():this.identity.tryUpgrade()?"upgraded":"unchanged")==="switched"&&this.log(`[maind-mcp-bridge] presence: this agent process now hosts a different conversation (${s} \u2192 ${this.identity.current().id}) \u2014 announcing it as its own session.`)}}catch{}let n=this.identity.current(),r={project_key:this.projectKey,session_id:n.id,status:t,ttl_minutes:lD,announce_source:"bridge"};if(t==="active"){r.identity_source=n.source,n.aliases.length>0&&(r.also_known_as=n.aliases);let s=await this.gitBranch();if(s&&(r.branch=s),this.lastBranch=s,s)try{let a=await this.gitBranchObject(s);a!==null&&a!==this.lastSentObjectId&&(r.object_ids=[a],this.lastSentObjectId=a)}catch{}if(this.machineLabel&&(r.machine_label=this.machineLabel),this.sessionMeta!==null)try{let a=await this.sessionMeta();a?.model&&(r.model=a.model),a?.title&&(r.title=a.title)}catch{}if(this.workingPathsEnabled&&this.deriveWorkingPaths)try{let a=await this.deriveWorkingPaths();a&&a.length>0&&(r.working_paths=a)}catch{}}let i=await this.postToolCall("announce_session",r);if(t==="active"&&i!==null&&typeof i=="object"){let s=i;if(s.ok===!0&&typeof s.session_id=="string")try{this.identity.adopt(s.session_id)}catch{}}if(this.snapshot)try{if(t==="ended")this.snapshot.endSession();else if(i!=null){let s={sessionId:this.sessionId,branch:this.lastBranch},a=typeof i=="object"?i:null;if(a!==null&&a.ok===!0)this.snapshot.write(i,s);else if(this.snapshot.markFailed){let c=a!==null&&typeof a.error=="string"?a.error:"announce_failed";this.snapshot.markFailed(c,s)}}}catch{}}};o(hD,"defaultGitBranchObject");o(gD,"normalizeObjectId");o(yD,"defaultGitBranch");o(_D,"normalizeMachineLabel");o(bD,"staticIdentity")});import{mkdirSync as mw,readdirSync as _w,readFileSync as wD,renameSync as hw,statSync as vD,unlinkSync as zd,writeFileSync as gw}from"node:fs";import{homedir as kD}from"node:os";import{join as Ar}from"node:path";function bw(){return Ar(kD(),".maind","presence")}function ww(e,t){return Ar(e,t)}function vw(e){let t=e.baseDir??bw(),n=ww(t,e.projectKey),r=e.pid??process.pid,i=e.ppid??process.ppid,s=e.cwd??process.cwd(),a=e.now??Date.now,c=null,l=o(d=>{if(c!==null&&c!==d)try{zd(c)}catch{}c=d},"replaceOwn");return{write(d,u){try{if(typeof d!="object"||d===null)return;let f=d;if(f.ok!==!0)return;let p={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:Array.isArray(f.peers)?f.peers:[],conflicts:Array.isArray(f.conflicts)?f.conflicts:[],...(()=>{let y=rs(f.assigned_to_you);return y.length>0?{assigned_to_you:y}:{}})()};mw(n,{recursive:!0,mode:448});let h=Ar(n,`${u.sessionId}.json`),g=`${h}.tmp-${r}`;gw(g,JSON.stringify(p),{mode:384}),hw(g,h),l(h),yw(n,a(),h)}catch{}},endSession(){try{c&&zd(c)}catch{}},markFailed(d,u){try{let f={v:1,written_at:new Date(a()).toISOString(),project_key:e.projectKey,own_session_id:u.sessionId,own_pid:r,own_ppid:i,cwd:s,branch:u.branch,peers:[],conflicts:[],announce_error:d};mw(n,{recursive:!0,mode:448});let p=Ar(n,`${u.sessionId}.json`),h=`${p}.tmp-${r}`;gw(h,JSON.stringify(f),{mode:384}),hw(h,p),l(p),yw(n,a(),p)}catch{}}}}function yw(e,t,n){try{for(let r of _w(e)){if(!r.endsWith(".json"))continue;let i=Ar(e,r);if(i!==n)try{t-vD(i).mtimeMs>xD&&zd(i)}catch{}}}catch{}}function On(e,t=bw()){try{let n=ww(t,e),r=[];for(let i of _w(n))if(i.endsWith(".json"))try{let s=JSON.parse(wD(Ar(n,i),"utf8")),a=SD(s);a&&r.push(a)}catch{}return r.sort((i,s)=>s.written_at.localeCompare(i.written_at)),r}catch{return[]}}function SD(e){if(typeof e!="object"||e===null)return null;let t=e;return t.v!==1||typeof t.written_at!="string"||typeof t.project_key!="string"||typeof t.own_session_id!="string"||typeof t.own_pid!="number"||typeof t.own_ppid!="number"||typeof t.cwd!="string"?null:{v:1,written_at:t.written_at,project_key:t.project_key,own_session_id:t.own_session_id,own_pid:t.own_pid,own_ppid:t.own_ppid,cwd:t.cwd,branch:typeof t.branch=="string"?t.branch:null,peers:Array.isArray(t.peers)?t.peers:[],conflicts:Array.isArray(t.conflicts)?t.conflicts:[],...typeof t.announce_error=="string"?{announce_error:t.announce_error}:{},...(()=>{let n=rs(t.assigned_to_you);return n.length>0?{assigned_to_you:n}:{}})()}}var xD,Jo=_(()=>{"use strict";Ur();xD=120*6e4;o(bw,"presenceSnapshotBaseDir");o(ww,"projectDir");o(vw,"createSnapshotStore");o(yw,"pruneStale");o(On,"readSnapshots");o(SD,"parseSnapshot")});import{execFileSync as ED}from"node:child_process";import{createHash as TD,randomUUID as AD}from"node:crypto";import{existsSync as RD,mkdirSync as CD,readdirSync as ID,readFileSync as xw,renameSync as ND,statSync as qd,unlinkSync as Sw,writeFileSync as OD}from"node:fs";import{homedir as DD}from"node:os";import{basename as PD,join as Gt}from"node:path";function Rr(e){return Gt(e??Gt(DD(),".maind","presence"),"identity")}function Ni(e,t){if(e){let n=PD(e).replace(/\.jsonl$/i,"");if(Ii.test(n))return n.toLowerCase()}return t&&Ii.test(t)?t.toLowerCase():null}function Ew(e){let t=e.nowMs??Date.now();CD(e.dir,{recursive:!0,mode:448});let n=Gt(e.dir,`${e.agentPid}.json`),r=`${n}.tmp-${process.pid}`,i={};if(!e.transcriptPath||!e.model)try{let l=JSON.parse(xw(n,"utf8"));l.session_id===e.sessionId&&(i={...typeof l.transcript_path=="string"?{transcript_path:l.transcript_path}:{},...typeof l.model=="string"?{model:l.model}:{}})}catch{}let s=e.transcriptPath??i.transcript_path,a=e.model??i.model,c={v:1,session_id:e.sessionId,transcript_stem:e.transcriptStem,cwd:e.cwd,agent_pid:e.agentPid,written_at:new Date(t).toISOString(),...s?{transcript_path:s}:{},...a?{model:a}:{}};OD(r,JSON.stringify(c,null,2)+`
774
+ `,{mode:384}),ND(r,n),jD(e.dir,t)}function Tw(e,t,n,r=Date.now()){try{let i=qd(Gt(e,`${t}.json`));return r-i.mtimeMs>n}catch{return!0}}function Aw(e,t){try{Sw(Gt(e,`${t}.json`))}catch{}}function jD(e,t){try{for(let n of ID(e))if(n.endsWith(".json"))try{let r=qd(Gt(e,n));t-r.mtimeMs>$D&&Sw(Gt(e,n))}catch{}}catch{}}function UD(e){return Rw(e)?.file??null}function Rw(e){let t=Gt(e.dir,`${e.agentPid}.json`);try{if(!RD(t))return null;let n=qd(t);if(n.mtimeMs<e.bridgeStartMs-LD)return null;let r=JSON.parse(xw(t,"utf8"));if(typeof r!="object"||r===null)return null;let i=r;return i.v!==1||typeof i.transcript_stem!="string"||!Ii.test(i.transcript_stem)||typeof i.session_id!="string"||typeof i.cwd!="string"||i.agent_pid!==e.agentPid||!HD(i.cwd,e.cwd)?null:{file:i,mtimeMs:n.mtimeMs}}catch{return null}}function kw(e){return e.replace(/\/+$/,"")}function HD(e,t){let n=kw(e),r=kw(t);return n===r?!0:n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}function BD(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),r=TD("sha1").update(n).update(e,"utf8").digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=i.toString("hex");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function GD(e){if(process.platform==="win32")return null;try{let t=ED("ps",["-o","lstart=","-p",String(e)],{timeout:1e3,encoding:"utf8"}).trim().replace(/\s+/g," ");return t.length>0?t:null}catch{return null}}function WD(){try{return re()}catch{return null}}var Ii,MD,$D,LD,FD,Xo,Zo=_(()=>{"use strict";ue();Ii=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,MD=8,$D=48*60*6e4,LD=6e4,FD="9f3c72da-2f10-4b8f-9c31-ad291c0de291";o(Rr,"identityDirPath");o(Ni,"transcriptStemOf");o(Ew,"writeAgentIdentityFile");o(Tw,"identityFileStale");o(Aw,"deleteAgentIdentityFile");o(jD,"pruneIdentityDir");o(UD,"readAgentIdentityFile");o(Rw,"readAgentIdentityEntry");o(kw,"normDir");o(HD,"sameSessionTree");o(BD,"uuidV5");o(GD,"processStartTime");Xo=class{static{o(this,"SessionIdentityManager")}env;agentPid;cwd;dir;bridgeStartMs;nowMs;envId;id;source;aliases=[];stem=null;constructor(t){this.env=t.env??process.env,this.agentPid=t.agentPid??process.ppid,this.cwd=t.cwd??process.cwd(),this.dir=t.identityDir??Rr(),this.bridgeStartMs=t.bridgeStartMs??Date.now(),this.nowMs=t.nowMs??Date.now;let n=(this.env.MAIND_SESSION_ID??"").trim().toLowerCase();this.envId=Ii.test(n)?n:null;let r=this.readStem();if(r!==null){this.id=r,this.stem=r,this.source="client_native",this.envId&&this.envId!==r&&(this.aliases=[this.envId]);return}if(this.envId!==null){this.id=this.envId,this.source="env";return}let i=(t.deviceId??WD)(),s=(t.ppidStart??GD)(this.agentPid);if(i!==null&&s!==null&&t.projectKey!==null){this.id=BD(`${i}|${this.agentPid}|${s}|${t.projectKey}`,FD),this.source="derived";return}this.id=AD(),this.source="random"}current(){return{id:this.id,source:this.source,aliases:[...this.aliases]}}tryUpgrade(){return this.resync()!=="unchanged"}resync(){let t=this.readStem();if(t===null)return"unchanged";if(this.source==="client_native")return t===this.stem?"unchanged":(this.id=t,this.stem=t,this.aliases=this.envId!==null&&this.envId!==t?[this.envId]:[],"switched");if(t===this.id)return"unchanged";let n=this.id;return this.id=t,this.stem=t,this.source="client_native",this.pushAlias(n),this.envId!==null&&this.pushAlias(this.envId),"upgraded"}adopt(t){let n=t.trim().toLowerCase();if(!Ii.test(n)||n===this.id)return;let r=this.id;this.id=n,!(this.source==="client_native"&&r===this.stem)&&this.pushAlias(r)}pushAlias(t){t===this.id||this.aliases.includes(t)||(this.aliases.push(t),this.aliases.length>MD&&this.aliases.shift())}activityAtMs(){return Rw({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})?.mtimeMs??null}readStem(){let t=this.sideChannel();return t===null?null:t.transcript_stem.toLowerCase()}sideChannel(){return UD({dir:this.dir,agentPid:this.agentPid,cwd:this.cwd,bridgeStartMs:this.bridgeStartMs,nowMs:this.nowMs()})}};o(WD,"defaultDeviceId")});function Yd(){return{ultracode:!1,planMode:!1,autoMode:!1}}var Jd=_(()=>{"use strict";o(Yd,"newModeState")});import{createReadStream as KD,existsSync as VD}from"node:fs";import{stat as zD}from"node:fs/promises";import{createInterface as qD}from"node:readline";async function Xd(e){if(!e||!VD(e))return null;let t;try{t=await zD(e)}catch{return null}let n=new Set,r=0,i=0,s=0;return await new Promise(a=>{let c=KD(e,{encoding:"utf-8"}),l=qD({input:c});l.on("line",d=>{let u=d.trim();if(u){s++;try{let f=JSON.parse(u),p=f.message?.usage;if(!p)return;let h=typeof f.message?.id=="string"&&f.message.id?f.message.id:null,g=typeof f.requestId=="string"&&f.requestId?f.requestId:null,y=h??g;if(y!==null){if(n.has(y))return;n.add(y)}typeof p.input_tokens=="number"&&(r+=p.input_tokens),typeof p.output_tokens=="number"&&(i+=p.output_tokens)}catch{}}}),l.on("close",()=>{a({input_tokens:r,output_tokens:i,total_tokens:r+i,lines_seen:s,last_modified_ms:t.mtimeMs})}),l.on("error",()=>a(null)),c.on("error",()=>a(null))})}var Cw=_(()=>{"use strict";o(Xd,"summariseTranscript")});var Iw=_(()=>{"use strict"});function Oi(e){if(!e)return null;let t=null;for(let n of e.matchAll(JD)){let r=n[1].toLowerCase();YD.has(r)&&(t=r)}return t}var YD,JD,Qo=_(()=>{"use strict";YD=new Set(["low","medium","high","xhigh","max"]),JD=/(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;o(Oi,"detectEffortLevel")});import{createReadStream as XD,existsSync as ZD,readdirSync as QD}from"node:fs";import{basename as Dw,dirname as eP,join as Nw}from"node:path";import{createInterface as tP}from"node:readline";function Mw(e,t){if(typeof t!="string")return;let n=t.trim().toLowerCase();!iP.test(n)||e.ids.includes(n)||e.ids.length>=Pw||e.ids.push(n)}function sP(e,t){if(Array.isArray(t))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string"||!r.name.startsWith(ea)||rP.has(r.name))continue;let i=r.input&&typeof r.input=="object"?r.input:{};i.session_id!==void 0?Mw(e,i.session_id):r.name===`${ea}announce_session`&&typeof r.id=="string"&&e.pendingAnnounce.add(r.id)}}function oP(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&(t+=n.text);return t}function aP(e,t){if(!(e.pendingAnnounce.size===0||!Array.isArray(t)))for(let n of t){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_result"||typeof r.tool_use_id!="string"||!e.pendingAnnounce.delete(r.tool_use_id))continue;let i=oP(r.content),s=null;try{let a=JSON.parse(i);a&&a.ok===!0&&(s=a.session_id)}catch{let a=/"session_id"\s*:\s*"([0-9a-f-]{36})"/i.exec(i);s=a?a[1]:null}Mw(e,s)}}function Cr(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}function lP(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let r=n;if(r.type!=="tool_use"||typeof r.name!="string")continue;let i=cP[r.name];if(!i||!r.input||typeof r.input!="object")continue;let s=r.input[i];typeof s=="string"&&s.length>0&&t.push(s)}return t}function ta(e){let t=Dw(e).replace(/\.jsonl$/,""),n=Nw(eP(e),t,"subagents"),r;try{r=QD(n)}catch{return[]}return r.filter(i=>i.endsWith(".jsonl")).sort().map(i=>Nw(n,i))}async function Ow(e,t,n,r,i,s){ZD(e)&&await new Promise(a=>{let c=XD(e,{encoding:"utf-8"}),l=tP({input:c}),d=0;l.on("line",u=>{d++;let f=u.trim();if(!f)return;let p;try{p=JSON.parse(f)}catch{return}if(p.message?.role==="user"){aP(s,p.message.content);return}if(p.message?.role!=="assistant")return;sP(s,p.message.content);let h=typeof p.message.id=="string"&&p.message.id?p.message.id:null,g=typeof p.requestId=="string"&&p.requestId?p.requestId:null,y=h??g??`${e}#${d}`,b=lP(p.message.content),w=r.get(y);if(w){for(let E of b)w.edited_paths.includes(E)||w.edited_paths.push(E);return}if(n.has(y))return;n.add(y);let k=p.message.usage??{},S=typeof p.timestamp=="string"?Date.parse(p.timestamp):Number.NaN,x=typeof p.message.model=="string"&&p.message.model?p.message.model:"",v={ts:Number.isFinite(S)?S:0,model:x||"<unknown>",synthetic:x===nP,input_tokens:Cr(k.input_tokens),output_tokens:Cr(k.output_tokens),cache_read_tokens:Cr(k.cache_read_input_tokens),cache_creation_tokens:Cr(k.cache_creation_input_tokens),cache_creation_1h_tokens:Math.min(Cr(k.cache_creation?.ephemeral_1h_input_tokens),Cr(k.cache_creation_input_tokens)),sidechain:p.isSidechain===!0,stream:t,edited_paths:b,cwd:typeof p.cwd=="string"&&p.cwd?p.cwd:null};r.set(y,v),i.push(v)}),l.on("close",()=>a()),l.on("error",()=>a()),c.on("error",()=>a())})}function Zd(e){let t=0;for(let r of e)r.ts>0?t=r.ts:t>0&&(r.ts=t);let n=0;for(let r=e.length-1;r>=0;r--){let i=e[r];i.ts>0?n=i.ts:n>0&&(i.ts=n)}}async function Di(e){let t=new Set,n=new Map,r=[],i=e?ta(e):[],s={ids:[],pendingAnnounce:new Set};if(!e)return{turns:r,subagent_files:i,coordination_ids:[]};let a=[];await Ow(e,Dn,t,n,a,s),Zd(a),r.push(...a);for(let c of i){let l=[],d=Dw(c).replace(/\.jsonl$/,"");s.pendingAnnounce.clear(),await Ow(c,d,t,n,l,s),Zd(l);for(let u of l)u.sidechain=!0;r.push(...l)}return{turns:r,subagent_files:i,coordination_ids:s.ids}}var Dn,nP,ea,rP,iP,Pw,cP,na=_(()=>{"use strict";Dn="main",nP="<synthetic>",ea="mcp__maind__",rP=new Set([`${ea}get_session_analysis`,`${ea}get_session_cost_context`]),iP=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Pw=32;o(Mw,"addCoordinationId");o(sP,"noteCoordinationUse");o(oP,"resultText");o(aP,"noteAnnounceResult");cP={Edit:"file_path",Write:"file_path",MultiEdit:"file_path",NotebookEdit:"notebook_path"};o(Cr,"num");o(lP,"editedPathsOf");o(ta,"subagentFilesOf");o(Ow,"readStream");o(Zd,"fillTimestamps");o(Di,"collectTurns")});import{createReadStream as $w,existsSync as dP}from"node:fs";import{createInterface as Lw}from"node:readline";function yP(e,t,n,r,i){let s=`${n?"s":"m"}:${t}`,a=e.get(s);if(!a){e.set(s,{model:t,turns:1,output_tokens:r,first_ts:i,last_ts:i,sidechain:n});return}a.turns++,a.output_tokens+=r,i>0&&((a.first_ts===0||i<a.first_ts)&&(a.first_ts=i),i>a.last_ts&&(a.last_ts=i))}function ra(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function _P(e){let t=[];for(let n of e)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
775
+ `)}function bP(e,t){let n=o(l=>new Set(l.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(d=>d.length>2)),"toks"),r=n(e),i=n(t);if(r.size<3||i.size<3)return!1;let[s,a]=r.size<=i.size?[r,i]:[i,r],c=0;for(let l of s)a.has(l)&&c++;return c/s.size>=.8}function wP(e,t,n){return uP.test(e)?{polarity:-1,magnitude:Ir.rework,kind:"rework"}:n&&fP.test(e)?{polarity:-1,magnitude:Ir.correction,kind:"correction"}:pP.test(e)?{polarity:1,magnitude:Ir.acceptance,kind:"acceptance"}:t!==null&&bP(t,e)?{polarity:-1,magnitude:Ir.repeat,kind:"repeat"}:{polarity:0,magnitude:0,kind:"neutral"}}function vP(e){return{session_id:e,user_turns:0,assistant_turns:0,tool_calls:0,agent_questions:0,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,user_chars:0,user_token_estimate:0,human_share:0,reactions_pos:0,reactions_neg:0,net_sentiment:0,corrections:0,reworks:0,interrupts:0,tool_denials:0,repeated_instructions:0,acceptances:0,momentum_series:[],momentum_final:0,momentum_auc:0,ended_positive:!1,recovery_events:0,effort_at_end:null,model_mix:[],ai_title:null,session_slug:null,maind_tool_calls:{},maind_connected:"unknown",lines_seen:0,analyzer_version:Fw,behaviour_measured:!0}}async function kP(e,t){for(let n of ta(e))await new Promise(r=>{let i=Lw({input:$w(n,{encoding:"utf-8"})});i.on("line",s=>{let a=s.trim();if(!a)return;let c;try{c=JSON.parse(a)}catch{return}if(c.message?.role==="assistant")for(let l of ra(c.message?.content)){if(l.type!=="tool_use"||typeof l.name!="string"||!l.name.startsWith(ia))continue;let d=l.name.slice(ia.length);d&&(t.maind_tool_calls??={},t.maind_tool_calls[d]=(t.maind_tool_calls[d]??0)+1)}}),i.on("error",()=>r()),i.on("close",()=>r())})}async function Qd(e,t={}){let n=vP("");if(!e||!dP(e))return n;let r=t.turns??(await Di(e)).turns;for(let h of r)n.input_tokens+=h.input_tokens,n.output_tokens+=h.output_tokens,n.cache_read_tokens+=h.cache_read_tokens,n.cache_creation_tokens+=h.cache_creation_tokens,h.sidechain||n.assistant_turns++;let i=[],s=new Map,a=null,c=!1,l=null;await new Promise(h=>{let g=$w(e,{encoding:"utf-8"}),y=Lw({input:g}),b=o(w=>{let k=w.trim();if(!k)return;let S;try{S=JSON.parse(k)}catch{return}if(n.lines_seen++,!n.session_id){let L=S.sessionId??S.session_id;typeof L=="string"&&L&&(n.session_id=L)}S.type==="ai-title"&&typeof S.aiTitle=="string"&&S.aiTitle&&(n.ai_title=S.aiTitle),typeof S.slug=="string"&&S.slug&&(n.session_slug=S.slug);let x=S.message?.role,v=S.isSidechain===!0;if(x==="assistant")for(let L of ra(S.message?.content)){if(L.type!=="tool_use"||typeof L.name!="string"||!L.name.startsWith(ia))continue;let G=L.name.slice(ia.length);G&&(n.maind_tool_calls??={},n.maind_tool_calls[G]=(n.maind_tool_calls[G]??0)+1)}if(v)return;if(x==="assistant"){let L=ra(S.message?.content),G=!1;for(let yt of L)yt.type==="tool_use"&&(n.tool_calls++,G=!0,yt.name==="AskUserQuestion"&&n.agent_questions++);c=G;return}if(x!=="user")return;let E=ra(S.message?.content),N=_P(E);if(N.includes(mP)){n.interrupts++,i.push({polarity:-1,magnitude:Ir.interrupt,kind:"interrupt"});return}if(E.some(L=>L.type==="tool_result"&&L.is_error===!0&&typeof L.content=="string"&&L.content.includes(hP))){n.tool_denials++,i.push({polarity:-1,magnitude:Ir.denial,kind:"denial"});return}if(E.some(L=>L.type==="tool_result")||!N.trim())return;n.user_turns++,n.user_chars+=N.length;let H=Oi(N);H&&(a=H);let P=wP(N,l,c);l=N,P.kind==="correction"?n.corrections++:P.kind==="rework"?n.reworks++:P.kind==="repeat"?n.repeated_instructions++:P.kind==="acceptance"&&n.acceptances++,P.polarity!==0&&i.push(P),c=!1},"processLine");y.on("line",w=>{try{b(w)}catch{}}),y.on("close",()=>h()),y.on("error",()=>h()),g.on("error",()=>h())}),await kP(e,n),n.effort_at_end=a;for(let h of r)h.synthetic||h.model==="<unknown>"||yP(s,h.model,h.sidechain,h.output_tokens,h.ts);n.model_mix=[...s.values()].sort((h,g)=>h.first_ts-g.first_ts||h.model.localeCompare(g.model)),n.user_token_estimate=Math.round(n.user_chars/4);let d=n.user_token_estimate+n.output_tokens;n.human_share=d>0?Number((n.user_token_estimate/d).toFixed(4)):0;let u=0,f=0,p=[];return i.forEach((h,g)=>{h.polarity>0?n.reactions_pos++:h.polarity<0&&n.reactions_neg++,u=u*gP+h.polarity*h.magnitude;let y=Number(u.toFixed(3));p.push({t:g,value:y,...h.kind!=="neutral"?{kind:h.kind}:{}}),f+=y,g>0&&i[g-1].polarity<0&&h.polarity>0&&n.recovery_events++}),n.net_sentiment=n.reactions_pos-n.reactions_neg,n.momentum_series=p,n.momentum_final=p.length?p[p.length-1].value:0,n.momentum_auc=Number(f.toFixed(3)),n.ended_positive=n.momentum_final>0,Object.keys(n.maind_tool_calls??{}).length>0&&(n.maind_connected="connected"),n}var ia,Fw,uP,fP,pP,mP,hP,gP,Ir,jw=_(()=>{"use strict";Qo();na();ia="mcp__maind__",Fw="2026-10-01",uP=/(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i,fP=/(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i,pP=/(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i,mP="[Request interrupted by user",hP="The user doesn't want to proceed with this tool use",gP=.7,Ir={denial:1.5,interrupt:1.25,rework:1.5,correction:1,acceptance:1,repeat:.75};o(yP,"bumpModel");o(ra,"asBlocks");o(_P,"textOf");o(bP,"isRepeat");o(wP,"classifyGenuine");o(vP,"emptyAnalysis");o(kP,"tallySubagentMaindCalls");o(Qd,"analyzeSession")});function eu(e){let t=e!==null&&typeof e=="object"?e:{},n=typeof t.slices_stored=="boolean"?t.slices_stored:null;return{analyticsStored:t.analytics_stored===!0,spanStored:t.span_stored===!0,slicesStored:n,slicesReason:n===null?null:typeof t.slices_reason=="string"?t.slices_reason:null,slicesCount:typeof t.slices_count=="number"&&Number.isFinite(t.slices_count)?t.slices_count:0}}function tu(e,t){return!t||e.slicesStored===!0?null:e.slicesStored===null?"cost slices sent, verdict unknown \u2014 the ingest endpoint predates slice verdicts (redeploy mcp-client-metrics-ingest)":`cost slices not stored: ${e.slicesReason??"no reason given"} (${e.slicesCount} sent)`}function nu(e,t,n,r="unknown",i){let s={session_analytics:{...e,ingest_source:r,...n?.client_session_id?{client_session_id:n.client_session_id}:{},...n?.client?{client:n.client}:{},...n?.coordination_session_ids&&n.coordination_session_ids.length>0?{coordination_session_ids:[...n.coordination_session_ids]}:{},...i?{cost_slices:i.slices,cost_context_ok:i.context_ok}:{}}};if(t&&t.started_at)if(n){let{coordination_session_ids:a,...c}=n;s.session_span={...t,...c}}else s.session_span=t;return s}var Uw=_(()=>{"use strict";o(eu,"parseIngestResponse");o(tu,"describeSliceVerdict");o(nu,"ingestBody")});import{isAbsolute as Hw,relative as xP,resolve as Bw,sep as Gw}from"node:path";function Ww(e){return e>oa[1]?"above_272k":e>oa[0]?"band_200k_272k":"standard"}function Kw(e){return e.trim().replace(/\[[^\]]*\]$/,"")}function sa(e){if(typeof e!="string"||!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}function Pi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t;if(n.ok!==!0)return null;let r=o(a=>{if(!Array.isArray(a))return[];let c=[];for(let l of a){if(!l||typeof l!="object")continue;let d=l,u=sa(d.from);typeof d.object_id!="string"||!ru.test(d.object_id)||u===null||c.push({object_id:d.object_id.toLowerCase(),from:u,to:sa(d.to)})}return c},"windows"),i=[];if(Array.isArray(n.claims))for(let a of n.claims){if(!a||typeof a!="object")continue;let c=a,l=sa(c.from);typeof c.path_prefix!="string"||l===null||i.push({path_prefix:c.path_prefix,from:l,to:sa(c.to)})}let s=[];if(Array.isArray(n.anchors))for(let a of n.anchors){if(!a||typeof a!="object")continue;let c=a;typeof c.object_id!="string"||!ru.test(c.object_id)||typeof c.path_prefix=="string"&&s.push({object_id:c.object_id.toLowerCase(),path_prefix:c.path_prefix})}return{canonical_session_id:typeof n.canonical_session_id=="string"&&ru.test(n.canonical_session_id)?n.canonical_session_id.toLowerCase():null,session_row:n.session_row===!0,leases:r(n.leases),bindings:r(n.bindings),claims:i,anchors:s}}function aa(e,t){if(!Hw(e))return null;let n=xP(Bw(t),Bw(e));return!n||n==="."||n.startsWith("..")||Hw(n)?null:Gw==="/"?n:n.split(Gw).join("/")}function EP(e,t){return t===""||e===t||e.startsWith(t+"/")}function su(e,t){return e===t||e===""||t===""||e.startsWith(t+"/")||t.startsWith(e+"/")}function Vw(e){return[...e].sort((t,n)=>n.path_prefix.length-t.path_prefix.length||t.object_id.localeCompare(n.object_id))}function ou(e,t){for(let n of Vw(t))if(EP(e,n.path_prefix))return n.object_id;return null}function TP(e,t){for(let n of Vw(t))if(su(e,n.path_prefix))return n.object_id;return null}function iu(e,t){return e>=t.from&&(t.to===null||e<t.to)}function zw(e,t,n,r){let i=e.ts,s=r?.anchors??[],a=t.map(c=>ou(c,s)).filter(c=>c!==null);if(r&&i>0){let c=r.leases.filter(u=>iu(i,u));if(c.length)return c.sort((u,f)=>f.from-u.from||u.object_id.localeCompare(f.object_id)),{object_id:c[0].object_id,source:"lease"};let l=r.bindings.filter(u=>iu(i,u));if(l.length)return{object_id:(l.find(f=>a.includes(f.object_id))??l.find(f=>n!==null&&f.object_id===n.object_id)??[...l].sort((f,p)=>f.object_id.localeCompare(p.object_id))[0]).object_id,source:"binding"};let d=r.claims.filter(u=>iu(i,u));if(d.length){let u=t[0]??n?.rel??null,f=(u===null?d:d.filter(p=>su(p.path_prefix,u))).sort((p,h)=>h.path_prefix.length-p.path_prefix.length);for(let p of f){let h=TP(p.path_prefix,s);if(h)return{object_id:h,source:"claim"}}}}return a.length?{object_id:a[0],source:"path"}:n?{object_id:n.object_id,source:"path"}:{object_id:null,source:"none"}}function au(e,t,n){let r=t?.anchors??[],i=n.repoRoot,s=n.relativize??(i?b=>aa(b,i):null),a=o(b=>{if(!s)return[];let w=[];for(let k of b.edited_paths){let S=s(k);S!==null&&!w.includes(S)&&w.push(S)}return w},"relOf"),c=o(b=>{for(let w of b){let k=ou(w,r);if(k)return{object_id:k,rel:w}}return null},"firstAnchoredEdit"),l=new Map;for(let b of e){let w=l.get(b.stream)??[];w.push(b),l.set(b.stream,w)}let d=[...l.entries()].sort(([b],[w])=>b===Dn?-1:w===Dn?1:0),u=[],f=o(b=>{let w=null;for(let k of u){if(k.ts>b&&b>0)break;w=k.seg}return w},"mainSegmentAt"),p=new Map;for(let[b,w]of d){let k=w.map((x,v)=>({t:x,i:v,rels:a(x)})).sort((x,v)=>x.t.ts-v.t.ts||x.i-v.i),S=null;for(let x of k){let v=c(x.rels);if(v){S=v;break}}!S&&b!==Dn&&k.length&&(S=f(k[0].t.ts));for(let x of k){let v=c(x.rels);v&&(S=v),b===Dn&&u.push({ts:x.t.ts,seg:S});let E=x.t;if(E.input_tokens+E.output_tokens+E.cache_read_tokens+E.cache_creation_tokens===0)continue;let F=zw(E,x.rels,S,t),H=Ww(E.input_tokens+E.cache_read_tokens+E.cache_creation_tokens),P=Kw(E.model),L=`${F.object_id??""}|${F.source}|${P}|${H}`,G=p.get(L);G||(G={object_id:F.object_id,attribution_source:F.source,model:P,context_tier:H,input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,cache_creation_1h_tokens:0,first_ts:"",last_ts:"",turns:0,firstMs:0,lastMs:0},p.set(L,G)),G.input_tokens+=E.input_tokens,G.output_tokens+=E.output_tokens,G.cache_read_tokens+=E.cache_read_tokens,G.cache_creation_tokens+=E.cache_creation_tokens,G.cache_creation_1h_tokens+=E.cache_creation_1h_tokens,G.turns+=1,E.ts>0&&((G.firstMs===0||E.ts<G.firstMs)&&(G.firstMs=E.ts),E.ts>G.lastMs&&(G.lastMs=E.ts))}}let h=n.nowMs??Date.now(),g=[];for(let b of p.values()){let{firstMs:w,lastMs:k,...S}=b;S.first_ts=new Date(w>0?w:h).toISOString(),S.last_ts=new Date(k>0?k:h).toISOString(),g.push(S)}let y={lease:0,binding:1,claim:2,path:3,none:4};return g.sort((b,w)=>y[b.attribution_source]-y[w.attribution_source]||(b.object_id??"").localeCompare(w.object_id??"")||b.model.localeCompare(w.model)||b.context_tier.localeCompare(w.context_tier)),g}var oa,SP,ru,cu=_(()=>{"use strict";na();oa=[2e5,272e3];o(Ww,"contextTierOf");o(Kw,"normalizeModelId");SP=oa[0],ru=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(sa,"msOf");o(Pi,"parseCostContext");o(aa,"toRepoRelative");o(EP,"underPrefix");o(su,"prefixesOverlap");o(Vw,"sortedAnchors");o(ou,"anchorFor");o(TP,"bestAnchorOverlapping");o(iu,"inWindow");o(zw,"assignTurn");o(au,"sliceSession")});import{mkdirSync as AP,readFileSync as RP,renameSync as CP,writeFileSync as IP}from"node:fs";import{dirname as NP,isAbsolute as ca,sep as lu}from"node:path";function OP(e){let t=e.split(lu).join("/"),n=t.lastIndexOf("/");return n<=0?t:t.slice(0,n)}function DP(e,t){return e===t||e.startsWith(t.endsWith("/")?t:t+"/")}function du(e){let t=new Map,n=o(u=>{let f=t.get(u);if(f!==void 0)return f;let p=e.keyOfRoot(u);return t.set(u,p),p},"keyOf"),r=new Map,i=o(u=>{let f=r.get(u);if(f!==void 0)return f;let p=e.gitRoot(u);return r.set(u,p),p},"gitRoot"),s=new Map,a=[...(e.known??new Map).entries()].filter(([u])=>ca(u)).sort((u,f)=>f[0].length-u[0].length),c=new Map,l=o(u=>{if(!e.isDir)return null;let f=c.get(u);if(f!==void 0)return f;let p=d(u);return c.set(u,p),p},"byConvention"),d=o(u=>{if(!e.isDir)return null;let f=u.split("/");for(let p=2;p<f.length+1;p++){let h=f.slice(0,p).join("/");if(!h||e.isDir(h))continue;let g=f.slice(0,p-1).join("/")||"/",y=f[p-1];for(let b=y.lastIndexOf("-");b>0;b=y.lastIndexOf("-",b-1)){let w=`${g==="/"?"":g}/${y.slice(0,b)}`;if(e.isDir(w)&&i(w)===w)return{root:h,key:n(w)}}return null}return null},"conventionRoot");return{of(u){if(!ca(u))return null;let f=u.split(lu).join("/"),p=OP(f),h=i(p);if(h){let g=n(h);return s.set(h,g),{root:h,key:g}}for(let[g,y]of a)if(!(!DP(f,g)||f===g)&&!(e.isDir&&e.isDir(g)))return{root:g,key:y};return l(p)},seenLive(){return[...s.entries()].map(([u,f])=>({root:u,key:f}))}}}function uu(e,t){let n=new Map;for(let a of e){let c=new Map;for(let l of a.edited_paths){let d=t.of(l);!d||!d.key||c.set(d.key,Math.max(c.get(d.key)??0,d.root.length))}for(let[l,d]of c){let u=n.get(l)??{turns:0,depth:0};u.turns+=1,u.depth=Math.max(u.depth,d),n.set(l,u)}}let r=null,i=0,s=0;for(let[a,c]of n)(c.turns>i||c.turns===i&&(c.depth>s||c.depth===s&&r!==null&&a<r))&&(r=a,i=c.turns,s=c.depth);return r}function fu(e,t){return n=>{let r=t.of(n);return!r||r.key!==e?null:aa(n.split(lu).join("/"),r.root)}}function Jw(e){try{let t=JSON.parse(RP(e,"utf8"));if(t&&t.v===1&&t.checkouts&&typeof t.checkouts=="object")return{v:1,checkouts:t.checkouts}}catch{}return{v:1,checkouts:{}}}function Mi(e){let t=new Map,n=Jw(e);for(let[r,i]of Object.entries(n.checkouts)){if(!ca(r)||!i||typeof i!="object")continue;let s=typeof i.project_key=="string"&&Yw.test(i.project_key)?i.project_key:null;t.set(r,s)}return t}function $i(e,t,n=Date.now()){try{let r=Jw(e),i=new Date(n).toISOString(),s=!1;for(let c of t){if(!ca(c.root))continue;let l=c.key&&Yw.test(c.key)?c.key:null,d=r.checkouts[c.root],u=Date.parse(d?.seen_at??"");(!d||d.project_key!==l||!Number.isFinite(u)||n-u>PP)&&(r.checkouts[c.root]={project_key:l,seen_at:i},s=!0)}for(let[c,l]of Object.entries(r.checkouts)){let d=Date.parse(l?.seen_at??"");(!Number.isFinite(d)||n-d>qw)&&(delete r.checkouts[c],s=!0)}if(!s)return;AP(NP(e),{recursive:!0});let a=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;IP(a,JSON.stringify(r),{mode:384}),CP(a,e)}catch{}}var qw,PP,Yw,Xw=_(()=>{"use strict";cu();o(OP,"dirOf");o(DP,"within");o(du,"createCheckoutResolver");o(uu,"dominantProjectKey");o(fu,"relativizerFor");qw=90*24*60*60*1e3,PP=60*60*1e3,Yw=/^[a-f0-9]{64}$/;o(Jw,"readMemory");o(Mi,"loadCheckoutMemory");o($i,"rememberCheckouts")});import{homedir as MP}from"node:os";import{join as $P}from"node:path";var LP,pu=_(()=>{"use strict";LP=$P(MP(),".codex","sessions")});var Zw=_(()=>{"use strict";pu()});var Qw=_(()=>{"use strict"});import{createReadStream as jP,existsSync as UP}from"node:fs";import{createInterface as HP}from"node:readline";function ev(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}function WP(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
776
+ `)}function rv(e){return{session_id:e,started_at:null,ended_at:null,wall_seconds:0,agent_seconds:0,wait_seconds:0,pauses:[],pause_count:0,pause_seconds:0,pauses_truncated:!1,turn_count:0,event_count:0}}function KP(e){let t=e.message?.role;if(t==="assistant")return{holder:ev(e.message?.content).some(c=>c.type==="tool_use")?"agent":"human",genuine:!1};if(t!=="user")return null;let n=ev(e.message?.content),r=WP(n);return r.includes(BP)?{holder:"human",genuine:!1}:n.some(s=>s.type==="tool_result"&&s.is_error===!0&&typeof s.content=="string"&&s.content.includes(GP))?{holder:"agent",genuine:!1}:n.some(s=>s.type==="tool_result")?{holder:"agent",genuine:!1}:r.trim()?{holder:"agent",genuine:!0}:null}async function mu(e){let t=rv("");if(!e||!UP(e))return t;let n=null,r=0,i=0,s=null,a="human",c=[];return await new Promise(l=>{let d=jP(e,{encoding:"utf-8"}),u=HP({input:d}),f=o(p=>{let h=p.trim();if(!h)return;let g;try{g=JSON.parse(h)}catch{return}if(!t.session_id){let w=g.sessionId??g.session_id;typeof w=="string"&&w&&(t.session_id=w)}if(g.isSidechain===!0)return;let y=typeof g.timestamp=="string"?Date.parse(g.timestamp):NaN;if(!Number.isFinite(y)||s!==null&&y<s)return;let b=KP(g);if(b!==null){if(t.event_count++,b.genuine&&t.turn_count++,n===null&&(n=y),r=y,s!==null){let w=y-s;a==="agent"?i+=w:w>=tv*1e3&&(t.pause_count++,t.pause_seconds+=Math.round(w/1e3),c.length<nv&&c.push({offset_seconds:Math.round((s-n)/1e3),duration_seconds:Math.round(w/1e3)}))}s=y,a=b.holder}},"processLine");u.on("line",p=>{try{f(p)}catch{}}),u.on("close",()=>l()),u.on("error",()=>l()),d.on("error",()=>l())}),n===null||(t.started_at=new Date(n).toISOString(),t.ended_at=new Date(r).toISOString(),t.wall_seconds=Math.round((r-n)/1e3),t.agent_seconds=Math.round(i/1e3),t.wait_seconds=t.wall_seconds-t.agent_seconds,t.pauses=c,t.pauses_truncated=t.pause_count>c.length),t}var BP,GP,tv,nv,iv=_(()=>{"use strict";BP="[Request interrupted by user",GP="The user doesn't want to proceed with this tool use",tv=60,nv=200;o(ev,"asBlocks");o(WP,"textOf");o(rv,"emptySpan");o(KP,"classify");o(mu,"analyzeSpan")});import{createReadStream as VP,existsSync as zP}from"node:fs";import{createInterface as qP}from"node:readline";function JP(e){return e==="ultracode"?"ultracode":e==="plan"?"planMode":"autoMode"}function la(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function XP(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=[];for(let n of e)if(n&&typeof n=="object"&&"text"in n){let r=n.text;typeof r=="string"&&t.push(r)}return t.join(`
777
+ `)}return""}async function hu(e,t={}){if(!e||!zP(e))return{events:[],bytesRead:t.start??0,effortAtEnd:t.initialEffort??null,modesAtEnd:t.initialModes?{...t.initialModes}:Yd(),seenMessagesAtEnd:new Set(t.initialSeenMessages??[])};let n=[],r=new Set(t.initialSeenMessages??[]),i=t.initialEffort??null,s=t.initialModes?{...t.initialModes}:Yd(),a=t.start??0;return await new Promise(c=>{let l=VP(e,{encoding:"utf-8",start:t.start??0}),d=qP({input:l});d.on("line",f=>{a+=Buffer.byteLength(f,"utf-8")+1;let p=f.trim();if(!p)return;let h;try{h=JSON.parse(p)}catch{return}let g=h.sessionId??h.session_id??"",y=h.timestamp?Date.parse(h.timestamp):Date.now(),b=h.message?.role;if(h.type==="ai-title"&&typeof h.aiTitle=="string"){n.push({kind:"title",session_id:g,ts:y,title:h.aiTitle});return}if(h.type==="attachment"&&h.attachment?.type){let w=YP[h.attachment.type];w&&(s[JP(w.mode)]=w.active,n.push({kind:"mode",session_id:g,ts:y,mode:w.mode,active:w.active}));return}if(b==="user"){let w=XP(h.message?.content),k=Oi(w);k&&(i=k);let S={session_id:g,ts:y,text:w,effort_directive:k};n.push({kind:"user",...S});return}if(b==="assistant"){let w=h.message?.usage,k=typeof h.message?.id=="string"&&h.message.id?h.message.id:null,S=typeof h.requestId=="string"&&h.requestId?h.requestId:null,x=k??S,v=x!==null&&r.has(x);x!==null&&!v&&r.add(x);let E={session_id:g,ts:y,model:h.message?.model??null,input_tokens:v?0:la(w?.input_tokens),output_tokens:v?0:la(w?.output_tokens),cache_read_input_tokens:v?0:la(w?.cache_read_input_tokens),cache_creation_input_tokens:v?0:la(w?.cache_creation_input_tokens),effort:i,isSidechain:h.isSidechain===!0,...s.ultracode?{ultracode:!0}:{},...s.planMode?{planMode:!0}:{},...s.autoMode?{autoMode:!0}:{}};n.push({kind:"assistant",...E})}});let u=o(()=>({events:n,bytesRead:a,effortAtEnd:i,modesAtEnd:{...s},seenMessagesAtEnd:new Set(r)}),"finalResult");d.on("close",()=>c(u())),d.on("error",()=>c(u())),l.on("error",()=>c(u()))})}var YP,sv=_(()=>{"use strict";Qo();Jd();YP={ultra_effort_enter:{mode:"ultracode",active:!0},ultra_effort_exit:{mode:"ultracode",active:!1},plan_mode:{mode:"plan",active:!0},plan_mode_reentry:{mode:"plan",active:!0},plan_mode_exit:{mode:"plan",active:!1},auto_mode:{mode:"auto",active:!0},auto_mode_exit:{mode:"auto",active:!1}};o(JP,"modeFlagKey");o(la,"num");o(XP,"extractUserText");o(hu,"streamTranscript")});var ov=_(()=>{"use strict"});import{homedir as ZP}from"node:os";import{join as QP}from"node:path";function yu(e){return e.replace(/[/.]/g,"-")}var eM,gu,av=_(()=>{"use strict";eM=ZP(),gu=QP(eM,".claude","projects");o(yu,"projectPathFromCwd")});var Pn=_(()=>{"use strict";Jd();Cw();Iw();jw();Uw();na();Xw();pu();Zw();cu();Qw();iv();sv();Qo();ov();av()});import{parse as lM}from"jsonc-parser";function _u(e,t){let n=e.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0),r=t.split(/[.+-]/).slice(0,3).map(i=>Number.parseInt(i,10)||0);for(let i=0;i<3;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function wu(e){if(e.raw===null)return null;if(e.kind==="toml"){let a=/\[mcp_servers\.maind\]([\s\S]*?)(?=\n\[|$)/.exec(e.raw);if(!a)return null;let c=/^\s*command\s*=\s*"([^"]*)"/m.exec(a[1]),l=/^\s*args\s*=\s*\[([^\]]*)\]/m.exec(a[1]);return c?{command:c[1],args:l?[...l[1].matchAll(/"([^"]*)"/g)].map(d=>d[1]):[]}:null}let t=[],n=lM(e.raw,t,{allowTrailingComma:!0});if(t.length>0||typeof n!="object"||n===null)return null;let r=n,i=r.servers?.maind??r.mcpServers?.maind,s=i?.transport??i;return!s||typeof s.command!="string"?null:{command:s.command,args:Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[]}}function Nr(e,t){let n=`npm i -g ${Or}@${e}`;return t?`nvm use ${t} && ${n}`:n}function ua(e){let t=[],n=[e.runningVersion,...e.nodeTrees.map(f=>f.bridgeVersion).filter(f=>f!==null)],r=e.latestVersion??n.sort(_u).at(-1)??e.runningVersion;e.latestVersion===null&&t.push({check:"version",level:"info",message:`doctor ${e.runningVersion}; the npm registry was not reachable, so "published" is unknown and installs are not compared.`});let i=e.nodeTrees.filter(f=>f.bridgeVersion!==null);if(e.nodeTrees.length>0){let f=e.pathWinner?.node??null,p=e.nodeTrees.find(g=>g.node===f);if(e.pathWinner===null?t.push({check:"node-trees",level:"info",message:"no `maind-mcp-bridge` on PATH \u2014 only a client configured with the bare command needs it (see client-config)."}):p&&t.push({check:"node-trees",level:"ok",message:`PATH resolves maind-mcp-bridge to the ${p.node} tree (${p.bridgeVersion??"?"}).`}),e.nvmDefault!==null){let g=e.nodeTrees.find(y=>y.node===e.nvmDefault);g&&g.bridgeVersion===null&&t.push({check:"node-trees",level:"warn",message:`the nvm default ${g.node} has no bridge installed \u2014 after \`nvm use default\` (or in a fresh shell) the bin is gone.`,fix:Nr(r,g.node)})}if(new Set(i.map(g=>g.bridgeVersion)).size>1)for(let g of i.filter(y=>_u(y.bridgeVersion,r)<0))t.push({check:"node-trees",level:"warn",message:`${g.node} carries bridge ${g.bridgeVersion}, others carry a newer one \u2014 which one runs depends on PATH order, and \`npm ls -g\` only ever shows one.`,fix:Nr(r,g.node)})}let s=!1,a=new Map,c=o((f,p)=>{let h=a.get(f)??{version:e.installVersionOf(f),clients:[]};h.clients.push(p),a.set(f,h)},"noteInstall");for(let f of e.clientConfigs){let p=wu(f);if(p===null)continue;if(f.present===!1){t.push({check:"client-config",level:"warn",message:`${f.label}: ${f.path} names maind, but the client is not installed \u2014 nothing reads this file (a leftover of an earlier install).`,fix:"maind-mcp-bridge doctor --remove-phantoms"});continue}if(s=!0,/(^|\/)npx(\.cmd)?$/.test(p.command)&&p.args.some(y=>y.includes(Or))){t.push({check:"client-config",level:"warn",message:`${f.label} starts the bridge through npx \u2014 every cold start rebuilds better-sqlite3 and races the client's connect timeout.`,fix:`${Nr(r)}, then set "command": "maind-mcp-bridge" (no args) in ${f.path}`});continue}let g=/(^|[\\/])node(\.exe)?$/.test(p.command);if(g&&p.args.length>0){let y=p.args[0];if(!e.fileExists(y)){t.push({check:"client-config",level:"error",message:`${f.label} runs ${y}, which does not exist.`,fix:`re-run \`npx -y ${Or}@${r} install\` to rewrite the entry`});continue}c(y,f.label)}else if(p.command.includes("/")||p.command.includes("\\")){if(!e.fileExists(p.command)){t.push({check:"client-config",level:"error",message:`${f.label} points at ${p.command}, which does not exist.`,fix:`set "command": "maind-mcp-bridge" in ${f.path} (after ${Nr(r)})`});continue}}else if(p.command==="maind-mcp-bridge"&&e.pathWinner===null){t.push({check:"client-config",level:"error",message:`${f.label} runs \`maind-mcp-bridge\`, but nothing on PATH answers to it.`,fix:Nr(r,e.nvmDefault)});continue}g||(p.command.includes("/")||p.command.includes("\\")?c(p.command,f.label):p.command==="maind-mcp-bridge"&&e.pathWinner&&c(e.pathWinner.path,f.label)),t.push({check:"client-config",level:"ok",message:`${f.label}: ${[p.command,...p.args].join(" ")}`})}if(s||t.push({check:"client-config",level:"warn",message:"no installed MCP client's config names a `maind` server.",fix:`npx -y ${Or} install`}),e.latestVersion!==null)for(let[f,p]of a){let h=p.clients.join(", ");if(p.version===null)t.push({check:"version",level:"info",message:`${h}: cannot tell which bridge version ${f} is.`});else if(_u(p.version,e.latestVersion)<0){let g=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(f)?.[1]??null;t.push({check:"version",level:"warn",message:`${h} run bridge ${p.version} (${f}); published is ${e.latestVersion}. An installed bridge never updates itself.`,fix:g?Nr(e.latestVersion,g):`npx -y ${Or}@${e.latestVersion} install`})}else t.push({check:"version",level:"ok",message:`${h} run bridge ${p.version} (published: ${e.latestVersion}).`})}for(let{dir:f,maind:p}of e.npxStaleDirs)t.push({check:"npx-cache",level:p?"error":"info",message:p?`a half-built better-sqlite3 was left in ${f} \u2014 every npx start of this maind entry now fails with ENOTEMPTY.`:`a half-built better-sqlite3 was left in ${f} (another tool's npx entry, not maind's).`,fix:`rm -rf '${f.replace(/'/g,"'\\''")}'`});let l=e.envApiKey??e.apiKey;(e.deviceId===null||!dv.test(e.deviceId))&&t.push({check:"credentials",level:"error",message:"no valid device id \u2014 the server binds keys to a device, so every call ends in 401 invalid_or_device_required.",fix:"maind-mcp-bridge --reauth"}),l===null?t.push({check:"credentials",level:"error",message:"no API key stored and none in MAIND_API_KEY.",fix:"maind-mcp-bridge --reauth"}):dM.test(l)?t.push({check:"credentials",level:e.deviceId!==null&&dv.test(e.deviceId)?"ok":"info",message:`key ${l.slice(0,12)}\u2026 present${e.envApiKey?" (from MAIND_API_KEY)":""}. Whether the server still binds it to this device only the server can say \u2014 a 401 invalid_or_device_required means re-pair.`}):t.push({check:"credentials",level:"error",message:`the ${e.envApiKey?"MAIND_API_KEY value":"stored key"} is not a maind key (mnd_<8 hex>_<56 hex>).`,fix:e.envApiKey?"fix or remove MAIND_API_KEY in the client config":"maind-mcp-bridge --reauth"});let d=e.connection;if(d===null?t.push({check:"connection",level:"info",message:"no connection outcome recorded yet (bridges before 0.75.0 did not record one)."}):d.outcome==="ok"||d.outcome==="paired"?t.push({check:"connection",level:"ok",message:`last connection ${d.outcome==="ok"?"succeeded":"was paired"} at ${d.at} (bridge ${d.bridge_version}).`}):t.push({check:"connection",level:"error",message:d.outcome==="auth_failed"?`the server rejected the last connection (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 maind is not reachable until this device is paired again.`:`the bridge could not sign in (${d.at}${d.detail?`: ${d.detail}`:""}) \u2014 without a key nothing reaches maind.`,fix:"run `maind-mcp-bridge --reauth` in a terminal (it opens the browser), then restart the MCP client"}),e.claudeSettings!==null){let f=Ce(e.claudeSettings,{fileExists:o(h=>e.fileExists(h),"fileExists")}),p=e.pathWinner?e.installVersionOf(e.pathWinner.path):null;for(let h of f){if(h.status==="missing")continue;if(h.status!=="ok"){t.push({check:"hooks",level:h.status==="broken"?"error":"warn",message:h.detail});continue}let g=h.command?/(\S+\/build\/index\.js)/.exec(h.command)?.[1]??null:null,y=g?e.installVersionOf(g):null;y!==null&&p!==null&&y!==p&&t.push({check:"hooks",level:"warn",message:`${h.event}/${h.subcommand} runs bridge ${y}, the MCP server runs ${p} \u2014 writer and reader of the presence snapshot must be the same install.`,fix:`point the hook at the same install as the server: ${e.pathWinner?.path??"maind-mcp-bridge"} ${h.subcommand}`})}t.some(h=>h.check==="hooks")||t.push({check:"hooks",level:"ok",message:"every wired bridge hook points at an existing install."})}if(e.claudeSettings!==null){let f=e.guardMode??"off",p=Mo(e.claudeSettings,{guardMode:f,fileExists:o(b=>e.fileExists(b),"fileExists")}),g=`${e.bridgeCommand??(e.pathWinner?"maind-mcp-bridge":`npx -y ${Or}`)} install --hooks-only`,y=(e.declinedHooks??[]).includes(Ze);p.channel==="core"?t.push({check:"session-start",level:"ok",message:`Claude Code sessions receive the briefing and the project conventions at session start (${Ze} hook).`}):p.core.status==="broken"?t.push({check:"session-start",level:"warn",message:`the ${Ze} hook is wired, but its script is gone \u2014 sessions start without the project conventions (see the hooks finding for the fix).`}):p.channel==="guard"?t.push({check:"session-start",level:"info",message:`the briefing reaches Claude Code through the guard's guard-inject (guard mode ${f}); without the core ${Ze} hook it stops when the guard is switched off.`,fix:g}):y?t.push({check:"session-start",level:"info",message:`no session-start briefing \u2014 the ${Ze} hook was declined at install, so Claude Code sessions see only the MCP instructions, which it cuts after ~2,000 characters.`,fix:g}):t.push({check:"session-start",level:"warn",message:`no session-start briefing hook is wired (${Ze}) \u2014 Claude Code sessions start without the project conventions; the MCP instructions that do arrive are cut after ~2,000 characters.`,fix:g})}let u=e.context??null;if(u!==null&&e.claudeSettings!==null){let f=Ce(e.claudeSettings,{fileExists:o(p=>e.fileExists(p),"fileExists")}).filter(p=>(p.subcommand==="on-prompt-context"||p.subcommand==="on-read-context")&&p.status!=="missing").map(p=>p.subcommand);if(f.length>0){let p=t.length;u.sqlite.ok?u.repoRoot!==null&&!u.indexPresent&&t.push({check:"context",level:"info",message:`${u.repoRoot} has no code index \u2014 on-read-context stays silent there, and on-prompt-context can only match conventions.`,fix:"ask your agent to run codebase_index once (or run `maind index` in the repo); the Stop hook keeps it fresh after that"}):t.push({check:"context",level:"warn",message:`${f.join(" and ")} cannot read the local code index here \u2014 no SQLite backend loads (${u.sqlite.reason}). They stay silent.`,fix:"update Node to >= 22.16 (builtin SQLite), or run `npm rebuild better-sqlite3` in the bridge's install prefix"}),f.includes("on-prompt-context")&&u.repoRoot!==null&&!u.conventionsCached&&t.push({check:"context",level:"info",message:`no conventions are cached for ${u.repoRoot} yet \u2014 on-prompt-context matches them once the MAIND MCP server has started in this repo.`}),t.length===p&&t.push({check:"context",level:"ok",message:`${f.join(" and ")}: code index and cached conventions present${u.repoRoot?` for ${u.repoRoot}`:""}.`})}}return t}function uv(e){let t=e.filter(i=>i.level==="error"&&bu.includes(i.check)).sort((i,s)=>bu.indexOf(i.check)-bu.indexOf(s.check)),n=t[0];if(n===void 0)return uM(e);let r=t.length>1?` ${t.length-1} more finding(s).`:"";return`[maind] setup problem \u2014 ${n.message}`+(n.fix?` Fix: ${n.fix}.`:"")+r+" All findings with fixes: `maind-mcp-bridge doctor` (or `npx -y @maind-dev/mcp-bridge doctor`)."}function uM(e){let t=e.find(n=>n.check==="session-start"&&n.level==="warn");return t===void 0?null:`[maind] setup gap \u2014 ${t.message} Call get_session_briefing now to load them.`+(t.fix?` To add the hook, run in a terminal (append-only, asks consent per hook): ${t.fix}`:"")}function fv(e){let t={error:"\u2717",warn:"!",info:"\xB7",ok:"\u2713"},n={error:0,warn:1,info:2,ok:3},r=[...e].sort((a,c)=>n[a.level]-n[c.level]).flatMap(a=>[`${t[a.level]} [${a.check}] ${a.message}`,...a.fix?[` fix: ${a.fix}`]:[]]),i=e.filter(a=>a.level==="error").length,s=e.filter(a=>a.level==="warn").length;return r.push("",i+s===0?"maind-mcp-bridge doctor: nothing to fix.":`maind-mcp-bridge doctor: ${i} error(s), ${s} warning(s).`),r.push("A running MCP client does not reload its servers \u2014 restart it after a fix."),r.join(`
778
778
  `)+`
779
- `}var Nr,MP,Yw,uu,sa=_(()=>{"use strict";Oo();Mt();Nr="@maind-dev/mcp-bridge",MP=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,Yw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(du,"compareVersions");o(pu,"maindEntry");o(Ir,"installFix");o(ia,"diagnose");uu=["connection","client-config","npx-cache","hooks"];o(Jw,"sessionStartLine");o($P,"briefingGapLine");o(Xw,"renderFindings")});import{findNodeAtLocation as LP,parse as Zw,parseTree as FP,stripComments as jP}from"jsonc-parser";function Qw(e){let t=[];for(let n of e){if(n.present!==!1||n.kind!=="json"||n.raw===null||pu(n)===null)continue;let r=[],i=Zw(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!fu(i))continue;let s=fu(i.servers)&&"maind"in i.servers?"servers":"mcpServers",a=i[s];if(!fu(a)||!("maind"in a))continue;let c=Object.keys(a).filter(f=>f!=="maind").length,l=Object.keys(i).filter(f=>f!==s),d=jP(n.raw)!==n.raw;if(c===0&&l.length===0&&!d){t.push({label:n.label,path:n.path,action:"delete",raw:n.raw,next:null,keeps:null});continue}let u=[...c>0?[`${c} other server${c===1?"":"s"}`]:[],...l.length>0?[`keys ${l.join(", ")}`]:[],...d?["comments"]:[]].join(", "),p=UP(n.raw,[s,"maind"]);t.push(p===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${s}.maind by hand \u2014 it cannot be cut out cleanly; stays: ${u}`}:{label:n.label,path:n.path,action:"edit",raw:n.raw,next:p,keeps:`remove ${s}.maind; stays: ${u}`})}return t}function UP(e,t){let n=FP(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:LP(n,[...t])?.parent,i=r?.parent?.children;if(r===void 0||r.type!=="property"||i===void 0)return null;let s=i.indexOf(r),a=r.offset,c=r.offset+r.length;if(s+1<i.length)c=i[s+1].offset;else if(s>0){let u=i[s-1];a=u.offset+u.length}else{let u=r.parent;u!==void 0&&e.slice(u.offset+1,r.offset).trim()===""&&(a=u.offset+1);let p=/^\s*,/.exec(e.slice(c));p&&(c+=p[0].length)}let l=e.slice(0,a)+e.slice(c),d=[];return Zw(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function ev(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
779
+ `}var Or,dM,dv,bu,fa=_(()=>{"use strict";$o();Mt();Or="@maind-dev/mcp-bridge",dM=/^mnd_[a-f0-9]{8}_[a-f0-9]{56}$/,dv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(_u,"compareVersions");o(wu,"maindEntry");o(Nr,"installFix");o(ua,"diagnose");bu=["connection","client-config","npx-cache","hooks"];o(uv,"sessionStartLine");o(uM,"briefingGapLine");o(fv,"renderFindings")});import{findNodeAtLocation as fM,parse as pv,parseTree as pM,stripComments as mM}from"jsonc-parser";function mv(e){let t=[];for(let n of e){if(n.present!==!1||n.kind!=="json"||n.raw===null||wu(n)===null)continue;let r=[],i=pv(n.raw,r,{allowTrailingComma:!0});if(r.length>0||!vu(i))continue;let s=vu(i.servers)&&"maind"in i.servers?"servers":"mcpServers",a=i[s];if(!vu(a)||!("maind"in a))continue;let c=Object.keys(a).filter(p=>p!=="maind").length,l=Object.keys(i).filter(p=>p!==s),d=mM(n.raw)!==n.raw;if(c===0&&l.length===0&&!d){t.push({label:n.label,path:n.path,action:"delete",raw:n.raw,next:null,keeps:null});continue}let u=[...c>0?[`${c} other server${c===1?"":"s"}`]:[],...l.length>0?[`keys ${l.join(", ")}`]:[],...d?["comments"]:[]].join(", "),f=hM(n.raw,[s,"maind"]);t.push(f===null?{label:n.label,path:n.path,action:"manual",raw:n.raw,next:null,keeps:`remove ${s}.maind by hand \u2014 it cannot be cut out cleanly; stays: ${u}`}:{label:n.label,path:n.path,action:"edit",raw:n.raw,next:f,keeps:`remove ${s}.maind; stays: ${u}`})}return t}function hM(e,t){let n=pM(e,[],{allowTrailingComma:!0}),r=n===void 0?void 0:fM(n,[...t])?.parent,i=r?.parent?.children;if(r===void 0||r.type!=="property"||i===void 0)return null;let s=i.indexOf(r),a=r.offset,c=r.offset+r.length;if(s+1<i.length)c=i[s+1].offset;else if(s>0){let u=i[s-1];a=u.offset+u.length}else{let u=r.parent;u!==void 0&&e.slice(u.offset+1,r.offset).trim()===""&&(a=u.offset+1);let f=/^\s*,/.exec(e.slice(c));f&&(c+=f[0].length)}let l=e.slice(0,a)+e.slice(c),d=[];return pv(l,d,{allowTrailingComma:!0}),d.length===0?l:null}function hv(e,t){if(e.length===0)return`No phantom configs: every file that names maind belongs to an installed client.
780
780
  `;let n=["Configs that name maind for a client that is not installed \u2014 nothing reads them:",""];for(let r of e)n.push(` ${r.action.padEnd(6)} ${r.path}`),n.push(` ${r.label} \u2014 ${r.action==="delete"?"holds nothing but maind's entry":r.keeps}`);return n.push(""),n.push(t?"Applying (a file that changed since it was read is left alone):":"Dry run \u2014 nothing was changed. Apply with: maind-mcp-bridge doctor --remove-phantoms --yes"),n.join(`
781
781
  `)+`
782
- `}function fu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tv=_(()=>{"use strict";sa();o(Qw,"planPhantomRemovals");o(UP,"withoutProperty");o(ev,"renderPhantomPlan");o(fu,"isObject")});var ov={};Q(ov,{contextProbe:()=>sv,realProbe:()=>Mi,resolveNvmAlias:()=>iv,runDoctor:()=>QP});import{execFileSync as HP}from"node:child_process";import{existsSync as Di,readFileSync as BP,readdirSync as mu,realpathSync as GP,unlinkSync as WP}from"node:fs";import{homedir as Pi,platform as oa}from"node:os";import{delimiter as KP,dirname as nv,join as oe}from"node:path";function gt(e){try{return Di(e)?BP(e,"utf8"):null}catch{return null}}function VP(){try{let e=HP(oa()==="win32"?"npm.cmd":"npm",["view",rv,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function hu(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:oe(Pi(),".nvm")}function zP(){let e=oe(hu(),"versions","node"),t=[];try{t=mu(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=gt(oe(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),i=null;try{i=r?JSON.parse(r).version??null:null}catch{i=null}return{node:n,bridgeVersion:i}})}function iv(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let p=0;p<3;p++)if(d[p]!==u[p])return(d[p]??0)-(u[p]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let a=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(a)).at(-1)??null}function qP(e){let t=gt(oe(hu(),"alias","default"));return t===null?null:iv(t,e.map(n=>n.node),n=>{let r=gt(oe(hu(),"alias",n));return r===null?null:r})}function YP(){let e=oa()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(KP))if(t)for(let n of e){let r=oe(t,n);if(Di(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function JP(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:oa()==="win32"?oe(process.env.LOCALAPPDATA??oe(Pi(),"AppData","Local"),"npm-cache"):oe(Pi(),".npm"),t=oe(e,"_npx"),n=[],r=[];try{r=mu(t)}catch{return[]}for(let i of r)try{let s=mu(oe(t,i,"node_modules"));s.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:oe(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function XP(e){let t;try{t=nv(GP(e))}catch{return null}for(let n=0;n<6;n++){let r=gt(oe(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===rv)return s.version??null}catch{}let i=nv(t);if(i===t)break;t=i}return null}function sv(e){let t=Ft(e),n=!1;try{let i=gt(xr);n=i!==null&&typeof JSON.parse(i).conventions=="string"}catch{n=!1}let r=Co();return{repoRoot:t,indexPresent:t!==null&&Di(oe(t,Lt)),conventionsCached:n||t!==null&&Di(oe(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function Mi(e=process.cwd(),t={}){let n=zP(),r=gt(oe($e(),"device-id")),i=no({projectRoot:e,homeDir:Pi(),platform:oa(),env:process.env}),s=null;try{s=q()}catch{s=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=Ce(),l=Ee({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:B,latestVersion:t.offline===!0?null:VP(),nodeTrees:n,nvmDefault:qP(n),pathWinner:YP(),clientConfigs:_i(i).map(d=>({label:d.label,path:d.path,kind:d.kind,raw:gt(d.path),present:d.presence===void 0?null:Xl(d.presence,so)})),npxStaleDirs:JP(),connection:xy(),claudeSettings:gt(oe(Pi(),".claude","settings.json")),fileExists:o(d=>Di(d),"fileExists"),installVersionOf:XP,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:a.length>0?a:null,guardMode:ie(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?Ot(l):null,context:t.offline===!0?null:sv(e)}}async function ZP(e){let t=Qw(Mi(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(ev(t,e)),!e)return 0;let n=0;for(let r of t){if(r.action==="manual"){process.stdout.write(` left ${r.path} \u2014 remove the maind entry by hand
782
+ `}function vu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var gv=_(()=>{"use strict";fa();o(mv,"planPhantomRemovals");o(hM,"withoutProperty");o(hv,"renderPhantomPlan");o(vu,"isObject")});var vv={};ee(vv,{contextProbe:()=>wv,realProbe:()=>ji,resolveNvmAlias:()=>bv,runDoctor:()=>RM});import{execFileSync as gM}from"node:child_process";import{existsSync as Li,readFileSync as yM,readdirSync as ku,realpathSync as _M,unlinkSync as bM}from"node:fs";import{homedir as Fi,platform as pa}from"node:os";import{delimiter as wM,dirname as yv,join as ae}from"node:path";function gt(e){try{return Li(e)?yM(e,"utf8"):null}catch{return null}}function vM(){try{let e=gM(pa()==="win32"?"npm.cmd":"npm",["view",_v,"version","--prefer-online"],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim();return/^\d+\.\d+\.\d+/.test(e)?e:null}catch{return null}}function xu(){return process.env.NVM_DIR&&process.env.NVM_DIR.length>0?process.env.NVM_DIR:ae(Fi(),".nvm")}function kM(){let e=ae(xu(),"versions","node"),t=[];try{t=ku(e).filter(n=>n.startsWith("v"))}catch{return[]}return t.map(n=>{let r=gt(ae(e,n,"lib","node_modules","@maind-dev","mcp-bridge","package.json")),i=null;try{i=r?JSON.parse(r).version??null:null}catch{i=null}return{node:n,bridgeVersion:i}})}function bv(e,t,n){let r=e.trim();for(let c=0;c<5;c++){let l=n(r);if(l===null)break;r=l.trim()}let i=[...t].sort((c,l)=>{let d=c.slice(1).split(".").map(Number),u=l.slice(1).split(".").map(Number);for(let f=0;f<3;f++)if(d[f]!==u[f])return(d[f]??0)-(u[f]??0);return 0});if(r==="node"||r==="stable")return i.at(-1)??null;let s=r.startsWith("v")?r:`v${r}`;if(t.includes(s))return s;let a=s.endsWith(".")?s:`${s}.`;return i.filter(c=>c.startsWith(a)).at(-1)??null}function xM(e){let t=gt(ae(xu(),"alias","default"));return t===null?null:bv(t,e.map(n=>n.node),n=>{let r=gt(ae(xu(),"alias",n));return r===null?null:r})}function SM(){let e=pa()==="win32"?["maind-mcp-bridge.cmd","maind-mcp-bridge.exe","maind-mcp-bridge"]:["maind-mcp-bridge"];for(let t of(process.env.PATH??"").split(wM))if(t)for(let n of e){let r=ae(t,n);if(Li(r)){let i=/[\\/]versions[\\/]node[\\/](v[^\\/]+)[\\/]/.exec(r);return{node:i?i[1]:null,path:r}}}return null}function EM(){let e=process.env.npm_config_cache&&process.env.npm_config_cache.length>0?process.env.npm_config_cache:pa()==="win32"?ae(process.env.LOCALAPPDATA??ae(Fi(),"AppData","Local"),"npm-cache"):ae(Fi(),".npm"),t=ae(e,"_npx"),n=[],r=[];try{r=ku(t)}catch{return[]}for(let i of r)try{let s=ku(ae(t,i,"node_modules"));s.some(a=>a.startsWith(".better-sqlite3-"))&&n.push({dir:ae(t,i),maind:s.includes("@maind-dev")})}catch{}return n}function TM(e){let t;try{t=yv(_M(e))}catch{return null}for(let n=0;n<6;n++){let r=gt(ae(t,"package.json"));if(r!==null)try{let s=JSON.parse(r);if(s.name===_v)return s.version??null}catch{}let i=yv(t);if(i===t)break;t=i}return null}function wv(e){let t=Ft(e),n=!1;try{let i=gt(Er);n=i!==null&&typeof JSON.parse(i).conventions=="string"}catch{n=!1}let r=Do();return{repoRoot:t,indexPresent:t!==null&&Li(ae(t,Lt)),conventionsCached:n||t!==null&&Li(ae(t,".maind","conventions-cache.json")),sqlite:r.ok?{ok:!0}:{ok:!1,reason:r.reason}}}function ji(e=process.cwd(),t={}){let n=kM(),r=gt(ae(Le(),"device-id")),i=oo({projectRoot:e,homeDir:Fi(),platform:pa(),env:process.env}),s=null;try{s=Y()}catch{s=null}let a=(process.env.MAIND_API_KEY??"").trim(),c=Ie(),l=Te({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0});return{runningVersion:B,latestVersion:t.offline===!0?null:vM(),nodeTrees:n,nvmDefault:xM(n),pathWinner:SM(),clientConfigs:bi(i).map(d=>({label:d.label,path:d.path,kind:d.kind,raw:gt(d.path),present:d.presence===void 0?null:id(d.presence,lo)})),npxStaleDirs:EM(),connection:Oy(),claudeSettings:gt(ae(Fi(),".claude","settings.json")),fileExists:o(d=>Li(d),"fileExists"),installVersionOf:TM,deviceId:r===null?null:r.trim(),apiKey:s,envApiKey:a.length>0?a:null,guardMode:se(process.env,c).mode,declinedHooks:c?.declined_hooks??[],bridgeCommand:l.fallbackReason===null?Ot(l):null,context:t.offline===!0?null:wv(e)}}async function AM(e){let t=mv(ji(process.cwd(),{offline:!0}).clientConfigs);if(process.stdout.write(hv(t,e)),!e)return 0;let n=0;for(let r of t){if(r.action==="manual"){process.stdout.write(` left ${r.path} \u2014 remove the maind entry by hand
783
783
  `);continue}if(gt(r.path)!==r.raw){process.stdout.write(` skipped ${r.path} \u2014 changed since it was read
784
- `),n++;continue}try{r.action==="delete"?WP(r.path):await V(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
784
+ `),n++;continue}try{r.action==="delete"?bM(r.path):await z(r.path,r.next??r.raw),process.stdout.write(` ${r.action==="delete"?"deleted":"edited "} ${r.path}
785
785
  `)}catch(i){process.stdout.write(` failed ${r.path}: ${i instanceof Error?i.message:String(i)}
786
- `),n++}}return n>0?1:0}async function QP(e){if(e.includes("--remove-phantoms"))return ZP(e.includes("--yes"));let t=ia(Mi());return e.includes("--json")?process.stdout.write(JSON.stringify({version:B,findings:t},null,2)+`
787
- `):process.stdout.write(Xw(t)),t.some(n=>n.level==="error")?1:0}var rv,gu=_(()=>{"use strict";$t();Kl();Sr();fo();Bt();ue();Xe();wn();_e();fr();Zl();Le();sa();tv();rv="@maind-dev/mcp-bridge";o(gt,"readOrNull");o(VP,"latestVersion");o(hu,"nvmDir");o(zP,"nodeTrees");o(iv,"resolveNvmAlias");o(qP,"nvmDefault");o(YP,"pathWinner");o(JP,"npxStaleDirs");o(XP,"installVersionOf");o(sv,"contextProbe");o(Mi,"realProbe");o(ZP,"removePhantoms");o(QP,"runDoctor")});function eM(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":ne()}}async function av(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:eM(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var aa,yu=_(()=>{"use strict";ue();ur();aa=process.env.MAIND_ENDPOINT??dr("mcp-client-metrics-ingest");o(eM,"ingestHeaders");o(av,"postMetrics")});function cv(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function dv(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of s){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function Pn(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function $i(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function uv(e,t,n){let r=n.maxAgeMs??lv,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,a=dv(e,s),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)cv(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${$i(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${$i(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(cv(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${$i(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${$i(s)} ago, advisory \u2014 never a lock):
786
+ `),n++}}return n>0?1:0}async function RM(e){if(e.includes("--remove-phantoms"))return AM(e.includes("--yes"));let t=ua(ji());return e.includes("--json")?process.stdout.write(JSON.stringify({version:B,findings:t},null,2)+`
787
+ `):process.stdout.write(fv(t)),t.some(n=>n.level==="error")?1:0}var _v,Su=_(()=>{"use strict";$t();Zl();Tr();yo();Bt();ue();Qe();wn();_e();hr();sd();Fe();fa();gv();_v="@maind-dev/mcp-bridge";o(gt,"readOrNull");o(vM,"latestVersion");o(xu,"nvmDir");o(kM,"nodeTrees");o(bv,"resolveNvmAlias");o(xM,"nvmDefault");o(SM,"pathWinner");o(EM,"npxStaleDirs");o(TM,"installVersionOf");o(wv,"contextProbe");o(ji,"realProbe");o(AM,"removePhantoms");o(RM,"runDoctor")});function CM(e){return{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":re()}}async function kv(e,t,n){if(n.length===0)return{ok:!0,inserted:0};try{let r=await fetch(e,{method:"POST",headers:CM(t),body:JSON.stringify({metrics:n})});if(!r.ok){let s=await r.text().catch(()=>"");return{ok:!1,inserted:0,status:r.status,error:s.slice(0,500)}}return{ok:!0,inserted:(await r.json().catch(()=>null))?.inserted_metrics??n.length,status:r.status}}catch(r){return{ok:!1,inserted:0,error:r instanceof Error?r.message:String(r)}}}var ma,Eu=_(()=>{"use strict";ue();fr();ma=process.env.MAIND_ENDPOINT??ur("mcp-client-metrics-ingest");o(CM,"ingestHeaders");o(kv,"postMetrics")});function xv(e,t){return e===t||e===""||t===""?!0:e.startsWith(t+"/")||t.startsWith(e+"/")}function Ev(e,t){let n=[];for(let r of e.peers){if(typeof r!="object"||r===null)continue;let i=r,s=Array.isArray(i.active_claims)?i.active_claims:[],a=[];for(let c of s){if(typeof c!="object"||c===null)continue;let l=c;if(typeof l.path_prefix!="string")continue;let u=(typeof l.expires_in_seconds=="number"?l.expires_in_seconds:0)-t;u<=0||a.push({path_prefix:l.path_prefix,note:typeof l.note=="string"?l.note:null,remaining_seconds:Math.round(u)})}n.push({session_id_short:typeof i.session_id_short=="string"?i.session_id_short:"?",is_own_user:i.is_own_user===!0,branch:typeof i.branch=="string"?i.branch:null,focus:typeof i.focus=="string"?i.focus:null,machine_label:typeof i.machine_label=="string"?i.machine_label:null,last_seen_seconds:typeof i.last_seen_seconds=="number"?i.last_seen_seconds:0,claims:a,working_paths:Array.isArray(i.working_paths)?i.working_paths.filter(c=>typeof c=="string"):[]})}return n}function Mn(e,t){if(t.hostPids.length>0){let r=e.find(i=>t.hostPids.includes(i.own_ppid));if(r)return{snap:r,via:"ppid"}}let n=e.find(r=>r.cwd===t.cwd);return n?{snap:n,via:"cwd"}:null}function Ui(e){return e<90?`${Math.max(1,Math.round(e))}s`:`${Math.round(e/60)}m`}function Tv(e,t,n){let r=n.maxAgeMs??Sv,i=n.nowMs-Date.parse(e.written_at);if(!Number.isFinite(i)||i<0||i>r)return null;let s=i/1e3,a=Ev(e,s),c=[];for(let l of a)if(!(n.via==="cwd"&&(n.currentBranch===null||l.branch===null||l.branch===n.currentBranch))){for(let d of l.claims)xv(t,d.path_prefix)&&c.push(`'${d.path_prefix}' is CLAIMED by peer session ${l.session_id_short}${l.branch?` (branch ${l.branch}`:" ("}${l.machine_label?`, ${l.machine_label}`:""}${l.focus?`, focus: "${l.focus}"`:""}, last seen ${Ui(l.last_seen_seconds+s)} ago)${d.note?` \u2014 note: "${d.note}"`:""}, claim expires in ${Ui(d.remaining_seconds)}`);if(n.via==="ppid"&&l.is_own_user){for(let d of l.working_paths)if(xv(t,d)){c.push(`'${d}' has recent changes by your own peer session ${l.session_id_short}${l.branch?` (branch ${l.branch})`:""}, last seen ${Ui(l.last_seen_seconds+s)} ago`);break}}}return c.length===0?null:`[maind coordination] Editing '${t}' overlaps parallel work (view as of ${Ui(s)} ago, advisory \u2014 never a lock):
788
788
  `+c.map(l=>` \u2022 ${l}`).join(`
789
789
  `)+`
790
- Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function pv(e,t){let n=typeof e?.own_session_id=="string"?e.own_session_id.toLowerCase():null,r=t!==null?t.toLowerCase():null;return r!==null&&n!==null&&n!==r?{id:r,announceError:null}:{id:e?.own_session_id??null,announceError:e?.announce_error??null}}function fv(e,t,n,r=lv,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let a=s/1e3,c=dv(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,p=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",f=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${p}${f}) as of ${$i(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
791
- ${h}`:h}var lv,_u=_(()=>{"use strict";o(cv,"prefixConflict");lv=10*6e4;o(dv,"parsePeers");o(Pn,"selectOwnSnapshot");o($i,"ageDisplay");o(uv,"adviseOnPath");o(pv,"claimedIdentity");o(fv,"sessionStartSummary")});function hv(e){let t=[];for(let n of gv(e)){let r=aM(n);r&&!t.includes(r)&&t.push(r)}return t}function gv(e){let t=[],n="",r=null,i=0,s=[],a=o(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){s.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
790
+ Verify live before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: ["${t}"]}) \u2014 then claim_paths for your own edit area.`}function Av(e,t){let n=typeof e?.own_session_id=="string"?e.own_session_id.toLowerCase():null,r=t!==null?t.toLowerCase():null;return r!==null&&n!==null&&n!==r?{id:r,announceError:null}:{id:e?.own_session_id??null,announceError:e?.announce_error??null}}function Rv(e,t,n,r=Sv,i=null){if(!e)return null;let s=n-Date.parse(e.written_at);if(!Number.isFinite(s)||s<0||s>r)return null;let a=s/1e3,c=Ev(e,a),l=i!==null?`[maind] no live coordination session for this bridge \u2014 the last announce was rejected (${i}). Do NOT reuse a remembered session_id; a fresh announce_session({project_key}) registers this session.`:t!==null?`[maind] your coordination session: ${t} \u2014 pass as session_id to claim_paths / check_path_conflicts / announce_session (enriches THIS row instead of duplicating it).`:null;if(c.length===0)return l;let d=c.reduce((g,y)=>g+y.claims.length,0),u=c.filter(g=>g.focus===null&&g.working_paths.length===0&&g.claims.length===0).length,f=d>0?`${d} active claim${d===1?"":"s"}`:"no active claims",p=u>0?`, ${u} presence-only`:"",h=`[maind] ${c.length} peer session${c.length===1?"":"s"} on this repo (${f}${p}) as of ${Ui(a)} ago \u2014 before large edits: check_path_conflicts({project_key: "${e.project_key}", paths: [...]}).`;return l!==null?`${l}
791
+ ${h}`:h}var Sv,Tu=_(()=>{"use strict";o(xv,"prefixConflict");Sv=10*6e4;o(Ev,"parsePeers");o(Mn,"selectOwnSnapshot");o(Ui,"ageDisplay");o(Tv,"adviseOnPath");o(Av,"claimedIdentity");o(Rv,"sessionStartSummary")});function Iv(e){let t=[];for(let n of Nv(e)){let r=$M(n);r&&!t.includes(r)&&t.push(r)}return t}function Nv(e){let t=[],n="",r=null,i=0,s=[],a=o(()=>{n.trim()&&t.push(n),n=""},"flush");for(;i<e.length;){let c=e[i];if(r){if(c==="\\"&&r==='"'){n+=c+(e[i+1]??""),i+=2;continue}c===r&&(r=null),n+=c,i+=1;continue}if(c==="'"||c==='"'){r=c,n+=c,i+=1;continue}if(c==="<"&&e[i+1]==="<"){let l=/^<<-?\s*(?:'([^']+)'|"([^"]+)"|([A-Za-z_][\w-]*))/.exec(e.slice(i));if(l){s.push(l[1]??l[2]??l[3]),n+=l[0],i+=l[0].length;continue}}if(c===`
792
792
  `){if(s.length>0){let d=e.slice(i+1).split(`
793
- `),u=0;for(;s.length>0&&u<d.length;)d[u].trim()===s[0]&&s.shift(),u+=1;i+=1+d.slice(0,u).reduce((p,f)=>p+f.length+1,0),s=[],a();continue}a(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){a(),i+=2;continue}if(c===";"||c==="|"){a(),i+=1;continue}n+=c,i+=1}return a(),t}function aM(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(nM.test(a)){n+=1;continue}if(iM.has(a)){n+=1;continue}if(sM.has(a))return null;let c=a.split("/").pop()??a;if(rM.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!mv.test(i))return null;if(!tM.test(i))return bu;if(!oM.has(i))return i;let s=t[n+1];return s&&mv.test(s)?`${i} ${s}`:i}function wu(e){let t=hv(e).filter(n=>n!==bu&&!yv.has(n));return t.length>0?t[t.length-1]:null}var mv,tM,bu,nM,rM,iM,sM,oM,yv,vu=_(()=>{"use strict";mv=/^[A-Za-z][A-Za-z0-9._-]*$/,tM=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,bu="?",nM=/^[A-Za-z_][A-Za-z0-9_]*=/,rM=new Set(["sudo","env","time","nohup","nice","command","exec"]),iM=new Set(["do","then","else","elif","if","while","until","!","{","("]),sM=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),oM=new Set(["git","gh","npm","pnpm","yarn","npx","bun","deno","docker","kubectl","terraform","aws","gcloud","cargo","go","pip","poetry","uv","dotnet","mvn","supabase","vercel","brew","apt","systemctl"]);o(hv,"shellPrograms");o(gv,"commandSegments");o(aM,"programOf");yv=new Set(["echo","printf","cat","head","tail","less","more","grep","egrep","fgrep","rg","ag","sed","awk","cut","sort","uniq","wc","tr","tee","xargs","jq","yq","column","nl","diff","cmp","comm","ls","tree","find","fd","stat","file","du","df","basename","dirname","realpath","readlink","rm","cp","mv","mkdir","rmdir","touch","chmod","chown","ln","cd","pushd","popd","test","true","false","read","set","export","source","sleep","wait","which","whereis","type","date","printenv","ps","pgrep","lsof","kill","pkill","killall","id","whoami","uname","open","git log","git show","git status","git diff","git grep","git cat-file","git rev-parse","git ls-files","git blame","git branch","git remote","git config","git worktree","git stash","git merge-base","git describe","git reflog","git ls-remote","git for-each-ref","git symbolic-ref","git check-ignore"]);o(wu,"primaryVerb")});function _v(e){let t=e.length>ku?e.slice(-ku):e;return cM.some(n=>n.test(t))}function xu(e){return e.includes("maind")?lM.some(t=>e.includes(t)):!1}function bv(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function wv(e,t){if(!bv(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?wu(n):null}function Su(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=wv(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&_v(e.output)?"fail":"ok",verb:t}}var ku,cM,lM,vv=_(()=>{"use strict";vu();ku=8192,cM=[/\b[1-9]\d* (?:failed|failing)\b/,/^# fail [1-9]\d*/m,/\berror TS\d{4}\b/,/^npm ERR!/m,/\bERR_PNPM_[A-Z_]+/,/\bELIFECYCLE\b/,/\bCommand failed with exit code [1-9]/,/^Traceback \(most recent call last\):/m,/✖ [1-9]\d* problems? \([1-9]\d* errors?/,/^ERROR: {1,2}\S/m,/^--- FAIL: /m,/^error(?:\[E\d{4}\])?: /m,/^(?:Type|Reference|Syntax|Range)Error: /m,/^fatal: /m];o(_v,"outputShowsFailure");lM=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];o(xu,"isConsultationTool");o(bv,"isCountedTool");o(wv,"verbOfCall");o(Su,"observe")});function kv(e){let t=[...e].reverse().find(n=>typeof n.v=="string");return{start:e[0].t,end:e[e.length-1].t,failures:e,lastVerb:t?.v??null}}function Eu(e,t=-1/0){let n=e.filter(s=>s.k==="fail"&&s.t>t).slice().sort((s,a)=>s.t-a.t),r=[],i=[];for(let s of n)i.length>0&&s.t-i[i.length-1].t>6e5&&(r.push(kv(i)),i=[]),i.push(s);return i.length>0&&r.push(kv(i)),r}function Tu(e,t,n){if(t===null)return null;let r=null;for(let i of e)i.k==="ok"&&i.v===t&&i.t>n&&(r===null||i.t<r)&&(r=i.t);return r}function xv(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Or(e,t,n){let r=xv(e,t),i=Eu(e,r),s=i.length>0?i[i.length-1]:null,a=s!==null&&n-s.end<=6e5?s:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Tu(e,a.lastVerb,a.end)!==null,l=e.some(d=>d.k==="nudge"&&d.t>=a.start);return{open:a.failures.length>=4&&!c,chain:a,nudged:l,resolved:c}}function Au(e){return e.open&&!e.nudged}function Ru(e,t){let n=-1/0;for(let s of e)s.k==="prompt"&&s.t>n&&(n=s.t);let r=Math.max(t,n),i=Eu(e,r);for(let s=i.length-1;s>=0;s--){let a=i[s];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=Tu(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function Li(e){let t=new Map;for(let n of e.failures){let r=n.v??"?";t.set(r,(t.get(r)??0)+1)}return[...t.entries()].map(([n,r])=>r>1?`${n} \xD7${r}`:n).join(", ")}var Cu=_(()=>{"use strict";o(kv,"chainOf");o(Eu,"failureChains");o(Tu,"succeededAfter");o(xv,"resetPoint");o(Or,"difficultyStatus");o(Au,"shouldNudge");o(Ru,"captureCandidate");o(Li,"verbSummary")});function uM(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,s=typeof i=="string"&&dM.has(i)?i:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:a}}function la(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return ji;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=uM(i);s!==null&&(s.id===Fi?n=s:s.id===ca&&(r=s))}return{difficulty:n,capture:r}}function Dr(e){return e!==null&&e.enabled}function Iu(e){return Dr(e)&&e.severity==="required"}var Fi,ca,ji,dM,Nu=_(()=>{"use strict";Fi="conv_consult_on_difficulty",ca="conv_learning_capture_offer",ji={difficulty:null,capture:null},dM=new Set(["required","recommended","info"]);o(uM,"ruleOf");o(la,"extractTriggerPolicy");o(Dr,"isActive");o(Iu,"isDenyCapable")});function pM(e){return Math.max(1,Math.round(e/6e4))}function Ui(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${Li(e)}) and no maind consultation since they started (${Fi}). Before the next attempt, consult maind: search_lessons with the symptom \u2014 error code, tool or library, the failing program \u2014 never paths, file contents or secrets. If a hit applies, use it; if none does, say so in one line and go on. This hint appears once per episode.`}function Ou(e){return`difficulty episode (${e.failures.length} failed attempts: ${Li(e)}) without a maind consultation since it started (${Fi}, required)`}function Du(e,t="guard"){let n=pM(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${ca}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${Li(e)}), then ${r}. Before you finish, ask the user whether the finding should be recorded: (1) private memory (keep_memory), (2) lesson draft (run the submission routing gate first, then submit_content_draft), (3) project documentation (ADR or code note), or (4) no. Record nothing without an explicit yes. If the finding is trivial or already recorded, say so in one line instead (\`maind-skip: learning-capture <reason>\`). This hold happens once per episode.`}var Sv=_(()=>{"use strict";Cu();Nu();o(pM,"minutes");o(Ui,"nudgeText");o(Ou,"difficultyDenyHead");o(Du,"captureText")});var Pr=_(()=>{"use strict";vu();vv();Cu();Nu();Sv()});function Mn(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function Ne(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function da(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Tv(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Av(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Wt=_(()=>{"use strict";o(Mn,"denyPayload");o(Ne,"advisoryPayload");o(da,"postAdvisoryPayload");o(Tv,"postFailureAdvisoryPayload");o(Av,"promptAdvisoryPayload")});import{realpathSync as fM}from"node:fs";import{basename as Rv,dirname as Cv,join as mM}from"node:path";function $n(e){let t=Cv(e),n=[Rv(e)];for(;;)try{let r=fM(t);return mM(r,...n.reverse())}catch{let r=Cv(t);if(r===t)return e;n.push(Rv(t)),t=r}}var ua=_(()=>{"use strict";o($n,"realpathOfUnwritten")});import{existsSync as hM,realpathSync as gM,statSync as yM}from"node:fs";import{dirname as Iv,isAbsolute as _M,join as bM}from"node:path";function kM(e,t){let n=e.filter(i=>Nv.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
793
+ `),u=0;for(;s.length>0&&u<d.length;)d[u].trim()===s[0]&&s.shift(),u+=1;i+=1+d.slice(0,u).reduce((f,p)=>f+p.length+1,0),s=[],a();continue}a(),i+=1;continue}if(c==="&"&&e[i+1]==="&"||c==="|"&&e[i+1]==="|"){a(),i+=2;continue}if(c===";"||c==="|"){a(),i+=1;continue}n+=c,i+=1}return a(),t}function $M(e){let t=e.trim().split(/\s+/).filter(Boolean),n=0;for(;;){let a=t[n];if(a===void 0)return null;if(NM.test(a)){n+=1;continue}if(DM.has(a)){n+=1;continue}if(PM.has(a))return null;let c=a.split("/").pop()??a;if(OM.has(c)){n+=1;continue}break}let r=t[n],i=r.split("/").pop()??r;if(!Cv.test(i))return null;if(!IM.test(i))return Au;if(!MM.has(i))return i;let s=t[n+1];return s&&Cv.test(s)?`${i} ${s}`:i}function Ru(e){let t=Iv(e).filter(n=>n!==Au&&!Ov.has(n));return t.length>0?t[t.length-1]:null}var Cv,IM,Au,NM,OM,DM,PM,MM,Ov,Cu=_(()=>{"use strict";Cv=/^[A-Za-z][A-Za-z0-9._-]*$/,IM=/^[a-z][a-z0-9_.-]*[a-z0-9]$|^[a-z]$/,Au="?",NM=/^[A-Za-z_][A-Za-z0-9_]*=/,OM=new Set(["sudo","env","time","nohup","nice","command","exec"]),DM=new Set(["do","then","else","elif","if","while","until","!","{","("]),PM=new Set(["done","fi","esac","}",")","for","case","in","select","function","continue","break","return","exit"]),MM=new Set(["git","gh","npm","pnpm","yarn","npx","bun","deno","docker","kubectl","terraform","aws","gcloud","cargo","go","pip","poetry","uv","dotnet","mvn","supabase","vercel","brew","apt","systemctl"]);o(Iv,"shellPrograms");o(Nv,"commandSegments");o($M,"programOf");Ov=new Set(["echo","printf","cat","head","tail","less","more","grep","egrep","fgrep","rg","ag","sed","awk","cut","sort","uniq","wc","tr","tee","xargs","jq","yq","column","nl","diff","cmp","comm","ls","tree","find","fd","stat","file","du","df","basename","dirname","realpath","readlink","rm","cp","mv","mkdir","rmdir","touch","chmod","chown","ln","cd","pushd","popd","test","true","false","read","set","export","source","sleep","wait","which","whereis","type","date","printenv","ps","pgrep","lsof","kill","pkill","killall","id","whoami","uname","open","git log","git show","git status","git diff","git grep","git cat-file","git rev-parse","git ls-files","git blame","git branch","git remote","git config","git worktree","git stash","git merge-base","git describe","git reflog","git ls-remote","git for-each-ref","git symbolic-ref","git check-ignore"]);o(Ru,"primaryVerb")});function Dv(e){let t=e.length>Iu?e.slice(-Iu):e;return LM.some(n=>n.test(t))}function Nu(e){return e.includes("maind")?FM.some(t=>e.includes(t)):!1}function Pv(e){return e==="Bash"?!0:e.startsWith("mcp__")&&!e.startsWith("mcp__maind__")}function Mv(e,t){if(!Pv(e))return null;if(e!=="Bash")return e;let n=t!==null&&typeof t=="object"?t.command:void 0;return typeof n=="string"?Ru(n):null}function Ou(e){if(e.isInterrupt===!0||e.isSubagent===!0)return null;let t=Mv(e.tool,e.input);return t===null?null:{kind:e.failed||e.tool==="Bash"&&typeof e.output=="string"&&Dv(e.output)?"fail":"ok",verb:t}}var Iu,LM,FM,$v=_(()=>{"use strict";Cu();Iu=8192,LM=[/\b[1-9]\d* (?:failed|failing)\b/,/^# fail [1-9]\d*/m,/\berror TS\d{4}\b/,/^npm ERR!/m,/\bERR_PNPM_[A-Z_]+/,/\bELIFECYCLE\b/,/\bCommand failed with exit code [1-9]/,/^Traceback \(most recent call last\):/m,/✖ [1-9]\d* problems? \([1-9]\d* errors?/,/^ERROR: {1,2}\S/m,/^--- FAIL: /m,/^error(?:\[E\d{4}\])?: /m,/^(?:Type|Reference|Syntax|Range)Error: /m,/^fatal: /m];o(Dv,"outputShowsFailure");FM=["search_lessons","get_session_briefing","get_lesson","get_conventions","activate_skill","suggest_skills","codebase_change_briefing"];o(Nu,"isConsultationTool");o(Pv,"isCountedTool");o(Mv,"verbOfCall");o(Ou,"observe")});function Lv(e){let t=[...e].reverse().find(n=>typeof n.v=="string");return{start:e[0].t,end:e[e.length-1].t,failures:e,lastVerb:t?.v??null}}function Du(e,t=-1/0){let n=e.filter(s=>s.k==="fail"&&s.t>t).slice().sort((s,a)=>s.t-a.t),r=[],i=[];for(let s of n)i.length>0&&s.t-i[i.length-1].t>6e5&&(r.push(Lv(i)),i=[]),i.push(s);return i.length>0&&r.push(Lv(i)),r}function Pu(e,t,n){if(t===null)return null;let r=null;for(let i of e)i.k==="ok"&&i.v===t&&i.t>n&&(r===null||i.t<r)&&(r=i.t);return r}function Fv(e,t){let n=t??-1/0;for(let r of e)r.k==="skip"&&r.t>n&&(n=r.t);return n}function Dr(e,t,n){let r=Fv(e,t),i=Du(e,r),s=i.length>0?i[i.length-1]:null,a=s!==null&&n-s.end<=6e5?s:null;if(a===null)return{open:!1,chain:null,nudged:!1,resolved:!1};let c=Pu(e,a.lastVerb,a.end)!==null,l=e.some(d=>d.k==="nudge"&&d.t>=a.start);return{open:a.failures.length>=4&&!c,chain:a,nudged:l,resolved:c}}function Mu(e){return e.open&&!e.nudged}function $u(e,t){let n=-1/0;for(let s of e)s.k==="prompt"&&s.t>n&&(n=s.t);let r=Math.max(t,n),i=Du(e,r);for(let s=i.length-1;s>=0;s--){let a=i[s];if(a.failures.length<5||a.end-a.start<3e5)continue;let c=Pu(e,a.lastVerb,a.end);if(c!==null)return{...a,resolvedAt:c}}return null}function Hi(e){let t=new Map;for(let n of e.failures){let r=n.v??"?";t.set(r,(t.get(r)??0)+1)}return[...t.entries()].map(([n,r])=>r>1?`${n} \xD7${r}`:n).join(", ")}var Lu=_(()=>{"use strict";o(Lv,"chainOf");o(Du,"failureChains");o(Pu,"succeededAfter");o(Fv,"resetPoint");o(Dr,"difficultyStatus");o(Mu,"shouldNudge");o($u,"captureCandidate");o(Hi,"verbSummary")});function UM(e){let t=e.id;if(typeof t!="string")return null;let n=e.version,r=typeof n=="number"&&Number.isInteger(n)&&n>=1?n:1,i=e.severity,s=typeof i=="string"&&jM.has(i)?i:"recommended",a=e.enabled!==!1;return{id:t,version:r,severity:s,enabled:a}}function ga(e){let t=Array.isArray(e)?e:e!==null&&typeof e=="object"?e.conventions:void 0;if(!Array.isArray(t))return Gi;let n=null,r=null;for(let i of t){if(i===null||typeof i!="object")continue;let s=UM(i);s!==null&&(s.id===Bi?n=s:s.id===ha&&(r=s))}return{difficulty:n,capture:r}}function Pr(e){return e!==null&&e.enabled}function Fu(e){return Pr(e)&&e.severity==="required"}var Bi,ha,Gi,jM,ju=_(()=>{"use strict";Bi="conv_consult_on_difficulty",ha="conv_learning_capture_offer",Gi={difficulty:null,capture:null},jM=new Set(["required","recommended","info"]);o(UM,"ruleOf");o(ga,"extractTriggerPolicy");o(Pr,"isActive");o(Fu,"isDenyCapable")});function HM(e){return Math.max(1,Math.round(e/6e4))}function Wi(e,t="guard"){return`[maind ${t}] Difficulty: ${e.failures.length} failed attempts in a row (${Hi(e)}) and no maind consultation since they started (${Bi}). Before the next attempt, consult maind: search_lessons with the symptom \u2014 error code, tool or library, the failing program \u2014 never paths, file contents or secrets. If a hit applies, use it; if none does, say so in one line and go on. This hint appears once per episode.`}function Uu(e){return`difficulty episode (${e.failures.length} failed attempts: ${Hi(e)}) without a maind consultation since it started (${Bi}, required)`}function Hu(e,t="guard"){let n=HM(e.end-e.start),r=e.lastVerb?`\`${e.lastVerb}\` succeeded`:"it succeeded";return`[maind ${t}] Learning capture (${ha}): this conversation fought through a difficulty \u2014 ${e.failures.length} failed attempts over ${n} min (${Hi(e)}), then ${r}. Before you finish, ask the user whether the finding should be recorded: (1) private memory (keep_memory), (2) lesson draft (run the submission routing gate first, then submit_content_draft), (3) project documentation (ADR or code note), or (4) no. Record nothing without an explicit yes. If the finding is trivial or already recorded, say so in one line instead (\`maind-skip: learning-capture <reason>\`). This hold happens once per episode.`}var jv=_(()=>{"use strict";Lu();ju();o(HM,"minutes");o(Wi,"nudgeText");o(Uu,"difficultyDenyHead");o(Hu,"captureText")});var Mr=_(()=>{"use strict";Cu();$v();Lu();ju();jv()});function $n(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}function Oe(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:e}})}function ya(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e}})}function Hv(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:e}})}function Bv(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}})}var Wt=_(()=>{"use strict";o($n,"denyPayload");o(Oe,"advisoryPayload");o(ya,"postAdvisoryPayload");o(Hv,"postFailureAdvisoryPayload");o(Bv,"promptAdvisoryPayload")});import{realpathSync as BM}from"node:fs";import{basename as Gv,dirname as Wv,join as GM}from"node:path";function Ln(e){let t=Wv(e),n=[Gv(e)];for(;;)try{let r=BM(t);return GM(r,...n.reverse())}catch{let r=Wv(t);if(r===t)return e;n.push(Gv(t)),t=r}}var _a=_(()=>{"use strict";o(Ln,"realpathOfUnwritten")});import{execFileSync as WM}from"node:child_process";import{existsSync as KM}from"node:fs";import{join as Kv}from"node:path";function VM(e){try{let t=WM("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();return t?mr(t):null}catch{return null}}function Vv(e,t){try{if(!(t.isCheckoutRoot??(i=>KM(Kv(i,".git"))))(e)||Mi(t.memoryPath).has(e))return!1;let r=(t.keyOf??VM)(e);return $i(t.memoryPath,[{root:e,key:r}],t.now?.()??Date.now()),!0}catch{return!1}}var Ki,Bu=_(()=>{"use strict";Pn();He();Ee();Ki=Kv(Ue,"checkout-roots.json");o(VM,"originKey");o(Vv,"rememberEditCheckout")});import{existsSync as zM,realpathSync as qM,statSync as YM}from"node:fs";import{dirname as zv,isAbsolute as JM,join as XM}from"node:path";function e$(e,t){let n=e.filter(i=>qv.includes(i.id));if(n.length===0)return null;let r=n.map(i=>{let s=i.hint?`
794
794
  \u2192 ${i.hint}`:"";return` \u2022 ${i.title}
795
795
  ${i.detail}${s}`});return`maind repo-health (${t}) \u2014 checked once per session, before your first edit here:
796
796
 
@@ -798,42 +798,42 @@ ${h}`:h}var lv,_u=_(()=>{"use strict";o(cv,"prefixConflict");lv=10*6e4;o(dv,"par
798
798
 
799
799
  `)+`
800
800
 
801
- This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function xM(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function SM(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function Pu(e){let t=Iv(e);for(;;){try{if(yM(t).isDirectory())return t}catch{}let n=Iv(t);if(n===t)return t;t=n}}async function EM(e,t,n){let r=await n.load();if(xM(r,e,t))return null;SM(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>Nv.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:wM,metric_value:1},{session_id:e,metric_key:vM,metric_value:s}),await n.save(a),kM(i,t)}async function Ov(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=Ie(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=_M(r)?r:bM(i,r),a=hM(s)?gM(s):$n(s),c=dt(Pu(a)),l=await EM(n,c,{load:X,save:Ze,check:o(async d=>(await ti(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(Ne(l)),0}catch{return 0}}var Nv,wM,vM,Mu=_(()=>{"use strict";It();Nt();Wt();ge();ua();Qe();Nv=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],wM="repo_health_hook_runs",vM="repo_health_hook_findings";o(kM,"formatRepoHealth");o(xM,"alreadySeen");o(SM,"markSeen");o(Pu,"nearestExistingDir");o(EM,"repoHealthForEdit");o(Ov,"runOnRepoHealth")});import{existsSync as TM,readFileSync as AM,realpathSync as RM}from"node:fs";import{isAbsolute as Pv,join as Mv,posix as CM,relative as IM,sep as NM}from"node:path";function Dv(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function $M(e,t){return{contracts:t.filter(r=>Dv(r.spec)===e||Dv(r.impl)===e).map(r=>r.id),theme:PM.test(e),acl:MM.test(e)}}function LM(e){return e.contracts.length===0&&!e.theme&&!e.acl}function FM(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},a=s[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},s[t]=a,e.write_health_seen=s}return l}function jM(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
801
+ This is advisory; nothing is blocked. Resolve it before running build/test commands in this tree \u2014 otherwise the failure arrives later, disguised as your own change.`}function t$(e,t,n){return e.repo_health_seen?.[t]?.[n]!==void 0}function n$(e,t,n,r=Date.now()){let i=e.repo_health_seen??{},s=i[t]??{};s[n]=new Date(r).toISOString(),i[t]=s,e.repo_health_seen=i}function Gu(e){let t=zv(e);for(;;){try{if(YM(t).isDirectory())return t}catch{}let n=zv(t);if(n===t)return t;t=n}}async function r$(e,t,n){let r=await n.load();if(t$(r,e,t))return null;n$(r,e,t,n.now?.()),await n.save(r);let i;try{i=await n.check(t)}catch{return null}let s=i.filter(c=>qv.includes(c.id)).length,a=await n.load();return a.pending_metrics.push({session_id:e,metric_key:ZM,metric_value:1},{session_id:e,metric_key:QM,metric_value:s}),await n.save(a),e$(i,t)}async function Yv(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"";if(!n)return 0;let r=Ne(e);if(!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=JM(r)?r:XM(i,r),a=zM(s)?qM(s):Ln(s),c=ut(Gu(a));try{Vv(c,{memoryPath:Ki})}catch{}let l=await r$(n,c,{load:Z,save:et,check:o(async d=>(await ni(d,{includeRelease:!1})).findings,"check")});return l!==null&&process.stdout.write(Oe(l)),0}catch{return 0}}var qv,ZM,QM,Wu=_(()=>{"use strict";It();Nt();Bu();Wt();ge();_a();He();qv=["worktree.parity-missing","worktree.deps-missing","worktree.stale-package-build","worktree.detached-head","worktree.in-progress-op","setup.hooks-unwired"],ZM="repo_health_hook_runs",QM="repo_health_hook_findings";o(e$,"formatRepoHealth");o(t$,"alreadySeen");o(n$,"markSeen");o(Gu,"nearestExistingDir");o(r$,"repoHealthForEdit");o(Yv,"runOnRepoHealth")});import{existsSync as i$,readFileSync as s$,realpathSync as o$}from"node:fs";import{isAbsolute as Xv,join as Zv,posix as a$,relative as c$,sep as l$}from"node:path";function Jv(e){if(e===null||typeof e!="object")return null;let t=e.path;return typeof t=="string"&&t.length>0?t:null}function m$(e,t){return{contracts:t.filter(r=>Jv(r.spec)===e||Jv(r.impl)===e).map(r=>r.id),theme:f$.test(e),acl:p$.test(e)}}function h$(e){return e.contracts.length===0&&!e.theme&&!e.acl}function g$(e,t,n,r,i=Date.now()){let s=e.write_health_seen??{},a=s[t]??{},c=new Set(a[n]?.keys??[]),l=r.filter(d=>!c.has(d.key));if(l.length>0){for(let d of l)c.add(d.key);a[n]={at:new Date(i).toISOString(),keys:[...c]},s[t]=a,e.write_health_seen=s}return l}function y$(e,t){return e.length===0?null:`maind write-health \u2014 your edit to ${t} makes these checks relevant, and each finding below is reported once per session:
802
802
 
803
803
  `+e.map(n=>` \u2022 ${n.line}`).join(`
804
804
  `)+`
805
805
 
806
- Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function UM(e,t){let n=IM(e,t);return!n||n.startsWith("..")||Pv(n)?null:n.split(NM).join(CM.sep)}function HM(e){try{let t=AM(Mv(e,Rs),"utf8"),{manifest:n}=Os(t);return n?.contracts??[]}catch{return[]}}async function $v(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Ie(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=Pv(r)?r:Mv(i,r),a=TM(s)?RM(s):$n(s),c=dt(Pu(a)),l=UM(c,a);if(l===null)return 0;let d=$M(l,HM(c));if(LM(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await fn(c,{contracts:d.contracts});for(let y of g.findings)y.status==="open"&&u.push({key:`spec:${y.id}`,line:`spec-drift (${y.contract}): ${y.detail}`})}catch{}if(d.theme)try{let g=hn(c);for(let y of g.findings)y.status==="open"&&u.push({key:`theme:${y.file}:${y.klass}`,line:`theme-class-drift: \`${y.klass}\` in ${y.file} \u2014 no token \`--color-${y.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=mn(c);for(let y of g.findings)y.status==="open"&&u.push({key:`acl:${y.id}`,line:`table-acl-lint: \`${y.table}\` (created in ${y.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let p=await X(),f=FM(p,n,c,u);p.pending_metrics.push({session_id:n,metric_key:OM,metric_value:1},{session_id:n,metric_key:DM,metric_value:f.length}),await Ze(p);let h=jM(f,l);return h!==null&&process.stdout.write(da(h)),0}catch{return 0}}var OM,DM,PM,MM,Lv=_(()=>{"use strict";It();Nt();Wt();ge();Mu();ua();Qe();OM="write_health_hook_runs",DM="write_health_hook_findings",PM=/\.(tsx?|jsx?|css)$/,MM=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;o(Dv,"declPath");o($M,"routesForPath");o(LM,"routesAreEmpty");o(FM,"takeUnreported");o(jM,"formatWriteHealth");o(UM,"repoRelative");o(HM,"readContracts");o($v,"runOnWriteHealth")});var Jv={};Q(Jv,{agentHostPidCandidates:()=>et,closeTrackedSession:()=>Wv,effectiveConfig:()=>Ln,grandparentPid:()=>Vv,isCaptureTool:()=>$u,recordGuardSignals:()=>Gv,runFlush:()=>i$,runHookStatus:()=>s$,runOnFileEdit:()=>t$,runOnFileWrite:()=>e$,runOnRepoHealth:()=>Ov,runOnSessionStart:()=>qM,runOnToolUse:()=>XM,runOnWriteHealth:()=>$v,runSessionEndMetrics:()=>Fu,runSyncConfig:()=>a$,writeIdentitySideChannel:()=>Lu});import{execFileSync as jv}from"node:child_process";import{existsSync as ma,readFileSync as Uv,realpathSync as BM}from"node:fs";import{writeFile as GM}from"node:fs/promises";import{homedir as Hv}from"node:os";import{isAbsolute as fa,join as Hi,relative as Bv}from"node:path";function Gv(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=xu(n),s=n.includes("review_changes")||n.includes("review_verdict"),a=$u(n);if(!i&&!s&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),s&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function $u(e){return e.includes("maind")?e.includes("keep_memory")||e.includes("update_memory")||e.includes("graduate_memory")||e.includes("submit_content_draft")||e.includes("submit_convention_draft")||e.includes("revise_content_draft"):!1}function Wv(e,t,n=Date.now()){zM(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function zM(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-i>pa&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>pa&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>pa&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>pa&&delete e.sessions[n]}}function Ln(e){if(e.config)return e.config;let t=q();return t===null?null:{api_key:t,endpoint:aa}}function Kv(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function qM(){try{let r=Jw(ia(Mi(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
807
- `)}catch{}let e=await X();if(Ln(e)===null)return 0;let t=await G(),n=Yv(t);if(n===null)return 0;Kv(e,n),await Ze(e);try{Lu(t,n)}catch{}try{let r=Y();if(r!==null){let i=On(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=Pn(i,{hostPids:et(),cwd:s}),c=pv(a?.snap??null,Ii(kr(t)||null,n)),l=fv(a?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
808
- `);let d=Qi(Aa(n,zv(a?.snap??null,i,Date.now()),Date.now()));d!==null&&process.stdout.write(`[maind] ${d}
809
- `)}}catch{}try{let r=Re(YM());if(id(r)&&po(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
810
- `)}}catch{}return 0}function YM(){try{let e=Hi(Hv(),".claude","settings.json");return ma(e)?Uv(e,"utf8"):null}catch{return null}}function Lu(e,t,n,r=Tr()){let i=n??et();if(i.length===0)return;let s=Ii(kr(e)||null,t);if(s===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=kr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)gw({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:a,transcriptPath:c,model:l})}function Vv(){try{if(process.platform==="win32")return null;let e=jv("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function et(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=Vv();return n!==null&&n>1&&n!==t&&e.push(n),e}async function XM(){let e=await X();if(Ln(e)===null)return 0;let t=await G(),n=Yv(t)??"unknown",r=Kv(e,n);r.tool_call_count+=1;try{let a=et().filter(c=>yw(Tr(),c,JM));n!=="unknown"&&a.length>0&&Lu(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),Gv(e,n,i),$u(i)&&n!=="unknown"&&await J({event:"capture_taken",session_id:n,detail:i});let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let a=await Wd(r.transcript_path);a&&(r.token_count=a.total_tokens,await r$(e,r))}await Ze(e);try{let a=Date.now();if(n!=="unknown"&&!bp(n,a)){let c=Y();if(c!==null){let l=On(c),d=Pn(l,{hostPids:et(),cwd:typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd()}),u=Qi(Aa(n,zv(d?.snap??null,l,a),a));u!==null&&process.stdout.write(Ne(`[maind] ${u}`)+`
811
- `)}}}catch{}return 0}function zv(e,t,n){return e!==null?e.announce_error?[]:e.assigned_to_you??[]:t.find(i=>!i.announce_error&&n-Date.parse(i.written_at)<ZM)?.assigned_to_you??[]}function QM(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
806
+ Advisory; nothing is blocked. These are findings THIS branch introduces (pre-existing ones are graded out) \u2014 fix them now, or they surface at the gate.`}function _$(e,t){let n=c$(e,t);return!n||n.startsWith("..")||Xv(n)?null:n.split(l$).join(a$.sep)}function b$(e){try{let t=s$(Zv(e,Ds),"utf8"),{manifest:n}=Ls(t);return n?.contracts??[]}catch{return[]}}async function Qv(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=typeof e.session_id=="string"?e.session_id:"",r=Ne(e);if(!n||!r)return 0;let i=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),s=Xv(r)?r:Zv(i,r),a=i$(s)?o$(s):Ln(s),c=ut(Gu(a)),l=_$(c,a);if(l===null)return 0;let d=m$(l,b$(c));if(h$(d))return 0;let u=[];if(d.contracts.length>0)try{let g=await pn(c,{contracts:d.contracts});for(let y of g.findings)y.status==="open"&&u.push({key:`spec:${y.id}`,line:`spec-drift (${y.contract}): ${y.detail}`})}catch{}if(d.theme)try{let g=hn(c);for(let y of g.findings)y.status==="open"&&u.push({key:`theme:${y.file}:${y.klass}`,line:`theme-class-drift: \`${y.klass}\` in ${y.file} \u2014 no token \`--color-${y.token}\`; Tailwind generates NO rule, the class is a silent no-op.`})}catch{}if(d.acl)try{let g=mn(c);for(let y of g.findings)y.status==="open"&&u.push({key:`acl:${y.id}`,line:`table-acl-lint: \`${y.table}\` (created in ${y.createdIn}) never revoked its default grants \u2014 anon/authenticated keep CRUD on it.`})}catch{}let f=await Z(),p=g$(f,n,c,u);f.pending_metrics.push({session_id:n,metric_key:d$,metric_value:1},{session_id:n,metric_key:u$,metric_value:p.length}),await et(f);let h=y$(p,l);return h!==null&&process.stdout.write(ya(h)),0}catch{return 0}}var d$,u$,f$,p$,ek=_(()=>{"use strict";It();Nt();Wt();ge();Wu();_a();He();d$="write_health_hook_runs",u$="write_health_hook_findings",f$=/\.(tsx?|jsx?|css)$/,p$=/(^|\/)supabase\/migrations\/[^/]+\.sql$/;o(Jv,"declPath");o(m$,"routesForPath");o(h$,"routesAreEmpty");o(g$,"takeUnreported");o(y$,"formatWriteHealth");o(_$,"repoRelative");o(b$,"readContracts");o(Qv,"runOnWriteHealth")});var pk={};ee(pk,{agentHostPidCandidates:()=>tt,closeTrackedSession:()=>ak,effectiveConfig:()=>Fn,grandparentPid:()=>lk,isCaptureTool:()=>Ku,recordGuardSignals:()=>ok,runFlush:()=>$$,runHookStatus:()=>L$,runOnFileEdit:()=>D$,runOnFileWrite:()=>O$,runOnRepoHealth:()=>Yv,runOnSessionStart:()=>T$,runOnToolUse:()=>C$,runOnWriteHealth:()=>Qv,runSessionEndMetrics:()=>zu,runSyncConfig:()=>j$,writeIdentitySideChannel:()=>Vu});import{execFileSync as nk}from"node:child_process";import{existsSync as va,readFileSync as rk,realpathSync as w$}from"node:fs";import{writeFile as v$}from"node:fs/promises";import{homedir as ik}from"node:os";import{isAbsolute as wa,join as Vi,relative as sk}from"node:path";function ok(e,t,n,r=Date.now()){if(!n.includes("maind"))return;let i=Nu(n),s=n.includes("review_changes")||n.includes("review_verdict"),a=Ku(n);if(!i&&!s&&!a)return;let c=e.guard_signals??{},l=c[t]??{},d=new Date(r).toISOString();i&&(l.consulted_at=d),s&&(l.reviewed_at=d),a&&(l.captured_at=d),c[t]=l,e.guard_signals=c}function Ku(e){return e.includes("maind")?e.includes("keep_memory")||e.includes("update_memory")||e.includes("graduate_memory")||e.includes("submit_content_draft")||e.includes("submit_convention_draft")||e.includes("revise_content_draft"):!1}function ak(e,t,n=Date.now()){E$(e,n);let r=e.sessions[t];if(!r)return!1;let i=n-new Date(r.started_at).getTime();return e.pending_metrics.push({session_id:t,metric_key:"session_duration_ms",metric_value:Math.max(0,i)},{session_id:t,metric_key:"tool_call_count",metric_value:r.tool_call_count},{session_id:t,metric_key:"lessons_consulted",metric_value:r.lessons_consulted}),delete e.sessions[t],!0}function E$(e,t){if(e.guard_signals)for(let[n,r]of Object.entries(e.guard_signals)){let i=Math.max(Date.parse(r.consulted_at??"")||0,Date.parse(r.reviewed_at??"")||0,Date.parse(r.captured_at??"")||0);t-i>ba&&delete e.guard_signals[n]}if(e.repo_health_seen)for(let[n,r]of Object.entries(e.repo_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s)||0));t-i>ba&&delete e.repo_health_seen[n]}if(e.write_health_seen)for(let[n,r]of Object.entries(e.write_health_seen)){let i=Math.max(0,...Object.values(r).map(s=>Date.parse(s.at)||0));t-i>ba&&delete e.write_health_seen[n]}for(let[n,r]of Object.entries(e.sessions)){let i=Date.parse(r.started_at);!Number.isNaN(i)&&t-i>ba&&delete e.sessions[n]}}function Fn(e){if(e.config)return e.config;let t=Y();return t===null?null:{api_key:t,endpoint:ma}}function ck(e,t){let n=e.sessions[t];return n||(n={session_id:t,started_at:new Date().toISOString(),tool_call_count:0,lessons_consulted:0},e.sessions[t]=n),n}async function T$(){try{let r=uv(ua(ji(process.cwd(),{offline:!0})));r!==null&&process.stdout.write(r+`
807
+ `)}catch{}let e=await Z();if(Fn(e)===null)return 0;let t=await W(),n=fk(t);if(n===null)return 0;ck(e,n),await et(e);try{Vu(t,n)}catch{}try{let r=J();if(r!==null){let i=On(r),s=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),a=Mn(i,{hostPids:tt(),cwd:s}),c=Av(a?.snap??null,Ni(Sr(t)||null,n)),l=Rv(a?.snap??i[0]??null,c.id,Date.now(),void 0,c.announceError);l!==null&&process.stdout.write(l+`
808
+ `);let d=is(Pa(n,dk(a?.snap??null,i,Date.now()),Date.now()));d!==null&&process.stdout.write(`[maind] ${d}
809
+ `)}}catch{}try{let r=Ce(A$());if(ud(r)&&go(r)){let i=r.filter(s=>s.remedy==="run-install").map(s=>s.subcommand).join(", ");process.stderr.write(`[maind] New bridge capability not yet wired (${i}) \u2014 run \`maind-mcp-bridge install\` once (append-only, asks consent per hook).
810
+ `)}}catch{}return 0}function A$(){try{let e=Vi(ik(),".claude","settings.json");return va(e)?rk(e,"utf8"):null}catch{return null}}function Vu(e,t,n,r=Rr()){let i=n??tt();if(i.length===0)return;let s=Ni(Sr(e)||null,t);if(s===null)return;let a=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),c=Sr(e)||void 0,l=typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():void 0;for(let d of i)Ew({dir:r,agentPid:d,sessionId:t,transcriptStem:s,cwd:a,transcriptPath:c,model:l})}function lk(){try{if(process.platform==="win32")return null;let e=nk("ps",["-o","ppid=","-p",String(process.ppid)],{timeout:1e3,encoding:"utf8"}),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function tt(){let e=[],t=process.ppid;Number.isFinite(t)&&t>1&&e.push(t);let n=lk();return n!==null&&n>1&&n!==t&&e.push(n),e}async function C$(){let e=await Z();if(Fn(e)===null)return 0;let t=await W(),n=fk(t)??"unknown",r=ck(e,n);r.tool_call_count+=1;try{let a=tt().filter(c=>Tw(Rr(),c,R$));n!=="unknown"&&a.length>0&&Vu(t,n,a)}catch{}let i=(t.tool_name??"").toString();(i.includes("search_lessons")||i.includes("get_session_briefing")||i.includes("get_lesson"))&&(r.lessons_consulted+=1),ok(e,n,i),Ku(i)&&n!=="unknown"&&await X({event:"capture_taken",session_id:n,detail:i});let s=t.transcript_path;if(typeof s=="string"&&s&&!r.transcript_path&&(r.transcript_path=s),r.transcript_path){let a=await Xd(r.transcript_path);a&&(r.token_count=a.total_tokens,await M$(e,r))}await et(e);try{let a=Date.now();if(n!=="unknown"&&!Cf(n,a)){let c=J();if(c!==null){let l=On(c),d=Mn(l,{hostPids:tt(),cwd:typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd()}),u=is(Pa(n,dk(d?.snap??null,l,a),a));u!==null&&process.stdout.write(Oe(`[maind] ${u}`)+`
811
+ `)}}}catch{}return 0}function dk(e,t,n){return e!==null?e.announce_error?[]:e.assigned_to_you??[]:t.find(i=>!i.announce_error&&n-Date.parse(i.written_at)<I$)?.assigned_to_you??[]}function N$(e,t){let n=e.sightings.map(r=>` - ${r.path} (${r.where})`).join(`
812
812
  `);return`${t.prefix}${e.number} is already taken:
813
813
  ${n}
814
814
 
815
815
  Next free number in ${t.dir}: ${t.prefix}${e.suggestion}. Write the file under that number instead.
816
816
 
817
- Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function e$(){try{let e=await G();if((e.tool_name??"")!=="Write")return 0;let t=Ie(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=fa(t)?t:Hi(n,t);if(ma(r))return 0;let i=dt(n),s=Bv(i,$n(r));if(s.length===0||s.startsWith("..")||fa(s))return 0;let a=await pn(i,s);return!a.taken||a.namespace===null||process.stdout.write(Mn(QM(a,a.namespace))),0}catch{return 0}}async function t$(){try{let e=await G(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Ie(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=fa(n)?n:Hi(r,n),s=Y();if(s===null)return 0;let a=On(s);if(a.length===0)return 0;let c=Pn(a,{hostPids:et(),cwd:r});if(c===null)return 0;let l=dt(r),d=ma(i)?BM(i):$n(i),u=Bv(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||fa(u))return 0;let p=uv(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?n$(r):null,nowMs:Date.now()});return p===null||process.stdout.write(Ne(p)),0}catch{return 0}}function n$(e){try{let n=jv("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function r$(e,t){let n=Ad(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await GM(Hi(pt,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
817
+ Renumbering later is not the same cost: once the index entry, the links and the commit message name the number, every one of them has to be rewritten.`}async function O$(){try{let e=await W();if((e.tool_name??"")!=="Write")return 0;let t=Ne(e);if(!t)return 0;let n=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),r=wa(t)?t:Vi(n,t);if(va(r))return 0;let i=ut(n),s=sk(i,Ln(r));if(s.length===0||s.startsWith("..")||wa(s))return 0;let a=await fn(i,s);return!a.taken||a.namespace===null||process.stdout.write($n(N$(a,a.namespace))),0}catch{return 0}}async function D$(){try{let e=await W(),t=(e.tool_name??"").toString();if(t!=="Edit"&&t!=="Write")return 0;let n=Ne(e);if(!n)return 0;let r=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),i=wa(n)?n:Vi(r,n),s=J();if(s===null)return 0;let a=On(s);if(a.length===0)return 0;let c=Mn(a,{hostPids:tt(),cwd:r});if(c===null)return 0;let l=ut(r),d=va(i)?w$(i):Ln(i),u=sk(l,d).replace(/\\/g,"/");if(u.length===0||u.startsWith("..")||wa(u))return 0;let f=Tv(c.snap,u,{via:c.via,currentBranch:c.via==="cwd"?P$(r):null,nowMs:Date.now()});return f===null||process.stdout.write(Oe(f)),0}catch{return 0}}function P$(e){try{let n=nk("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,timeout:1e3,encoding:"utf8"}).trim();return n.length>0&&n!=="HEAD"?n:null}catch{return null}}async function M$(e,t){let n=Pd(e),r=t.token_count??0;if(n.model_token_limit<=0)return;let i=r/n.model_token_limit,s="ok";if(i>=n.handoff_at_pct/100?s="handoff_recommended":i>=n.warn_at_pct/100&&(s="warn"),t.last_advisory_status===s||(t.last_advisory_status=s,s==="ok"))return;let a=Math.round(i*100),c={session_id:t.session_id,status:s,tokens:r,ratio:Number(i.toFixed(3)),pct:a,thresholds:n,suggested_next:s==="handoff_recommended"?"use_generate_handoff_brief":"wrap_up_current_subtask",emitted_at:new Date().toISOString()};try{await v$(Vi(Ue,`handoff_advisory_${t.session_id}.json`),JSON.stringify(c,null,2))}catch(l){process.stderr.write(`[maind-mcp-bridge] failed to write advisory marker: ${l instanceof Error?l.message:String(l)}
818
818
  `)}s==="warn"?process.stderr.write(`[maind] \u26A0 Token usage at ~${a}% (warn threshold ${n.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
819
819
  `):process.stderr.write(`[maind] \u26D4 Token usage at ~${a}% (handoff threshold ${n.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
820
- `)}async function Fu(e){try{let t=await X(),n=Ln(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(Wv(t,r),await Ze(t)),await qv(n,KM)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
821
- `)}}async function i$(){let e=await X(),t=Ln(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await qv(t,VM);return process.stdout.write(JSON.stringify(n,null,2)+`
822
- `),n.ok?0:1}async function qv(e,t){let n=await X();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=av(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,s]);if(a.ok){let c=await X();return c.pending_metrics=c.pending_metrics.slice(r.length),await Ze(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function s$(){let e=await X(),t=Ln(e),n=o$(),r=id(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:Ad(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...po(n.findings)?{remedy:Fv}:{}}},null,2)+`
820
+ `)}async function zu(e){try{let t=await Z(),n=Fn(t);if(n===null)return;let r=e??Object.keys(t.sessions)[0];r&&t.sessions[r]&&(ak(t,r),await et(t)),await uk(n,x$)}catch(t){process.stderr.write(`[maind-mcp-bridge] session metrics failed: ${t instanceof Error?t.message:String(t)}
821
+ `)}}async function $$(){let e=await Z(),t=Fn(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=await uk(t,S$);return process.stdout.write(JSON.stringify(n,null,2)+`
822
+ `),n.ok?0:1}async function uk(e,t){let n=await Z();if(n.pending_metrics.length===0)return{ok:!0,flushed:0,remaining:0};let r=n.pending_metrics.slice(0,100),i=kv(e.endpoint,e.api_key,r),s=new Promise(c=>setTimeout(()=>c({ok:!1,inserted:0,error:"timeout"}),t)),a=await Promise.race([i,s]);if(a.ok){let c=await Z();return c.pending_metrics=c.pending_metrics.slice(r.length),await et(c),{ok:!0,flushed:r.length,remaining:c.pending_metrics.length}}return{ok:!1,flushed:0,remaining:n.pending_metrics.length,error:a.error}}async function L$(){let e=await Z(),t=Fn(e),n=F$(),r=ud(n.findings);if(process.stdout.write(JSON.stringify({paired:t!==null,source:e.config?"maind-hook init (legacy)":"bridge credential",endpoint:t?.endpoint??null,api_key_prefix:t?t.api_key.slice(0,12)+"\u2026":null,open_sessions:Object.keys(e.sessions).length,pending_metrics:e.pending_metrics.length,thresholds:Pd(e),thresholds_synced_at:e.thresholds_synced_at??e.config?.thresholds_synced_at??null,hook_wiring:{settings_file:n.settingsPath,ok:!r,hooks:n.findings.map(i=>({event:i.event,subcommand:i.subcommand,status:i.status,detail:i.detail})),...go(n.findings)?{remedy:tk}:{}}},null,2)+`
823
823
  `),r){process.stderr.write(`
824
824
  [maind] Claude Code hook wiring is incomplete:
825
825
  `);for(let i of n.findings)i.status!=="ok"&&process.stderr.write(` \u2022 ${i.detail}
826
- `);po(n.findings)&&process.stderr.write(` ${Fv}
827
- `)}return 0}function o$(){let e=Hi(Hv(),".claude","settings.json"),t=null;try{ma(e)&&(t=Uv(e,"utf8"))}catch{}return{settingsPath:e,findings:Re(t)}}async function a$(){let e=await X(),t=Ln(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??WM,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
826
+ `);go(n.findings)&&process.stderr.write(` ${tk}
827
+ `)}return 0}function F$(){let e=Vi(ik(),".claude","settings.json"),t=null;try{va(e)&&(t=rk(e,"utf8"))}catch{}return{settingsPath:e,findings:Ce(t)}}async function j$(){let e=await Z(),t=Fn(e);if(t===null)return process.stderr.write("[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"),1;let n=t.thresholds_endpoint??k$,r;try{r=await fetch(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.api_key}`}})}catch(a){return process.stderr.write(`[maind-mcp-bridge] sync-config network error: ${a instanceof Error?a.message:String(a)}
828
828
  `),1}if(!r.ok){process.stderr.write(`[maind-mcp-bridge] sync-config HTTP ${r.status} ${r.statusText}
829
829
  `);let a=await r.text().catch(()=>"");return a&&process.stderr.write(a.slice(0,500)+`
830
830
  `),1}let i;try{i=await r.json()}catch{return process.stderr.write(`[maind-mcp-bridge] sync-config: invalid JSON response
831
831
  `),1}let s=i;return typeof s.warn_at_pct!="number"||typeof s.handoff_at_pct!="number"||typeof s.model_token_limit!="number"?(process.stderr.write(`[maind-mcp-bridge] sync-config: response missing expected fields
832
- `),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await Ze(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
833
- `),0)}function Yv(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var WM,KM,VM,pa,JM,ZM,Fv,ju=_(()=>{"use strict";Cr();Pr();It();Nt();ht();ue();Mt();Vo();jr();Fe();yu();_u();qo();ge();Wt();ua();Qe();ur();sa();gu();Mu();Lv();WM=process.env.MAIND_THRESHOLDS_ENDPOINT??dr("get-context-thresholds"),KM=1500,VM=1e4,pa=7*24*60*60*1e3;o(Gv,"recordGuardSignals");o($u,"isCaptureTool");o(Wv,"closeTrackedSession");o(zM,"gcState");o(Ln,"effectiveConfig");o(Kv,"getOrCreateSession");o(qM,"runOnSessionStart");o(YM,"readSettingsRaw");o(Lu,"writeIdentitySideChannel");JM=6e4;o(Vv,"grandparentPid");o(et,"agentHostPidCandidates");o(XM,"runOnToolUse");ZM=5*6e4;o(zv,"assignedFrom");o(QM,"denyReason");o(e$,"runOnFileWrite");o(t$,"runOnFileEdit");o(n$,"currentGitBranch");o(r$,"maybeEmitAdvisory");o(Fu,"runSessionEndMetrics");o(i$,"runFlush");o(qv,"flushPending");o(s$,"runHookStatus");Fv="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";o(o$,"readHookWiring");o(a$,"runSyncConfig");o(Yv,"sessionIdOf")});function Xv(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var Zv=_(()=>{"use strict";o(Xv,"resolveConnection")});function ek(e,t,n,r=Date.now()){let i=t===null?null:tu(t),s=iu(e,i,{repoRoot:n,nowMs:r});return s.length===0?null:{slices:s,context_ok:i!==null}}var Qv,Uu=_(()=>{"use strict";Cr();Qv=2e3;o(ek,"buildCostPayload")});function nk(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!tk.test(n))return null;let r=n.toLowerCase();return t!==null&&tk.test(t)&&r!==t.toLowerCase()?null:r}var tk,rk=_(()=>{"use strict";tk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(nk,"snapshotSessionId")});async function ik(e){let t=e.now??Date.now,n=e.fetchContext(e.projectKey),{turns:r}=await Oi(e.transcriptPath),i=e.resolveRoot?su(r,e.resolveRoot):null,s=i&&e.projectKeyOf?e.projectKeyOf(i):null,a=i!==null&&s!==null&&s!==e.projectKey;a&&n.catch(()=>{});let[c,l,d]=await Promise.all([Vd(e.transcriptPath,{turns:r}),ou(e.transcriptPath),a?e.fetchContext(s):n]),u=i??e.repoRoot;if(e.sessionId&&(c.session_id=e.sessionId,l.session_id=e.sessionId),c.maind_connected=e.connection(c.maind_connected==="connected",t()),!c.session_id)return{posted:!1,contextOk:d!==null,sentSlices:!1};let p=ek(r,d,u,t()),f=Yd(c,l,{client_session_id:e.coordSessionId,client:"claude-code"},"live_bridge",p);return await e.post(f,p!==null),{posted:!0,contextOk:p?.context_ok??d!==null,sentSlices:p!==null}}var sk=_(()=>{"use strict";Cr();Uu();o(ik,"ingestSessionEnd")});var ck={};Q(ck,{runOnSessionEnd:()=>g$});import{execFileSync as Hu}from"node:child_process";function l$(e,t){try{let n=Y(),r=n!==null&&!Fd(process.env,Ce()),i=null;if(n!==null){let s=Pn(On(n),{hostPids:et(),cwd:process.cwd()});if(s){let a=Date.parse(s.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return Xv({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function d$(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=Y();if(r!==null){let i=Pn(On(r),{hostPids:et(),cwd:process.cwd()}),s=nk(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function u$(){try{let e=Hu("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function p$(e){let t=ok.get(e);if(t!==void 0)return t;let n=null;try{let r=Hu("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return ok.set(e,n),n}function f$(e){let t=ak.get(e);if(t!==void 0)return t;let n=null;try{let r=Hu("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=Xs(r))}catch{n=null}return ak.set(e,n),n}async function m$(e,t,n,r){if(n===null)return null;try{return await ut("get_session_cost_context",{project_key:n,...r?{session_id:r}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:B,timeoutMs:Qv})}catch{return null}}async function h$(e,t,n,r,i){let s=fetch(c$,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":B},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=qd(zd(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
834
- `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([s,a])}async function g$(){try{for(let i of et())_w(Tr(),i)}catch{}let e=q();if(!e)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=kr(t);if(r)try{let i=ne(),s=d$(Ii(r,n)),a=Y();await ik({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:s,repoRoot:u$(),resolveRoot:p$,projectKeyOf:f$,fetchContext:o(c=>m$(e,i,c,s),"fetchContext"),post:o((c,l)=>h$(e,i,c,1500,l),"post"),connection:l$})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
835
- `)}return await Fu(n),0}var c$,ok,ak,lk=_(()=>{"use strict";Cr();$t();ue();An();yu();_u();ge();ju();jd();Vo();Fe();qo();Le();Zv();Uu();rk();sk();c$=aa;o(l$,"connectionVerdict");o(d$,"presenceSessionId");o(u$,"sessionRepoRoot");ok=new Map;o(p$,"gitRootOf");ak=new Map;o(f$,"projectKeyOfRoot");o(m$,"fetchCostContext");o(h$,"postWithTimeout");o(g$,"runOnSessionEnd")});var dk={};Q(dk,{runOnSessionBriefing:()=>y$});async function y$(){try{return await Lo("core",await G())}catch{return 0}}var uk=_(()=>{"use strict";Sr();ge();o(y$,"runOnSessionBriefing")});function _$(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function pk(e,t,n=process.stdout){let r=_$(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
836
- `),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of gr)s.push(await ud(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
832
+ `),1):(e.thresholds={warn_at_pct:s.warn_at_pct,handoff_at_pct:s.handoff_at_pct,model_token_limit:s.model_token_limit},e.thresholds_synced_at=new Date().toISOString(),await et(e),process.stdout.write(JSON.stringify({ok:!0,thresholds:e.thresholds,synced_at:e.thresholds_synced_at},null,2)+`
833
+ `),0)}function fk(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";return t.length>0?t:null}var k$,x$,S$,ba,R$,I$,tk,qu=_(()=>{"use strict";Pn();Mr();It();Nt();ht();ue();Mt();Jo();Ur();Ee();Eu();Tu();Zo();ge();Wt();_a();He();fr();fa();Su();Wu();ek();k$=process.env.MAIND_THRESHOLDS_ENDPOINT??ur("get-context-thresholds"),x$=1500,S$=1e4,ba=7*24*60*60*1e3;o(ok,"recordGuardSignals");o(Ku,"isCaptureTool");o(ak,"closeTrackedSession");o(E$,"gcState");o(Fn,"effectiveConfig");o(ck,"getOrCreateSession");o(T$,"runOnSessionStart");o(A$,"readSettingsRaw");o(Vu,"writeIdentitySideChannel");R$=6e4;o(lk,"grandparentPid");o(tt,"agentHostPidCandidates");o(C$,"runOnToolUse");I$=5*6e4;o(dk,"assignedFrom");o(N$,"denyReason");o(O$,"runOnFileWrite");o(D$,"runOnFileEdit");o(P$,"currentGitBranch");o(M$,"maybeEmitAdvisory");o(zu,"runSessionEndMetrics");o($$,"runFlush");o(uk,"flushPending");o(L$,"runHookStatus");tk="Re-run `maind-mcp-bridge install` to add the missing hooks \u2014 it is append-only and idempotent: it adds only what is absent, asks consent per hook, and never rewrites an entry you already have.";o(F$,"readHookWiring");o(j$,"runSyncConfig");o(fk,"sessionIdOf")});function mk(e){return e.ownSnapshotAgeMs!==null&&e.ownSnapshotAgeMs<=18e5||e.sawMaindCall?"connected":e.presenceUsable?"not_connected":"unknown"}var hk=_(()=>{"use strict";o(mk,"resolveConnection")});function yk(e,t,n,r=Date.now()){let i=t===null?null:Pi(t),s=typeof n=="object"&&n!==null?n:{repoRoot:n},a=au(e,i,{repoRoot:s.repoRoot,...s.relativize?{relativize:s.relativize}:{},nowMs:r});return a.length===0?null:{slices:a,context_ok:i!==null}}var gk,Yu=_(()=>{"use strict";Pn();gk=2e3;o(yk,"buildCostPayload")});function bk(e,t=null){if(!e||e.announce_error!=null)return null;let n=e.own_session_id;if(typeof n!="string"||!_k.test(n))return null;let r=n.toLowerCase();return t!==null&&_k.test(t)&&r!==t.toLowerCase()?null:r}var _k,wk=_(()=>{"use strict";_k=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(bk,"snapshotSessionId")});function H$(e){let t=[];for(let n of e){if(typeof n!="string")continue;let r=n.trim().toLowerCase();U$.test(r)&&!t.includes(r)&&t.push(r)}return t}async function vk(e){let t=e.now??Date.now,{turns:n,coordination_ids:r}=await Di(e.transcriptPath),i=e.resolveRoot&&e.projectKeyOf?du({gitRoot:e.resolveRoot,keyOfRoot:e.projectKeyOf,known:B$(()=>e.knownCheckouts?.()??null,null),...e.isDir?{isDir:e.isDir}:{}}):null,s=i?uu(n,i):null,a=s??e.projectKey,c=H$([e.coordSessionId,e.sessionId,...r]),[l,d,u]=await Promise.all([Qd(e.transcriptPath,{turns:n}),mu(e.transcriptPath),e.fetchContext(a,c)]);if(i&&e.rememberCheckouts)try{e.rememberCheckouts(i.seenLive())}catch{}if(e.sessionId&&(l.session_id=e.sessionId,d.session_id=e.sessionId),l.maind_connected=e.connection(l.maind_connected==="connected",t()),!l.session_id)return{posted:!1,contextOk:u!==null,sentSlices:!1};let f=s&&i?fu(s,i):null,p=yk(n,u,{repoRoot:e.repoRoot,relativize:f},t()),h=u===null?null:Pi(u)?.canonical_session_id??null,g=e.coordSessionId??h,y=nu(l,d,{client_session_id:g,client:"claude-code",coordination_session_ids:c},"live_bridge",p);return await e.post(y,p!==null),{posted:!0,contextOk:p?.context_ok??u!==null,sentSlices:p!==null}}function B$(e,t){try{return e()}catch{return t}}var U$,kk=_(()=>{"use strict";Pn();Yu();U$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;o(H$,"sessionIdsFor");o(vk,"ingestSessionEnd");o(B$,"safe")});var Ek={};ee(Ek,{runOnSessionEnd:()=>Q$});import{execFileSync as Ju}from"node:child_process";import{statSync as G$}from"node:fs";function K$(e,t){try{let n=J(),r=n!==null&&!Kd(process.env,Ie()),i=null;if(n!==null){let s=Mn(On(n),{hostPids:tt(),cwd:process.cwd()});if(s){let a=Date.parse(s.snap.written_at);i=Number.isFinite(a)?Math.max(0,t-a):null}}return mk({ownSnapshotAgeMs:i,sawMaindCall:e,presenceUsable:r})}catch{return e?"connected":"unknown"}}function V$(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;try{let r=J();if(r!==null){let i=Mn(On(r),{hostPids:tt(),cwd:process.cwd()}),s=bk(i?.snap,e);if(s!==null)return s}}catch{}let n=(process.env.MAIND_SESSION_ID??"").trim().toLowerCase();return t.test(n)?n:null}function z$(){try{let e=Ju("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();return e.length>0?e:null}catch{return null}}function q$(e){let t=xk.get(e);if(t!==void 0)return t;let n=null;try{let r=Ju("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();n=r.length>0?r:null}catch{n=null}return xk.set(e,n),n}function Y$(e){let t=Sk.get(e);if(t!==void 0)return t;let n=null;try{let r=Ju("git",["-C",e,"config","--get","remote.origin.url"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim();r&&(n=mr(r))}catch{n=null}return Sk.set(e,n),n}function J$(e){try{return G$(e).isDirectory()}catch{return!1}}async function X$(e,t,n,r){if(n===null)return null;let[i,...s]=r;try{return await ft("get_session_cost_context",{project_key:n,...i?{session_id:i}:{},...s.length>0?{also_session_ids:s}:{}},{apiKey:e,deviceId:t,projectKey:n,bridgeVersion:B,timeoutMs:gk})}catch{return null}}async function Z$(e,t,n,r,i){let s=fetch(W$,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`,"x-maind-device-id":t,"x-maind-bridge-version":B},body:JSON.stringify(n)}).then(async c=>{if(!c.ok)return;let l=tu(eu(await c.json().catch(()=>null)),i);l!==null&&process.stderr.write(`[maind] ${l}
834
+ `)}).catch(()=>{}),a=new Promise(c=>setTimeout(c,r));await Promise.race([s,a])}async function Q$(){try{for(let i of tt())Aw(Rr(),i)}catch{}let e=Y();if(!e)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id?t.session_id:null,r=Sr(t);if(r)try{let i=re(),s=V$(Ni(r,n)),a=J();await vk({apiKey:e,deviceId:i,sessionId:n,transcriptPath:r,projectKey:a,coordSessionId:s,repoRoot:z$(),resolveRoot:q$,projectKeyOf:Y$,knownCheckouts:o(()=>Mi(Ki),"knownCheckouts"),isDir:J$,rememberCheckouts:o(c=>$i(Ki,c),"rememberCheckouts"),fetchContext:o((c,l)=>X$(e,i,c,l),"fetchContext"),post:o((c,l)=>Z$(e,i,c,1500,l),"post"),connection:K$})}catch(i){process.stderr.write(`[maind-mcp-bridge] session-end ingest failed: ${i instanceof Error?i.message:String(i)}
835
+ `)}return await zu(n),0}var W$,xk,Sk,Tk=_(()=>{"use strict";Pn();$t();ue();An();Eu();Tu();ge();qu();Vd();Jo();Ee();Zo();Fe();Bu();hk();Yu();wk();kk();W$=ma;o(K$,"connectionVerdict");o(V$,"presenceSessionId");o(z$,"sessionRepoRoot");xk=new Map;o(q$,"gitRootOf");Sk=new Map;o(Y$,"projectKeyOfRoot");o(J$,"isDirectory");o(X$,"fetchCostContext");o(Z$,"postWithTimeout");o(Q$,"runOnSessionEnd")});var Ak={};ee(Ak,{runOnSessionBriefing:()=>eL});async function eL(){try{return await Ho("core",await W())}catch{return 0}}var Rk=_(()=>{"use strict";Tr();ge();o(eL,"runOnSessionBriefing")});function tL(e){let t={mode:"warn",stopGate:!1,full:!1,dryRun:!1};for(let n=0;n<e.length;n++)switch(e[n]){case"--mode":{let i=e[++n];if(i!=="warn"&&i!=="block")return null;t.mode=i;break}case"--stop-gate":t.stopGate=!0;break;case"--full":case"--yes":t.full=!0;break;case"--dry-run":t.dryRun=!0;break;default:return null}return t}async function Ck(e,t,n=process.stdout){let r=tL(e);if(r===null)return n.write(`usage: maind-mcp-bridge guard install [--mode warn|block] [--stop-gate] [--full] [--dry-run]
836
+ `),1;let i={homeDir:t,isInteractive:process.stdin.isTTY===!0,full:r.full,skip:!1,dryRun:r.dryRun,out:n},s=[];for(let l of _r)s.push(await _d(i,l));for(let l of s)n.write(` ${l.status.padEnd(12)} ${l.target}${l.detail?` \u2014 ${l.detail}`:""}
837
837
  `);let a=s.some(l=>l.detail==="user declined"),c=s.some(l=>l.status==="failed");return r.dryRun?(n.write(`
838
838
  [dry-run] would set guard_mode=${r.mode}`+(r.stopGate?" + guard_stop_gate=true":"")+` in the bridge config.
839
839
  `),0):(await Rn({guard_mode:r.mode,...r.stopGate?{guard_stop_gate:!0}:{}}),n.write(`
@@ -843,9 +843,9 @@ Guard mode: ${r.mode}`+(r.stopGate?" (+ strict stop-gate)":"")+`
843
843
  check: maind-mcp-bridge guard status
844
844
  Takes effect for NEW Claude Code sessions (hooks are read at session start).
845
845
  `),a&&n.write(`Note: at least one hook was declined \u2014 the guard runs with what was consented.
846
- `),c?1:0)}var fk=_(()=>{"use strict";Mt();fd();Xe();o(_$,"parseGuardInstallFlags");o(pk,"runGuardInstall")});import{existsSync as mk}from"node:fs";import{appendFile as b$,mkdir as w$,readFile as v$}from"node:fs/promises";import{join as k$}from"node:path";function Bu(e,t=ha){return k$(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function Mr(e,t=ha){return mk(Bu(e,t))}async function Kt(e,t,n=ha){try{await w$(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await b$(Bu(e,n),r+`
847
- `,{mode:384})}catch{}}async function Fn(e,t=ha){try{let n=Bu(e,t);if(!mk(n))return[];let r=[];for(let i of(await v$(n,"utf8")).split(`
848
- `))if(i.trim())try{let s=JSON.parse(i),a=s.t,c=s.k,l=s.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!x$.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var ha,x$,Bi=_(()=>{"use strict";mt();ha=Cd,x$=new Set(["fail","ok","nudge","skip","prompt"]);o(Bu,"triggerLogPath");o(Mr,"hasTriggerLog");o(Kt,"appendTriggerEvent");o(Fn,"loadTriggerEvents")});import{existsSync as S$}from"node:fs";import{mkdir as E$,readFile as T$,rename as A$,writeFile as R$}from"node:fs/promises";import{dirname as C$,join as I$}from"node:path";function Gi(e=process.env){let t=q();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??Ei,keyFp:lr(t)}}async function Gu(e,t=Date.now(),n=ga){try{if(!S$(n))return null;let r=JSON.parse(await T$(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let s=r.policy;return{policy:la([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<N$}}catch{return null}}async function D$(e,t,n,r){try{await E$(C$(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},s=`${r}.tmp`;await R$(s,JSON.stringify(i,null,2),{mode:384}),await A$(s,r)}catch{}}async function P$(){let e=q();if(e===null)return null;let t=null;try{t=Y()}catch{t=null}let n=await ut("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:M$(),projectKey:t,bridgeVersion:B,timeoutMs:O$});if(n===null)return null;try{return la(JSON.parse(n))}catch{return null}}async function $r(e,t={}){let n=t.nowMs??Date.now(),r=t.file??ga,i=t.identity===void 0?Gi():t.identity;if(i===null)return ji;let s=await Gu(i,n,r);if(s?.fresh)return s.policy;if(e){let a=await(t.fetcher??P$)();if(a!==null)return await D$(i,a,n,r),a}return s?.policy??ji}function M$(){try{return ne()}catch{return null}}var ga,N$,O$,Lr=_(()=>{"use strict";Pr();Nt();ue();Fe();Le();An();mt();ga=I$(Ue,"trigger-policy.json"),N$=12*60*60*1e3,O$=3e3;o(Gi,"currentIdentity");o(Gu,"readCachedPolicy");o(D$,"writeCachedPolicy");o(P$,"fetchTriggerPolicy");o($r,"resolveTriggerPolicy");o(M$,"safeDeviceId")});var gk={};Q(gk,{runGuard:()=>U$});import{existsSync as $$,readFileSync as L$}from"node:fs";import{homedir as hk}from"node:os";import{join as F$}from"node:path";async function U$(e){let t=e[0],n=e.slice(1);switch(t){case"install":return pk(n,hk());case"status":return B$();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
846
+ `),c?1:0)}var Ik=_(()=>{"use strict";Mt();wd();Qe();o(tL,"parseGuardInstallFlags");o(Ck,"runGuardInstall")});import{existsSync as Nk}from"node:fs";import{appendFile as nL,mkdir as rL,readFile as iL}from"node:fs/promises";import{join as sL}from"node:path";function Xu(e,t=ka){return sL(t,e.replace(/[^a-zA-Z0-9._-]/g,"_")+".jsonl")}function $r(e,t=ka){return Nk(Xu(e,t))}async function Kt(e,t,n=ka){try{await rL(n,{recursive:!0,mode:448});let r=JSON.stringify(t.v===void 0?{t:t.t,k:t.k}:t);await nL(Xu(e,n),r+`
847
+ `,{mode:384})}catch{}}async function jn(e,t=ka){try{let n=Xu(e,t);if(!Nk(n))return[];let r=[];for(let i of(await iL(n,"utf8")).split(`
848
+ `))if(i.trim())try{let s=JSON.parse(i),a=s.t,c=s.k,l=s.v;if(typeof a!="number"||!Number.isFinite(a)||typeof c!="string"||!oL.has(c))continue;r.push(typeof l=="string"?{t:a,k:c,v:l}:{t:a,k:c})}catch{}return r}catch{return[]}}var ka,oL,zi=_(()=>{"use strict";mt();ka=$d,oL=new Set(["fail","ok","nudge","skip","prompt"]);o(Xu,"triggerLogPath");o($r,"hasTriggerLog");o(Kt,"appendTriggerEvent");o(jn,"loadTriggerEvents")});import{existsSync as aL}from"node:fs";import{mkdir as cL,readFile as lL,rename as dL,writeFile as uL}from"node:fs/promises";import{dirname as fL,join as pL}from"node:path";function qi(e=process.env){let t=Y();return t===null?null:{mcpUrl:e.MAIND_MCP_URL??Ti,keyFp:dr(t)}}async function Zu(e,t=Date.now(),n=xa){try{if(!aL(n))return null;let r=JSON.parse(await lL(n,"utf8"));if(r.mcp_url!==e.mcpUrl||r.key_fp!==e.keyFp||typeof r.fetched_at!="string")return null;let i=Date.parse(r.fetched_at);if(Number.isNaN(i))return null;let s=r.policy;return{policy:ga([s?.difficulty,s?.capture].filter(c=>c!=null)),fetchedAt:r.fetched_at,fresh:t-i<mL}}catch{return null}}async function gL(e,t,n,r){try{await cL(fL(r),{recursive:!0,mode:448});let i={fetched_at:new Date(n).toISOString(),mcp_url:e.mcpUrl,key_fp:e.keyFp,policy:t},s=`${r}.tmp`;await uL(s,JSON.stringify(i,null,2),{mode:384}),await dL(s,r)}catch{}}async function yL(){let e=Y();if(e===null)return null;let t=null;try{t=J()}catch{t=null}let n=await ft("get_conventions",{scope:"operating_procedure",include_disabled:!0},{apiKey:e,deviceId:_L(),projectKey:t,bridgeVersion:B,timeoutMs:hL});if(n===null)return null;try{return ga(JSON.parse(n))}catch{return null}}async function Lr(e,t={}){let n=t.nowMs??Date.now(),r=t.file??xa,i=t.identity===void 0?qi():t.identity;if(i===null)return Gi;let s=await Zu(i,n,r);if(s?.fresh)return s.policy;if(e){let a=await(t.fetcher??yL)();if(a!==null)return await gL(i,a,n,r),a}return s?.policy??Gi}function _L(){try{return re()}catch{return null}}var xa,mL,hL,Fr=_(()=>{"use strict";Mr();Nt();ue();Ee();Fe();An();mt();xa=pL(Be,"trigger-policy.json"),mL=12*60*60*1e3,hL=3e3;o(qi,"currentIdentity");o(Zu,"readCachedPolicy");o(gL,"writeCachedPolicy");o(yL,"fetchTriggerPolicy");o(Lr,"resolveTriggerPolicy");o(_L,"safeDeviceId")});var Dk={};ee(Dk,{runGuard:()=>xL});import{existsSync as bL,readFileSync as wL}from"node:fs";import{homedir as Ok}from"node:os";import{join as vL}from"node:path";async function xL(e){let t=e[0],n=e.slice(1);switch(t){case"install":return Ck(n,Ok());case"status":return EL();case"mode":{let r=n[0];return r!=="warn"&&r!=="block"?(process.stdout.write(`usage: maind-mcp-bridge guard mode <warn|block>
849
849
  `),1):(await Rn({guard_mode:r}),process.stdout.write(`guard mode set to '${r}' \u2014 takes effect for new sessions.
850
850
  `),0)}case"off":return await Rn({guard_mode:"off"}),process.stdout.write(`guard disabled \u2014 wired hooks become no-ops. Re-enable: guard mode <warn|block>.
851
851
  `),0;case"stop-gate":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard stop-gate <on|off>
@@ -853,71 +853,71 @@ Takes effect for NEW Claude Code sessions (hooks are read at session start).
853
853
  `),0)}case"difficulty":case"capture":{let r=n[0];return r!=="on"&&r!=="off"?(process.stdout.write(`usage: maind-mcp-bridge guard ${t} <on|off>
854
854
  `),1):(await Rn(t==="difficulty"?{guard_difficulty:r==="on"}:{guard_capture:r==="on"}),process.stdout.write(r==="on"?`${t} trigger follows your convention prefs again on this machine.
855
855
  `:`${t} trigger disabled on this machine (your convention prefs are unchanged).
856
- `),0)}case"skip":return H$(n);default:return process.stdout.write(j$),t===void 0||t==="--help"||t==="-h"?0:1}}async function H$(e){let t=null,n=null,r="consult";for(let a=0;a<e.length;a++)e[a]==="--session"?t=e[++a]??null:e[a]==="--reason"?n=e[++a]??null:e[a]==="--kind"&&(r=e[++a]??"");if(!t||!n||n.trim().length===0||!["consult","difficulty","capture"].includes(r))return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]
857
- `),1;let i=n.trim().slice(0,500);if(r!=="consult")return await Kt(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await J({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
856
+ `),0)}case"skip":return SL(n);default:return process.stdout.write(kL),t===void 0||t==="--help"||t==="-h"?0:1}}async function SL(e){let t=null,n=null,r="consult";for(let a=0;a<e.length;a++)e[a]==="--session"?t=e[++a]??null:e[a]==="--reason"?n=e[++a]??null:e[a]==="--kind"&&(r=e[++a]??"");if(!t||!n||n.trim().length===0||!["consult","difficulty","capture"].includes(r))return process.stdout.write(`usage: maind-mcp-bridge guard skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]
857
+ `),1;let i=n.trim().slice(0,500);if(r!=="consult")return await Kt(t,{t:Date.now(),k:r==="difficulty"?"skip":"prompt"}),await X({event:"override",session_id:t,reason:i,detail:r,cwd:process.cwd()}),process.stdout.write(`${r} override recorded for session ${t}.
858
858
  logged (auditable) in ${Cn}
859
- `),0;let s=await ft(t);return await ye(t,{...s,override_reason:i}),await J({event:"override",session_id:t,reason:i,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
859
+ `),0;let s=await pt(t);return await ye(t,{...s,override_reason:i}),await X({event:"override",session_id:t,reason:i,cwd:process.cwd()}),process.stdout.write(`override recorded for session ${t} \u2014 the gate opens on the next attempt.
860
860
  logged (auditable) in ${Cn}
861
- `),0}async function B$(){let e=ie(),t=F$(hk(),".claude","settings.json"),n=null;try{$$(t)&&(n=L$(t,"utf8"))}catch{}let r=Re(n,{},gr),i=await gb(),s=Gi(),a=s?await Gu(s):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",briefing_channel:No(n,{guardMode:e.mode}).channel,in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,policy:a?{difficulty:a.policy.difficulty,capture:a.policy.capture,fetched_at:a.fetchedAt,fresh:a.fresh}:null,policy_file:ga},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:Cn},null,2)+`
861
+ `),0}async function EL(){let e=se(),t=vL(Ok(),".claude","settings.json"),n=null;try{bL(t)&&(n=wL(t,"utf8"))}catch{}let r=Ce(n,{},_r),i=await Eb(),s=qi(),a=s?await Zu(s):null;process.stdout.write(JSON.stringify({mode:e.mode,stop_gate:e.stopGate,mode_source:process.env.MAIND_GUARD?"env:MAIND_GUARD":"config.json",briefing_channel:Mo(n,{guardMode:e.mode}).channel,in_loop_triggers:{difficulty_local:e.difficulty,capture_local:e.capture,policy:a?{difficulty:a.policy.difficulty,capture:a.policy.capture,fetched_at:a.fetchedAt,fresh:a.fresh}:null,policy_file:xa},hook_wiring:r.map(l=>({event:l.event,subcommand:l.subcommand,status:l.status,detail:l.detail})),events:i,events_file:Cn},null,2)+`
862
862
  `);let c=r.filter(l=>l.status!=="ok");if(e.mode==="off"&&process.stderr.write("\n[maind] guard is OFF \u2014 enable with `guard install` (first time) or `guard mode warn|block`.\n"),c.length>0&&e.mode!=="off"){process.stderr.write(`
863
863
  [maind] guard hook wiring is incomplete:
864
864
  `);for(let l of c)process.stderr.write(` \u2022 ${l.detail}
865
- `);c.some(l=>l.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var j$,yk=_(()=>{"use strict";Oo();Mt();Xe();fk();ht();mt();Bi();Lr();j$=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)"," difficulty <on|off>"," in-loop trigger 1 on this machine (ADR-360): repeated failures \u2192 consult maind"," capture <on|off>"," in-loop trigger 2 on this machine (ADR-360): hard-won fix \u2192 ask about a learning"," (on = follow your convention prefs, which are the declared opt-out)",' skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]'," record a logged override for one session (default kind: consult \u2014"," the block-gate exit valve; difficulty closes the open episode;"," capture answers the pending learning question)",""].join(`
866
- `);o(U$,"runGuard");o(H$,"runGuardSkip");o(B$,"runGuardStatus")});var wk={};Q(wk,{bashOutputOf:()=>_k,consultedAtOf:()=>ya,outcomeFromHook:()=>bk,runGuardDifficulty:()=>W$});function _k(e){if(e===null||typeof e!="object")return{output:null,interrupted:!1};let t=e,n=[t.stdout,t.stderr].filter(r=>typeof r=="string"&&r.length>0);return{output:n.length>0?n.join(`
867
- `):null,interrupted:t.interrupted===!0}}function bk(e){let t=e.hook_event_name;if(t!=="PostToolUse"&&t!=="PostToolUseFailure")return null;let n=typeof e.tool_name=="string"?e.tool_name:"",r=t==="PostToolUseFailure",i=!r&&n==="Bash"?_k(e.tool_response):{output:null,interrupted:!1},s=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof s=="string"&&s.length>0}}}function ya(e,t){let n=e.guard_signals?.[t]?.consulted_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}async function G$(e,t,n){if(!Mr(e))return;let r=await Fn(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let i=Or(r,null,n);await Kt(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await J({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function W$(){try{let e=ie();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=bk(t);if(r===null)return 0;let i=Su(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await G$(n,i.verb,s),0;await Kt(n,{t:s,k:"fail",v:i.verb});let a=await Fn(n),c=Or(a,ya(await X(),n),s);if(!Au(c)||c.chain===null)return 0;let l=await $r(!0);if(!e.difficulty||!Dr(l.difficulty))return 0;await Kt(n,{t:s,k:"nudge"});let d=Ui(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Tv(d):da(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await J({event:"difficulty_nudge",session_id:n,cwd:u,project_key:Y()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Wu=_(()=>{"use strict";Pr();ge();Wt();Qe();Fe();Xe();ht();Bi();Lr();o(_k,"bashOutputOf");o(bk,"outcomeFromHook");o(ya,"consultedAtOf");o(G$,"recordSuccess");o(W$,"runGuardDifficulty")});var Sk={};Q(Sk,{decideDifficultyGate:()=>xk,decideGate:()=>kk,runGuardGate:()=>z$});function kk(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:vk(n)}:(n.deny_count??0)>=_a?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+vk(n)}:{kind:"deny",reason:K$(e.sessionId,n)}}function vk(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function K$(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
865
+ `);c.some(l=>l.remedy==="run-install")&&process.stderr.write(" Run `maind-mcp-bridge guard install` to add the missing hooks.\n")}return 0}var kL,Pk=_(()=>{"use strict";$o();Mt();Qe();Ik();ht();mt();zi();Fr();kL=["usage: maind-mcp-bridge guard <verb>",""," install [--mode warn|block] [--stop-gate] [--full] [--dry-run]"," wire the guard hooks (consent per hook, append-only) + set the mode"," status mode, hook wiring, and local event counts"," mode <warn|block>"," flip enforcement hardness (config-only; settings.json untouched)"," off disable the guard (hooks stay wired, become no-ops)"," stop-gate <on|off>"," toggle the strict completion gate (review before finish)"," difficulty <on|off>"," in-loop trigger 1 on this machine (ADR-360): repeated failures \u2192 consult maind"," capture <on|off>"," in-loop trigger 2 on this machine (ADR-360): hard-won fix \u2192 ask about a learning"," (on = follow your convention prefs, which are the declared opt-out)",' skip --session <id> --reason "<why>" [--kind consult|difficulty|capture]'," record a logged override for one session (default kind: consult \u2014"," the block-gate exit valve; difficulty closes the open episode;"," capture answers the pending learning question)",""].join(`
866
+ `);o(xL,"runGuard");o(SL,"runGuardSkip");o(EL,"runGuardStatus")});var Lk={};ee(Lk,{bashOutputOf:()=>Mk,consultedAtOf:()=>Sa,outcomeFromHook:()=>$k,runGuardDifficulty:()=>AL});function Mk(e){if(e===null||typeof e!="object")return{output:null,interrupted:!1};let t=e,n=[t.stdout,t.stderr].filter(r=>typeof r=="string"&&r.length>0);return{output:n.length>0?n.join(`
867
+ `):null,interrupted:t.interrupted===!0}}function $k(e){let t=e.hook_event_name;if(t!=="PostToolUse"&&t!=="PostToolUseFailure")return null;let n=typeof e.tool_name=="string"?e.tool_name:"",r=t==="PostToolUseFailure",i=!r&&n==="Bash"?Mk(e.tool_response):{output:null,interrupted:!1},s=e.agent_id;return{event:t,outcome:{tool:n,input:e.tool_input,failed:r,output:i.output,isInterrupt:e.is_interrupt===!0||i.interrupted,isSubagent:typeof s=="string"&&s.length>0}}}function Sa(e,t){let n=e.guard_signals?.[t]?.consulted_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}async function TL(e,t,n){if(!$r(e))return;let r=await jn(e);if(!r.some(a=>a.k==="fail"&&a.v===t))return;let i=Dr(r,null,n);await Kt(e,{t:n,k:"ok",v:t});let s=i.chain;s!==null&&s.failures.length>=4&&!i.resolved&&s.lastVerb===t&&await X({event:"difficulty_resolved",session_id:e,detail:String(s.failures.length)})}async function AL(){try{let e=se();if(e.mode==="off"||!e.difficulty&&!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=$k(t);if(r===null)return 0;let i=Ou(r.outcome);if(i===null)return 0;let s=Date.now();if(i.kind==="ok")return await TL(n,i.verb,s),0;await Kt(n,{t:s,k:"fail",v:i.verb});let a=await jn(n),c=Dr(a,Sa(await Z(),n),s);if(!Mu(c)||c.chain===null)return 0;let l=await Lr(!0);if(!e.difficulty||!Pr(l.difficulty))return 0;await Kt(n,{t:s,k:"nudge"});let d=Wi(c.chain);process.stdout.write(r.event==="PostToolUseFailure"?Hv(d):ya(d));let u=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd();return await X({event:"difficulty_nudge",session_id:n,cwd:u,project_key:J()??void 0,detail:String(c.chain.failures.length)}),0}catch{return 0}}var Qu=_(()=>{"use strict";Mr();ge();Wt();He();Ee();Qe();ht();zi();Fr();o(Mk,"bashOutputOf");o($k,"outcomeFromHook");o(Sa,"consultedAtOf");o(TL,"recordSuccess");o(AL,"runGuardDifficulty")});var Hk={};ee(Hk,{decideDifficultyGate:()=>Uk,decideGate:()=>jk,runGuardGate:()=>IL});function jk(e){let{mode:t,session:n}=e;return t==="off"?{kind:"allow"}:n.injected===!0||n.carryover===!0||typeof n.override_reason=="string"||e.consulted?{kind:"allow"}:t==="warn"?n.warned===!0?{kind:"allow"}:{kind:"warn",context:Fk(n)}:(n.deny_count??0)>=Ea?n.warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Block-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+Fk(n)}:{kind:"deny",reason:RL(e.sessionId,n)}}function Fk(e){return`[maind guard | warn] ${e.inject_failed===!0?"The automatic briefing injection FAILED for this session (server unreachable or not paired) \u2014 call get_session_briefing yourself to close the gap.":"No maind consultation has happened in this session yet."} The project mandates session-start consultation (proc/maind-consultation-triggers): call get_session_briefing, or search_lessons with the task's key terms, before substantive edits. This reminder appears once per session.`}function RL(e,t){return`[maind guard | block] Edit denied \u2014 ${t.inject_failed===!0?"the automatic briefing injection failed for this session, so the consultation is still open":"no maind consultation has happened in this session"} (mandated by proc/maind-consultation-triggers). Two exits:
868
868
  1. Consult: call get_session_briefing (or search_lessons with 2-3 key terms) \u2014 the gate opens on the next attempt.
869
869
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${e} --reason "<why consultation is unnecessary here>"\` and retry.
870
- After ${_a} denies this gate downgrades itself to warn.`}function xk(e){let{mode:t,status:n,session:r}=e;return t!=="block"||!e.enabled||!e.denyCapable?{kind:"allow"}:!n.open||n.chain===null?{kind:"allow"}:(r.difficulty_deny_count??0)>=_a?r.difficulty_breaker_warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Difficulty-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+Ui(n.chain)}:{kind:"deny",reason:V$(n,e.sessionId)}}function V$(e,t){return`[maind guard | block] Edit denied \u2014 ${Ou(e.chain)}. Two exits:
870
+ After ${Ea} denies this gate downgrades itself to warn.`}function Uk(e){let{mode:t,status:n,session:r}=e;return t!=="block"||!e.enabled||!e.denyCapable?{kind:"allow"}:!n.open||n.chain===null?{kind:"allow"}:(r.difficulty_deny_count??0)>=Ea?r.difficulty_breaker_warned===!0?{kind:"allow"}:{kind:"warn",context:"[maind guard] Difficulty-gate circuit breaker: 3 denies without a consultation \u2014 downgraded to warn for this session. "+Wi(n.chain)}:{kind:"deny",reason:CL(n,e.sessionId)}}function CL(e,t){return`[maind guard | block] Edit denied \u2014 ${Uu(e.chain)}. Two exits:
871
871
  1. Consult: call search_lessons with the symptom \u2014 error code, tool or library, never paths or secrets \u2014 the gate opens on the next attempt.
872
872
  2. Override (logged): run \`maind-mcp-bridge guard skip --session ${t} --kind difficulty --reason "<why consulting does not help here>"\` and retry.
873
- After ${_a} denies this gate downgrades itself to warn.`}async function z$(){try{let e=ie();if(e.mode==="off")return 0;let t=await G(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await ft(r),s=ya(await X(),r),a=s!==null,c=kk({mode:e.mode,session:i,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=Y()??void 0;if(c.kind==="deny")return process.stdout.write(Mn(c.reason)),await ye(r,{...i,deny_count:(i.deny_count??0)+1}),await J({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(Ne(c.context)),await ye(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await J({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&Mr(r)){let u=Or(await Fn(r),s,Date.now()),p=u.open?xk({mode:e.mode,enabled:e.difficulty,denyCapable:Iu((await $r(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(p.kind==="deny")return process.stdout.write(Mn(p.reason)),await ye(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await J({event:"difficulty_deny",session_id:r,cwd:l,project_key:d,detail:String(u.chain?.failures.length??0)}),0;if(p.kind==="warn")return process.stdout.write(Ne(p.context)),await ye(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await ye(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var _a,Ek=_(()=>{"use strict";Pr();ge();Wt();Qe();Fe();Xe();Wu();ht();mt();Bi();Lr();_a=3;o(kk,"decideGate");o(vk,"warnText");o(K$,"denyText");o(xk,"decideDifficultyGate");o(V$,"difficultyDenyText");o(z$,"runGuardGate")});var Ak={};Q(Ak,{decideStopGate:()=>Tk,runGuardStop:()=>Y$});function Tk(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function Y$(){try{let e=ie();if(e.mode==="off"||!e.stopGate)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await ft(n),i=(await X()).guard_signals?.[n]?.reviewed_at!==void 0;return Tk({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:q$})),await ye(n,{...r,stop_blocked:!0}),await J({event:"stop_block",session_id:n})),0}catch{return 0}}var q$,Rk=_(()=>{"use strict";ge();Qe();Xe();ht();mt();o(Tk,"decideStopGate");q$="[maind guard] Stop gate (strict, opt-in): this session edited files but no review ran. Run the review over the edit batches \u2014 attest_review_changes (one call, a server verdict; a clean pushed commit is also recorded), or codebase_review_changes then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";o(Y$,"runGuardStop")});var Nk={};Q(Nk,{capturedAtOf:()=>Ck,decideCapture:()=>Ik,runGuardCapture:()=>J$});function Ck(e,t){let n=e.guard_signals?.[t]?.captured_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}function Ik(e){if(e.stopHookActive||!Dr(e.policy.capture))return null;let t=Ru(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Du(t)}}async function J$(){try{let e=ie();if(e.mode==="off"||!e.capture)return 0;let t=await G(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!Mr(n))return 0;let r=Ik({events:await Fn(n),capturedAtMs:Ck(await X(),n),policy:await $r(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Kt(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await J({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var Ok=_(()=>{"use strict";Pr();ge();Qe();Xe();ht();Bi();Lr();o(Ck,"capturedAtOf");o(Ik,"decideCapture");o(J$,"runGuardCapture")});import{appendFile as X$,mkdir as Z$,readFile as Pk,rename as Mk,writeFile as $k}from"node:fs/promises";import{homedir as Lk}from"node:os";import{join as Fk}from"node:path";function jk(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=new Map,a=1/0,c=-1/0;for(let d of e){d.at<a&&(a=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let p=s.get(d.convention_id);(p===void 0||d.convention_version>p)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function jn(){return Fk(Lk(),".maind","gateway","attest-spool.jsonl")}async function Ku(e){let t=q();if(t===null)return!1;let n=await ut("gateway_attest",{...e},{apiKey:t,deviceId:ne(),projectKey:e.project_key??null,bridgeVersion:B,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function Uk(e){try{await Z$(Fk(Lk(),".maind","gateway"),{recursive:!0}),await X$(jn(),JSON.stringify(e)+`
874
- `,{mode:384}),await Q$()}catch{}}async function Q$(){try{let t=(await Pk(jn(),"utf8")).split(`
875
- `).filter(r=>r.trim());if(t.length<=Dk)return;let n=`${jn()}.${process.pid}.tmp`;await $k(n,t.slice(-Dk).join(`
873
+ After ${Ea} denies this gate downgrades itself to warn.`}async function IL(){try{let e=se();if(e.mode==="off")return 0;let t=await W(),n=(t.tool_name??"").toString();if(n!=="Edit"&&n!=="Write")return 0;let r=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(r===null)return 0;let i=await pt(r),s=Sa(await Z(),r),a=s!==null,c=jk({mode:e.mode,session:i,consulted:a,sessionId:r}),l=typeof t.cwd=="string"&&t.cwd.length>0?t.cwd:process.cwd(),d=J()??void 0;if(c.kind==="deny")return process.stdout.write($n(c.reason)),await ye(r,{...i,deny_count:(i.deny_count??0)+1}),await X({event:"deny",session_id:r,cwd:l,project_key:d}),0;if(c.kind==="warn")return process.stdout.write(Oe(c.context)),await ye(r,{...i,warned:!0,edits_seen:(i.edits_seen??0)+1}),await X({event:"warn",session_id:r,cwd:l,project_key:d}),0;if(e.mode==="block"&&e.difficulty&&$r(r)){let u=Dr(await jn(r),s,Date.now()),f=u.open?Uk({mode:e.mode,enabled:e.difficulty,denyCapable:Fu((await Lr(!1)).difficulty),status:u,session:i,sessionId:r}):{kind:"allow"};if(f.kind==="deny")return process.stdout.write($n(f.reason)),await ye(r,{...i,difficulty_deny_count:(i.difficulty_deny_count??0)+1}),await X({event:"difficulty_deny",session_id:r,cwd:l,project_key:d,detail:String(u.chain?.failures.length??0)}),0;if(f.kind==="warn")return process.stdout.write(Oe(f.context)),await ye(r,{...i,difficulty_breaker_warned:!0,edits_seen:(i.edits_seen??0)+1}),0}return await ye(r,{...i,edits_seen:(i.edits_seen??0)+1}),0}catch{return 0}}var Ea,Bk=_(()=>{"use strict";Mr();ge();Wt();He();Ee();Qe();Qu();ht();mt();zi();Fr();Ea=3;o(jk,"decideGate");o(Fk,"warnText");o(RL,"denyText");o(Uk,"decideDifficultyGate");o(CL,"difficultyDenyText");o(IL,"runGuardGate")});var Wk={};ee(Wk,{decideStopGate:()=>Gk,runGuardStop:()=>OL});function Gk(e){return{block:e.enabled&&e.editsSeen>0&&!e.reviewed&&!e.stopHookActive&&!e.alreadyBlocked}}async function OL(){try{let e=se();if(e.mode==="off"||!e.stopGate)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null)return 0;let r=await pt(n),i=(await Z()).guard_signals?.[n]?.reviewed_at!==void 0;return Gk({enabled:!0,editsSeen:r.edits_seen??0,reviewed:i,stopHookActive:t.stop_hook_active===!0,alreadyBlocked:r.stop_blocked===!0}).block&&(process.stdout.write(JSON.stringify({decision:"block",reason:NL})),await ye(n,{...r,stop_blocked:!0}),await X({event:"stop_block",session_id:n})),0}catch{return 0}}var NL,Kk=_(()=>{"use strict";ge();He();Qe();ht();mt();o(Gk,"decideStopGate");NL="[maind guard] Stop gate (strict, opt-in): this session edited files but no review ran. Run the review over the edit batches \u2014 attest_review_changes (one call, a server verdict; a clean pushed commit is also recorded), or codebase_review_changes then review_changes with its review_args (or `maind review` from the CLI) \u2014 report the findings, then finish. This gate blocks only once.";o(OL,"runGuardStop")});var qk={};ee(qk,{capturedAtOf:()=>Vk,decideCapture:()=>zk,runGuardCapture:()=>DL});function Vk(e,t){let n=e.guard_signals?.[t]?.captured_at,r=typeof n=="string"?Date.parse(n):NaN;return Number.isNaN(r)?null:r}function zk(e){if(e.stopHookActive||!Pr(e.policy.capture))return null;let t=$u(e.events,e.capturedAtMs??-1/0);return t===null?null:{candidate:t,reason:Hu(t)}}async function DL(){try{let e=se();if(e.mode==="off"||!e.capture)return 0;let t=await W(),n=typeof t.session_id=="string"&&t.session_id.trim().length>0?t.session_id.trim():null;if(n===null||!$r(n))return 0;let r=zk({events:await jn(n),capturedAtMs:Vk(await Z(),n),policy:await Lr(!1),stopHookActive:t.stop_hook_active===!0});return r===null||(await Kt(n,{t:Date.now(),k:"prompt"}),process.stdout.write(JSON.stringify({decision:"block",reason:r.reason})),await X({event:"capture_prompt",session_id:n,detail:String(r.candidate.failures.length)})),0}catch{return 0}}var Yk=_(()=>{"use strict";Mr();ge();He();Qe();ht();zi();Fr();o(Vk,"capturedAtOf");o(zk,"decideCapture");o(DL,"runGuardCapture")});import{appendFile as PL,mkdir as ML,readFile as Xk,rename as Zk,writeFile as Qk}from"node:fs/promises";import{homedir as ex}from"node:os";import{join as tx}from"node:path";function nx(e,t,n,r){if(t==="off"||e.length===0)return null;let i={},s=new Map,a=1/0,c=-1/0;for(let d of e){d.at<a&&(a=d.at),d.at>c&&(c=d.at);let u=i[d.tool]??={calls:0,warns:0,denies:0};if(d.event==="tool_call"?u.calls+=1:d.event==="policy_warn"||d.event==="sha_warn"?u.warns+=1:u.denies+=1,(d.event==="policy_warn"||d.event==="policy_deny")&&d.convention_id!==void 0&&d.convention_version!==void 0){let f=s.get(d.convention_id);(f===void 0||d.convention_version>f)&&s.set(d.convention_id,d.convention_version)}}let l=Object.entries(i).sort((d,u)=>u[1].calls+u[1].warns+u[1].denies-(d[1].calls+d[1].warns+d[1].denies)).slice(0,64);return{window_start:new Date(a).toISOString(),window_end:new Date(c).toISOString(),server_label:n,gateway_mode:t,counts:Object.fromEntries(l),event_count:Math.min(e.length,1e5),citations:[...s.entries()].slice(0,32).map(([d,u])=>({convention_id:d,convention_version:u})),...r?{project_key:r}:{}}}function Un(){return tx(ex(),".maind","gateway","attest-spool.jsonl")}async function ef(e){let t=Y();if(t===null)return!1;let n=await ft("gateway_attest",{...e},{apiKey:t,deviceId:re(),projectKey:e.project_key??null,bridgeVersion:B,clientFamily:"gateway",timeoutMs:6e3});if(n===null)return!1;try{return JSON.parse(n).ok===!0}catch{return!1}}async function rx(e){try{await ML(tx(ex(),".maind","gateway"),{recursive:!0}),await PL(Un(),JSON.stringify(e)+`
874
+ `,{mode:384}),await $L()}catch{}}async function $L(){try{let t=(await Xk(Un(),"utf8")).split(`
875
+ `).filter(r=>r.trim());if(t.length<=Jk)return;let n=`${Un()}.${process.pid}.tmp`;await Qk(n,t.slice(-Jk).join(`
876
876
  `)+`
877
- `,{mode:384}),await Mk(n,jn())}catch{}}async function Hk(){let e;try{e=(await Pk(jn(),"utf8")).split(`
878
- `).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await Ku(i)||(n=!0,t.push(r))}try{let r=`${jn()}.${process.pid}.tmp`;await $k(r,t.length>0?t.join(`
877
+ `,{mode:384}),await Zk(n,Un())}catch{}}async function ix(){let e;try{e=(await Xk(Un(),"utf8")).split(`
878
+ `).filter(r=>r.trim())}catch{return}if(e.length===0)return;let t=[],n=!1;for(let r of e){if(n){t.push(r);continue}let i=null;try{i=JSON.parse(r)}catch{continue}await ef(i)||(n=!0,t.push(r))}try{let r=`${Un()}.${process.pid}.tmp`;await Qk(r,t.length>0?t.join(`
879
879
  `)+`
880
- `:"",{mode:384}),await Mk(r,jn())}catch{}}var Dk,Bk=_(()=>{"use strict";ue();An();Le();Dk=256;o(jk,"aggregateWindow");o(jn,"attestSpoolPath");o(Ku,"postAttestation");o(Uk,"spoolAttestation");o(Q$,"capSpool");o(Hk,"flushAttestSpool")});function Wi(e=process.env,t=Ce()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function ba(e=process.env,t=Ce()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function Gk(e,t=je()){let n={};try{let i=await Z(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await V(t,JSON.stringify(r,null,2)+`
881
- `,384)}async function Wk(e,t=je()){await Gk({gateway_mode:e},t)}async function Kk(e,t=je()){await Gk({gateway_attest:e},t)}function Vk(e=process.env,t=Ce()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var Vu=_(()=>{"use strict";$t();_e();o(Wi,"resolveGatewayMode");o(ba,"resolveGatewayAttest");o(Gk,"writeGatewayConfigPatch");o(Wk,"writeGatewayMode");o(Kk,"writeGatewayAttest");o(Vk,"resolveShaProofMode")});function qk(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let a=s;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&eL.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",p=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(p!==null&&p.length===0)continue;let f=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of f){if(n.length>=256)return n;n.push({tool:h,servers:p,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function tL(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function Yk(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)tL(s,e,t)&&(i===null||zk[s.severity]>zk[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function Jk(e,t){let n=`${t.conventionId} v${t.conventionVersion}`,r=t.summary?` ("${t.summary}")`:"";return`maind gateway: tool '${e}' is denied by convention ${n}${r}. The call was not forwarded to the server. Exits: ask the user to run 'maind-mcp-bridge gateway mode warn' (observe instead of enforce), or to disable the convention for themselves (set_convention_pref) if it is not mandatory.`}var eL,zk,zu=_(()=>{"use strict";eL=new Set(["required","recommended","info"]);o(qk,"extractGatewayRules");zk={required:2,recommended:1,info:0};o(tL,"ruleMatches");o(Yk,"decideToolCall");o(Jk,"policyDenyText")});import{mkdirSync as nL,readFileSync as rL,renameSync as iL,writeFileSync as sL}from"node:fs";import{homedir as oL}from"node:os";import{dirname as aL,join as cL}from"node:path";function Xk(){return cL(oL(),".maind","gateway","policy-cache.json")}function wa(e,t,n=new Date().toISOString()){try{let r={version:qu,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=Xk();nL(aL(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;sL(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),iL(s,i)}catch{}}function va(e){try{let t=rL(Xk(),"utf8"),n=JSON.parse(t);return n.version!==qu||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:qu,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var qu,Yu=_(()=>{"use strict";qu=1;o(Xk,"policyCachePath");o(wa,"writePolicyCache");o(va,"readPolicyCache")});function Ki(e=process.env){let t=e.MAIND_MCP_URL??Ei,n=q();return{mcpUrl:t,keyFp:n?lr(n):"anon"}}async function ka(e=6e3){let t=q();if(t===null)return null;let n=null;try{n=Y()}catch{n=null}let r=await ut("get_conventions",{},{apiKey:t,deviceId:ne(),projectKey:n,bridgeVersion:B,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return qk(i)}var Ju=_(()=>{"use strict";Nt();ue();An();Fe();Le();zu();o(Ki,"policyIdentity");o(ka,"fetchGatewayRules")});function Vi(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function lL(e){if(Vi(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function dL(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Vi(e)?{action:"skip",reason:"already-wrapped"}:lL(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function Zk(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function Qk(e){if(!Vi(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function ex(e){return Object.entries(e).map(([t,n])=>{let r=dL(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var tx=_(()=>{"use strict";o(Vi,"isGatewayWrapped");o(lL,"isMaindProxyEntry");o(dL,"classifyServer");o(Zk,"wrapServerEntry");o(Qk,"unwrapServerEntry");o(ex,"planRewrites")});var ax={};Q(ax,{runGatewayInstall:()=>gL,runGatewayUninstall:()=>yL});import{existsSync as uL,readFileSync as pL}from"node:fs";import{homedir as fL}from"node:os";import{join as nx}from"node:path";import{createInterface as mL}from"node:readline";function rx(e){let t={yes:!1,dryRun:!1};for(let n of e)if(n==="--yes")t.yes=!0;else if(n==="--dry-run")t.dryRun=!0;else return null;return t}function ix(){return[{label:"Claude Code (project .mcp.json)",path:nx(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:nx(fL(),".claude.json")}]}async function sx(e){let t=mL({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{t.close()}}function ox(e){let t=hL(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function hL(e){try{return uL(e)?pL(e,"utf8"):null}catch{return null}}async function gL(e){let t=rx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
882
- `),2;let n=Ee({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of ix()){let s=ox(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
883
- `);continue}let a=ex(s.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
884
- `);continue}if(!(t.yes||await sx(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
880
+ `:"",{mode:384}),await Zk(r,Un())}catch{}}var Jk,sx=_(()=>{"use strict";ue();An();Fe();Jk=256;o(nx,"aggregateWindow");o(Un,"attestSpoolPath");o(ef,"postAttestation");o(rx,"spoolAttestation");o($L,"capSpool");o(ix,"flushAttestSpool")});function Yi(e=process.env,t=Ie()){let n=e.MAIND_GATEWAY;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_mode??"warn"}function Ta(e=process.env,t=Ie()){let n=e.MAIND_GATEWAY_ATTEST;return n==="1"?!0:n==="0"?!1:t?.gateway_attest===!0}async function ox(e,t=je()){let n={};try{let i=await Q(t);if(i!==null&&i.trim().length>0){let s=JSON.parse(i);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(n=s)}}catch{}let r={...n,...e};await z(t,JSON.stringify(r,null,2)+`
881
+ `,384)}async function ax(e,t=je()){await ox({gateway_mode:e},t)}async function cx(e,t=je()){await ox({gateway_attest:e},t)}function lx(e=process.env,t=Ie()){let n=e.MAIND_GATEWAY_SHA;return n==="off"||n==="warn"||n==="enforce"?n:t?.gateway_sha_proof??"warn"}var tf=_(()=>{"use strict";$t();_e();o(Yi,"resolveGatewayMode");o(Ta,"resolveGatewayAttest");o(ox,"writeGatewayConfigPatch");o(ax,"writeGatewayMode");o(cx,"writeGatewayAttest");o(lx,"resolveShaProofMode")});function ux(e){if(typeof e!="object"||e===null)return[];let t=e.conventions;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(typeof r!="object"||r===null)continue;let i=r,s=i.gateway_gate;if(typeof s!="object"||s===null)continue;let a=s;if(a.enabled!==!0)continue;let c=typeof i.id=="string"&&i.id.length>0&&i.id.length<=64?i.id:null,l=typeof i.version=="number"&&Number.isInteger(i.version)&&i.version>=1?i.version:null;if(c===null||l===null)continue;let d=typeof i.severity=="string"&&LL.has(i.severity)?i.severity:"recommended",u=typeof i.summary=="string"?i.summary:"",f=Array.isArray(a.servers)?a.servers.filter(h=>typeof h=="string"&&h.length>0):null;if(f!==null&&f.length===0)continue;let p=Array.isArray(a.deny_tools)?a.deny_tools.filter(h=>typeof h=="string"&&h.length>0):[];for(let h of p){if(n.length>=256)return n;n.push({tool:h,servers:f,conventionId:c,conventionVersion:l,severity:d,summary:u})}}return n}function FL(e,t,n){return e.tool!==t?!1:e.servers===null?!0:e.servers.includes("*")||e.servers.includes(n)}function fx(e,t,n,r){if(r==="off")return{kind:"allow"};let i=null;for(let s of n)FL(s,e,t)&&(i===null||dx[s.severity]>dx[i.severity])&&(i=s);return i===null?{kind:"allow"}:i.severity==="required"&&r==="enforce"?{kind:"deny",rule:i}:{kind:"warn",rule:i}}function px(e,t){let n=`${t.conventionId} v${t.conventionVersion}`,r=t.summary?` ("${t.summary}")`:"";return`maind gateway: tool '${e}' is denied by convention ${n}${r}. The call was not forwarded to the server. Exits: ask the user to run 'maind-mcp-bridge gateway mode warn' (observe instead of enforce), or to disable the convention for themselves (set_convention_pref) if it is not mandatory.`}var LL,dx,nf=_(()=>{"use strict";LL=new Set(["required","recommended","info"]);o(ux,"extractGatewayRules");dx={required:2,recommended:1,info:0};o(FL,"ruleMatches");o(fx,"decideToolCall");o(px,"policyDenyText")});import{mkdirSync as jL,readFileSync as UL,renameSync as HL,writeFileSync as BL}from"node:fs";import{homedir as GL}from"node:os";import{dirname as WL,join as KL}from"node:path";function mx(){return KL(GL(),".maind","gateway","policy-cache.json")}function Aa(e,t,n=new Date().toISOString()){try{let r={version:rf,cached_at:n,mcp_url:e.mcpUrl,key_fp:e.keyFp,rules:t},i=mx();jL(WL(i),{recursive:!0});let s=`${i}.${process.pid}.tmp`;BL(s,JSON.stringify(r,null,2),{encoding:"utf8",mode:384}),HL(s,i)}catch{}}function Ra(e){try{let t=UL(mx(),"utf8"),n=JSON.parse(t);return n.version!==rf||n.mcp_url!==e.mcpUrl||n.key_fp!==e.keyFp||typeof n.cached_at!="string"||!Array.isArray(n.rules)?null:{version:rf,cached_at:n.cached_at,mcp_url:n.mcp_url,key_fp:n.key_fp,rules:n.rules}}catch{return null}}var rf,sf=_(()=>{"use strict";rf=1;o(mx,"policyCachePath");o(Aa,"writePolicyCache");o(Ra,"readPolicyCache")});function Ji(e=process.env){let t=e.MAIND_MCP_URL??Ti,n=Y();return{mcpUrl:t,keyFp:n?dr(n):"anon"}}async function Ca(e=6e3){let t=Y();if(t===null)return null;let n=null;try{n=J()}catch{n=null}let r=await ft("get_conventions",{},{apiKey:t,deviceId:re(),projectKey:n,bridgeVersion:B,clientFamily:"gateway",timeoutMs:e});if(r===null)return null;let i;try{i=JSON.parse(r)}catch{return null}return ux(i)}var of=_(()=>{"use strict";Nt();ue();An();Ee();Fe();nf();o(Ji,"policyIdentity");o(Ca,"fetchGatewayRules")});function Xi(e){let t=Array.isArray(e.args)?e.args.map(String):[],n=t.indexOf("gateway");if(n===-1||t.indexOf("--",n+1)===-1)return!1;if(n===0)return!0;let r=[String(e.command??""),...t.slice(0,n)].join(" ");return/maind-mcp-bridge|@maind-dev\/mcp-bridge|\.js\s*$/.test(r)}function VL(e){if(Xi(e))return!1;let t=typeof e.command=="string"?e.command:"",n=Array.isArray(e.args)?e.args:[],r=[t,...n.map(String)].join(" ");return r.includes("maind-mcp-bridge")||/@maind-dev\/mcp-bridge/.test(r)}function zL(e){return typeof e.command!="string"||e.command.length===0?{action:"skip",reason:"not-stdio"}:typeof e.url=="string"?{action:"skip",reason:"not-stdio"}:Xi(e)?{action:"skip",reason:"already-wrapped"}:VL(e)?{action:"skip",reason:"maind-proxy"}:{action:"wrap"}}function hx(e,t,n){let r=String(e.command),i=Array.isArray(e.args)?e.args.map(String):[],s=typeof e.env=="object"&&e.env!==null?e.env:void 0,a=s||t.env?{...s??{},...t.env??{}}:void 0,c={...e,command:t.command,args:[...t.args,"gateway","--label",n,"--",r,...i]};return a&&(c.env=a),c}function gx(e){if(!Xi(e))return null;let t=e.args.map(String),n=t.indexOf("--",t.indexOf("gateway")+1);return n===-1||n+1>=t.length?null:{...e,command:t[n+1],args:t.slice(n+2)}}function yx(e){return Object.entries(e).map(([t,n])=>{let r=zL(n);return r.action==="wrap"?{key:t,action:"wrap"}:{key:t,action:"skip",reason:r.reason}})}var _x=_(()=>{"use strict";o(Xi,"isGatewayWrapped");o(VL,"isMaindProxyEntry");o(zL,"classifyServer");o(hx,"wrapServerEntry");o(gx,"unwrapServerEntry");o(yx,"planRewrites")});var Sx={};ee(Sx,{runGatewayInstall:()=>QL,runGatewayUninstall:()=>eF});import{existsSync as qL,readFileSync as YL}from"node:fs";import{homedir as JL}from"node:os";import{join as bx}from"node:path";import{createInterface as XL}from"node:readline";function wx(e){let t={yes:!1,dryRun:!1};for(let n of e)if(n==="--yes")t.yes=!0;else if(n==="--dry-run")t.dryRun=!0;else return null;return t}function vx(){return[{label:"Claude Code (project .mcp.json)",path:bx(process.cwd(),".mcp.json")},{label:"Claude Code (user ~/.claude.json)",path:bx(JL(),".claude.json")}]}async function kx(e){let t=XL({input:process.stdin,output:process.stderr});try{let n=await new Promise(r=>t.question(`${e} [y/N] `,r));return n.trim().toLowerCase()==="y"||n.trim().toLowerCase()==="yes"}finally{t.close()}}function xx(e){let t=ZL(e);if(t===null)return null;try{let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=n,i=r.mcpServers;return typeof i!="object"||i===null||Array.isArray(i)?null:{raw:r,servers:i}}catch{return null}}function ZL(e){try{return qL(e)?YL(e,"utf8"):null}catch{return null}}async function QL(e){let t=wx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway install [--yes] [--dry-run]
882
+ `),2;let n=Te({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),r=0;for(let i of vx()){let s=xx(i.path);if(s===null){process.stderr.write(` skipped ${i.label} \u2014 no mcpServers object
883
+ `);continue}let a=yx(s.servers);for(let c of a){if(c.action==="skip"){process.stderr.write(` skipped ${i.label} \xB7 ${c.key} \u2014 ${c.reason}
884
+ `);continue}if(!(t.yes||await kx(`Wrap MCP server '${c.key}' in ${i.label} with the maind gateway?
885
885
  Tool-call NAMES (never arguments) will be logged to ~/.maind/gateway/events.jsonl.
886
886
  The original launch command stays inside the entry and 'gateway uninstall' restores it.`))){process.stderr.write(` declined ${i.label} \xB7 ${c.key}
887
- `);continue}s.servers[c.key]=Zk(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
888
- `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await V(i.path,JSON.stringify(s.raw,null,2)+`
887
+ `);continue}s.servers[c.key]=hx(s.servers[c.key],n,c.key),r+=1,process.stderr.write(` ${t.dryRun?"would wrap":"wrapped"} ${i.label} \xB7 ${c.key}
888
+ `)}!t.dryRun&&a.some(c=>c.action==="wrap")&&await z(i.path,JSON.stringify(s.raw,null,2)+`
889
889
  `,384)}return process.stderr.write(r>0?`
890
890
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions (MCP servers spawn at session start).
891
891
  `:`
892
892
  Nothing to wrap.
893
- `),0}async function yL(e){let t=rx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
894
- `),2;let n=0;for(let r of ix()){let i=ox(r.path);if(i===null)continue;let s=!1;for(let[a,c]of Object.entries(i.servers)){if(!Vi(c)||!(t.yes||await sx(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=Qk(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
893
+ `),0}async function eF(e){let t=wx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
894
+ `),2;let n=0;for(let r of vx()){let i=xx(r.path);if(i===null)continue;let s=!1;for(let[a,c]of Object.entries(i.servers)){if(!Xi(c)||!(t.yes||await kx(`Unwrap MCP server '${a}' in ${r.label}?`)))continue;let d=gx(c);if(d===null){process.stderr.write(` BROKEN ${r.label} \xB7 ${a} \u2014 wrapped shape unrecognized, left untouched
895
895
  `);continue}i.servers[a]=d,s=!0,n+=1,process.stderr.write(` ${t.dryRun?"would unwrap":"unwrapped"} ${r.label} \xB7 ${a}
896
- `)}!t.dryRun&&s&&await V(r.path,JSON.stringify(i.raw,null,2)+`
896
+ `)}!t.dryRun&&s&&await z(r.path,JSON.stringify(i.raw,null,2)+`
897
897
  `,384)}return process.stderr.write(n>0?`
898
898
  ${t.dryRun?"Dry-run \u2014 nothing written. ":""}Takes effect for NEW sessions.
899
899
  `:`
900
900
  Nothing wrapped \u2014 nothing to restore.
901
- `),0}var cx=_(()=>{"use strict";_e();wn();tx();o(rx,"parseFlags");o(ix,"targets");o(sx,"confirm");o(ox,"loadConfig");o(hL,"readFileSafeSync");o(gL,"runGatewayInstall");o(yL,"runGatewayUninstall")});var lx={};Q(lx,{runGatewayAttest:()=>bL,runGatewayMode:()=>_L,runGatewayPolicy:()=>kL});async function _L(e){let t=e[0];if(t===void 0){let n=Wi(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
901
+ `),0}var Ex=_(()=>{"use strict";_e();wn();_x();o(wx,"parseFlags");o(vx,"targets");o(kx,"confirm");o(xx,"loadConfig");o(ZL,"readFileSafeSync");o(QL,"runGatewayInstall");o(eF,"runGatewayUninstall")});var Tx={};ee(Tx,{runGatewayAttest:()=>nF,runGatewayMode:()=>tF,runGatewayPolicy:()=>sF});async function tF(e){let t=e[0];if(t===void 0){let n=Yi(),r=process.env.MAIND_GATEWAY!==void 0;return process.stdout.write(`maind: gateway mode is '${n}'${r?" (from MAIND_GATEWAY env)":""}
902
902
  `),0}return t!=="off"&&t!=="warn"&&t!=="enforce"?(process.stderr.write(`usage: maind-mcp-bridge gateway mode [off|warn|enforce]
903
- `),2):(await Wk(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
903
+ `),2):(await ax(t),process.stdout.write(`maind: gateway mode set to '${t}'. `+(t==="enforce"?`Conventions with gateway_gate + severity=required now DENY matching tools.
904
904
  `:t==="warn"?`Convention matches are logged (policy_warn) and forwarded \u2014 nothing is denied.
905
905
  `:`Convention policy is off; only explicit --deny-tool flags apply.
906
- `)),0)}async function bL(e){let t=e[0];if(t===void 0){let n=ba(),r=process.env.MAIND_GATEWAY_ATTEST!==void 0;return process.stdout.write(`maind: gateway attestation reports are ${n?"ON":"OFF"}${r?" (from MAIND_GATEWAY_ATTEST env)":""}.
906
+ `)),0)}async function nF(e){let t=e[0];if(t===void 0){let n=Ta(),r=process.env.MAIND_GATEWAY_ATTEST!==void 0;return process.stdout.write(`maind: gateway attestation reports are ${n?"ON":"OFF"}${r?" (from MAIND_GATEWAY_ATTEST env)":""}.
907
907
  `+(n?"":`maind: enable with 'gateway attest on' \u2014 reports observation windows (per-tool call/warn/deny COUNTERS, tool NAMES, convention citations, server label) to your maind account. Never tool arguments, results, paths, or prompts.
908
908
  `)),0}return t!=="on"&&t!=="off"?(process.stderr.write(`usage: maind-mcp-bridge gateway attest [on|off]
909
- `),2):(await Kk(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
909
+ `),2):(await cx(t==="on"),process.stdout.write(t==="on"?`maind: attestation reports ON. Each gateway now reports observation windows (tool-name counters + convention citations \u2014 never arguments) to your maind account, at gateway end and every 30 min.
910
910
  `:`maind: attestation reports OFF. Events stay local (~/.maind/gateway/events.jsonl).
911
- `),0)}function wL(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
911
+ `),0)}function rF(e){if(e.length===0)return` (no rules \u2014 no visible convention carries a gateway_gate)
912
912
  `;let t="";for(let n of e){let r=n.servers===null?"*":n.servers.join(","),i=n.severity==="required"?"deny-capable":"warn-only";t+=` ${n.tool} [servers: ${r}] ${n.conventionId} v${n.conventionVersion} (${n.severity} \u2192 ${i})
913
- `}return t}function vL(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function kL(e){let t=e.includes("--refresh"),n=Wi(),r=Ki();if(t){let s=await ka();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
914
- `):(wa(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
915
- `))}let i=va(r);return process.stdout.write(`maind: gateway mode '${n}'
913
+ `}return t}function iF(e,t=Date.now()){let n=Date.parse(e.cached_at);if(Number.isNaN(n))return"unknown age";let r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r} min ago`;let i=Math.floor(r/60);return i<24?`${i} h ago`:`${Math.floor(i/24)} d ago`}async function sF(e){let t=e.includes("--refresh"),n=Yi(),r=Ji();if(t){let s=await Ca();s===null?process.stderr.write(`maind: policy refresh failed (not paired, offline, or server error) \u2014 showing last cached state.
914
+ `):(Aa(r,s),process.stdout.write(`maind: policy refreshed (${s.length} rule(s)).
915
+ `))}let i=Ra(r);return process.stdout.write(`maind: gateway mode '${n}'
916
916
  `),i===null?(process.stdout.write(`maind: no cached policy for this identity. Run 'gateway policy --refresh' while paired.
917
- `),0):(process.stdout.write(`maind: policy from cache (${vL(i)}, ${r.mcpUrl}):
918
- `),process.stdout.write(wL(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
919
- `),0)}var dx=_(()=>{"use strict";Vu();Yu();Ju();o(_L,"runGatewayMode");o(bL,"runGatewayAttest");o(wL,"renderRules");o(vL,"cacheAge");o(kL,"runGatewayPolicy")});var hx={};Q(hx,{gatewayEventsFile:()=>fx,parseGatewayArgs:()=>mx,runGateway:()=>CL});import{spawn as xL}from"node:child_process";import{appendFile as SL,mkdir as EL}from"node:fs/promises";import{homedir as ux}from"node:os";import{basename as TL,join as px}from"node:path";import{createInterface as AL}from"node:readline";function fx(){return px(ux(),".maind","gateway","events.jsonl")}async function RL(e){try{let t=fx();await EL(px(ux(),".maind","gateway"),{recursive:!0}),await SL(t,JSON.stringify(e)+`
920
- `,{mode:384})}catch{}}function mx(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function CL(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:k,runGatewayUninstall:v}=await Promise.resolve().then(()=>(cx(),ax));return e[0]==="install"?k(e.slice(1)):v(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:k,runGatewayMode:v,runGatewayPolicy:T}=await Promise.resolve().then(()=>(dx(),lx));return e[0]==="mode"?v(e.slice(1)):e[0]==="attest"?k(e.slice(1)):T(e.slice(1))}let t=mx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
917
+ `),0):(process.stdout.write(`maind: policy from cache (${iF(i)}, ${r.mcpUrl}):
918
+ `),process.stdout.write(rF(i.rules)),n!=="enforce"&&process.stdout.write(`maind: note \u2014 deny-capable rules only deny in mode 'enforce'; current mode logs them as policy_warn.
919
+ `),0)}var Ax=_(()=>{"use strict";tf();sf();of();o(tF,"runGatewayMode");o(nF,"runGatewayAttest");o(rF,"renderRules");o(iF,"cacheAge");o(sF,"runGatewayPolicy")});var Ox={};ee(Ox,{gatewayEventsFile:()=>Ix,parseGatewayArgs:()=>Nx,runGateway:()=>fF});import{spawn as oF}from"node:child_process";import{appendFile as aF,mkdir as cF}from"node:fs/promises";import{homedir as Rx}from"node:os";import{basename as lF,join as Cx}from"node:path";import{createInterface as dF}from"node:readline";function Ix(){return Cx(Rx(),".maind","gateway","events.jsonl")}async function uF(e){try{let t=Ix();await cF(Cx(Rx(),".maind","gateway"),{recursive:!0}),await aF(t,JSON.stringify(e)+`
920
+ `,{mode:384})}catch{}}function Nx(e){let t=new Set,n=null,r=0;for(;r<e.length;){let i=e[r];if(i==="--deny-tool"){let s=e[r+1];if(!s)return null;t.add(s),r+=2;continue}if(i==="--label"){let s=e[r+1];if(!s)return null;n=s,r+=2;continue}if(i==="--"){let s=e[r+1];return s?{denyTools:t,label:n,command:s,args:e.slice(r+2)}:null}return null}return null}async function fF(e){if(e[0]==="install"||e[0]==="uninstall"){let{runGatewayInstall:x,runGatewayUninstall:v}=await Promise.resolve().then(()=>(Ex(),Sx));return e[0]==="install"?x(e.slice(1)):v(e.slice(1))}if(e[0]==="mode"||e[0]==="policy"||e[0]==="attest"){let{runGatewayAttest:x,runGatewayMode:v,runGatewayPolicy:E}=await Promise.resolve().then(()=>(Ax(),Tx));return e[0]==="mode"?v(e.slice(1)):e[0]==="attest"?x(e.slice(1)):E(e.slice(1))}let t=Nx(e);if(t===null)return process.stderr.write(`usage: maind-mcp-bridge gateway [--deny-tool <name>]... [--label <name>] -- <command> [args...]
921
921
  maind-mcp-bridge gateway install [--yes] [--dry-run]
922
922
  maind-mcp-bridge gateway uninstall [--yes] [--dry-run]
923
923
  maind-mcp-bridge gateway mode [off|warn|enforce]
@@ -927,58 +927,58 @@ EXPERIMENTAL (gateway spike): wraps a stdio MCP server; logs tool-call
927
927
  NAMES to ~/.maind/gateway/events.jsonl and answers denied tools locally.
928
928
  install/uninstall rewrite Claude Code MCP configs (consent per server).
929
929
  mode/policy: convention-bound policy (Stufe 2b) \u2014 deny only in enforce.
930
- `),2;let{denyTools:n,label:r,command:i,args:s}=t,a=r??TL(i),c=Wi(),l=Vk(),d=l==="off"?null:es(),u=c==="off"?[]:va(Ki())?.rules??[];c!=="off"&&ka().then(k=>{k!==null&&(u=k,wa(Ki(),k))}).catch(()=>{});let p=[],f=ba()&&q()!==null&&c!=="off",h=null;try{h=Y()}catch{h=null}let g=o(k=>{RL(k),f&&p.push(k)},"record"),y=o(async()=>{if(!f)return;let k=jk(p.splice(0),c,a,h);k!==null&&(await Ku(k)||await Uk(k))},"attestAndReset");f&&Hk().catch(()=>{});let b=setInterval(()=>{y()},30*6e4);b.unref();let w=xL(i,s,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",k=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(k)}
931
- `),process.exitCode=1});let x=AL({input:process.stdin,terminal:!1});x.on("line",k=>{let v=kp(k);if(v.kind==="request"&&v.method==="tools/call"&&v.toolName){if(n.has(v.toolName)&&v.id!==void 0){process.stdout.write(Hn(v.id,v.toolName)+`
932
- `),g(Ca("deny",a,v.toolName,Date.now()));return}let T=Yk(v.toolName,a,u,c);if(T.kind==="deny"&&v.id!==void 0){process.stdout.write(Hn(v.id,v.toolName,Jk(v.toolName,T.rule))+`
933
- `),g(Ia("policy_deny",a,v.toolName,Date.now(),T.rule.conventionId,T.rule.conventionVersion));return}(T.kind==="warn"||T.kind==="deny")&&g(Ia("policy_warn",a,v.toolName,Date.now(),T.rule.conventionId,T.rule.conventionVersion));let O=ts(k,d);if(O.length>0){let j=O.find(U=>U.verdict==="fabricated");if(j!==void 0&&l==="enforce"&&c==="enforce"&&v.id!==void 0&&j!==void 0&&v.id!==void 0){process.stdout.write(Hn(v.id,v.toolName,Bn(j,!0))+`
934
- `),g(Na("sha_deny",a,v.toolName,Date.now()));return}let N=j??O[0];process.stderr.write(`[maind gateway] ${Bn(N,!1)}
935
- `),g(Na("sha_warn",a,v.toolName,Date.now()))}g(Ca("tool_call",a,v.toolName,Date.now()))}w.stdin.write(k+`
936
- `)}),x.on("close",()=>{w.stdin.end()});let S=await new Promise(k=>{w.on("exit",(v,T)=>{k(v??(T?1:0))})});return clearInterval(b),await y(),S}var gx=_(()=>{"use strict";Oa();Bk();Vu();zu();Da();Yu();Ju();ue();Fe();o(fx,"gatewayEventsFile");o(RL,"logEvent");o(mx,"parseGatewayArgs");o(CL,"runGateway")});var rp={};Q(rp,{MAX_ENTRIES:()=>Xu,TTL_MS:()=>ep,crossSessionDir:()=>tp,decideCrossSession:()=>bx,parseSessionDb:()=>_x,pruneDb:()=>np,runGuardCrossCheck:()=>FL,runGuardCrossObserve:()=>LL,staleReason:()=>Zu});import{mkdir as IL,readFile as NL,readdir as OL,stat as yx,unlink as DL,writeFile as PL}from"node:fs/promises";import{homedir as ML}from"node:os";import{join as Qu}from"node:path";function tp(){return Qu(ML(),".maind","cross-session")}function _x(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[s,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[s]=a);return{files:r,warned:i}}function np(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=ep);return n.length>Xu&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-Xu)),{files:Object.fromEntries(n),warned:e.warned}}function bx(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function Zu(e,t){return`Cross-session guard: '${e}' changed on disk after this session last read it (mtime ${Math.floor(t.current/1e3)} > recorded ${Math.floor(t.baseline/1e3)}). Likely a parallel session, an editor, or git (checkout/pull). Re-read the file, reconcile with the external change, then retry.`}async function wx(e){let t=tp();return await IL(t,{recursive:!0}),Qu(t,`${e}.json`)}async function vx(e,t){try{let n=await NL(await wx(e),"utf8");return np(_x(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function kx(e,t){try{await PL(await wx(e),JSON.stringify(t),{mode:384})}catch{}}async function $L(e){try{let t=tp();for(let n of await OL(t)){if(!n.endsWith(".json"))continue;let r=Qu(t,n),i=await yx(r).catch(()=>null);i&&e-i.mtimeMs>ep&&await DL(r).catch(()=>{})}}catch{}}async function xx(e){try{return(await yx(e)).mtimeMs}catch{return}}async function LL(e,t=Date.now()){try{if(ie().mode==="off")return 0;let r=e??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=Ie(r);if(!i||!s)return 0;let a=await xx(s);if(a===void 0)return 0;let c=await vx(i,t);return c.files[s]={m:a,t},delete c.warned[s],await kx(i,np(c,t)),await $L(t),0}catch{return 0}}async function FL(e,t=Date.now()){try{let n=ie();if(n.mode==="off")return 0;let r=e??await G(),i=typeof r.session_id=="string"?r.session_id:"",s=Ie(r);if(!i||!s)return 0;let a=await vx(i,t),c=bx(a.files[s]?.m,await xx(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write(Mn(Zu(s,c))+`
937
- `),await J({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(a.warned[s]===c.current||(process.stdout.write(Ne(Zu(s,c))+`
938
- `),a.warned[s]=c.current,await kx(i,a),await J({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var ep,Xu,ip=_(()=>{"use strict";ge();Wt();Xe();ht();ep=48*3600*1e3,Xu=500;o(tp,"crossSessionDir");o(_x,"parseSessionDb");o(np,"pruneDb");o(bx,"decideCrossSession");o(Zu,"staleReason");o(wx,"dbPath");o(vx,"loadDb");o(kx,"saveDb");o($L,"sweepStaleSessionFiles");o(xx,"fileMtime");o(LL,"runGuardCrossObserve");o(FL,"runGuardCrossCheck")});var sp={};Q(sp,{INDEX_REFRESH_WORKER:()=>Sx,acquireLock:()=>Ho,releaseLock:()=>Ri,runIndexRefreshWorker:()=>WL,runOnIndexRefresh:()=>GL});import{spawn as jL}from"node:child_process";import{existsSync as UL}from"node:fs";import{join as HL}from"node:path";function BL(e){return HL(e,".maind","code-index.sqlite")}async function GL(){try{let e=await G(),t=he(typeof e.cwd=="string"?e.cwd:process.cwd());if(!UL(BL(t))||!Ho(t))return 0;let n=process.argv[1];if(n===void 0)return Ri(t),0;jL(process.execPath,[n,Sx,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function WL(){let e=process.argv[3]??he();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(Ao(),xd)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Ri(e)}return 0}var Sx,op=_(()=>{"use strict";ge();Bt();Nd();Sx="index-refresh-run";o(BL,"indexDbPath");o(GL,"runOnIndexRefresh");o(WL,"runIndexRefreshWorker")});function Ea(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&/(sh|ch|x|z|ss)es$/.test(t)||t.length>6&&t.endsWith("ungen")?t.slice(0,-2):t.length>5&&t.endsWith("ing")?t.slice(0,-3):t.length>5&&t.endsWith("en")||t.length>4&&t.endsWith("ed")?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function xa(e){return e.length<3||/^\d+$/.test(e)||Ex.has(e)||Ex.has(Ea(e))}function zL(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function qL(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function Ax(e){let t=new Set,n=new Set,r=[];for(let i of e.matchAll(YL)){let s=i[0],a=s.toLowerCase();if(r.push(a),/[._-]/.test(s)){let c=qL(a);c.length>=4&&!Tx.has(c)&&n.add(c)}for(let c of zL(s)){let l=c.toLowerCase();xa(l)||t.add(Ea(l))}}for(let i=0;i+1<r.length;i++){if(/[._-]/.test(r[i])||/[._-]/.test(r[i+1]))continue;let s=`${r[i]}-${r[i+1]}`;Tx.has(s)||n.add(s)}return{words:t,compounds:n}}function JL(e){return e.slice(0,8e3).replace(/<pasted_content\b[\s\S]*?(<\/pasted_content>|$)/g," ").replace(/https?:\/\/\S+/g," ").replace(/(?:~|\.{1,2})?\/[\w.@%+~-]+(?:\/[\w.@%+~-]*)+/g," ").replace(/\b[\w.-]+(?:\/[\w.@%+~-]+)+/g," ")}function Rx(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function cp(e){if(!e)return[];let t=[];for(let n of e.split(`
939
- `)){let r=XL.exec(n.trim());r&&t.push({scope:r[1],shortId:r[2],id:`conv_${r[2].replace(/-/g,"_")}`,version:Number.parseInt(r[3],10),summary:r[4].trim()})}return t}function ZL(e){let t=e.shortId.split("-"),n=new Set;for(let s of t)xa(s)||n.add(Ea(s));let r=new Set;for(let s=0;s+1<t.length;s++)!xa(t[s])&&!xa(t[s+1])&&r.add(`${t[s]}-${t[s+1]}`);let i=Ax(e.summary);for(let s of i.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(s)&&r.add(s);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:i.words}}function Cx(e,t,n=3,r=[]){if(t.length===0)return[];let i=new Set([...r].map(f=>Ea(f.toLowerCase()))),s=t.map(ZL),a=new Map,c=new Map;for(let f of s){let h=new Set([...f.keyWords,...f.keyCompounds]);for(let g of h)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...h,...f.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=s.length,d=o(f=>Math.log(1+l/(c.get(f)??l)),"idf"),u=Ax(JL(e));for(let f of i)u.words.delete(f);let p=[];for(let f of s){let h=new Set;for(let x of u.words)f.keyWords.has(x)&&h.add(x);for(let x of u.compounds)f.keyCompounds.has(x)&&h.add(x);let g=new Set;for(let x of u.words)!h.has(x)&&f.summaryWords.has(x)&&g.add(x);if(h.size===0&&g.size===0)continue;let y=0;for(let x of h)y+=2*d(x);for(let x of g)y+=d(x);let b=[...h].some(x=>(a.get(x)??0)!==1?!1:/[.-]/.test(x)?x.length>=5:x.length>=6),w=h.size>=1&&h.size+g.size>=2&&y>=QL;!b&&!w||p.push({convention:f.convention,score:y,matched:[...h,...g]})}return p.sort((f,h)=>h.score-f.score||f.convention.id.localeCompare(h.convention.id)).slice(0,n)}function nF(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function Ix(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],i=new Set,s=o((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||eF.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!nF(u))return;let p=u.split("."),f=p[p.length-1];f.length<(l||d?3:4)||tF.has(f.toLowerCase())||i.has(f)||(i.add(f),r.push({name:f,qualifier:p.length>1?p[p.length-2]:null}))},"consider");for(let c of n.matchAll(/`([^`\n]{1,120})`/g))s(c[1].trim(),!0);let a=n.replace(/`[^`\n]{1,120}`/g," ");for(let c of a.matchAll(/(?<![\w$./\\-])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)(?![\w$/\\-])/g))s(c[1],!1);return r}function ap(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ox(e,t=2e3){let n=e.conventions,r=e.symbols.filter(d=>d.locations.length>0);if(n.length===0&&r.length===0)return null;let i=new Sa(t-Nx);if(!i.tryAdd(`${KL} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let s=[],a=[],c=!1;if(n.length>0&&i.tryAdd("Project conventions whose terms appear in this prompt (full text: get_conventions({id})):"))for(let d of n){let u=`- ${d.convention.id} (v${d.convention.version}): ${ap(d.convention.summary,320)}`;if(!i.tryAdd(u)){c=!0;break}s.push(d.convention.id)}if(r.length>0&&!c){let d=e.repoRoot?` in ${e.repoRoot}`:"";if(i.tryAdd(`Symbols this prompt names, as the local code index places them${d} (files unchanged since indexing):`))for(let u of r){let p=u.locations.slice(0,3),f=p.map(y=>{let b=y.qualifiedName===u.candidate.name?y.kind:`${y.kind} ${y.qualifiedName}`;return`${y.filePath}:${y.startLine} (${b})${y.signature?` '${ap(y.signature,70)}'`:""}`}).join("; "),h=u.total-p.length,g=`- ${u.candidate.name} \u2192 ${f}${h>0?` (+${h} more \u2014 codebase_search)`:""}`;if(!i.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(s.length===0&&a.length===0)return null;let l=i.toString();return c&&(l+=`
940
- (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:s,symbolNames:a}}function iF(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>rF}function sF(e){if(e.length===0)return"";let t=e.map(i=>i.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(i=>i[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function oF(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function Dx(e,t=1500){let n=new Map;for(let g of e.callers){let y=n.get(g.calleeKey)??[];y.some(b=>b.caller.nodeKey===g.caller.nodeKey)||y.push(g),n.set(g.calleeKey,y)}let r=o(g=>new Set((n.get(g)??[]).map(y=>y.caller.filePath)).size,"fileCount"),i=e.symbols.filter(g=>n.has(g.nodeKey)).sort((g,y)=>r(y.nodeKey)-r(g.nodeKey)||g.startLine-y.startLine),s=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=iF(e.range,s)&&a.length>0;if(i.length===0&&e.importers.length===0&&!c)return null;let l=sF([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new Sa(t-Nx),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${VL} ${e.relPath} as the local code index knows it (the index matches this file on disk).${u}`))return null;let p=!1;if(c&&d.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let g="",y=0;for(let w of a){let x=`${w.qualifiedName} L${w.startLine}`,S=g.length===0?x:`${g} \xB7 ${x}`;if(S.length>500)break;g=S,y++}let b=a.length-y;d.tryAdd(b>0?`${g} \xB7 +${b} more`:g)||(p=!0)}if(i.length>0&&!p&&d.tryAdd("Called from other files (import-resolved call graph):"))for(let g of i){let y=n.get(g.nodeKey)??[],b=y.slice(0,3).map(k=>`${oF(k.caller,l)}${k.kind==="calls"?"":` [${k.kind}]`}`),w=y.length-b.length,x=g.signature?` '${ap(g.signature,80)}'`:"",S=`- ${g.qualifiedName} L${g.startLine}${x} \u2190 ${b.join(", ")}${w>0?` +${w} more`:""}`;if(!d.tryAdd(S)){p=!0;break}}if(e.importers.length>0&&!p){let g=e.importers.slice(0,5).map(x=>x.slice(l.length)),y=e.importers.length-g.length,b=e.importers.length,w=`Imported by ${b} file${b===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(w)||(p=!0)}e.hidden>0&&!p&&d.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let f=e.unchecked??0;if(f>0&&!p&&d.tryAdd(`(+${f} more reference${f===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),d.size<=1)return null;let h=d.toString();return p&&(h+=`
941
- (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),h}var KL,VL,Ex,Tx,YL,XL,QL,eF,tF,Sa,Nx,rF,Px=_(()=>{"use strict";KL="[maind context \xB7 prompt]",VL="[maind context \xB7 read]",Ex=new Set("a an the and or but if then else when while of to in on at by for with from into onto over under about as is are was were be been being it its this that these those there here we you i me my our your they them their he she his her not no yes do does did done can could should would will shall may might must have has had so too very just also only all any some each every more most less than what which who whom whose why how where please let lets make made use used uses using get got new now one two via per etc out up down off again before after first last next previous other same different main default good bad right wrong both much many few own still even ever never always add added adding build builds built change changes changed check checks checked create created fix fixed fixes update updated updates write writes written read reads run runs running start started stop set show find look need needs want work works working try keep move put give take call called see know think tell say ask help mean like sure ok okay thing things stuff way part step steps case cases time today explicit implicit user users agent agents file files code line lines value values name names list type types data text rule rules policy pattern patterns anti convention conventions maind claude project projects repo repository branch branches feature features task tasks issue issues problem error errors bug bugs test tests verify version versions thanks thank gate gates content note notes org block apply applies render renders object objects title titles comment comments description local remote script scripts sync kind strategy request alternative better open close merge merged action reason lesson lessons word words der die das den dem des ein eine einen einem einer eines und oder aber wenn dann sonst als wie was wer wo warum weil dass ist sind war waren sein bin bist hat haben hatte wird werden wurde kann k\xF6nnen koennen k\xF6nnte soll sollen sollte muss m\xFCssen muessen darf nicht kein keine nur auch noch schon mal bitte ich du er sie es wir ihr mich mir dich dir uns euch ihnen sich mit ohne f\xFCr fuer auf aus bei nach vor \xFCber ueber unter zum zur im am um an in von zu bis durch gegen hier da dort jetzt ja nein doch also man dies diese dieser dieses mach mache machen lass lasst gib geht gehen gut schreib schreibe schreiben bau baue bauen pr\xFCf pr\xFCfe pr\xFCfen pruefen lies lesen starte starten teste testen nutze nutzen brauch brauchen datei dateien zeile zeilen neue neuen neu alte alten erst gleich kurz einfach richtig falsch danke".split(/\s+/)),Tx=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);o(Ea,"stem");o(xa,"isNoise");o(zL,"splitParts");o(qL,"normalizeCompound");YL=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;o(Ax,"termsOf");o(JL,"promptForMatching");o(Rx,"repoNameWords");XL=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;o(cp,"parseConventionLines");o(ZL,"profileOf");QL=4.5;o(Cx,"matchConventions");eF=/\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts|py|pyi|md|mdx|json|jsonc|ya?ml|toml|sql|css|scss|html|sh|txt|lock|env|log|png|svg|jpe?g|gif|pdf)$/i,tF=new Set(["JavaScript","TypeScript","GitHub","GitLab","PostgreSQL","MySQL","SQLite","NodeJS","NextJS","macOS","iOS","iPhone","iPad","iCloud","OpenAI","YouTube","LinkedIn","PowerShell","VSCode","WebSocket","OAuth","PostHog","DevTools","ChatGPT","DeepSeek","OpenVSX","AgentComposer","ClaudeCode","McpServer","README","TODO","FIXME"].map(e=>e.toLowerCase()));o(nF,"looksLikeCode");o(Ix,"extractSymbolCandidates");o(ap,"clip");Sa=class{constructor(t){this.budget=t}static{o(this,"Budgeted")}lines=[];used=0;tryAdd(t){let n=t.length+(this.lines.length>0?1:0);return this.used+n>this.budget?!1:(this.lines.push(t),this.used+=n,!0)}get size(){return this.lines.length}toString(){return this.lines.join(`
942
- `)}},Nx=90;o(Ox,"renderPromptContext");rF=2e3;o(iF,"isPartialRead");o(sF,"commonDir");o(oF,"callerLabel");o(Dx,"renderReadContext")});import{createHash as aF}from"node:crypto";import{existsSync as Mx,mkdirSync as cF,readdirSync as lF,rmSync as dF,statSync as uF,writeFileSync as pF}from"node:fs";import{join as Ta}from"node:path";function lp(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function hF(e,t,n=null,r=mF){try{for(let i of lF(e)){let s=Ta(e,i);if(s!==n)try{t-uF(s).mtimeMs>r&&dF(s,{recursive:!0,force:!0})}catch{}}}catch{}}var fF,mF,zi,$x=_(()=>{"use strict";Qe();fF=Ta(pt,"context"),mF=7*24*60*60*1e3;o(lp,"safe");zi=class e{constructor(t,n){this.root=t;this.dir=n}static{o(this,"SeenMarks")}static forScope(t,n,r=fF){let i=n?`${lp(t)}__${lp(n)}`:lp(t);return new e(r,Ta(r,i))}fileFor(t){return Ta(this.dir,aF("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return Mx(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{Mx(this.dir)||(cF(this.dir,{recursive:!0,mode:448}),hF(this.root,n,this.dir));for(let r of t)try{pF(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};o(hF,"sweepStaleScopes")});var pp={};Q(pp,{INDEX_RELPATH:()=>Lt,SOFT_BUDGET_MS:()=>jx,findRepoRoot:()=>Ft,isMachinePrompt:()=>Gx,loadCachedConventions:()=>Hx,promptContextFor:()=>Kx,promptTextOf:()=>Bx,readContextFor:()=>Vx,runOnPromptContext:()=>SF,runOnReadContext:()=>TF});import{existsSync as Lx,readFileSync as gF,realpathSync as yF,statSync as _F}from"node:fs";import{dirname as bF,isAbsolute as Fx,join as qi,relative as wF,sep as vF}from"node:path";function kF(e,t){let n=wF(e,t);return!n||n.startsWith("..")||Fx(n)?null:n.split(vF).join("/")}function up(e){try{let t=_F(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function Ux(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(Ao(),xd));return t(e)}function Hx(e,t={}){try{let n=t.identity===void 0?Gi():t.identity;if(e!==null&&n!==null){let r=Ks(e,n),i=Po(r?.result.instructions??null),s=cp(i);if(s.length>0)return s}}catch{}try{let n=JSON.parse(gF(t.briefingCacheFile??xr,"utf8"));if(typeof n.conventions=="string")return cp(n.conventions)}catch{}return[]}function Bx(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function Gx(e,t){if(e.is_command===!0)return!0;let n=t.trimStart();return/^\/[A-Za-z][\w:-]*(\s|$)/.test(n)||/^<[a-z][\w-]*[\s>]/.test(n)||n.startsWith("This session is being continued from a previous conversation")}function Wx(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";if(!t)return null;let n=typeof e.agent_id=="string"&&e.agent_id.trim()?e.agent_id.trim():null;return{sessionId:t,agentId:n}}async function xF(e,t,n,r){let i;try{i=await r(n)}catch{return[]}try{if(!i.meta().schemaCurrent)return[];let s=i.symbolsNamed(e.map(d=>d.name)),a=i.files([...s.values()].flat().map(d=>d.filePath).slice(0,dp)),c=new Set;for(let[d,u]of a){let p=up(qi(t,d));p!==null&&fi(u,p)&&c.add(d)}let l=[];for(let d of e){let u=s.get(d.name)??[],p=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),f=p.length>0?p:u,h=f.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));h.length>0&&l.push({candidate:d,locations:h,total:f.length})}return l}catch{return[]}finally{try{i.close()}catch{}}}async function Kx(e,t={}){let n=t.now??Date.now,r=n();if(Ai(e,t.env??process.env))return null;let i=Bx(e);if(i.trim().length===0||Gx(e,i))return null;let s=Wx(e);if(s===null)return null;let a=zi.forScope(s.sessionId,s.agentId,t.seenRoot),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Ft(c),d=Cx(i,(t.loadConventions??Hx)(l),6,Rx(l)).filter(y=>!a.has(`conv:${y.convention.id}@${y.convention.version}`)).slice(0,3),u=Ix(i).filter(y=>!a.has(`sym:${l??""}:${y.name}`)),p=l===null?null:qi(l,Lt),f=u.length>0&&p!==null&&l!==null&&Lx(p)&&n()-r<jx?await xF(u,l,p,t.openReader??Ux):[],h=Ox({repoRoot:l,conventions:d,symbols:f});if(h===null)return null;let g=new Map(d.map(y=>[y.convention.id,y.convention.version]));return a.mark([...h.conventionIds.map(y=>`conv:${y}@${g.get(y)??0}`),...h.symbolNames.map(y=>`sym:${l??""}:${y}`)],n()),h.text}async function SF(){try{let e=await Kx(await G());e!==null&&process.stdout.write(Av(e))}catch{}return 0}function EF(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=typeof n.offset=="number"&&Number.isFinite(n.offset)?n.offset:void 0,i=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&i===void 0?null:{offset:r,limit:i}}async function Vx(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read"||Ai(e,t.env??process.env))return null;let r=Ie(e);if(!r||er(r)===null||Jr(r))return null;let i=Wx(e);if(i===null)return null;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=Fx(r)?r:qi(s,r),c;try{c=yF(a)}catch{return null}let l=Ft(bF(c));if(l===null)return null;let d=qi(l,Lt);if(!Lx(d))return null;let u=kF(l,c);if(u===null)return null;let p=await(t.openReader??Ux)(d);try{let f=p.meta();if(!f.schemaCurrent)return null;let h=p.file(u);if(h===null)return null;let g=up(c);if(g===null||!fi(h,g))return null;let y=zi.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${l}:${u}@${h.contentHash}`;if(y.has(b))return null;let w=p.symbolsInFile(u),x=f.edgesDirty?[]:p.callersOfFile(u),S=f.edgesDirty?[]:p.importersOf(u),k=[...new Set([...x.map(z=>z.caller.filePath),...S])],v=k.slice(0,dp),T=new Set(k.slice(dp)),O=p.files(v),j=new Set;for(let z of v){let be=O.get(z),Un=be===void 0?null:up(qi(l,z));be!==void 0&&Un!==null&&fi(be,Un)&&j.add(z)}let H=o(z=>x.filter(be=>z.has(be.caller.filePath)).length+S.filter(be=>z.has(be)).length,"countIn"),N=x.filter(z=>j.has(z.caller.filePath)).map(z=>({calleeKey:z.calleeKey,kind:z.kind,caller:{nodeKey:z.caller.nodeKey,kind:z.caller.kind,qualifiedName:z.caller.qualifiedName,filePath:z.caller.filePath,startLine:z.caller.startLine}})),U=S.filter(z=>j.has(z)),ae=H(T),yt=x.length-N.length+(S.length-U.length)-ae,Fr=Dx({relPath:u,symbols:w,callers:N,importers:U,hidden:yt,unchecked:ae,range:EF(e)});return Fr===null?null:(y.mark([b],n()),Fr)}finally{p.close()}}async function TF(){try{let e=await Vx(await G());e!==null&&process.stdout.write(Ne(e))}catch{}return 0}var jx,dp,fp=_(()=>{"use strict";It();Td();Sr();Lr();Nt();Px();$x();fo();ge();Wt();jx=200,dp=200;o(kF,"repoRelative");o(up,"diskStat");o(Ux,"openReader");o(Hx,"loadCachedConventions");o(Bx,"promptTextOf");o(Gx,"isMachinePrompt");o(Wx,"scopeOf");o(xF,"locateSymbols");o(Kx,"promptContextFor");o(SF,"runOnPromptContext");o(EF,"readRangeOf");o(Vx,"readContextFor");o(TF,"runOnReadContext")});import{randomUUID as AF}from"node:crypto";jr();import{createInterface as OR}from"node:readline";var cS=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["cline","cline"],["continue","continue"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function lS(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of cS)if(t.includes(n))return r;return null}o(lS,"mapClientInfoNameToFamily");function vp(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ra(t)||t.method!=="initialize")return null;let n=t.params;if(!Ra(n))return null;let r=n.clientInfo;if(!Ra(r))return null;let i=r.name,s=lS(typeof i=="string"?i:null);if(s===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:s,version:c}}o(vp,"tryExtractInitializeClient");function Ra(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Ra,"isRecord");Oa();Da();function Pa(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch{return[]}let n=[],r=[],i=o(()=>{if(r.length===0)return;let s=r.join(`
930
+ `),2;let{denyTools:n,label:r,command:i,args:s}=t,a=r??lF(i),c=Yi(),l=lx(),d=l==="off"?null:ss(),u=c==="off"?[]:Ra(Ji())?.rules??[];c!=="off"&&Ca().then(x=>{x!==null&&(u=x,Aa(Ji(),x))}).catch(()=>{});let f=[],p=Ta()&&Y()!==null&&c!=="off",h=null;try{h=J()}catch{h=null}let g=o(x=>{uF(x),p&&f.push(x)},"record"),y=o(async()=>{if(!p)return;let x=nx(f.splice(0),c,a,h);x!==null&&(await ef(x)||await rx(x))},"attestAndReset");p&&ix().catch(()=>{});let b=setInterval(()=>{y()},30*6e4);b.unref();let w=oF(i,s,{stdio:["pipe","pipe","inherit"]});w.stdout.pipe(process.stdout),w.on("error",x=>{process.stderr.write(`[maind gateway] failed to start '${i}': ${String(x)}
931
+ `),process.exitCode=1});let k=dF({input:process.stdin,terminal:!1});k.on("line",x=>{let v=Of(x);if(v.kind==="request"&&v.method==="tools/call"&&v.toolName){if(n.has(v.toolName)&&v.id!==void 0){process.stdout.write(Bn(v.id,v.toolName)+`
932
+ `),g($a("deny",a,v.toolName,Date.now()));return}let E=fx(v.toolName,a,u,c);if(E.kind==="deny"&&v.id!==void 0){process.stdout.write(Bn(v.id,v.toolName,px(v.toolName,E.rule))+`
933
+ `),g(La("policy_deny",a,v.toolName,Date.now(),E.rule.conventionId,E.rule.conventionVersion));return}(E.kind==="warn"||E.kind==="deny")&&g(La("policy_warn",a,v.toolName,Date.now(),E.rule.conventionId,E.rule.conventionVersion));let N=os(x,d);if(N.length>0){let F=N.find(L=>L.verdict==="fabricated");if(F!==void 0&&l==="enforce"&&c==="enforce"&&v.id!==void 0&&F!==void 0&&v.id!==void 0){process.stdout.write(Bn(v.id,v.toolName,Gn(F,!0))+`
934
+ `),g(Fa("sha_deny",a,v.toolName,Date.now()));return}let P=F??N[0];process.stderr.write(`[maind gateway] ${Gn(P,!1)}
935
+ `),g(Fa("sha_warn",a,v.toolName,Date.now()))}g($a("tool_call",a,v.toolName,Date.now()))}w.stdin.write(x+`
936
+ `)}),k.on("close",()=>{w.stdin.end()});let S=await new Promise(x=>{w.on("exit",(v,E)=>{x(v??(E?1:0))})});return clearInterval(b),await y(),S}var Dx=_(()=>{"use strict";ja();sx();tf();nf();Ua();sf();of();ue();Ee();o(Ix,"gatewayEventsFile");o(uF,"logEvent");o(Nx,"parseGatewayArgs");o(fF,"runGateway")});var pf={};ee(pf,{MAX_ENTRIES:()=>af,TTL_MS:()=>df,crossSessionDir:()=>uf,decideCrossSession:()=>$x,parseSessionDb:()=>Mx,pruneDb:()=>ff,runGuardCrossCheck:()=>vF,runGuardCrossObserve:()=>wF,staleReason:()=>cf});import{mkdir as pF,readFile as mF,readdir as hF,stat as Px,unlink as gF,writeFile as yF}from"node:fs/promises";import{homedir as _F}from"node:os";import{join as lf}from"node:path";function uf(){return lf(_F(),".maind","cross-session")}function Mx(e){let t={files:{},warned:{}};if(typeof e!="object"||e===null)return t;let n=e,r={};if(typeof n.files=="object"&&n.files!==null)for(let[s,a]of Object.entries(n.files)){if(typeof a!="object"||a===null)continue;let c=a;typeof c.m!="number"||typeof c.t!="number"||!Number.isFinite(c.m)||!Number.isFinite(c.t)||(r[s]={m:c.m,t:c.t})}let i={};if(typeof n.warned=="object"&&n.warned!==null)for(let[s,a]of Object.entries(n.warned))typeof a=="number"&&Number.isFinite(a)&&(i[s]=a);return{files:r,warned:i}}function ff(e,t){let n=Object.entries(e.files).filter(([,r])=>t-r.t<=df);return n.length>af&&(n=n.sort((r,i)=>r[1].t-i[1].t).slice(n.length-af)),{files:Object.fromEntries(n),warned:e.warned}}function $x(e,t){return e===void 0||t===void 0?{kind:"allow"}:t>e?{kind:"stale",baseline:e,current:t}:{kind:"allow"}}function cf(e,t){return`Cross-session guard: '${e}' changed on disk after this session last read it (mtime ${Math.floor(t.current/1e3)} > recorded ${Math.floor(t.baseline/1e3)}). Likely a parallel session, an editor, or git (checkout/pull). Re-read the file, reconcile with the external change, then retry.`}async function Lx(e){let t=uf();return await pF(t,{recursive:!0}),lf(t,`${e}.json`)}async function Fx(e,t){try{let n=await mF(await Lx(e),"utf8");return ff(Mx(JSON.parse(n)),t)}catch{return{files:{},warned:{}}}}async function jx(e,t){try{await yF(await Lx(e),JSON.stringify(t),{mode:384})}catch{}}async function bF(e){try{let t=uf();for(let n of await hF(t)){if(!n.endsWith(".json"))continue;let r=lf(t,n),i=await Px(r).catch(()=>null);i&&e-i.mtimeMs>df&&await gF(r).catch(()=>{})}}catch{}}async function Ux(e){try{return(await Px(e)).mtimeMs}catch{return}}async function wF(e,t=Date.now()){try{if(se().mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Ne(r);if(!i||!s)return 0;let a=await Ux(s);if(a===void 0)return 0;let c=await Fx(i,t);return c.files[s]={m:a,t},delete c.warned[s],await jx(i,ff(c,t)),await bF(t),0}catch{return 0}}async function vF(e,t=Date.now()){try{let n=se();if(n.mode==="off")return 0;let r=e??await W(),i=typeof r.session_id=="string"?r.session_id:"",s=Ne(r);if(!i||!s)return 0;let a=await Fx(i,t),c=$x(a.files[s]?.m,await Ux(s));return c.kind==="allow"?0:n.mode==="block"?(process.stdout.write($n(cf(s,c))+`
937
+ `),await X({event:"cross_session_deny",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s}),0):(a.warned[s]===c.current||(process.stdout.write(Oe(cf(s,c))+`
938
+ `),a.warned[s]=c.current,await jx(i,a),await X({event:"cross_session_warn",session_id:i,cwd:typeof r.cwd=="string"?r.cwd:void 0,detail:s})),0)}catch{return 0}}var df,af,mf=_(()=>{"use strict";ge();Wt();Qe();ht();df=48*3600*1e3,af=500;o(uf,"crossSessionDir");o(Mx,"parseSessionDb");o(ff,"pruneDb");o($x,"decideCrossSession");o(cf,"staleReason");o(Lx,"dbPath");o(Fx,"loadDb");o(jx,"saveDb");o(bF,"sweepStaleSessionFiles");o(Ux,"fileMtime");o(wF,"runGuardCrossObserve");o(vF,"runGuardCrossCheck")});var hf={};ee(hf,{INDEX_REFRESH_WORKER:()=>Hx,acquireLock:()=>Ko,releaseLock:()=>Ci,runIndexRefreshWorker:()=>AF,runOnIndexRefresh:()=>TF});import{spawn as kF}from"node:child_process";import{existsSync as xF}from"node:fs";import{join as SF}from"node:path";function EF(e){return SF(e,".maind","code-index.sqlite")}async function TF(){try{let e=await W(),t=he(typeof e.cwd=="string"?e.cwd:process.cwd());if(!xF(EF(t))||!Ko(t))return 0;let n=process.argv[1];if(n===void 0)return Ci(t),0;kF(process.execPath,[n,Hx,t],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch{}return 0}async function AF(){let e=process.argv[3]??he();try{let{createNodeCodeIndex:t}=await Promise.resolve().then(()=>(No(),Id)),n=t({repoRoot:e});try{await n.indexRepository({full:!1})}finally{await n.close()}}catch{}finally{Ci(e)}return 0}var Hx,gf=_(()=>{"use strict";ge();Bt();Fd();Hx="index-refresh-run";o(EF,"indexDbPath");o(TF,"runOnIndexRefresh");o(AF,"runIndexRefreshWorker")});function Oa(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&/(sh|ch|x|z|ss)es$/.test(t)||t.length>6&&t.endsWith("ungen")?t.slice(0,-2):t.length>5&&t.endsWith("ing")?t.slice(0,-3):t.length>5&&t.endsWith("en")||t.length>4&&t.endsWith("ed")?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function Ia(e){return e.length<3||/^\d+$/.test(e)||Bx.has(e)||Bx.has(Oa(e))}function IF(e){return e.split(/[._-]+/).flatMap(t=>t.split(/(?<=[a-z0-9])(?=[A-Z])/)).filter(t=>t.length>0)}function NF(e){return e.replace(/_/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function Wx(e){let t=new Set,n=new Set,r=[];for(let i of e.matchAll(OF)){let s=i[0],a=s.toLowerCase();if(r.push(a),/[._-]/.test(s)){let c=NF(a);c.length>=4&&!Gx.has(c)&&n.add(c)}for(let c of IF(s)){let l=c.toLowerCase();Ia(l)||t.add(Oa(l))}}for(let i=0;i+1<r.length;i++){if(/[._-]/.test(r[i])||/[._-]/.test(r[i+1]))continue;let s=`${r[i]}-${r[i+1]}`;Gx.has(s)||n.add(s)}return{words:t,compounds:n}}function DF(e){return e.slice(0,8e3).replace(/<pasted_content\b[\s\S]*?(<\/pasted_content>|$)/g," ").replace(/https?:\/\/\S+/g," ").replace(/(?:~|\.{1,2})?\/[\w.@%+~-]+(?:\/[\w.@%+~-]*)+/g," ").replace(/\b[\w.-]+(?:\/[\w.@%+~-]+)+/g," ")}function Kx(e){return e?(e.split(/[\\/]/).filter(Boolean).pop()??"").split(/[^\p{L}\p{N}]+/u).filter(n=>n.length>=3):[]}function _f(e){if(!e)return[];let t=[];for(let n of e.split(`
939
+ `)){let r=PF.exec(n.trim());r&&t.push({scope:r[1],shortId:r[2],id:`conv_${r[2].replace(/-/g,"_")}`,version:Number.parseInt(r[3],10),summary:r[4].trim()})}return t}function MF(e){let t=e.shortId.split("-"),n=new Set;for(let s of t)Ia(s)||n.add(Oa(s));let r=new Set;for(let s=0;s+1<t.length;s++)!Ia(t[s])&&!Ia(t[s+1])&&r.add(`${t[s]}-${t[s+1]}`);let i=Wx(e.summary);for(let s of i.compounds)e.summary.toLowerCase().replace(/_/g,"-").includes(s)&&r.add(s);return{convention:e,keyWords:n,keyCompounds:r,summaryWords:i.words}}function Vx(e,t,n=3,r=[]){if(t.length===0)return[];let i=new Set([...r].map(p=>Oa(p.toLowerCase()))),s=t.map(MF),a=new Map,c=new Map;for(let p of s){let h=new Set([...p.keyWords,...p.keyCompounds]);for(let g of h)a.set(g,(a.get(g)??0)+1);for(let g of new Set([...h,...p.summaryWords]))c.set(g,(c.get(g)??0)+1)}let l=s.length,d=o(p=>Math.log(1+l/(c.get(p)??l)),"idf"),u=Wx(DF(e));for(let p of i)u.words.delete(p);let f=[];for(let p of s){let h=new Set;for(let k of u.words)p.keyWords.has(k)&&h.add(k);for(let k of u.compounds)p.keyCompounds.has(k)&&h.add(k);let g=new Set;for(let k of u.words)!h.has(k)&&p.summaryWords.has(k)&&g.add(k);if(h.size===0&&g.size===0)continue;let y=0;for(let k of h)y+=2*d(k);for(let k of g)y+=d(k);let b=[...h].some(k=>(a.get(k)??0)!==1?!1:/[.-]/.test(k)?k.length>=5:k.length>=6),w=h.size>=1&&h.size+g.size>=2&&y>=$F;!b&&!w||f.push({convention:p.convention,score:y,matched:[...h,...g]})}return f.sort((p,h)=>h.score-p.score||p.convention.id.localeCompare(h.convention.id)).slice(0,n)}function jF(e){return e.split(".").some(t=>/[a-z][A-Z]/.test(t)||/[A-Za-z0-9]_[A-Za-z0-9]/.test(t))}function zx(e,t=6){let n=e.slice(0,8e3).replace(/https?:\/\/\S+/g," "),r=[],i=new Set,s=o((c,l)=>{if(r.length>=t)return;let d=c.endsWith("()"),u=d?c.slice(0,-2):c;if(u.includes("/")||LF.test(u)||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(u)||!l&&!d&&!jF(u))return;let f=u.split("."),p=f[f.length-1];p.length<(l||d?3:4)||FF.has(p.toLowerCase())||i.has(p)||(i.add(p),r.push({name:p,qualifier:f.length>1?f[f.length-2]:null}))},"consider");for(let c of n.matchAll(/`([^`\n]{1,120})`/g))s(c[1].trim(),!0);let a=n.replace(/`[^`\n]{1,120}`/g," ");for(let c of a.matchAll(/(?<![\w$./\\-])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)(?![\w$/\\-])/g))s(c[1],!1);return r}function yf(e,t){let n=e.replace(/\s+/g," ").replace(/`/g,"'").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Yx(e,t=2e3){let n=e.conventions,r=e.symbols.filter(d=>d.locations.length>0);if(n.length===0&&r.length===0)return null;let i=new Na(t-qx);if(!i.tryAdd(`${RF} Looked up on this machine for this prompt; the prompt was not uploaded.`))return null;let s=[],a=[],c=!1;if(n.length>0&&i.tryAdd("Project conventions whose terms appear in this prompt (full text: get_conventions({id})):"))for(let d of n){let u=`- ${d.convention.id} (v${d.convention.version}): ${yf(d.convention.summary,320)}`;if(!i.tryAdd(u)){c=!0;break}s.push(d.convention.id)}if(r.length>0&&!c){let d=e.repoRoot?` in ${e.repoRoot}`:"";if(i.tryAdd(`Symbols this prompt names, as the local code index places them${d} (files unchanged since indexing):`))for(let u of r){let f=u.locations.slice(0,3),p=f.map(y=>{let b=y.qualifiedName===u.candidate.name?y.kind:`${y.kind} ${y.qualifiedName}`;return`${y.filePath}:${y.startLine} (${b})${y.signature?` '${yf(y.signature,70)}'`:""}`}).join("; "),h=u.total-f.length,g=`- ${u.candidate.name} \u2192 ${p}${h>0?` (+${h} more \u2014 codebase_search)`:""}`;if(!i.tryAdd(g)){c=!0;break}a.push(u.candidate.name)}}if(s.length===0&&a.length===0)return null;let l=i.toString();return c&&(l+=`
940
+ (trimmed to the hook budget \u2014 get_conventions / codebase_search have the rest)`),{text:l,conventionIds:s,symbolNames:a}}function HF(e,t){return e!==null&&(e.limit!==void 0||e.offset!==void 0&&e.offset>1)?!0:t>UF}function BF(e){if(e.length===0)return"";let t=e.map(i=>i.split("/").slice(0,-1)),n=t[0],r=0;for(;r<n.length&&t.every(i=>i[r]===n[r]);)r++;return r===0?"":`${n.slice(0,r).join("/")}/`}function GF(e,t){let n=e.filePath.slice(t.length);return e.kind==="module"?`${n} (module level)`:`${e.qualifiedName} (${n}:${e.startLine})`}function Jx(e,t=1500){let n=new Map;for(let g of e.callers){let y=n.get(g.calleeKey)??[];y.some(b=>b.caller.nodeKey===g.caller.nodeKey)||y.push(g),n.set(g.calleeKey,y)}let r=o(g=>new Set((n.get(g)??[]).map(y=>y.caller.filePath)).size,"fileCount"),i=e.symbols.filter(g=>n.has(g.nodeKey)).sort((g,y)=>r(y.nodeKey)-r(g.nodeKey)||g.startLine-y.startLine),s=e.symbols.reduce((g,y)=>Math.max(g,y.endLine),0),a=e.symbols.filter(g=>!g.qualifiedName.includes(".")&&g.kind!=="module"),c=HF(e.range,s)&&a.length>0;if(i.length===0&&e.importers.length===0&&!c)return null;let l=BF([e.relPath,...e.callers.map(g=>g.caller.filePath),...e.importers]),d=new Na(t-qx),u=l?` Paths below are relative to ${l}.`:"";if(!d.tryAdd(`${CF} ${e.relPath} as the local code index knows it (the index matches this file on disk).${u}`))return null;let f=!1;if(c&&d.tryAdd("Outline of the whole file (start lines; this Read shows only part of it):")){let g="",y=0;for(let w of a){let k=`${w.qualifiedName} L${w.startLine}`,S=g.length===0?k:`${g} \xB7 ${k}`;if(S.length>500)break;g=S,y++}let b=a.length-y;d.tryAdd(b>0?`${g} \xB7 +${b} more`:g)||(f=!0)}if(i.length>0&&!f&&d.tryAdd("Called from other files (import-resolved call graph):"))for(let g of i){let y=n.get(g.nodeKey)??[],b=y.slice(0,3).map(x=>`${GF(x.caller,l)}${x.kind==="calls"?"":` [${x.kind}]`}`),w=y.length-b.length,k=g.signature?` '${yf(g.signature,80)}'`:"",S=`- ${g.qualifiedName} L${g.startLine}${k} \u2190 ${b.join(", ")}${w>0?` +${w} more`:""}`;if(!d.tryAdd(S)){f=!0;break}}if(e.importers.length>0&&!f){let g=e.importers.slice(0,5).map(k=>k.slice(l.length)),y=e.importers.length-g.length,b=e.importers.length,w=`Imported by ${b} file${b===1?"":"s"}: ${g.join(", ")}${y>0?` +${y} more`:""}`;d.tryAdd(w)||(f=!0)}e.hidden>0&&!f&&d.tryAdd(`(${e.hidden} more reference${e.hidden===1?"":"s"} sit in files changed since the last index run \u2014 not listed.)`);let p=e.unchecked??0;if(p>0&&!f&&d.tryAdd(`(+${p} more reference${p===1?"":"s"} not checked here \u2014 codebase_trace lists them.)`),d.size<=1)return null;let h=d.toString();return f&&(h+=`
941
+ (trimmed to the hook budget \u2014 codebase_trace has the full graph)`),h}var RF,CF,Bx,Gx,OF,PF,$F,LF,FF,Na,qx,UF,Xx=_(()=>{"use strict";RF="[maind context \xB7 prompt]",CF="[maind context \xB7 read]",Bx=new Set("a an the and or but if then else when while of to in on at by for with from into onto over under about as is are was were be been being it its this that these those there here we you i me my our your they them their he she his her not no yes do does did done can could should would will shall may might must have has had so too very just also only all any some each every more most less than what which who whom whose why how where please let lets make made use used uses using get got new now one two via per etc out up down off again before after first last next previous other same different main default good bad right wrong both much many few own still even ever never always add added adding build builds built change changes changed check checks checked create created fix fixed fixes update updated updates write writes written read reads run runs running start started stop set show find look need needs want work works working try keep move put give take call called see know think tell say ask help mean like sure ok okay thing things stuff way part step steps case cases time today explicit implicit user users agent agents file files code line lines value values name names list type types data text rule rules policy pattern patterns anti convention conventions maind claude project projects repo repository branch branches feature features task tasks issue issues problem error errors bug bugs test tests verify version versions thanks thank gate gates content note notes org block apply applies render renders object objects title titles comment comments description local remote script scripts sync kind strategy request alternative better open close merge merged action reason lesson lessons word words der die das den dem des ein eine einen einem einer eines und oder aber wenn dann sonst als wie was wer wo warum weil dass ist sind war waren sein bin bist hat haben hatte wird werden wurde kann k\xF6nnen koennen k\xF6nnte soll sollen sollte muss m\xFCssen muessen darf nicht kein keine nur auch noch schon mal bitte ich du er sie es wir ihr mich mir dich dir uns euch ihnen sich mit ohne f\xFCr fuer auf aus bei nach vor \xFCber ueber unter zum zur im am um an in von zu bis durch gegen hier da dort jetzt ja nein doch also man dies diese dieser dieses mach mache machen lass lasst gib geht gehen gut schreib schreibe schreiben bau baue bauen pr\xFCf pr\xFCfe pr\xFCfen pruefen lies lesen starte starten teste testen nutze nutzen brauch brauchen datei dateien zeile zeilen neue neuen neu alte alten erst gleich kurz einfach richtig falsch danke".split(/\s+/)),Gx=new Set(["anti-pattern","non-trivial","one-line","e.g","i.e","e-g","i-e"]);o(Oa,"stem");o(Ia,"isNoise");o(IF,"splitParts");o(NF,"normalizeCompound");OF=/[\p{L}\p{N}]+(?:[._-][\p{L}\p{N}]+)*/gu;o(Wx,"termsOf");o(DF,"promptForMatching");o(Kx,"repoNameWords");PF=/^- \[([a-z]+)\/([a-z0-9][a-z0-9-]*) v(\d+)(?:,[^\]]*)?\]\s+(.+)$/;o(_f,"parseConventionLines");o(MF,"profileOf");$F=4.5;o(Vx,"matchConventions");LF=/\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts|py|pyi|md|mdx|json|jsonc|ya?ml|toml|sql|css|scss|html|sh|txt|lock|env|log|png|svg|jpe?g|gif|pdf)$/i,FF=new Set(["JavaScript","TypeScript","GitHub","GitLab","PostgreSQL","MySQL","SQLite","NodeJS","NextJS","macOS","iOS","iPhone","iPad","iCloud","OpenAI","YouTube","LinkedIn","PowerShell","VSCode","WebSocket","OAuth","PostHog","DevTools","ChatGPT","DeepSeek","OpenVSX","AgentComposer","ClaudeCode","McpServer","README","TODO","FIXME"].map(e=>e.toLowerCase()));o(jF,"looksLikeCode");o(zx,"extractSymbolCandidates");o(yf,"clip");Na=class{constructor(t){this.budget=t}static{o(this,"Budgeted")}lines=[];used=0;tryAdd(t){let n=t.length+(this.lines.length>0?1:0);return this.used+n>this.budget?!1:(this.lines.push(t),this.used+=n,!0)}get size(){return this.lines.length}toString(){return this.lines.join(`
942
+ `)}},qx=90;o(Yx,"renderPromptContext");UF=2e3;o(HF,"isPartialRead");o(BF,"commonDir");o(GF,"callerLabel");o(Jx,"renderReadContext")});import{createHash as WF}from"node:crypto";import{existsSync as Zx,mkdirSync as KF,readdirSync as VF,rmSync as zF,statSync as qF,writeFileSync as YF}from"node:fs";import{join as Da}from"node:path";function bf(e){return e.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,100)}function ZF(e,t,n=null,r=XF){try{for(let i of VF(e)){let s=Da(e,i);if(s!==n)try{t-qF(s).mtimeMs>r&&zF(s,{recursive:!0,force:!0})}catch{}}}catch{}}var JF,XF,Zi,Qx=_(()=>{"use strict";He();JF=Da(Ue,"context"),XF=7*24*60*60*1e3;o(bf,"safe");Zi=class e{constructor(t,n){this.root=t;this.dir=n}static{o(this,"SeenMarks")}static forScope(t,n,r=JF){let i=n?`${bf(t)}__${bf(n)}`:bf(t);return new e(r,Da(r,i))}fileFor(t){return Da(this.dir,WF("sha256").update(t).digest("hex").slice(0,32))}has(t){try{return Zx(this.fileFor(t))}catch{return!1}}mark(t,n=Date.now()){if(t.length!==0)try{Zx(this.dir)||(KF(this.dir,{recursive:!0,mode:448}),ZF(this.root,n,this.dir));for(let r of t)try{YF(this.fileFor(r),"",{flag:"wx",mode:384})}catch{}}catch{}}};o(ZF,"sweepStaleScopes")});var kf={};ee(kf,{INDEX_RELPATH:()=>Lt,SOFT_BUDGET_MS:()=>nS,findRepoRoot:()=>Ft,isMachinePrompt:()=>oS,loadCachedConventions:()=>iS,promptContextFor:()=>cS,promptTextOf:()=>sS,readContextFor:()=>lS,runOnPromptContext:()=>aj,runOnReadContext:()=>lj});import{existsSync as eS,readFileSync as QF,realpathSync as ej,statSync as tj}from"node:fs";import{dirname as nj,isAbsolute as tS,join as Qi,relative as rj,sep as ij}from"node:path";function sj(e,t){let n=rj(e,t);return!n||n.startsWith("..")||tS(n)?null:n.split(ij).join("/")}function vf(e){try{let t=tj(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return null}}async function rS(e){let{openIndexReader:t}=await Promise.resolve().then(()=>(No(),Id));return t(e)}function iS(e,t={}){try{let n=t.identity===void 0?qi():t.identity;if(e!==null&&n!==null){let r=Js(e,n),i=Fo(r?.result.instructions??null),s=_f(i);if(s.length>0)return s}}catch{}try{let n=JSON.parse(QF(t.briefingCacheFile??Er,"utf8"));if(typeof n.conventions=="string")return _f(n.conventions)}catch{}return[]}function sS(e){return typeof e.prompt=="string"?e.prompt:typeof e.user_input=="string"?e.user_input:""}function oS(e,t){if(e.is_command===!0)return!0;let n=t.trimStart();return/^\/[A-Za-z][\w:-]*(\s|$)/.test(n)||/^<[a-z][\w-]*[\s>]/.test(n)||n.startsWith("This session is being continued from a previous conversation")}function aS(e){let t=typeof e.session_id=="string"?e.session_id.trim():"";if(!t)return null;let n=typeof e.agent_id=="string"&&e.agent_id.trim()?e.agent_id.trim():null;return{sessionId:t,agentId:n}}async function oj(e,t,n,r){let i;try{i=await r(n)}catch{return[]}try{if(!i.meta().schemaCurrent)return[];let s=i.symbolsNamed(e.map(d=>d.name)),a=i.files([...s.values()].flat().map(d=>d.filePath).slice(0,wf)),c=new Set;for(let[d,u]of a){let f=vf(Qi(t,d));f!==null&&mi(u,f)&&c.add(d)}let l=[];for(let d of e){let u=s.get(d.name)??[],f=d.qualifier===null?[]:u.filter(g=>g.qualifiedName===`${d.qualifier}.${d.name}`),p=f.length>0?f:u,h=p.filter(g=>c.has(g.filePath)).map(g=>({kind:g.kind,qualifiedName:g.qualifiedName,filePath:g.filePath,startLine:g.startLine,signature:g.signature}));h.length>0&&l.push({candidate:d,locations:h,total:p.length})}return l}catch{return[]}finally{try{i.close()}catch{}}}async function cS(e,t={}){let n=t.now??Date.now,r=n();if(Ri(e,t.env??process.env))return null;let i=sS(e);if(i.trim().length===0||oS(e,i))return null;let s=aS(e);if(s===null)return null;let a=Zi.forScope(s.sessionId,s.agentId,t.seenRoot),c=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),l=Ft(c),d=Vx(i,(t.loadConventions??iS)(l),6,Kx(l)).filter(y=>!a.has(`conv:${y.convention.id}@${y.convention.version}`)).slice(0,3),u=zx(i).filter(y=>!a.has(`sym:${l??""}:${y.name}`)),f=l===null?null:Qi(l,Lt),p=u.length>0&&f!==null&&l!==null&&eS(f)&&n()-r<nS?await oj(u,l,f,t.openReader??rS):[],h=Yx({repoRoot:l,conventions:d,symbols:p});if(h===null)return null;let g=new Map(d.map(y=>[y.convention.id,y.convention.version]));return a.mark([...h.conventionIds.map(y=>`conv:${y}@${g.get(y)??0}`),...h.symbolNames.map(y=>`sym:${l??""}:${y}`)],n()),h.text}async function aj(){try{let e=await cS(await W());e!==null&&process.stdout.write(Bv(e))}catch{}return 0}function cj(e){let t=e.tool_input;if(t===null||typeof t!="object")return null;let n=t,r=typeof n.offset=="number"&&Number.isFinite(n.offset)?n.offset:void 0,i=typeof n.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0;return r===void 0&&i===void 0?null:{offset:r,limit:i}}async function lS(e,t={}){let n=t.now??Date.now;if((e.tool_name??"")!=="Read"||Ri(e,t.env??process.env))return null;let r=Ne(e);if(!r||tr(r)===null||Xr(r))return null;let i=aS(e);if(i===null)return null;let s=typeof e.cwd=="string"&&e.cwd.length>0?e.cwd:process.cwd(),a=tS(r)?r:Qi(s,r),c;try{c=ej(a)}catch{return null}let l=Ft(nj(c));if(l===null)return null;let d=Qi(l,Lt);if(!eS(d))return null;let u=sj(l,c);if(u===null)return null;let f=await(t.openReader??rS)(d);try{let p=f.meta();if(!p.schemaCurrent)return null;let h=f.file(u);if(h===null)return null;let g=vf(c);if(g===null||!mi(h,g))return null;let y=Zi.forScope(i.sessionId,i.agentId,t.seenRoot),b=`read:${l}:${u}@${h.contentHash}`;if(y.has(b))return null;let w=f.symbolsInFile(u),k=p.edgesDirty?[]:f.callersOfFile(u),S=p.edgesDirty?[]:f.importersOf(u),x=[...new Set([...k.map(q=>q.caller.filePath),...S])],v=x.slice(0,wf),E=new Set(x.slice(wf)),N=f.files(v),F=new Set;for(let q of v){let be=N.get(q),Hn=be===void 0?null:vf(Qi(l,q));be!==void 0&&Hn!==null&&mi(be,Hn)&&F.add(q)}let H=o(q=>k.filter(be=>q.has(be.caller.filePath)).length+S.filter(be=>q.has(be)).length,"countIn"),P=k.filter(q=>F.has(q.caller.filePath)).map(q=>({calleeKey:q.calleeKey,kind:q.kind,caller:{nodeKey:q.caller.nodeKey,kind:q.caller.kind,qualifiedName:q.caller.qualifiedName,filePath:q.caller.filePath,startLine:q.caller.startLine}})),L=S.filter(q=>F.has(q)),G=H(E),yt=k.length-P.length+(S.length-L.length)-G,jr=Jx({relPath:u,symbols:w,callers:P,importers:L,hidden:yt,unchecked:G,range:cj(e)});return jr===null?null:(y.mark([b],n()),jr)}finally{f.close()}}async function lj(){try{let e=await lS(await W());e!==null&&process.stdout.write(Oe(e))}catch{}return 0}var nS,wf,xf=_(()=>{"use strict";It();Dd();Tr();Fr();Nt();Xx();Qx();yo();ge();Wt();nS=200,wf=200;o(sj,"repoRelative");o(vf,"diskStat");o(rS,"openReader");o(iS,"loadCachedConventions");o(sS,"promptTextOf");o(oS,"isMachinePrompt");o(aS,"scopeOf");o(oj,"locateSymbols");o(cS,"promptContextFor");o(aj,"runOnPromptContext");o(cj,"readRangeOf");o(lS,"readContextFor");o(lj,"runOnReadContext")});import{randomUUID as dj}from"node:crypto";Ur();import{createInterface as YR}from"node:readline";var ES=[["claude-code","claude-code"],["claude-cli","claude-code"],["claude-desktop","claude-desktop"],["claude.app","claude-desktop"],["openai-codex","codex"],["codex-cli","codex"],["codex","codex"],["github-copilot","copilot"],["vscode-copilot","copilot"],["copilot","copilot"],["cursor","cursor"],["windsurf","windsurf"],["codeium","windsurf"],["cline","cline"],["continue","continue"],["vscode-extension","vscode-extension"],["maind-vscode","vscode-extension"],["mcp-inspector","mcp-inspector"],["maind-cli","maind-cli"],["maind-mcp-bridge","mcp-bridge"]];function TS(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();if(t.length===0)return null;for(let[n,r]of ES)if(t.includes(n))return r;return null}o(TS,"mapClientInfoNameToFamily");function Nf(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ma(t)||t.method!=="initialize")return null;let n=t.params;if(!Ma(n))return null;let r=n.clientInfo;if(!Ma(r))return null;let i=r.name,s=TS(typeof i=="string"?i:null);if(s===null)return null;let a=r.version,c=typeof a=="string"&&a.length>0?a.slice(0,64):null;return{family:s,version:c}}o(Nf,"tryExtractInitializeClient");function Ma(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(Ma,"isRecord");ja();Ua();function Ha(e){let t=e.trim();if(t.length===0)return[];if(t.startsWith("{")||t.startsWith("["))try{let s=JSON.parse(t);return Array.isArray(s)?s:[s]}catch{return[]}let n=[],r=[],i=o(()=>{if(r.length===0)return;let s=r.join(`
943
943
  `).trim();if(r=[],s.length!==0)try{n.push(JSON.parse(s))}catch{}},"flush");for(let s of t.split(`
944
- `)){let a=s.endsWith("\r")?s.slice(0,-1):s;if(a===""){i();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return i(),n}o(Pa,"rpcMessagesOf");function Rp(e,t){for(let n of Pa(e)){if(typeof n!="object"||n===null)continue;let r=n;if(r.id!==t)continue;if(typeof r.error=="object"&&r.error!==null){let c=r.error;return{kind:"rpc_error",code:typeof c.code=="number"?c.code:-32603,message:typeof c.message=="string"?c.message:""}}let i=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(i.content)?i.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:i.isError===!0,text:a?.text??""}}return null}o(Rp,"parseCloudToolResponse");Nt();var DR="https://mcp.maind.dev/mcp",hi=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{o(this,"BridgeReauthNeeded")}},qs=class{static{o(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;onSessionReady;assignedInbox;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=lr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=PR(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=MR(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.onConnectionOutcome=t.onConnectionOutcome??null,this.onSessionReady=t.onSessionReady??null,this.assignedInbox=t.assignedInbox??null;let s=t.carry??null;s!==null&&(this.initFrame=s.initFrame,this.clientFamily===null&&(this.clientFamily=s.clientFamily),this.clientVersion===null&&(this.clientVersion=s.clientVersion),this.replayFrame=s.pendingFrame),this.shaRepoRoot=es(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??DR}async run(t=Hl()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r)return;let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=vp(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&mi(t)&&(this.initFrame=t);let r=FR(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=ts(t,this.shaRepoRoot);if(u.length>0){let p=u.find(h=>h.verdict==="fabricated"),f=p??u[0];if(p!==void 0&&Tp(p)&&r.id!==null){let h=Bn(p,!0);process.stderr.write(`[maind] ${h}
945
- `);let g=r.params?.name;process.stdout.write(Hn(r.id,typeof g=="string"?g:"unknown",h)+`
946
- `);return}i=Bn(f,!1),process.stderr.write(`[maind] ${i}
947
- `)}if(this.assignedInbox&&!wp(this.clientFamily)){let p=this.assignedInbox.takeNote();p!==null&&(i=i===null?p:`${i}
948
- [maind] ${p}`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let u=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(u+`
949
- `);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!mi(t)&&await this.recoverSession();let a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(u){let p=Vs(t);if(this.serveInitializeFromCache(t,p))return;zs(p,-32603,`bridge network error: ${gy(u)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!mi(t)){let u=await c.text().catch(()=>"");if(hy(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let p=Vs(t);zs(p,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Vs(t),p=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;zs(u,-32603,`bridge upstream error (HTTP ${c.status}): ${p.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(s&&this.localRouter){let u=d.startsWith("text/event-stream")?await jl(c):await c.text(),p=this.localRouter.augmentToolsList(u);p.trim().length>0&&process.stdout.write(p+`
950
- `);return}if(mi(t)){let u=d.startsWith("text/event-stream")?await jl(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
951
- `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await jl(c):await c.text(),p=LR(u,i);p.trim().length>0&&process.stdout.write(p+`
952
- `);return}if(d.startsWith("text/event-stream"))await $R(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
953
- `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new hi(UR(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=Vs(n);zs(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return HR(s)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,s=await this.postCloudToolCall(t,n,i);if(s.kind!=="session_lost")return s;if(!await this.recoverSession())return{kind:"http_error",status:404,body:s.body.slice(0,500)};let a=await this.postCloudToolCall(t,n,i);return a.kind==="session_lost"?{kind:"http_error",status:404,body:a.body.slice(0,500)}:a}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,s=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let a=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:s,signal:AbortSignal.timeout(r)}),c=a.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await a.text();return a.status===404&&hy(l)?{kind:"session_lost",body:l}:a.ok?Rp(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:a.status,body:l.slice(0,500)}}catch(a){return{kind:"transport_error",message:gy(a),timedOut:jR(a)}}}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=dt()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&fy(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!mi(t))return!1;let r=Ks(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(my(n,r)+`
954
- `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${Ws(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function Hl(){return OR({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}o(Hl,"stdinLines");function PR(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","cline","continue","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}o(PR,"normalizeClientFamily");function MR(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}o(MR,"normalizeClientVersion");async function $R(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=o(()=>{if(i.length===0)return;let a=i.join(`
944
+ `)){let a=s.endsWith("\r")?s.slice(0,-1):s;if(a===""){i();continue}a.startsWith("data:")&&r.push(a.slice(5).replace(/^\s/,""))}return i(),n}o(Ha,"rpcMessagesOf");function Ff(e,t){for(let n of Ha(e)){if(typeof n!="object"||n===null)continue;let r=n;if(r.id!==t)continue;if(typeof r.error=="object"&&r.error!==null){let c=r.error;return{kind:"rpc_error",code:typeof c.code=="number"?c.code:-32603,message:typeof c.message=="string"?c.message:""}}let i=typeof r.result=="object"&&r.result!==null?r.result:{},a=(Array.isArray(i.content)?i.content:[]).find(c=>typeof c=="object"&&c!==null&&c.type==="text"&&typeof c.text=="string");return{kind:"result",isError:i.isError===!0,text:a?.text??""}}return null}o(Ff,"parseCloudToolResponse");Nt();var JR="https://mcp.maind.dev/mcp",gi=class extends Error{constructor(n){super(`re-authorization required: ${n}`);this.reason=n;this.name="BridgeReauthNeeded"}static{o(this,"BridgeReauthNeeded")}},Qs=class{static{o(this,"Forwarder")}mcpUrl;apiKey;deviceId;bridgeVersion;clientFamily;clientVersion;clientFamilyLocked;clientVersionLocked;projectKey;localRouter;presence;onConnectionOutcome;onSessionReady;assignedInbox;connectionOkRecorded=!1;presenceFrameId=0;cloudFrameId=0;sessionId=null;shaRepoRoot;initFrame=null;pendingFrame=null;replayFrame=null;terminated=!1;keyFp;repoRoot=null;constructor(t){this.apiKey=t.apiKey,this.keyFp=dr(t.apiKey),this.deviceId=t.deviceId,this.bridgeVersion=t.bridgeVersion;let n=t.clientFamily??process.env.MAIND_CLIENT_FAMILY??null;this.clientFamily=XR(n),this.clientFamilyLocked=this.clientFamily!==null;let r=t.clientVersion??process.env.MAIND_CLIENT_VERSION??null;this.clientVersion=ZR(r),this.clientVersionLocked=this.clientVersion!==null;let i=(t.projectKey??null)?.trim().toLowerCase()??null;this.projectKey=i&&/^[a-f0-9]{64}$/.test(i)?i:null,this.localRouter=t.localRouter??null,this.presence=t.presence??null,this.onConnectionOutcome=t.onConnectionOutcome??null,this.onSessionReady=t.onSessionReady??null,this.assignedInbox=t.assignedInbox??null;let s=t.carry??null;s!==null&&(this.initFrame=s.initFrame,this.clientFamily===null&&(this.clientFamily=s.clientFamily),this.clientVersion===null&&(this.clientVersion=s.clientVersion),this.replayFrame=s.pendingFrame),this.shaRepoRoot=ss(),this.mcpUrl=t.mcpUrl??process.env.MAIND_MCP_URL??JR}async run(t=ql()){if(this.replayFrame!==null){let n=this.replayFrame;this.replayFrame=null,await this.forwardFrame(n)}for(;;){if(this.terminated)return;let{value:n,done:r}=await t.next();if(r)return;let i=n.trim();i.length!==0&&await this.forwardFrame(i)}}carryOver(){return{initFrame:this.initFrame,clientFamily:this.clientFamily,clientVersion:this.clientVersion,pendingFrame:this.pendingFrame}}async forwardFrame(t,n=!1){if(!this.clientFamilyLocked&&this.clientFamily===null){let u=Nf(t);u!==null&&(this.clientFamily=u.family,!this.clientVersionLocked&&this.clientVersion===null&&(this.clientVersion=u.version))}this.initFrame===null&&hi(t)&&(this.initFrame=t);let r=tC(t),i=null;if(r?.method==="tools/call"){this.presence?.onActivity();let u=os(t,this.shaRepoRoot);if(u.length>0){let f=u.find(h=>h.verdict==="fabricated"),p=f??u[0];if(f!==void 0&&$f(f)&&r.id!==null){let h=Gn(f,!0);process.stderr.write(`[maind] ${h}
945
+ `);let g=r.params?.name;process.stdout.write(Bn(r.id,typeof g=="string"?g:"unknown",h)+`
946
+ `);return}i=Gn(p,!1),process.stderr.write(`[maind] ${i}
947
+ `)}if(this.assignedInbox&&!If(this.clientFamily)){let f=this.assignedInbox.takeNote();f!==null&&(i=i===null?f:`${i}
948
+ [maind] ${f}`)}}if(this.localRouter&&this.localRouter.handlesToolCall(r?.method,r?.params)){let u=await this.localRouter.handleToolCall(r?.id??null,r?.params);process.stdout.write(u+`
949
+ `);return}let s=this.localRouter!==null&&r?.method==="tools/list";this.sessionId===null&&this.initFrame!==null&&!n&&!hi(t)&&await this.recoverSession();let a=this.buildHeaders(!0),c;try{c=await fetch(this.mcpUrl,{method:"POST",headers:a,body:t})}catch(u){let f=Xs(t);if(this.serveInitializeFromCache(t,f))return;Zs(f,-32603,`bridge network error: ${Ey(u)}`);return}let l=c.headers.get("mcp-session-id");if(l&&l!==this.sessionId&&(this.sessionId=l),c.status===401){await this.handle401(c,t);return}if(c.ok&&!this.connectionOkRecorded&&(this.connectionOkRecorded=!0,this.recordOutcome("ok",null)),c.status===404&&!n&&this.initFrame!==null&&this.sessionId!==null&&!hi(t)){let u=await c.text().catch(()=>"");if(Sy(u)&&await this.recoverSession()){await this.forwardFrame(t,!0);return}let f=Xs(t);Zs(f,-32603,`bridge upstream error (HTTP 404): ${u.slice(0,500)}`);return}if(!c.ok){let u=Xs(t),f=await c.text().catch(()=>"");if(this.serveInitializeFromCache(t,u))return;Zs(u,-32603,`bridge upstream error (HTTP ${c.status}): ${f.slice(0,500)}`);return}let d=c.headers.get("content-type")??"";if(s&&this.localRouter){let u=d.startsWith("text/event-stream")?await Vl(c):await c.text(),f=this.localRouter.augmentToolsList(u);f.trim().length>0&&process.stdout.write(f+`
950
+ `);return}if(hi(t)){let u=d.startsWith("text/event-stream")?await Vl(c):await c.text();this.cacheInitializeResult(u),this.presence?.onSessionReady(),u.trim().length>0&&process.stdout.write(u+`
951
+ `);try{this.onSessionReady?.({clientFamily:this.clientFamily})}catch{}return}if(i!==null){let u=d.startsWith("text/event-stream")?await Vl(c):await c.text(),f=eC(u,i);f.trim().length>0&&process.stdout.write(f+`
952
+ `);return}if(d.startsWith("text/event-stream"))await QR(c);else{if(c.status===202)return;{let u=await c.text();u.trim().length>0&&process.stdout.write(u+`
953
+ `)}}}async handle401(t,n){let r=await t.text().catch(()=>""),i=r.toLowerCase();if(i.includes("device_mismatch")||i.includes("device_revoked")||i.includes("device_required")||i.includes("invalid or revoked"))throw this.terminated=!0,this.pendingFrame=n,new gi(rC(i));this.connectionOkRecorded=!1,this.recordOutcome("auth_failed",r.slice(0,200));let a=Xs(n);Zs(a,-32001,`bridge auth error: ${r.slice(0,200)}`)}recordOutcome(t,n){try{this.onConnectionOutcome?.(t,n)}catch{}}async postPresenceToolCall(t,n){if(this.sessionId===null)throw new Error("presence: no MCP session established yet");this.presenceFrameId+=1;let r=JSON.stringify({jsonrpc:"2.0",id:`maind-presence-${this.presenceFrameId}`,method:"tools/call",params:{name:t,arguments:n}}),i=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:r}),s=await i.text().catch(()=>"");if(!i.ok)throw new Error(`presence: upstream HTTP ${i.status}`);return iC(s)}async callCloudTool(t,n,r={}){if(this.sessionId===null&&!await this.recoverSession())return{kind:"no_session"};let i=r.timeoutMs??9e4,s=await this.postCloudToolCall(t,n,i);if(s.kind!=="session_lost")return s;if(!await this.recoverSession())return{kind:"http_error",status:404,body:s.body.slice(0,500)};let a=await this.postCloudToolCall(t,n,i);return a.kind==="session_lost"?{kind:"http_error",status:404,body:a.body.slice(0,500)}:a}async postCloudToolCall(t,n,r){this.cloudFrameId+=1;let i=`maind-bridge-${this.cloudFrameId}`,s=JSON.stringify({jsonrpc:"2.0",id:i,method:"tools/call",params:{name:t,arguments:n}});try{let a=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:s,signal:AbortSignal.timeout(r)}),c=a.headers.get("mcp-session-id");c&&c!==this.sessionId&&(this.sessionId=c);let l=await a.text();return a.status===404&&Sy(l)?{kind:"session_lost",body:l}:a.ok?Ff(l,i)??{kind:"transport_error",message:`the response carried no answer to ${i}: ${l.slice(0,200)}`,timedOut:!1}:{kind:"http_error",status:a.status,body:l.slice(0,500)}}catch(a){return{kind:"transport_error",message:Ey(a),timedOut:nC(a)}}}buildHeaders(t){let n={"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${this.apiKey}`,"x-maind-device-id":this.deviceId,"x-maind-bridge-version":this.bridgeVersion};return this.clientFamily!==null&&(n["x-maind-client-family"]=this.clientFamily),this.clientVersion!==null&&(n["x-maind-client-version"]=this.clientVersion),this.projectKey!==null&&(n["x-maind-project-key"]=this.projectKey),t&&this.sessionId!==null&&(n["mcp-session-id"]=this.sessionId),n}async recoverSession(){if(this.initFrame===null)return!1;this.sessionId=null;let t;try{t=await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!1),body:this.initFrame})}catch{return!1}let n=t.headers.get("mcp-session-id");if(await t.text().catch(()=>""),!t.ok||!n)return!1;this.sessionId=n;try{await(await fetch(this.mcpUrl,{method:"POST",headers:this.buildHeaders(!0),body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})})).text().catch(()=>"")}catch{}return!0}getRepoRoot(){return this.repoRoot===null&&(this.repoRoot=ut()),this.repoRoot}cacheInitializeResult(t){try{let n=JSON.parse(t);n&&n.result&&ky(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp},n.result)}catch{}}serveInitializeFromCache(t,n){if(!hi(t))return!1;let r=Js(this.getRepoRoot(),{mcpUrl:this.mcpUrl,keyFp:this.keyFp});return r===null?!1:(process.stdout.write(xy(n,r)+`
954
+ `),console.error(`[maind-bridge] MCP server unreachable \u2014 served cached conventions from ${Ys(this.getRepoRoot())} (snapshot ${r.cached_at})`),!0)}};function ql(){return YR({input:process.stdin,crlfDelay:1/0})[Symbol.asyncIterator]()}o(ql,"stdinLines");function XR(e){if(e===null)return null;let t=e.trim().toLowerCase();return t.length===0?null:new Set(["claude-code","codex","copilot","cursor","windsurf","cline","continue","mcp-bridge","vscode-extension","claude-desktop","mcp-inspector"]).has(t)?t:null}o(XR,"normalizeClientFamily");function ZR(e){if(e===null)return null;let t=e.trim();return t.length===0?null:t.slice(0,64)}o(ZR,"normalizeClientVersion");async function QR(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=o(()=>{if(i.length===0)return;let a=i.join(`
955
955
  `).trim();i=[],a.length>0&&process.stdout.write(a+`
956
956
  `)},"flushEvent");try{for(;;){let{value:a,done:c}=await t.read();if(c)break;r+=n.decode(a,{stream:!0});let l;for(;(l=r.indexOf(`
957
- `))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}o($R,"pipeSseToStdout");function LR(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}o(LR,"appendNoteToToolResult");function FR(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}o(FR,"parseRpc");async function jl(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],a=o(()=>{if(s.length===0)return;let c=s.join(`
957
+ `))!==-1;){let d=r.slice(0,l);r=r.slice(l+1);let u=d.endsWith("\r")?d.slice(0,-1):d;if(u===""){s();continue}u.startsWith(":")||u.startsWith("data:")&&i.push(u.slice(5).replace(/^\s/,""))}}}finally{s()}}o(QR,"pipeSseToStdout");function eC(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return e;let r=n.result;return typeof r!="object"||r===null||!Array.isArray(r.content)?e:(r.content.push({type:"text",text:`[maind] ${t}`}),JSON.stringify(n))}catch{return e}}o(eC,"appendNoteToToolResult");function tC(e){try{let t=JSON.parse(e);return{id:t.id??null,method:t.method,params:t.params}}catch{return null}}o(tC,"parseRpc");async function Vl(e){if(!e.body)return"";let t=e.body.getReader(),n=new TextDecoder,r="",i=[],s=[],a=o(()=>{if(s.length===0)return;let c=s.join(`
958
958
  `).trim();s=[],c.length>0&&i.push(c)},"flushEvent");try{for(;;){let{value:c,done:l}=await t.read();if(l)break;r+=n.decode(c,{stream:!0});let d;for(;(d=r.indexOf(`
959
- `))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let p=u.endsWith("\r")?u.slice(0,-1):u;if(p===""){a();continue}p.startsWith(":")||p.startsWith("data:")&&s.push(p.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
960
- `)}o(jl,"collectSseText");function Vs(e){try{return JSON.parse(e).id??null}catch{return null}}o(Vs,"tryExtractId");function mi(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}o(mi,"isInitializeRequest");function hy(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}o(hy,"isSessionLossBody");function gy(e){return e instanceof Error?e.message:String(e)}o(gy,"stringifyErr");function jR(e){return e?.name==="TimeoutError"}o(jR,"isTimeoutError");function zs(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
961
- `)}o(zs,"emitJsonRpcError");function UR(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}o(UR,"extractHint");function HR(e){try{let t=Pa(e);if(t.length===0)return null;let r=t[t.length-1]?.result?.content?.[0]?.text;return typeof r!="string"?null:JSON.parse(r)}catch{return null}}o(HR,"parsePresenceToolResult");ue();ue();ur();import{spawn as ZR}from"node:child_process";import{platform as QR}from"node:os";async function pr(e,t=process.stderr){let n=yi(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=Js(e),a=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:s})});if(!c.ok){let p=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${p}`)}let l=await c.json();await rC(l.verification_uri_complete).catch(()=>{}),nC(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await tC(u);let p=await eC(i,l.device_code).catch(f=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(f)}
962
- `),null));if(p){if(p.status==="approved")return _n(p.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${p.plan}). API key saved to ~/.config/maind/api-key
963
- `),{apiKey:p.api_key,plan:p.plan};if(p.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
964
- `),null;if(p.status==="expired"||p.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${p.status}
959
+ `))!==-1;){let u=r.slice(0,d);r=r.slice(d+1);let f=u.endsWith("\r")?u.slice(0,-1):u;if(f===""){a();continue}f.startsWith(":")||f.startsWith("data:")&&s.push(f.slice(5).replace(/^\s/,""))}}}finally{a()}return i.join(`
960
+ `)}o(Vl,"collectSseText");function Xs(e){try{return JSON.parse(e).id??null}catch{return null}}o(Xs,"tryExtractId");function hi(e){try{return JSON.parse(e).method==="initialize"}catch{return!1}}o(hi,"isInitializeRequest");function Sy(e){let t=e.toLowerCase();return t.includes("session not found")||t.includes("session expired")||t.includes("no valid session")||t.includes("reinitialize")||t.includes("session")&&t.includes("expired")}o(Sy,"isSessionLossBody");function Ey(e){return e instanceof Error?e.message:String(e)}o(Ey,"stringifyErr");function nC(e){return e?.name==="TimeoutError"}o(nC,"isTimeoutError");function Zs(e,t,n){let r={jsonrpc:"2.0",id:e,error:{code:t,message:n}};process.stdout.write(JSON.stringify(r)+`
961
+ `)}o(Zs,"emitJsonRpcError");function rC(e){return e.includes("device_mismatch")?"device_mismatch":e.includes("device_revoked")?"device_revoked":e.includes("device_required")?"device_required":"auth_failed"}o(rC,"extractHint");function iC(e){try{let t=Ha(e);if(t.length===0)return null;let r=t[t.length-1]?.result?.content?.[0]?.text;return typeof r!="string"?null:JSON.parse(r)}catch{return null}}o(iC,"parsePresenceToolResult");ue();ue();fr();import{spawn as hC}from"node:child_process";import{platform as gC}from"node:os";async function pr(e,t=process.stderr){let n=_i(),r=`${n}/device-authorization-start`,i=`${n}/device-authorization-poll`,s=to(e),a=`mcp-bridge-${s.device_id.slice(0,8)}`,c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({label:a,meta:s})});if(!c.ok){let f=await c.text();throw new Error(`device-authorization-start failed: ${c.status} ${f}`)}let l=await c.json();await wC(l.verification_uri_complete).catch(()=>{}),bC(l,t);let d=Date.now()+l.expires_in*1e3,u=Math.max(l.interval,3)*1e3;for(;Date.now()<d;){await _C(u);let f=await yC(i,l.device_code).catch(p=>(t.write(`[maind-mcp-bridge] poll error (will retry): ${String(p)}
962
+ `),null));if(f){if(f.status==="approved")return _n(f.api_key),t.write(`[maind-mcp-bridge] signed in (plan: ${f.plan}). API key saved to ~/.config/maind/api-key
963
+ `),{apiKey:f.api_key,plan:f.plan};if(f.status==="denied")return t.write(`[maind-mcp-bridge] sign-in denied by user
964
+ `),null;if(f.status==="expired"||f.status==="consumed")return t.write(`[maind-mcp-bridge] sign-in ${f.status}
965
965
  `),null}}return t.write(`[maind-mcp-bridge] sign-in timed out
966
- `),null}o(pr,"runDeviceFlow");async function eC(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}o(eC,"pollOnce");function tC(e){return new Promise(t=>setTimeout(t,e))}o(tC,"sleep");function nC(e,t){let n=[""," \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"," \u2502 \u2502"," \u2502 maind-mcp-bridge \u2014 first-time setup \u2502"," \u2502 \u2502"," \u2502 Approve this bridge to bind it to your maind account: \u2502"," \u2502 \u2502",` \u2502 Open: ${vy(e.verification_uri,56)} \u2502`,` \u2502 Code: ${vy(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
966
+ `),null}o(pr,"runDeviceFlow");async function yC(e,t){let n=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t})});if(!n.ok){let r=await n.text();throw new Error(`poll ${n.status}: ${r}`)}return await n.json()}o(yC,"pollOnce");function _C(e){return new Promise(t=>setTimeout(t,e))}o(_C,"sleep");function bC(e,t){let n=[""," \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"," \u2502 \u2502"," \u2502 maind-mcp-bridge \u2014 first-time setup \u2502"," \u2502 \u2502"," \u2502 Approve this bridge to bind it to your maind account: \u2502"," \u2502 \u2502",` \u2502 Open: ${Iy(e.verification_uri,56)} \u2502`,` \u2502 Code: ${Iy(e.user_code,56)} \u2502`," \u2502 \u2502",` \u2502 (expires in ${Math.round(e.expires_in/60)} minutes)`.padEnd(67)+"\u2502"," \u2502 \u2502"," \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",""];t.write(n.join(`
967
967
  `)+`
968
- `)}o(nC,"printAuthInstructions");function vy(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}o(vy,"pad");async function rC(e){let t,n;switch(QR()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=ZR(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}o(rC,"openExternalBrowser");Kl();Le();Fe();Le();import*as Nb from"node:os";fr();function Dy(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,hooksOnly:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--hooks-only":t.hooksOnly=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ae("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ae("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ae("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ae("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Ae(`--client requires a family argument (${bi.join(", ")})`);let s=i.trim().toLowerCase();if(!bi.includes(s))throw new Ae(`--client "${i}" is not a known client family. Known: ${bi.join(", ")}`);t.client=s,n++;break}default:throw new Ae(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}if(t.full&&(t.nonInteractive=!0),t.hooksOnly){let n=[t.noHook&&"--no-hook",t.projectRoot!==null&&"--project-root",t.noPreamble&&"--no-preamble",t.token!==null&&"--token",t.oneClickToken!==null&&"--one-click-token",t.oneClickExchangeUrl!==null&&"--one-click-exchange-url",t.client!==null&&"--client",t.skipCodex&&"--skip-codex",t.telemetry&&"--telemetry",t.autoWorkingPaths&&"--auto-working-paths"].filter(r=>typeof r=="string");if(n.length>0)throw new Ae(`--hooks-only wires the Claude Code hooks and nothing else \u2014 drop ${n.join(", ")}`)}return t}o(Dy,"parseInstallFlags");var Ae=class extends Error{static{o(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Py(){process.stdout.write(IC())}o(Py,"printInstallHelp");function IC(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${bi.join(", ")}`," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only wire the Claude Code hooks into ~/.claude/settings.json"," (no pairing, no MCP configs, no preamble files) \u2014 adds what"," an existing install is missing; with --full, without prompts"," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
969
- `)}o(IC,"installHelpText");var wi=class{static{o(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
968
+ `)}o(bC,"printAuthInstructions");function Iy(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}o(Iy,"pad");async function wC(e){let t,n;switch(gC()){case"darwin":t="open",n=[e];break;case"win32":t="cmd",n=["/c","start","",e];break;default:t="xdg-open",n=[e];break}return new Promise((r,i)=>{try{let s=hC(t,n,{stdio:"ignore",detached:!0});s.on("error",i),s.unref(),r()}catch(s){i(s)}})}o(wC,"openExternalBrowser");Zl();Fe();Ee();Fe();import*as Ub from"node:os";hr();function By(e){let t={projectRoot:null,full:!1,noPreamble:!1,noHook:!1,nonInteractive:!1,token:null,oneClickToken:null,oneClickExchangeUrl:null,telemetry:!1,client:null,skipCodex:!1,dryRun:!1,autoWorkingPaths:!1,hooksOnly:!1,help:!1};for(let n=0;n<e.length;n++){let r=e[n];switch(r){case"-h":case"--help":t.help=!0;break;case"--full":t.full=!0;break;case"--no-preamble":t.noPreamble=!0;break;case"--no-hook":t.noHook=!0;break;case"--non-interactive":t.nonInteractive=!0;break;case"--telemetry":t.telemetry=!0;break;case"--skip-codex":t.skipCodex=!0;break;case"--dry-run":t.dryRun=!0;break;case"--auto-working-paths":t.autoWorkingPaths=!0;break;case"--hooks-only":t.hooksOnly=!0;break;case"--project-root":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--project-root requires a path argument");t.projectRoot=i,n++;break}case"--token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--token requires a token argument");t.token=i,n++;break}case"--one-click-token":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--one-click-token requires a token argument");t.oneClickToken=i,n++;break}case"--one-click-exchange-url":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re("--one-click-exchange-url requires a URL argument");t.oneClickExchangeUrl=i,n++;break}case"--client":{let i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Re(`--client requires a family argument (${wi.join(", ")})`);let s=i.trim().toLowerCase();if(!wi.includes(s))throw new Re(`--client "${i}" is not a known client family. Known: ${wi.join(", ")}`);t.client=s,n++;break}default:throw new Re(`Unknown flag: ${r} \u2014 run \`install --help\` for supported flags`)}}if(t.full&&(t.nonInteractive=!0),t.hooksOnly){let n=[t.noHook&&"--no-hook",t.projectRoot!==null&&"--project-root",t.noPreamble&&"--no-preamble",t.token!==null&&"--token",t.oneClickToken!==null&&"--one-click-token",t.oneClickExchangeUrl!==null&&"--one-click-exchange-url",t.client!==null&&"--client",t.skipCodex&&"--skip-codex",t.telemetry&&"--telemetry",t.autoWorkingPaths&&"--auto-working-paths"].filter(r=>typeof r=="string");if(n.length>0)throw new Re(`--hooks-only wires the Claude Code hooks and nothing else \u2014 drop ${n.join(", ")}`)}return t}o(By,"parseInstallFlags");var Re=class extends Error{static{o(this,"InstallFlagError")}constructor(t){super(t),this.name="InstallFlagError"}};function Gy(){process.stdout.write(zC())}o(Gy,"printInstallHelp");function zC(){return["","@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.","","Detects your project root, pairs this device with MAIND, merges the","MCP-server entry into every supported AI-client config it finds, and","(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /","Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.","","Usage:"," npx -y @maind-dev/mcp-bridge install [flags]","","Common flags:"," --project-root <path> Override project-root detection (default: walk up from cwd)"," --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)"," --no-preamble Skip the 5 preamble files (MCP-config + pairing only)"," --no-hook Never write the Claude Code hooks (overrides --full for hooks)"," --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)"," --token <key> Use a pre-issued mnd_ api-key instead of browser pairing"," --one-click-token <jwt> Exchange the dashboard one-click token for a device-bound"," key \u2014 no browser (needs --one-click-exchange-url; ADR-267)"," --one-click-exchange-url <url> Exchange endpoint (set by the launcher scripts)"," --client <family> Install only for one client family \u2014 one of:",` ${wi.join(", ")}`," --skip-codex Skip the Codex ~/.codex/config.toml target",' --dry-run Compute the plan but do not write anything (status "would-\u2026")'," --hooks-only Only wire the Claude Code hooks into ~/.claude/settings.json"," (no pairing, no MCP configs, no preamble files) \u2014 adds what"," an existing install is missing; with --full, without prompts"," --telemetry Opt-in: post anonymous install_completed event"," -h, --help Show this help text","","Examples:"," npx -y @maind-dev/mcp-bridge install # interactive default"," npx -y @maind-dev/mcp-bridge install --dry-run # preview without writing anything"," npx -y @maind-dev/mcp-bridge install --full --telemetry # full setup, opt-in telemetry"," npx -y @maind-dev/mcp-bridge install --client cursor # only Cursor target","","After it finishes, restart your MCP client so the new server entry takes effect.",""].join(`
969
+ `)}o(zC,"installHelpText");var vi=class{static{o(this,"InstallReport")}results=[];add(t){this.results.push(t)}results_(){return this.results}summary(){let t=0,n=0,r=0;for(let i of this.results)i.status==="created"||i.status==="merged"||i.status==="skipped"||i.status==="would-create"||i.status==="would-merge"||i.status==="would-pair"?t++:i.status==="needs-user-decision"?n++:i.status==="failed"&&r++;return{total:this.results.length,ok:t,needsDecision:n,failed:r}}hasFailures(){return this.results.some(t=>t.status==="failed")}hasUserDecisionPending(){return this.results.some(t=>t.status==="needs-user-decision")}exitCode(){return this.hasFailures()||this.hasUserDecisionPending()?1:0}toMarkdownTable(){if(this.results.length===0)return`_no steps were attempted_
970
970
  `;let t=["Target","Action","Status","Detail"],n=Math.max(t[0].length,...this.results.map(d=>d.target.length)),r=Math.max(t[1].length,...this.results.map(d=>d.action.length)),i=Math.max(t[2].length,...this.results.map(d=>d.status.length)),s=Math.max(t[3].length,...this.results.map(d=>(d.detail??"").length)),a=o((d,u)=>d+" ".repeat(Math.max(0,u-d.length)),"pad"),c=`| ${"-".repeat(n)} | ${"-".repeat(r)} | ${"-".repeat(i)} | ${"-".repeat(s)} |`,l=[];l.push(`| ${a(t[0],n)} | ${a(t[1],r)} | ${a(t[2],i)} | ${a(t[3],s)} |`),l.push(c);for(let d of this.results)l.push(`| ${a(d.target,n)} | ${a(d.action,r)} | ${a(d.status,i)} | ${a(d.detail??"",s)} |`);return l.join(`
971
971
  `)+`
972
972
  `}print(t){let n=this.summary();t.write(`
973
973
  `),t.write(this.toMarkdownTable()),t.write(`
974
974
  Summary: ${n.ok}/${n.total} OK \xB7 ${n.needsDecision} pending \xB7 ${n.failed} failed
975
- `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};Yl();fr();wn();_e();Zl();_e();fr();import{applyEdits as FC,modify as jC,parse as UC,printParseErrorCode as HC}from"jsonc-parser";var mr="maind";async function Ky(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r=Oy(e),i=r.serversKey==="servers",s;try{s=await Z(e.path)}catch(h){return Ql(e,"read",h)}let a,c="create";if(s===null||s.trim().length===0)a={};else{c="merge";try{a=i?BC(s):JSON.parse(s)}catch(h){return Ql(e,"parse",h)}}if(!vn(a))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let l=e.key==="claude-code-user"&&WC(a),d,u,p=!1;if(l){let h=a[mr];p=Wy(h,t,r),u=Gy(h,t,r),d={...a,[mr]:u}}else{let h=a[r.serversKey],g=vn(h)?h:{},y=g[mr];p=Wy(y,t,r),u=Gy(y,t,r),d={...a,[r.serversKey]:{...g,[mr]:u}}}if(p&&s!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let f=i&&!l?GC(s??"",[r.serversKey,mr],u):JSON.stringify(d,null,2)+`
976
- `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await V(e.path,f)}catch(h){return Ql(e,"write",h)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}o(Ky,"mergeJsonConfig");function Gy(e,t,n){let r=vn(e)&&vn(e.env)?e.env:{},i={...t.env};for(let[p,f]of Object.entries(r))!(p in i)&&typeof f=="string"&&(i[p]=f);let s={command:t.command,args:[...t.args],env:i},a=n.entryType===void 0?s:{type:n.entryType,...s};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(vn(e))for(let[p,f]of Object.entries(e))p in a||l.includes(p)||(d[p]=f);let u=Object.entries(c).filter(([p])=>!(p in d));return{...a,...d,...Object.fromEntries(u)}}o(Gy,"mergeEntry");function BC(e){let t=[],n=UC(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${HC(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}o(BC,"parseJsoncStrict");function GC(e,t,n){let r=jC(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
977
- `}}),i=FC(e,r);return i.endsWith(`
975
+ `)}toJson(){return{steps:[...this.results],summary:this.summary()}}};nd();hr();wn();_e();sd();_e();hr();import{applyEdits as tI,modify as nI,parse as rI,printParseErrorCode as iI}from"jsonc-parser";var gr="maind";async function e_(e,t,n=!1){if(e.kind!=="json")return{target:e.key,action:"merge",status:"failed",detail:`expected json target, got ${e.kind}`};let r=Hy(e),i=r.serversKey==="servers",s;try{s=await Q(e.path)}catch(h){return od(e,"read",h)}let a,c="create";if(s===null||s.trim().length===0)a={};else{c="merge";try{a=i?sI(s):JSON.parse(s)}catch(h){return od(e,"parse",h)}}if(!vn(a))return{target:e.key,action:"merge",status:"failed",detail:"existing file is not a JSON object at root"};let l=e.key==="claude-code-user"&&aI(a),d,u,f=!1;if(l){let h=a[gr];f=Qy(h,t,r),u=Zy(h,t,r),d={...a,[gr]:u}}else{let h=a[r.serversKey],g=vn(h)?h:{},y=g[gr];f=Qy(y,t,r),u=Zy(y,t,r),d={...a,[r.serversKey]:{...g,[gr]:u}}}if(f&&s!==null)return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let p=i&&!l?oI(s??"",[r.serversKey,gr],u):JSON.stringify(d,null,2)+`
976
+ `;if(n)return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"would-create":"would-merge",detail:e.path};try{await z(e.path,p)}catch(h){return od(e,"write",h)}return{target:e.key,action:c==="create"?"write":"merge",status:c==="create"?"created":"merged",detail:e.path}}o(e_,"mergeJsonConfig");function Zy(e,t,n){let r=vn(e)&&vn(e.env)?e.env:{},i={...t.env};for(let[f,p]of Object.entries(r))!(f in i)&&typeof p=="string"&&(i[f]=p);let s={command:t.command,args:[...t.args],env:i},a=n.entryType===void 0?s:{type:n.entryType,...s};if(n.clientKeys===void 0)return a;let{defaults:c,drop:l}=n.clientKeys,d={};if(vn(e))for(let[f,p]of Object.entries(e))f in a||l.includes(f)||(d[f]=p);let u=Object.entries(c).filter(([f])=>!(f in d));return{...a,...d,...Object.fromEntries(u)}}o(Zy,"mergeEntry");function sI(e){let t=[],n=rI(e,t,{allowTrailingComma:!0}),r=t[0];if(r!==void 0)throw new Error(`invalid JSONC \u2014 ${iI(r.error)} at offset ${r.offset}`+(t.length>1?` (+${t.length-1} more)`:""));return n}o(sI,"parseJsoncStrict");function oI(e,t,n){let r=nI(e,t,n,{formattingOptions:{insertSpaces:!/^\t/m.test(e),tabSize:2,eol:`
977
+ `}}),i=tI(e,r);return i.endsWith(`
978
978
  `)?i:i+`
979
- `}o(GC,"editInPlace");function WC(e){return!("mcpServers"in e||!(mr in e))}o(WC,"hasRootShape");function Wy(e,t,n){if(!vn(e)||n.entryType!==void 0&&e.type!==n.entryType||n.clientKeys!==void 0&&n.clientKeys.drop.some(r=>r in e)||e.command!==t.command||!KC(e.args,t.args)||!vn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}o(Wy,"serverEntriesEqual");function KC(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}o(KC,"arrayEquals");function vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(vn,"isObject");function Ql(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(Ql,"failed");_e();import{parse as VC,stringify as zC}from"smol-toml";async function Vy(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await Z(e.path)}catch(g){return oo(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=VC(r);if(!kn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return oo(e,"parse",g)}}let a=kn(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(kn(c)&&qC(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=kn(c)&&kn(c.env)?c.env:{},d={...t.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:t.command,args:[...t.args],env:d},p={...i,mcp_servers:{...a,maind:u}},f;try{f=zC(p),f.endsWith(`
980
- `)||(f+=`
981
- `)}catch(g){return oo(e,"write",g)}let h=f.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await V(e.path,f)}catch(g){return oo(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}o(Vy,"mergeTomlConfig");function qC(e,t){if(!kn(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!kn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(qC,"tomlServerEntryEqual");function kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(kn,"isObject");function oo(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(oo,"failed");nd();fd();ad();Mt();$t();_e();import*as r_ from"node:readline";var En="config:auto_working_paths",vI=`
979
+ `}o(oI,"editInPlace");function aI(e){return!("mcpServers"in e||!(gr in e))}o(aI,"hasRootShape");function Qy(e,t,n){if(!vn(e)||n.entryType!==void 0&&e.type!==n.entryType||n.clientKeys!==void 0&&n.clientKeys.drop.some(r=>r in e)||e.command!==t.command||!cI(e.args,t.args)||!vn(e.env))return!1;for(let r of Object.keys(t.env))if(e.env[r]!==t.env[r])return!1;return!0}o(Qy,"serverEntriesEqual");function cI(e,t){if(!Array.isArray(e)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}o(cI,"arrayEquals");function vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(vn,"isObject");function od(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(od,"failed");_e();import{parse as lI,stringify as dI}from"smol-toml";async function t_(e,t,n=!1){if(e.kind!=="toml")return{target:e.key,action:"merge",status:"failed",detail:`expected toml target, got ${e.kind}`};let r;try{r=await Q(e.path)}catch(g){return uo(e,"read",g)}let i,s="create";if(r===null||r.trim().length===0)i={};else{s="merge";try{let g=lI(r);if(!kn(g))return{target:e.key,action:"merge",status:"failed",detail:"parsed TOML is not an object at root"};i=g}catch(g){return uo(e,"parse",g)}}let a=kn(i.mcp_servers)?i.mcp_servers:{},c=a.maind;if(kn(c)&&uI(c,t))return{target:e.key,action:"merge",status:"skipped",detail:"maind entry already up-to-date"};let l=kn(c)&&kn(c.env)?c.env:{},d={...t.env};for(let[g,y]of Object.entries(l))!(g in d)&&typeof y=="string"&&(d[g]=y);let u={command:t.command,args:[...t.args],env:d},f={...i,mcp_servers:{...a,maind:u}},p;try{p=dI(f),p.endsWith(`
980
+ `)||(p+=`
981
+ `)}catch(g){return uo(e,"write",g)}let h=p.match(/^\[mcp_servers\.maind\]/gm)??[];if(h.length!==1)return{target:e.key,action:"merge",status:"failed",detail:`expected exactly one [mcp_servers.maind] section, got ${h.length}`};if(n)return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"would-create":"would-merge",detail:e.path};try{await z(e.path,p)}catch(g){return uo(e,"write",g)}return{target:e.key,action:s==="create"?"write":"merge",status:s==="create"?"created":"merged",detail:e.path}}o(t_,"mergeTomlConfig");function uI(e,t){if(!kn(e)||e.command!==t.command||!Array.isArray(e.args)||e.args.length!==t.args.length)return!1;for(let n=0;n<e.args.length;n++)if(e.args[n]!==t.args[n])return!1;if(!kn(e.env))return!1;for(let n of Object.keys(t.env))if(e.env[n]!==t.env[n])return!1;return!0}o(uI,"tomlServerEntryEqual");function kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(kn,"isObject");function uo(e,t,n){let r=n instanceof Error?n.message:String(n);return{target:e.key,action:"merge",status:"failed",detail:`${t}: ${r}`}}o(uo,"failed");ld();wd();md();Mt();$t();_e();import*as f_ from"node:readline";var En="config:auto_working_paths",FI=`
982
982
  Enable presence enrichment (auto working_paths)?
983
983
  With this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your
984
984
  locally changed files (from \`git status\`, max 8, re-derived at most every 45s)
@@ -987,42 +987,42 @@ before editing the same area. Directory names only: never file contents, never
987
987
  absolute paths. Server-side these paths are account-private (org members never
988
988
  see them) and revocable any time on the dashboard consent page or via
989
989
  {"auto_working_paths": false} in the bridge config.
990
- [y/N]: `;async function i_(e){let t=e.configPath??je(),n={};try{let a=await Z(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:En,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${t}`};let r;if(e.explicitFlag)r=!0;else if(e.isInteractive){if(e.dryRun)return{target:En,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??kI)(e.out,vI)}else return{target:En,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:En,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},s=JSON.stringify(i,null,2)+`
991
- `;if(e.dryRun)return{target:En,action:"merge",status:"would-merge",detail:t};try{await V(t,s,384)}catch(a){return{target:En,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:En,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}o(i_,"applyWorkingPathsConsent");async function kI(e,t){e.write(t);let n=r_.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}o(kI,"promptYesNoDefaultNo");fo();import{existsSync as EI}from"node:fs";import{join as TI}from"node:path";function AI(e){let t=e.find(n=>n.target.startsWith("hook(on-read-context)"));return t===void 0?!1:t.status==="skipped"?/already runs maind on-read-context/.test(t.detail??""):t.status!=="failed"}o(AI,"readHookWired");function o_(e,t,n=EI){if(!AI(t))return null;let r=Ft(e,n)??e;return n(TI(r,Lt))?null:{target:"context-moment",action:"probe",status:"skipped",detail:`on-read-context is wired, but ${r} has no code index yet \u2014 it stays silent there until one exists. Ask your agent to run codebase_index once (or run \`maind index\` in the repo); the Stop hook keeps it fresh after that.`}}o(o_,"contextIndexRow");ue();async function a_(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),s={};try{s=await i.json()}catch{}return i.ok?s.status!=="exchanged"||typeof s.api_key!="string"||!s.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:s.api_key,plan:s.plan??"unknown"}:{ok:!1,reason:s.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}o(a_,"exchangeOneClickToken");async function d_(e){let t="browser-pair";if(e.token!==null)try{let s=RI(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(gi(),_n(s),{apiKey:s,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:c_(s)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let s=Js(e.bridgeVersion),a=await a_({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:wy(),clientMeta:{...s}});if(a.ok)return gi(),_n(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,l_(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
992
- `)}let r=n===null?"":` (after exchange failure: ${n})`,i=q();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await pr(e.bridgeVersion,l_(e));return s===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:c_(s)}}}}o(d_,"pairOrUseToken");function RI(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}o(RI,"validateTokenShape");function c_(e){return e instanceof Error?e.message:String(e)}o(c_,"errMessage");function l_(e){return e.out??process.stdout}o(l_,"out");ur();var CI="install-completed",II=3e3;async function u_(e){if(!e.enabled||e.apiKey===null)return;let t=dr(CI),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:OI(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:NI(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),II);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(i)}}o(u_,"postInstallTelemetry");function NI(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}o(NI,"countStatuses");function OI(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}o(OI,"parseNodeMajor");Bt();Id();Fe();var hO="https://mcp.maind.dev/mcp";async function Ob(e){let t=Date.now(),n;try{n=Dy(e)}catch(k){if(k instanceof Ae)return process.stderr.write(`error: ${k.message}
993
- `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw k}if(n.help)return Py(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=Nb.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
994
- `),2;if(n.hooksOnly)return gO({homeDir:s,isInteractive:i,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let k=await ro(process.cwd());if(k.length===0)a=await Ly(process.cwd());else if(k.length===1)a=k[0];else{let v=await jy(k,i);if(v===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
995
- `);for(let T of k)process.stderr.write(` candidate: ${T}
996
- `);return 2}a=v}}let c=new wi,l=(process.env.MAIND_MCP_URL??"").trim()||hO;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
990
+ [y/N]: `;async function p_(e){let t=e.configPath??je(),n={};try{let a=await Q(t);if(a!==null&&a.trim().length>0){let c=JSON.parse(a);typeof c=="object"&&c!==null&&!Array.isArray(c)&&(n=c)}}catch{}if(typeof n.auto_working_paths=="boolean")return{target:En,action:"skip",status:"skipped",detail:`already decided (${n.auto_working_paths?"enabled":"disabled"}) in ${t}`};let r;if(e.explicitFlag)r=!0;else if(e.isInteractive){if(e.dryRun)return{target:En,action:"merge",status:"would-merge",detail:`${t} (would prompt for consent in real run)`};r=await(e.promptFn??jI)(e.out,FI)}else return{target:En,action:"skip",status:"skipped",detail:"consent-required: pass --auto-working-paths to enable non-interactively (deliberately not implied by --full)"};if(!r)return{target:En,action:"skip",status:"skipped",detail:"user declined \u2014 announce stays the minimal skeleton (ask again: re-run install after deleting the key from config.json)"};let i={...n,auto_working_paths:!0},s=JSON.stringify(i,null,2)+`
991
+ `;if(e.dryRun)return{target:En,action:"merge",status:"would-merge",detail:t};try{await z(t,s,384)}catch(a){return{target:En,action:"merge",status:"failed",detail:`write: ${a instanceof Error?a.message:String(a)}`}}return{target:En,action:"merge",status:"merged",detail:`${t} \u2014 presence enrichment enabled (revoke: dashboard consent page or auto_working_paths=false)`}}o(p_,"applyWorkingPathsConsent");async function jI(e,t){e.write(t);let n=f_.createInterface({input:process.stdin,output:e,terminal:!0}),r=await new Promise(i=>{n.question("",s=>i(s.trim().toLowerCase()))});return n.close(),r==="y"||r==="yes"}o(jI,"promptYesNoDefaultNo");yo();import{existsSync as BI}from"node:fs";import{join as GI}from"node:path";function WI(e){let t=e.find(n=>n.target.startsWith("hook(on-read-context)"));return t===void 0?!1:t.status==="skipped"?/already runs maind on-read-context/.test(t.detail??""):t.status!=="failed"}o(WI,"readHookWired");function h_(e,t,n=BI){if(!WI(t))return null;let r=Ft(e,n)??e;return n(GI(r,Lt))?null:{target:"context-moment",action:"probe",status:"skipped",detail:`on-read-context is wired, but ${r} has no code index yet \u2014 it stays silent there until one exists. Ask your agent to run codebase_index once (or run \`maind index\` in the repo); the Stop hook keeps it fresh after that.`}}o(h_,"contextIndexRow");ue();async function g_(e){let t=e.fetchImpl??fetch,n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs??1e4);try{let i=await t(e.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:e.token,device_id:e.deviceId,label:e.label,client_meta:e.clientMeta}),signal:n.signal}),s={};try{s=await i.json()}catch{}return i.ok?s.status!=="exchanged"||typeof s.api_key!="string"||!s.api_key.startsWith("mnd_")?{ok:!1,reason:"unexpected_response"}:{ok:!0,apiKey:s.api_key,plan:s.plan??"unknown"}:{ok:!1,reason:s.error??`http_${i.status}`}}catch(i){return i instanceof Error&&i.name==="AbortError"?{ok:!1,reason:"timeout"}:{ok:!1,reason:i instanceof Error?i.message:String(i)}}finally{clearTimeout(r)}}o(g_,"exchangeOneClickToken");async function b_(e){let t="browser-pair";if(e.token!==null)try{let s=KI(e.token);return e.dryRun?{apiKey:s,result:{target:t,action:"token",status:"would-pair",detail:"would pair via --token (one-click flow)"}}:(yi(),_n(s),{apiKey:s,result:{target:t,action:"token",status:"created",detail:"paired via --token (one-click flow)"}})}catch(s){return{apiKey:null,result:{target:t,action:"token",status:"failed",detail:y_(s)}}}let n=null;if(e.oneClickToken!==null&&e.oneClickExchangeUrl!==null){if(e.dryRun)return{apiKey:null,result:{target:t,action:"exchange",status:"would-pair",detail:"would exchange one-click token for a device-bound key (no browser)"}};let s=to(e.bridgeVersion),a=await g_({token:e.oneClickToken,url:e.oneClickExchangeUrl,deviceId:s.device_id,label:Cy(),clientMeta:{...s}});if(a.ok)return yi(),_n(a.apiKey),{apiKey:a.apiKey,result:{target:t,action:"exchange",status:"created",detail:`device-bound api-key via one-click exchange (plan: ${a.plan})`}};n=a.reason,__(e).write(`[maind-mcp-bridge] one-click exchange failed (${a.reason}) \u2014 falling back to browser pairing.
992
+ `)}let r=n===null?"":` (after exchange failure: ${n})`,i=Y();if(i!==null)return{apiKey:i,result:{target:t,action:"skip",status:"skipped",detail:`device already paired \u2014 use --reauth to force a fresh pairing${r}`}};if(e.dryRun)return{apiKey:null,result:{target:t,action:"pair",status:"would-pair",detail:"would open browser for device-authorization flow"}};try{let s=await pr(e.bridgeVersion,__(e));return s===null?{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:`device-authorization flow did not complete (denied / expired / timeout)${r}`}}:{apiKey:s.apiKey,result:{target:t,action:"pair",status:"created",detail:`device-bound api-key written (plan: ${s.plan})${r}`}}}catch(s){return{apiKey:null,result:{target:t,action:"pair",status:"failed",detail:y_(s)}}}}o(b_,"pairOrUseToken");function KI(e){let t=e.trim();if(t.length===0)throw new Error("--token is empty");if(!/^mnd_[A-Za-z0-9_]+$/.test(t))throw new Error("--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?");return t}o(KI,"validateTokenShape");function y_(e){return e instanceof Error?e.message:String(e)}o(y_,"errMessage");function __(e){return e.out??process.stdout}o(__,"out");fr();var VI="install-completed",zI=3e3;async function w_(e){if(!e.enabled||e.apiKey===null)return;let t=ur(VI),n={installer_version:e.installerVersion,wall_clock_ms:e.wallClockMs,os_family:process.platform,node_major:YI(process.version),summary:{total:e.summary.total,ok:e.summary.ok,needs_decision:e.summary.needsDecision,failed:e.summary.failed},step_status_counts:qI(e.steps),client_family_filter:e.clientFamilyFilter??null},r=new AbortController,i=setTimeout(()=>r.abort(),zI);try{await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"user-agent":`@maind-dev/mcp-bridge install/${e.installerVersion}`},body:JSON.stringify(n),signal:r.signal})}catch{}finally{clearTimeout(i)}}o(w_,"postInstallTelemetry");function qI(e){let t={created:0,merged:0,skipped:0,"needs-user-decision":0,failed:0};for(let n of e)t[n.status]=(t[n.status]??0)+1;return t}o(qI,"countStatuses");function YI(e){let t=/^v?(\d+)\./.exec(e);return t===null?0:Number.parseInt(t[1],10)}o(YI,"parseNodeMajor");Bt();Ld();Ee();var OO="https://mcp.maind.dev/mcp";async function Hb(e){let t=Date.now(),n;try{n=By(e)}catch(x){if(x instanceof Re)return process.stderr.write(`error: ${x.message}
993
+ `),process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n"),2;throw x}if(n.help)return Gy(),0;let i=!!process.stdin.isTTY&&!n.nonInteractive,s=Ub.homedir();if(s.trim().length===0)return process.stderr.write(`error: could not resolve home directory (os.homedir() returned empty)
994
+ `),2;if(n.hooksOnly)return DO({homeDir:s,isInteractive:i,full:n.full,skip:!1,dryRun:n.dryRun,out:process.stdout});let a;if(n.projectRoot!==null)a=n.projectRoot;else{let x=await ao(process.cwd());if(x.length===0)a=await Vy(process.cwd());else if(x.length===1)a=x[0];else{let v=await qy(x,i);if(v===null){process.stderr.write(`error: multiple project roots found and we cannot prompt (non-interactive). Pass --project-root <path> to pick one explicitly.
995
+ `);for(let E of x)process.stderr.write(` candidate: ${E}
996
+ `);return 2}a=v}}let c=new vi,l=(process.env.MAIND_MCP_URL??"").trim()||OO;n.dryRun&&process.stdout.write(`DRY RUN \u2014 computing the plan, no files will be modified.
997
997
  `),process.stdout.write(`maind install \u2014 project root: ${a}
998
998
  `),process.stdout.write(` \u2014 mcp endpoint: ${l}
999
999
 
1000
- `);let d=no({projectRoot:a,homeDir:s,platform:process.platform,env:process.env}),u=_i(d);if(u=Ny(u,n.client),n.skipCodex&&(u=u.filter(k=>k.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
1000
+ `);let d=oo({projectRoot:a,homeDir:s,platform:process.platform,env:process.env}),u=bi(d);if(u=Uy(u,n.client),n.skipCodex&&(u=u.filter(x=>x.key!=="codex-cli")),u.length===0)return process.stderr.write(n.client!==null?`error: --client "${n.client}" matched no known target. Run --help for the list.
1001
1001
  `:`error: no client targets selected (did you skip all of them?)
1002
- `),c.print(process.stdout),2;let p=await d_({bridgeVersion:B,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(p.result),p.result.status==="failed")return process.stderr.write(`
1003
- pairing failed: ${p.result.detail??"unknown"}
1002
+ `),c.print(process.stdout),2;let f=await b_({bridgeVersion:B,token:n.token,oneClickToken:n.oneClickToken,oneClickExchangeUrl:n.oneClickExchangeUrl,dryRun:n.dryRun,out:process.stdout});if(c.add(f.result),f.result.status==="failed")return process.stderr.write(`
1003
+ pairing failed: ${f.result.detail??"unknown"}
1004
1004
  Skipping remaining steps.
1005
- `),c.print(process.stdout),2;for(let k of u){let v=By({target:k,explicitFamily:n.client,probe:so});if(v!==null){c.add(v);continue}let T=Ay({mcpUrl:l,clientFamily:k.clientFamilyEnv}),O;k.kind==="json"?O=await Ky(k,T,n.dryRun):O=await Vy(k,T,n.dryRun),c.add(O)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let k=await Xy({projectRoot:a,homeDir:s,conventions:o(()=>Fo(p.apiKey,Zs(a),{allowFetch:!n.dryRun}),"conventions")},n.dryRun);for(let v of k)c.add(v)}let f={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await n_(f));let h=await pd(f);for(let k of h)c.add(k);n.dryRun||await od(Pt,h);let g=o_(a,h);g!==null&&c.add(g),c.add(await i_({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let y=Co();y.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${y.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await u_({enabled:n.telemetry||n.full,installerVersion:B,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:p.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let b=c.exitCode(),w=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1005
+ `),c.print(process.stdout),2;for(let x of u){let v=Xy({target:x,explicitFamily:n.client,probe:lo});if(v!==null){c.add(v);continue}let E=$y({mcpUrl:l,clientFamily:x.clientFamilyEnv}),N;x.kind==="json"?N=await e_(x,E,n.dryRun):N=await t_(x,E,n.dryRun),c.add(N)}if(n.noPreamble)c.add({target:"preamble:*",action:"skip",status:"skipped",detail:"--no-preamble"});else{let x=await o_({projectRoot:a,homeDir:s,conventions:o(()=>Bo(f.apiKey,no(a),{allowFetch:!n.dryRun}),"conventions")},n.dryRun);for(let v of x)c.add(v)}let p={homeDir:s,isInteractive:i,full:n.full,skip:n.noHook,dryRun:n.dryRun,out:process.stdout};c.add(await u_(p));let h=await bd(p);for(let x of h)c.add(x);n.dryRun||await pd(Pt,h);let g=h_(a,h);g!==null&&c.add(g),c.add(await p_({isInteractive:i,explicitFlag:n.autoWorkingPaths,dryRun:n.dryRun,out:process.stdout}));let y=Do();y.ok||c.add({target:"codebase-tools",action:"probe",status:"skipped",detail:`codebase_* tools disabled \u2014 better-sqlite3 unavailable (${y.reason}). Bridge works; fix: npm rebuild better-sqlite3`}),n.dryRun||await w_({enabled:n.telemetry||n.full,installerVersion:B,summary:c.summary(),steps:c.results_(),wallClockMs:Date.now()-t,apiKey:f.apiKey,clientFamilyFilter:n.client}),c.print(process.stdout);let b=c.exitCode(),w=((Date.now()-t)/1e3).toFixed(1);n.dryRun?process.stdout.write(`
1006
1006
  DRY RUN finished in ${w}s. No files were modified. Re-run without --dry-run to apply.
1007
1007
  `):process.stdout.write(`
1008
1008
  Finished in ${w}s. Restart your MCP client so it picks up the new server entry.
1009
- `);let x=Ee({entryPath:Te(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),S=x.fallbackReason===null?`${Ot(x)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${S}
1009
+ `);let k=Te({entryPath:Ae(),nodePath:process.execPath,isElectron:process.versions.electron!==void 0}),S=k.fallbackReason===null?`${Ot(k)} --reauth`:"npx -y @maind-dev/mcp-bridge --reauth";return process.stdout.write(`Re-pair this device later with: ${S}
1010
1010
  `),b===1&&process.stdout.write(`Note: some steps were skipped or failed \u2014 review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.
1011
- `),b}o(Ob,"runInstall");async function gO(e){let t=new wi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1011
+ `),b}o(Hb,"runInstall");async function DO(e){let t=new vi;e.dryRun&&e.out.write(`DRY RUN \u2014 computing the plan, no files will be modified.
1012
1012
  `),e.out.write(`maind install --hooks-only \u2014 Claude Code hooks in ~/.claude/settings.json
1013
- `);let n=await pd(e);for(let r of n)t.add(r);return e.dryRun||await od(Pt,n),t.print(e.out),e.out.write(e.dryRun?`
1013
+ `);let n=await bd(e);for(let r of n)t.add(r);return e.dryRun||await pd(Pt,n),t.print(e.out),e.out.write(e.dryRun?`
1014
1014
  DRY RUN finished. No files were modified.
1015
1015
  `:`
1016
1016
  Claude Code reads hooks when a session starts \u2014 new sessions pick them up.
1017
- `),t.exitCode()}o(gO,"runHooksOnly");Bt();Bt();import{readFileSync as yO}from"node:fs";import{join as Db}from"node:path";function jo(e){return e?Math.ceil(e.length/4):0}o(jo,"estimateTokens");var Pb=1e6,Uo=class{static{o(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function Mb(e){try{let t=yO(e,"utf8");return t.length>Pb?t.slice(0,Pb):t}catch{return""}}o(Mb,"readFileCapped");function _O(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}o(_O,"distinctFilePaths");function $b(e,t,n,r){try{let i=jo(n);if(e==="codebase_search"){let s=_O(t);if(s.length===0)return 0;let a=0;for(let c of s)a+=jo(Mb(Db(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let a=jo(Mb(Db(r,s)));return Math.max(0,a-i)}return 0}catch{return 0}}o($b,"measureLocalToolSaved");It();Bt();import{createHash as jO}from"node:crypto";It();import{execFileSync as kO}from"node:child_process";import{createHash as xO}from"node:crypto";Bt();Nd();import{realpathSync as Bb}from"node:fs";function SO(e,t){try{return Bb(e)===Bb(t)}catch{return e===t}}o(SO,"samePath");var Od=30,EO=10,Gb=20,TO=new Map;function Dd(e){return e instanceof Error?e.message:String(e)}o(Dd,"msg");function Bo(e){let t=e.split(`
1018
- `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}o(Bo,"firstLine");var Wb=o(e=>e?e.slice(0,12):"?","short");async function AO(e,t,n,r){let i=await e.status(),s=!i.indexed||i.fileCount===0,a=await Hb(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:Dd(c)}}},n);return a.locked?a.value.ok?s?(r.push(`no local index found \u2014 built it now (${a.value.stats.filesParsed} file(s), ${Math.round(a.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:a.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:a.value.stats.filesParsed,missing:!1}:(s||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:s}):(s||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:s})}o(AO,"refreshIndex");function RO(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}o(RO,"isEmptyRange");function CO(e){let t=o(r=>`${r.detector_id}\0${r.rule_id}\0${r.title}`,"key"),n=new Set(e.commit.local.map(t));return e.local.local.filter(r=>!n.has(t(r)))}o(CO,"localOnly");function IO(e){let t=[],n=e.diff_stats;return e.base_sha||t.push("base_sha_missing"),n.stale_file_count!==0&&t.push("stale_files"),n.truncated!==!1&&t.push("truncated"),n.hunk_coverage!=="full"&&t.push("hunk_coverage_not_full"),n.detector_coverage!=="full"&&t.push("detector_coverage_not_full"),t}o(IO,"localGradeBlockers");function NO(e){if(!e.persistWanted)return{persist:!1,skipped:"no_report"};if(e.since===void 0)return{persist:!1,skipped:"no_base"};if(e.result.dirty)return{persist:!1,skipped:"dirty_tree"};let t=Pl(!1,e.projectKey,e.result);if(!t.persist)return t;let n=IO(e.payload);return n.length>0?{persist:!1,skipped:"not_grade_eligible",detail:n}:e.git===null||e.git.defaultBranch===null||e.git.forkPoint===null?{persist:!1,skipped:"fork_point_unknown",detail:[e.git?.defaultBranch?`origin/${e.git.defaultBranch}`:"no default branch"]}:e.git.forkPoint!==e.result.mergeBaseSha?{persist:!1,skipped:"base_not_fork_point",detail:[e.result.mergeBaseSha??"?",e.git.forkPoint,`origin/${e.git.defaultBranch}`]}:e.git.pushed?e.recordedRunId!==null?{persist:!1,skipped:"already_recorded",detail:[e.recordedRunId]}:{persist:!0,skipped:null}:{persist:!1,skipped:"head_not_pushed"}}o(NO,"bridgePersistDecision");function Kb(e,t){try{return kO("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}o(Kb,"git");function OO(e,t){let n=Qr(e),r=n&&Kb(e,["merge-base",t,`origin/${n}`])||null,i=Kb(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}o(OO,"gitPersistFacts");function DO(e,t){return xO("sha256").update(`${e??""}
1019
- ${JSON.stringify(t)}`).digest("hex")}o(DO,"payloadKey");function He(e,t,n){return{kind:"error",error:e,message:t,hint:n}}o(He,"fail");var In="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function Vb(e){let t=$l(e);if(t!==null&&Ll(t))return He("server_predates_attest_mode","the MAIND server predates attest mode (< 0.62.0): it rejected a review_verdict call without `findings`.","No fallback: the legacy two-call path only yields an advisory verdict. For that today use codebase_review_changes \u2192 review_changes \u2192 review_verdict.");if(t?.kind==="invalid_params"){let n=t.issues[0];return He("attest_rejected",`the server rejected the attest payload${n?` at ${(n.path??[]).join(".")||"(root)"}: ${n.message??n.code??"invalid"}`:""}.`,"This is a bridge/server version mismatch, not a problem with your change. Update the bridge (`npx -y @maind-dev/mcp-bridge@latest`) and call again; if it persists, report it.")}return He("cloud_unavailable",`review_verdict failed: ${Bo(t?.detail??e)||"no detail"}`,In)}o(Vb,"fromProtocolText");function PO(e,t,n){switch(e.kind){case"no_session":return He("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${In}`);case"transport_error":return e.timedOut?He("cloud_timeout",`review_verdict did not answer within ${Math.round(t/1e3)} s.`,n?"The call asked for a record, and the server may still have written one. Check before calling again: `maind verify --commit HEAD`.":"The call asked for no record, so nothing was written. Call again when the server responds."):He("cloud_unavailable",`network error: ${e.message}`,In);case"http_error":return e.status===401?He("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Bo(e.body)}`,"If the key was revoked or rebound, the next forwarded MAIND call starts the re-authorization; otherwise run `npx -y @maind-dev/mcp-bridge --reauth`."):e.status===413?He("payload_too_large","the attest payload exceeded the server's request limit (HTTP 413).","Symbols are never cut to fit \u2014 a shortened list would attest a review that did not happen. Split the change into smaller commits or pull requests."):He("cloud_unavailable",`HTTP ${e.status}: ${Bo(e.body)}`,In);case"rpc_error":return Vb(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return Vb(e.text);let r;try{r=JSON.parse(e.text)}catch{return He("cloud_unavailable",`review_verdict returned non-JSON text: ${Bo(e.text)}`,In)}return typeof r!="object"||r===null?He("cloud_unavailable","review_verdict returned no object",In):{kind:"verdict",body:r}}}}o(PO,"interpretOutcome");var MO="review_verdict \u2014 and with it this tool \u2014 is a Team-plan feature. codebase_review_changes still gives you the advisory review (https://maind.dev/pricing).",$O={dirty:"commit (or stash) your changes \u2014 a dirty worktree cannot be recomputed",base_kind_not_ref:"pass `since` \u2014 only a committed range is replayable",base_sha_missing:"pass `since` \u2014 only a committed range is replayable",stale_files:"the index was stale for changed files \u2014 run codebase_index, then call again",truncated:"more than 1000 changed symbols, or labels beyond the schema \u2014 split the change",hunk_coverage_not_full:"some changes could not be line-graded (binary or unusual diffs)",detector_coverage_not_full:"a repo-health detector could not run \u2014 see local.detectors",merge_base_missing:"no merge-base with `since` (shallow clone?) \u2014 fetch the full history",private_citation:"a finding cites a private convention \u2014 not verifiable by others"},zb=o(e=>e.map(t=>$O[t]??t).join("; "),"adviceFor");function LO(e,t){switch(e){case"no_report":return"persist: false \u2014 verdict only, nothing recorded.";case"no_head":return"no HEAD commit \u2014 there is nothing a record could be anchored to.";case"no_project_key":return"no origin remote, so no project_key to file a record under \u2014 the verdict is computed but not recorded.";case"no_merge_base":return"no merge-base between HEAD and `since` (shallow clone?) \u2014 the verdict is computed but not recorded; fetch the full history.";case"no_base":return"uncommitted work is judged but never recorded. Commit and push, then call again with `since` = the branch's base (e.g. origin/master).";case"dirty_tree":return"the worktree has uncommitted or untracked changes \u2014 a record attests a commit, and a dirty tree cannot be recomputed. Commit (or stash) them, then call again.";case"not_grade_eligible":return`this run could not be attestation-grade (${(t??[]).join(", ")}), and only replayable runs are recorded. To fix: ${zb(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=t??[];return`the reviewed range starts at ${Wb(n)}, but this branch forks off ${i??"the default branch"} at ${Wb(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}o(LO,"skipText");function FO(e,t,n,r){if(e.persisted){if(t===!0)return`Recorded as attestation-grade run ${e.run_id} (format 3). Recompute it: \`maind verify ${e.run_id}\``+(r?` \u2014 a teammate: \`maind verify --commit ${r}\`.`:".");let c=zb(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",s=LO(i,e.detail),a=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${a}`:`Not recorded (${i||"the server gave no reason"}).${a}`}o(FO,"recordHint");async function qb(e,t,n){let r=n.repoRoot??he(),i=r,s=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let ee=vr(c,r);if(ee===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(c)} could not be located \u2014 no repository was reviewed, nothing was sent.`,hint:"Pass a path that exists relative to the workspace (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};if(!SO(ee.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=ee.repoRoot,s=n.engineFor(i),a=n.projectKeyFor?.(i)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,d=l!==void 0&&t.include_uncommitted===!0,u=t.persist!==!1,p=n.timeoutMs??9e4,f=n.recorded??TO,h=[],g=await AO(s,i,n.lock,h);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:h};let y=await s.reviewChanges(Ol(l,d)),b={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(RO(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:b,warnings:h};let w;try{w=await s.reviewDetectorScopes({baseRef:l})}catch(ee){let mp=xe(ct(`reviewDetectorScopes failed: ${Dd(ee)}`));w={commit:mp,local:mp},h.push(`repo-health detectors unavailable (${Dd(ee)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:x,dropped:S}=Dl(y,w.commit);S>0&&h.push(`${S} symbol(s) exceed the server schema (name > ${Bs} or qualified name > ${Gs} chars) and were left out \u2014 this run is not attestation-grade.`);let k=DO(a,x),v=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",T=NO({persistWanted:u,since:l,projectKey:a,result:y,payload:x,git:v?(n.persistFacts??OO)(i,y.headSha):null,recordedRunId:f.get(k)??null}),O={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:x.changed_symbols.length,symbols_dropped:S,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:w.commit.coverage,findings:w.commit.local.slice(0,Gb),local_only:CO(w).slice(0,Gb)}},j=await n.callCloudTool("review_verdict",{attest:x,persist:T.persist,...a?{project_key:a}:{}},{timeoutMs:p}),H=PO(j,p,T.persist);if(H.kind==="error")return{ok:!1,error:H.error,message:H.message,hint:H.hint,base:b,local:O,warnings:h};let N=H.body;if(N.ok!==!0){let ee=N.error==="requires_team"||N.error==="requires_enterprise";return{ok:!1,error:N.error??"unknown_error",message:N.message??"review_verdict returned no message",hint:ee?MO:N.hint??In,base:b,local:O,warnings:h}}if(N.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:b,local:O,warnings:h};let U=N.attest,ae=N.run??null,yt=ae&&typeof ae.id=="string"?{persisted:!0,run_id:ae.id,commit_sha:ae.commit_sha??null,attestation_format:ae.attestation_format??null}:{persisted:!1,reason:T.skipped??N.run_note??"not_persisted",...T.detail?{detail:T.detail}:{}};yt.persisted&&f.set(k,ae.id);let Fr=typeof U?.attestation_grade=="boolean"?U.attestation_grade:null,z=Array.isArray(U?.grade_blockers)?U.grade_blockers:[],be=N.counts??{},Un=Array.isArray(N.findings)?N.findings:[],zx=`Verdict ${N.verdict??"?"}: ${be.block??0} block, ${be.warn??0} warn, ${be.note??0} note`+(N.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:N.verdict??null,counts:be,record:yt,attest:U?{attestation_grade:Fr,grade_blockers:z,attestation_format:U.attestation_format??null,input_hash:U.input_hash??null,policy_hash:U.policy_hash??null,evaluated_convention_count:U.evaluated_convention_count??null,detector_coverage:U.detector_coverage??null}:null,hint:`${zx} ${FO(yt,Fr,z,y.headSha)}`,findings:Un.slice(0,Od).map(ee=>({convention_id:ee.convention_id,convention_version:ee.convention_version,severity:ee.severity,action:ee.action,...ee.downgrade_reason?{downgrade_reason:ee.downgrade_reason}:{},summary:ee.summary,matched_changed_symbols:(ee.matched_changed_symbols??[]).slice(0,EO),matched_symbol_count:ee.matched_symbols?.length??0})),...Un.length>Od?{findings_not_shown:Un.length-Od}:{},detector_findings:N.detector_findings??[],policy_source:N.policy_source??null,coverage_note:Ml(y,U?.evaluated_convention_count,S),base:b,local:O,warnings:h}}o(qb,"runAttestReview");var Yb=(()=>{let e=Object.keys(ii),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function Go(e){return jO("sha256").update(e,"utf8").digest("hex")}o(Go,"nodeKeyHash");var UO=["module","class","interface","function","method","type_alias","enum","variable"],Pd=[{name:"codebase_index",description:"Build or update the LOCAL codebase index for the current repo (tree-sitter \u2192 symbol graph in .maind/code-index.sqlite). Runs on this machine; nothing is uploaded. Incremental by default \u2014 only changed files are re-parsed. Call once before codebase_search/trace/map if the index is empty (see codebase_status).",inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Force a full rebuild instead of incremental."}}}},{name:"codebase_status",description:"Report the local codebase index status: file/symbol/edge counts, languages, and when it was last built. Use this to decide whether to run codebase_index first.",inputSchema:{type:"object",properties:{}}},{name:"codebase_search",description:"Search indexed symbols by name/identifier (lexical FTS over function/class/method/\u2026 names, split on camelCase & snake_case). Returns matching symbols with their node_key, file, and line. Feed a node_key into codebase_snippet or codebase_trace.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text (identifier fragments)."},kind:{type:"string",enum:UO,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. For TS/JS, CALLS follow the caller's imports (relative paths, tsconfig aliases, workspace packages, barrels) and include `new`, JSX and module-level code; a method call is linked only when the receiver's declared type or an importable class identifies it. Not modelled: non-call references (type annotations, a function passed as a value) and types inferred through other types \u2014 an empty 'in' is strong evidence, not proof. Python stays name-based.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the "+Yb+" \u2014 ADR-324 \u2014 and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full counts as a complete check. This two-step gives an ADVISORY verdict and writes no record: diff_stats carries no commit anchors (MAIND-581). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located. For a gate verdict \u2014 and, for a clean pushed commit, a replayable attestation record \u2014 use attest_review_changes instead: one call, and the bridge sends the payload itself.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"attest_review_changes",description:"Gate verdict for your change in ONE call, computed by the MAIND server (ADR-357) \u2014 and, for a clean pushed commit, recorded as a replayable attestation. The bridge refreshes the local index, enumerates the diff (merge-base of `since` \u2192 HEAD), runs the "+Yb+", builds the attest payload exactly like `maind review --gate`, and sends it to review_verdict itself \u2014 you copy no symbols and no commit hashes. The server matches ALL changed symbols (up to 1000) against its full visible code_review convention set and answers pass|warn|block with cited findings. A RECORD is written only when anyone with the commit can recompute it (`maind verify <run_id>`): `since` given, a clean worktree, HEAD pushed, the range starting where the branch forks off the default branch (so `since` = e.g. 'origin/master'), and nothing that keeps the run from being attestation-grade. Otherwise you still get the verdict, and `record.reason` names the step that leads to a record. THIS TOOL UPLOADS, unlike the codebase_* tools: symbol names and qualified names, kinds, languages, change grades and changed-line counts; closed-enum risk flags; detector ids, rule ids, levels and evidence HASHES; file counts; commit hashes; this repo's project_key hash. Never paths, source, detector titles or reasons. Call this WHEN: (a) your work is committed and pushed and you are about to open or update a PR \u2014 pass `since` = the branch's base (e.g. 'origin/master'); (b) a reviewer or CI needs a verdict with provenance, not an advisory list; (c) you want to see how uncommitted work fares against the gate \u2014 omit `since` (judged, never recorded). To iterate on local edits, codebase_review_changes is cheaper and uploads nothing. review_verdict is a Team-plan feature. Read `verdict` and `record` first; `ok: false` always carries an `error` code and a `hint`.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref the change is based on (e.g. 'origin/master', a SHA). Reviewed range: merge-base(since, HEAD) \u2192 HEAD. A record is written only when this range starts where the branch forks off the default branch. Omit to judge your uncommitted work against HEAD (never recorded)."},include_uncommitted:{type:"boolean",description:"With `since`: also include uncommitted changes \u2014 judged, never recorded (a dirty worktree cannot be recomputed). Default false; ignored without `since`."},persist:{type:"boolean",description:"Record the run when it is replayable (default true). false = verdict only, nothing written."},dir:{type:"string",description:`A path inside the repository to review (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 e.g. "Asgard/Maind". The record is filed under THAT repository's origin remote. Omit for the workspace repo. A path that cannot be located answers dir_not_found \u2014 nothing is sent.`}}},annotations:{title:"Attested review verdict",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Md=new Map([["codebase_review_verdict","attest_review_changes"]]),Zb=new Set([...Pd.map(e=>e.name),...Md.keys()]),$d=new Set(["attest_review_changes",...[...Md].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function Qb(e,t,n,r){if(!$d.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await qb(e,n,r),s=Md.get(t);return s?{...i,renamed:{from:t,to:s,note:`${t} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}o(Qb,"dispatchCloudBackedTool");function se(e){return typeof e=="string"&&e.length>0?e:void 0}o(se,"str");function Nn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Nn,"num");function Jb(e){if(e===void 0)return{repoRoot:he(),scanDirs:void 0};let t=vr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(Jb,"anchorRepo");function Xb(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}o(Xb,"dirNotFound");async function ew(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,s=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=se(n.for_path);if(i!==void 0){let u=Z_(i);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let p=await pn(u.repoRoot,u.repoRelPath,{minFiles:r}),f=p.namespace,h=o(y=>y===null?null:`${f?.prefix??""}${y}`,"full"),g=f===null?"no_opinion":p.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:p.path,repo_root:u.repoRoot,namespace:f===null?null:{dir:f.dir,prefix:f.prefix,file_count:f.fileCount},number:h(p.number),taken:g==="no_opinion"?null:p.taken,suggestion:h(p.suggestion),held_by:p.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":p.taken?`${h(p.number)} is already held (see held_by). Create the file as ${h(p.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(p.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,p=[];for(let S of s){let k=vr(S);if(k===null){p.push(S);continue}let v=u.get(k.repoRoot)??new Set;v.add(k.repoRelDir),u.set(k.repoRoot,v)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:p,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let f=[],h=[],g=[],y=[];for(let[S,k]of u){let v=[...k],T=v.includes(""),O=await un(S,{dirs:T?void 0:v,minFiles:r});f.push({repo_root:S,dirs:T?null:v}),h.push(...O.findings),g.push(...O.facts.namespaces.map(j=>({repo_root:S,dir:j.dir,prefix:j.prefix,file_count:j.fileCount}))),y.push(...O.facts.skipped)}let b=h.filter(S=>S.status==="open"),w=h.filter(S=>S.status==="info"),x=p.length>0?` ${p.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:b.length===0,open_count:b.length,preexisting_count:w.length,findings:b,preexisting:w.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:g,skipped:y,scanned:f,...p.length>0?{unresolved_dirs:p}:{},hint:(b.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${b.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+x}}let a=he(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:se(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(p=>typeof p=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=o(p=>r.findings.filter(f=>f.status===p),"of"),s=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=s.filter(p=>p.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:s.length,warn_count:a.length,preexisting_count:c.length,findings:[...s,...a],preexisting:c.map(p=>p.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${s.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${s.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=se(n.dir),i,s;if(r!==void 0){let u=vr(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,s=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=he(),s=void 0;let a=hn(i,{dirs:s,baseRef:se(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=Jb(se(n.dir));if(r===null)return Xb("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=mn(r.repoRoot,{dirs:r.scanDirs,baseRef:se(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=Jb(se(n.dir));if(r===null)return Xb("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Tl(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:se(n.remote_db_url)}),s=i.facts.projects.map(p=>({dir:p.dir,migration_count:p.migrationCount,verdict:p.verdict,database:{host:p.db.host,port:p.db.port,config_source:p.db.configSource,reachable:p.db.reachable,ledger_count:p.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=o(p=>i.findings.filter(f=>f.status===p),"of"),c=a("open"),l=a("warn"),d=a("info"),u=s.map(p=>p.database.port===null?`${p.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${p.dir}: ${p.database.host}:${p.database.port} (config from ${p.database.config_source}, reachable=${p.database.reachable}, ledger rows=${p.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:s,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(p=>p.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=se(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:se(n.kind),limit:Nn(n.limit)})).map(s=>({...s,nodeKeyHash:Go(s.nodeKey)}))}case"codebase_trace":{let r=se(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Nn(n.max_depth),limit:Nn(n.limit)})}case"codebase_snippet":{let r=se(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:Go(r)}}case"codebase_map":return e.getArchitecture({topN:Nn(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:se(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nn(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:Go(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:se(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nn(n.limit)}),i;if(n.include_history!==!1)try{i=uc(await e.fileHistory({since:se(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:se(n.since)})}catch(l){s=xe(ct(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:Go(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:se(n.since),limit:Nn(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}o(ew,"dispatchLocalTool");var Wo=class{constructor(t=eb,n=null,r=he,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Pd}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&Zb.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=$d.has(i)?await Qb(this.getEngine(),i,s,this.ctx??void 0):await ew(this.getEngine(),i,s),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=J_(a)?`${X_} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(s=>s&&typeof s=="object"?s.name:void 0).filter(s=>typeof s=="string")),i=this.descriptors().filter(s=>!r.has(s.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=$b(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};ur();var HO="/mcp-client-metrics-ingest",BO=4e3,GO="codebase_search_tokens_saved";async function tw(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${yi()}${HO}`,n=new AbortController,r=setTimeout(()=>n.abort(),BO);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:GO,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
1020
- `),!1}finally{clearTimeout(r)}}o(tw,"postSavingsMetric");jd();Vo();jr();qo();Cr();import{join as TP}from"node:path";var AP="<synthetic>";function zw(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:TP(cu,lu(e.cwd),`${e.transcript_stem}.jsonl`)}o(zw,"transcriptPathFromSideChannel");var ra=class{constructor(t){this.deps=t}static{o(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??au)(n,{start:this.offset});for(let s of i.events)if(s.kind==="title"){let a=s.title.trim();a.length>0&&(this.title=a)}else s.kind==="assistant"&&!s.isSidechain&&typeof s.model=="string"&&s.model.length>0&&s.model!==AP&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as RP}from"node:child_process";var CP=8,IP=32;function NP(e){return e.split(`
1021
- `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,IP)}o(NP,"parsePorcelain");function OP(e,t=CP){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(s.length===0||n.includes(s))&&(n.push(s),n.length>=t))break}return n}o(OP,"condenseToDirs");async function qw(e=DP){let t=await e();if(t===null)return null;let n=OP(NP(t));return n.length>0?n:null}o(qw,"deriveWorkingPaths");async function DP(){return await new Promise(e=>{RP("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}o(DP,"defaultGitStatus");var RF=1,CF=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function IF(e){return CF.includes(e)}o(IF,"isHookSubcommand");var NF=6e4;async function OF(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==q()&&_n(e),e;let t=q();if(t!==null)return t;let n=await pr(B);return n===null&&(bn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:B}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1022
- `),process.exit(1)),bn("paired",null,{version:B}),n.apiKey}o(OF,"ensureApiKey");async function DF(e){let t=await pr(B);return t===null&&(bn("auth_failed",`${e}; re-authorization did not complete`,{version:B}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1023
- `),process.exit(1)),bn("paired",null,{version:B}),t.apiKey}o(DF,"reauth");async function PF(){let e=process.argv.slice(2).find(v=>!v.startsWith("-"));if(e==="install"){let v=process.argv.indexOf("install"),T=process.argv.slice(v+1),O=await Ob(T);process.exit(O)}if(e==="doctor"){let{runDoctor:v}=await Promise.resolve().then(()=>(gu(),ov));process.exit(await v(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:v}=await Promise.resolve().then(()=>(lk(),ck));process.exit(await v())}if(e==="on-session-briefing"){let{runOnSessionBriefing:v}=await Promise.resolve().then(()=>(uk(),dk));process.exit(await v())}if(e==="guard"){let v=process.argv.indexOf("guard"),{runGuard:T}=await Promise.resolve().then(()=>(yk(),gk));process.exit(await T(process.argv.slice(v+1)))}if(e==="guard-inject"){let{runGuardInject:v}=await Promise.resolve().then(()=>(Sr(),vb));process.exit(await v())}if(e==="guard-gate"){let{runGuardGate:v}=await Promise.resolve().then(()=>(Ek(),Sk));process.exit(await v())}if(e==="guard-stop"){let{runGuardStop:v}=await Promise.resolve().then(()=>(Rk(),Ak));process.exit(await v())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:v}=await Promise.resolve().then(()=>(Wu(),wk));process.exit(await v())}if(e==="guard-capture"){let{runGuardCapture:v}=await Promise.resolve().then(()=>(Ok(),Nk));process.exit(await v())}if(e==="gateway"){let v=process.argv.indexOf("gateway"),{runGateway:T}=await Promise.resolve().then(()=>(gx(),hx));process.exit(await T(process.argv.slice(v+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:v}=await Promise.resolve().then(()=>(ip(),rp));process.exit(await v())}if(e==="guard-cross-check"){let{runGuardCrossCheck:v}=await Promise.resolve().then(()=>(ip(),rp));process.exit(await v())}if(e==="on-index-refresh"){let{runOnIndexRefresh:v}=await Promise.resolve().then(()=>(op(),sp));process.exit(await v())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:v}=await Promise.resolve().then(()=>(op(),sp));process.exit(await v())}if(e==="on-prompt-context"){let{runOnPromptContext:v}=await Promise.resolve().then(()=>(fp(),pp));process.exit(await v())}if(e==="on-read-context"){let{runOnReadContext:v}=await Promise.resolve().then(()=>(fp(),pp));process.exit(await v())}if(e!==void 0&&IF(e)){let v=await Promise.resolve().then(()=>(ju(),Jv)),T={"on-session-start":v.runOnSessionStart,"on-tool-use":v.runOnToolUse,"on-file-write":v.runOnFileWrite,"on-file-edit":v.runOnFileEdit,"on-repo-health":v.runOnRepoHealth,"on-write-health":v.runOnWriteHealth,"sync-config":v.runSyncConfig,flush:v.runFlush,status:v.runHookStatus}[e];process.exit(await T())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(B+`
1024
- `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(MF(),process.exit(0)),process.argv.includes("--reauth")&&(gi(),await pr(B,process.stdout)===null&&process.exit(1),bn("paired",null,{version:B}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1025
- `),process.exit(0));let t=ne(),n=await OF(),r=Y(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Uo:null,a=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new Wo(void 0,s,void 0,{callCloudTool:o((v,T,O)=>a===null?Promise.resolve({kind:"no_session"}):a.callCloudTool(v,T,O),"callCloudTool"),projectKey:r,engineFor:o(v=>{let T=c.get(v);return T===void 0&&(T=tb(v),c.set(v,T)),T},"engineFor"),projectKeyFor:Zs}),d=`bridge-${AF()}`,u=o(async()=>{if(!s)return;let v=s.takePending();v.tokens<=0||await tw({apiKey:n,deviceId:t,sessionId:d,tokensSaved:v.tokens,bridgeVersion:B})},"flushSavings"),p=s?setInterval(()=>{u()},NF):null;p?.unref();let f=new zo({projectKey:r}),h=new ra({resolvePath:o(()=>zw(f.sideChannel()),"resolvePath"),fallbackModel:o(()=>f.sideChannel()?.model??null,"fallbackModel")}),g=new Ji,y=new Ko({projectKey:r,identity:f,sessionMeta:o(()=>h.read(),"sessionMeta"),postToolCall:o((v,T)=>a===null?Promise.reject(new Error("presence: no active forwarder")):a.postPresenceToolCall(v,T),"postToolCall"),deriveWorkingPaths:o(()=>qw(),"deriveWorkingPaths"),snapshot:r!==null?$F(pw({projectKey:r}),g):void 0}),b=y.isEnabled?setInterval(()=>{y.pollActivity()},iw):null;if(b?.unref(),y.isEnabled){let v=o(T=>{y.end().finally(()=>process.exit(T))},"endAndExit");process.on("SIGTERM",()=>v(143)),process.on("SIGINT",()=>v(130))}let w=!1,x=o(v=>{if(w||v!=="codex")return;w=!0,setTimeout(()=>{Promise.resolve().then(()=>(Id(),Ib)).then(({refreshAgentsMdConventions:O})=>O(v,{apiKey:n,projectKey:r})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),S=0,k=Hl();try{for(;;){let v=a?.carryOver()??null,T=new qs({apiKey:n,deviceId:t,bridgeVersion:B,projectKey:r,localRouter:l,presence:y,onConnectionOutcome:o((O,j)=>bn(O,j,{version:B}),"onConnectionOutcome"),onSessionReady:o(({clientFamily:O})=>x(O),"onSessionReady"),assignedInbox:g,carry:v});a=T;try{await T.run(k);return}catch(O){if(O instanceof hi&&S<RF){S+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${O.message}; re-authorizing\u2026
1026
- `),n=await DF(O.reason);continue}throw O}}}finally{p&&clearInterval(p),b&&clearInterval(b),await y.end(),await u()}}o(PF,"main");function MF(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge doctor --remove-phantoms [--yes]"," # list (then remove) maind entries of clients that are not installed"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-session-briefing add the session briefing + project conventions at session start (MAIND-620, never blocks)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture] logged override'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop,"," guard-cross-observe, guard-cross-check, guard-difficulty, guard-outcome, guard-capture)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the conventions block in AGENTS.md for Codex (ADR-359 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
1027
- `))}o(MF,"printHelp");PF().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1028
- `),process.exit(1)});function $F(e,t){return{...e,write(n,r){try{t.update(n)}catch{}e.write(n,r)}}}o($F,"withAssignedCapture");
1017
+ `),t.exitCode()}o(DO,"runHooksOnly");Bt();Bt();import{readFileSync as PO}from"node:fs";import{join as Bb}from"node:path";function Go(e){return e?Math.ceil(e.length/4):0}o(Go,"estimateTokens");var Gb=1e6,Wo=class{static{o(this,"SavingsAggregator")}pendingTokens=0;pendingCalls=0;add(t){!Number.isFinite(t)||t<=0||(this.pendingTokens+=Math.floor(t),this.pendingCalls+=1)}hasPending(){return this.pendingTokens>0}takePending(){let t={tokens:this.pendingTokens,calls:this.pendingCalls};return this.pendingTokens=0,this.pendingCalls=0,t}};function Wb(e){try{let t=PO(e,"utf8");return t.length>Gb?t.slice(0,Gb):t}catch{return""}}o(Wb,"readFileCapped");function MO(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=n?.filePath;typeof r=="string"&&r.length>0&&t.add(r)}return[...t]}o(MO,"distinctFilePaths");function Kb(e,t,n,r){try{let i=Go(n);if(e==="codebase_search"){let s=MO(t);if(s.length===0)return 0;let a=0;for(let c of s)a+=Go(Wb(Bb(r,c)));return Math.max(0,a-i)}if(e==="codebase_snippet"){let s=t?.filePath;if(typeof s!="string"||s.length===0)return 0;let a=Go(Wb(Bb(r,s)));return Math.max(0,a-i)}return 0}catch{return 0}}o(Kb,"measureLocalToolSaved");It();Bt();import{createHash as nD}from"node:crypto";It();import{execFileSync as jO}from"node:child_process";import{createHash as UO}from"node:crypto";Bt();Fd();import{realpathSync as Xb}from"node:fs";function HO(e,t){try{return Xb(e)===Xb(t)}catch{return e===t}}o(HO,"samePath");var jd=30,BO=10,Zb=20,GO=new Map;function Ud(e){return e instanceof Error?e.message:String(e)}o(Ud,"msg");function Vo(e){let t=e.split(`
1018
+ `,1)[0]??"";return t.length>300?`${t.slice(0,300)}\u2026`:t}o(Vo,"firstLine");var Qb=o(e=>e?e.slice(0,12):"?","short");async function WO(e,t,n,r){let i=await e.status(),s=!i.indexed||i.fileCount===0,a=await Jb(t,async()=>{try{return{ok:!0,stats:await e.indexRepository()}}catch(c){return{ok:!1,error:Ud(c)}}},n);return a.locked?a.value.ok?s?(r.push(`no local index found \u2014 built it now (${a.value.stats.filesParsed} file(s), ${Math.round(a.value.stats.durationMs/1e3)} s).`),{action:"built",files_parsed:a.value.stats.filesParsed,missing:!1}):{action:"refreshed",files_parsed:a.value.stats.filesParsed,missing:!1}:(s||r.push(`index refresh failed \u2014 continuing with the existing index: ${a.value.error}`),{action:"kept",note:"refresh_failed",missing:s}):(s||r.push("another process holds the index lock (the Stop hook's refresh?) \u2014 reviewing with the existing index; stale files degrade to co_located and keep the run from being attestation-grade."),{action:"kept",note:"lock_busy",missing:s})}o(WO,"refreshIndex");function KO(e,t,n){return t===void 0?!e.dirty:typeof e.mergeBaseSha=="string"&&e.mergeBaseSha===e.headSha&&(!n||!e.dirty)}o(KO,"isEmptyRange");function VO(e){let t=o(r=>`${r.detector_id}\0${r.rule_id}\0${r.title}`,"key"),n=new Set(e.commit.local.map(t));return e.local.local.filter(r=>!n.has(t(r)))}o(VO,"localOnly");function zO(e){let t=[],n=e.diff_stats;return e.base_sha||t.push("base_sha_missing"),n.stale_file_count!==0&&t.push("stale_files"),n.truncated!==!1&&t.push("truncated"),n.hunk_coverage!=="full"&&t.push("hunk_coverage_not_full"),n.detector_coverage!=="full"&&t.push("detector_coverage_not_full"),t}o(zO,"localGradeBlockers");function qO(e){if(!e.persistWanted)return{persist:!1,skipped:"no_report"};if(e.since===void 0)return{persist:!1,skipped:"no_base"};if(e.result.dirty)return{persist:!1,skipped:"dirty_tree"};let t=Hl(!1,e.projectKey,e.result);if(!t.persist)return t;let n=zO(e.payload);return n.length>0?{persist:!1,skipped:"not_grade_eligible",detail:n}:e.git===null||e.git.defaultBranch===null||e.git.forkPoint===null?{persist:!1,skipped:"fork_point_unknown",detail:[e.git?.defaultBranch?`origin/${e.git.defaultBranch}`:"no default branch"]}:e.git.forkPoint!==e.result.mergeBaseSha?{persist:!1,skipped:"base_not_fork_point",detail:[e.result.mergeBaseSha??"?",e.git.forkPoint,`origin/${e.git.defaultBranch}`]}:e.git.pushed?e.recordedRunId!==null?{persist:!1,skipped:"already_recorded",detail:[e.recordedRunId]}:{persist:!0,skipped:null}:{persist:!1,skipped:"head_not_pushed"}}o(qO,"bridgePersistDecision");function ew(e,t){try{return jO("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()}catch{return null}}o(ew,"git");function YO(e,t){let n=ei(e),r=n&&ew(e,["merge-base",t,`origin/${n}`])||null,i=ew(e,["for-each-ref","--contains",t,"--format=%(refname)","refs/remotes"]);return{defaultBranch:n,forkPoint:r,pushed:i!==null&&i.length>0}}o(YO,"gitPersistFacts");function JO(e,t){return UO("sha256").update(`${e??""}
1019
+ ${JSON.stringify(t)}`).digest("hex")}o(JO,"payloadKey");function Ge(e,t,n){return{kind:"error",error:e,message:t,hint:n}}o(Ge,"fail");var In="The local review is unaffected \u2014 codebase_review_changes still works without the server.";function tw(e){let t=Gl(e);if(t!==null&&Wl(t))return Ge("server_predates_attest_mode","the MAIND server predates attest mode (< 0.62.0): it rejected a review_verdict call without `findings`.","No fallback: the legacy two-call path only yields an advisory verdict. For that today use codebase_review_changes \u2192 review_changes \u2192 review_verdict.");if(t?.kind==="invalid_params"){let n=t.issues[0];return Ge("attest_rejected",`the server rejected the attest payload${n?` at ${(n.path??[]).join(".")||"(root)"}: ${n.message??n.code??"invalid"}`:""}.`,"This is a bridge/server version mismatch, not a problem with your change. Update the bridge (`npx -y @maind-dev/mcp-bridge@latest`) and call again; if it persists, report it.")}return Ge("cloud_unavailable",`review_verdict failed: ${Vo(t?.detail??e)||"no detail"}`,In)}o(tw,"fromProtocolText");function XO(e,t,n){switch(e.kind){case"no_session":return Ge("cloud_unavailable","no MCP session with the MAIND server \u2014 the client never completed its handshake through this bridge.",`Retry once the MAIND cloud tools respond. ${In}`);case"transport_error":return e.timedOut?Ge("cloud_timeout",`review_verdict did not answer within ${Math.round(t/1e3)} s.`,n?"The call asked for a record, and the server may still have written one. Check before calling again: `maind verify --commit HEAD`.":"The call asked for no record, so nothing was written. Call again when the server responds."):Ge("cloud_unavailable",`network error: ${e.message}`,In);case"http_error":return e.status===401?Ge("auth_rejected",`the MAIND server rejected this bridge's key (HTTP 401): ${Vo(e.body)}`,"If the key was revoked or rebound, the next forwarded MAIND call starts the re-authorization; otherwise run `npx -y @maind-dev/mcp-bridge --reauth`."):e.status===413?Ge("payload_too_large","the attest payload exceeded the server's request limit (HTTP 413).","Symbols are never cut to fit \u2014 a shortened list would attest a review that did not happen. Split the change into smaller commits or pull requests."):Ge("cloud_unavailable",`HTTP ${e.status}: ${Vo(e.body)}`,In);case"rpc_error":return tw(`MCP error ${e.code}: ${e.message}`);case"result":{if(e.isError)return tw(e.text);let r;try{r=JSON.parse(e.text)}catch{return Ge("cloud_unavailable",`review_verdict returned non-JSON text: ${Vo(e.text)}`,In)}return typeof r!="object"||r===null?Ge("cloud_unavailable","review_verdict returned no object",In):{kind:"verdict",body:r}}}}o(XO,"interpretOutcome");var ZO="review_verdict \u2014 and with it this tool \u2014 is a Team-plan feature. codebase_review_changes still gives you the advisory review (https://maind.dev/pricing).",QO={dirty:"commit (or stash) your changes \u2014 a dirty worktree cannot be recomputed",base_kind_not_ref:"pass `since` \u2014 only a committed range is replayable",base_sha_missing:"pass `since` \u2014 only a committed range is replayable",stale_files:"the index was stale for changed files \u2014 run codebase_index, then call again",truncated:"more than 1000 changed symbols, or labels beyond the schema \u2014 split the change",hunk_coverage_not_full:"some changes could not be line-graded (binary or unusual diffs)",detector_coverage_not_full:"a repo-health detector could not run \u2014 see local.detectors",merge_base_missing:"no merge-base with `since` (shallow clone?) \u2014 fetch the full history",private_citation:"a finding cites a private convention \u2014 not verifiable by others"},nw=o(e=>e.map(t=>QO[t]??t).join("; "),"adviceFor");function eD(e,t){switch(e){case"no_report":return"persist: false \u2014 verdict only, nothing recorded.";case"no_head":return"no HEAD commit \u2014 there is nothing a record could be anchored to.";case"no_project_key":return"no origin remote, so no project_key to file a record under \u2014 the verdict is computed but not recorded.";case"no_merge_base":return"no merge-base between HEAD and `since` (shallow clone?) \u2014 the verdict is computed but not recorded; fetch the full history.";case"no_base":return"uncommitted work is judged but never recorded. Commit and push, then call again with `since` = the branch's base (e.g. origin/master).";case"dirty_tree":return"the worktree has uncommitted or untracked changes \u2014 a record attests a commit, and a dirty tree cannot be recomputed. Commit (or stash) them, then call again.";case"not_grade_eligible":return`this run could not be attestation-grade (${(t??[]).join(", ")}), and only replayable runs are recorded. To fix: ${nw(t??[])}.`;case"fork_point_unknown":return`the branch's fork point is unknown (${(t??[]).join(", ")||"no default branch"}): no origin/HEAD, origin/main or origin/master resolves, or it shares no history with HEAD. Without it the reviewed range cannot be checked to cover the whole branch. Fetch the default branch, then call again.`;case"base_not_fork_point":{let[n,r,i]=t??[];return`the reviewed range starts at ${Qb(n)}, but this branch forks off ${i??"the default branch"} at ${Qb(r)} \u2014 a record over a different range could stand in for the full review of this commit. Call again with \`since\` = ${i??"the default branch"}.`}case"head_not_pushed":return"HEAD is on no remote-tracking branch \u2014 nobody else could fetch the commit to recompute the record, and an amend or rebase would orphan it. Push, then call again with the same `since`.";case"already_recorded":return`this bridge already recorded the identical run as ${(t??[])[0]??"an earlier run"} \u2014 nothing changed since.`;default:return null}}o(eD,"skipText");function tD(e,t,n,r){if(e.persisted){if(t===!0)return`Recorded as attestation-grade run ${e.run_id} (format 3). Recompute it: \`maind verify ${e.run_id}\``+(r?` \u2014 a teammate: \`maind verify --commit ${r}\`.`:".");let c=nw(n);return`Recorded as run ${e.run_id}, but NOT attestation-grade (${n.join(", ")||"no reason given"}). `+(c?`To fix: ${c}.`:"")}let i=e.reason??"",s=eD(i,e.detail),a=t===!0&&i!=="no_report"?" The run itself is attestation-grade.":"";return s!==null?`Not recorded: ${s}${a}`:`Not recorded (${i||"the server gave no reason"}).${a}`}o(tD,"recordHint");async function rw(e,t,n){let r=n.repoRoot??he(),i=r,s=e,a=n.projectKey,c=typeof t.dir=="string"&&t.dir.length>0?t.dir:void 0;if(c!==void 0){let te=xr(c,r);if(te===null)return{ok:!1,error:"dir_not_found",message:`the path ${JSON.stringify(c)} could not be located \u2014 no repository was reviewed, nothing was sent.`,hint:"Pass a path that exists relative to the workspace (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};if(!HO(te.repoRoot,r)){if(n.engineFor===void 0)return{ok:!1,error:"dir_unsupported",message:"this bridge process cannot open a second repository's index.",hint:"Run the review from a session whose workspace is that repository."};i=te.repoRoot,s=n.engineFor(i),a=n.projectKeyFor?.(i)??null}}let l=typeof t.since=="string"&&t.since.length>0?t.since:void 0,d=l!==void 0&&t.include_uncommitted===!0,u=t.persist!==!1,f=n.timeoutMs??9e4,p=n.recorded??GO,h=[],g=await WO(s,i,n.lock,h);if(g.missing)return{ok:!1,error:"index_unavailable",message:g.note==="lock_busy"?"there is no local index yet, and another process held the index lock for the whole wait.":"there is no local index yet, and building it failed.",hint:"Run codebase_index, then call again.",warnings:h};let y=await s.reviewChanges(jl(l,d)),b={repo_root:i,since:l??null,include_uncommitted:l===void 0?!0:d,base_kind:y.baseKind,base_sha:y.baseSha,merge_base_sha:y.mergeBaseSha??null,head_sha:y.headSha,dirty:y.dirty};if(KO(y,l,d))return{ok:!1,error:"empty_range",message:l===void 0?"no uncommitted changes \u2014 there is nothing to judge.":`HEAD is the merge-base with ${l} \u2014 the committed range is empty${d?" and the worktree is clean":""}.`,hint:"Commit your work on a branch, then pass `since` = the branch's base (e.g. origin/master). A record over an empty range would read as a pass over nothing.",base:b,warnings:h};let w;try{w=await s.reviewDetectorScopes({baseRef:l})}catch(te){let Sf=xe(lt(`reviewDetectorScopes failed: ${Ud(te)}`));w={commit:Sf,local:Sf},h.push(`repo-health detectors unavailable (${Ud(te)}) \u2014 sent as 'unavailable', not attestation-grade.`)}let{payload:k,dropped:S}=Ul(y,w.commit);S>0&&h.push(`${S} symbol(s) exceed the server schema (name > ${zs} or qualified name > ${qs} chars) and were left out \u2014 this run is not attestation-grade.`);let x=JO(a,k),v=u&&l!==void 0&&!y.dirty&&typeof y.headSha=="string",E=qO({persistWanted:u,since:l,projectKey:a,result:y,payload:k,git:v?(n.persistFacts??YO)(i,y.headSha):null,recordedRunId:p.get(x)??null}),N={changed_files:y.changedFiles,indexed_files:y.indexedFiles,stale_files:y.staleFiles,symbols_sent:k.changed_symbols.length,symbols_dropped:S,risk_flags:y.riskFlags,index:{action:g.action,...g.files_parsed!==void 0?{files_parsed:g.files_parsed}:{},...g.note?{note:g.note}:{}},detectors:{coverage:w.commit.coverage,findings:w.commit.local.slice(0,Zb),local_only:VO(w).slice(0,Zb)}},F=await n.callCloudTool("review_verdict",{attest:k,persist:E.persist,...a?{project_key:a}:{}},{timeoutMs:f}),H=XO(F,f,E.persist);if(H.kind==="error")return{ok:!1,error:H.error,message:H.message,hint:H.hint,base:b,local:N,warnings:h};let P=H.body;if(P.ok!==!0){let te=P.error==="requires_team"||P.error==="requires_enterprise";return{ok:!1,error:P.error??"unknown_error",message:P.message??"review_verdict returned no message",hint:te?ZO:P.hint??In,base:b,local:N,warnings:h}}if(P.mode!=="attest")return{ok:!1,error:"attest_echo_missing",message:"review_verdict answered without the attest-mode echo (mode: 'attest').",hint:"Refusing to present it as a server-matched verdict. Update the bridge and call again; if it persists, report it.",base:b,local:N,warnings:h};let L=P.attest,G=P.run??null,yt=G&&typeof G.id=="string"?{persisted:!0,run_id:G.id,commit_sha:G.commit_sha??null,attestation_format:G.attestation_format??null}:{persisted:!1,reason:E.skipped??P.run_note??"not_persisted",...E.detail?{detail:E.detail}:{}};yt.persisted&&p.set(x,G.id);let jr=typeof L?.attestation_grade=="boolean"?L.attestation_grade:null,q=Array.isArray(L?.grade_blockers)?L.grade_blockers:[],be=P.counts??{},Hn=Array.isArray(P.findings)?P.findings:[],dS=`Verdict ${P.verdict??"?"}: ${be.block??0} block, ${be.warn??0} warn, ${be.note??0} note`+(P.verdict==="block"?" \u2014 resolve the blocking findings before merging.":".");return{ok:!0,verdict:P.verdict??null,counts:be,record:yt,attest:L?{attestation_grade:jr,grade_blockers:q,attestation_format:L.attestation_format??null,input_hash:L.input_hash??null,policy_hash:L.policy_hash??null,evaluated_convention_count:L.evaluated_convention_count??null,detector_coverage:L.detector_coverage??null}:null,hint:`${dS} ${tD(yt,jr,q,y.headSha)}`,findings:Hn.slice(0,jd).map(te=>({convention_id:te.convention_id,convention_version:te.convention_version,severity:te.severity,action:te.action,...te.downgrade_reason?{downgrade_reason:te.downgrade_reason}:{},summary:te.summary,matched_changed_symbols:(te.matched_changed_symbols??[]).slice(0,BO),matched_symbol_count:te.matched_symbols?.length??0})),...Hn.length>jd?{findings_not_shown:Hn.length-jd}:{},detector_findings:P.detector_findings??[],policy_source:P.policy_source??null,coverage_note:Bl(y,L?.evaluated_convention_count,S),base:b,local:N,warnings:h}}o(rw,"runAttestReview");var iw=(()=>{let e=Object.keys(si),t=e.map(n=>n.replace(/^det_/,"").replace(/_/g," "));return`${e.length} built-in repo-health detectors (${t.join(", ")})`})();function zo(e){return nD("sha256").update(e,"utf8").digest("hex")}o(zo,"nodeKeyHash");var rD=["module","class","interface","function","method","type_alias","enum","variable"],Hd=[{name:"codebase_index",description:"Build or update the LOCAL codebase index for the current repo (tree-sitter \u2192 symbol graph in .maind/code-index.sqlite). Runs on this machine; nothing is uploaded. Incremental by default \u2014 only changed files are re-parsed. Call once before codebase_search/trace/map if the index is empty (see codebase_status).",inputSchema:{type:"object",properties:{full:{type:"boolean",description:"Force a full rebuild instead of incremental."}}}},{name:"codebase_status",description:"Report the local codebase index status: file/symbol/edge counts, languages, and when it was last built. Use this to decide whether to run codebase_index first.",inputSchema:{type:"object",properties:{}}},{name:"codebase_search",description:"Search indexed symbols by name/identifier (lexical FTS over function/class/method/\u2026 names, split on camelCase & snake_case). Returns matching symbols with their node_key, file, and line. Feed a node_key into codebase_snippet or codebase_trace.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text (identifier fragments)."},kind:{type:"string",enum:rD,description:"Restrict to a symbol kind."},limit:{type:"number",description:"Max results (default 20)."}},required:["query"]}},{name:"codebase_trace",description:"Traverse the call/dependency graph from a symbol. direction 'out' = what this symbol calls/contains/imports; 'in' = what calls/depends on it. Returns edges as node_key \u2192 node_key with the edge kind. For TS/JS, CALLS follow the caller's imports (relative paths, tsconfig aliases, workspace packages, barrels) and include `new`, JSX and module-level code; a method call is linked only when the receiver's declared type or an importable class identifies it. Not modelled: non-call references (type annotations, a function passed as a value) and types inferred through other types \u2014 an empty 'in' is strong evidence, not proof. Python stays name-based.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"Start symbol's node_key (from codebase_search)."},direction:{type:"string",enum:["out","in"],description:"Traversal direction (default out)."},max_depth:{type:"number",description:"BFS depth 1\u20135 (default 3)."},limit:{type:"number",description:"Max edges returned (default 100)."}},required:["node_key"]}},{name:"codebase_snippet",description:"Return the exact source text of a symbol by node_key (read locally from disk \u2014 never uploaded). Use after codebase_search/trace to read a function/class without opening the file.",inputSchema:{type:"object",properties:{node_key:{type:"string",description:"The symbol's node_key."}},required:["node_key"]}},{name:"codebase_map",description:"Architecture overview of the indexed repo: symbol-kind distribution, languages, and the most-imported (highest fan-in) modules \u2014 a cheap way to orient in an unfamiliar codebase.",inputSchema:{type:"object",properties:{top_n:{type:"number",description:"How many top modules to list (default 10)."}}}},{name:"codebase_changes",description:"Enumerate the symbols in files you changed (git diff/status against the LOCAL index \u2014 runs on this machine, nothing is uploaded). Call after finishing an edit batch, before committing. The output includes a ready-to-paste `briefing_args` block with paths deliberately stripped \u2014 feed it to the cloud tool codebase_change_briefing to get the maind conventions and lessons that apply to exactly these symbols. Requires a built index (codebase_index) for symbol enumeration; files without index rows are counted but contribute no symbols.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."}}}},{name:"codebase_review_changes",description:"Review-grade change enumeration (ADR-228): like codebase_changes, but hunk-aware \u2014 each symbol is graded added|modified|co_located by intersecting git diff hunks with symbol spans (runs on this machine, nothing is uploaded), plus closed-enum risk_flags from the raw path list (SQL migrations, RLS/SECURITY DEFINER, CI workflows, env files \u2014 files the index itself cannot see). The output's `review_args` block is path-free by construction \u2014 feed it to the cloud tool review_changes for provenance-backed convention findings. It ALSO runs the "+iw+" \u2014 ADR-324 \u2014 and emits a `verdict_args` block for the cloud tool review_verdict: `detector_findings` carry ids, rules, level/baseline and an evidence HASH only (paths, tokens, class and table names stay in the local `detectors` block, never on the wire); `[]` means the detectors ran and found nothing, which is a finding \u2014 do not drop the key. `diff_stats.detector_coverage` says whether every detector ran or honestly abstained (full), one could not run or grade (partial), or none ran (none) \u2014 only full counts as a complete check. This two-step gives an ADVISORY verdict and writes no record: diff_stats carries no commit anchors (MAIND-581). Requires a FRESH index (codebase_index) \u2014 stale files degrade honestly to co_located. For a gate verdict \u2014 and, for a clean pushed commit, a replayable attestation record \u2014 use attest_review_changes instead: one call, and the bridge sends the payload itself.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref to diff against (e.g. 'main', a SHA). Default: HEAD (= your uncommitted work)."},include_uncommitted:{type:"boolean",description:"Include uncommitted/untracked changes (default true). false requires `since`."},limit:{type:"number",description:"Max symbols (default 64, cap 200)."},include_history:{type:"boolean",description:"Attach a counts-only regression context (`history`: churn/authors/age as NUMBERS \u2014 no names, subjects, or paths) to review_args for the cloud review (default true)."}}}},{name:"attest_review_changes",description:"Gate verdict for your change in ONE call, computed by the MAIND server (ADR-357) \u2014 and, for a clean pushed commit, recorded as a replayable attestation. The bridge refreshes the local index, enumerates the diff (merge-base of `since` \u2192 HEAD), runs the "+iw+", builds the attest payload exactly like `maind review --gate`, and sends it to review_verdict itself \u2014 you copy no symbols and no commit hashes. The server matches ALL changed symbols (up to 1000) against its full visible code_review convention set and answers pass|warn|block with cited findings. A RECORD is written only when anyone with the commit can recompute it (`maind verify <run_id>`): `since` given, a clean worktree, HEAD pushed, the range starting where the branch forks off the default branch (so `since` = e.g. 'origin/master'), and nothing that keeps the run from being attestation-grade. Otherwise you still get the verdict, and `record.reason` names the step that leads to a record. THIS TOOL UPLOADS, unlike the codebase_* tools: symbol names and qualified names, kinds, languages, change grades and changed-line counts; closed-enum risk flags; detector ids, rule ids, levels and evidence HASHES; file counts; commit hashes; this repo's project_key hash. Never paths, source, detector titles or reasons. Call this WHEN: (a) your work is committed and pushed and you are about to open or update a PR \u2014 pass `since` = the branch's base (e.g. 'origin/master'); (b) a reviewer or CI needs a verdict with provenance, not an advisory list; (c) you want to see how uncommitted work fares against the gate \u2014 omit `since` (judged, never recorded). To iterate on local edits, codebase_review_changes is cheaper and uploads nothing. review_verdict is a Team-plan feature. Read `verdict` and `record` first; `ok: false` always carries an `error` code and a `hint`.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Git ref the change is based on (e.g. 'origin/master', a SHA). Reviewed range: merge-base(since, HEAD) \u2192 HEAD. A record is written only when this range starts where the branch forks off the default branch. Omit to judge your uncommitted work against HEAD (never recorded)."},include_uncommitted:{type:"boolean",description:"With `since`: also include uncommitted changes \u2014 judged, never recorded (a dirty worktree cannot be recomputed). Default false; ignored without `since`."},persist:{type:"boolean",description:"Record the run when it is replayable (default true). false = verdict only, nothing written."},dir:{type:"string",description:`A path inside the repository to review (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 e.g. "Asgard/Maind". The record is filed under THAT repository's origin remote. Omit for the workspace repo. A path that cannot be located answers dir_not_found \u2014 nothing is sent.`}}},annotations:{title:"Attested review verdict",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},{name:"codebase_history",description:"Git history for files/directories \u2014 recent commits, ownership ('who worked here last / most'), and an optional regression window ('what changed in X since Y'). Runs on this machine via local git, nothing is uploaded; output may include commit authors and subjects, which stay local BY DESIGN (Phase B privacy: history is never synced to the cloud \u2014 do not paste author/subject data into cloud tools). Works without a built index. When paths is omitted, defaults to the files you currently changed. Ownership is aggregated over a bounded recent-commit window (reported as ownership_window_commits).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Files or directories to inspect (repo-relative). Default: your currently changed files. Cap 50."},since:{type:"string",description:"Regression window start: a git ref (resolved first) or a date string (e.g. '2026-06-01'). Omit for recent+ownership only."},limit:{type:"number",description:"Max recent commits per path (default 20, cap 100)."},include_ownership:{type:"boolean",description:"Aggregate per-path ownership (default true)."}}}},{name:"check_divergence",description:"Local silent-divergence detector (ADR-238): check whether the repo/worktree state has quietly diverged from what git/CLI success messages imply \u2014 the recurring AI-coding failure where a command reports 'ok / up to date / done' while upstream, worktree, or release state is actually wrong. Runs entirely on this machine (git + fs), nothing is uploaded. Returns findings in the open|warn|info vocabulary with fix hints, covering: branch/remote (no upstream, upstream tracking the WRONG branch, never-pushed, ahead/behind/diverged), worktree (detached HEAD, in-progress rebase/merge, uncommitted work on the shared base tree, a COMMIT on the shared base tree \u2014 one that a branch switch undone by a parallel session redirected there, which no success message reports and which `git push` would make worse, tooling files missing vs the main checkout so tools silently target the wrong project, and a workspace package whose build/dist artifacts are OLDER than its src \u2014 after a rebase/pull nothing rebuilds, so typecheck reads stale types and fails on code you never touched while CI stays green), and release (all CI checks red \u2192 suspect account/billing/quota, not your code). Call this WHEN: (a) you are about to recommend or run git push / a deploy / a release; (b) a git/supabase/CLI command reported success but the result looks wrong; (c) at the start of work in a fresh worktree or right after a rebase/pull that touched workspace packages. An 'open' finding means proceed only after it is resolved or the user explicitly acknowledges it. VERDICTS: `clean` (measured, nothing open or warn), `diverged` (measured, at least one), `no_opinion` (the directory is not a git work tree \u2014 nothing was examined). Read the verdict, never `findings.length` alone: an empty finding list under `no_opinion` is an ABSTENTION, not a pass, and `ok` is false. A directory outside a repository never gets a green tick.",inputSchema:{type:"object",properties:{include_release:{type:"boolean",description:"Query gh for the all-checks-red signal (default true). Set false for a fully offline check."},probe_paths:{type:"array",items:{type:"string"},description:"Extra repo-relative worktree-parity probe paths, beyond the defaults + a committed .maind/worktree-requirements manifest."}}}},{name:"check_number_collisions",description:"Local guard against a numbered namespace being claimed twice (ADR-250): filenames carrying a sequential counter \u2014 ADR-248-*.md, 0001-use-postgres.md (adr-tools), RFC-12-*, Supabase migration slots \u2014 are a distributed counter with NO allocator. Two parallel agent sessions each list the directory, each see N as the highest, each write N+1: both are individually correct and the duplicate exists only in the union on the default branch, where it surfaces at merge time (or, for migrations, as a silently skipped push). Runs entirely on this machine (git + fs), nothing is uploaded. Namespaces are DISCOVERED, not configured \u2014 no prefix is hardcoded, and date-stamped families (BRIEF-2026-\u2026) are rejected because a counter's numbers are near-unique while a date family's repeat. Consults four sources, and the fourth is the point: the default branch, all other local branches, all SIBLING WORKTREES INCLUDING THEIR UNCOMMITTED FILES, and your own tree \u2014 the competing file is typically in no pushed commit yet. Findings use open|warn|info: `open` = THIS branch introduces the clash (act on it), `info` = the collision predates your work (inventory, not your problem). Call this WHEN: (a) you are about to create a file in a numbered series \u2014 an ADR, RFC, migration, numbered spec \u2014 and picked the number by listing the directory; (b) before pushing a branch that adds such a file; (c) a merge conflicted in an index/README that lists numbered documents. An `open` finding means renumber BEFORE pushing \u2014 resolving it after the merge means rewriting every reference. (d) BEST of all, pass `for_path` with the path you are about to create and get the verdict plus the next free number BEFORE the file exists \u2014 the only moment where fixing it costs one filename instead of a filename plus every index entry, link and comment that names it (ADR-263).",inputSchema:{type:"object",properties:{dirs:{type:"array",items:{type:"string"},description:'Restrict detection to these directories (default: the workspace repo). Each dir is resolved FROM ITS OWN PATH (absolute, or relative to the workspace / cwd) and scanned in the repository it belongs to \u2014 nested checkouts work when you give their prefix, e.g. "Asgard/docs/adr". Dirs that cannot be located are listed in `unresolved_dirs` and NOT scanned; if none resolve, the answer is `verdict: "no_opinion"` \u2014 an abstention, not collision-free. `scanned` shows which repo root was actually swept.'},min_files:{type:"number",description:"How many files must share a prefix before it counts as a namespace (default 3). Lower it to cover a young series that is still below the threshold."},for_path:{type:"string",description:'A path you are ABOUT to create, e.g. "docs/adr/ADR-263-retry-policy.md". Switches the tool from auditing what exists to answering the allocator question for a file that does not exist yet: is that number already held, and which is the next free one. Scoped to that file\'s own directory, so it is the cheap call. The repository is resolved FROM THIS PATH (absolute, or relative to the workspace / cwd), so nested checkouts work \u2014 give the prefix that locates the file, e.g. "Asgard/docs/adr/\u2026". Read `verdict` ("free" | "taken" | "no_opinion"), never `taken` alone: when the path cannot be located or its directory is no counter namespace, the answer is `no_opinion` \u2014 that is an abstention, NOT a free number.'}}}},{name:"check_spec_drift",description:"Local specification-fidelity detector (ADR-292): check whether an implementation still matches the NORMATIVE LIST it is supposed to implement \u2014 a design artefact, an OpenAPI document, a feature-flag catalogue, a permission matrix. The failure it catches is building against a PROSE SUMMARY of the specification instead of the specification: on 2026-08-19 a nav registry reached the default branch with 22 of the 40 targets its design artefact declares, and it surfaced only on the finished product. The specification was not missing \u2014 nothing in the system knew it existed. Runs entirely on this machine (git + fs), nothing is uploaded. The pairs to compare are DECLARED BY THIS REPO in `.maind/spec-contracts.json`; the manifest declares EXTRACTION, not content, so it never holds a copy of the expected values. Findings use open|warn|info across five closed dimensions: `coverage` (declared, not implemented), `fields` (implemented in the wrong group/section), `order` (right set, wrong sequence \u2014 the class a set comparison structurally cannot see), `extra` (implemented, not declared \u2014 a warning, the spec may lag) and `unrealized` (a key with no artefact behind it). Pre-existing findings grade `info` against the merge-base, so only what THIS branch introduces blocks. Call this WHEN: (a) you changed either side of a declared pair; (b) before opening or merging a PR that touches a registry, a router, a catalogue or the artefact that governs it; (c) you are about to build from a plan, handoff or ADR that SUMMARISES a specification \u2014 read the artefact, then verify with this. TWO THINGS IT DOES NOT DO. First: an absent manifest returns `verdict: no_opinion` \u2014 that is an abstention, NOT alignment; a repo that declares nothing never gets a green tick, and `ok` is false. Second: it cannot see APPEARANCE. No CSS, no measurements, no rendering. A green result means the declared entries agree in membership, grouping and order \u2014 it says nothing else about the thing you built. A `contract.unreadable:<id>` finding is a BROKEN POINTER (an anchor symbol moved), never a drift report: nothing was compared for that contract.",inputSchema:{type:"object",properties:{manifest:{type:"string",description:'Repo-relative manifest path (default ".maind/spec-contracts.json"). Point it at a throwaway path to see the abstention: `verdict: "no_opinion"`, `ok: false`.'},contracts:{type:"array",items:{type:"string"},description:"Restrict the run to these contract ids. Omit to evaluate every contract the manifest declares."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory, wrong for a gate."}}}},{name:"check_theme_class_drift",description:"Local dead-theme-class detector (ADR-303): find Tailwind utility classes that point at a theme token which does NOT exist. In Tailwind v4 an unknown theme colour generates NO rule \u2014 no error, no warning, the class is a silent no-op and the element simply has no background or colour. Neither tsc nor eslint nor the build can see it; it surfaces on the finished product, and typically in only ONE of the two colour modes (the sibling `dark:` class usually exists, which is exactly why it hides). Real incident 2026-08-26: `bg-surface-white` sat in nine files with no `--color-surface-white` anywhere; light-mode menus rendered without a background and read as a z-index bug. Runs entirely on this machine (git + fs), nothing is uploaded. The rule is sharp enough to gate on: only HOUSE namespaces are checked, and the namespaces are DERIVED from the repo's own `--color-*` and `--background-image-*` tokens (from `--color-surface-alt` follows `surface`) \u2014 `bg-red-500` or `text-xs` can never enter the check, so there is no judgement call and no config. Prose and template interpolation are excluded (a real class name never ends at a hyphen). Verdicts: `clean` (every house class is covered), `drift` (dead classes found \u2014 the findings name file, class and the missing token), `no_opinion` (the repo declares NO theme tokens; that is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo without tokens never gets a green tick). Call this WHEN: (a) you added or renamed a Tailwind theme token, or wrote a `bg-`/`text-`/`border-`-style class using a house palette name from memory; (b) a surface renders without background/colour in one mode while looking fine in the other \u2014 check for a dead class BEFORE reaching for z-index; (c) before merging a branch that touches styling or tokens.css; (d) auditing a repo you did not write. What it structurally cannot see: whether a token is used in the RIGHT place (a syntactically valid dark background on a light surface), and dynamically composed class names \u2014 the Tailwind JIT shares that blindness. GRADING (ADR-323): every finding carries `status` \u2014 `open` = introduced by THIS branch (working tree compared against the merge-base with the default branch), `info` = already present at the merge-base (inventory, not your problem). `ok` is true only when no `open` finding exists and never under `no_opinion`; `verdict` stays descriptive and reads `drift` whenever any dead class exists at all. Without a resolvable baseline every finding is `open` \u2014 ungraded is honest, guessed is not.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict the SOURCE scan to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the code, e.g. "Asgard/Maind". Token discovery always sweeps that whole repository: a scoped scan against a partial token set would fabricate findings. Omit to scan the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist at the merge-base with it are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_table_acl_lint",description:"Local Supabase table-ACL lint (ADR-309): find tables whose DEFAULT GRANTS were never revoked. Supabase's `ALTER DEFAULT PRIVILEGES` grants SELECT/INSERT/UPDATE/DELETE on EVERY new table in `public` to `anon` AND `authenticated` \u2014 and `REVOKE \u2026 FROM PUBLIC` does NOT remove that, because default privileges are direct role grants. Nothing enforces the counter-REVOKE; it is pure author discipline, so the leak is invisible until someone audits the live database. Real incident 2026-08-26: four tables carried full CRUD for anon and authenticated into production for up to eleven weeks (RLS held, the second line of defence simply did not exist). Runs entirely on this machine (git + fs), NO database is consulted, nothing is uploaded. The statement is about the FOLDED MIGRATION HISTORY, not about one file: CREATE/DROP/RENAME are folded in version order, and a REVOKE delivered in a LATER migration counts \u2014 which is exactly what a per-file lint cannot see. Two conditions per surviving public table: (A) some table-level REVOKE naming `anon` EXPLICITLY (PUBLIC alone never counts), and (B) table-level REVOKEs naming `authenticated` that cumulatively cover INSERT+UPDATE+DELETE (ALL covers). SELECT for `authenticated` may stay \u2014 the RLS-scoped read pattern is deliberate, not a leak. Findings grade `open` when THIS branch introduces them (new table without revokes, or a deleted revoke) and `info` when they predate the merge-base \u2014 inventory, not your problem. Verdicts: `clean`, `exposed`, `no_opinion`. Call this WHEN: (a) you added a `CREATE TABLE` migration \u2014 before opening the PR; (b) you are auditing a Supabase repo you did not write; (c) an RLS policy is being relaxed or removed, so the grant layer becomes load-bearing. TWO THINGS IT DOES NOT DO. First: `no_opinion` (a repo with no tracked `supabase/migrations/*.sql`) is an ABSTENTION, not a pass \u2014 `ok` is false, and a repo outside the tool's scope never gets a green tick. Second: it only sees MIGRATIONS. DDL applied through the dashboard or raw psql is invisible to it (the migration ledger shares that blindness), it covers schema `public` only, and REVOKEs inside `DO $$` blocks deliberately do NOT count \u2014 the error direction is always red, never a false green.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to sweep every Supabase project in the workspace repo.'},base_ref:{type:"string",description:"Grade open-vs-info against this git ref instead of the resolved default branch (e.g. a release tag). Findings that already exist there are `info`."},include_baseline:{type:"boolean",description:"Compare against the merge-base so pre-existing findings grade `info` instead of `open` (default true). false reports EVERY finding as newly introduced \u2014 useful for a full inventory of an unfamiliar repo, wrong for a gate."}}}},{name:"check_migration_ledger_drift",description:"Local Supabase migration-ledger drift detector (ADR-309) \u2014 and it ALWAYS reports WHICH DATABASE it talked to (host, port, and where the port came from). Compares three things per Supabase project: the tracked migrations directory, the ledger (`supabase_migrations.schema_migrations`) of the ACTUALLY connected local database, and \u2014 only with an explicitly supplied source \u2014 a remote ledger. Runs on this machine; read-only by construction (a single SELECT, never a repair, never an insert, never `db reset`), nothing is uploaded. Two real incidents on 2026-08-26 shaped it: (1) `supabase/config.toml` is gitignored and therefore missing in every fresh git worktree; without it the CLI falls back to its DEFAULT port 54322, where a DIFFERENT project's database was listening \u2014 `migration repair --status applied --local` reported `INSERT 0 1` and success while writing into a foreign ledger. This tool therefore NEVER guesses a port: no config means no connection, and the refusal is itself the finding. (2) With the local schema behind the repo, a promote gate skipped its SQL assertions SILENTLY \u2014 so a file without a ledger row is an `open` finding (`ledger.behind`), not a footnote. A ledger row WITHOUT a file is first EXPLAINED, then judged: if that version exists as a file in a SIBLING WORKTREE it is that branch's work-in-progress on the shared local stack (`info`, the expected steady state \u2014 local \u2287 trunk; do NOT 'repair' it, that would un-book a running session's work); only an unexplained row is a phantom (`warn`). Verdicts: `in_sync`, `drift`, `blind`, `no_opinion`. Call this WHEN: (a) you are starting work in a fresh worktree, BEFORE any `supabase` command; (b) a migration/CLI command reported success but the result looks wrong; (c) before running a gate or test suite that asserts DB guarantees \u2014 a run against a stale schema checks yesterday's guarantees and reports green for today's migration; (d) before a `db push`. READ THE VERDICT, NEVER `findings.length` ALONE: `blind` means the question is valid but the DB view is missing (`config_missing` = open, the silent-redirect class; `db_unreachable` / `psql_missing` / `no_ledger_schema` = warn \u2014 a port that answers WITHOUT a Supabase ledger suggests you are pointed at a foreign database). `no_opinion` (no tracked migrations) is an ABSTENTION, not a pass. `ok` is true only for `in_sync` \u2014 'I do not know which database you are talking to' is never ok. It compares VERSION PREFIXES, not contents: a migration edited after it was applied looks in sync here.",inputSchema:{type:"object",properties:{dir:{type:"string",description:'Restrict discovery to this directory (absolute, or relative to the workspace / cwd). The repository is resolved FROM THIS PATH, so nested checkouts work \u2014 give the prefix that locates the project, e.g. "Asgard/Maind". Omit to check every Supabase project in the workspace repo.'},remote_db_url:{type:"string",description:"Optional connection string for a REMOTE ledger (e.g. the cloud project). Only read (SELECT). Omitted \u21D2 no remote comparison happens at all and `facts.remote_consulted` is false \u2014 the tool never hunts for credentials on its own."}}}}],Bd=new Map([["codebase_review_verdict","attest_review_changes"]]),aw=new Set([...Hd.map(e=>e.name),...Bd.keys()]),Gd=new Set(["attest_review_changes",...[...Bd].filter(([,e])=>e==="attest_review_changes").map(([e])=>e)]);async function cw(e,t,n,r){if(!Gd.has(t))throw new Error(`not a cloud-backed tool: ${t}`);if(r===void 0)return{ok:!1,error:"cloud_unavailable",message:"this bridge process has no cloud session wired to its tools.",hint:"codebase_review_changes still gives you the advisory review."};let i=await rw(e,n,r),s=Bd.get(t);return s?{...i,renamed:{from:t,to:s,note:`${t} is ${s} since bridge 0.79.0 \u2014 call ${s}; the old name goes in a later minor.`}}:i}o(cw,"dispatchCloudBackedTool");function oe(e){return typeof e=="string"&&e.length>0?e:void 0}o(oe,"str");function Nn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Nn,"num");function sw(e){if(e===void 0)return{repoRoot:he(),scanDirs:void 0};let t=xr(e);return t===null?null:{repoRoot:t.repoRoot,scanDirs:t.repoRelDir===""?void 0:[t.repoRelDir]}}o(sw,"anchorRepo");function ow(e,t){return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,projects:[],findings:[],hint:`No opinion \u2014 this directory could not be located, so no repository was scanned. ${t} Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. \`Asgard/Maind\`) or an absolute path. Nothing was verified as ${e}.`}}o(ow,"dirNotFound");async function lw(e,t,n){switch(t){case"codebase_index":return e.indexRepository({full:n.full===!0});case"codebase_status":return e.status();case"check_divergence":{let r=await e.checkDivergence({includeRelease:n.include_release!==!1,probePaths:Array.isArray(n.probe_paths)?n.probe_paths.filter(a=>typeof a=="string"):void 0});if(r.verdict==="no_opinion")return{ok:!1,verdict:r.verdict,reason:r.reason,open_count:0,warn_count:0,findings:[],facts:r.facts,hint:"No opinion \u2014 this directory is not a git work tree, so nothing was examined. That is an ABSTENTION, not a pass: it says nothing about whether the state is sound. Run the check from inside the repository you mean (nested checkouts need their own path)."};let i=r.findings.filter(a=>a.status==="open").length,s=r.findings.filter(a=>a.status==="warn").length;return{ok:r.ok,verdict:r.verdict,reason:r.reason,open_count:i,warn_count:s,findings:r.findings,facts:r.facts,hint:r.ok?"No silent divergence detected \u2014 safe to proceed.":`${i} blocking (open) + ${s} warning finding(s). Resolve the 'open' findings \u2014 or get the user's explicit acknowledgement \u2014 BEFORE recommending push/deploy/release.`}}case"check_number_collisions":{let r=typeof n.min_files=="number"?n.min_files:void 0,i=oe(n.for_path);if(i!==void 0){let u=ab(i);if(u===null)return{ok:!1,mode:"proposed_path",verdict:"no_opinion",reason:"path_not_found",path:i,namespace:null,number:null,taken:null,suggestion:null,held_by:[],hint:"No opinion \u2014 this path could not be located on disk, so no repository was scanned. Do NOT read this as free. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr/\u2026`) or an absolute path."};let f=await fn(u.repoRoot,u.repoRelPath,{minFiles:r}),p=f.namespace,h=o(y=>y===null?null:`${p?.prefix??""}${y}`,"full"),g=p===null?"no_opinion":f.taken?"taken":"free";return{ok:g==="free",mode:"proposed_path",verdict:g,reason:g==="no_opinion"?"no_namespace":void 0,path:f.path,repo_root:u.repoRoot,namespace:p===null?null:{dir:p.dir,prefix:p.prefix,file_count:p.fileCount},number:h(f.number),taken:g==="no_opinion"?null:f.taken,suggestion:h(f.suggestion),held_by:f.sightings.map(y=>({kind:y.kind,where:y.where,path:y.path})),hint:g==="no_opinion"?"No opinion: that filename carries no number, or its directory is not a detected counter namespace. Do NOT read this as free \u2014 nothing was compared. Pass min_files to cover a series below the detection threshold.":f.taken?`${h(f.number)} is already held (see held_by). Create the file as ${h(f.suggestion)} instead \u2014 right now it costs one filename; after the index entry, the links and the commit message name it, it costs all of them.`:`${h(f.number)} is free across the default branch, sibling branches and sibling worktrees. Advisory, not a reservation: nothing stops a parallel session from taking it a second from now, so write the file rather than noting the number for later.`}}let s=Array.isArray(n.dirs)?n.dirs.filter(u=>typeof u=="string"):void 0;if(s!==void 0&&s.length>0){let u=new Map,f=[];for(let S of s){let x=xr(S);if(x===null){f.push(S);continue}let v=u.get(x.repoRoot)??new Set;v.add(x.repoRelDir),u.set(x.repoRoot,v)}if(u.size===0)return{ok:!1,verdict:"no_opinion",reason:"dirs_not_found",unresolved_dirs:f,open_count:0,preexisting_count:0,findings:[],preexisting:[],namespaces:[],scanned:[],hint:"No opinion \u2014 none of the given dirs could be located on disk, so no repository was scanned. Do NOT read this as collision-free. Pass dirs that exist relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/docs/adr`) or absolute paths."};let p=[],h=[],g=[],y=[];for(let[S,x]of u){let v=[...x],E=v.includes(""),N=await un(S,{dirs:E?void 0:v,minFiles:r});p.push({repo_root:S,dirs:E?null:v}),h.push(...N.findings),g.push(...N.facts.namespaces.map(F=>({repo_root:S,dir:F.dir,prefix:F.prefix,file_count:F.fileCount}))),y.push(...N.facts.skipped)}let b=h.filter(S=>S.status==="open"),w=h.filter(S=>S.status==="info"),k=f.length>0?` ${f.length} dir(s) could not be located and were NOT scanned (see unresolved_dirs).`:"";return{ok:b.length===0,open_count:b.length,preexisting_count:w.length,findings:b,preexisting:w.map(S=>`${S.namespace.prefix}${S.number}`),namespaces:g,skipped:y,scanned:p,...f.length>0?{unresolved_dirs:f}:{},hint:(b.length===0?g.length===0?"No numbered namespace detected in the scanned dirs \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${b.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+k}}let a=he(),c=await e.checkNumberCollisions({minFiles:r}),l=c.findings.filter(u=>u.status==="open"),d=c.findings.filter(u=>u.status==="info");return{ok:c.ok,repo_root:a,open_count:l.length,preexisting_count:d.length,findings:l,preexisting:d.map(u=>`${u.namespace.prefix}${u.number}`),namespaces:c.facts.namespaces.map(u=>({dir:u.dir,prefix:u.prefix,file_count:u.fileCount})),skipped:c.facts.skipped,hint:(c.ok?c.facts.namespaces.length===0?"No numbered namespace detected \u2014 nothing to collide. Pass min_files to cover a series below the detection threshold.":"No number introduced by this branch is taken elsewhere.":`${l.length} number(s) this branch adds are already taken. Renumber BEFORE pushing \u2014 afterwards every reference (links, index entries, comments) has to be rewritten.`)+" Scanned repo_root only \u2014 nested checkouts inside it are separate repositories; pass dirs with their prefix to cover them."}}case"check_spec_drift":{let r=await e.checkSpecDrift({manifestPath:oe(n.manifest),contracts:Array.isArray(n.contracts)?n.contracts.filter(f=>typeof f=="string"):void 0,includeBaseline:n.include_baseline!==!1}),i=o(f=>r.findings.filter(p=>p.status===f),"of"),s=i("open"),a=i("warn"),c=i("info"),l={manifest:r.facts.manifestPath,base_ref:r.facts.baseRef,skipped:r.facts.skipped};if(r.verdict==="no_opinion")return{...l,ok:!1,verdict:"no_opinion",reason:r.reason,contracts:[],findings:[],hint:`No opinion \u2014 nothing was compared. This is an ABSTENTION, NOT alignment: ${r.reason??"no contract could be read"}. Declare the pairs in ${r.facts.manifestPath} (a contract needs id, reason, spec and impl) before treating this repo as aligned.`};let d="Compares declared entries only: membership, declared fields, and order within a partition. It cannot see appearance \u2014 no CSS, no measurements, no rendering \u2014 and it only knows the pairs this repo declared.",u=s.filter(f=>f.id.startsWith("contract.unreadable:"));return{...l,ok:r.ok,verdict:r.verdict,contracts:r.contracts,open_count:s.length,warn_count:a.length,preexisting_count:c.length,findings:[...s,...a],preexisting:c.map(f=>f.id),coverage_note:d,hint:(r.ok?"The declared entries agree.":u.length>0?`${u.length} contract(s) could NOT BE MEASURED (broken pointer, not drift) and ${s.length-u.length} finding(s) are real drift. Repair the contract first \u2014 an unmeasured contract is not a passing one.`:`${s.length} blocking finding(s) introduced by this branch. On a contradiction the specification wins: read the artefact rather than a summary of it.`)+" "+d}}case"check_theme_class_drift":{let r=oe(n.dir),i,s;if(r!==void 0){let u=xr(r);if(u===null)return{ok:!1,verdict:"no_opinion",reason:"dir_not_found",repo_root:null,token_count:null,findings:[],hint:"No opinion \u2014 this directory could not be located, so no repository was scanned. Do NOT read this as clean. Pass a path that exists relative to the repo you mean (nested checkouts need their own prefix, e.g. `Asgard/Maind`) or an absolute path."};i=u.repoRoot,s=u.repoRelDir===""?void 0:[u.repoRelDir]}else i=he(),s=void 0;let a=hn(i,{dirs:s,baseRef:oe(n.base_ref),includeBaseline:n.include_baseline!==!1});if(a.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_theme_tokens",repo_root:i,token_count:0,findings:[],hint:"No opinion \u2014 this repository declares no `--color-*`/`--background-image-*` theme tokens, so there is nothing to check classes against. That is an ABSTENTION, not a pass: a repo without tokens never gets a green tick. If this repo uses Tailwind v4 theme tokens, they were not found in any tracked .css file."};let c=a.findings.filter(u=>u.status==="open").length,l=a.findings.length-c;return{ok:a.ok,verdict:a.verdict,repo_root:i,token_count:a.tokenCount,namespace_count:a.namespaceCount,scanned_files:a.scannedFiles,findings:a.findings.map(u=>({file:u.file,class:u.klass,status:u.status,missing_token:u.token,namespace:u.namespace})),hint:(a.findings.length===0?`All house-namespace classes are covered (${a.tokenCount} tokens, ${a.namespaceCount} namespaces).`:c===0?`No dead class introduced by this branch; ${l} pre-existing (info, already at the merge-base) \u2014 inventory, not a blocker.`:`${c} dead class(es) introduced by this branch${l>0?` (plus ${l} pre-existing, info)`:""}: each generates NO CSS rule and fails silently on the finished product, typically in one colour mode only. Fix by defining the missing token or switching the class to an existing one.`)+" "+"Checks house-namespace classes against declared theme tokens only. It cannot see whether a token is used in the RIGHT place, nor dynamically composed class names (the Tailwind JIT shares that blindness)."}}case"check_table_acl_lint":{let r=sw(oe(n.dir));if(r===null)return ow("clean","Do NOT read this as clean \u2014 nothing was scanned for table grants.");let i=mn(r.repoRoot,{dirs:r.scanDirs,baseRef:oe(n.base_ref),includeBaseline:n.include_baseline!==!1}),s="Reads MIGRATIONS only: DDL applied via dashboard or raw psql is invisible (the ledger shares that blindness), schema `public` only, and REVOKEs inside DO blocks deliberately do not count (error direction: red, never a false green).";if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is nothing to lint. That is an ABSTENTION, not a pass: `ok` is false and a repo outside the tool's scope never gets a green tick. If this repo does carry Supabase migrations, they are untracked or live under a prefix this scan did not reach (pass `dir`)."};let a=i.findings.filter(l=>l.status==="open"),c=i.findings.filter(l=>l.status==="info");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,base_ref:i.facts.baseRef,projects:i.facts.projects.map(l=>({dir:l.dir,migration_count:l.migrationCount,table_count:l.tableCount})),open_count:a.length,preexisting_count:c.length,findings:a,preexisting:c.map(l=>l.table),skipped:i.facts.skipped,hint:(a.length===0?c.length===0?"Every table born in these migrations addresses its default grants.":`Nothing this branch introduces is exposed. ${c.length} pre-existing table(s) still carry unrevoked default grants \u2014 inventory, not a blocker.`:`${a.length} table(s) this branch adds or exposes have unrevoked default grants: anon/authenticated get full CRUD from ALTER DEFAULT PRIVILEGES, leaving RLS as the only line of defence. Add the REVOKEs in the same migration.`)+" "+s}}case"check_migration_ledger_drift":{let r=sw(oe(n.dir));if(r===null)return ow("in sync","Do NOT read this as in sync \u2014 no repository and no database were consulted.");let i=Dl(r.repoRoot,{dirs:r.scanDirs,remoteDbUrl:oe(n.remote_db_url)}),s=i.facts.projects.map(f=>({dir:f.dir,migration_count:f.migrationCount,verdict:f.verdict,database:{host:f.db.host,port:f.db.port,config_source:f.db.configSource,reachable:f.db.reachable,ledger_count:f.db.ledgerCount}}));if(i.verdict==="no_opinion")return{ok:!1,verdict:"no_opinion",reason:"no_supabase_migrations",repo_root:r.repoRoot,projects:[],findings:[],remote_consulted:i.facts.remoteConsulted,hint:"No opinion \u2014 this repository has no tracked `supabase/migrations/*.sql`, so there is no ledger question to answer. That is an ABSTENTION, not a pass: `ok` is false, and no database was contacted."};let a=o(f=>i.findings.filter(p=>p.status===f),"of"),c=a("open"),l=a("warn"),d=a("info"),u=s.map(f=>f.database.port===null?`${f.dir}: NO DATABASE (config.toml missing \u2014 a CLI here would silently use the default port 54322)`:`${f.dir}: ${f.database.host}:${f.database.port} (config from ${f.database.config_source}, reachable=${f.database.reachable}, ledger rows=${f.database.ledger_count})`).join(" \xB7 ");return{ok:i.ok,verdict:i.verdict,repo_root:r.repoRoot,projects:s,open_count:c.length,warn_count:l.length,findings:[...c,...l],expected:d.map(f=>f.id),remote_consulted:i.facts.remoteConsulted,skipped:i.facts.skipped,database_targets:u,hint:(i.verdict==="in_sync"?`Directory and ledger agree. Talked to \u2014 ${u}.`:i.verdict==="blind"?`NO JUDGEMENT POSSIBLE: the migrations exist but the database view is missing. Talked to \u2014 ${u}. This is not a pass; resolve the blindness (copy config.toml from the main checkout / start the stack / install psql) before trusting any gate or test that asserts DB guarantees.`:`${c.length} blocking + ${l.length} warning finding(s). Talked to \u2014 ${u}.`)+" Compares version prefixes, not contents: a migration edited after it was applied looks in sync here."}}case"codebase_search":{let r=oe(n.query);if(!r)throw new Error("codebase_search requires a 'query' string");return(await e.searchGraph(r,{kind:oe(n.kind),limit:Nn(n.limit)})).map(s=>({...s,nodeKeyHash:zo(s.nodeKey)}))}case"codebase_trace":{let r=oe(n.node_key);if(!r)throw new Error("codebase_trace requires a 'node_key' string");let i=n.direction==="in"?"in":"out";return e.tracePath(r,{direction:i,maxDepth:Nn(n.max_depth),limit:Nn(n.limit)})}case"codebase_snippet":{let r=oe(n.node_key);if(!r)throw new Error("codebase_snippet requires a 'node_key' string");let i=await e.getCodeSnippet(r);if(!i)throw new Error(`no symbol found for node_key: ${r}`);return{...i,nodeKeyHash:zo(r)}}case"codebase_map":return e.getArchitecture({topN:Nn(n.top_n)});case"codebase_changes":{let r=await e.changedSymbols({since:oe(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nn(n.limit)});return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,truncated:r.truncated,symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language,file:i.filePath,start_line:i.startLine,node_key:i.nodeKey,node_key_hash:zo(i.nodeKey)})),briefing_args:{changed_symbols:r.symbols.map(i=>({name:i.name,qualified_name:i.qualifiedName,kind:i.kind,language:i.language}))},hint:r.symbols.length>0?"Next: call codebase_change_briefing with the briefing_args block (symbol names only \u2014 no paths) to get the maind conventions and lessons that apply to these changes.":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry.":"No changed files detected."}}case"codebase_review_changes":{let r=await e.reviewChanges({since:oe(n.since),includeUncommitted:n.include_uncommitted!==!1,limit:Nn(n.limit)}),i;if(n.include_history!==!1)try{i=_c(await e.fileHistory({since:oe(n.since),limit:1}))}catch{i=void 0}let s;try{s=await e.reviewDetectors({baseRef:oe(n.since)})}catch(l){s=xe(lt(`reviewDetectors failed: ${l instanceof Error?l.message:String(l)}`))}let a={changed_file_count:r.changedFiles,unindexed_file_count:r.changedFiles-r.indexedFiles,stale_file_count:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,base_kind:r.baseKind,detector_coverage:s.coverage},c=s.findings.filter(l=>l.baseline==="introduced"&&l.level==="open").reduce((l,d)=>l+d.count,0);return{changed_files:r.changedFiles,indexed_files:r.indexedFiles,stale_files:r.staleFiles,truncated:r.truncated,hunk_coverage:r.hunkCoverage,risk_flags:r.riskFlags,symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount,stale_index:l.staleIndex,file:l.filePath,start_line:l.startLine,node_key:l.nodeKey,node_key_hash:zo(l.nodeKey)})),review_args:{changed_symbols:r.symbols.map(l=>({name:l.name,qualified_name:l.qualifiedName,kind:l.kind,language:l.language,change:l.change,changed_line_count:l.changedLineCount})),risk_flags:r.riskFlags,diff_stats:a,...i?{history:i}:{}},verdict_args:{detector_findings:s.findings,risk_flags:r.riskFlags,diff_stats:a},detectors:{coverage:s.coverage,truncated:s.truncated,block_eligible:c,engines:s.engines,findings:s.local},hint:(r.symbols.length>0?"Next: call the cloud tool review_changes with the review_args block (symbol names + closed-enum flags only \u2014 no paths) for provenance-backed convention findings. ":r.changedFiles>0?"Changed files found but no index rows \u2014 run codebase_index first, then retry. ":"No changed files detected. ")+`Then call review_verdict with { findings: <convention_findings from review_changes, or []>, ...verdict_args } \u2014 the ${s.findings.length} detector row(s) (${c} block-eligible, coverage ${s.coverage}) are hashes only; keep detector_findings even when it is []. That two-step gives an advisory verdict and writes no record. For a gate verdict \u2014 and a replayable attestation record for a clean pushed commit \u2014 call attest_review_changes instead (one call; the bridge sends the payload itself).`}}case"codebase_history":{let r=Array.isArray(n.paths)?n.paths.filter(s=>typeof s=="string"):void 0,i=await e.fileHistory({paths:r,since:oe(n.since),limit:Nn(n.limit),includeOwnership:n.include_ownership!==!1});return{history:i.history.map(s=>({path:s.path,last_commits:s.lastCommits.map(a=>({sha:a.sha,author_name:a.authorName,author_email:a.authorEmail,date_iso:a.dateIso,subject:a.subject})),ownership:s.ownership?{top_authors:s.ownership.topAuthors.map(a=>({name:a.name,email:a.email,commits:a.commits,last_date_iso:a.lastDateIso})),commits_in_window:s.ownership.commitsInWindow}:null})),regression:i.regression?{since_input:i.regression.sinceInput,since_resolved:i.regression.sinceResolved,truncated:i.regression.truncated,commits:i.regression.commits.map(s=>({sha:s.sha,date_iso:s.dateIso,author_name:s.authorName,subject:s.subject,files_touched:s.filesTouched}))}:null,ownership_window_commits:i.ownershipWindowCommits,paths_truncated:i.pathsTruncated,hint:i.history.length===0?"No paths in scope \u2014 pass paths explicitly, or make changes first (default scope is your changed files).":"History is local-only (Phase B): author/subject data stays on this machine \u2014 do not forward it to cloud tools."}}default:throw new Error(`unknown local tool: ${t}`)}}o(lw,"dispatchLocalTool");var qo=class{constructor(t=lb,n=null,r=he,i=null){this.makeEngine=t;this.aggregator=n;this.resolveRoot=r;this.ctx=i}static{o(this,"LocalToolRouter")}engine=null;repoRootCache=null;descriptors(){return Hd}handlesToolCall(t,n){if(t!=="tools/call")return!1;let r=n?.name;return typeof r=="string"&&aw.has(r)}async handleToolCall(t,n){let r=n??{},i=typeof r.name=="string"?r.name:"",s=r.arguments&&typeof r.arguments=="object"?r.arguments:{};try{let a=Gd.has(i)?await cw(this.getEngine(),i,s,this.ctx??void 0):await lw(this.getEngine(),i,s),c=JSON.stringify(a,null,2);return this.recordSavings(i,a,c),JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:c}]}})}catch(a){let c=a instanceof Error?a.message:String(a),l=sb(a)?`${ob} (${c})`:`codebase tool error: ${c}`;return JSON.stringify({jsonrpc:"2.0",id:t,result:{content:[{type:"text",text:l}],isError:!0}})}}augmentToolsList(t){try{let n=JSON.parse(t);if(n&&n.result&&Array.isArray(n.result.tools)){let r=new Set(n.result.tools.map(s=>s&&typeof s=="object"?s.name:void 0).filter(s=>typeof s=="string")),i=this.descriptors().filter(s=>!r.has(s.name));return n.result.tools=[...n.result.tools,...i],JSON.stringify(n)}}catch{}return t}getEngine(){return this.engine||(this.engine=this.makeEngine()),this.engine}recordSavings(t,n,r){if(this.aggregator&&!(t!=="codebase_search"&&t!=="codebase_snippet"))try{this.repoRootCache===null&&(this.repoRootCache=this.resolveRoot());let i=Kb(t,n,r,this.repoRootCache);this.aggregator.add(i)}catch{}}};fr();var iD="/mcp-client-metrics-ingest",sD=4e3,oD="codebase_search_tokens_saved";async function dw(e){if(!Number.isFinite(e.tokensSaved)||e.tokensSaved<=0)return!1;let t=`${_i()}${iD}`,n=new AbortController,r=setTimeout(()=>n.abort(),sD);try{let i=await fetch(t,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`,"x-maind-device-id":e.deviceId,"user-agent":`@maind-dev/mcp-bridge/${e.bridgeVersion}`},body:JSON.stringify({metrics:[{session_id:e.sessionId,metric_key:oD,metric_value:Math.floor(e.tokensSaved)}]}),signal:n.signal});return await i.text().catch(()=>""),i.ok}catch(i){return process.stderr.write(`[maind-mcp-bridge] savings metric post failed (ignored): ${i instanceof Error?i.message:String(i)}
1020
+ `),!1}finally{clearTimeout(r)}}o(dw,"postSavingsMetric");Vd();Jo();Ur();Zo();Pn();import{join as tM}from"node:path";var nM="<synthetic>";function cv(e){return e===null?null:typeof e.transcript_path=="string"&&e.transcript_path.length>0?e.transcript_path:!e.transcript_stem||!e.cwd?null:tM(gu,yu(e.cwd),`${e.transcript_stem}.jsonl`)}o(cv,"transcriptPathFromSideChannel");var da=class{constructor(t){this.deps=t}static{o(this,"TranscriptMetaReader")}path=null;offset=0;model=null;title=null;async read(){try{let n=this.deps.resolvePath();if(n!==this.path&&(this.path=n,this.offset=0,this.model=null,this.title=null),n!==null){let i=await(this.deps.stream??hu)(n,{start:this.offset});for(let s of i.events)if(s.kind==="title"){let a=s.title.trim();a.length>0&&(this.title=a)}else s.kind==="assistant"&&!s.isSidechain&&typeof s.model=="string"&&s.model.length>0&&s.model!==nM&&(this.model=s.model);i.bytesRead>this.offset&&(this.offset=i.bytesRead)}}catch{}let t=null;try{t=this.deps.fallbackModel?.()??null}catch{t=null}return{model:this.model??t,title:this.title}}};import{execFile as rM}from"node:child_process";var iM=8,sM=32;function oM(e){return e.split(`
1021
+ `).filter(t=>t.trim().length>0).map(t=>(t.slice(3).split(" -> ").pop()??"").trim().replace(/^"|"$/g,"")).filter(t=>t.length>0).slice(0,sM)}o(oM,"parsePorcelain");function aM(e,t=iM){let n=[];for(let r of e){let i=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");if(i.length===0)continue;let s=i.includes("/")?i.slice(0,i.lastIndexOf("/")):i;if(!(s.length===0||n.includes(s))&&(n.push(s),n.length>=t))break}return n}o(aM,"condenseToDirs");async function lv(e=cM){let t=await e();if(t===null)return null;let n=aM(oM(t));return n.length>0?n:null}o(lv,"deriveWorkingPaths");async function cM(){return await new Promise(e=>{rM("git",["status","--porcelain"],{timeout:2e3,encoding:"utf8",maxBuffer:1024*1024},(t,n)=>e(t?null:n))})}o(cM,"defaultGitStatus");var uj=1,fj=["on-session-start","on-tool-use","on-file-write","on-file-edit","on-repo-health","on-write-health","sync-config","flush","status"];function pj(e){return fj.includes(e)}o(pj,"isHookSubcommand");var mj=6e4;async function hj(){let e=(process.env.MAIND_API_KEY??"").trim();if(e.length>0)return e!==Y()&&_n(e),e;let t=Y();if(t!==null)return t;let n=await pr(B);return n===null&&(bn("not_paired","sign-in did not complete \u2014 the device flow cannot finish inside an MCP client",{version:B}),process.stderr.write(`[maind-mcp-bridge] sign-in did not complete; exiting.
1022
+ `),process.exit(1)),bn("paired",null,{version:B}),n.apiKey}o(hj,"ensureApiKey");async function gj(e){let t=await pr(B);return t===null&&(bn("auth_failed",`${e}; re-authorization did not complete`,{version:B}),process.stderr.write(`[maind-mcp-bridge] re-authorization failed; exiting.
1023
+ `),process.exit(1)),bn("paired",null,{version:B}),t.apiKey}o(gj,"reauth");async function yj(){let e=process.argv.slice(2).find(v=>!v.startsWith("-"));if(e==="install"){let v=process.argv.indexOf("install"),E=process.argv.slice(v+1),N=await Hb(E);process.exit(N)}if(e==="doctor"){let{runDoctor:v}=await Promise.resolve().then(()=>(Su(),vv));process.exit(await v(process.argv.slice(process.argv.indexOf("doctor")+1)))}if(e==="on-session-end"){let{runOnSessionEnd:v}=await Promise.resolve().then(()=>(Tk(),Ek));process.exit(await v())}if(e==="on-session-briefing"){let{runOnSessionBriefing:v}=await Promise.resolve().then(()=>(Rk(),Ak));process.exit(await v())}if(e==="guard"){let v=process.argv.indexOf("guard"),{runGuard:E}=await Promise.resolve().then(()=>(Pk(),Dk));process.exit(await E(process.argv.slice(v+1)))}if(e==="guard-inject"){let{runGuardInject:v}=await Promise.resolve().then(()=>(Tr(),Ib));process.exit(await v())}if(e==="guard-gate"){let{runGuardGate:v}=await Promise.resolve().then(()=>(Bk(),Hk));process.exit(await v())}if(e==="guard-stop"){let{runGuardStop:v}=await Promise.resolve().then(()=>(Kk(),Wk));process.exit(await v())}if(e==="guard-difficulty"||e==="guard-outcome"){let{runGuardDifficulty:v}=await Promise.resolve().then(()=>(Qu(),Lk));process.exit(await v())}if(e==="guard-capture"){let{runGuardCapture:v}=await Promise.resolve().then(()=>(Yk(),qk));process.exit(await v())}if(e==="gateway"){let v=process.argv.indexOf("gateway"),{runGateway:E}=await Promise.resolve().then(()=>(Dx(),Ox));process.exit(await E(process.argv.slice(v+1)))}if(e==="guard-cross-observe"){let{runGuardCrossObserve:v}=await Promise.resolve().then(()=>(mf(),pf));process.exit(await v())}if(e==="guard-cross-check"){let{runGuardCrossCheck:v}=await Promise.resolve().then(()=>(mf(),pf));process.exit(await v())}if(e==="on-index-refresh"){let{runOnIndexRefresh:v}=await Promise.resolve().then(()=>(gf(),hf));process.exit(await v())}if(e==="index-refresh-run"){let{runIndexRefreshWorker:v}=await Promise.resolve().then(()=>(gf(),hf));process.exit(await v())}if(e==="on-prompt-context"){let{runOnPromptContext:v}=await Promise.resolve().then(()=>(xf(),kf));process.exit(await v())}if(e==="on-read-context"){let{runOnReadContext:v}=await Promise.resolve().then(()=>(xf(),kf));process.exit(await v())}if(e!==void 0&&pj(e)){let v=await Promise.resolve().then(()=>(qu(),pk)),E={"on-session-start":v.runOnSessionStart,"on-tool-use":v.runOnToolUse,"on-file-write":v.runOnFileWrite,"on-file-edit":v.runOnFileEdit,"on-repo-health":v.runOnRepoHealth,"on-write-health":v.runOnWriteHealth,"sync-config":v.runSyncConfig,flush:v.runFlush,status:v.runHookStatus}[e];process.exit(await E())}(process.argv.includes("--version")||process.argv.includes("-v"))&&(process.stdout.write(B+`
1024
+ `),process.exit(0)),(process.argv.includes("--help")||process.argv.includes("-h"))&&(_j(),process.exit(0)),process.argv.includes("--reauth")&&(yi(),await pr(B,process.stdout)===null&&process.exit(1),bn("paired",null,{version:B}),process.stdout.write(`[maind-mcp-bridge] re-authorization complete.
1025
+ `),process.exit(0));let t=re(),n=await hj(),r=J(),s=process.env.MAIND_DISABLE_CODEBASE_TOOLS!=="1"&&process.env.MAIND_DISABLE_SAVINGS_METRICS!=="1"?new Wo:null,a=null,c=new Map,l=process.env.MAIND_DISABLE_CODEBASE_TOOLS==="1"?null:new qo(void 0,s,void 0,{callCloudTool:o((v,E,N)=>a===null?Promise.resolve({kind:"no_session"}):a.callCloudTool(v,E,N),"callCloudTool"),projectKey:r,engineFor:o(v=>{let E=c.get(v);return E===void 0&&(E=db(v),c.set(v,E)),E},"engineFor"),projectKeyFor:no}),d=`bridge-${dj()}`,u=o(async()=>{if(!s)return;let v=s.takePending();v.tokens<=0||await dw({apiKey:n,deviceId:t,sessionId:d,tokensSaved:v.tokens,bridgeVersion:B})},"flushSavings"),f=s?setInterval(()=>{u()},mj):null;f?.unref();let p=new Xo({projectKey:r}),h=new da({resolvePath:o(()=>cv(p.sideChannel()),"resolvePath"),fallbackModel:o(()=>p.sideChannel()?.model??null,"fallbackModel")}),g=new ts,y=new Yo({projectKey:r,identity:p,sessionMeta:o(()=>h.read(),"sessionMeta"),postToolCall:o((v,E)=>a===null?Promise.reject(new Error("presence: no active forwarder")):a.postPresenceToolCall(v,E),"postToolCall"),deriveWorkingPaths:o(()=>lv(),"deriveWorkingPaths"),snapshot:r!==null?bj(vw({projectKey:r}),g):void 0}),b=y.isEnabled?setInterval(()=>{y.pollActivity()},pw):null;if(b?.unref(),y.isEnabled){let v=o(E=>{y.end().finally(()=>process.exit(E))},"endAndExit");process.on("SIGTERM",()=>v(143)),process.on("SIGINT",()=>v(130))}let w=!1,k=o(v=>{if(w||v!=="codex")return;w=!0,setTimeout(()=>{Promise.resolve().then(()=>(Ld(),jb)).then(({refreshAgentsMdConventions:N})=>N(v,{apiKey:n,projectKey:r})).catch(()=>{})},0).unref()},"scheduleAgentsMdRefresh"),S=0,x=ql();try{for(;;){let v=a?.carryOver()??null,E=new Qs({apiKey:n,deviceId:t,bridgeVersion:B,projectKey:r,localRouter:l,presence:y,onConnectionOutcome:o((N,F)=>bn(N,F,{version:B}),"onConnectionOutcome"),onSessionReady:o(({clientFamily:N})=>k(N),"onSessionReady"),assignedInbox:g,carry:v});a=E;try{await E.run(x);return}catch(N){if(N instanceof gi&&S<uj){S+=1,process.stderr.write(`[maind-mcp-bridge] server reported ${N.message}; re-authorizing\u2026
1026
+ `),n=await gj(N.reason);continue}throw N}}}finally{f&&clearInterval(f),b&&clearInterval(b),await y.end(),await u()}}o(yj,"main");function _j(){let e=["","@maind-dev/mcp-bridge \u2014 local MCP wrapper that pins your maind API key to this device.","","Usage:"," npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)"," npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)"," npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow"," npx -y @maind-dev/mcp-bridge doctor # offline self-diagnosis with fix commands (--json)"," npx -y @maind-dev/mcp-bridge doctor --remove-phantoms [--yes]"," # list (then remove) maind entries of clients that are not installed"," npx -y @maind-dev/mcp-bridge --version"," npx -y @maind-dev/mcp-bridge --help","","Run `install --help` for full setup flags:"," npx -y @maind-dev/mcp-bridge install --help","","Claude Code hook subcommands (wired by `install`; run them by hand only for","diagnostics). They read the hook payload on stdin and use the bridge's own","paired credential \u2014 no separate init:"," on-session-start open a tracked session (Tier-3 flat metrics)"," on-session-briefing add the session briefing + project conventions at session start (MAIND-620, never blocks)"," on-tool-use bump counters + evaluate the ADR-039 context advisory"," on-file-write block a Write that claims a taken number (ADR-263)"," on-file-edit advise on Edit/Write overlapping a peer session's claim (ADR-277, never blocks)"," on-repo-health surface this worktree's repo-health findings before the first edit in it (ADR-323, never blocks)"," on-write-health after an edit, run the path-relevant checks (spec/theme/table-acl) and report what this branch introduced (ADR-323, never blocks)"," on-session-end session analytics + close/flush the tracked session"," sync-config pull your context thresholds from the server (ADR-039)"," flush post queued Tier-3 metrics now"," status show pairing, queued metrics and active thresholds","","Guard (ADR-284) \u2014 deterministic consultation enforcement, explicit opt-in:"," guard install wire the guard hook pack (consent per hook) + set mode"," guard status mode, guard-hook wiring, local enforcement-event counts"," guard mode <warn|block> | guard off | guard stop-gate <on|off>"," guard difficulty <on|off> | guard capture <on|off> in-loop triggers (ADR-360)",' guard skip --session <id> --reason "\u2026" [--kind consult|difficulty|capture] logged override'," (hook subcommands, wired by `guard install`: guard-inject, guard-gate, guard-stop,"," guard-cross-observe, guard-cross-check, guard-difficulty, guard-outcome, guard-capture)","","Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent","Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.","","Environment overrides (rarely needed):"," MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)"," MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)"," MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)"," MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth"," MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)"," MAIND_NO_AGENTS_MD_REFRESH Set to 1 to stop refreshing the conventions block in AGENTS.md for Codex (ADR-359 E3)"," MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe"," XDG_CONFIG_HOME Override config-dir parent on Linux/BSD","","Auto-presence (ADR-242): the bridge announces this session on the repo's","shared working tree (project_key hash + branch only \u2014 no hostname, no paths),","refreshes while tools are actually called, and ends the row on exit.","Persistent opt-out / explicit machine_label via config.json in the maind",'config dir: { "auto_announce": false, "machine_label": "my-box" }',"","Place this in your .mcp.json (or equivalent):",""," {",' "mcpServers": {',' "maind": {',' "command": "npx",',' "args": ["-y", "@maind-dev/mcp-bridge"]'," }"," }"," }",""];process.stderr.write(e.join(`
1027
+ `))}o(_j,"printHelp");yj().catch(e=>{process.stderr.write(`[maind-mcp-bridge] fatal: ${e instanceof Error?e.message:String(e)}
1028
+ `),process.exit(1)});function bj(e,t){return{...e,write(n,r){try{t.update(n)}catch{}e.write(n,r)}}}o(bj,"withAssignedCapture");